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 | mpl-2.0 | f6d42eb4ad7cec752d89bb4d72ba9af379757db6 | 0 | Pilarbrist/rhino,tejassaoji/RhinoCoarseTainting,tejassaoji/RhinoCoarseTainting,sam/htmlunit-rhino-fork,AlexTrotsenko/rhino,AlexTrotsenko/rhino,Angelfirenze/rhino,lv7777/egit_test,tntim96/htmlunit-rhino-fork,Distrotech/rhino,lv7777/egit_test,AlexTrotsenko/rhino,qhanam/rhino,tuchida/rhino,Angelfirenze/rhino,Angelfirenze/rhino,ashwinrayaprolu1984/rhino,swannodette/rhino,sainaen/rhino,ashwinrayaprolu1984/rhino,lv7777/egit_test,sainaen/rhino,tntim96/rhino-jscover-repackaged,ashwinrayaprolu1984/rhino,sam/htmlunit-rhino-fork,qhanam/rhino,sainaen/rhino,swannodette/rhino,sam/htmlunit-rhino-fork,tntim96/htmlunit-rhino-fork,Angelfirenze/rhino,swannodette/rhino,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,swannodette/rhino,sainaen/rhino,Angelfirenze/rhino,Distrotech/rhino,tntim96/rhino-apigee,tntim96/rhino-jscover-repackaged,qhanam/rhino,InstantWebP2P/rhino-android,tejassaoji/RhinoCoarseTainting,sainaen/rhino,ashwinrayaprolu1984/rhino,AlexTrotsenko/rhino,tejassaoji/RhinoCoarseTainting,tntim96/rhino-apigee,InstantWebP2P/rhino-android,sam/htmlunit-rhino-fork,Pilarbrist/rhino,lv7777/egit_test,lv7777/egit_test,tuchida/rhino,tejassaoji/RhinoCoarseTainting,jsdoc3/rhino,Pilarbrist/rhino,Pilarbrist/rhino,sam/htmlunit-rhino-fork,AlexTrotsenko/rhino,AlexTrotsenko/rhino,tejassaoji/RhinoCoarseTainting,sainaen/rhino,tuchida/rhino,lv7777/egit_test,tejassaoji/RhinoCoarseTainting,tuchida/rhino,qhanam/rhino,Angelfirenze/rhino,AlexTrotsenko/rhino,jsdoc3/rhino,tuchida/rhino,jsdoc3/rhino,rasmuserik/rhino,sam/htmlunit-rhino-fork,sainaen/rhino,swannodette/rhino,swannodette/rhino,tuchida/rhino,ashwinrayaprolu1984/rhino,tntim96/rhino-jscover,ashwinrayaprolu1984/rhino,Angelfirenze/rhino,rasmuserik/rhino,tntim96/rhino-apigee,Pilarbrist/rhino,Pilarbrist/rhino,sam/htmlunit-rhino-fork,tntim96/rhino-jscover,tuchida/rhino,lv7777/egit_test,swannodette/rhino | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Brendan Eich
* Roger Lawrence
* Mike McCabe
* Ian D. Stewart
* Andi Vajda
* Andrew Wason
* Kemal Bayram
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
// API class
package org.mozilla.javascript;
import java.beans.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.ResourceBundle;
import java.text.MessageFormat;
import java.lang.reflect.*;
import org.mozilla.javascript.debug.*;
/**
* This class represents the runtime context of an executing script.
*
* Before executing a script, an instance of Context must be created
* and associated with the thread that will be executing the script.
* The Context will be used to store information about the executing
* of the script such as the call stack. Contexts are associated with
* the current thread using the <a href="#enter()">enter()</a> method.<p>
*
* The behavior of the execution engine may be altered through methods
* such as <a href="#setLanguageVersion>setLanguageVersion</a> and
* <a href="#setErrorReporter>setErrorReporter</a>.<p>
*
* Different forms of script execution are supported. Scripts may be
* evaluated from the source directly, or first compiled and then later
* executed. Interactive execution is also supported.<p>
*
* Some aspects of script execution, such as type conversions and
* object creation, may be accessed directly through methods of
* Context.
*
* @see Scriptable
* @author Norris Boyd
* @author Brendan Eich
*/
public class Context {
public static final String languageVersionProperty = "language version";
public static final String errorReporterProperty = "error reporter";
/**
* Create a new Context.
*
* Note that the Context must be associated with a thread before
* it can be used to execute a script.
*
* @see org.mozilla.javascript.Context#enter
*/
public Context() {
setLanguageVersion(VERSION_DEFAULT);
optimizationLevel = codegenClass != null ? 0 : -1;
}
/**
* Get a context associated with the current thread, creating
* one if need be.
*
* The Context stores the execution state of the JavaScript
* engine, so it is required that the context be entered
* before execution may begin. Once a thread has entered
* a Context, then getCurrentContext() may be called to find
* the context that is associated with the current thread.
* <p>
* Calling <code>enter()</code> will
* return either the Context currently associated with the
* thread, or will create a new context and associate it
* with the current thread. Each call to <code>enter()</code>
* must have a matching call to <code>exit()</code>. For example,
* <pre>
* Context cx = Context.enter();
* try {
* ...
* cx.evaluateString(...);
* } finally {
* Context.exit();
* }
* </pre>
* @return a Context associated with the current thread
* @see org.mozilla.javascript.Context#getCurrentContext
* @see org.mozilla.javascript.Context#exit
*/
public static Context enter()
{
return enter(null);
}
/**
* Get a Context associated with the current thread, using
* the given Context if need be.
* <p>
* The same as <code>enter()</code> except that <code>cx</code>
* is associated with the current thread and returned if
* the current thread has no associated context and <code>cx</code>
* is not associated with any other thread.
* @param cx a Context to associate with the thread if possible
* @return a Context associated with the current thread
*/
public static Context enter(Context cx)
{
Context old = getCurrentContext();
if (old != null) {
if (cx != null && cx != old && cx.enterCount != 0) {
// The suplied context must be the context for
// the current thread if it is already entered
throw new IllegalArgumentException(
"Cannot enter Context active on another thread");
}
cx = old;
} else {
if (cx == null)
cx = new Context();
if (cx.enterCount != 0) Kit.codeBug();
if (!cx.hideFromContextListeners && !cx.creationEventWasSent) {
cx.creationEventWasSent = true;
Object listeners = contextListeners;
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
((ContextListener)l).contextCreated(cx);
}
}
}
if (!cx.hideFromContextListeners) {
Object listeners = contextListeners;
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
((ContextListener)l).contextEntered(cx);
}
}
if (old == null) {
setThreadContext(cx);
}
++cx.enterCount;
return cx;
}
/**
* Exit a block of code requiring a Context.
*
* Calling <code>exit()</code> will remove the association between
* the current thread and a Context if the prior call to
* <code>enter()</code> on this thread newly associated a Context
* with this thread.
* Once the current thread no longer has an associated Context,
* it cannot be used to execute JavaScript until it is again associated
* with a Context.
*
* @see org.mozilla.javascript.Context#enter
*/
public static void exit()
{
Context cx = getCurrentContext();
if (cx == null) {
throw new IllegalStateException(
"Calling Context.exit without previous Context.enter");
}
if (Context.check && cx.enterCount < 1) Kit.codeBug();
--cx.enterCount;
if (cx.enterCount == 0) {
setThreadContext(null);
}
if (!cx.hideFromContextListeners) {
Object listeners = contextListeners;
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
((ContextListener)l).contextExited(cx);
}
if (cx.enterCount == 0) {
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
((ContextListener)l).contextReleased(cx);
}
}
}
}
/**
* Add a Context listener.
*/
public static void addContextListener(ContextListener listener)
{
synchronized (contextListenersLock) {
contextListeners = Kit.addListener(contextListeners, listener);
}
}
/**
* Remove a Context listener.
* @param listener the listener to remove.
*/
public static void removeContextListener(ContextListener listener)
{
synchronized (contextListenersLock) {
contextListeners = Kit.removeListener(contextListeners, listener);
}
}
/**
* Do not notify any listener registered with
* {@link #addContextListener(ContextListener)} about this Context instance.
* The function can only be called if this Context is not associated with
* any thread.
*/
public final void hideFromContextListeners()
{
if (enterCount != 0) throw new IllegalStateException();
hideFromContextListeners = true;
}
/**
* Get the current Context.
*
* The current Context is per-thread; this method looks up
* the Context associated with the current thread. <p>
*
* @return the Context associated with the current thread, or
* null if no context is associated with the current
* thread.
* @see org.mozilla.javascript.Context#enter
* @see org.mozilla.javascript.Context#exit
*/
public static Context getCurrentContext() {
if (threadLocalCx != null) {
try {
return (Context)threadLocalGet.invoke(threadLocalCx, null);
} catch (Exception ex) { }
}
Thread t = Thread.currentThread();
return (Context) threadContexts.get(t);
}
private static void setThreadContext(Context cx) {
if (threadLocalCx != null) {
try {
threadLocalSet.invoke(threadLocalCx, new Object[] { cx });
return;
} catch (Exception ex) { }
}
Thread t = Thread.currentThread();
if (cx != null) {
threadContexts.put(t, cx);
} else {
threadContexts.remove(t);
}
}
/**
* Language versions
*
* All integral values are reserved for future version numbers.
*/
/**
* The unknown version.
*/
public static final int VERSION_UNKNOWN = -1;
/**
* The default version.
*/
public static final int VERSION_DEFAULT = 0;
/**
* JavaScript 1.0
*/
public static final int VERSION_1_0 = 100;
/**
* JavaScript 1.1
*/
public static final int VERSION_1_1 = 110;
/**
* JavaScript 1.2
*/
public static final int VERSION_1_2 = 120;
/**
* JavaScript 1.3
*/
public static final int VERSION_1_3 = 130;
/**
* JavaScript 1.4
*/
public static final int VERSION_1_4 = 140;
/**
* JavaScript 1.5
*/
public static final int VERSION_1_5 = 150;
/**
* Get the current language version.
* <p>
* The language version number affects JavaScript semantics as detailed
* in the overview documentation.
*
* @return an integer that is one of VERSION_1_0, VERSION_1_1, etc.
*/
public int getLanguageVersion() {
return version;
}
/**
* Set the language version.
*
* <p>
* Setting the language version will affect functions and scripts compiled
* subsequently. See the overview documentation for version-specific
* behavior.
*
* @param version the version as specified by VERSION_1_0, VERSION_1_1, etc.
*/
public void setLanguageVersion(int version) {
Object listeners = instanceListeners;
if (listeners != null && version != this.version) {
firePropertyChangeImpl(listeners, languageVersionProperty,
new Integer(this.version),
new Integer(version));
}
this.version = version;
}
/**
* Get the implementation version.
*
* <p>
* The implementation version is of the form
* <pre>
* "<i>name langVer</i> <code>release</code> <i>relNum date</i>"
* </pre>
* where <i>name</i> is the name of the product, <i>langVer</i> is
* the language version, <i>relNum</i> is the release number, and
* <i>date</i> is the release date for that specific
* release in the form "yyyy mm dd".
*
* @return a string that encodes the product, language version, release
* number, and date.
*/
public String getImplementationVersion() {
return "Rhino 1.5 release 5 0000 00 00";
}
/**
* Get the current error reporter.
*
* @see org.mozilla.javascript.ErrorReporter
*/
public ErrorReporter getErrorReporter() {
if (errorReporter == null) {
errorReporter = new DefaultErrorReporter();
}
return errorReporter;
}
/**
* Change the current error reporter.
*
* @return the previous error reporter
* @see org.mozilla.javascript.ErrorReporter
*/
public ErrorReporter setErrorReporter(ErrorReporter reporter) {
ErrorReporter result = errorReporter;
Object listeners = instanceListeners;
if (listeners != null && errorReporter != reporter) {
firePropertyChangeImpl(listeners, errorReporterProperty,
errorReporter, reporter);
}
errorReporter = reporter;
return result;
}
/**
* Get the current locale. Returns the default locale if none has
* been set.
*
* @see java.util.Locale
*/
public Locale getLocale() {
if (locale == null)
locale = Locale.getDefault();
return locale;
}
/**
* Set the current locale.
*
* @see java.util.Locale
*/
public Locale setLocale(Locale loc) {
Locale result = locale;
locale = loc;
return result;
}
/**
* Register an object to receive notifications when a bound property
* has changed
* @see java.beans.PropertyChangeEvent
* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
* @param listener the listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener)
{
instanceListeners = Kit.addListener(instanceListeners, listener);
}
/**
* Remove an object from the list of objects registered to receive
* notification of changes to a bounded property
* @see java.beans.PropertyChangeEvent
* @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
* @param listener the listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener)
{
instanceListeners = Kit.removeListener(instanceListeners, listener);
}
/**
* Notify any registered listeners that a bounded property has changed
* @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
* @see java.beans.PropertyChangeListener
* @see java.beans.PropertyChangeEvent
* @param property the bound property
* @param oldValue the old value
* @param newVale the new value
*/
void firePropertyChange(String property, Object oldValue,
Object newValue)
{
Object listeners = instanceListeners;
if (listeners != null) {
firePropertyChangeImpl(listeners, property, oldValue, newValue);
}
}
private void firePropertyChangeImpl(Object listeners, String property,
Object oldValue, Object newValue)
{
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
if (l instanceof PropertyChangeListener) {
PropertyChangeListener pcl = (PropertyChangeListener)l;
pcl.propertyChange(new PropertyChangeEvent(
this, property, oldValue, newValue));
}
}
}
/**
* Report a warning using the error reporter for the current thread.
*
* @param message the warning message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportWarning(String message, String sourceName,
int lineno, String lineSource,
int lineOffset)
{
Context cx = Context.getContext();
cx.getErrorReporter().warning(message, sourceName, lineno,
lineSource, lineOffset);
}
/**
* Report a warning using the error reporter for the current thread.
*
* @param message the warning message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportWarning(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
Context.reportWarning(message, filename, linep[0], null, 0);
}
/**
* Report an error using the error reporter for the current thread.
*
* @param message the error message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportError(String message, String sourceName,
int lineno, String lineSource,
int lineOffset)
{
Context cx = getCurrentContext();
if (cx != null) {
cx.getErrorReporter().error(message, sourceName, lineno,
lineSource, lineOffset);
} else {
throw new EvaluatorException(message, sourceName, lineno,
lineSource, lineOffset);
}
}
/**
* Report an error using the error reporter for the current thread.
*
* @param message the error message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportError(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
Context.reportError(message, filename, linep[0], null, 0);
}
/**
* Report a runtime error using the error reporter for the current thread.
*
* @param message the error message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @return a runtime exception that will be thrown to terminate the
* execution of the script
* @see org.mozilla.javascript.ErrorReporter
*/
public static EvaluatorException reportRuntimeError(String message,
String sourceName,
int lineno,
String lineSource,
int lineOffset)
{
Context cx = getCurrentContext();
if (cx != null) {
return cx.getErrorReporter().
runtimeError(message, sourceName, lineno,
lineSource, lineOffset);
} else {
throw new EvaluatorException(message, sourceName, lineno,
lineSource, lineOffset);
}
}
static EvaluatorException reportRuntimeError0(String messageId)
{
String msg = getMessage0(messageId);
return reportRuntimeError(msg);
}
static EvaluatorException reportRuntimeError1(String messageId,
Object arg1)
{
String msg = getMessage1(messageId, arg1);
return reportRuntimeError(msg);
}
static EvaluatorException reportRuntimeError2(String messageId,
Object arg1, Object arg2)
{
String msg = getMessage2(messageId, arg1, arg2);
return reportRuntimeError(msg);
}
static EvaluatorException reportRuntimeError3(String messageId,
Object arg1, Object arg2,
Object arg3)
{
String msg = getMessage3(messageId, arg1, arg2, arg3);
return reportRuntimeError(msg);
}
static EvaluatorException reportRuntimeError4(String messageId,
Object arg1, Object arg2,
Object arg3, Object arg4)
{
String msg = getMessage4(messageId, arg1, arg2, arg3, arg4);
return reportRuntimeError(msg);
}
/**
* Report a runtime error using the error reporter for the current thread.
*
* @param message the error message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static EvaluatorException reportRuntimeError(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
return Context.reportRuntimeError(message, filename, linep[0], null, 0);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This method does not affect the Context it is called upon.
*
* @return the initialized scope
*/
public GlobalScope initStandardObjects()
{
return initStandardObjects(false);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This form of the method also allows for creating "sealed" standard
* objects. An object that is sealed cannot have properties added, changed,
* or removed. This is useful to create a "superglobal" that can be shared
* among several top-level objects. Note that sealing is not allowed in
* the current ECMA/ISO language specification, but is likely for
* the next version.
*
* This method does not affect the Context it is called upon.
*
* @param sealed whether or not to create sealed standard objects that
* cannot be modified.
* @return the initialized scope
*/
public GlobalScope initStandardObjects(boolean sealed)
{
GlobalScope global = new GlobalScope();
initStandardObjects(global, sealed);
return global;
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This method does not affect the Context it is called upon.
*
* If the explicit scope argument is not null and is not an instance of
* {@link GlobalScope} or its subclasses, parts of the standard library
* will be run slower.
*
* @param scope the scope to initialize, or null, in which case a new
* object will be created to serve as the scope
* @return the initialized scope
*/
public ScriptableObject initStandardObjects(ScriptableObject scope)
{
return initStandardObjects(scope, false);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This method does not affect the Context it is called upon.<p>
*
* This form of the method also allows for creating "sealed" standard
* objects. An object that is sealed cannot have properties added, changed,
* or removed. This is useful to create a "superglobal" that can be shared
* among several top-level objects. Note that sealing is not allowed in
* the current ECMA/ISO language specification, but is likely for
* the next version.
*
* If the explicit scope argument is not null and is not an instance of
* {@link GlobalScope} or its subclasses, parts of the standard library
* will be run slower.
*
* @param scope the scope to initialize, or null, in which case a new
* object will be created to serve as the scope
* @param sealed whether or not to create sealed standard objects that
* cannot be modified.
* @return the initialized scope
* @since 1.4R3
*/
public ScriptableObject initStandardObjects(ScriptableObject scope,
boolean sealed)
{
if (scope == null) {
scope = new GlobalScope();
} else if (!(scope instanceof GlobalScope)) {
GlobalScope.embed(scope);
}
BaseFunction.init(this, scope, sealed);
NativeObject.init(this, scope, sealed);
Scriptable objectProto = ScriptableObject.getObjectPrototype(scope);
// Function.prototype.__proto__ should be Object.prototype
Scriptable functionProto = ScriptableObject.getFunctionPrototype(scope);
functionProto.setPrototype(objectProto);
// Set the prototype of the object passed in if need be
if (scope.getPrototype() == null)
scope.setPrototype(objectProto);
// must precede NativeGlobal since it's needed therein
NativeError.init(this, scope, sealed);
NativeGlobal.init(this, scope, sealed);
NativeArray.init(this, scope, sealed);
NativeString.init(this, scope, sealed);
NativeBoolean.init(this, scope, sealed);
NativeNumber.init(this, scope, sealed);
NativeDate.init(this, scope, sealed);
NativeMath.init(this, scope, sealed);
NativeWith.init(this, scope, sealed);
NativeCall.init(this, scope, sealed);
NativeScript.init(this, scope, sealed);
new LazilyLoadedCtor(scope,
"RegExp",
"org.mozilla.javascript.regexp.NativeRegExp",
sealed);
// This creates the Packages and java package roots.
new LazilyLoadedCtor(scope,
"Packages",
"org.mozilla.javascript.NativeJavaTopPackage",
sealed);
new LazilyLoadedCtor(scope,
"java",
"org.mozilla.javascript.NativeJavaTopPackage",
sealed);
new LazilyLoadedCtor(scope,
"getClass",
"org.mozilla.javascript.NativeJavaTopPackage",
sealed);
// Define the JavaAdapter class, allowing it to be overridden.
String adapterClass = "org.mozilla.javascript.JavaAdapter";
String adapterProperty = "JavaAdapter";
try {
adapterClass = System.getProperty(adapterClass, adapterClass);
adapterProperty = System.getProperty
("org.mozilla.javascript.JavaAdapterClassName",
adapterProperty);
}
catch (SecurityException e) {
// We may not be allowed to get system properties. Just
// use the default adapter in that case.
}
new LazilyLoadedCtor(scope, adapterProperty, adapterClass, sealed);
return scope;
}
/**
* Get the singleton object that represents the JavaScript Undefined value.
*/
public static Object getUndefinedValue() {
return Undefined.instance;
}
/**
* Evaluate a JavaScript source string.
*
* The provided source name and line number are used for error messages
* and for producing debug information.
*
* @param scope the scope to execute in
* @param source the JavaScript source
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return the result of evaluating the string
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while evaluating the source string
* @see org.mozilla.javascript.SecurityController
*/
public Object evaluateString(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
throws JavaScriptException
{
Script script = compileString(scope, source, sourceName, lineno,
securityDomain);
if (script != null) {
return script.exec(this, scope);
} else {
return null;
}
}
/**
* Evaluate a reader as JavaScript source.
*
* All characters of the reader are consumed.
*
* @param scope the scope to execute in
* @param in the Reader to get JavaScript source from
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return the result of evaluating the source
*
* @exception IOException if an IOException was generated by the Reader
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while evaluating the Reader
*/
public Object evaluateReader(Scriptable scope, Reader in,
String sourceName, int lineno,
Object securityDomain)
throws IOException, JavaScriptException
{
Script script = compileReader(scope, in, sourceName, lineno,
securityDomain);
if (script != null) {
return script.exec(this, scope);
} else {
return null;
}
}
/**
* Check whether a string is ready to be compiled.
* <p>
* stringIsCompilableUnit is intended to support interactive compilation of
* javascript. If compiling the string would result in an error
* that might be fixed by appending more source, this method
* returns false. In every other case, it returns true.
* <p>
* Interactive shells may accumulate source lines, using this
* method after each new line is appended to check whether the
* statement being entered is complete.
*
* @param source the source buffer to check
* @return whether the source is ready for compilation
* @since 1.4 Release 2
*/
public boolean stringIsCompilableUnit(String source)
{
// no source name or source text manager, because we're just
// going to throw away the result.
TokenStream ts = new TokenStream(null, source, false, null, 1,
new DefaultErrorReporter());
boolean errorseen = false;
Interpreter compiler = new Interpreter();
IRFactory irf = compiler.createIRFactory(this, ts);
Parser p = createParser();
Decompiler decompiler = new Decompiler();
try {
p.parse(ts, irf, decompiler);
} catch (IOException ioe) {
errorseen = true;
} catch (EvaluatorException ee) {
errorseen = true;
}
// Return false only if an error occurred as a result of reading past
// the end of the file, i.e. if the source could be fixed by
// appending more source.
if (errorseen && ts.eof())
return false;
else
return true;
}
/**
* Compiles the source in the given reader.
* <p>
* Returns a script that may later be executed.
* Will consume all the source in the reader.
*
* @param scope if nonnull, will be the scope in which the script object
* is created. The script object will be a valid JavaScript object
* as if it were created using the JavaScript1.3 Script constructor
* @param in the input reader
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number for reporting errors
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a script that may later be executed
* @see org.mozilla.javascript.Script#exec
* @exception IOException if an IOException was generated by the Reader
*/
public Script compileReader(Scriptable scope, Reader in, String sourceName,
int lineno, Object securityDomain)
throws IOException
{
if (lineno < 0) {
throw new IllegalArgumentException(
"Line number can not be negative:"+lineno);
}
return (Script) compile(scope, in, null, sourceName, lineno,
securityDomain, false);
}
/**
* Compiles the source in the given string.
* <p>
* Returns a script that may later be executed.
*
* @param scope if nonnull, will be the scope in which the script object
* is created. The script object will be a valid JavaScript object
* as if it were created using the JavaScript1.3 Script constructor
* @param source the source string
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number for reporting errors
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a script that may later be executed
* @see org.mozilla.javascript.Script#exec
*/
public Script compileString(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
{
if (lineno < 0) {
throw new IllegalArgumentException(
"Line number can not be negative:"+lineno);
}
try {
return (Script) compile(scope, null, source, sourceName, lineno,
securityDomain, false);
} catch (IOException ex) {
// Should not happen when dealing with source as string
throw new RuntimeException();
}
}
/**
* Compile a JavaScript function.
* <p>
* The function source must be a function definition as defined by
* ECMA (e.g., "function f(a) { return a; }").
*
* @param scope the scope to compile relative to
* @param source the function definition source
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a Function that may later be called
* @see org.mozilla.javascript.Function
*/
public Function compileFunction(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
{
try {
return (Function) compile(scope, null, source, sourceName, lineno,
securityDomain, true);
}
catch (IOException ioe) {
// Should never happen because we just made the reader
// from a String
throw new RuntimeException();
}
}
/**
* Decompile the script.
* <p>
* The canonical source of the script is returned.
*
* @param script the script to decompile
* @param scope the scope under which to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the script source
*/
public String decompileScript(Script script, Scriptable scope,
int indent)
{
NativeFunction scriptImpl = (NativeFunction) script;
return scriptImpl.decompile(this, indent, false);
}
/**
* Decompile a JavaScript Function.
* <p>
* Decompiles a previously compiled JavaScript function object to
* canonical source.
* <p>
* Returns function body of '[native code]' if no decompilation
* information is available.
*
* @param fun the JavaScript function to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the function source
*/
public String decompileFunction(Function fun, int indent) {
if (fun instanceof BaseFunction)
return ((BaseFunction)fun).decompile(this, indent, false);
else
return "function " + fun.getClassName() +
"() {\n\t[native code]\n}\n";
}
/**
* Decompile the body of a JavaScript Function.
* <p>
* Decompiles the body a previously compiled JavaScript Function
* object to canonical source, omitting the function header and
* trailing brace.
*
* Returns '[native code]' if no decompilation information is available.
*
* @param fun the JavaScript function to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the function body source.
*/
public String decompileFunctionBody(Function fun, int indent) {
if (fun instanceof BaseFunction)
return ((BaseFunction)fun).decompile(this, indent, true);
else
// not sure what the right response here is. JSRef currently
// dumps core.
return "[native code]\n";
}
/**
* Create a new JavaScript object.
*
* Equivalent to evaluating "new Object()".
* @param scope the scope to search for the constructor and to evaluate
* against
* @return the new object
* @exception EvaluatorException if "Object" cannot be found in
* the scope or is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while creating the object
*/
public Scriptable newObject(Scriptable scope)
throws EvaluatorException, JavaScriptException
{
return newObject(scope, "Object", ScriptRuntime.emptyArgs);
}
/**
* Create a new JavaScript object by executing the named constructor.
*
* The call <code>newObject(scope, "Foo")</code> is equivalent to
* evaluating "new Foo()".
*
* @param scope the scope to search for the constructor and to evaluate against
* @param constructorName the name of the constructor to call
* @return the new object
* @exception EvaluatorException if a property with the constructor
* name cannot be found in the scope or is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while creating the object
*/
public Scriptable newObject(Scriptable scope, String constructorName)
throws EvaluatorException, JavaScriptException
{
return newObject(scope, constructorName, ScriptRuntime.emptyArgs);
}
/**
* Creates a new JavaScript object by executing the named constructor.
*
* Searches <code>scope</code> for the named constructor, calls it with
* the given arguments, and returns the result.<p>
*
* The code
* <pre>
* Object[] args = { "a", "b" };
* newObject(scope, "Foo", args)</pre>
* is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo
* constructor has been defined in <code>scope</code>.
*
* @param scope The scope to search for the constructor and to evaluate
* against
* @param constructorName the name of the constructor to call
* @param args the array of arguments for the constructor
* @return the new object
* @exception EvaluatorException if a property with the constructor
* name cannot be found in the scope or is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurs while creating the object
*/
public Scriptable newObject(Scriptable scope, String constructorName,
Object[] args)
throws EvaluatorException, JavaScriptException
{
scope = ScriptableObject.getTopLevelScope(scope);
Function ctor = ScriptRuntime.getExistingCtor(this, scope,
constructorName);
if (args == null) { args = ScriptRuntime.emptyArgs; }
return ctor.construct(this, scope, args);
}
/**
* Create an array with a specified initial length.
* <p>
* @param scope the scope to create the object in
* @param length the initial length (JavaScript arrays may have
* additional properties added dynamically).
* @return the new array object
*/
public Scriptable newArray(Scriptable scope, int length) {
Scriptable result = new NativeArray(length);
newArrayHelper(scope, result);
return result;
}
/**
* Create an array with a set of initial elements.
* <p>
* @param scope the scope to create the object in
* @param elements the initial elements. Each object in this array
* must be an acceptable JavaScript type.
* @return the new array object
*/
public Scriptable newArray(Scriptable scope, Object[] elements) {
Scriptable result = new NativeArray(elements);
newArrayHelper(scope, result);
return result;
}
/**
* Get the elements of a JavaScript array.
* <p>
* If the object defines a length property convertible to double number,
* then the number is converted Uint32 value as defined in Ecma 9.6
* and Java array of that size is allocated.
* The array is initialized with the values obtained by
* calling get() on object for each value of i in [0,length-1]. If
* there is not a defined value for a property the Undefined value
* is used to initialize the corresponding element in the array. The
* Java array is then returned.
* If the object doesn't define a length property or it is not a number,
* empty array is returned.
* @param object the JavaScript array or array-like object
* @return a Java array of objects
* @since 1.4 release 2
*/
public Object[] getElements(Scriptable object) {
long longLen = NativeArray.getLengthProperty(object);
if (longLen > Integer.MAX_VALUE) {
// arrays beyond MAX_INT is not in Java in any case
throw new IllegalArgumentException();
}
int len = (int) longLen;
if (len == 0) {
return ScriptRuntime.emptyArgs;
} else {
Object[] result = new Object[len];
for (int i=0; i < len; i++) {
Object elem = ScriptableObject.getProperty(object, i);
result[i] = (elem == Scriptable.NOT_FOUND) ? Undefined.instance
: elem;
}
return result;
}
}
/**
* Convert the value to a JavaScript boolean value.
* <p>
* See ECMA 9.2.
*
* @param value a JavaScript value
* @return the corresponding boolean value converted using
* the ECMA rules
*/
public static boolean toBoolean(Object value) {
return ScriptRuntime.toBoolean(value);
}
/**
* Convert the value to a JavaScript Number value.
* <p>
* Returns a Java double for the JavaScript Number.
* <p>
* See ECMA 9.3.
*
* @param value a JavaScript value
* @return the corresponding double value converted using
* the ECMA rules
*/
public static double toNumber(Object value) {
return ScriptRuntime.toNumber(value);
}
/**
* Convert the value to a JavaScript String value.
* <p>
* See ECMA 9.8.
* <p>
* @param value a JavaScript value
* @return the corresponding String value converted using
* the ECMA rules
*/
public static String toString(Object value) {
return ScriptRuntime.toString(value);
}
/**
* Convert the value to an JavaScript object value.
* <p>
* Note that a scope must be provided to look up the constructors
* for Number, Boolean, and String.
* <p>
* See ECMA 9.9.
* <p>
* Additionally, arbitrary Java objects and classes will be
* wrapped in a Scriptable object with its Java fields and methods
* reflected as JavaScript properties of the object.
*
* @param value any Java object
* @param scope global scope containing constructors for Number,
* Boolean, and String
* @return new JavaScript object
*/
public static Scriptable toObject(Object value, Scriptable scope) {
return ScriptRuntime.toObject(scope, value);
}
/**
* @deprecated Use {@link #toObject(Object, Scriptable)} instead.
*/
public static Scriptable toObject(Object value, Scriptable scope,
Class staticType)
{
return ScriptRuntime.toObject(scope, value);
}
/**
* Convert a JavaScript value into the desired type.
* Uses the semantics defined with LiveConnect3 and throws an
* Illegal argument exception if the conversion cannot be performed.
* @param value the JavaScript value to convert
* @param desiredType the Java type to convert to. Primitive Java
* types are represented using the TYPE fields in the corresponding
* wrapper class in java.lang.
* @return the converted value
* @throws IllegalArgumentException if the conversion cannot be performed
*/
public static Object toType(Object value, Class desiredType)
throws IllegalArgumentException
{
return NativeJavaObject.coerceType(desiredType, value, false);
}
/**
* Tell whether debug information is being generated.
* @since 1.3
*/
public boolean isGeneratingDebug() {
return generatingDebug;
}
/**
* Specify whether or not debug information should be generated.
* <p>
* Setting the generation of debug information on will set the
* optimization level to zero.
* @since 1.3
*/
public void setGeneratingDebug(boolean generatingDebug) {
generatingDebugChanged = true;
if (generatingDebug && getOptimizationLevel() > 0)
setOptimizationLevel(0);
this.generatingDebug = generatingDebug;
}
/**
* Tell whether source information is being generated.
* @since 1.3
*/
public boolean isGeneratingSource() {
return generatingSource;
}
/**
* Specify whether or not source information should be generated.
* <p>
* Without source information, evaluating the "toString" method
* on JavaScript functions produces only "[native code]" for
* the body of the function.
* Note that code generated without source is not fully ECMA
* conformant.
* @since 1.3
*/
public void setGeneratingSource(boolean generatingSource) {
this.generatingSource = generatingSource;
}
/**
* Get the current optimization level.
* <p>
* The optimization level is expressed as an integer between -1 and
* 9.
* @since 1.3
*
*/
public int getOptimizationLevel() {
return optimizationLevel;
}
/**
* Set the current optimization level.
* <p>
* The optimization level is expected to be an integer between -1 and
* 9. Any negative values will be interpreted as -1, and any values
* greater than 9 will be interpreted as 9.
* An optimization level of -1 indicates that interpretive mode will
* always be used. Levels 0 through 9 indicate that class files may
* be generated. Higher optimization levels trade off compile time
* performance for runtime performance.
* The optimizer level can't be set greater than -1 if the optimizer
* package doesn't exist at run time.
* @param optimizationLevel an integer indicating the level of
* optimization to perform
* @since 1.3
*
*/
public void setOptimizationLevel(int optimizationLevel) {
if (optimizationLevel < 0) {
optimizationLevel = -1;
} else if (optimizationLevel > 9) {
optimizationLevel = 9;
}
if (codegenClass == null)
optimizationLevel = -1;
this.optimizationLevel = optimizationLevel;
}
/**
* Set the security controller for this context.
* <p> SecurityController may only be set if it is currently null.
* Otherwise a SecurityException is thrown.
* @param controller a SecurityController object
* @throws SecurityException if there is already a SecurityController
* object for this Context
*/
public void setSecurityController(SecurityController controller) {
if (controller == null) throw new IllegalArgumentException();
if (securityController != null) {
throw new SecurityException("Cannot overwrite existing " +
"SecurityController object");
}
securityController = controller;
}
/**
* Set the LiveConnect access filter for this context.
* <p> {@link ClassShutter} may only be set if it is currently null.
* Otherwise a SecurityException is thrown.
* @param shutter a ClassShutter object
* @throws SecurityException if there is already a ClassShutter
* object for this Context
*/
public void setClassShutter(ClassShutter shutter) {
if (shutter == null) throw new IllegalArgumentException();
if (classShutter != null) {
throw new SecurityException("Cannot overwrite existing " +
"ClassShutter object");
}
classShutter = shutter;
}
final ClassShutter getClassShutter() {
return classShutter;
}
/**
* Get a value corresponding to a key.
* <p>
* Since the Context is associated with a thread it can be
* used to maintain values that can be later retrieved using
* the current thread.
* <p>
* Note that the values are maintained with the Context, so
* if the Context is disassociated from the thread the values
* cannot be retreived. Also, if private data is to be maintained
* in this manner the key should be a java.lang.Object
* whose reference is not divulged to untrusted code.
* @param key the key used to lookup the value
* @return a value previously stored using putThreadLocal.
*/
public final Object getThreadLocal(Object key) {
if (hashtable == null)
return null;
return hashtable.get(key);
}
/**
* Put a value that can later be retrieved using a given key.
* <p>
* @param key the key used to index the value
* @param value the value to save
*/
public void putThreadLocal(Object key, Object value) {
if (hashtable == null)
hashtable = new Hashtable();
hashtable.put(key, value);
}
/**
* Remove values from thread-local storage.
* @param key the key for the entry to remove.
* @since 1.5 release 2
*/
public void removeThreadLocal(Object key) {
if (hashtable == null)
return;
hashtable.remove(key);
}
/**
* Return whether functions are compiled by this context using
* dynamic scope.
* <p>
* If functions are compiled with dynamic scope, then they execute
* in the scope of their caller, rather than in their parent scope.
* This is useful for sharing functions across multiple scopes.
* @since 1.5 Release 1
*/
public final boolean hasCompileFunctionsWithDynamicScope() {
return compileFunctionsWithDynamicScopeFlag;
}
/**
* Set whether functions compiled by this context should use
* dynamic scope.
* <p>
* @param flag if true, compile functions with dynamic scope
* @since 1.5 Release 1
*/
public void setCompileFunctionsWithDynamicScope(boolean flag) {
compileFunctionsWithDynamicScopeFlag = flag;
}
/**
* @deprecated To enable/disable caching for a particular top scope,
* use {@link GlobalScope#get(Scriptable)} and
* {@link GlobalScope#setCachingEnabled(boolean)}.
* The function is kept only for compatibility and does nothing.
*/
public static void setCachingEnabled(boolean cachingEnabled)
{
}
// Proxy to allow to use deprecated WrapHandler in place of WrapFactory
private static class WrapHandlerProxy extends WrapFactory {
WrapHandler _handler;
WrapHandlerProxy(WrapHandler handler) {
_handler = handler;
}
public Object wrap(Context cx, Scriptable scope,
Object obj, Class staticType)
{
if (obj == null) { return obj; }
Object result = _handler.wrap(scope, obj, staticType);
if (result == null) {
result = super.wrap(cx, scope, obj, staticType);
}
return result;
}
public Scriptable wrapNewObject(Context cx, Scriptable scope,
Object obj)
{
Object wrap = _handler.wrap(scope, obj, obj.getClass());
if (wrap instanceof Scriptable) {
return (Scriptable)wrap;
}
if (wrap == null) {
return super.wrapNewObject(cx, scope, obj);
}
throw new RuntimeException
("Please upgrade from WrapHandler to WrapFactory");
}
}
/**
* @deprecated As of Rhino 1.5 Release 4, use
* {@link WrapFactory} and {@link #setWrapFactory(WrapFactory)}
*/
public void setWrapHandler(WrapHandler wrapHandler) {
if (wrapHandler == null) {
setWrapFactory(new WrapFactory());
} else {
setWrapFactory(new WrapHandlerProxy(wrapHandler));
}
}
/**
* @deprecated As of Rhino 1.5 Release 4, use
* {@link WrapFactory} and {@link #getWrapFactory()}
*/
public WrapHandler getWrapHandler() {
WrapFactory f = getWrapFactory();
if (f instanceof WrapHandlerProxy) {
return ((WrapHandlerProxy)f)._handler;
}
return null;
}
/**
* Set a WrapFactory for this Context.
* <p>
* The WrapFactory allows custom object wrapping behavior for
* Java object manipulated with JavaScript.
* @see org.mozilla.javascript.WrapFactory
* @since 1.5 Release 4
*/
public void setWrapFactory(WrapFactory wrapFactory) {
if (wrapFactory == null) throw new IllegalArgumentException();
this.wrapFactory = wrapFactory;
}
/**
* Return the current WrapHandler, or null if none is defined.
* @see org.mozilla.javascript.WrapHandler
* @since 1.5 Release 4
*/
public final WrapFactory getWrapFactory() {
if (wrapFactory == null) {
wrapFactory = new WrapFactory();
}
return wrapFactory;
}
/**
* Return the current debugger.
* @return the debugger, or null if none is attached.
*/
public final Debugger getDebugger() {
return debugger;
}
/**
* Return the debugger context data associated with current context.
* @return the debugger data, or null if debugger is not attached
*/
public final Object getDebuggerContextData() {
return debuggerData;
}
/**
* Set the associated debugger.
* @param debugger the debugger to be used on callbacks from
* the engine.
* @param contextData arbitrary object that debugger can use to store
* per Context data.
*/
public void setDebugger(Debugger debugger, Object contextData) {
this.debugger = debugger;
debuggerData = contextData;
}
/**
* If hasFeature(FEATURE_NON_ECMA_GET_YEAR) returns true,
* Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000.
* The default behavior is always to subtruct 1900 as rquired
* by Ecma B.2.4.
*/
public static final int FEATURE_NON_ECMA_GET_YEAR = 1;
/**
* If hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME) returns true,
* allow 'function memberExpression(args) { body }' to be syntax sugar
* for
* 'memberExpression = function(args) { body }', when memberExpression
* is not simply identifier.
* See Ecma-262, section 11.2 for definition of memberExpression.
*/
public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2;
/**
* If hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER) returns true,
* treat future reserved keyword (see Ecma-262, section 7.5.3) as ordinary
* identifiers but warn about this usage
*/
public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3;
/**
* If hasFeature(FEATURE_TO_STRING_AS_SOURCE) returns true,
* calling toString on JS objects gives JS source with code to create an
* object with all enumeratable fields of the original object instead of
* printing "[object <object-type>]".
* By default {@link #hasFeature(int)} returns true only if
* the current JS version is set to {@link #VERSION_1_2}.
*/
public static final int FEATURE_TO_STRING_AS_SOURCE = 4;
/**
* Controls certain aspects of script semantics.
* Should be overwritten to alter default behavior.
* @param featureIndex feature index to check
* @return true if the <code>featureIndex</code> feature is turned on
* @see #FEATURE_NON_ECMA_GET_YEAR
* @see #FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME
* @see #FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER
* @see #FEATURE_TO_STRING_AS_SOURCE
*/
public boolean hasFeature(int featureIndex) {
switch (featureIndex) {
case FEATURE_NON_ECMA_GET_YEAR:
/*
* During the great date rewrite of 1.3, we tried to track the
* evolving ECMA standard, which then had a definition of
* getYear which always subtracted 1900. Which we
* implemented, not realizing that it was incompatible with
* the old behavior... now, rather than thrash the behavior
* yet again, we've decided to leave it with the - 1900
* behavior and point people to the getFullYear method. But
* we try to protect existing scripts that have specified a
* version...
*/
return (version == Context.VERSION_1_0
|| version == Context.VERSION_1_1
|| version == Context.VERSION_1_2);
case FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME:
return false;
case FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER:
return false;
case FEATURE_TO_STRING_AS_SOURCE:
return version == VERSION_1_2;
}
// It is a bug to call the method with unknown featureIndex
throw new IllegalArgumentException();
}
/**
* Get/Set threshold of executed instructions counter that triggers call to
* <code>observeInstructionCount()</code>.
* When the threshold is zero, instruction counting is disabled,
* otherwise each time the run-time executes at least the threshold value
* of script instructions, <code>observeInstructionCount()</code> will
* be called.
*/
public int getInstructionObserverThreshold() {
return instructionThreshold;
}
public void setInstructionObserverThreshold(int threshold) {
instructionThreshold = threshold;
}
/**
* Allow application to monitor counter of executed script instructions
* in Context subclasses.
* Run-time calls this when instruction counting is enabled and the counter
* reaches limit set by <code>setInstructionObserverThreshold()</code>.
* The method is useful to observe long running scripts and if necessary
* to terminate them.
* @param instructionCount amount of script instruction executed since
* last call to <code>observeInstructionCount</code>
* @throws Error to terminate the script
*/
protected void observeInstructionCount(int instructionCount) {}
public GeneratedClassLoader createClassLoader(ClassLoader parent) {
return new DefiningClassLoader(parent);
}
public final ClassLoader getApplicationClassLoader()
{
if (applicationClassLoader == null) {
// If Context was subclassed, the following gets the loader
// for the subclass which can be different from Rhino loader,
// but then proper Rhino classes should be accessible through it
// in any case or JVM class loading is severely broken
Class cxClass = this.getClass();
ClassLoader loader = cxClass.getClassLoader();
if (method_getContextClassLoader != null) {
Thread thread = Thread.currentThread();
ClassLoader threadLoader = null;
try {
threadLoader = (ClassLoader)method_getContextClassLoader.
invoke(thread, ScriptRuntime.emptyArgs);
} catch (Exception ex) { }
if (threadLoader != null && threadLoader != loader) {
if (testIfCanUseLoader(threadLoader, cxClass)) {
// Thread.getContextClassLoader is not cached since
// its caching prevents it from GC which may lead to
// a memory leak and hides updates to
// Thread.getContextClassLoader
return threadLoader;
}
}
}
applicationClassLoader = loader;
}
return applicationClassLoader;
}
public void setApplicationClassLoader(ClassLoader loader)
{
if (loader == null) {
// restore default behaviour
applicationClassLoader = null;
return;
}
if (!testIfCanUseLoader(loader, this.getClass())) {
throw new IllegalArgumentException(
"Loader can not resolve Rhino classes");
}
applicationClassLoader = loader;
}
private static boolean testIfCanUseLoader(ClassLoader loader, Class cxClass)
{
// Check that Context or its suclass is accesible from this loader
Class x = Kit.classOrNull(loader, cxClass.getName());
if (x != cxClass) {
// The check covers the case when x == null =>
// loader does not know about Rhino or the case
// when x != null && x != cxClass =>
// loader loads unrelated Rhino instance
return false;
}
return true;
}
/********** end of API **********/
static String getMessage0(String messageId)
{
return getMessage(messageId, null);
}
static String getMessage1(String messageId, Object arg1)
{
Object[] arguments = {arg1};
return getMessage(messageId, arguments);
}
static String getMessage2(String messageId, Object arg1, Object arg2)
{
Object[] arguments = {arg1, arg2};
return getMessage(messageId, arguments);
}
static String getMessage3(String messageId, Object arg1, Object arg2,
Object arg3)
{
Object[] arguments = {arg1, arg2, arg3};
return getMessage(messageId, arguments);
}
static String getMessage4(String messageId, Object arg1, Object arg2,
Object arg3, Object arg4)
{
Object[] arguments = {arg1, arg2, arg3, arg4};
return getMessage(messageId, arguments);
}
/**
* Internal method that reports an error for missing calls to
* enter().
*/
static Context getContext() {
Context cx = getCurrentContext();
if (cx == null) {
throw new RuntimeException(
"No Context associated with current Thread");
}
return cx;
}
/* OPT there's a noticable delay for the first error! Maybe it'd
* make sense to use a ListResourceBundle instead of a properties
* file to avoid (synchronized) text parsing.
*/
static final String defaultResource =
"org.mozilla.javascript.resources.Messages";
static String getMessage(String messageId, Object[] arguments) {
Context cx = getCurrentContext();
Locale locale = cx != null ? cx.getLocale() : Locale.getDefault();
// ResourceBundle does cacheing.
ResourceBundle rb = ResourceBundle.getBundle(defaultResource, locale);
String formatString;
try {
formatString = rb.getString(messageId);
} catch (java.util.MissingResourceException mre) {
throw new RuntimeException
("no message resource found for message property "+ messageId);
}
/*
* It's OK to format the string, even if 'arguments' is null;
* we need to format it anyway, to make double ''s collapse to
* single 's.
*/
// TODO: MessageFormat is not available on pJava
MessageFormat formatter = new MessageFormat(formatString);
return formatter.format(arguments);
}
private static String readReader(Reader r)
throws IOException
{
char[] buffer = new char[512];
int cursor = 0;
for (;;) {
int n = r.read(buffer, cursor, buffer.length - cursor);
if (n < 0) { break; }
cursor += n;
if (cursor == buffer.length) {
char[] tmp = new char[buffer.length * 2];
System.arraycopy(buffer, 0, tmp, 0, cursor);
buffer = tmp;
}
}
return new String(buffer, 0, cursor);
}
/**
* Compile a script.
*
* Reads script source from the reader and compiles it, returning
* a class for either the script or the function depending on the
* value of <code>returnFunction</code>.
*
* @param scope the scope to compile relative to
* @param in the Reader to read source from
* @param sourceName the name of the origin of the source (usually
* a file or URL)
* @param lineno the line number of the start of the source
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @param returnFunction if true, will expect the source to contain
* a function; return value is assumed to
* then be a org.mozilla.javascript.Function
* @return a class for the script or function
* @see org.mozilla.javascript.Context#compileReader
*/
private Object compile(Scriptable scope,
Reader sourceReader, String sourceString,
String sourceName, int lineno,
Object securityDomain, boolean returnFunction)
throws IOException
{
// One of sourceReader or sourceString has to be null
if (!(sourceReader == null ^ sourceString == null)) Kit.codeBug();
Interpreter compiler = createCompiler();
if (securityController != null) {
securityDomain = securityController.
getDynamicSecurityDomain(securityDomain);
} else {
securityDomain = null;
}
if (debugger != null) {
if (sourceReader != null) {
sourceString = readReader(sourceReader);
sourceReader = null;
}
}
boolean fromEval = (scope != null);
TokenStream ts = new TokenStream(sourceReader, sourceString,
fromEval, sourceName, lineno,
getErrorReporter());
Parser p = createParser();
IRFactory irf = compiler.createIRFactory(this, ts);
Decompiler decompiler = new Decompiler();
ScriptOrFnNode tree = p.parse(ts, irf, decompiler);
if (tree == null)
return null;
String encodedSource = null;
if (isGeneratingSource()) {
encodedSource = decompiler.getEncodedSource();
}
decompiler = null; // It helps GC
tree = compiler.transform(this, irf, tree);
if (Token.printTrees) { System.out.println(tree.toStringTree(tree)); }
if (returnFunction) {
int functionCount = tree.getFunctionCount();
if (functionCount == 0)
return null;
tree = tree.getFunctionNode(0);
}
Object result = compiler.compile(this, scope, tree,
securityController, securityDomain,
encodedSource);
if (debugger != null) {
if (sourceString == null) Kit.codeBug();
compiler.notifyDebuggerCompilationDone(this, result, sourceString);
}
return ts.errorCount == 0 ? result : null;
}
private static Class codegenClass = Kit.classOrNull(
"org.mozilla.javascript.optimizer.Codegen");
private Interpreter createCompiler() {
Interpreter result = null;
if (optimizationLevel >= 0 && codegenClass != null) {
result = (Interpreter)Kit.newInstanceOrNull(codegenClass);
}
if (result == null) {
result = new Interpreter();
}
return result;
}
private Parser createParser() {
Parser parser = new Parser();
parser.setLanguageVersion(getLanguageVersion());
parser.setAllowMemberExprAsFunctionName(
hasFeature(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME));
return parser;
}
static String getSourcePositionFromStack(int[] linep) {
Context cx = getCurrentContext();
if (cx == null)
return null;
if (cx.interpreterData != null) {
return Interpreter.getSourcePositionFromStack(cx, linep);
}
/**
* A bit of a hack, but the only way to get filename and line
* number from an enclosing frame.
*/
CharArrayWriter writer = new CharArrayWriter();
RuntimeException re = new RuntimeException();
re.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
int open = -1;
int close = -1;
int colon = -1;
for (int i=0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ':')
colon = i;
else if (c == '(')
open = i;
else if (c == ')')
close = i;
else if (c == '\n' && open != -1 && close != -1 && colon != -1 &&
open < colon && colon < close)
{
String fileStr = s.substring(open + 1, colon);
if (!fileStr.endsWith(".java")) {
String lineStr = s.substring(colon + 1, close);
try {
linep[0] = Integer.parseInt(lineStr);
return fileStr;
}
catch (NumberFormatException e) {
// fall through
}
}
open = close = colon = -1;
}
}
return null;
}
RegExpProxy getRegExpProxy() {
if (regExpProxy == null) {
Class cl = Kit.classOrNull(
"org.mozilla.javascript.regexp.RegExpImpl");
if (cl != null) {
regExpProxy = (RegExpProxy)Kit.newInstanceOrNull(cl);
}
}
return regExpProxy;
}
private void newArrayHelper(Scriptable scope, Scriptable array) {
array.setParentScope(scope);
Object ctor = ScriptRuntime.getTopLevelProp(scope, "Array");
if (ctor != null && ctor instanceof Scriptable) {
Scriptable s = (Scriptable) ctor;
array.setPrototype((Scriptable) s.get("prototype", s));
}
}
final boolean isVersionECMA1() {
return version == VERSION_DEFAULT || version >= VERSION_1_3;
}
// Should not be public
SecurityController getSecurityController() {
return securityController;
}
public boolean isGeneratingDebugChanged() {
return generatingDebugChanged;
}
/**
* Add a name to the list of names forcing the creation of real
* activation objects for functions.
*
* @param name the name of the object to add to the list
*/
public void addActivationName(String name) {
if (activationNames == null)
activationNames = new Hashtable(5);
activationNames.put(name, name);
}
/**
* Check whether the name is in the list of names of objects
* forcing the creation of activation objects.
*
* @param name the name of the object to test
*
* @return true if an function activation object is needed.
*/
public boolean isActivationNeeded(String name) {
if ("arguments".equals(name))
return true;
return activationNames != null && activationNames.containsKey(name);
}
/**
* Remove a name from the list of names forcing the creation of real
* activation objects for functions.
*
* @param name the name of the object to remove from the list
*/
public void removeActivationName(String name) {
if (activationNames != null)
activationNames.remove(name);
}
static final boolean check = true;
private static Hashtable threadContexts = new Hashtable(11);
private static Object threadLocalCx;
private static Method threadLocalGet;
private static Method threadLocalSet;
static {
Class cl = Kit.classOrNull("java.lang.ThreadLocal");
if (cl != null) {
try {
threadLocalGet = cl.getMethod("get", null);
threadLocalSet = cl.getMethod("set",
new Class[] { ScriptRuntime.ObjectClass });
threadLocalCx = cl.newInstance();
} catch (Exception ex) { }
}
}
// We'd like to use "Thread.getContextClassLoader", but
// that's only available on Java2.
private static Method method_getContextClassLoader;
static {
// Don't use "Thread.class": that performs the lookup
// in the class initializer, which doesn't allow us to
// catch possible security exceptions.
Class threadClass = Kit.classOrNull("java.lang.Thread");
if (threadClass != null) {
try {
method_getContextClassLoader =
threadClass.getDeclaredMethod("getContextClassLoader",
new Class[0]);
} catch (Exception ex) { }
}
}
private static final Object contextListenersLock = new Object();
private static volatile Object contextListeners;
/**
* The activation of the currently executing function or script.
*/
NativeCall currentActivation;
// for Objects, Arrays to tag themselves as being printed out,
// so they don't print themselves out recursively.
// Use ObjToIntMap instead of java.util.HashSet for JDK 1.1 compatibility
ObjToIntMap iterating;
Object interpreterSecurityDomain;
int version;
private SecurityController securityController;
private ClassShutter classShutter;
private ErrorReporter errorReporter;
private RegExpProxy regExpProxy;
private Locale locale;
private boolean generatingDebug;
private boolean generatingDebugChanged;
private boolean generatingSource=true;
private boolean compileFunctionsWithDynamicScopeFlag;
private int optimizationLevel;
private WrapFactory wrapFactory;
Debugger debugger;
private Object debuggerData;
private int enterCount;
private Object instanceListeners;
private Hashtable hashtable;
private ClassLoader applicationClassLoader;
private boolean hideFromContextListeners;
private boolean creationEventWasSent;
/**
* This is the list of names of objects forcing the creation of
* function activation records.
*/
private Hashtable activationNames;
// For the interpreter to indicate line/source for error reports.
int interpreterLineIndex;
InterpreterData interpreterData;
// For instruction counting (interpreter only)
int instructionCount;
int instructionThreshold;
}
| src/org/mozilla/javascript/Context.java | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Brendan Eich
* Roger Lawrence
* Mike McCabe
* Ian D. Stewart
* Andi Vajda
* Andrew Wason
* Kemal Bayram
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
// API class
package org.mozilla.javascript;
import java.beans.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.ResourceBundle;
import java.text.MessageFormat;
import java.lang.reflect.*;
import org.mozilla.javascript.debug.*;
/**
* This class represents the runtime context of an executing script.
*
* Before executing a script, an instance of Context must be created
* and associated with the thread that will be executing the script.
* The Context will be used to store information about the executing
* of the script such as the call stack. Contexts are associated with
* the current thread using the <a href="#enter()">enter()</a> method.<p>
*
* The behavior of the execution engine may be altered through methods
* such as <a href="#setLanguageVersion>setLanguageVersion</a> and
* <a href="#setErrorReporter>setErrorReporter</a>.<p>
*
* Different forms of script execution are supported. Scripts may be
* evaluated from the source directly, or first compiled and then later
* executed. Interactive execution is also supported.<p>
*
* Some aspects of script execution, such as type conversions and
* object creation, may be accessed directly through methods of
* Context.
*
* @see Scriptable
* @author Norris Boyd
* @author Brendan Eich
*/
public class Context {
public static final String languageVersionProperty = "language version";
public static final String errorReporterProperty = "error reporter";
/**
* Create a new Context.
*
* Note that the Context must be associated with a thread before
* it can be used to execute a script.
*
* @see org.mozilla.javascript.Context#enter
*/
public Context() {
setLanguageVersion(VERSION_DEFAULT);
optimizationLevel = codegenClass != null ? 0 : -1;
}
/**
* Get a context associated with the current thread, creating
* one if need be.
*
* The Context stores the execution state of the JavaScript
* engine, so it is required that the context be entered
* before execution may begin. Once a thread has entered
* a Context, then getCurrentContext() may be called to find
* the context that is associated with the current thread.
* <p>
* Calling <code>enter()</code> will
* return either the Context currently associated with the
* thread, or will create a new context and associate it
* with the current thread. Each call to <code>enter()</code>
* must have a matching call to <code>exit()</code>. For example,
* <pre>
* Context cx = Context.enter();
* try {
* ...
* cx.evaluateString(...);
* } finally {
* Context.exit();
* }
* </pre>
* @return a Context associated with the current thread
* @see org.mozilla.javascript.Context#getCurrentContext
* @see org.mozilla.javascript.Context#exit
*/
public static Context enter()
{
return enter(null);
}
/**
* Get a Context associated with the current thread, using
* the given Context if need be.
* <p>
* The same as <code>enter()</code> except that <code>cx</code>
* is associated with the current thread and returned if
* the current thread has no associated context and <code>cx</code>
* is not associated with any other thread.
* @param cx a Context to associate with the thread if possible
* @return a Context associated with the current thread
*/
public static Context enter(Context cx)
{
Context old = getCurrentContext();
if (old != null) {
if (cx != null && cx != old && cx.enterCount != 0) {
// The suplied context must be the context for
// the current thread if it is already entered
throw new IllegalArgumentException(
"Cannot enter Context active on another thread");
}
cx = old;
} else {
if (cx == null)
cx = new Context();
if (cx.enterCount != 0) Kit.codeBug();
if (!cx.hideFromContextListeners && !cx.creationEventWasSent) {
cx.creationEventWasSent = true;
Object listeners = contextListeners;
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
((ContextListener)l).contextCreated(cx);
}
}
}
if (!cx.hideFromContextListeners) {
Object listeners = contextListeners;
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
((ContextListener)l).contextEntered(cx);
}
}
if (old == null) {
setThreadContext(cx);
}
++cx.enterCount;
return cx;
}
/**
* Exit a block of code requiring a Context.
*
* Calling <code>exit()</code> will remove the association between
* the current thread and a Context if the prior call to
* <code>enter()</code> on this thread newly associated a Context
* with this thread.
* Once the current thread no longer has an associated Context,
* it cannot be used to execute JavaScript until it is again associated
* with a Context.
*
* @see org.mozilla.javascript.Context#enter
*/
public static void exit()
{
Context cx = getCurrentContext();
if (cx == null) {
throw new IllegalStateException(
"Calling Context.exit without previous Context.enter");
}
if (Context.check && cx.enterCount < 1) Kit.codeBug();
--cx.enterCount;
if (cx.enterCount == 0) {
setThreadContext(null);
}
if (!cx.hideFromContextListeners) {
Object listeners = contextListeners;
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
((ContextListener)l).contextExited(cx);
}
if (cx.enterCount == 0) {
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
((ContextListener)l).contextReleased(cx);
}
}
}
}
/**
* Add a Context listener.
*/
public static void addContextListener(ContextListener listener)
{
synchronized (contextListenersLock) {
contextListeners = Kit.addListener(contextListeners, listener);
}
}
/**
* Remove a Context listener.
* @param listener the listener to remove.
*/
public static void removeContextListener(ContextListener listener)
{
synchronized (contextListenersLock) {
contextListeners = Kit.removeListener(contextListeners, listener);
}
}
/**
* Do not notify any listener registered with
* {@link #addContextListener(ContextListener)} about this Context instance.
* The function can only be called if this Context is not associated with
* any thread.
*/
public final void hideFromContextListeners()
{
if (enterCount != 0) throw new IllegalStateException();
hideFromContextListeners = true;
}
/**
* Get the current Context.
*
* The current Context is per-thread; this method looks up
* the Context associated with the current thread. <p>
*
* @return the Context associated with the current thread, or
* null if no context is associated with the current
* thread.
* @see org.mozilla.javascript.Context#enter
* @see org.mozilla.javascript.Context#exit
*/
public static Context getCurrentContext() {
if (threadLocalCx != null) {
try {
return (Context)threadLocalGet.invoke(threadLocalCx, null);
} catch (Exception ex) { }
}
Thread t = Thread.currentThread();
return (Context) threadContexts.get(t);
}
private static void setThreadContext(Context cx) {
if (threadLocalCx != null) {
try {
threadLocalSet.invoke(threadLocalCx, new Object[] { cx });
return;
} catch (Exception ex) { }
}
Thread t = Thread.currentThread();
if (cx != null) {
threadContexts.put(t, cx);
} else {
threadContexts.remove(t);
}
}
/**
* Language versions
*
* All integral values are reserved for future version numbers.
*/
/**
* The unknown version.
*/
public static final int VERSION_UNKNOWN = -1;
/**
* The default version.
*/
public static final int VERSION_DEFAULT = 0;
/**
* JavaScript 1.0
*/
public static final int VERSION_1_0 = 100;
/**
* JavaScript 1.1
*/
public static final int VERSION_1_1 = 110;
/**
* JavaScript 1.2
*/
public static final int VERSION_1_2 = 120;
/**
* JavaScript 1.3
*/
public static final int VERSION_1_3 = 130;
/**
* JavaScript 1.4
*/
public static final int VERSION_1_4 = 140;
/**
* JavaScript 1.5
*/
public static final int VERSION_1_5 = 150;
/**
* Get the current language version.
* <p>
* The language version number affects JavaScript semantics as detailed
* in the overview documentation.
*
* @return an integer that is one of VERSION_1_0, VERSION_1_1, etc.
*/
public int getLanguageVersion() {
return version;
}
/**
* Set the language version.
*
* <p>
* Setting the language version will affect functions and scripts compiled
* subsequently. See the overview documentation for version-specific
* behavior.
*
* @param version the version as specified by VERSION_1_0, VERSION_1_1, etc.
*/
public void setLanguageVersion(int version) {
Object listeners = instanceListeners;
if (listeners != null && version != this.version) {
firePropertyChangeImpl(listeners, languageVersionProperty,
new Integer(this.version),
new Integer(version));
}
this.version = version;
}
/**
* Get the implementation version.
*
* <p>
* The implementation version is of the form
* <pre>
* "<i>name langVer</i> <code>release</code> <i>relNum date</i>"
* </pre>
* where <i>name</i> is the name of the product, <i>langVer</i> is
* the language version, <i>relNum</i> is the release number, and
* <i>date</i> is the release date for that specific
* release in the form "yyyy mm dd".
*
* @return a string that encodes the product, language version, release
* number, and date.
*/
public String getImplementationVersion() {
return "Rhino 1.5 release 5 0000 00 00";
}
/**
* Get the current error reporter.
*
* @see org.mozilla.javascript.ErrorReporter
*/
public ErrorReporter getErrorReporter() {
if (errorReporter == null) {
errorReporter = new DefaultErrorReporter();
}
return errorReporter;
}
/**
* Change the current error reporter.
*
* @return the previous error reporter
* @see org.mozilla.javascript.ErrorReporter
*/
public ErrorReporter setErrorReporter(ErrorReporter reporter) {
ErrorReporter result = errorReporter;
Object listeners = instanceListeners;
if (listeners != null && errorReporter != reporter) {
firePropertyChangeImpl(listeners, errorReporterProperty,
errorReporter, reporter);
}
errorReporter = reporter;
return result;
}
/**
* Get the current locale. Returns the default locale if none has
* been set.
*
* @see java.util.Locale
*/
public Locale getLocale() {
if (locale == null)
locale = Locale.getDefault();
return locale;
}
/**
* Set the current locale.
*
* @see java.util.Locale
*/
public Locale setLocale(Locale loc) {
Locale result = locale;
locale = loc;
return result;
}
/**
* Register an object to receive notifications when a bound property
* has changed
* @see java.beans.PropertyChangeEvent
* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
* @param listener the listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener)
{
instanceListeners = Kit.addListener(instanceListeners, listener);
}
/**
* Remove an object from the list of objects registered to receive
* notification of changes to a bounded property
* @see java.beans.PropertyChangeEvent
* @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
* @param listener the listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener)
{
instanceListeners = Kit.removeListener(instanceListeners, listener);
}
/**
* Notify any registered listeners that a bounded property has changed
* @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
* @see java.beans.PropertyChangeListener
* @see java.beans.PropertyChangeEvent
* @param property the bound property
* @param oldValue the old value
* @param newVale the new value
*/
void firePropertyChange(String property, Object oldValue,
Object newValue)
{
Object listeners = instanceListeners;
if (listeners != null) {
firePropertyChangeImpl(listeners, property, oldValue, newValue);
}
}
private void firePropertyChangeImpl(Object listeners, String property,
Object oldValue, Object newValue)
{
for (int i = 0; ; ++i) {
Object l = Kit.getListener(listeners, i);
if (l == null)
break;
if (l instanceof PropertyChangeListener) {
PropertyChangeListener pcl = (PropertyChangeListener)l;
pcl.propertyChange(new PropertyChangeEvent(
this, property, oldValue, newValue));
}
}
}
/**
* Report a warning using the error reporter for the current thread.
*
* @param message the warning message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportWarning(String message, String sourceName,
int lineno, String lineSource,
int lineOffset)
{
Context cx = Context.getContext();
cx.getErrorReporter().warning(message, sourceName, lineno,
lineSource, lineOffset);
}
/**
* Report a warning using the error reporter for the current thread.
*
* @param message the warning message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportWarning(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
Context.reportWarning(message, filename, linep[0], null, 0);
}
/**
* Report an error using the error reporter for the current thread.
*
* @param message the error message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportError(String message, String sourceName,
int lineno, String lineSource,
int lineOffset)
{
Context cx = getCurrentContext();
if (cx != null) {
cx.getErrorReporter().error(message, sourceName, lineno,
lineSource, lineOffset);
} else {
throw new EvaluatorException(message, sourceName, lineno,
lineSource, lineOffset);
}
}
/**
* Report an error using the error reporter for the current thread.
*
* @param message the error message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportError(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
Context.reportError(message, filename, linep[0], null, 0);
}
/**
* Report a runtime error using the error reporter for the current thread.
*
* @param message the error message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @return a runtime exception that will be thrown to terminate the
* execution of the script
* @see org.mozilla.javascript.ErrorReporter
*/
public static EvaluatorException reportRuntimeError(String message,
String sourceName,
int lineno,
String lineSource,
int lineOffset)
{
Context cx = getCurrentContext();
if (cx != null) {
return cx.getErrorReporter().
runtimeError(message, sourceName, lineno,
lineSource, lineOffset);
} else {
throw new EvaluatorException(message, sourceName, lineno,
lineSource, lineOffset);
}
}
static EvaluatorException reportRuntimeError0(String messageId)
{
String msg = getMessage0(messageId);
return reportRuntimeError(msg);
}
static EvaluatorException reportRuntimeError1(String messageId,
Object arg1)
{
String msg = getMessage1(messageId, arg1);
return reportRuntimeError(msg);
}
static EvaluatorException reportRuntimeError2(String messageId,
Object arg1, Object arg2)
{
String msg = getMessage2(messageId, arg1, arg2);
return reportRuntimeError(msg);
}
static EvaluatorException reportRuntimeError3(String messageId,
Object arg1, Object arg2,
Object arg3)
{
String msg = getMessage3(messageId, arg1, arg2, arg3);
return reportRuntimeError(msg);
}
static EvaluatorException reportRuntimeError4(String messageId,
Object arg1, Object arg2,
Object arg3, Object arg4)
{
String msg = getMessage4(messageId, arg1, arg2, arg3, arg4);
return reportRuntimeError(msg);
}
/**
* Report a runtime error using the error reporter for the current thread.
*
* @param message the error message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static EvaluatorException reportRuntimeError(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
return Context.reportRuntimeError(message, filename, linep[0], null, 0);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This method does not affect the Context it is called upon.
*
* @return the initialized scope
*/
public GlobalScope initStandardObjects()
{
return initStandardObjects(false);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This form of the method also allows for creating "sealed" standard
* objects. An object that is sealed cannot have properties added, changed,
* or removed. This is useful to create a "superglobal" that can be shared
* among several top-level objects. Note that sealing is not allowed in
* the current ECMA/ISO language specification, but is likely for
* the next version.
*
* This method does not affect the Context it is called upon.
*
* @param sealed whether or not to create sealed standard objects that
* cannot be modified.
* @return the initialized scope
*/
public GlobalScope initStandardObjects(boolean sealed)
{
GlobalScope global = new GlobalScope();
initStandardObjects(global, sealed);
return global;
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This method does not affect the Context it is called upon.
*
* If the explicit scope argument is not null and is not an instance of
* {@link GlobalScope} or its subclasses, parts of the standard library
* will be run slower.
*
* @param scope the scope to initialize, or null, in which case a new
* object will be created to serve as the scope
* @return the initialized scope
*/
public ScriptableObject initStandardObjects(ScriptableObject scope)
{
return initStandardObjects(scope, false);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This method does not affect the Context it is called upon.<p>
*
* This form of the method also allows for creating "sealed" standard
* objects. An object that is sealed cannot have properties added, changed,
* or removed. This is useful to create a "superglobal" that can be shared
* among several top-level objects. Note that sealing is not allowed in
* the current ECMA/ISO language specification, but is likely for
* the next version.
*
* If the explicit scope argument is not null and is not an instance of
* {@link GlobalScope} or its subclasses, parts of the standard library
* will be run slower.
*
* @param scope the scope to initialize, or null, in which case a new
* object will be created to serve as the scope
* @param sealed whether or not to create sealed standard objects that
* cannot be modified.
* @return the initialized scope
* @since 1.4R3
*/
public ScriptableObject initStandardObjects(ScriptableObject scope,
boolean sealed)
{
if (scope == null) {
scope = new GlobalScope();
} else if (!(scope instanceof GlobalScope)) {
GlobalScope.embed(scope);
}
BaseFunction.init(this, scope, sealed);
NativeObject.init(this, scope, sealed);
Scriptable objectProto = ScriptableObject.getObjectPrototype(scope);
// Function.prototype.__proto__ should be Object.prototype
Scriptable functionProto = ScriptableObject.getFunctionPrototype(scope);
functionProto.setPrototype(objectProto);
// Set the prototype of the object passed in if need be
if (scope.getPrototype() == null)
scope.setPrototype(objectProto);
// must precede NativeGlobal since it's needed therein
NativeError.init(this, scope, sealed);
NativeGlobal.init(this, scope, sealed);
NativeArray.init(this, scope, sealed);
NativeString.init(this, scope, sealed);
NativeBoolean.init(this, scope, sealed);
NativeNumber.init(this, scope, sealed);
NativeDate.init(this, scope, sealed);
NativeMath.init(this, scope, sealed);
NativeWith.init(this, scope, sealed);
NativeCall.init(this, scope, sealed);
NativeScript.init(this, scope, sealed);
new LazilyLoadedCtor(scope,
"RegExp",
"org.mozilla.javascript.regexp.NativeRegExp",
sealed);
// This creates the Packages and java package roots.
new LazilyLoadedCtor(scope,
"Packages",
"org.mozilla.javascript.NativeJavaTopPackage",
sealed);
new LazilyLoadedCtor(scope,
"java",
"org.mozilla.javascript.NativeJavaTopPackage",
sealed);
new LazilyLoadedCtor(scope,
"getClass",
"org.mozilla.javascript.NativeJavaTopPackage",
sealed);
// Define the JavaAdapter class, allowing it to be overridden.
String adapterClass = "org.mozilla.javascript.JavaAdapter";
String adapterProperty = "JavaAdapter";
try {
adapterClass = System.getProperty(adapterClass, adapterClass);
adapterProperty = System.getProperty
("org.mozilla.javascript.JavaAdapterClassName",
adapterProperty);
}
catch (SecurityException e) {
// We may not be allowed to get system properties. Just
// use the default adapter in that case.
}
new LazilyLoadedCtor(scope, adapterProperty, adapterClass, sealed);
return scope;
}
/**
* Get the singleton object that represents the JavaScript Undefined value.
*/
public static Object getUndefinedValue() {
return Undefined.instance;
}
/**
* Evaluate a JavaScript source string.
*
* The provided source name and line number are used for error messages
* and for producing debug information.
*
* @param scope the scope to execute in
* @param source the JavaScript source
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return the result of evaluating the string
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while evaluating the source string
* @see org.mozilla.javascript.SecurityController
*/
public Object evaluateString(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
throws JavaScriptException
{
Script script = compileString(scope, source, sourceName, lineno,
securityDomain);
if (script != null) {
return script.exec(this, scope);
} else {
return null;
}
}
/**
* Evaluate a reader as JavaScript source.
*
* All characters of the reader are consumed.
*
* @param scope the scope to execute in
* @param in the Reader to get JavaScript source from
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return the result of evaluating the source
*
* @exception IOException if an IOException was generated by the Reader
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while evaluating the Reader
*/
public Object evaluateReader(Scriptable scope, Reader in,
String sourceName, int lineno,
Object securityDomain)
throws IOException, JavaScriptException
{
Script script = compileReader(scope, in, sourceName, lineno,
securityDomain);
if (script != null) {
return script.exec(this, scope);
} else {
return null;
}
}
/**
* Check whether a string is ready to be compiled.
* <p>
* stringIsCompilableUnit is intended to support interactive compilation of
* javascript. If compiling the string would result in an error
* that might be fixed by appending more source, this method
* returns false. In every other case, it returns true.
* <p>
* Interactive shells may accumulate source lines, using this
* method after each new line is appended to check whether the
* statement being entered is complete.
*
* @param source the source buffer to check
* @return whether the source is ready for compilation
* @since 1.4 Release 2
*/
public boolean stringIsCompilableUnit(String source)
{
// no source name or source text manager, because we're just
// going to throw away the result.
TokenStream ts = new TokenStream(null, source, false, null, 1,
new DefaultErrorReporter());
boolean errorseen = false;
Interpreter compiler = new Interpreter();
IRFactory irf = compiler.createIRFactory(this, ts);
Parser p = createParser();
Decompiler decompiler = new Decompiler();
try {
p.parse(ts, irf, decompiler);
} catch (IOException ioe) {
errorseen = true;
} catch (EvaluatorException ee) {
errorseen = true;
}
// Return false only if an error occurred as a result of reading past
// the end of the file, i.e. if the source could be fixed by
// appending more source.
if (errorseen && ts.eof())
return false;
else
return true;
}
/**
* Compiles the source in the given reader.
* <p>
* Returns a script that may later be executed.
* Will consume all the source in the reader.
*
* @param scope if nonnull, will be the scope in which the script object
* is created. The script object will be a valid JavaScript object
* as if it were created using the JavaScript1.3 Script constructor
* @param in the input reader
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number for reporting errors
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a script that may later be executed
* @see org.mozilla.javascript.Script#exec
* @exception IOException if an IOException was generated by the Reader
*/
public Script compileReader(Scriptable scope, Reader in, String sourceName,
int lineno, Object securityDomain)
throws IOException
{
if (lineno < 0) {
throw new IllegalArgumentException(
"Line number can not be negative:"+lineno);
}
return (Script) compile(scope, in, null, sourceName, lineno,
securityDomain, false);
}
/**
* Compiles the source in the given string.
* <p>
* Returns a script that may later be executed.
*
* @param scope if nonnull, will be the scope in which the script object
* is created. The script object will be a valid JavaScript object
* as if it were created using the JavaScript1.3 Script constructor
* @param source the source string
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number for reporting errors
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a script that may later be executed
* @see org.mozilla.javascript.Script#exec
*/
public Script compileString(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
{
if (lineno < 0) {
throw new IllegalArgumentException(
"Line number can not be negative:"+lineno);
}
try {
return (Script) compile(scope, null, source, sourceName, lineno,
securityDomain, false);
} catch (IOException ex) {
// Should not happen when dealing with source as string
throw new RuntimeException();
}
}
/**
* Compile a JavaScript function.
* <p>
* The function source must be a function definition as defined by
* ECMA (e.g., "function f(a) { return a; }").
*
* @param scope the scope to compile relative to
* @param source the function definition source
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a Function that may later be called
* @see org.mozilla.javascript.Function
*/
public Function compileFunction(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
{
try {
return (Function) compile(scope, null, source, sourceName, lineno,
securityDomain, true);
}
catch (IOException ioe) {
// Should never happen because we just made the reader
// from a String
throw new RuntimeException();
}
}
/**
* Decompile the script.
* <p>
* The canonical source of the script is returned.
*
* @param script the script to decompile
* @param scope the scope under which to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the script source
*/
public String decompileScript(Script script, Scriptable scope,
int indent)
{
NativeFunction scriptImpl = (NativeFunction) script;
return scriptImpl.decompile(this, indent, false);
}
/**
* Decompile a JavaScript Function.
* <p>
* Decompiles a previously compiled JavaScript function object to
* canonical source.
* <p>
* Returns function body of '[native code]' if no decompilation
* information is available.
*
* @param fun the JavaScript function to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the function source
*/
public String decompileFunction(Function fun, int indent) {
if (fun instanceof BaseFunction)
return ((BaseFunction)fun).decompile(this, indent, false);
else
return "function " + fun.getClassName() +
"() {\n\t[native code]\n}\n";
}
/**
* Decompile the body of a JavaScript Function.
* <p>
* Decompiles the body a previously compiled JavaScript Function
* object to canonical source, omitting the function header and
* trailing brace.
*
* Returns '[native code]' if no decompilation information is available.
*
* @param fun the JavaScript function to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the function body source.
*/
public String decompileFunctionBody(Function fun, int indent) {
if (fun instanceof BaseFunction)
return ((BaseFunction)fun).decompile(this, indent, true);
else
// not sure what the right response here is. JSRef currently
// dumps core.
return "[native code]\n";
}
/**
* Create a new JavaScript object.
*
* Equivalent to evaluating "new Object()".
* @param scope the scope to search for the constructor and to evaluate
* against
* @return the new object
* @exception EvaluatorException if "Object" cannot be found in
* the scope or is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while creating the object
*/
public Scriptable newObject(Scriptable scope)
throws EvaluatorException, JavaScriptException
{
return newObject(scope, "Object", ScriptRuntime.emptyArgs);
}
/**
* Create a new JavaScript object by executing the named constructor.
*
* The call <code>newObject(scope, "Foo")</code> is equivalent to
* evaluating "new Foo()".
*
* @param scope the scope to search for the constructor and to evaluate against
* @param constructorName the name of the constructor to call
* @return the new object
* @exception EvaluatorException if a property with the constructor
* name cannot be found in the scope or is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while creating the object
*/
public Scriptable newObject(Scriptable scope, String constructorName)
throws EvaluatorException, JavaScriptException
{
return newObject(scope, constructorName, ScriptRuntime.emptyArgs);
}
/**
* Creates a new JavaScript object by executing the named constructor.
*
* Searches <code>scope</code> for the named constructor, calls it with
* the given arguments, and returns the result.<p>
*
* The code
* <pre>
* Object[] args = { "a", "b" };
* newObject(scope, "Foo", args)</pre>
* is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo
* constructor has been defined in <code>scope</code>.
*
* @param scope The scope to search for the constructor and to evaluate
* against
* @param constructorName the name of the constructor to call
* @param args the array of arguments for the constructor
* @return the new object
* @exception EvaluatorException if a property with the constructor
* name cannot be found in the scope or is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurs while creating the object
*/
public Scriptable newObject(Scriptable scope, String constructorName,
Object[] args)
throws EvaluatorException, JavaScriptException
{
scope = ScriptableObject.getTopLevelScope(scope);
Function ctor = ScriptRuntime.getExistingCtor(this, scope,
constructorName);
if (args == null) { args = ScriptRuntime.emptyArgs; }
return ctor.construct(this, scope, args);
}
/**
* Create an array with a specified initial length.
* <p>
* @param scope the scope to create the object in
* @param length the initial length (JavaScript arrays may have
* additional properties added dynamically).
* @return the new array object
*/
public Scriptable newArray(Scriptable scope, int length) {
Scriptable result = new NativeArray(length);
newArrayHelper(scope, result);
return result;
}
/**
* Create an array with a set of initial elements.
* <p>
* @param scope the scope to create the object in
* @param elements the initial elements. Each object in this array
* must be an acceptable JavaScript type.
* @return the new array object
*/
public Scriptable newArray(Scriptable scope, Object[] elements) {
Scriptable result = new NativeArray(elements);
newArrayHelper(scope, result);
return result;
}
/**
* Get the elements of a JavaScript array.
* <p>
* If the object defines a length property convertible to double number,
* then the number is converted Uint32 value as defined in Ecma 9.6
* and Java array of that size is allocated.
* The array is initialized with the values obtained by
* calling get() on object for each value of i in [0,length-1]. If
* there is not a defined value for a property the Undefined value
* is used to initialize the corresponding element in the array. The
* Java array is then returned.
* If the object doesn't define a length property or it is not a number,
* empty array is returned.
* @param object the JavaScript array or array-like object
* @return a Java array of objects
* @since 1.4 release 2
*/
public Object[] getElements(Scriptable object) {
long longLen = NativeArray.getLengthProperty(object);
if (longLen > Integer.MAX_VALUE) {
// arrays beyond MAX_INT is not in Java in any case
throw new IllegalArgumentException();
}
int len = (int) longLen;
if (len == 0) {
return ScriptRuntime.emptyArgs;
} else {
Object[] result = new Object[len];
for (int i=0; i < len; i++) {
Object elem = ScriptableObject.getProperty(object, i);
result[i] = (elem == Scriptable.NOT_FOUND) ? Undefined.instance
: elem;
}
return result;
}
}
/**
* Convert the value to a JavaScript boolean value.
* <p>
* See ECMA 9.2.
*
* @param value a JavaScript value
* @return the corresponding boolean value converted using
* the ECMA rules
*/
public static boolean toBoolean(Object value) {
return ScriptRuntime.toBoolean(value);
}
/**
* Convert the value to a JavaScript Number value.
* <p>
* Returns a Java double for the JavaScript Number.
* <p>
* See ECMA 9.3.
*
* @param value a JavaScript value
* @return the corresponding double value converted using
* the ECMA rules
*/
public static double toNumber(Object value) {
return ScriptRuntime.toNumber(value);
}
/**
* Convert the value to a JavaScript String value.
* <p>
* See ECMA 9.8.
* <p>
* @param value a JavaScript value
* @return the corresponding String value converted using
* the ECMA rules
*/
public static String toString(Object value) {
return ScriptRuntime.toString(value);
}
/**
* Convert the value to an JavaScript object value.
* <p>
* Note that a scope must be provided to look up the constructors
* for Number, Boolean, and String.
* <p>
* See ECMA 9.9.
* <p>
* Additionally, arbitrary Java objects and classes will be
* wrapped in a Scriptable object with its Java fields and methods
* reflected as JavaScript properties of the object.
*
* @param value any Java object
* @param scope global scope containing constructors for Number,
* Boolean, and String
* @return new JavaScript object
*/
public static Scriptable toObject(Object value, Scriptable scope) {
return ScriptRuntime.toObject(scope, value);
}
/**
* @deprecated Use {@link #toObject(Object, Scriptable)} instead.
*/
public static Scriptable toObject(Object value, Scriptable scope,
Class staticType)
{
return ScriptRuntime.toObject(scope, value);
}
/**
* Convert a JavaScript value into the desired type.
* Uses the semantics defined with LiveConnect3 and throws an
* Illegal argument exception if the conversion cannot be performed.
* @param value the JavaScript value to convert
* @param desiredType the Java type to convert to. Primitive Java
* types are represented using the TYPE fields in the corresponding
* wrapper class in java.lang.
* @return the converted value
* @throws IllegalArgumentException if the conversion cannot be performed
*/
public static Object toType(Object value, Class desiredType)
throws IllegalArgumentException
{
return NativeJavaObject.coerceType(desiredType, value, false);
}
/**
* Tell whether debug information is being generated.
* @since 1.3
*/
public boolean isGeneratingDebug() {
return generatingDebug;
}
/**
* Specify whether or not debug information should be generated.
* <p>
* Setting the generation of debug information on will set the
* optimization level to zero.
* @since 1.3
*/
public void setGeneratingDebug(boolean generatingDebug) {
generatingDebugChanged = true;
if (generatingDebug && getOptimizationLevel() > 0)
setOptimizationLevel(0);
this.generatingDebug = generatingDebug;
}
/**
* Tell whether source information is being generated.
* @since 1.3
*/
public boolean isGeneratingSource() {
return generatingSource;
}
/**
* Specify whether or not source information should be generated.
* <p>
* Without source information, evaluating the "toString" method
* on JavaScript functions produces only "[native code]" for
* the body of the function.
* Note that code generated without source is not fully ECMA
* conformant.
* @since 1.3
*/
public void setGeneratingSource(boolean generatingSource) {
this.generatingSource = generatingSource;
}
/**
* Get the current optimization level.
* <p>
* The optimization level is expressed as an integer between -1 and
* 9.
* @since 1.3
*
*/
public int getOptimizationLevel() {
return optimizationLevel;
}
/**
* Set the current optimization level.
* <p>
* The optimization level is expected to be an integer between -1 and
* 9. Any negative values will be interpreted as -1, and any values
* greater than 9 will be interpreted as 9.
* An optimization level of -1 indicates that interpretive mode will
* always be used. Levels 0 through 9 indicate that class files may
* be generated. Higher optimization levels trade off compile time
* performance for runtime performance.
* The optimizer level can't be set greater than -1 if the optimizer
* package doesn't exist at run time.
* @param optimizationLevel an integer indicating the level of
* optimization to perform
* @since 1.3
*
*/
public void setOptimizationLevel(int optimizationLevel) {
if (optimizationLevel < 0) {
optimizationLevel = -1;
} else if (optimizationLevel > 9) {
optimizationLevel = 9;
}
if (codegenClass == null)
optimizationLevel = -1;
this.optimizationLevel = optimizationLevel;
}
/**
* Set the security controller for this context.
* <p> SecurityController may only be set if it is currently null.
* Otherwise a SecurityException is thrown.
* @param controller a SecurityController object
* @throws SecurityException if there is already a SecurityController
* object for this Context
*/
public void setSecurityController(SecurityController controller) {
if (controller == null) throw new IllegalArgumentException();
if (securityController != null) {
throw new SecurityException("Cannot overwrite existing " +
"SecurityController object");
}
securityController = controller;
}
/**
* Set the LiveConnect access filter for this context.
* <p> {@link ClassShutter} may only be set if it is currently null.
* Otherwise a SecurityException is thrown.
* @param shutter a ClassShutter object
* @throws SecurityException if there is already a ClassShutter
* object for this Context
*/
public void setClassShutter(ClassShutter shutter) {
if (shutter == null) throw new IllegalArgumentException();
if (classShutter != null) {
throw new SecurityException("Cannot overwrite existing " +
"ClassShutter object");
}
classShutter = shutter;
}
final ClassShutter getClassShutter() {
return classShutter;
}
/**
* Get a value corresponding to a key.
* <p>
* Since the Context is associated with a thread it can be
* used to maintain values that can be later retrieved using
* the current thread.
* <p>
* Note that the values are maintained with the Context, so
* if the Context is disassociated from the thread the values
* cannot be retreived. Also, if private data is to be maintained
* in this manner the key should be a java.lang.Object
* whose reference is not divulged to untrusted code.
* @param key the key used to lookup the value
* @return a value previously stored using putThreadLocal.
*/
public final Object getThreadLocal(Object key) {
if (hashtable == null)
return null;
return hashtable.get(key);
}
/**
* Put a value that can later be retrieved using a given key.
* <p>
* @param key the key used to index the value
* @param value the value to save
*/
public void putThreadLocal(Object key, Object value) {
if (hashtable == null)
hashtable = new Hashtable();
hashtable.put(key, value);
}
/**
* Remove values from thread-local storage.
* @param key the key for the entry to remove.
* @since 1.5 release 2
*/
public void removeThreadLocal(Object key) {
if (hashtable == null)
return;
hashtable.remove(key);
}
/**
* Return whether functions are compiled by this context using
* dynamic scope.
* <p>
* If functions are compiled with dynamic scope, then they execute
* in the scope of their caller, rather than in their parent scope.
* This is useful for sharing functions across multiple scopes.
* @since 1.5 Release 1
*/
public final boolean hasCompileFunctionsWithDynamicScope() {
return compileFunctionsWithDynamicScopeFlag;
}
/**
* Set whether functions compiled by this context should use
* dynamic scope.
* <p>
* @param flag if true, compile functions with dynamic scope
* @since 1.5 Release 1
*/
public void setCompileFunctionsWithDynamicScope(boolean flag) {
compileFunctionsWithDynamicScopeFlag = flag;
}
/**
* @deprecated To enable/disable caching for a particular top scope,
* use {@link GlobalScope#get(Scriptable)} and
* {@link GlobalScope#setCachingEnabled(boolean)}.
* The function is kept only for compatibility and does nothing.
*/
public static void setCachingEnabled(boolean cachingEnabled)
{
}
// Proxy to allow to use deprecated WrapHandler in place of WrapFactory
private static class WrapHandlerProxy extends WrapFactory {
WrapHandler _handler;
WrapHandlerProxy(WrapHandler handler) {
_handler = handler;
}
public Object wrap(Context cx, Scriptable scope,
Object obj, Class staticType)
{
if (obj == null) { return obj; }
Object result = _handler.wrap(scope, obj, staticType);
if (result == null) {
result = super.wrap(cx, scope, obj, staticType);
}
return result;
}
public Scriptable wrapNewObject(Context cx, Scriptable scope,
Object obj)
{
Object wrap = _handler.wrap(scope, obj, obj.getClass());
if (wrap instanceof Scriptable) {
return (Scriptable)wrap;
}
if (wrap == null) {
return super.wrapNewObject(cx, scope, obj);
}
throw new RuntimeException
("Please upgrade from WrapHandler to WrapFactory");
}
}
/**
* @deprecated As of Rhino 1.5 Release 4, use
* {@link WrapFactory} and {@link #setWrapFactory(WrapFactory)}
*/
public void setWrapHandler(WrapHandler wrapHandler) {
if (wrapHandler == null) {
setWrapFactory(new WrapFactory());
} else {
setWrapFactory(new WrapHandlerProxy(wrapHandler));
}
}
/**
* @deprecated As of Rhino 1.5 Release 4, use
* {@link WrapFactory} and {@link #getWrapFactory()}
*/
public WrapHandler getWrapHandler() {
WrapFactory f = getWrapFactory();
if (f instanceof WrapHandlerProxy) {
return ((WrapHandlerProxy)f)._handler;
}
return null;
}
/**
* Set a WrapFactory for this Context.
* <p>
* The WrapFactory allows custom object wrapping behavior for
* Java object manipulated with JavaScript.
* @see org.mozilla.javascript.WrapFactory
* @since 1.5 Release 4
*/
public void setWrapFactory(WrapFactory wrapFactory) {
if (wrapFactory == null) throw new IllegalArgumentException();
this.wrapFactory = wrapFactory;
}
/**
* Return the current WrapHandler, or null if none is defined.
* @see org.mozilla.javascript.WrapHandler
* @since 1.5 Release 4
*/
public final WrapFactory getWrapFactory() {
if (wrapFactory == null) {
wrapFactory = new WrapFactory();
}
return wrapFactory;
}
/**
* Return the current debugger.
* @return the debugger, or null if none is attached.
*/
public final Debugger getDebugger() {
return debugger;
}
/**
* Return the debugger context data associated with current context.
* @return the debugger data, or null if debugger is not attached
*/
public final Object getDebuggerContextData() {
return debuggerData;
}
/**
* Set the associated debugger.
* @param debugger the debugger to be used on callbacks from
* the engine.
* @param contextData arbitrary object that debugger can use to store
* per Context data.
*/
public void setDebugger(Debugger debugger, Object contextData) {
this.debugger = debugger;
debuggerData = contextData;
}
/**
* If hasFeature(FEATURE_NON_ECMA_GET_YEAR) returns true,
* Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000.
* The default behavior is always to subtruct 1900 as rquired
* by Ecma B.2.4.
*/
public static final int FEATURE_NON_ECMA_GET_YEAR = 1;
/**
* If hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME) returns true,
* allow 'function memberExpression(args) { body }' to be syntax sugar
* for
* 'memberExpression = function(args) { body }', when memberExpression
* is not simply identifier.
* See Ecma-262, section 11.2 for definition of memberExpression.
*/
public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2;
/**
* If hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER) returns true,
* treat future reserved keyword (see Ecma-262, section 7.5.3) as ordinary
* identifiers but warn about this usage
*/
public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3;
/**
* If hasFeature(FEATURE_TO_STRING_AS_SOURCE) returns true,
* calling toString on JS objects gives JS source with code to create an
* object with all enumeratable fields of the original object instead of
* printing "[object <object-type>]".
* By default {@link #hasFeature(int)} returns true only if
* the current JS version is set to {@link #VERSION_1_2}.
*/
public static final int FEATURE_TO_STRING_AS_SOURCE = 4;
/**
* Controls certain aspects of script semantics.
* Should be overwritten to alter default behavior.
* @param featureIndex feature index to check
* @return true if the <code>featureIndex</code> feature is turned on
* @see #FEATURE_NON_ECMA_GET_YEAR
* @see #FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME
* @see #FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER
* @see #FEATURE_TO_STRING_AS_SOURCE
*/
public boolean hasFeature(int featureIndex) {
switch (featureIndex) {
case FEATURE_NON_ECMA_GET_YEAR:
/*
* During the great date rewrite of 1.3, we tried to track the
* evolving ECMA standard, which then had a definition of
* getYear which always subtracted 1900. Which we
* implemented, not realizing that it was incompatible with
* the old behavior... now, rather than thrash the behavior
* yet again, we've decided to leave it with the - 1900
* behavior and point people to the getFullYear method. But
* we try to protect existing scripts that have specified a
* version...
*/
return (version == Context.VERSION_1_0
|| version == Context.VERSION_1_1
|| version == Context.VERSION_1_2);
case FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME:
return false;
case FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER:
return false;
case FEATURE_TO_STRING_AS_SOURCE:
return version == VERSION_1_2;
}
// It is a bug to call the method with unknown featureIndex
throw new IllegalArgumentException();
}
/**
* Get/Set threshold of executed instructions counter that triggers call to
* <code>observeInstructionCount()</code>.
* When the threshold is zero, instruction counting is disabled,
* otherwise each time the run-time executes at least the threshold value
* of script instructions, <code>observeInstructionCount()</code> will
* be called.
*/
public int getInstructionObserverThreshold() {
return instructionThreshold;
}
public void setInstructionObserverThreshold(int threshold) {
instructionThreshold = threshold;
}
/**
* Allow application to monitor counter of executed script instructions
* in Context subclasses.
* Run-time calls this when instruction counting is enabled and the counter
* reaches limit set by <code>setInstructionObserverThreshold()</code>.
* The method is useful to observe long running scripts and if necessary
* to terminate them.
* @param instructionCount amount of script instruction executed since
* last call to <code>observeInstructionCount</code>
* @throws Error to terminate the script
*/
protected void observeInstructionCount(int instructionCount) {}
public GeneratedClassLoader createClassLoader(ClassLoader parent) {
return new DefiningClassLoader(parent);
}
public final ClassLoader getApplicationClassLoader()
{
if (applicationClassLoader != null) {
return applicationClassLoader;
}
ClassLoader loader = null;
if (method_getContextClassLoader != null) {
Thread thread = Thread.currentThread();
try {
loader = (ClassLoader)method_getContextClassLoader.invoke(
thread, ScriptRuntime.emptyArgs);
} catch (Exception ex) { }
}
if (loader != null && !testIfCanUseLoader(loader)) {
loader = null;
}
if (loader == null) {
// If Context was subclassed, the following gets the loader
// for the subclass which can be different from Rhino loader,
// but then proper Rhino classes should be accessible through it
// in any case or JVM class loading is severely broken
loader = this.getClass().getClassLoader();
}
// The result is not cached since caching
// Thread.getContextClassLoader prevents it from GC which
// may lead to a memory leak and hides updates to
// Thread.getContextClassLoader
return loader;
}
public void setApplicationClassLoader(ClassLoader loader)
{
if (loader == null) {
// restore default behaviour
applicationClassLoader = null;
return;
}
if (!testIfCanUseLoader(loader)) {
throw new IllegalArgumentException(
"Loader can not resolve Rhino classes");
}
applicationClassLoader = loader;
}
private boolean testIfCanUseLoader(ClassLoader loader)
{
// If Context was subclussed, cxClass != Context.class
Class cxClass = this.getClass();
// Check that Context or its suclass is accesible from this loader
Class x = Kit.classOrNull(loader, cxClass.getName());
if (x != cxClass) {
// The check covers the case when x == null =>
// threadLoader does not know about Rhino or the case
// when x != null && x != cxClass =>
// threadLoader loads unrelated Rhino instance
return false;
}
return true;
}
/********** end of API **********/
static String getMessage0(String messageId)
{
return getMessage(messageId, null);
}
static String getMessage1(String messageId, Object arg1)
{
Object[] arguments = {arg1};
return getMessage(messageId, arguments);
}
static String getMessage2(String messageId, Object arg1, Object arg2)
{
Object[] arguments = {arg1, arg2};
return getMessage(messageId, arguments);
}
static String getMessage3(String messageId, Object arg1, Object arg2,
Object arg3)
{
Object[] arguments = {arg1, arg2, arg3};
return getMessage(messageId, arguments);
}
static String getMessage4(String messageId, Object arg1, Object arg2,
Object arg3, Object arg4)
{
Object[] arguments = {arg1, arg2, arg3, arg4};
return getMessage(messageId, arguments);
}
/**
* Internal method that reports an error for missing calls to
* enter().
*/
static Context getContext() {
Context cx = getCurrentContext();
if (cx == null) {
throw new RuntimeException(
"No Context associated with current Thread");
}
return cx;
}
/* OPT there's a noticable delay for the first error! Maybe it'd
* make sense to use a ListResourceBundle instead of a properties
* file to avoid (synchronized) text parsing.
*/
static final String defaultResource =
"org.mozilla.javascript.resources.Messages";
static String getMessage(String messageId, Object[] arguments) {
Context cx = getCurrentContext();
Locale locale = cx != null ? cx.getLocale() : Locale.getDefault();
// ResourceBundle does cacheing.
ResourceBundle rb = ResourceBundle.getBundle(defaultResource, locale);
String formatString;
try {
formatString = rb.getString(messageId);
} catch (java.util.MissingResourceException mre) {
throw new RuntimeException
("no message resource found for message property "+ messageId);
}
/*
* It's OK to format the string, even if 'arguments' is null;
* we need to format it anyway, to make double ''s collapse to
* single 's.
*/
// TODO: MessageFormat is not available on pJava
MessageFormat formatter = new MessageFormat(formatString);
return formatter.format(arguments);
}
private static String readReader(Reader r)
throws IOException
{
char[] buffer = new char[512];
int cursor = 0;
for (;;) {
int n = r.read(buffer, cursor, buffer.length - cursor);
if (n < 0) { break; }
cursor += n;
if (cursor == buffer.length) {
char[] tmp = new char[buffer.length * 2];
System.arraycopy(buffer, 0, tmp, 0, cursor);
buffer = tmp;
}
}
return new String(buffer, 0, cursor);
}
/**
* Compile a script.
*
* Reads script source from the reader and compiles it, returning
* a class for either the script or the function depending on the
* value of <code>returnFunction</code>.
*
* @param scope the scope to compile relative to
* @param in the Reader to read source from
* @param sourceName the name of the origin of the source (usually
* a file or URL)
* @param lineno the line number of the start of the source
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @param returnFunction if true, will expect the source to contain
* a function; return value is assumed to
* then be a org.mozilla.javascript.Function
* @return a class for the script or function
* @see org.mozilla.javascript.Context#compileReader
*/
private Object compile(Scriptable scope,
Reader sourceReader, String sourceString,
String sourceName, int lineno,
Object securityDomain, boolean returnFunction)
throws IOException
{
// One of sourceReader or sourceString has to be null
if (!(sourceReader == null ^ sourceString == null)) Kit.codeBug();
Interpreter compiler = createCompiler();
if (securityController != null) {
securityDomain = securityController.
getDynamicSecurityDomain(securityDomain);
} else {
securityDomain = null;
}
if (debugger != null) {
if (sourceReader != null) {
sourceString = readReader(sourceReader);
sourceReader = null;
}
}
boolean fromEval = (scope != null);
TokenStream ts = new TokenStream(sourceReader, sourceString,
fromEval, sourceName, lineno,
getErrorReporter());
Parser p = createParser();
IRFactory irf = compiler.createIRFactory(this, ts);
Decompiler decompiler = new Decompiler();
ScriptOrFnNode tree = p.parse(ts, irf, decompiler);
if (tree == null)
return null;
String encodedSource = null;
if (isGeneratingSource()) {
encodedSource = decompiler.getEncodedSource();
}
decompiler = null; // It helps GC
tree = compiler.transform(this, irf, tree);
if (Token.printTrees) { System.out.println(tree.toStringTree(tree)); }
if (returnFunction) {
int functionCount = tree.getFunctionCount();
if (functionCount == 0)
return null;
tree = tree.getFunctionNode(0);
}
Object result = compiler.compile(this, scope, tree,
securityController, securityDomain,
encodedSource);
if (debugger != null) {
if (sourceString == null) Kit.codeBug();
compiler.notifyDebuggerCompilationDone(this, result, sourceString);
}
return ts.errorCount == 0 ? result : null;
}
private static Class codegenClass = Kit.classOrNull(
"org.mozilla.javascript.optimizer.Codegen");
private Interpreter createCompiler() {
Interpreter result = null;
if (optimizationLevel >= 0 && codegenClass != null) {
result = (Interpreter)Kit.newInstanceOrNull(codegenClass);
}
if (result == null) {
result = new Interpreter();
}
return result;
}
private Parser createParser() {
Parser parser = new Parser();
parser.setLanguageVersion(getLanguageVersion());
parser.setAllowMemberExprAsFunctionName(
hasFeature(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME));
return parser;
}
static String getSourcePositionFromStack(int[] linep) {
Context cx = getCurrentContext();
if (cx == null)
return null;
if (cx.interpreterData != null) {
return Interpreter.getSourcePositionFromStack(cx, linep);
}
/**
* A bit of a hack, but the only way to get filename and line
* number from an enclosing frame.
*/
CharArrayWriter writer = new CharArrayWriter();
RuntimeException re = new RuntimeException();
re.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
int open = -1;
int close = -1;
int colon = -1;
for (int i=0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ':')
colon = i;
else if (c == '(')
open = i;
else if (c == ')')
close = i;
else if (c == '\n' && open != -1 && close != -1 && colon != -1 &&
open < colon && colon < close)
{
String fileStr = s.substring(open + 1, colon);
if (!fileStr.endsWith(".java")) {
String lineStr = s.substring(colon + 1, close);
try {
linep[0] = Integer.parseInt(lineStr);
return fileStr;
}
catch (NumberFormatException e) {
// fall through
}
}
open = close = colon = -1;
}
}
return null;
}
RegExpProxy getRegExpProxy() {
if (regExpProxy == null) {
Class cl = Kit.classOrNull(
"org.mozilla.javascript.regexp.RegExpImpl");
if (cl != null) {
regExpProxy = (RegExpProxy)Kit.newInstanceOrNull(cl);
}
}
return regExpProxy;
}
private void newArrayHelper(Scriptable scope, Scriptable array) {
array.setParentScope(scope);
Object ctor = ScriptRuntime.getTopLevelProp(scope, "Array");
if (ctor != null && ctor instanceof Scriptable) {
Scriptable s = (Scriptable) ctor;
array.setPrototype((Scriptable) s.get("prototype", s));
}
}
final boolean isVersionECMA1() {
return version == VERSION_DEFAULT || version >= VERSION_1_3;
}
// Should not be public
SecurityController getSecurityController() {
return securityController;
}
public boolean isGeneratingDebugChanged() {
return generatingDebugChanged;
}
/**
* Add a name to the list of names forcing the creation of real
* activation objects for functions.
*
* @param name the name of the object to add to the list
*/
public void addActivationName(String name) {
if (activationNames == null)
activationNames = new Hashtable(5);
activationNames.put(name, name);
}
/**
* Check whether the name is in the list of names of objects
* forcing the creation of activation objects.
*
* @param name the name of the object to test
*
* @return true if an function activation object is needed.
*/
public boolean isActivationNeeded(String name) {
if ("arguments".equals(name))
return true;
return activationNames != null && activationNames.containsKey(name);
}
/**
* Remove a name from the list of names forcing the creation of real
* activation objects for functions.
*
* @param name the name of the object to remove from the list
*/
public void removeActivationName(String name) {
if (activationNames != null)
activationNames.remove(name);
}
static final boolean check = true;
private static Hashtable threadContexts = new Hashtable(11);
private static Object threadLocalCx;
private static Method threadLocalGet;
private static Method threadLocalSet;
static {
Class cl = Kit.classOrNull("java.lang.ThreadLocal");
if (cl != null) {
try {
threadLocalGet = cl.getMethod("get", null);
threadLocalSet = cl.getMethod("set",
new Class[] { ScriptRuntime.ObjectClass });
threadLocalCx = cl.newInstance();
} catch (Exception ex) { }
}
}
// We'd like to use "Thread.getContextClassLoader", but
// that's only available on Java2.
private static Method method_getContextClassLoader;
static {
// Don't use "Thread.class": that performs the lookup
// in the class initializer, which doesn't allow us to
// catch possible security exceptions.
Class threadClass = Kit.classOrNull("java.lang.Thread");
if (threadClass != null) {
try {
method_getContextClassLoader =
threadClass.getDeclaredMethod("getContextClassLoader",
new Class[0]);
} catch (Exception ex) { }
}
}
private static final Object contextListenersLock = new Object();
private static volatile Object contextListeners;
/**
* The activation of the currently executing function or script.
*/
NativeCall currentActivation;
// for Objects, Arrays to tag themselves as being printed out,
// so they don't print themselves out recursively.
// Use ObjToIntMap instead of java.util.HashSet for JDK 1.1 compatibility
ObjToIntMap iterating;
Object interpreterSecurityDomain;
int version;
private SecurityController securityController;
private ClassShutter classShutter;
private ErrorReporter errorReporter;
private RegExpProxy regExpProxy;
private Locale locale;
private boolean generatingDebug;
private boolean generatingDebugChanged;
private boolean generatingSource=true;
private boolean compileFunctionsWithDynamicScopeFlag;
private int optimizationLevel;
private WrapFactory wrapFactory;
Debugger debugger;
private Object debuggerData;
private int enterCount;
private Object instanceListeners;
private Hashtable hashtable;
private ClassLoader applicationClassLoader;
private boolean hideFromContextListeners;
private boolean creationEventWasSent;
/**
* This is the list of names of objects forcing the creation of
* function activation records.
*/
private Hashtable activationNames;
// For the interpreter to indicate line/source for error reports.
int interpreterLineIndex;
InterpreterData interpreterData;
// For instruction counting (interpreter only)
int instructionCount;
int instructionThreshold;
}
| In getApplicationClassLoader cache result of Thread.getContextClassLoader if it coincides with the loader that loaded Context class.
| src/org/mozilla/javascript/Context.java | In getApplicationClassLoader cache result of Thread.getContextClassLoader if it coincides with the loader that loaded Context class. | <ide><path>rc/org/mozilla/javascript/Context.java
<ide>
<ide> public final ClassLoader getApplicationClassLoader()
<ide> {
<del> if (applicationClassLoader != null) {
<del> return applicationClassLoader;
<del> }
<del> ClassLoader loader = null;
<del> if (method_getContextClassLoader != null) {
<del> Thread thread = Thread.currentThread();
<del> try {
<del> loader = (ClassLoader)method_getContextClassLoader.invoke(
<del> thread, ScriptRuntime.emptyArgs);
<del> } catch (Exception ex) { }
<del> }
<del> if (loader != null && !testIfCanUseLoader(loader)) {
<del> loader = null;
<del> }
<del> if (loader == null) {
<add> if (applicationClassLoader == null) {
<ide> // If Context was subclassed, the following gets the loader
<ide> // for the subclass which can be different from Rhino loader,
<ide> // but then proper Rhino classes should be accessible through it
<ide> // in any case or JVM class loading is severely broken
<del> loader = this.getClass().getClassLoader();
<del> }
<del> // The result is not cached since caching
<del> // Thread.getContextClassLoader prevents it from GC which
<del> // may lead to a memory leak and hides updates to
<del> // Thread.getContextClassLoader
<del> return loader;
<add> Class cxClass = this.getClass();
<add> ClassLoader loader = cxClass.getClassLoader();
<add> if (method_getContextClassLoader != null) {
<add> Thread thread = Thread.currentThread();
<add> ClassLoader threadLoader = null;
<add> try {
<add> threadLoader = (ClassLoader)method_getContextClassLoader.
<add> invoke(thread, ScriptRuntime.emptyArgs);
<add> } catch (Exception ex) { }
<add> if (threadLoader != null && threadLoader != loader) {
<add> if (testIfCanUseLoader(threadLoader, cxClass)) {
<add> // Thread.getContextClassLoader is not cached since
<add> // its caching prevents it from GC which may lead to
<add> // a memory leak and hides updates to
<add> // Thread.getContextClassLoader
<add> return threadLoader;
<add> }
<add> }
<add> }
<add> applicationClassLoader = loader;
<add> }
<add> return applicationClassLoader;
<ide> }
<ide>
<ide> public void setApplicationClassLoader(ClassLoader loader)
<ide> applicationClassLoader = null;
<ide> return;
<ide> }
<del> if (!testIfCanUseLoader(loader)) {
<add> if (!testIfCanUseLoader(loader, this.getClass())) {
<ide> throw new IllegalArgumentException(
<ide> "Loader can not resolve Rhino classes");
<ide> }
<ide> applicationClassLoader = loader;
<ide> }
<ide>
<del> private boolean testIfCanUseLoader(ClassLoader loader)
<del> {
<del> // If Context was subclussed, cxClass != Context.class
<del> Class cxClass = this.getClass();
<add> private static boolean testIfCanUseLoader(ClassLoader loader, Class cxClass)
<add> {
<ide> // Check that Context or its suclass is accesible from this loader
<ide> Class x = Kit.classOrNull(loader, cxClass.getName());
<ide> if (x != cxClass) {
<ide> // The check covers the case when x == null =>
<del> // threadLoader does not know about Rhino or the case
<add> // loader does not know about Rhino or the case
<ide> // when x != null && x != cxClass =>
<del> // threadLoader loads unrelated Rhino instance
<add> // loader loads unrelated Rhino instance
<ide> return false;
<ide> }
<ide> return true; |
|
Java | apache-2.0 | b92ccb2d9ecf35d35a2a338d521064277abd7368 | 0 | supriyantomaftuh/java-client-api,supriyantomaftuh/java-client-api,marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api,omkarudipi/java-client-api,omkarudipi/java-client-api,grechaw/java-client-api,marklogic/java-client-api,supriyantomaftuh/java-client-api,supriyantomaftuh/java-client-api,omkarudipi/java-client-api,marklogic/java-client-api,omkarudipi/java-client-api,grechaw/java-client-api | package com.marklogic.client.io;
import com.marklogic.client.DocumentIdentifier;
import com.marklogic.client.Format;
import com.marklogic.client.MarkLogicIOException;
import com.marklogic.client.config.FacetHeatmapValue;
import com.marklogic.client.config.FacetResult;
import com.marklogic.client.config.FacetValue;
import com.marklogic.client.config.MatchDocumentSummary;
import com.marklogic.client.config.MatchLocation;
import com.marklogic.client.config.MatchSnippet;
import com.marklogic.client.config.QueryDefinition;
import com.marklogic.client.config.SearchMetrics;
import com.marklogic.client.config.SearchResults;
import com.marklogic.client.config.search.jaxb.Facet;
import com.marklogic.client.config.search.jaxb.Match;
import com.marklogic.client.config.search.jaxb.Metrics;
import com.marklogic.client.config.search.jaxb.Response;
import com.marklogic.client.config.search.jaxb.Result;
import com.marklogic.client.config.search.jaxb.Snippet;
import com.marklogic.client.io.marker.SearchReadHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Vector;
/**
* Created by IntelliJ IDEA.
* User: ndw
* Date: 3/20/12
* Time: 10:41 AM
* To change this template use File | Settings | File Templates.
*/
public class SearchHandle implements SearchReadHandle<InputStream>, SearchResults {
static final private Logger logger = LoggerFactory.getLogger(DOMHandle.class);
protected JAXBContext jc = null;
protected Unmarshaller unmarshaller = null;
protected Marshaller m = null;
private Response jaxbResponse = null;
private QueryDefinition querydef = null;
SearchMetrics metrics = null;
MatchDocumentSummary[] summary = null;
FacetResult[] facets = null;
String[] facetNames = null;
@Override
public Format getFormat() {
return Format.XML;
}
@Override
public void setFormat(Format format) {
if (format != Format.XML)
new IllegalArgumentException("SearchHandle supports the XML format only");
}
public SearchHandle withFormat(Format format) {
setFormat(format);
return this;
}
@Override
public Class<InputStream> receiveAs() {
return InputStream.class;
}
@Override
public void receiveContent(InputStream content) {
try {
jc = JAXBContext.newInstance("com.marklogic.client.config.search.jaxb");
unmarshaller = jc.createUnmarshaller();
m = jc.createMarshaller();
jaxbResponse = (Response) unmarshaller.unmarshal(content);
} catch (JAXBException e) {
throw new MarkLogicIOException(
"Could not construct search results because of thrown JAXB Exception",
e);
}
}
/** Sets the query definition used in the search.
*
* Calling this method always deletes any cached search results.
*
* @param querydef The new QueryDefinition
*/
public void setQueryCriteria(QueryDefinition querydef) {
this.querydef = querydef;
jaxbResponse = null;
metrics = null;
summary = null;
facets = null;
facetNames = null;
}
@Override
public QueryDefinition getQueryCriteria() {
return querydef;
}
@Override
public long getTotalResults() {
if (jaxbResponse == null) {
return -1;
} else {
return jaxbResponse.getTotal();
}
}
@Override
public SearchMetrics getMetrics() {
if (jaxbResponse == null || metrics != null) {
return metrics;
}
Date now = new Date();
Metrics jaxbMetrics = jaxbResponse.getMetrics();
long qrTime = jaxbMetrics.getQueryResolutionTime() == null ? -1 : jaxbMetrics.getQueryResolutionTime().getTimeInMillis(now);
long frTime = jaxbMetrics.getFacetResolutionTime() == null ? -1 : jaxbMetrics.getFacetResolutionTime().getTimeInMillis(now);
long srTime = jaxbMetrics.getSnippetResolutionTime() == null ? - 1: jaxbMetrics.getSnippetResolutionTime().getTimeInMillis(now);
long totalTime = jaxbMetrics.getTotalTime() == null ? -1 : jaxbMetrics.getTotalTime().getTimeInMillis(now);
metrics = new SearchMetricsImpl(qrTime, frTime, srTime, totalTime);
return metrics;
}
@Override
public MatchDocumentSummary[] getMatchResults() {
if (jaxbResponse == null || summary != null) {
return summary;
}
List<Result> results = jaxbResponse.getResult();
summary = new MatchDocumentSummary[results.size()];
int idx = 0;
for (Result result : results) {
String uri = result.getUri();
int score = result.getScore().intValue();
double conf = result.getConfidence();
double fit = result.getFitness();
String path = result.getPath();
summary[idx] = new MatchDocumentSummaryImpl(uri, score, conf, fit, path, result);
idx++;
}
return summary;
}
@Override
public FacetResult[] getFacetResults() {
if (jaxbResponse == null || facets != null) {
return facets;
}
List<JAXBElement<?>> jfacets = jaxbResponse.getResponseFacet();
facets = new FacetResult[jfacets.size()];
int pos = 0;
for (JAXBElement<?> jfacet : jfacets) {
facets[pos++] = new FacetResultImpl(jfacet);
}
return facets;
}
@Override
public FacetResult getFacetResult(String name) {
getFacetResults();
if (facets != null) {
for (FacetResult facet : facets) {
if (facet.getName().equals(name)) {
return facet;
}
}
}
return null;
}
@Override
public String[] getFacetNames() {
getFacetResults();
return facetNames;
}
private class SearchMetricsImpl implements SearchMetrics {
long qrTime = -1;
long frTime = -1;
long srTime = -1;
long totalTime = -1;
public SearchMetricsImpl(long qrTime, long frTime, long srTime, long totalTime) {
this.qrTime = qrTime;
this.frTime = frTime;
this.srTime = srTime;
this.totalTime = totalTime;
}
@Override
public long getQueryResolutionTime() {
return qrTime;
}
@Override
public long getFacetResolutionTime() {
return frTime;
}
@Override
public long getSnippetResolutionTime() {
return srTime;
}
@Override
public long getTotalTime() {
return totalTime;
}
}
private class MatchDocumentSummaryImpl implements MatchDocumentSummary {
private String uri = null;
private int score = -1;
private double conf = -1;
private double fit = -1;
private String path = null;
private Result result = null;
private MatchLocation[] locations = null;
private String mimetype = null;
private long byteLength = 0;
public MatchDocumentSummaryImpl(String uri, int score, double confidence, double fitness, String path, Result result) {
this.uri = uri;
this.score = score;
conf = confidence;
fit = fitness;
this.path = path;
this.result = result;
}
@Override
public String getUri() {
return uri;
}
@Override
public int getScore() {
return score;
}
@Override
public double getConfidence() {
return conf;
}
@Override
public double getFitness() {
return fit;
}
@Override
public String getPath() {
return path;
}
@Override
public MatchLocation[] getMatchLocations() {
if (locations != null) {
return locations;
}
List<Snippet> jaxbSnippets = result.getSnippet();
// FIXME: ? The total number of snippet matches across all the snippets
// is variable. So we just build them dynamically.
Vector<MatchLocation> locVector = new Vector<MatchLocation>();
for (Snippet snippet : jaxbSnippets) {
for (Object jaxbMatch : snippet.getMatchOrAnyOrAny()) {
if (jaxbMatch instanceof Match) {
Match match = (Match) jaxbMatch;
String path = match.getPath();
locVector.add(new MatchLocationImpl(path, match));
} else {
throw new UnsupportedOperationException("Cannot parse customized snippets");
}
}
}
locations = new MatchLocation[0];
locations = locVector.toArray(locations);
return locations;
}
@Override
public void setUri(String uri) {
throw new UnsupportedOperationException("Cannot set URI on MatchDocumentSummar");
}
@Override
public DocumentIdentifier withUri(String uri) {
if (uri != null && uri.equals(this.uri)) {
return this;
} else {
throw new UnsupportedOperationException("Cannot set URI on MatchDocumentSummar");
}
}
@Override
public String getMimetype() {
return mimetype;
}
@Override
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
}
@Override
public DocumentIdentifier withMimetype(String mimetype) {
setMimetype(mimetype);
return this;
}
@Override
public long getByteLength() {
return byteLength;
}
@Override
public void setByteLength(long length) {
byteLength = length;
}
}
public class MatchLocationImpl implements MatchLocation {
private String path = null;
private MatchSnippet[] snippets = null;
private Match jaxbMatch = null;
public MatchLocationImpl(String path, Match match) {
this.path = path;
jaxbMatch = match;
}
@Override
public String getPath() {
return path;
}
@Override
public String getAllSnippetText() {
getSnippets();
String text = "";
for (MatchSnippet snippet : snippets) {
text += snippet.getText();
}
return text;
}
@Override
public MatchSnippet[] getSnippets() {
List<Serializable> jaxbContent = jaxbMatch.getContent();
snippets = new MatchSnippet[jaxbContent.size()];
int idx = 0;
for (Object content : jaxbContent) {
if (content instanceof String) {
snippets[idx] = new MatchSnippetImpl(false, (String) content);
} else {
snippets[idx] = new MatchSnippetImpl(true, (String) ((JAXBElement) content).getValue());
}
idx++;
}
return snippets;
}
}
private class MatchSnippetImpl implements MatchSnippet {
private boolean high = false;
private String text = null;
public MatchSnippetImpl(boolean high, String text) {
this.high = high;
this.text = text;
}
@Override
public boolean isHighlighted() {
return high;
}
@Override
public String getText() {
return text;
}
}
public class FacetResultImpl implements FacetResult {
private String name = null;
private FacetValue[] values = null;
public FacetResultImpl(JAXBElement jelem) {
if (jelem.getDeclaredType() == com.marklogic.client.config.search.jaxb.Facet.class) {
com.marklogic.client.config.search.jaxb.Facet jfacet
= (com.marklogic.client.config.search.jaxb.Facet) jelem.getValue();
name = jfacet.getName();
List<com.marklogic.client.config.search.jaxb.FacetValue> jvalues = jfacet.getFacetValue();
values = new FacetValue[jvalues.size()];
int pos = 0;
for (com.marklogic.client.config.search.jaxb.FacetValue jvalue : jvalues) {
values[pos++] = new FacetValueImpl(jvalue);
}
} else if (jelem.getDeclaredType() == com.marklogic.client.config.search.jaxb.Boxes.class) {
com.marklogic.client.config.search.jaxb.Boxes jfacet
= (com.marklogic.client.config.search.jaxb.Boxes) jelem.getValue();
name = jfacet.getName();
List<com.marklogic.client.config.search.jaxb.Box> jvalues = jfacet.getBox();
values = new FacetValue[jvalues.size()];
int pos = 0;
for (com.marklogic.client.config.search.jaxb.Box jvalue : jvalues) {
values[pos++] = new FacetHeatmapValueImpl(jvalue);
}
} else {
throw new UnsupportedOperationException("Unexpected facet value: facet or boxes expected.");
}
}
@Override
public String getName() {
return name;
}
@Override
public FacetValue[] getFacetValues() {
return values;
}
}
public class FacetValueImpl implements FacetValue {
private String name = null;
private long count = 0;
private String label = null;
public FacetValueImpl(com.marklogic.client.config.search.jaxb.FacetValue jvalue) {
name = jvalue.getName();
count = jvalue.getCount();
//FIXME: this isn't right
label = name;
}
@Override
public String getName() {
return name;
}
@Override
public long getCount() {
return count;
}
@Override
public String getLabel() {
return label;
}
}
public class FacetHeatmapValueImpl implements FacetHeatmapValue {
private String name = null;
private long count = 0;
private String label = null;
private double[] box = null;
public FacetHeatmapValueImpl(com.marklogic.client.config.search.jaxb.Box jvalue) {
box = new double[4];
box[0] = jvalue.getS();
box[1] = jvalue.getW();
box[2] = jvalue.getN();
box[3] = jvalue.getE();
name = "[" + box[0] + ", " + box[1]+ ", " + box[2] + ", " + box[3] + "]";
count = jvalue.getCount();
label = name;
}
@Override
public String getName() {
return name;
}
@Override
public long getCount() {
return count;
}
@Override
public String getLabel() {
return label;
}
@Override
public double[] getBox() {
return box;
}
}
}
| src/main/java/com/marklogic/client/io/SearchHandle.java | package com.marklogic.client.io;
import com.marklogic.client.DocumentIdentifier;
import com.marklogic.client.Format;
import com.marklogic.client.MarkLogicIOException;
import com.marklogic.client.config.FacetHeatmapValue;
import com.marklogic.client.config.FacetResult;
import com.marklogic.client.config.FacetValue;
import com.marklogic.client.config.MatchDocumentSummary;
import com.marklogic.client.config.MatchLocation;
import com.marklogic.client.config.MatchSnippet;
import com.marklogic.client.config.QueryDefinition;
import com.marklogic.client.config.SearchMetrics;
import com.marklogic.client.config.SearchResults;
import com.marklogic.client.config.search.jaxb.Facet;
import com.marklogic.client.config.search.jaxb.Match;
import com.marklogic.client.config.search.jaxb.Metrics;
import com.marklogic.client.config.search.jaxb.Response;
import com.marklogic.client.config.search.jaxb.Result;
import com.marklogic.client.config.search.jaxb.Snippet;
import com.marklogic.client.io.marker.SearchReadHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Vector;
/**
* Created by IntelliJ IDEA.
* User: ndw
* Date: 3/20/12
* Time: 10:41 AM
* To change this template use File | Settings | File Templates.
*/
public class SearchHandle implements SearchReadHandle<InputStream>, SearchResults {
static final private Logger logger = LoggerFactory.getLogger(DOMHandle.class);
protected JAXBContext jc = null;
protected Unmarshaller unmarshaller = null;
protected Marshaller m = null;
private Response jaxbResponse = null;
private QueryDefinition querydef = null;
SearchMetrics metrics = null;
MatchDocumentSummary[] summary = null;
FacetResult[] facets = null;
String[] facetNames = null;
@Override
public Format getFormat() {
return Format.XML;
}
@Override
public void setFormat(Format format) {
if (format != Format.XML)
new IllegalArgumentException("SearchHandle supports the XML format only");
}
public SearchHandle withFormat(Format format) {
setFormat(format);
return this;
}
@Override
public Class<InputStream> receiveAs() {
return InputStream.class;
}
@Override
public void receiveContent(InputStream content) {
try {
jc = JAXBContext.newInstance("com.marklogic.client.config.search.jaxb");
unmarshaller = jc.createUnmarshaller();
m = jc.createMarshaller();
jaxbResponse = (Response) unmarshaller.unmarshal(content);
} catch (JAXBException e) {
throw new MarkLogicIOException(
"Could not construct search results because of thrown JAXB Exception",
e);
}
}
/** Sets the query definition used in the search.
*
* Calling this method always deletes any cached search results.
*
* @param querydef The new QueryDefinition
*/
public void setQueryCriteria(QueryDefinition querydef) {
this.querydef = querydef;
jaxbResponse = null;
metrics = null;
summary = null;
facets = null;
facetNames = null;
}
@Override
public QueryDefinition getQueryCriteria() {
return querydef;
}
@Override
public long getTotalResults() {
if (jaxbResponse == null) {
return -1;
} else {
return jaxbResponse.getTotal();
}
}
@Override
public SearchMetrics getMetrics() {
if (jaxbResponse == null || metrics != null) {
return metrics;
}
Date now = new Date();
Metrics jaxbMetrics = jaxbResponse.getMetrics();
long qrTime = jaxbMetrics.getQueryResolutionTime() == null ? -1 : jaxbMetrics.getQueryResolutionTime().getTimeInMillis(now);
long frTime = jaxbMetrics.getFacetResolutionTime() == null ? -1 : jaxbMetrics.getFacetResolutionTime().getTimeInMillis(now);
long srTime = jaxbMetrics.getSnippetResolutionTime() == null ? - 1: jaxbMetrics.getSnippetResolutionTime().getTimeInMillis(now);
long totalTime = jaxbMetrics.getTotalTime() == null ? -1 : jaxbMetrics.getTotalTime().getTimeInMillis(now);
metrics = new SearchMetricsImpl(qrTime, frTime, srTime, totalTime);
return metrics;
}
@Override
public MatchDocumentSummary[] getMatchResults() {
if (jaxbResponse == null || summary != null) {
return summary;
}
List<Result> results = jaxbResponse.getResult();
summary = new MatchDocumentSummary[results.size()];
int idx = 0;
for (Result result : results) {
String uri = result.getUri();
int score = result.getScore().intValue();
double conf = result.getConfidence();
double fit = result.getFitness();
String path = result.getPath();
summary[idx] = new MatchDocumentSummaryImpl(uri, score, conf, fit, path, result);
idx++;
}
return summary;
}
@Override
public FacetResult[] getFacetResults() {
if (jaxbResponse == null || facets != null) {
return facets;
}
List<JAXBElement<?>> jfacets = jaxbResponse.getResponseFacet();
facets = new FacetResult[jfacets.size()];
int pos = 0;
for (JAXBElement<?> jfacet : jfacets) {
facets[pos++] = new FacetResultImpl(jfacet);
}
return facets;
}
@Override
public FacetResult getFacetResult(String name) {
getFacetResults();
if (facets != null) {
for (FacetResult facet : facets) {
if (facet.getName().equals(name)) {
return facet;
}
}
}
return null;
}
@Override
public String[] getFacetNames() {
getFacetResults();
return facetNames;
}
private class SearchMetricsImpl implements SearchMetrics {
long qrTime = -1;
long frTime = -1;
long srTime = -1;
long totalTime = -1;
public SearchMetricsImpl(long qrTime, long frTime, long srTime, long totalTime) {
this.qrTime = qrTime;
this.frTime = frTime;
this.srTime = srTime;
this.totalTime = totalTime;
}
@Override
public long getQueryResolutionTime() {
return qrTime;
}
@Override
public long getFacetResolutionTime() {
return frTime;
}
@Override
public long getSnippetResolutionTime() {
return srTime;
}
@Override
public long getTotalTime() {
return totalTime;
}
}
private class MatchDocumentSummaryImpl implements MatchDocumentSummary {
private String uri = null;
private int score = -1;
private double conf = -1;
private double fit = -1;
private String path = null;
private Result result = null;
private MatchLocation[] locations = null;
private String mimetype = null;
private long byteLength = 0;
public MatchDocumentSummaryImpl(String uri, int score, double confidence, double fitness, String path, Result result) {
this.uri = uri;
this.score = score;
conf = confidence;
fit = fitness;
this.path = path;
this.result = result;
}
@Override
public String getUri() {
return uri;
}
@Override
public int getScore() {
return score;
}
@Override
public double getConfidence() {
return conf;
}
@Override
public double getFitness() {
return fit;
}
@Override
public String getPath() {
return path;
}
@Override
public MatchLocation[] getMatchLocations() {
if (locations != null) {
return locations;
}
List<Snippet> jaxbSnippets = result.getSnippet();
locations = new MatchLocation[jaxbSnippets.size()];
int idx = 0;
for (Snippet snippet : jaxbSnippets) {
for (Object jaxbMatch : snippet.getMatchOrAnyOrAny()) {
if (jaxbMatch instanceof Match) {
Match match = (Match) jaxbMatch;
String path = match.getPath();
locations[idx] = new MatchLocationImpl(path, match);
idx++;
} else {
throw new UnsupportedOperationException("Cannot parse customized snippets");
}
}
}
return locations;
}
@Override
public void setUri(String uri) {
throw new UnsupportedOperationException("Cannot set URI on MatchDocumentSummar");
}
@Override
public DocumentIdentifier withUri(String uri) {
if (uri != null && uri.equals(this.uri)) {
return this;
} else {
throw new UnsupportedOperationException("Cannot set URI on MatchDocumentSummar");
}
}
@Override
public String getMimetype() {
return mimetype;
}
@Override
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
}
@Override
public DocumentIdentifier withMimetype(String mimetype) {
setMimetype(mimetype);
return this;
}
@Override
public long getByteLength() {
return byteLength;
}
@Override
public void setByteLength(long length) {
byteLength = length;
}
}
public class MatchLocationImpl implements MatchLocation {
private String path = null;
private MatchSnippet[] snippets = null;
private Match jaxbMatch = null;
public MatchLocationImpl(String path, Match match) {
this.path = path;
jaxbMatch = match;
}
@Override
public String getPath() {
return path;
}
@Override
public String getAllSnippetText() {
getSnippets();
String text = "";
for (MatchSnippet snippet : snippets) {
text += snippet.getText();
}
return text;
}
@Override
public MatchSnippet[] getSnippets() {
List<Serializable> jaxbContent = jaxbMatch.getContent();
snippets = new MatchSnippet[jaxbContent.size()];
int idx = 0;
for (Object content : jaxbContent) {
if (content instanceof String) {
snippets[idx] = new MatchSnippetImpl(false, (String) content);
} else {
snippets[idx] = new MatchSnippetImpl(true, (String) ((JAXBElement) content).getValue());
}
idx++;
}
return snippets;
}
}
private class MatchSnippetImpl implements MatchSnippet {
private boolean high = false;
private String text = null;
public MatchSnippetImpl(boolean high, String text) {
this.high = high;
this.text = text;
}
@Override
public boolean isHighlighted() {
return high;
}
@Override
public String getText() {
return text;
}
}
public class FacetResultImpl implements FacetResult {
private String name = null;
private FacetValue[] values = null;
public FacetResultImpl(JAXBElement jelem) {
if (jelem.getDeclaredType() == com.marklogic.client.config.search.jaxb.Facet.class) {
com.marklogic.client.config.search.jaxb.Facet jfacet
= (com.marklogic.client.config.search.jaxb.Facet) jelem.getValue();
name = jfacet.getName();
List<com.marklogic.client.config.search.jaxb.FacetValue> jvalues = jfacet.getFacetValue();
values = new FacetValue[jvalues.size()];
int pos = 0;
for (com.marklogic.client.config.search.jaxb.FacetValue jvalue : jvalues) {
values[pos++] = new FacetValueImpl(jvalue);
}
} else if (jelem.getDeclaredType() == com.marklogic.client.config.search.jaxb.Boxes.class) {
com.marklogic.client.config.search.jaxb.Boxes jfacet
= (com.marklogic.client.config.search.jaxb.Boxes) jelem.getValue();
name = jfacet.getName();
List<com.marklogic.client.config.search.jaxb.Box> jvalues = jfacet.getBox();
values = new FacetValue[jvalues.size()];
int pos = 0;
for (com.marklogic.client.config.search.jaxb.Box jvalue : jvalues) {
values[pos++] = new FacetHeatmapValueImpl(jvalue);
}
} else {
throw new UnsupportedOperationException("Unexpected facet value: facet or boxes expected.");
}
}
@Override
public String getName() {
return name;
}
@Override
public FacetValue[] getFacetValues() {
return values;
}
}
public class FacetValueImpl implements FacetValue {
private String name = null;
private long count = 0;
private String label = null;
public FacetValueImpl(com.marklogic.client.config.search.jaxb.FacetValue jvalue) {
name = jvalue.getName();
count = jvalue.getCount();
//FIXME: this isn't right
label = name;
}
@Override
public String getName() {
return name;
}
@Override
public long getCount() {
return count;
}
@Override
public String getLabel() {
return label;
}
}
public class FacetHeatmapValueImpl implements FacetHeatmapValue {
private String name = null;
private long count = 0;
private String label = null;
private double[] box = null;
public FacetHeatmapValueImpl(com.marklogic.client.config.search.jaxb.Box jvalue) {
box = new double[4];
box[0] = jvalue.getS();
box[1] = jvalue.getW();
box[2] = jvalue.getN();
box[3] = jvalue.getE();
name = "[" + box[0] + ", " + box[1]+ ", " + box[2] + ", " + box[3] + "]";
count = jvalue.getCount();
label = name;
}
@Override
public String getName() {
return name;
}
@Override
public long getCount() {
return count;
}
@Override
public String getLabel() {
return label;
}
@Override
public double[] getBox() {
return box;
}
}
}
| Fixed bug 16716, build snippets dynamically to avoid having to precompute how many there are
git-svn-id: 2087087167f935058d19856144d26af79f295c86@100710 62cac252-8da6-4816-9e9d-6dc37b19578c
| src/main/java/com/marklogic/client/io/SearchHandle.java | Fixed bug 16716, build snippets dynamically to avoid having to precompute how many there are | <ide><path>rc/main/java/com/marklogic/client/io/SearchHandle.java
<ide> }
<ide>
<ide> List<Snippet> jaxbSnippets = result.getSnippet();
<del> locations = new MatchLocation[jaxbSnippets.size()];
<del> int idx = 0;
<add>
<add> // FIXME: ? The total number of snippet matches across all the snippets
<add> // is variable. So we just build them dynamically.
<add> Vector<MatchLocation> locVector = new Vector<MatchLocation>();
<ide> for (Snippet snippet : jaxbSnippets) {
<ide> for (Object jaxbMatch : snippet.getMatchOrAnyOrAny()) {
<ide> if (jaxbMatch instanceof Match) {
<ide> Match match = (Match) jaxbMatch;
<ide> String path = match.getPath();
<del> locations[idx] = new MatchLocationImpl(path, match);
<del> idx++;
<add> locVector.add(new MatchLocationImpl(path, match));
<ide> } else {
<ide> throw new UnsupportedOperationException("Cannot parse customized snippets");
<ide> }
<ide> }
<ide> }
<ide>
<add> locations = new MatchLocation[0];
<add> locations = locVector.toArray(locations);
<ide> return locations;
<ide> }
<ide> |
|
JavaScript | apache-2.0 | 1b1c446bd8c4ecddd675c702bd36d7198631acb5 | 0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | /**
* Analytics Stories.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import { storiesOf } from '@storybook/react';
/**
* WordPress dependencies
*/
import { doAction } from '@wordpress/hooks';
import { __, _x } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import Layout from '../assets/js/components/layout/Layout';
import LegacyAnalyticsDashboardWidgetOverview from '../assets/js/modules/analytics/components/dashboard/LegacyAnalyticsDashboardWidgetOverview';
import LegacyAnalyticsDashboardWidgetSiteStats from '../assets/js/modules/analytics/components/dashboard/LegacyAnalyticsDashboardWidgetSiteStats';
import LegacyDashboardAcquisitionPieChart from '../assets/js/modules/analytics/components/dashboard/LegacyDashboardAcquisitionPieChart';
import LegacyAnalyticsDashboardWidgetTopAcquisitionSources from '../assets/js/modules/analytics/components/dashboard/LegacyAnalyticsDashboardWidgetTopAcquisitionSources';
import { googlesitekit as analyticsData } from '../.storybook/data/wp-admin-admin.php-page=googlesitekit-module-analytics-googlesitekit';
import {
AccountSelect,
PropertySelect,
PropertySelectIncludingGA4,
ProfileSelect,
AnonymizeIPSwitch,
UseSnippetSwitch,
TrackingExclusionSwitches,
GA4Notice,
} from '../assets/js/modules/analytics/components/common';
import { WithTestRegistry } from '../tests/js/utils';
import * as fixtures from '../assets/js/modules/analytics/datastore/__fixtures__';
import { properties as propertiesGA4 } from '../assets/js/modules/analytics-4/datastore/__fixtures__';
import { STORE_NAME } from '../assets/js/modules/analytics/datastore/constants';
import { MODULES_ANALYTICS_4 } from '../assets/js/modules/analytics-4/datastore/constants';
import { enabledFeatures } from '../assets/js/features';
function SetupWrap( { children } ) {
return (
<div className="googlesitekit-setup">
<section className="googlesitekit-setup__wrapper">
<div className="googlesitekit-setup-module">
{ children }
</div>
</section>
</div>
);
}
storiesOf( 'Analytics Module', module )
.add( 'Account Property Profile Select (none selected)', () => {
const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).receiveGetSettings( {} );
dispatch( STORE_NAME ).receiveGetAccounts( accounts );
// eslint-disable-next-line sitekit/acronym-case
dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
// eslint-disable-next-line sitekit/acronym-case
accountID: properties[ 0 ].accountId,
// eslint-disable-next-line sitekit/acronym-case
propertyID: profiles[ 0 ].webPropertyId,
} );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<div className="googlesitekit-setup-module__inputs">
<AccountSelect />
<PropertySelect />
<ProfileSelect />
</div>
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Account Property Profile Select (all selected)', () => {
const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).receiveGetAccounts( accounts );
// eslint-disable-next-line sitekit/acronym-case
dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
// eslint-disable-next-line sitekit/acronym-case
accountID: properties[ 0 ].accountId,
// eslint-disable-next-line sitekit/acronym-case
propertyID: profiles[ 0 ].webPropertyId,
} );
dispatch( STORE_NAME ).receiveGetSettings( {
// eslint-disable-next-line sitekit/acronym-case
accountID: profiles[ 0 ].accountId,
// eslint-disable-next-line sitekit/acronym-case
propertyID: profiles[ 0 ].webPropertyId,
// eslint-disable-next-line sitekit/acronym-case
internalWebPropertyID: profiles[ 0 ].internalWebPropertyId,
profileID: profiles[ 0 ].id,
} );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<div className="googlesitekit-setup-module__inputs">
<AccountSelect />
<PropertySelect />
<ProfileSelect />
</div>
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Property Select including GA4 properties', () => {
// Have to import like with tests
enabledFeatures.add( 'ga4setup' );
const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
/* eslint-disable sitekit/acronym-case */
const accountID = properties[ 0 ].accountId;
const propertyID = profiles[ 0 ].webPropertyId;
/* eslint-enable */
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).receiveGetAccounts( accounts );
dispatch( STORE_NAME ).finishResolution( 'getAccounts', [] );
// eslint-disable-next-line sitekit/acronym-case
dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
// I believe we don't need profiles for this story, do we? Let's get rid of it if we don't need it
dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
accountID,
propertyID,
} );
dispatch( STORE_NAME ).receiveGetSettings( {
accountID,
} );
dispatch( MODULES_ANALYTICS_4 ).receiveGetProperties(
propertiesGA4,
{ accountID }
);
};
return (
<WithTestRegistry
callback={ setupRegistry }
// This does not work
features={ [ 'ga4setup' ] }
>
<SetupWrap>
<h1>fooooz</h1>
<div className="googlesitekit-setup-module__inputs">
<PropertySelectIncludingGA4 />
</div>
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Anonymize IP switch, toggled on', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setUseSnippet( true );
dispatch( STORE_NAME ).setAnonymizeIP( true );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<AnonymizeIPSwitch />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Anonymize IP switch, toggled off', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setUseSnippet( true );
dispatch( STORE_NAME ).setAnonymizeIP( false );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<AnonymizeIPSwitch />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Use Snippet switch, toggled on (default)', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setUseSnippet( true );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<UseSnippetSwitch />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Use Snippet switch, toggled off', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setUseSnippet( false );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<UseSnippetSwitch />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Tracking exclusions (default)', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setTrackingDisabled( [ 'loggedinUsers' ] );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<TrackingExclusionSwitches />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Tracking exclusions (including loggedinUsers)', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setTrackingDisabled( [] );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<TrackingExclusionSwitches />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Tracking exclusions (including contentCreators)', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setTrackingDisabled( [ 'contentCreators' ] );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<TrackingExclusionSwitches />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'GA4 notice', () => {
return (
<SetupWrap>
<GA4Notice />
</SetupWrap>
);
} )
.add( 'Audience Overview Chart', () => {
global._googlesitekitLegacyData = analyticsData;
const selectedStats = [
0,
];
const series = {
0: {
color: '#4285f4',
targetAxisIndex: 0,
},
1: {
color: '#4285f4',
targetAxisIndex: 0,
lineDashStyle: [
3,
3,
],
lineWidth: 1,
},
};
const vAxes = null;
// Load the datacache with data.
setTimeout( () => {
doAction(
'googlesitekit.moduleLoaded',
'Single'
);
}, 250 );
return (
<WithTestRegistry>
<Layout
header
title={ __( 'Audience overview for the last 28 days', 'google-site-kit' ) }
headerCTALabel={ __( 'See full stats in Analytics', 'google-site-kit' ) }
headerCTALink="http://analytics.google.com"
>
<LegacyAnalyticsDashboardWidgetOverview
selectedStats={ selectedStats }
handleDataError={ () => {} }
/>
<LegacyAnalyticsDashboardWidgetSiteStats
selectedStats={ selectedStats }
series={ series }
vAxes={ vAxes }
/>
</Layout>
</WithTestRegistry>
);
},
// This uses the legacy widget, the new one is in:
// 'Analytics Module/Components/Module Page/Acquisition Channels Widget'.
{ options: { readySelector: '.googlesitekit-chart .googlesitekit-chart__inner' } } )
.add( 'Top Acquisition Pie Chart', () => {
global._googlesitekitLegacyData = analyticsData;
// Load the datacache with data.
setTimeout( () => {
doAction(
'googlesitekit.moduleLoaded',
'Single'
);
}, 250 );
return (
<WithTestRegistry>
<Layout
header
footer
title={ __( 'Top acquisition channels over the last 28 days', 'google-site-kit' ) }
headerCTALink="https://analytics.google.com"
headerCTALabel={ __( 'See full stats in Analytics', 'google-site-kit' ) }
footerCTALabel={ _x( 'Analytics', 'Service name', 'google-site-kit' ) }
footerCTALink="https://analytics.google.com"
>
<div className="mdc-layout-grid">
<div className="mdc-layout-grid__inner">
<div className="
mdc-layout-grid__cell
mdc-layout-grid__cell--span-4-desktop
mdc-layout-grid__cell--span-8-tablet
mdc-layout-grid__cell--span-4-phone
">
<LegacyDashboardAcquisitionPieChart />
</div>
<div className="
mdc-layout-grid__cell
mdc-layout-grid__cell--span-8-desktop
mdc-layout-grid__cell--span-8-tablet
mdc-layout-grid__cell--span-4-phone
">
<LegacyAnalyticsDashboardWidgetTopAcquisitionSources />
</div>
</div>
</div>
</Layout>
</WithTestRegistry>
);
},
{ options: { readySelector: '.googlesitekit-chart .googlesitekit-chart__inner' } } );
| stories/module-analytics.stories.js | /**
* Analytics Stories.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import { storiesOf } from '@storybook/react';
/**
* WordPress dependencies
*/
import { doAction } from '@wordpress/hooks';
import { __, _x } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import Layout from '../assets/js/components/layout/Layout';
import LegacyAnalyticsDashboardWidgetOverview from '../assets/js/modules/analytics/components/dashboard/LegacyAnalyticsDashboardWidgetOverview';
import LegacyAnalyticsDashboardWidgetSiteStats from '../assets/js/modules/analytics/components/dashboard/LegacyAnalyticsDashboardWidgetSiteStats';
import LegacyDashboardAcquisitionPieChart from '../assets/js/modules/analytics/components/dashboard/LegacyDashboardAcquisitionPieChart';
import LegacyAnalyticsDashboardWidgetTopAcquisitionSources from '../assets/js/modules/analytics/components/dashboard/LegacyAnalyticsDashboardWidgetTopAcquisitionSources';
import { googlesitekit as analyticsData } from '../.storybook/data/wp-admin-admin.php-page=googlesitekit-module-analytics-googlesitekit';
import {
AccountSelect,
PropertySelect,
PropertySelectIncludingGA4,
ProfileSelect,
AnonymizeIPSwitch,
UseSnippetSwitch,
TrackingExclusionSwitches,
GA4Notice,
} from '../assets/js/modules/analytics/components/common';
import { WithTestRegistry } from '../tests/js/utils';
import * as fixtures from '../assets/js/modules/analytics/datastore/__fixtures__';
import { properties as propertiesGA4 } from '../assets/js/modules/analytics-4/datastore/__fixtures__';
import { STORE_NAME } from '../assets/js/modules/analytics/datastore/constants';
import { MODULES_ANALYTICS_4 } from '../assets/js/modules/analytics-4/datastore/constants';
function SetupWrap( { children } ) {
return (
<div className="googlesitekit-setup">
<section className="googlesitekit-setup__wrapper">
<div className="googlesitekit-setup-module">
{ children }
</div>
</section>
</div>
);
}
storiesOf( 'Analytics Module', module )
.add( 'Account Property Profile Select (none selected)', () => {
const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).receiveGetSettings( {} );
dispatch( STORE_NAME ).receiveGetAccounts( accounts );
// eslint-disable-next-line sitekit/acronym-case
dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
// eslint-disable-next-line sitekit/acronym-case
accountID: properties[ 0 ].accountId,
// eslint-disable-next-line sitekit/acronym-case
propertyID: profiles[ 0 ].webPropertyId,
} );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<div className="googlesitekit-setup-module__inputs">
<AccountSelect />
<PropertySelect />
<ProfileSelect />
</div>
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Account Property Profile Select (all selected)', () => {
const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).receiveGetAccounts( accounts );
// eslint-disable-next-line sitekit/acronym-case
dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
// eslint-disable-next-line sitekit/acronym-case
accountID: properties[ 0 ].accountId,
// eslint-disable-next-line sitekit/acronym-case
propertyID: profiles[ 0 ].webPropertyId,
} );
dispatch( STORE_NAME ).receiveGetSettings( {
// eslint-disable-next-line sitekit/acronym-case
accountID: profiles[ 0 ].accountId,
// eslint-disable-next-line sitekit/acronym-case
propertyID: profiles[ 0 ].webPropertyId,
// eslint-disable-next-line sitekit/acronym-case
internalWebPropertyID: profiles[ 0 ].internalWebPropertyId,
profileID: profiles[ 0 ].id,
} );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<div className="googlesitekit-setup-module__inputs">
<AccountSelect />
<PropertySelect />
<ProfileSelect />
</div>
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Property Select including GA4 properties', () => {
const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
/* eslint-disable sitekit/acronym-case */
const accountID = properties[ 0 ].accountId;
const propertyID = profiles[ 0 ].webPropertyId;
/* eslint-enable */
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).receiveGetAccounts( accounts );
dispatch( STORE_NAME ).finishResolution( 'getAccounts', [] );
// eslint-disable-next-line sitekit/acronym-case
dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
accountID,
propertyID,
} );
dispatch( STORE_NAME ).receiveGetSettings( {
accountID,
} );
dispatch( MODULES_ANALYTICS_4 ).receiveGetProperties(
propertiesGA4,
{ accountID }
);
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<div className="googlesitekit-setup-module__inputs">
<PropertySelectIncludingGA4 />
</div>
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Anonymize IP switch, toggled on', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setUseSnippet( true );
dispatch( STORE_NAME ).setAnonymizeIP( true );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<AnonymizeIPSwitch />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Anonymize IP switch, toggled off', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setUseSnippet( true );
dispatch( STORE_NAME ).setAnonymizeIP( false );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<AnonymizeIPSwitch />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Use Snippet switch, toggled on (default)', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setUseSnippet( true );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<UseSnippetSwitch />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Use Snippet switch, toggled off', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setUseSnippet( false );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<UseSnippetSwitch />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Tracking exclusions (default)', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setTrackingDisabled( [ 'loggedinUsers' ] );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<TrackingExclusionSwitches />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Tracking exclusions (including loggedinUsers)', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setTrackingDisabled( [] );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<TrackingExclusionSwitches />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'Tracking exclusions (including contentCreators)', () => {
const setupRegistry = ( { dispatch } ) => {
dispatch( STORE_NAME ).setTrackingDisabled( [ 'contentCreators' ] );
};
return (
<WithTestRegistry callback={ setupRegistry }>
<SetupWrap>
<TrackingExclusionSwitches />
</SetupWrap>
</WithTestRegistry>
);
} )
.add( 'GA4 notice', () => {
return (
<SetupWrap>
<GA4Notice />
</SetupWrap>
);
} )
.add( 'Audience Overview Chart', () => {
global._googlesitekitLegacyData = analyticsData;
const selectedStats = [
0,
];
const series = {
0: {
color: '#4285f4',
targetAxisIndex: 0,
},
1: {
color: '#4285f4',
targetAxisIndex: 0,
lineDashStyle: [
3,
3,
],
lineWidth: 1,
},
};
const vAxes = null;
// Load the datacache with data.
setTimeout( () => {
doAction(
'googlesitekit.moduleLoaded',
'Single'
);
}, 250 );
return (
<WithTestRegistry>
<Layout
header
title={ __( 'Audience overview for the last 28 days', 'google-site-kit' ) }
headerCTALabel={ __( 'See full stats in Analytics', 'google-site-kit' ) }
headerCTALink="http://analytics.google.com"
>
<LegacyAnalyticsDashboardWidgetOverview
selectedStats={ selectedStats }
handleDataError={ () => {} }
/>
<LegacyAnalyticsDashboardWidgetSiteStats
selectedStats={ selectedStats }
series={ series }
vAxes={ vAxes }
/>
</Layout>
</WithTestRegistry>
);
},
// This uses the legacy widget, the new one is in:
// 'Analytics Module/Components/Module Page/Acquisition Channels Widget'.
{ options: { readySelector: '.googlesitekit-chart .googlesitekit-chart__inner' } } )
.add( 'Top Acquisition Pie Chart', () => {
global._googlesitekitLegacyData = analyticsData;
// Load the datacache with data.
setTimeout( () => {
doAction(
'googlesitekit.moduleLoaded',
'Single'
);
}, 250 );
return (
<WithTestRegistry>
<Layout
header
footer
title={ __( 'Top acquisition channels over the last 28 days', 'google-site-kit' ) }
headerCTALink="https://analytics.google.com"
headerCTALabel={ __( 'See full stats in Analytics', 'google-site-kit' ) }
footerCTALabel={ _x( 'Analytics', 'Service name', 'google-site-kit' ) }
footerCTALink="https://analytics.google.com"
>
<div className="mdc-layout-grid">
<div className="mdc-layout-grid__inner">
<div className="
mdc-layout-grid__cell
mdc-layout-grid__cell--span-4-desktop
mdc-layout-grid__cell--span-8-tablet
mdc-layout-grid__cell--span-4-phone
">
<LegacyDashboardAcquisitionPieChart />
</div>
<div className="
mdc-layout-grid__cell
mdc-layout-grid__cell--span-8-desktop
mdc-layout-grid__cell--span-8-tablet
mdc-layout-grid__cell--span-4-phone
">
<LegacyAnalyticsDashboardWidgetTopAcquisitionSources />
</div>
</div>
</div>
</Layout>
</WithTestRegistry>
);
},
{ options: { readySelector: '.googlesitekit-chart .googlesitekit-chart__inner' } } );
| Fix feature flags in story.
| stories/module-analytics.stories.js | Fix feature flags in story. | <ide><path>tories/module-analytics.stories.js
<ide> import { properties as propertiesGA4 } from '../assets/js/modules/analytics-4/datastore/__fixtures__';
<ide> import { STORE_NAME } from '../assets/js/modules/analytics/datastore/constants';
<ide> import { MODULES_ANALYTICS_4 } from '../assets/js/modules/analytics-4/datastore/constants';
<add>import { enabledFeatures } from '../assets/js/features';
<ide>
<ide> function SetupWrap( { children } ) {
<ide> return (
<ide> );
<ide> } )
<ide> .add( 'Property Select including GA4 properties', () => {
<add> // Have to import like with tests
<add> enabledFeatures.add( 'ga4setup' );
<add>
<ide> const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
<ide> /* eslint-disable sitekit/acronym-case */
<ide> const accountID = properties[ 0 ].accountId;
<ide>
<ide> // eslint-disable-next-line sitekit/acronym-case
<ide> dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID: properties[ 0 ].accountId } );
<add> // I believe we don't need profiles for this story, do we? Let's get rid of it if we don't need it
<ide> dispatch( STORE_NAME ).receiveGetProfiles( profiles, {
<ide> accountID,
<ide> propertyID,
<ide> };
<ide>
<ide> return (
<del> <WithTestRegistry callback={ setupRegistry }>
<del> <SetupWrap>
<add> <WithTestRegistry
<add> callback={ setupRegistry }
<add> // This does not work
<add> features={ [ 'ga4setup' ] }
<add> >
<add> <SetupWrap>
<add> <h1>fooooz</h1>
<ide> <div className="googlesitekit-setup-module__inputs">
<ide> <PropertySelectIncludingGA4 />
<ide> </div> |
|
Java | apache-2.0 | d3c871a1d348981fd3dea12e8cff86cf42470a61 | 0 | twogee/ant-ivy,jaikiran/ant-ivy,apache/ant-ivy,jaikiran/ant-ivy,twogee/ant-ivy,sbt/ivy,sbt/ivy,apache/ant-ivy,twogee/ant-ivy,jaikiran/ant-ivy,apache/ant-ivy,twogee/ant-ivy,apache/ant-ivy,jaikiran/ant-ivy | /*
* 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.ivy.ant;
import org.apache.ivy.core.cache.CacheManager;
import org.apache.ivy.core.retrieve.RetrieveOptions;
import org.apache.ivy.util.filter.Filter;
import org.apache.tools.ant.BuildException;
/**
* This task allow to retrieve dependencies from the cache to a local directory like a lib dir.
*/
public class IvyRetrieve extends IvyPostResolveTask {
private String pattern;
private String ivypattern = null;
private boolean sync = false;
private boolean symlink = false;
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public void doExecute() throws BuildException {
prepareAndCheck();
pattern = getProperty(pattern, getSettings(), "ivy.retrieve.pattern");
try {
Filter artifactFilter = getArtifactFilter();
int targetsCopied = getIvyInstance().retrieve(
getResolvedMrid(),
pattern,
new RetrieveOptions().setConfs(splitConfs(getConf())).setCache(
CacheManager.getInstance(getIvyInstance().getSettings(), getCache()))
.setDestIvyPattern(ivypattern).setArtifactFilter(artifactFilter).setSync(
sync).setUseOrigin(isUseOrigin()).setMakeSymlinks(symlink)
.setResolveId(getResolveId()));
boolean haveTargetsBeenCopied = targetsCopied > 0;
getProject().setProperty("ivy.nb.targets.copied", String.valueOf(targetsCopied));
getProject().setProperty("ivy.targets.copied", String.valueOf(haveTargetsBeenCopied));
} catch (Exception ex) {
throw new BuildException("impossible to ivy retrieve: " + ex, ex);
}
}
public String getIvypattern() {
return ivypattern;
}
public void setIvypattern(String ivypattern) {
this.ivypattern = ivypattern;
}
public boolean isSync() {
return sync;
}
public void setSync(boolean sync) {
this.sync = sync;
}
/**
* Option to create symlinks instead of copying.
*/
public void setSymlink(boolean symlink) {
this.symlink = symlink;
}
}
| src/java/org/apache/ivy/ant/IvyRetrieve.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.ivy.ant;
import org.apache.ivy.core.cache.CacheManager;
import org.apache.ivy.core.retrieve.RetrieveEngine;
import org.apache.ivy.core.retrieve.RetrieveOptions;
import org.apache.ivy.util.filter.Filter;
import org.apache.tools.ant.BuildException;
/**
* This task allow to retrieve dependencies from the cache to a local directory like a lib dir.
*
* @see RetrieveEngine
*/
public class IvyRetrieve extends IvyPostResolveTask {
private String pattern;
private String ivypattern = null;
private boolean sync = false;
private boolean symlink = false;
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public void doExecute() throws BuildException {
prepareAndCheck();
pattern = getProperty(pattern, getSettings(), "ivy.retrieve.pattern");
try {
Filter artifactFilter = getArtifactFilter();
int targetsCopied = getIvyInstance().retrieve(
getResolvedMrid(),
pattern,
new RetrieveOptions().setConfs(splitConfs(getConf())).setCache(
CacheManager.getInstance(getIvyInstance().getSettings(), getCache()))
.setDestIvyPattern(ivypattern).setArtifactFilter(artifactFilter).setSync(
sync).setUseOrigin(isUseOrigin()).setMakeSymlinks(symlink)
.setResolveId(getResolveId()));
boolean haveTargetsBeenCopied = targetsCopied > 0;
getProject().setProperty("ivy.nb.targets.copied", String.valueOf(targetsCopied));
getProject().setProperty("ivy.targets.copied", String.valueOf(haveTargetsBeenCopied));
} catch (Exception ex) {
throw new BuildException("impossible to ivy retrieve: " + ex, ex);
}
}
public String getIvypattern() {
return ivypattern;
}
public void setIvypattern(String ivypattern) {
this.ivypattern = ivypattern;
}
public boolean isSync() {
return sync;
}
public void setSync(boolean sync) {
this.sync = sync;
}
/**
* Option to create symlinks instead of copying.
*/
public void setSymlink(boolean symlink) {
this.symlink = symlink;
}
}
| Make checkstyle happy
git-svn-id: 4757cb15a840ff1a58eff8144c368923fad328dd@551346 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/ivy/ant/IvyRetrieve.java | Make checkstyle happy | <ide><path>rc/java/org/apache/ivy/ant/IvyRetrieve.java
<ide> package org.apache.ivy.ant;
<ide>
<ide> import org.apache.ivy.core.cache.CacheManager;
<del>import org.apache.ivy.core.retrieve.RetrieveEngine;
<ide> import org.apache.ivy.core.retrieve.RetrieveOptions;
<ide> import org.apache.ivy.util.filter.Filter;
<ide> import org.apache.tools.ant.BuildException;
<ide>
<ide> /**
<ide> * This task allow to retrieve dependencies from the cache to a local directory like a lib dir.
<del> *
<del> * @see RetrieveEngine
<ide> */
<ide> public class IvyRetrieve extends IvyPostResolveTask {
<ide> private String pattern; |
|
Java | bsd-2-clause | 914bad36d4fa8a5e7e397491269b7d05b16b4783 | 0 | thecastawaydev/tonegodgui-1,brainless-studios/tonegodgui,meltzow/tonegodgui | package tonegod.gui.core;
import com.jme3.app.Application;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.font.LineWrapMode;
import com.jme3.font.Rectangle;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector4f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.texture.Texture;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import tonegod.gui.controls.extras.DragElement;
import tonegod.gui.controls.form.Form;
import tonegod.gui.controls.text.TextElement;
import tonegod.gui.core.utils.UIDUtil;
import tonegod.gui.effects.Effect;
/**
*
* @author t0neg0d
*/
public class Element extends Node {
public static enum Borders {
NW,
N,
NE,
W,
E,
SW,
S,
SE;
};
/**
* Some controls provide different layout's based on the orientation of the control
*/
public static enum Orientation {
/**
* Vertical layout
*/
VERTICAL,
/**
* Horizontal layout
*/
HORIZONTAL
}
/**
* Defines how the element will dock to it's parent element during resize events
*/
public static enum Docking {
/**
* Docks to the top left of parent
*/
NW,
/**
* Docks to the top right of parent
*/
NE,
/**
* Docks to the bottom left of parent
*/
SW,
/**
* Docks to the bottom right of parent
*/
SE
}
protected Application app;
protected ElementManager screen;
private String UID;
private Vector2f position = new Vector2f();
public Vector2f orgPosition;
private Vector2f dimensions = new Vector2f();
public Vector2f orgDimensions, orgRelDimensions;
public Vector4f borders = new Vector4f(1,1,1,1);
public Vector4f borderHandles = new Vector4f(12,12,12,12);
private Vector2f minDimensions = new Vector2f(10, 10);
private boolean ignoreMouse = false;
protected boolean isMovable = false;
private boolean lockToParentBounds = false;
private boolean isResizable = false;
private boolean resizeN = true;
private boolean resizeS = true;
private boolean resizeW = true;
private boolean resizeE = true;
private boolean dockN = false;
private boolean dockW = true;
private boolean dockE = false;
private boolean dockS = true;
private boolean scaleNS = true;
private boolean scaleEW = true;
private boolean effectParent = false;
private boolean effectAbsoluteParent = false;
private Geometry geom;
private ElementQuadGrid model;
private boolean tileImage = false;
private Material mat;
private Texture defaultTex;
private boolean useLocalAtlas = false;
private String atlasCoords = "";
private Texture alphaMap = null;
protected BitmapText textElement;
// protected TextElement textElement;
protected Vector2f textPosition = new Vector2f(0,0);
protected LineWrapMode textWrap = LineWrapMode.Word;
protected BitmapFont.Align textAlign = BitmapFont.Align.Left;
protected BitmapFont.VAlign textVAlign = BitmapFont.VAlign.Top;
protected String text = "";
private String toolTipText = null;
protected BitmapFont font;
protected float fontSize = 20;
protected float textPadding = 0;
protected ColorRGBA fontColor = ColorRGBA.White;
private ColorRGBA defaultColor = new ColorRGBA(1,1,1,0);
private Element elementParent = null;
protected Map<String, Element> elementChildren = new LinkedHashMap();
protected boolean isClipped = false;
protected boolean wasClipped = false;
private Element clippingLayer;
private Vector4f clippingBounds = new Vector4f();
private float clipPadding = 0;
private float textClipPadding = 0;
protected boolean isVisible = true;
protected boolean wasVisible = true;
protected boolean isVisibleAsModal = false;
private boolean hasFocus = false;
private boolean resetKeyboardFocus = true;
private Form form;
private int tabIndex = 0;
private float zOrder;
private boolean effectZOrder = true;
private Map<Effect.EffectEvent, Effect> effects = new HashMap();
private OSRBridge bridge;
private boolean ignoreGlobalAlpha = false;
private boolean isModal = false;
private boolean isGlobalModal = false;
private Object elementUserData;
private boolean initialized = false;
private boolean isDragElement = false, isDropElement = false;
private Docking docking = Docking.NW;
private Orientation orientation = Orientation.HORIZONTAL;
/**
* The Element class is the single primitive for all controls in the gui library.
* Each element consists of an ElementQuadMesh for rendering resizable textures,
* as well as a BitmapText element if setText(String text) is called.
*
* Behaviors, such as movement and resizing, are common to all elements and can
* be enabled/disabled to ensure the element reacts to user input as needed.
*
* @param screen The Screen control the element or it's absolute parent element is being added to
* @param UID A unique String identifier used when looking up elements by screen.getElementByID()
* @param position A Vector2f containing the x/y coordinates (relative to it's parent elements x/y) for positioning
* @param dimensions A Vector2f containing the dimensions of the element, x being width, y being height
* @param resizeBorders A Vector4f containing the size of each border used for scaling images without distorting them (x = N, y = W, x = E, w = S)
* @param texturePath A String path to the default image to be rendered on the element's mesh
*/
public Element(ElementManager screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String texturePath) {
this.app = screen.getApplication();
this.screen = screen;
if (UID == null) {
this.UID = UIDUtil.getUID();
} else {
this.UID = UID;
}
this.position.set(position);
this.dimensions.set(dimensions);
this.orgDimensions = dimensions.clone();
this.orgRelDimensions = new Vector2f(1,1);
this.borders.set(resizeBorders);
BitmapFont tempFont = app.getAssetManager().loadFont(screen.getStyle("Font").getString("defaultFont"));
font = new BitmapFont();
font.setCharSet(app.getAssetManager().loadFont(screen.getStyle("Font").getString("defaultFont")).getCharSet());
Material[] pages = new Material[tempFont.getPageSize()];
for (int i = 0; i < pages.length; i++) {
pages[i] = tempFont.getPage(i).clone();
}
font.setPages(pages);
float imgWidth = 100;
float imgHeight = 100;
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
float textureAtlasX = 0, textureAtlasY = 0, textureAtlasW = imgWidth, textureAtlasH = imgHeight;
boolean useAtlas = screen.getUseTextureAtlas();
if (texturePath != null) {
if (useAtlas) {
float[] coords = screen.parseAtlasCoords(texturePath);
textureAtlasX = coords[0];
textureAtlasY = coords[1];
textureAtlasW = coords[2];
textureAtlasH = coords[3];
this.atlasCoords = "x=" + coords[0] + "|y=" + coords[1] + "|w=" + coords[2] + "|h=" + coords[3];
defaultTex = screen.getAtlasTexture();
imgWidth = defaultTex.getImage().getWidth();
imgHeight = defaultTex.getImage().getHeight();
pixelWidth = 1f/imgWidth;
pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
} else {
defaultTex = app.getAssetManager().loadTexture(texturePath);
defaultTex.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
defaultTex.setMagFilter(Texture.MagFilter.Nearest);
defaultTex.setWrap(Texture.WrapMode.Clamp);
imgWidth = defaultTex.getImage().getWidth();
imgHeight = defaultTex.getImage().getHeight();
pixelWidth = 1f/imgWidth;
pixelHeight = 1f/imgHeight;
textureAtlasW = imgWidth;
textureAtlasH = imgHeight;
}
}
mat = new Material(app.getAssetManager(), "tonegod/gui/shaders/Unshaded.j3md");
if (texturePath != null) {
mat.setTexture("ColorMap", defaultTex);
mat.setColor("Color", new ColorRGBA(1,1,1,1));
} else {
mat.setColor("Color", defaultColor);
}
if (useAtlas) mat.setBoolean("UseEffectTexCoords", true);
mat.setVector2("OffsetAlphaTexCoord", new Vector2f(0,0));
mat.setFloat("GlobalAlpha", screen.getGlobalAlpha());
mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Back);
this.model = new ElementQuadGrid(this.dimensions, borders, imgWidth, imgHeight, pixelWidth, pixelHeight, textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
this.setName(UID + ":Node");
geom = new Geometry(UID + ":Geometry");
geom.setMesh(model);
geom.setCullHint(CullHint.Never);
geom.setQueueBucket(Bucket.Gui);
geom.setMaterial(mat);
this.attachChild(geom);
this.setQueueBucket(Bucket.Gui);
this.setLocalTranslation(position.x, position.y, 0);
}
public void setAsContainerOnly() {
detachChildAt(0);
}
private void throwParserException() {
try {
throw new java.text.ParseException("The provided texture information does not conform to the expected standard of ?x=(int)&y=(int)&w=(int)&h=(int)", 0);
} catch (ParseException ex) {
Logger.getLogger(Element.class.getName()).log(Level.SEVERE, "The provided texture information does not conform to the expected standard of ?x=(int)&y=(int)&w=(int)&h=(int)", ex);
}
}
/**
* Sets the texture to use as an atlas image as well as the atlas image coords.
* @param tex The texture to use as a local atlas image
* @param queryString The position of the desire atlas image (e.g. "x=0|y=0|w=50|h=50")
*/
public void setTextureAtlasImage(Texture tex, String queryString) {
this.defaultTex = tex;
mat.setTexture("ColorMap", tex);
mat.setColor("Color", new ColorRGBA(1,1,1,1));
mat.setBoolean("UseEffectTexCoords", true);
this.useLocalAtlas = true;
this.atlasCoords = queryString;
float[] coords = screen.parseAtlasCoords(queryString);
float textureAtlasX = coords[0];
float textureAtlasY = coords[1];
float textureAtlasW = coords[2];
float textureAtlasH = coords[3];
float imgWidth = defaultTex.getImage().getWidth();
float imgHeight = defaultTex.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
this.model = new ElementQuadGrid(this.dimensions, borders, imgWidth, imgHeight, pixelWidth, pixelHeight, textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
geom.setMesh(model);
}
/**
* Returns the current unparsed string representing the Element's atlas image
* @return
*/
public String getAtlasCoords() { return this.atlasCoords; }
/**
* Sets the element image to the specified x/y/width/height
* @param queryString (e.g. "x=0|y=0|w=50|h=50")
*/
public void updateTextureAtlasImage(String queryString) {
float[] coords = screen.parseAtlasCoords(queryString);
float textureAtlasX = coords[0];
float textureAtlasY = coords[1];
float textureAtlasW = coords[2];
float textureAtlasH = coords[3];
float imgWidth = defaultTex.getImage().getWidth();
float imgHeight = defaultTex.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
getModel().updateTexCoords(textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
}
/**
* Returns if the element is using a local texture atlas of the screen defined texture atlas
* @return
*/
public boolean getUseLocalAtlas() { return this.useLocalAtlas; }
/**
* Returns the difference between the placement of the elements current image and the given texture coords.
* @param coords The x/y coords of the new image
* @return Vector2f containing The difference between the given coords and the original image
*/
public Vector2f getAtlasTextureOffset(float[] coords) {
Texture tex;
if (defaultTex != null) tex = defaultTex;
else tex = screen.getAtlasTexture();
float imgWidth = tex.getImage().getWidth();
float imgHeight = tex.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
return new Vector2f( getModel().getEffectOffset( pixelWidth*coords[0], pixelHeight*(imgHeight-coords[1]-coords[3]) ));
}
public void setTileImage(boolean tileImage) {
this.tileImage = tileImage;
if (tileImage)
((Texture)mat.getParam("ColorMap").getValue()).setWrap(Texture.WrapMode.Repeat);
else
((Texture)mat.getParam("ColorMap").getValue()).setWrap(Texture.WrapMode.Clamp);
setDimensions(dimensions);
}
public boolean getTileImage() {
return this.tileImage;
}
/**
* Converts the the inputed percentage (0.0f-1.0f) into pixels of the elements image
* @param in Vector2f containing the x and y percentage
* @return Vector2f containing the actual width/height in pixels
*/
public final Vector2f getV2fPercentToPixels(Vector2f in) {
if (getElementParent() == null) {
if (in.x < 1) in.setX(screen.getWidth()*in.x);
if (in.y < 1) in.setY(screen.getHeight()*in.y);
} else {
if (in.x < 1) in.setX(getElementParent().getWidth()*in.x);
if (in.y < 1) in.setY(getElementParent().getHeight()*in.y);
}
return in;
}
/**
* Adds the specified Element as a child to this Element.
* @param child The Element to add as a child
*/
public void addChild(Element child) {
child.elementParent = this;
if (!child.getInitialized()) {
child.setY(this.getHeight()-child.getHeight()-child.getY());
child.orgPosition = position.clone();
child.orgPosition.setY(child.getY());
child.setInitialized();
}
child.orgRelDimensions.set(child.getWidth()/getWidth(),child.getHeight()/getHeight());
child.setQueueBucket(RenderQueue.Bucket.Gui);
if (screen.getElementById(child.getUID()) != null) {
try {
throw new ConflictingIDException();
} catch (ConflictingIDException ex) {
Logger.getLogger(Element.class.getName()).log(Level.SEVERE, "The child element '" + child.getUID() + "' (" + child.getClass() + ") conflicts with a previously added child element in parent element '" + getUID() + "'.", ex);
System.exit(0);
}
} else {
elementChildren.put(child.getUID(), child);
this.attachChild(child);
}
}
/**
* Adds the specified Element as a child to this Element.
* @param child The Element to add as a child
*/
public void addChild(Element child, boolean hide) {
child.elementParent = this;
if (!child.getInitialized()) {
child.setY(this.getHeight()-child.getHeight()-child.getY());
child.orgPosition = position.clone();
child.orgPosition.setY(child.getY());
child.setInitialized();
}
child.orgRelDimensions.set(child.getWidth()/getWidth(),child.getHeight()/getHeight());
child.setQueueBucket(RenderQueue.Bucket.Gui);
if (screen.getElementById(child.getUID()) != null) {
try {
throw new ConflictingIDException();
} catch (ConflictingIDException ex) {
Logger.getLogger(Element.class.getName()).log(Level.SEVERE, "The child element '" + child.getUID() + "' (" + child.getClass() + ") conflicts with a previously added child element in parent element '" + getUID() + "'.", ex);
System.exit(0);
}
} else {
elementChildren.put(child.getUID(), child);
this.attachChild(child);
if (hide)
child.hide();
}
}
/**
* Removes the specified Element
* @param child Element to remove
*/
public void removeChild(Element child) {
Element e = elementChildren.remove(child.getUID());
if (e != null) {
e.elementParent = null;
e.removeFromParent();
e.cleanup();
}
}
/**
* Remove all child Elements from this Element
*/
public void removeAllChildren() {
for (Element e : elementChildren.values()) {
e.removeFromParent();
}
elementChildren.clear();
}
/**
* Returns the child elements as a Map
* @return
*/
public Map<String, Element> getElementsAsMap() {
return this.elementChildren;
}
/**
* Returns the child elements as a Collection
* @return
*/
public Collection<Element> getElements() {
return this.elementChildren.values();
}
/**
* Returns the one and only Element's screen
* @return
*/
public ElementManager getScreen() {
return this.screen;
}
// Z-ORDER
/**
* Recursive call made by the screen control to properly initialize z-order (depth) placement
* @param zOrder The depth to place the Element at. (Relative to the parent's z-order)
*/
protected void initZOrder(float zOrder) {
setLocalTranslation(getLocalTranslation().setZ(
zOrder
));
if (getTextElement() != null)
getTextElement().setLocalTranslation(getTextElement().getLocalTranslation().setZ(
screen.getZOrderStepMinor()
));
for (Element el : elementChildren.values()) {
el.initZOrder(screen.getZOrderStepMinor());
}
}
/**
* Returns the Element's zOrder
* @return float zOrder
*/
public float getZOrder() {
return this.zOrder;
}
/**
* Sets the Elements zOrder (I would suggest NOT using this method)
* @param zOrder
*/
public void setZOrder(float zOrder) {
this.zOrder = zOrder;
initZOrder(zOrder);
}
public void setEffectZOrder(boolean effectZOrder) {
this.effectZOrder = effectZOrder;
}
public boolean getEffectZOrder() { return this.effectZOrder; }
public void setGlobalUIScale(float widthPercent, float heightPercent) {
for (Element el : elementChildren.values()) {
el.setPosition(el.getPosition().x*widthPercent, el.getPosition().y*heightPercent);
el.setDimensions(el.getDimensions().x*widthPercent, el.getDimensions().y*heightPercent);
el.setFontSize(el.getFontSize()*heightPercent);
el.setGlobalUIScale(widthPercent, heightPercent);
}
}
/**
* Returns a list of all children that are an instance of DragElement
* @return List<Element>
*/
public List<Element> getDraggableChildren() {
List<Element> ret = new ArrayList();
for (Element el : elementChildren.values()) {
if (el instanceof DragElement) {
ret.add(el);
}
}
return ret;
}
// Recursive & non-recursive parent/child element searches
/**
* Recursively searches children elements for specified element containing the specified UID
* @param UID - Unique Indentifier of element to search for
* @return Element containing UID or null if not found
*/
public Element getChildElementById(String UID) {
Element ret = null;
if (this.UID.equals(UID)) {
ret = this;
} else {
if (elementChildren.containsKey(UID)) {
ret = elementChildren.get(UID);
} else {
for (Element el : elementChildren.values()) {
ret = el.getChildElementById(UID);
if (ret != null) {
break;
}
}
}
}
return ret;
}
/**
* Returns the top-most parent in the tree of Elements. The topmost element will always have a parent of null
* @return Element elementParent
*/
public Element getAbsoluteParent() {
if (elementParent == null) {
return this;
} else {
return elementParent.getAbsoluteParent();
}
}
/**
* Returns the parent element of this node
* @return Element elementParent
*/
public Element getElementParent() {
return elementParent;
}
/**
* Sets the element's parent element
* @param elementParent Element
*/
public void setElementParent(Element elementParent) {
this.elementParent = elementParent;
}
// Getters & Setters
/**
* Allows for setting the Element UID if (and ONLY if) the Element Parent is null
* @param UID The new UID
* @return boolean If setting the UID was successful
*/
public boolean setUID(String UID) {
if (this.elementParent == null) {
this.UID = UID;
return true;
} else {
return false;
}
}
/**
* Returns the element's unique string identifier
* @return String UID
*/
public String getUID() {
return UID;
}
/**
* Returns the default material for the element
* @return Material mat
*/
public Material getMaterial() {
return this.mat;
}
/**
* A way to override the default material of the element.
*
* NOTE: It is important that the shader used with the new material is either:
* A: The provided Unshaded material contained with this library, or
* B: The custom shader contains the caret, text range, clipping and effect
* handling provided in the default shader.
*
* @param mat The Material to use for rendering this Element.
*/
public void setLocalMaterial(Material mat) {
this.mat = mat;
this.setMaterial(mat);
}
/**
* Informs the screen control that this Element should be ignored by mouse events.
*
* @param ignoreMouse boolean
*/
public void setIgnoreMouse(boolean ignoreMouse) {
this.ignoreMouse = ignoreMouse;
}
/**
* Returns if the element is set to ingnore mouse events
*
* @return boolean ignoreMouse
*/
public boolean getIgnoreMouse() {
return this.ignoreMouse;
}
/**
* Enables draggable behavior for this element
* @param isMovable boolean
*/
public void setIsMovable(boolean isMovable) {
this.isMovable = isMovable;
}
/**
* Returns if the element has draggable behavior set
* @return boolean isMovable
*/
public boolean getIsMovable() {
return this.isMovable;
}
/**
* Enables resize behavior for this element
* @param isResizable boolean
*/
public void setIsResizable(boolean isResizable) {
this.isResizable = isResizable;
}
/**
* Returns if the element has resize behavior set
* @return boolean isResizable
*/
public boolean getIsResizable() {
return this.isResizable;
}
/**
* Enables/disables north border for resizing
* @param resizeN boolean
*/
public void setResizeN(boolean resizeN) {
this.resizeS = resizeN;
}
/**
* Returns whether the elements north border has enabled/disabled resizing
* @return boolean resizeN
*/
public boolean getResizeN() {
return this.resizeS;
}
/**
* Enables/disables south border for resizing
* @param resizeS boolean
*/
public void setResizeS(boolean resizeS) {
this.resizeN = resizeS;
}
/**
* Returns whether the elements south border has enabled/disabled resizing
* @return boolean resizeS
*/
public boolean getResizeS() {
return this.resizeN;
}
/**
* Enables/disables west border for resizing
* @param resizeW boolean
*/
public void setResizeW(boolean resizeW) {
this.resizeW = resizeW;
}
/**
* Returns whether the elements west border has enabled/disabled resizing
* @return boolean resizeW
*/
public boolean getResizeW() {
return this.resizeW;
}
/**
* Enables/disables east border for resizing
* @param resizeE boolean
*/
public void setResizeE(boolean resizeE) {
this.resizeE = resizeE;
}
/**
* Returns whether the elements east border has enabled/disabled resizing
* @return boolean resizeE
*/
public boolean getResizeE() {
return this.resizeE;
}
/**
* Sets how the element will docking to it's parent element during resize events.
* NW = Top Left of parent element
* NE = Top Right of parent element
* SW = Bottom Left of parent element
* SE = Bottom Right of parent element
* @param docking
*/
public void setDocking(Docking docking) {
this.docking = docking;
}
public Docking getDocking() {
return this.docking;
}
/**
* Enables north docking of element (disables south docking of Element). This
* determines how the Element should retain positioning on parent resize events.
*
* @param dockN boolean
*/
@Deprecated
public void setDockN(boolean dockN) {
this.dockS = dockN;
this.dockN = !dockN;
Docking d = null;
if (dockS) {
if (dockE) d = Docking.NE;
else d = Docking.NW;
} else {
if (dockE) d = Docking.SE;
else d = Docking.SW;
}
setDocking(d);
}
/**
* Returns if the Element is docked to the north quadrant of it's parent element.
* @return boolean dockN
*/
@Deprecated
public boolean getDockN() {
return this.dockS;
}
/**
* Enables west docking of Element (disables east docking of Element). This
* determines how the Element should retain positioning on parent resize events.
*
* @param dockW boolean
*/
@Deprecated
public void setDockW(boolean dockW) {
this.dockW = dockW;
this.dockE = !dockW;
Docking d = null;
if (dockE) {
if (dockS) d = Docking.NE;
else d = Docking.SE;
} else {
if (dockS) d = Docking.NW;
else d = Docking.SW;
}
setDocking(d);
}
/**
* Returns if the Element is docked to the west quadrant of it's parent element.
* @return boolean dockW
*/
@Deprecated
public boolean getDockW() {
return this.dockW;
}
/**
* Enables east docking of Element (disables west docking of Element). This
* determines how the Element should retain positioning on parent resize events.
*
* @param dockE boolean
*/
@Deprecated
public void setDockE(boolean dockE) {
this.dockE = dockE;
this.dockW = !dockE;
Docking d = null;
if (dockE) {
if (dockS) d = Docking.NE;
else d = Docking.SE;
} else {
if (dockS) d = Docking.NW;
else d = Docking.SW;
}
setDocking(d);
}
/**
* Returns if the Element is docked to the east quadrant of it's parent element.
* @return boolean dockE
*/
@Deprecated
public boolean getDockE() {
return this.dockE;
}
/**
* Enables south docking of Element (disables north docking of Element). This
* determines how the Element should retain positioning on parent resize events.
*
* @param dockS boolean
*/
@Deprecated
public void setDockS(boolean dockS) {
this.dockN = dockS;
this.dockS = !dockS;
Docking d = null;
if (dockS) {
if (dockE) d = Docking.NE;
else d = Docking.NW;
} else {
if (dockE) d = Docking.SE;
else d = Docking.SW;
}
setDocking(d);
}
/**
* Returns if the Element is docked to the south quadrant of it's parent element.
* @return boolean dockS
*/
@Deprecated
public boolean getDockS() {
return this.dockN;
}
/**
* Determines if the element should scale with parent when resized vertically.
* @param scaleNS boolean
*/
public void setScaleNS(boolean scaleNS) {
this.scaleNS = scaleNS;
}
/**
* Returns if the Element is set to scale vertically when it's parent Element is
* resized.
*
* @return boolean scaleNS
*/
public boolean getScaleNS() {
return this.scaleNS;
}
/**
* Determines if the element should scale with parent when resized horizontally.
* @param scaleEW boolean
*/
public void setScaleEW(boolean scaleEW) {
this.scaleEW = scaleEW;
}
/**
* Returns if the Element is set to scale horizontally when it's parent Element is
* resized.
*
* @return boolean scaleEW
*/
public boolean getScaleEW() {
return this.scaleEW;
}
/**
* Sets the element to pass certain events (movement, resizing) to it direct parent instead
* of effecting itself.
*
* @param effectParent boolean
*/
public void setEffectParent(boolean effectParent) {
this.effectParent = effectParent;
}
/**
* Returns if the Element is set to pass events to it's direct parent
* @return boolean effectParent
*/
public boolean getEffectParent() {
return this.effectParent;
}
/**
* Sets the element to pass certain events (movement, resizing) to it absolute
* parent instead of effecting itself.
*
* The Elements absolute parent is the element farthest up in it's nesting order,
* or simply put, was added to the screen.
*
* @param effectAbsoluteParent boolean
*/
public void setEffectAbsoluteParent(boolean effectAbsoluteParent) {
this.effectAbsoluteParent = effectAbsoluteParent;
}
/**
* Returns if the Element is set to pass events to it's absolute parent
* @return boolean effectParent
*/
public boolean getEffectAbsoluteParent() {
return this.effectAbsoluteParent;
}
/**
* Forces the object to stay within the constraints of it's parent Elements
* dimensions.
* NOTE: use setLockToParentBounds instead.
*
* @param lockToParentBounds boolean
*/
@Deprecated
public void setlockToParentBounds(boolean lockToParentBounds) {
this.lockToParentBounds = lockToParentBounds;
}/**
* Forces the object to stay within the constraints of it's parent Elements
* dimensions.
*
* @param lockToParentBounds boolean
*/
public void setLockToParentBounds(boolean lockToParentBounds) {
this.lockToParentBounds = lockToParentBounds;
}
/**
* Returns if the Element has been constrained to it's parent Element's dimensions.
*
* @return boolean lockToParentBounds
*/
public boolean getLockToParentBounds() {
return this.lockToParentBounds;
}
/**
* Set the x,y coordinates of the Element. X and y are relative to the parent
* Element.
*
* @param position Vector2f screen poisition of Element
*/
public void setPosition(Vector2f position) {
this.position.set(position);
updateNodeLocation();
}
/**
* Set the x,y coordinates of the Element. X and y are relative to the parent
* Element.
*
* @param x The x coordinate screen poisition of Element
* @param y The y coordinate screen poisition of Element
*/
public void setPosition(float x, float y) {
this.position.setX(x);
this.position.setY(y);
updateNodeLocation();
}
/**
* Set the x coordinates of the Element. X is relative to the parent Element.
*
* @param x The x coordinate screen poisition of Element
*/
public void setX(float x) {
this.position.setX(x);
updateNodeLocation();
}
/**
* Set the y coordinates of the Element. Y is relative to the parent Element.
*
* @param y The y coordinate screen poisition of Element
*/
public void setY(float y) {
this.position.setY(y);
updateNodeLocation();
}
private void updateNodeLocation() {
this.setLocalTranslation(position.x, position.y, this.getLocalTranslation().getZ());
updateClipping();
}
/**
* Flags Element as Drag Element for Drag & Drop interaction
* @param isDragElement boolean
*/
public void setIsDragDropDragElement(boolean isDragElement) {
this.isDragElement = isDragElement;
if (isDragElement)
this.isDropElement = false;
}
/**
* Returns if the Element is currently flagged as a Drag Element for Drag & Drop interaction
* @return boolean
*/
public boolean getIsDragDropDragElement() {
return this.isDragElement;
}
/**
* Flags Element as Drop Element for Drag & Drop interaction
* @param isDropElement boolean
*/
public void setIsDragDropDropElement(boolean isDropElement) {
this.isDropElement = isDropElement;
if (isDropElement)
this.isDragElement = false;
}
/**
* Returns if the Element is currently flagged as a Drop Element for Drag & Drop interaction
* @return boolean
*/
public boolean getIsDragDropDropElement() {
return this.isDropElement;
}
/**
* Returns the current screen location of the Element
* @return Vector2f position
*/
public Vector2f getPosition() {
return position;
}
/**
* Gets the relative x coordinate of the Element from it's parent Element's x
* @return float
*/
public float getX() {
return position.x;
}
/**
* Gets the relative y coordinate of the Element from it's parent Element's y
* @return float
*/
public float getY() {
return position.y;
}
/**
* Returns the x coord of an element from screen x 0, ignoring the nesting order.
* @return float x
*/
public float getAbsoluteX() {
float x = getX();
Element el = this;
while (el.getElementParent() != null) {
el = el.getElementParent();
x += el.getX();
}
return x;
}
/**
* Returns the y coord of an element from screen y 0, ignoring the nesting order.
* @return float
*/
public float getAbsoluteY() {
float y = getY();
Element el = this;
while (el.getElementParent() != null) {
el = el.getElementParent();
y += el.getY();
}
return y;
}
/**
* Sets the width and height of the element
* @param w float
* @param h float
*/
public void setDimensions(float w, float h) {
this.dimensions.setX(w);
this.dimensions.setY(h);
getModel().updateDimensions(dimensions.x, dimensions.y);
if (tileImage) {
float tcW = dimensions.x/getModel().getImageWidth();
float tcH = dimensions.y/getModel().getImageHeight();
getModel().updateTiledTexCoords(0, -tcH, tcW, 0);
}
geom.updateModelBound();
if (textElement != null) {
updateTextElement();
}
updateClipping();
}
/**
* Sets the width and height of the element
* @param dimensions Vector2f
*/
public void setDimensions(Vector2f dimensions) {
this.dimensions.set(dimensions);
getModel().updateDimensions(dimensions.x, dimensions.y);
if (tileImage) {
float tcW = dimensions.x/getModel().getImageWidth();
float tcH = dimensions.y/getModel().getImageHeight();
getModel().updateTiledTexCoords(0, -tcH, tcW, 0);
}
geom.updateModelBound();
if (textElement != null) {
updateTextElement();
}
updateClipping();
}
/**
* Stubbed for future use. This should limit resizing to the minimum dimensions defined
* @param minDimensions The absolute minimum dimensions for this Element.
*/
public void setMinDimensions(Vector2f minDimensions) {
if (this.minDimensions == null) this.minDimensions = new Vector2f();
this.minDimensions.set(minDimensions);
}
/**
* Sets the width of the element
* @param width float
*/
public void setWidth(float width) {
this.dimensions.setX(width);
getModel().updateWidth(dimensions.x);
if (tileImage) {
float tcW = dimensions.x/getModel().getImageWidth();
float tcH = dimensions.y/getModel().getImageHeight();
getModel().updateTiledTexCoords(0, -tcH, tcW, 0);
}
geom.updateModelBound();
if (textElement != null) {
updateTextElement();
}
updateClipping();
}
/**
* Sets the height of the element
* @param height float
*/
public void setHeight(float height) {
this.dimensions.setY(height);
getModel().updateHeight(dimensions.y);
if (tileImage) {
float tcW = dimensions.x/getModel().getImageWidth();
float tcH = dimensions.y/getModel().getImageHeight();
getModel().updateTiledTexCoords(0, -tcH, tcW, 0);
}
geom.updateModelBound();
if (textElement != null) {
updateTextElement();
}
updateClipping();
}
/**
* Returns a Vector2f containing the actual width and height of an Element
* @return float
*/
public Vector2f getDimensions() {
return dimensions;
}
/**
* Returns the dimensions defined at the time of the Element's creation.
* @return
*/
public Vector2f getOrgDimensions() { return this.orgDimensions; }
/**
* Returns the actual width of an Element
* @return float
*/
public float getWidth() {
return dimensions.x;
}
/**
* Returns the actual height of an Element
* @return float
*/
public float getHeight() {
return dimensions.y;
}
/**
* Returns the width of an Element from screen x 0
* @return float
*/
public float getAbsoluteWidth() {
return getAbsoluteX() + getWidth();
}
/**
* Returns the height of an Element from screen y 0
* @return float
*/
public float getAbsoluteHeight() {
return getAbsoluteY() + getHeight();
}
/**
* Stubbed for future use.
*/
public void validateLayout() {
if (getDimensions().x < 1 || getDimensions().y < 1) {
Vector2f dim = getV2fPercentToPixels(getDimensions());
resize(getAbsoluteX()+dim.x, getAbsoluteY()+dim.y, Element.Borders.SE);
}
if (getPosition().x < 1 || getPosition().y < 1) {
Vector2f pos = getV2fPercentToPixels(getPosition());
setPosition(pos.x,pos.y);
}
if (getElementParent() != null)
setY(getElementParent().getHeight()-getHeight()-getY());
else
setY(screen.getHeight()-getHeight()-getY());
for (Element el : elementChildren.values()) {
el.validateLayout();
}
}
/**
* Stubbed for future use.
*/
public void setInitialized() {
this.initialized = true;
}
/**
* Stubbed for future use.
*/
public boolean getInitialized() { return this.initialized; }
/**
* The preferred method for resizing Elements if the resize must effect nested
* Elements as well.
*
* @param x the absolute x coordinate from screen x 0
* @param y the absolute y coordinate from screen y 0
* @param dir The Element.Borders used to determine the direction of the resize event
*/
public void resize(float x, float y, Borders dir) {
float prevWidth = getWidth();
float prevHeight = getHeight();
float oX = x, oY = y;
if (getElementParent() != null) { x -= getAbsoluteX()-getX(); }
if (getElementParent() != null) { y -= getAbsoluteY()-getY(); }
float nextX, nextY;
if (dir == Borders.NW) {
if (getLockToParentBounds()) { if (x <= 0) { x = 0; } }
if (minDimensions != null) {
if (getX()+getWidth()-x <= minDimensions.x) { x = getX()+getWidth()-minDimensions.x; }
}
if (resizeW) {
setWidth(getX()+getWidth()-x);
setX(x);
}
if (getLockToParentBounds()) { if (y <= 0) { y = 0; } }
if (minDimensions != null) {
if (getY()+getHeight()-y <= minDimensions.y) { y = getY()+getHeight()-minDimensions.y; }
}
if (resizeN) {
setHeight(getY()+getHeight()-y);
setY(y);
}
} else if (dir == Borders.N) {
if (getLockToParentBounds()) { if (y <= 0) { y = 0; } }
if (minDimensions != null) {
if (getY()+getHeight()-y <= minDimensions.y) { y = getY()+getHeight()-minDimensions.y; }
}
if (resizeN) {
setHeight(getY()+getHeight()-y);
setY(y);
}
} else if (dir == Borders.NE) {
nextX = oX-getAbsoluteX();
if (getLockToParentBounds()) {
float checkWidth = (getElementParent() == null) ? screen.getWidth() : getElementParent().getWidth();
if (nextX >= checkWidth-getX()) {
nextX = checkWidth-getX();
}
}
if (minDimensions != null) {
if (nextX <= minDimensions.x) { nextX = minDimensions.x; }
}
if (resizeE) {
setWidth(nextX);
}
if (getLockToParentBounds()) { if (y <= 0) { y = 0; } }
if (minDimensions != null) {
if (getY()+getHeight()-y <= minDimensions.y) { y = getY()+getHeight()-minDimensions.y; }
}
if (resizeN) {
setHeight(getY()+getHeight()-y);
setY(y);
}
} else if (dir == Borders.W) {
if (getLockToParentBounds()) { if (x <= 0) { x = 0; } }
if (minDimensions != null) {
if (getX()+getWidth()-x <= minDimensions.x) { x = getX()+getWidth()-minDimensions.x; }
}
if (resizeW) {
setWidth(getX()+getWidth()-x);
setX(x);
}
} else if (dir == Borders.E) {
nextX = oX-getAbsoluteX();
if (getLockToParentBounds()) {
float checkWidth = (getElementParent() == null) ? screen.getWidth() : getElementParent().getWidth();
if (nextX >= checkWidth-getX()) {
nextX = checkWidth-getX();
}
}
if (minDimensions != null) {
if (nextX <= minDimensions.x) { nextX = minDimensions.x; }
}
if (resizeE) {
setWidth(nextX);
}
} else if (dir == Borders.SW) {
if (getLockToParentBounds()) { if (x <= 0) { x = 0; } }
if (minDimensions != null) {
if (getX()+getWidth()-x <= minDimensions.x) { x = getX()+getWidth()-minDimensions.x; }
}
if (resizeW) {
setWidth(getX()+getWidth()-x);
setX(x);
}
nextY = oY-getAbsoluteY();
if (getLockToParentBounds()) {
float checkHeight = (getElementParent() == null) ? screen.getHeight() : getElementParent().getHeight();
if (nextY >= checkHeight-getY()) {
nextY = checkHeight-getY();
}
}
if (minDimensions != null) {
if (nextY <= minDimensions.y) { nextY = minDimensions.y; }
}
if (resizeS) {
setHeight(nextY);
}
} else if (dir == Borders.S) {
nextY = oY-getAbsoluteY();
if (getLockToParentBounds()) {
float checkHeight = (getElementParent() == null) ? screen.getHeight() : getElementParent().getHeight();
if (nextY >= checkHeight-getY()) {
nextY = checkHeight-getY();
}
}
if (minDimensions != null) {
if (nextY <= minDimensions.y) { nextY = minDimensions.y; }
}
if (resizeS) {
setHeight(nextY);
}
} else if (dir == Borders.SE) {
nextX = oX-getAbsoluteX();
if (getLockToParentBounds()) {
float checkWidth = (getElementParent() == null) ? screen.getWidth() : getElementParent().getWidth();
if (nextX >= checkWidth-getX()) {
nextX = checkWidth-getX();
}
}
if (minDimensions != null) {
if (nextX <= minDimensions.x) { nextX = minDimensions.x; }
}
if (resizeE) {
setWidth(nextX);
}
nextY = oY-getAbsoluteY();
if (getLockToParentBounds()) {
float checkHeight = (getElementParent() == null) ? screen.getHeight() : getElementParent().getHeight();
if (nextY >= checkHeight-getY()) {
nextY = checkHeight-getY();
}
}
if (minDimensions != null) {
if (nextY <= minDimensions.y) { nextY = minDimensions.y; }
}
if (resizeS) {
setHeight(nextY);
}
}
float diffX = prevWidth-getWidth();
float diffY = prevHeight-getHeight();
controlResizeHook();
for (Element el : elementChildren.values()) {
el.childResize(diffX,diffY,dir);
el.controlResizeHook();
}
}
// Below are different ideas for implementing minimum dimensions. This will be cleaned up once I decide on the best approach.
/*
private void childResize(float diffX, float diffY, Borders dir) {
if (dir == Borders.N) {
// if (dockS && scaleNS) {
// if (minDimensions == null) {
// setHeight(getHeight()-diffY);
// } else if (getHeight()-diffY > minDimensions.y) {
// setHeight(getHeight()-diffY);
// } else {
// setHeight(minDimensions.y);
// }
// }
} else if (dir == Borders.S) {
if (dockS && scaleNS) {
if (minDimensions == null) {
setHeight(getHeight()-diffY);
} else {
float cY = getElementParent().getHeight()-(getElementParent().getHeight()-orgPosition.y);
if (getY() < cY) setHeight(minDimensions.y);
else setHeight(getHeight()-diffY);
if (getHeight() > minDimensions.y) setY(cY);
else setY(getY()-diffY);
}
} else
setY(getY()-diffY);
}
if (dir == Borders.W) {
if (dockE) {
}
} else if (dir == Borders.E) {
if (dockW) {
}
}
Set<String> keys = elementChildren.keySet();
for (String key : keys) {
elementChildren.get(key).childResize(diffX,diffY,dir);
}
}
*/
/*
private void childResize(float diffX, float diffY, Borders dir) {
if (getElementParent().getDimensions().y > getElementParent().getOrgDimensions().y) {
if (dir == Borders.NW || dir == Borders.N || dir == Borders.NE) {
if (getScaleNS()) { if (getHeight()-diffY > minDimensions.y) { setHeight(getHeight()-diffY); } }
// if (getScaleNS()) setHeight(getHeight()-diffY);
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
} else if (dir == Borders.SW || dir == Borders.S || dir == Borders.SE) {
if (getScaleNS()) { if (getHeight()-diffY > minDimensions.y) { setHeight(getHeight()-diffY); } }
// if (getScaleNS()) setHeight(getHeight()-diffY);
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
}
} else {
setHeight(getOrgDimensions().y);
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
}
if (getElementParent().getDimensions().x > getElementParent().getOrgDimensions().x) {
if (dir == Borders.NW || dir == Borders.W || dir == Borders.SW) {
if (getScaleEW()) { if (getWidth()-diffX > minDimensions.x) { setWidth(getWidth()-diffX); } }
// if (getScaleEW()) setWidth(getWidth()-diffX);
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
} else if (dir == Borders.NE || dir == Borders.E || dir == Borders.SE) {
if (getScaleEW()) { if (getWidth()-diffX > minDimensions.x) { setWidth(getWidth()-diffX); } }
// if (getScaleEW()) setWidth(getWidth()-diffX);
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
}
} else {
setWidth(getOrgDimensions().x);
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
}
for (Element el : elementChildren.values()) {
el.childResize(diffX,diffY,dir);
el.controlResizeHook();
}
}
*/
private void childResize(float diffX, float diffY, Borders dir) {
if (dir == Borders.NW || dir == Borders.N || dir == Borders.NE) {
if (getScaleNS()) setHeight(getHeight()-diffY);
if ((getDocking() == Docking.NW || getDocking() == Docking.NE) && !getScaleNS()) setY(getY()-diffY);
} else if (dir == Borders.SW || dir == Borders.S || dir == Borders.SE) {
if (getScaleNS()) setHeight(getHeight()-diffY);
if ((getDocking() == Docking.NW || getDocking() == Docking.NE) && !getScaleNS()) setY(getY()-diffY);
}
if (dir == Borders.NW || dir == Borders.W || dir == Borders.SW) {
if (getScaleEW()) setWidth(getWidth()-diffX);
if ((getDocking() == Docking.NE || getDocking() == Docking.SE) && !getScaleEW()) setX(getX()-diffX);
} else if (dir == Borders.NE || dir == Borders.E || dir == Borders.SE) {
if (getScaleEW()) setWidth(getWidth()-diffX);
if ((getDocking() == Docking.NE || getDocking() == Docking.SE) && !getScaleEW()) setX(getX()-diffX);
}
for (Element el : elementChildren.values()) {
el.childResize(diffX,diffY,dir);
el.controlResizeHook();
}
}
/*
private void childResize(float diffX, float diffY, Borders dir) {
if (getUID().equals("FirstName")) { System.out.println(orgRelDimensions); }
if (dir == Borders.NW || dir == Borders.N || dir == Borders.NE) {
if (getElementParent().getHeight()*orgRelDimensions.y > minDimensions.y) {
if (getScaleNS()) setHeight(getElementParent().getHeight()*orgRelDimensions.y);//getHeight()-diffY);
} else {
if (getScaleNS()) setHeight(orgDimensions.y);
}
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
} else if (dir == Borders.SW || dir == Borders.S || dir == Borders.SE) {
if (getElementParent().getHeight()*orgRelDimensions.y > minDimensions.y) {
if (getScaleNS()) setHeight(getElementParent().getHeight()*orgRelDimensions.y);//getHeight()-diffY);
} else {
if (getScaleNS()) setHeight(orgDimensions.y);
}
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
}
if (dir == Borders.NW || dir == Borders.W || dir == Borders.SW) {
if (getElementParent().getWidth()*orgRelDimensions.x > minDimensions.x) {
if (getScaleEW()) setWidth(getElementParent().getWidth()*orgRelDimensions.x);//getWidth()-diffX);
} else {
if (getScaleEW()) setWidth(orgDimensions.x);
}
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
} else if (dir == Borders.NE || dir == Borders.E || dir == Borders.SE) {
if (getElementParent().getWidth()*orgRelDimensions.x > minDimensions.x) {
if (getScaleEW()) setWidth(getElementParent().getWidth()*orgRelDimensions.x);//getWidth()-diffX);
} else {
if (getScaleEW()) setWidth(orgDimensions.x);
}
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
}
for (Element el : elementChildren.values()) {
el.childResize(diffX,diffY,dir);
el.controlResizeHook();
}
}
*/
/**
* Overridable method for extending the resize event
*/
public void controlResizeHook() {
}
public void sizeToContent() {
float innerX = 10000, innerY = 10000, innerW = -10000, innerH = -10000;
float currentHeight = getHeight();
Map<Element,Float> newY = new HashMap();
for (Element child : elementChildren.values()) {
float x = child.getX();
float y = currentHeight-(child.getY()+child.getHeight());
float w = child.getX()+child.getWidth();
float h = currentHeight-child.getY();
if (x < innerX) innerX = x;
if (y < innerY) innerY = y;
if (w > innerW) innerW = w;
if (h > innerH) innerH = h;
newY.put(child, h);
}
this.setDimensions(innerW+innerX, innerH+innerY);
for (Element child : elementChildren.values()) {
float diff = newY.get(child);
child.setY(innerH-(diff-innerY));
}
}
/**
* Moves the Element to the specified coordinates
* @param x The new x screen coordinate of the Element
* @param y The new y screen coordinate of the Element
*/
public void moveTo(float x, float y) {
if (getLockToParentBounds()) {
if (x < 0) { x = 0; }
if (y < 0) { y = 0; }
if (getElementParent() != null) {
if (x > getElementParent().getWidth()-getWidth()) {
x = getElementParent().getWidth()-getWidth();
}
if (y > getElementParent().getHeight()-getHeight()) {
y = getElementParent().getHeight()-getHeight();
}
} else {
if (x > screen.getWidth()-getWidth()) {
x = screen.getWidth()-getWidth();
}
if (y > screen.getHeight()-getHeight()) {
y = screen.getHeight()-getHeight();
}
}
}
setX(x);
setY(y);
controlMoveHook();
}
/**
* Overridable method for extending the move event
*/
public void controlMoveHook() {
}
/**
* Centers the Element to it's parent Element. If the parent element is null, it will use the screen's width/height.
*/
public void centerToParent() {
if (elementParent == null) {
setPosition(screen.getWidth()/2-(getWidth()/2),screen.getHeight()/2-(getHeight()/2));
} else {
setPosition(elementParent.getWidth()/2-(getWidth()/2),elementParent.getHeight()/2-(getHeight()/2));
}
}
/**
* Set the north, west, east and south borders in number of pixels
* @param borderSize
*/
public void setResizeBorders(float borderSize) {
borders.set(borderSize,borderSize,borderSize,borderSize);
}
/**
* Set the north, west, east and south borders in number of pixels
* @param nBorder float
* @param wBorder float
* @param eBorder float
* @param sBorder float
*/
public void setResizeBorders(float nBorder, float wBorder, float eBorder, float sBorder) {
borders.setX(nBorder);
borders.setY(wBorder);
borders.setZ(eBorder);
borders.setW(sBorder);
}
/**
* Sets the width of north border in number of pixels
* @param nBorder float
*/
public void setNorthResizeBorder(float nBorder) {
borders.setX(nBorder);
}
/**
* Sets the width of west border in number of pixels
* @param wBorder float
*/
public void setWestResizeBorder(float wBorder) {
borders.setY(wBorder);
}
/**
* Sets the width of east border in number of pixels
* @param eBorder float
*/
public void setEastResizeBorder(float eBorder) {
borders.setZ(eBorder);
}
/**
* Sets the width of south border in number of pixels
* @param sBorder float
*/
public void setSouthResizeBorder(float sBorder) {
borders.setW(sBorder);
}
/**
* Returns the height of the north resize border
*
* @return float
*/
public float getResizeBorderNorthSize() {
return this.borderHandles.x;
}
/**
* Returns the width of the west resize border
*
* @return float
*/
public float getResizeBorderWestSize() {
return this.borderHandles.y;
}
/**
* Returns the width of the east resize border
*
* @return float
*/
public float getResizeBorderEastSize() {
return this.borderHandles.z;
}
/**
* Returns the height of the south resize border
*
* @return float
*/
public float getResizeBorderSouthSize() {
return this.borderHandles.w;
}
/**
* Returns the default material for the element
* @param mat
*/
public void setElementMaterial(Material mat) {
this.mat = mat;
}
/**
* Returns a pointer to the Material used for rendering this Element.
*
* @return Material mat
*/
public Material getElementMaterial() {
return this.mat;
}
/**
* Returns the default Texture for the Element
*
* @return Texture defaultTexture
*/
public Texture getElementTexture() {
return this.defaultTex;
}
/**
* Returns a pointer to the custom mesh used to render the Element.
*
* @return ElementGridQuad model
*/
public ElementQuadGrid getModel() {
return this.model;
}
/**
* Returns the Element's Geometry.
* @return
*/
public Geometry getGeometry() {
return this.geom;
}
// Font & text
/**
* Sets the element's text layer font
* @param fontPath String The font asset path
*/
public void setFont(String fontPath) {
font = app.getAssetManager().loadFont(fontPath);
if (textElement != null) {
String text = this.getText();
textElement.removeFromParent();
textElement = null;
setText(text);
}
}
/**
* Returns the Bitmapfont used by the element's text layer
* @return BitmapFont font
*/
public BitmapFont getFont() {
return this.font;
}
/**
* Sets the element's text layer font size
* @param fontSize float The size to set the font to
*/
public void setFontSize(float fontSize) {
this.fontSize = fontSize;
if (textElement != null) {
textElement.setSize(fontSize);
}
}
/**
* Returns the element's text layer font size
* @return float fontSize
*/
public float getFontSize() {
return this.fontSize;
}
/**
* Sets the element's text layer font color
* @param fontColor ColorRGBA The color to set the font to
*/
public void setFontColor(ColorRGBA fontColor) {
this.fontColor = fontColor;
if (textElement != null) {
textElement.setColor(fontColor);
}
}
/**
* Return the element's text layer font color
* @return ColorRGBA fontColor
*/
public ColorRGBA getFontColor() {
return this.fontColor;
}
/**
* Sets the element's text layer horizontal alignment
*
* @param textAlign
*/
public void setTextAlign(BitmapFont.Align textAlign) {
this.textAlign = textAlign;
if (textElement != null) {
textElement.setAlignment(textAlign);
}
}
/**
* Returns the element's text layer horizontal alignment
* @return Align text Align
*/
public BitmapFont.Align getTextAlign() {
return this.textAlign;
}
/**
* Sets the element's text layer vertical alignment
*
* @param textVAlign
*/
public void setTextVAlign(BitmapFont.VAlign textVAlign) {
this.textVAlign = textVAlign;
if (textElement != null) {
textElement.setVerticalAlignment(textVAlign);
}
}
/**
* Returns the element's text layer vertical alignment
* @return VAlign textVAlign
*/
public BitmapFont.VAlign getTextVAlign() {
return this.textVAlign;
}
/**
* Sets the element's text later wrap mode
* @param textWrap LineWrapMode textWrap
*/
public void setTextWrap(LineWrapMode textWrap) {
this.textWrap = textWrap;
if (textElement != null) {
textElement.setLineWrapMode(textWrap);
}
}
/**
* Returns the element's text layer wrap mode
* @return LineWrapMode textWrap
*/
public LineWrapMode getTextWrap() {
return this.textWrap;
}
/**
* Sets the elements text layer position
* @param x Position's x coord
* @param y Position's y coord
*/
public void setTextPosition(float x, float y) {
this.textPosition = new Vector2f(x,y);
}
/**
* Returns the current x, y coords of the element's text layer
* @return Vector2f textPosition
*/
public Vector2f getTextPosition() {
return this.textPosition;
}
/**
* Sets the padding set for the element's text layer
* @param textPadding
*/
public void setTextPadding(float textPadding) {
this.textPadding = textPadding;
}
/**
* Returns the ammount of padding set for the elements text layer
* @return float textPadding
*/
public float getTextPadding() {
return this.textPadding;
}
/**
* Updates the element's textlayer position and boundary
*/
protected void updateTextElement() {
if (textElement != null) {
textElement.setLocalTranslation(textPosition.x+textPadding, getHeight()-(textPosition.y+textPadding), textElement.getLocalTranslation().z);
textElement.setBox(new Rectangle(0,0,dimensions.x-(textPadding*2),dimensions.y-(textPadding*2)));
// textElement.setPosition(textPadding, textPadding);
// textElement.setDimensions(dimensions.x-(textPadding*2),dimensions.y-(textPadding*2));
// textElement.controlResizeHook();
// textElement.updateAnimText(0);
}
}
/**
* Sets the text of the element.
* @param text String The text to display.
*/
public void setText(String text) {
this.text = text;
if (textElement == null) {
textElement = new BitmapText(font, false);
textElement.setBox(new Rectangle(0,0,dimensions.x,dimensions.y));
// textElement = new TextElement(screen, Vector2f.ZERO, getDimensions());
}
textElement.setLineWrapMode(textWrap);
textElement.setAlignment(textAlign);
textElement.setVerticalAlignment(textVAlign);
textElement.setSize(fontSize);
textElement.setColor(fontColor);
textElement.setText(text);
updateTextElement();
if (textElement.getParent() == null) {
this.attachChild(textElement);
}
}
/**
* Retuns the current visible text of the element.
* @return String text
*/
public String getText() {
return this.text;
}
/**
* Returns a pointer to the BitmapText element of this Element. Returns null
* if setText() has not been called.
*
* @return BitmapText textElement
*/
public BitmapText getTextElement() {
// public TextElement getTextElement() {
return this.textElement;
}
// Clipping
/**
* Adds an alpha map to the Elements material
* @param alphaMap A String path to the alpha map
*/
public void setAlphaMap(String alphaMap) {
Texture alpha = null;
if (screen.getUseTextureAtlas()) {
if (this.getElementTexture() != null) alpha = getElementTexture();
else alpha = screen.getAtlasTexture();
Vector2f alphaOffset = getAtlasTextureOffset(screen.parseAtlasCoords(alphaMap));
mat.setVector2("OffsetAlphaTexCoord", alphaOffset);
} else {
alpha = app.getAssetManager().loadTexture(alphaMap);
alpha.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
alpha.setMagFilter(Texture.MagFilter.Nearest);
alpha.setWrap(Texture.WrapMode.Clamp);
}
this.alphaMap = alpha;
if (defaultTex == null) {
if (!screen.getUseTextureAtlas()) {
float imgWidth = alpha.getImage().getWidth();
float imgHeight = alpha.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
this.model = new ElementQuadGrid(this.dimensions, borders, imgWidth, imgHeight, pixelWidth, pixelHeight, 0, 0, imgWidth, imgHeight);
geom.setMesh(model);
} else {
float[] coords = screen.parseAtlasCoords(alphaMap);
float textureAtlasX = coords[0];
float textureAtlasY = coords[1];
float textureAtlasW = coords[2];
float textureAtlasH = coords[3];
float imgWidth = alpha.getImage().getWidth();
float imgHeight = alpha.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
model = new ElementQuadGrid(this.getDimensions(), borders, imgWidth, imgHeight, pixelWidth, pixelHeight, textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
geom.setMesh(model);
mat.setVector2("OffsetAlphaTexCoord", new Vector2f(0,0));
}
}
mat.setTexture("AlphaMap", alpha);
}
public Texture getAlphaMap() {
return this.alphaMap;
}
public void setColorMap(String colorMap) {
Texture color = null;
if (screen.getUseTextureAtlas()) {
if (this.getElementTexture() != null) color = getElementTexture();
else color = screen.getAtlasTexture();
} else {
color = app.getAssetManager().loadTexture(colorMap);
color.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
color.setMagFilter(Texture.MagFilter.Nearest);
color.setWrap(Texture.WrapMode.Clamp);
}
this.defaultTex = color;
if (!screen.getUseTextureAtlas()) {
float imgWidth = color.getImage().getWidth();
float imgHeight = color.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
this.model = new ElementQuadGrid(this.dimensions, borders, imgWidth, imgHeight, pixelWidth, pixelHeight, 0, 0, imgWidth, imgHeight);
geom.setMesh(model);
} else {
float[] coords = screen.parseAtlasCoords(colorMap);
float textureAtlasX = coords[0];
float textureAtlasY = coords[1];
float textureAtlasW = coords[2];
float textureAtlasH = coords[3];
float imgWidth = color.getImage().getWidth();
float imgHeight = color.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
model = new ElementQuadGrid(this.getDimensions(), borders, imgWidth, imgHeight, pixelWidth, pixelHeight, textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
geom.setMesh(model);
}
mat.setTexture("ColorMap", color);
mat.setColor("Color", ColorRGBA.White);
}
/**
* This may be remove soon and probably should not be used as the method of handling
* hide show was updated making this unnecissary.
*
* @param wasVisible boolean
*/
public void setDefaultWasVisible(boolean wasVisible) {
this.wasVisible = wasVisible;
}
/**
* Shows the current Element with the defined Show effect. If no Show effect is defined, the Element will show as normal.
*/
public void showWithEffect() {
Effect effect = getEffect(Effect.EffectEvent.Show);
if (effect != null) {
if (effect.getEffectType() == Effect.EffectType.FadeIn) {
Effect clone = effect.clone();
clone.setAudioFile(null);
this.propagateEffect(clone, false);
} else {
if (getTextElement() != null)
getTextElement().setAlpha(1f);
screen.getEffectManager().applyEffect(effect);
}
} else
this.show();
}
/**
* Sets this Element and any Element contained within it's nesting order to visible.
*
* NOTE: Hide and Show relies on shader-based clipping
*/
public void show() {
if (!isVisible) {
screen.updateZOrder(getAbsoluteParent());
this.isVisible = true;
this.isClipped = wasClipped;
updateClipping();
controlShowHook();
if (getTextElement() != null)
getTextElement().setAlpha(1f);
if (getParent() == null) {
if (getElementParent() != null) {
getElementParent().attachChild(this);
} else {
screen.getGUINode().attachChild(this);
}
}
for (Element el : elementChildren.values()) {
el.childShow();
}
}
}
public void showAsModal(boolean showWithEffect) {
isVisibleAsModal = true;
screen.showAsModal(this,showWithEffect);
}
/**
* Recursive call for properly showing children of the Element. I'm thinking this
* this needs to be a private method, however I need to verify this before I
* update it.
*/
public void childShow() {
if (getTextElement() != null)
getTextElement().setAlpha(1f);
this.isVisible = wasVisible;
this.isClipped = wasClipped;
updateClipping();
controlShowHook();
for (Element el : elementChildren.values()) {
el.childShow();
}
}
/**
* An overridable method for extending the show event.
*/
public void controlShowHook() { }
/**
* Hides the element using the current defined Hide effect. If no Hide effect is defined, the Element will hide as usual.
*/
public void hideWithEffect() {
Effect effect = getEffect(Effect.EffectEvent.Hide);
if (effect != null) {
if (effect.getEffectType() == Effect.EffectType.FadeOut) {
Effect clone = effect.clone();
clone.setAudioFile(null);
this.propagateEffect(clone, true);
} else
screen.getEffectManager().applyEffect(effect);
if (isVisibleAsModal) {
isVisibleAsModal = false;
screen.hideModalBackground();
}
} else
this.hide();
}
/**
* Recursive call that sets this Element and any Element contained within it's
* nesting order to hidden.
*
* NOTE: Hide and Show relies on shader-based clipping
*/
public void hide() {
if (isVisible) {
if (isVisibleAsModal) {
isVisibleAsModal = false;
screen.hideModalBackground();
}
this.wasVisible = isVisible;
this.isVisible = false;
this.isClipped = true;
}
updateClipping();
controlHideHook();
removeFromParent();
for (Element el : elementChildren.values()) {
el.childHide();
}
}
/**
* For internal use. This method should never be called directly.
*/
public void childHide() {
if (isVisible) {
this.wasVisible = isVisible;
this.isVisible = false;
this.isClipped = true;
}
updateClipping();
controlHideHook();
for (Element el : elementChildren.values()) {
el.childHide();
}
}
/**
* Hides or shows the element (true = show, false = hide)
* @param visibleState
*/
public void setIsVisible(boolean visibleState) {
if (visibleState) {
show();
} else {
hide();
}
}
/**
* Toggles the Element's visibility based on the current state.
*/
public void setIsVisible() {
if (getIsVisible()) hide();
else show();
}
/**
* An overridable method for extending the hide event.
*/
public void controlHideHook() { }
public void cleanup() {
controlCleanupHook();
for (Element el : elementChildren.values()) {
el.cleanup();
}
}
/**
* An overridable method for handling control specific cleanup.
*/
public void controlCleanupHook() { }
/**
* For internal use only - DO NOT CALL THIS METHOD
* @param effect Effect
* @param callHide boolean
*/
public void propagateEffect(Effect effect, boolean callHide) {
Effect nEffect = effect.clone();
nEffect.setCallHide(callHide);
nEffect.setElement(this);
screen.getEffectManager().applyEffect(nEffect);
for (Element el : elementChildren.values()) {
el.propagateEffect(effect, false);
}
}
/**
* Return if the Element is visible
*
* @return boolean isVisible
*/
public boolean getIsVisible() {
return this.isVisible;
}
/**
* Sets the elements clipping layer to the provided element.
* @param clippingLayer The element that provides the clipping boundaries.
*/
public void setClippingLayer(Element clippingLayer) {
if (clippingLayer != null) {
this.isClipped = true;
this.wasClipped = true;
this.clippingLayer = clippingLayer;
this.mat.setBoolean("UseClipping", true);
} else {
this.isClipped = false;
this.wasClipped = false;
this.clippingLayer = null;
this.mat.setBoolean("UseClipping", false);
}
}
/**
* Recursive update of all child Elements clipping layer
* @param clippingLayer The clipping layer to apply
*/
public void setControlClippingLayer(Element clippingLayer) {
setClippingLayer(clippingLayer);
for (Element el : elementChildren.values()) {
el.setControlClippingLayer(clippingLayer);
}
}
/**
* Returns if the Element's clipping layer has been set
*
* @return boolean isClipped
*/
public boolean getIsClipped() {
return isClipped;
}
/**
* Returns the elements clipping layer or null is element doesn't use clipping
* @return Element clippingLayer
*/
public Element getClippingLayer() {
return this.clippingLayer;
}
/**
* Returns a Vector4f containing the current boundaries of the element's clipping layer
* @return Vector4f clippingBounds
*/
public Vector4f getClippingBounds() {
return this.clippingBounds;
}
/**
* Adds a padding to the clippinglayer, in effect this contracts the size of the clipping
* bounds by the specified number of pixels
* @param clipPadding The number of pixels to pad the clipping area
*/
public void setClipPadding(float clipPadding) {
this.clipPadding = clipPadding;
}
/**
* Returns the current clipPadding
* @return float clipPadding
*/
public float getClipPadding() {
return clipPadding;
}
/**
* Updates the clipping bounds for any element that has a clipping layer
*
* See updateLocalClipping
*/
public void updateClipping() {
updateLocalClipping();
for (Element el : elementChildren.values()) {
el.updateClipping();
}
}
/**
* Updates the clipping bounds for any element that has a clipping layer
*/
public void updateLocalClipping() {
if (isVisible) {
if (clippingLayer != null) {
float cPadding = 0;
if (clippingLayer != this)
cPadding = clippingLayer.getClipPadding();
clippingBounds.set(
clippingLayer.getAbsoluteX()+cPadding,
clippingLayer.getAbsoluteY()+cPadding,
clippingLayer.getAbsoluteWidth()-cPadding,
clippingLayer.getAbsoluteHeight()-cPadding
);
mat.setVector4("Clipping", clippingBounds);
mat.setBoolean("UseClipping", true);
} else {
mat.setBoolean("UseClipping", false);
}
} else {
clippingBounds.set(0,0,0,0);
mat.setVector4("Clipping", clippingBounds);
mat.setBoolean("UseClipping", true);
}
setFontPages();
}
/**
* Shrinks the clipping area by set number of pixels
*
* @param textClipPadding The number of pixels to pad the clipping area with on each side
*/
public void setTextClipPadding(float textClipPadding) {
this.textClipPadding = textClipPadding;
}
/**
* Updates font materials with any changes to clipping layers
*/
private void setFontPages() {
if (textElement != null) {
if (!isVisible) {
for (int i = 0; i < font.getPageSize(); i++) {
this.font.getPage(i).setVector4("Clipping", clippingBounds);
this.font.getPage(i).setBoolean("UseClipping", true);
}
} else {
if (isClipped) {
for (int i = 0; i < font.getPageSize(); i++) {
this.font.getPage(i).setVector4("Clipping", clippingBounds.add(textClipPadding, textClipPadding, -textClipPadding, -textClipPadding));
this.font.getPage(i).setBoolean("UseClipping", true);
}
} else {
for (int i = 0; i < font.getPageSize(); i++) {
this.font.getPage(i).setBoolean("UseClipping", false);
}
}
}
}
}
// Effects
/**
* Associates an Effect with this Element. Effects are not automatically associated
* with the specified event, but instead, the event type is used to retrieve the Effect
* at a later point
*
* @param effectEvent The Effect.EffectEvent the Effect is to be registered with
* @param effect The Effect to store
*/
public void addEffect(Effect.EffectEvent effectEvent, Effect effect) {
addEffect(effect);
}
/**
* Associates an Effect with this Element. Effects are not automatically associated
* with the specified event, but instead, the event type is used to retrieve the Effect
* at a later point
*
* @param effect The Effect to store
*/
public void addEffect(Effect effect) {
effects.remove(effect.getEffectEvent());
if (!effects.containsKey(effect.getEffectEvent())) {
effect.setElement(this);
effects.put(effect.getEffectEvent(), effect);
}
}
/**
* Removes the Effect associated with the Effect.EffectEvent specified
* @param effectEvent
*/
public void removeEffect(Effect.EffectEvent effectEvent) {
effects.remove(effectEvent);
}
/**
* Retrieves the Effect associated with the specified Effect.EffectEvent
*
* @param effectEvent
* @return effect
*/
public Effect getEffect(Effect.EffectEvent effectEvent) {
Effect effect = null;
if (effects.get(effectEvent) != null)
effect = effects.get(effectEvent).clone();
return effect;
}
/**
* Called by controls during construction to prepopulate effects based on Styles.
*
* @param styleName The String identifier of the Style
*/
protected void populateEffects(String styleName) {
int index = 0;
Effect effect;
while ((effect = screen.getStyle(styleName).getEffect("event" + index)) != null) {
effect = effect.clone();
effect.setElement(this);
this.addEffect(effect);
index++;
}
}
/**
* Overrides the screen global alpha with the specified value. setIngoreGlobalAlpha must be enabled prior to calling this method.
* @param globalAlpha
*/
public void setGlobalAlpha(float globalAlpha) {
if (!ignoreGlobalAlpha) {
getElementMaterial().setFloat("GlobalAlpha", globalAlpha);
for (Element el : elementChildren.values()) {
el.setGlobalAlpha(globalAlpha);
}
} else {
getElementMaterial().setFloat("GlobalAlpha", 1);
}
}
/**
* Will enable or disable the use of the screen defined global alpha setting.
* @param ignoreGlobalAlpha
*/
public void setIgnoreGlobalAlpha(boolean ignoreGlobalAlpha) {
this.ignoreGlobalAlpha = ignoreGlobalAlpha;
}
// Tab focus
/**
* For use by the Form control (Do not call this method directly)
* @param form The form the Element has been added to
*/
public void setForm(Form form) {
this.form = form;
}
/**
* Returns the form the Element is controlled by
* @return Form form
*/
public Form getForm() {
return this.form;
}
/**
* Sets the tab index (This is assigned by the Form control. Do not call this method directly)
* @param tabIndex The tab index assigned to the Element
*/
public void setTabIndex(int tabIndex) {
this.tabIndex = tabIndex;
}
/**
* Returns the tab index assigned by the Form control
* @return tabIndex
*/
public int getTabIndex() {
return tabIndex;
}
// Off Screen Rendering Bridge
public void addOSRBridge(OSRBridge bridge) {
this.bridge = bridge;
addControl(bridge);
getElementMaterial().setTexture("ColorMap", bridge.getTexture());
getElementMaterial().setColor("Color", ColorRGBA.White);
}
// Tool Tip
/**
* Sets the Element's ToolTip text
* @param toolTip String
*/
public void setToolTipText(String toolTip) {
this.toolTipText = toolTip;
}
/**
* Returns the Element's current ToolTip text
* @return String
*/
public String getToolTipText() {
return toolTipText;
}
/**
* For internal use - DO NOT CALL THIS METHOD
* @param hasFocus boolean
*/
public void setHasFocus(boolean hasFocus) {
this.hasFocus = hasFocus;
}
/**
* Returns if the Element currently has input focus
* @return
*/
public boolean getHasFocus() {
return this.hasFocus;
}
public void setResetKeyboardFocus(boolean resetKeyboardFocus) {
this.resetKeyboardFocus = resetKeyboardFocus;
}
public boolean getResetKeyboardFocus() { return this.resetKeyboardFocus; }
// Modal
/**
* Enables standard modal mode for the Element.
* @param isModal
*/
public void setIsModal(boolean isModal) {
this.isModal = isModal;
}
/**
* Returns if the Element is currently modal
* @return Ret
*/
public boolean getIsModal() {
return this.isModal;
}
/**
* For internal use - DO NOT CALL THIS METHOD
* @param hasFocus boolean
*/
public void setIsGlobalModal(boolean isGlobalModal) {
this.isGlobalModal = isGlobalModal;
}
/**
* For internal use - DO NOT CALL THIS METHOD
* @param hasFocus boolean
*/
public boolean getIsGlobalModal() {
return this.isGlobalModal;
}
// User data
/**
* Stores provided data with the Element
* @param elementUserData Object Data to store
*/
public void setElementUserData(Object elementUserData) {
this.elementUserData = elementUserData;
}
/**
* Returns the data stored with this Element
* @return Object
*/
public Object getElementUserData() {
return this.elementUserData;
}
Vector2f origin = new Vector2f(0,0);
/**
* Stubbed for future use
* @param originX
* @param originY
*/
public void setOrigin(float originX, float originY) {
origin.set(originX, originY);
}
/**
* Stubbed for future use.
* @return
*/
public Vector2f getOrigin() {
return this.origin;
}
}
| src/tonegod/gui/core/Element.java | package tonegod.gui.core;
import com.jme3.app.Application;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.font.LineWrapMode;
import com.jme3.font.Rectangle;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector4f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.texture.Texture;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import tonegod.gui.controls.extras.DragElement;
import tonegod.gui.controls.form.Form;
import tonegod.gui.controls.text.TextElement;
import tonegod.gui.core.utils.UIDUtil;
import tonegod.gui.effects.Effect;
/**
*
* @author t0neg0d
*/
public class Element extends Node {
public static enum Borders {
NW,
N,
NE,
W,
E,
SW,
S,
SE;
};
/**
* Some controls provide different layout's based on the orientation of the control
*/
public static enum Orientation {
/**
* Vertical layout
*/
VERTICAL,
/**
* Horizontal layout
*/
HORIZONTAL
}
/**
* Defines how the element will dock to it's parent element during resize events
*/
public static enum Docking {
/**
* Docks to the top left of parent
*/
NW,
/**
* Docks to the top right of parent
*/
NE,
/**
* Docks to the bottom left of parent
*/
SW,
/**
* Docks to the bottom right of parent
*/
SE
}
protected Application app;
protected ElementManager screen;
private String UID;
private Vector2f position = new Vector2f();
public Vector2f orgPosition;
private Vector2f dimensions = new Vector2f();
public Vector2f orgDimensions, orgRelDimensions;
public Vector4f borders = new Vector4f(1,1,1,1);
public Vector4f borderHandles = new Vector4f(12,12,12,12);
private Vector2f minDimensions = new Vector2f(10, 10);
private boolean ignoreMouse = false;
protected boolean isMovable = false;
private boolean lockToParentBounds = false;
private boolean isResizable = false;
private boolean resizeN = true;
private boolean resizeS = true;
private boolean resizeW = true;
private boolean resizeE = true;
private boolean dockN = false;
private boolean dockW = true;
private boolean dockE = false;
private boolean dockS = true;
private boolean scaleNS = true;
private boolean scaleEW = true;
private boolean effectParent = false;
private boolean effectAbsoluteParent = false;
private Geometry geom;
private ElementQuadGrid model;
private boolean tileImage = false;
private Material mat;
private Texture defaultTex;
private boolean useLocalAtlas = false;
private String atlasCoords = "";
private Texture alphaMap = null;
protected BitmapText textElement;
// protected TextElement textElement;
protected Vector2f textPosition = new Vector2f(0,0);
protected LineWrapMode textWrap = LineWrapMode.Word;
protected BitmapFont.Align textAlign = BitmapFont.Align.Left;
protected BitmapFont.VAlign textVAlign = BitmapFont.VAlign.Top;
protected String text = "";
private String toolTipText = null;
protected BitmapFont font;
protected float fontSize = 20;
protected float textPadding = 0;
protected ColorRGBA fontColor = ColorRGBA.White;
private ColorRGBA defaultColor = new ColorRGBA(1,1,1,0);
private Element elementParent = null;
protected Map<String, Element> elementChildren = new LinkedHashMap();
protected boolean isClipped = false;
protected boolean wasClipped = false;
private Element clippingLayer;
private Vector4f clippingBounds = new Vector4f();
private float clipPadding = 0;
private float textClipPadding = 0;
protected boolean isVisible = true;
protected boolean wasVisible = true;
protected boolean isVisibleAsModal = false;
private boolean hasFocus = false;
private boolean resetKeyboardFocus = true;
private Form form;
private int tabIndex = 0;
private float zOrder;
private boolean effectZOrder = true;
private Map<Effect.EffectEvent, Effect> effects = new HashMap();
private OSRBridge bridge;
private boolean ignoreGlobalAlpha = false;
private boolean isModal = false;
private boolean isGlobalModal = false;
private Object elementUserData;
private boolean initialized = false;
private boolean isDragElement = false, isDropElement = false;
private Docking docking = Docking.NW;
private Orientation orientation = Orientation.HORIZONTAL;
/**
* The Element class is the single primitive for all controls in the gui library.
* Each element consists of an ElementQuadMesh for rendering resizable textures,
* as well as a BitmapText element if setText(String text) is called.
*
* Behaviors, such as movement and resizing, are common to all elements and can
* be enabled/disabled to ensure the element reacts to user input as needed.
*
* @param screen The Screen control the element or it's absolute parent element is being added to
* @param UID A unique String identifier used when looking up elements by screen.getElementByID()
* @param position A Vector2f containing the x/y coordinates (relative to it's parent elements x/y) for positioning
* @param dimensions A Vector2f containing the dimensions of the element, x being width, y being height
* @param resizeBorders A Vector4f containing the size of each border used for scaling images without distorting them (x = N, y = W, x = E, w = S)
* @param texturePath A String path to the default image to be rendered on the element's mesh
*/
public Element(ElementManager screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String texturePath) {
this.app = screen.getApplication();
this.screen = screen;
if (UID == null) {
this.UID = UIDUtil.getUID();
} else {
this.UID = UID;
}
this.position.set(position);
this.dimensions.set(dimensions);
this.orgDimensions = dimensions.clone();
this.orgRelDimensions = new Vector2f(1,1);
this.borders.set(resizeBorders);
BitmapFont tempFont = app.getAssetManager().loadFont(screen.getStyle("Font").getString("defaultFont"));
font = new BitmapFont();
font.setCharSet(app.getAssetManager().loadFont(screen.getStyle("Font").getString("defaultFont")).getCharSet());
Material[] pages = new Material[tempFont.getPageSize()];
for (int i = 0; i < pages.length; i++) {
pages[i] = tempFont.getPage(i).clone();
}
font.setPages(pages);
float imgWidth = 100;
float imgHeight = 100;
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
float textureAtlasX = 0, textureAtlasY = 0, textureAtlasW = imgWidth, textureAtlasH = imgHeight;
boolean useAtlas = screen.getUseTextureAtlas();
if (texturePath != null) {
if (useAtlas) {
float[] coords = screen.parseAtlasCoords(texturePath);
textureAtlasX = coords[0];
textureAtlasY = coords[1];
textureAtlasW = coords[2];
textureAtlasH = coords[3];
this.atlasCoords = "x=" + coords[0] + "|y=" + coords[1] + "|w=" + coords[2] + "|h=" + coords[3];
defaultTex = screen.getAtlasTexture();
imgWidth = defaultTex.getImage().getWidth();
imgHeight = defaultTex.getImage().getHeight();
pixelWidth = 1f/imgWidth;
pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
} else {
defaultTex = app.getAssetManager().loadTexture(texturePath);
defaultTex.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
defaultTex.setMagFilter(Texture.MagFilter.Nearest);
defaultTex.setWrap(Texture.WrapMode.Clamp);
imgWidth = defaultTex.getImage().getWidth();
imgHeight = defaultTex.getImage().getHeight();
pixelWidth = 1f/imgWidth;
pixelHeight = 1f/imgHeight;
textureAtlasW = imgWidth;
textureAtlasH = imgHeight;
}
}
mat = new Material(app.getAssetManager(), "tonegod/gui/shaders/Unshaded.j3md");
if (texturePath != null) {
mat.setTexture("ColorMap", defaultTex);
mat.setColor("Color", new ColorRGBA(1,1,1,1));
} else {
mat.setColor("Color", defaultColor);
}
if (useAtlas) mat.setBoolean("UseEffectTexCoords", true);
mat.setVector2("OffsetAlphaTexCoord", new Vector2f(0,0));
mat.setFloat("GlobalAlpha", screen.getGlobalAlpha());
mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Back);
this.model = new ElementQuadGrid(this.dimensions, borders, imgWidth, imgHeight, pixelWidth, pixelHeight, textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
this.setName(UID + ":Node");
geom = new Geometry(UID + ":Geometry");
geom.setMesh(model);
geom.setCullHint(CullHint.Never);
geom.setQueueBucket(Bucket.Gui);
geom.setMaterial(mat);
this.attachChild(geom);
this.setQueueBucket(Bucket.Gui);
this.setLocalTranslation(position.x, position.y, 0);
}
public void setAsContainerOnly() {
detachChildAt(0);
}
private void throwParserException() {
try {
throw new java.text.ParseException("The provided texture information does not conform to the expected standard of ?x=(int)&y=(int)&w=(int)&h=(int)", 0);
} catch (ParseException ex) {
Logger.getLogger(Element.class.getName()).log(Level.SEVERE, "The provided texture information does not conform to the expected standard of ?x=(int)&y=(int)&w=(int)&h=(int)", ex);
}
}
/**
* Sets the texture to use as an atlas image as well as the atlas image coords.
* @param tex The texture to use as a local atlas image
* @param queryString The position of the desire atlas image (e.g. "x=0|y=0|w=50|h=50")
*/
public void setTextureAtlasImage(Texture tex, String queryString) {
this.defaultTex = tex;
mat.setTexture("ColorMap", tex);
mat.setColor("Color", new ColorRGBA(1,1,1,1));
mat.setBoolean("UseEffectTexCoords", true);
this.useLocalAtlas = true;
this.atlasCoords = queryString;
float[] coords = screen.parseAtlasCoords(queryString);
float textureAtlasX = coords[0];
float textureAtlasY = coords[1];
float textureAtlasW = coords[2];
float textureAtlasH = coords[3];
float imgWidth = defaultTex.getImage().getWidth();
float imgHeight = defaultTex.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
this.model = new ElementQuadGrid(this.dimensions, borders, imgWidth, imgHeight, pixelWidth, pixelHeight, textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
geom.setMesh(model);
}
/**
* Returns the current unparsed string representing the Element's atlas image
* @return
*/
public String getAtlasCoords() { return this.atlasCoords; }
/**
* Sets the element image to the specified x/y/width/height
* @param queryString (e.g. "x=0|y=0|w=50|h=50")
*/
public void updateTextureAtlasImage(String queryString) {
float[] coords = screen.parseAtlasCoords(queryString);
float textureAtlasX = coords[0];
float textureAtlasY = coords[1];
float textureAtlasW = coords[2];
float textureAtlasH = coords[3];
float imgWidth = defaultTex.getImage().getWidth();
float imgHeight = defaultTex.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
getModel().updateTexCoords(textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
}
/**
* Returns if the element is using a local texture atlas of the screen defined texture atlas
* @return
*/
public boolean getUseLocalAtlas() { return this.useLocalAtlas; }
/**
* Returns the difference between the placement of the elements current image and the given texture coords.
* @param coords The x/y coords of the new image
* @return Vector2f containing The difference between the given coords and the original image
*/
public Vector2f getAtlasTextureOffset(float[] coords) {
Texture tex;
if (defaultTex != null) tex = defaultTex;
else tex = screen.getAtlasTexture();
float imgWidth = tex.getImage().getWidth();
float imgHeight = tex.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
return new Vector2f( getModel().getEffectOffset( pixelWidth*coords[0], pixelHeight*(imgHeight-coords[1]-coords[3]) ));
}
public void setTileImage(boolean tileImage) {
this.tileImage = tileImage;
if (tileImage)
((Texture)mat.getParam("ColorMap").getValue()).setWrap(Texture.WrapMode.Repeat);
else
((Texture)mat.getParam("ColorMap").getValue()).setWrap(Texture.WrapMode.Clamp);
setDimensions(dimensions);
}
public boolean getTileImage() {
return this.tileImage;
}
/**
* Converts the the inputed percentage (0.0f-1.0f) into pixels of the elements image
* @param in Vector2f containing the x and y percentage
* @return Vector2f containing the actual width/height in pixels
*/
public final Vector2f getV2fPercentToPixels(Vector2f in) {
if (getElementParent() == null) {
if (in.x < 1) in.setX(screen.getWidth()*in.x);
if (in.y < 1) in.setY(screen.getHeight()*in.y);
} else {
if (in.x < 1) in.setX(getElementParent().getWidth()*in.x);
if (in.y < 1) in.setY(getElementParent().getHeight()*in.y);
}
return in;
}
/**
* Adds the specified Element as a child to this Element.
* @param child The Element to add as a child
*/
public void addChild(Element child) {
child.elementParent = this;
if (!child.getInitialized()) {
child.setY(this.getHeight()-child.getHeight()-child.getY());
child.orgPosition = position.clone();
child.orgPosition.setY(child.getY());
child.setInitialized();
}
child.orgRelDimensions.set(child.getWidth()/getWidth(),child.getHeight()/getHeight());
child.setQueueBucket(RenderQueue.Bucket.Gui);
if (screen.getElementById(child.getUID()) != null) {
try {
throw new ConflictingIDException();
} catch (ConflictingIDException ex) {
Logger.getLogger(Element.class.getName()).log(Level.SEVERE, "The child element '" + child.getUID() + "' (" + child.getClass() + ") conflicts with a previously added child element in parent element '" + getUID() + "'.", ex);
System.exit(0);
}
} else {
elementChildren.put(child.getUID(), child);
this.attachChild(child);
}
}
/**
* Adds the specified Element as a child to this Element.
* @param child The Element to add as a child
*/
public void addChild(Element child, boolean hide) {
child.elementParent = this;
if (!child.getInitialized()) {
child.setY(this.getHeight()-child.getHeight()-child.getY());
child.orgPosition = position.clone();
child.orgPosition.setY(child.getY());
child.setInitialized();
}
child.orgRelDimensions.set(child.getWidth()/getWidth(),child.getHeight()/getHeight());
child.setQueueBucket(RenderQueue.Bucket.Gui);
if (screen.getElementById(child.getUID()) != null) {
try {
throw new ConflictingIDException();
} catch (ConflictingIDException ex) {
Logger.getLogger(Element.class.getName()).log(Level.SEVERE, "The child element '" + child.getUID() + "' (" + child.getClass() + ") conflicts with a previously added child element in parent element '" + getUID() + "'.", ex);
System.exit(0);
}
} else {
elementChildren.put(child.getUID(), child);
this.attachChild(child);
if (hide)
child.hide();
}
}
/**
* Removes the specified Element
* @param child Element to remove
*/
public void removeChild(Element child) {
Element e = elementChildren.remove(child.getUID());
if (e != null) {
e.elementParent = null;
e.removeFromParent();
e.cleanup();
}
}
/**
* Remove all child Elements from this Element
*/
public void removeAllChildren() {
for (Element e : elementChildren.values()) {
e.removeFromParent();
}
elementChildren.clear();
}
/**
* Returns the child elements as a Map
* @return
*/
public Map<String, Element> getElementsAsMap() {
return this.elementChildren;
}
/**
* Returns the child elements as a Collection
* @return
*/
public Collection<Element> getElements() {
return this.elementChildren.values();
}
/**
* Returns the one and only Element's screen
* @return
*/
public ElementManager getScreen() {
return this.screen;
}
// Z-ORDER
/**
* Recursive call made by the screen control to properly initialize z-order (depth) placement
* @param zOrder The depth to place the Element at. (Relative to the parent's z-order)
*/
protected void initZOrder(float zOrder) {
setLocalTranslation(getLocalTranslation().setZ(
zOrder
));
if (getTextElement() != null)
getTextElement().setLocalTranslation(getTextElement().getLocalTranslation().setZ(
screen.getZOrderStepMinor()
));
for (Element el : elementChildren.values()) {
el.initZOrder(screen.getZOrderStepMinor());
}
}
/**
* Returns the Element's zOrder
* @return float zOrder
*/
public float getZOrder() {
return this.zOrder;
}
/**
* Sets the Elements zOrder (I would suggest NOT using this method)
* @param zOrder
*/
public void setZOrder(float zOrder) {
this.zOrder = zOrder;
initZOrder(zOrder);
}
public void setEffectZOrder(boolean effectZOrder) {
this.effectZOrder = effectZOrder;
}
public boolean getEffectZOrder() { return this.effectZOrder; }
public void setGlobalUIScale(float widthPercent, float heightPercent) {
for (Element el : elementChildren.values()) {
el.setPosition(el.getPosition().x*widthPercent, el.getPosition().y*heightPercent);
el.setDimensions(el.getDimensions().x*widthPercent, el.getDimensions().y*heightPercent);
el.setFontSize(el.getFontSize()*heightPercent);
el.setGlobalUIScale(widthPercent, heightPercent);
}
}
/**
* Returns a list of all children that are an instance of DragElement
* @return List<Element>
*/
public List<Element> getDraggableChildren() {
List<Element> ret = new ArrayList();
for (Element el : elementChildren.values()) {
if (el instanceof DragElement) {
ret.add(el);
}
}
return ret;
}
// Recursive & non-recursive parent/child element searches
/**
* Recursively searches children elements for specified element containing the specified UID
* @param UID - Unique Indentifier of element to search for
* @return Element containing UID or null if not found
*/
public Element getChildElementById(String UID) {
Element ret = null;
if (this.UID.equals(UID)) {
ret = this;
} else {
if (elementChildren.containsKey(UID)) {
ret = elementChildren.get(UID);
} else {
for (Element el : elementChildren.values()) {
ret = el.getChildElementById(UID);
if (ret != null) {
break;
}
}
}
}
return ret;
}
/**
* Returns the top-most parent in the tree of Elements. The topmost element will always have a parent of null
* @return Element elementParent
*/
public Element getAbsoluteParent() {
if (elementParent == null) {
return this;
} else {
return elementParent.getAbsoluteParent();
}
}
/**
* Returns the parent element of this node
* @return Element elementParent
*/
public Element getElementParent() {
return elementParent;
}
/**
* Sets the element's parent element
* @param elementParent Element
*/
public void setElementParent(Element elementParent) {
this.elementParent = elementParent;
}
// Getters & Setters
/**
* Allows for setting the Element UID if (and ONLY if) the Element Parent is null
* @param UID The new UID
* @return boolean If setting the UID was successful
*/
public boolean setUID(String UID) {
if (this.elementParent == null) {
this.UID = UID;
return true;
} else {
return false;
}
}
/**
* Returns the element's unique string identifier
* @return String UID
*/
public String getUID() {
return UID;
}
/**
* Returns the default material for the element
* @return Material mat
*/
public Material getMaterial() {
return this.mat;
}
/**
* A way to override the default material of the element.
*
* NOTE: It is important that the shader used with the new material is either:
* A: The provided Unshaded material contained with this library, or
* B: The custom shader contains the caret, text range, clipping and effect
* handling provided in the default shader.
*
* @param mat The Material to use for rendering this Element.
*/
public void setLocalMaterial(Material mat) {
this.mat = mat;
this.setMaterial(mat);
}
/**
* Informs the screen control that this Element should be ignored by mouse events.
*
* @param ignoreMouse boolean
*/
public void setIgnoreMouse(boolean ignoreMouse) {
this.ignoreMouse = ignoreMouse;
}
/**
* Returns if the element is set to ingnore mouse events
*
* @return boolean ignoreMouse
*/
public boolean getIgnoreMouse() {
return this.ignoreMouse;
}
/**
* Enables draggable behavior for this element
* @param isMovable boolean
*/
public void setIsMovable(boolean isMovable) {
this.isMovable = isMovable;
}
/**
* Returns if the element has draggable behavior set
* @return boolean isMovable
*/
public boolean getIsMovable() {
return this.isMovable;
}
/**
* Enables resize behavior for this element
* @param isResizable boolean
*/
public void setIsResizable(boolean isResizable) {
this.isResizable = isResizable;
}
/**
* Returns if the element has resize behavior set
* @return boolean isResizable
*/
public boolean getIsResizable() {
return this.isResizable;
}
/**
* Enables/disables north border for resizing
* @param resizeN boolean
*/
public void setResizeN(boolean resizeN) {
this.resizeS = resizeN;
}
/**
* Returns whether the elements north border has enabled/disabled resizing
* @return boolean resizeN
*/
public boolean getResizeN() {
return this.resizeS;
}
/**
* Enables/disables south border for resizing
* @param resizeS boolean
*/
public void setResizeS(boolean resizeS) {
this.resizeN = resizeS;
}
/**
* Returns whether the elements south border has enabled/disabled resizing
* @return boolean resizeS
*/
public boolean getResizeS() {
return this.resizeN;
}
/**
* Enables/disables west border for resizing
* @param resizeW boolean
*/
public void setResizeW(boolean resizeW) {
this.resizeW = resizeW;
}
/**
* Returns whether the elements west border has enabled/disabled resizing
* @return boolean resizeW
*/
public boolean getResizeW() {
return this.resizeW;
}
/**
* Enables/disables east border for resizing
* @param resizeE boolean
*/
public void setResizeE(boolean resizeE) {
this.resizeE = resizeE;
}
/**
* Returns whether the elements east border has enabled/disabled resizing
* @return boolean resizeE
*/
public boolean getResizeE() {
return this.resizeE;
}
/**
* Sets how the element will docking to it's parent element during resize events.
* NW = Top Left of parent element
* NE = Top Right of parent element
* SW = Bottom Left of parent element
* SE = Bottom Right of parent element
* @param docking
*/
public void setDocking(Docking docking) {
this.docking = docking;
}
public Docking getDocking() {
return this.docking;
}
/**
* Enables north docking of element (disables south docking of Element). This
* determines how the Element should retain positioning on parent resize events.
*
* @param dockN boolean
*/
@Deprecated
public void setDockN(boolean dockN) {
this.dockS = dockN;
this.dockN = !dockN;
Docking d = null;
if (dockS) {
if (dockE) d = Docking.NE;
else d = Docking.NW;
} else {
if (dockE) d = Docking.SE;
else d = Docking.SW;
}
setDocking(d);
}
/**
* Returns if the Element is docked to the north quadrant of it's parent element.
* @return boolean dockN
*/
@Deprecated
public boolean getDockN() {
return this.dockS;
}
/**
* Enables west docking of Element (disables east docking of Element). This
* determines how the Element should retain positioning on parent resize events.
*
* @param dockW boolean
*/
@Deprecated
public void setDockW(boolean dockW) {
this.dockW = dockW;
this.dockE = !dockW;
Docking d = null;
if (dockE) {
if (dockS) d = Docking.NE;
else d = Docking.SE;
} else {
if (dockS) d = Docking.NW;
else d = Docking.SW;
}
setDocking(d);
}
/**
* Returns if the Element is docked to the west quadrant of it's parent element.
* @return boolean dockW
*/
@Deprecated
public boolean getDockW() {
return this.dockW;
}
/**
* Enables east docking of Element (disables west docking of Element). This
* determines how the Element should retain positioning on parent resize events.
*
* @param dockE boolean
*/
@Deprecated
public void setDockE(boolean dockE) {
this.dockE = dockE;
this.dockW = !dockE;
Docking d = null;
if (dockE) {
if (dockS) d = Docking.NE;
else d = Docking.SE;
} else {
if (dockS) d = Docking.NW;
else d = Docking.SW;
}
setDocking(d);
}
/**
* Returns if the Element is docked to the east quadrant of it's parent element.
* @return boolean dockE
*/
@Deprecated
public boolean getDockE() {
return this.dockE;
}
/**
* Enables south docking of Element (disables north docking of Element). This
* determines how the Element should retain positioning on parent resize events.
*
* @param dockS boolean
*/
@Deprecated
public void setDockS(boolean dockS) {
this.dockN = dockS;
this.dockS = !dockS;
Docking d = null;
if (dockS) {
if (dockE) d = Docking.NE;
else d = Docking.NW;
} else {
if (dockE) d = Docking.SE;
else d = Docking.SW;
}
setDocking(d);
}
/**
* Returns if the Element is docked to the south quadrant of it's parent element.
* @return boolean dockS
*/
@Deprecated
public boolean getDockS() {
return this.dockN;
}
/**
* Determines if the element should scale with parent when resized vertically.
* @param scaleNS boolean
*/
public void setScaleNS(boolean scaleNS) {
this.scaleNS = scaleNS;
}
/**
* Returns if the Element is set to scale vertically when it's parent Element is
* resized.
*
* @return boolean scaleNS
*/
public boolean getScaleNS() {
return this.scaleNS;
}
/**
* Determines if the element should scale with parent when resized horizontally.
* @param scaleEW boolean
*/
public void setScaleEW(boolean scaleEW) {
this.scaleEW = scaleEW;
}
/**
* Returns if the Element is set to scale horizontally when it's parent Element is
* resized.
*
* @return boolean scaleEW
*/
public boolean getScaleEW() {
return this.scaleEW;
}
/**
* Sets the element to pass certain events (movement, resizing) to it direct parent instead
* of effecting itself.
*
* @param effectParent boolean
*/
public void setEffectParent(boolean effectParent) {
this.effectParent = effectParent;
}
/**
* Returns if the Element is set to pass events to it's direct parent
* @return boolean effectParent
*/
public boolean getEffectParent() {
return this.effectParent;
}
/**
* Sets the element to pass certain events (movement, resizing) to it absolute
* parent instead of effecting itself.
*
* The Elements absolute parent is the element farthest up in it's nesting order,
* or simply put, was added to the screen.
*
* @param effectAbsoluteParent boolean
*/
public void setEffectAbsoluteParent(boolean effectAbsoluteParent) {
this.effectAbsoluteParent = effectAbsoluteParent;
}
/**
* Returns if the Element is set to pass events to it's absolute parent
* @return boolean effectParent
*/
public boolean getEffectAbsoluteParent() {
return this.effectAbsoluteParent;
}
/**
* Forces the object to stay within the constraints of it's parent Elements
* dimensions.
* NOTE: use setLockToParentBounds instead.
*
* @param lockToParentBounds boolean
*/
@Deprecated
public void setlockToParentBounds(boolean lockToParentBounds) {
this.lockToParentBounds = lockToParentBounds;
}/**
* Forces the object to stay within the constraints of it's parent Elements
* dimensions.
*
* @param lockToParentBounds boolean
*/
public void setLockToParentBounds(boolean lockToParentBounds) {
this.lockToParentBounds = lockToParentBounds;
}
/**
* Returns if the Element has been constrained to it's parent Element's dimensions.
*
* @return boolean lockToParentBounds
*/
public boolean getLockToParentBounds() {
return this.lockToParentBounds;
}
/**
* Set the x,y coordinates of the Element. X and y are relative to the parent
* Element.
*
* @param position Vector2f screen poisition of Element
*/
public void setPosition(Vector2f position) {
this.position.set(position);
updateNodeLocation();
}
/**
* Set the x,y coordinates of the Element. X and y are relative to the parent
* Element.
*
* @param x The x coordinate screen poisition of Element
* @param y The y coordinate screen poisition of Element
*/
public void setPosition(float x, float y) {
this.position.setX(x);
this.position.setY(y);
updateNodeLocation();
}
/**
* Set the x coordinates of the Element. X is relative to the parent Element.
*
* @param x The x coordinate screen poisition of Element
*/
public void setX(float x) {
this.position.setX(x);
updateNodeLocation();
}
/**
* Set the y coordinates of the Element. Y is relative to the parent Element.
*
* @param y The y coordinate screen poisition of Element
*/
public void setY(float y) {
this.position.setY(y);
updateNodeLocation();
}
private void updateNodeLocation() {
this.setLocalTranslation(position.x, position.y, this.getLocalTranslation().getZ());
updateClipping();
}
/**
* Flags Element as Drag Element for Drag & Drop interaction
* @param isDragElement boolean
*/
public void setIsDragDropDragElement(boolean isDragElement) {
this.isDragElement = isDragElement;
if (isDragElement)
this.isDropElement = false;
}
/**
* Returns if the Element is currently flagged as a Drag Element for Drag & Drop interaction
* @return boolean
*/
public boolean getIsDragDropDragElement() {
return this.isDragElement;
}
/**
* Flags Element as Drop Element for Drag & Drop interaction
* @param isDropElement boolean
*/
public void setIsDragDropDropElement(boolean isDropElement) {
this.isDropElement = isDropElement;
if (isDropElement)
this.isDragElement = false;
}
/**
* Returns if the Element is currently flagged as a Drop Element for Drag & Drop interaction
* @return boolean
*/
public boolean getIsDragDropDropElement() {
return this.isDropElement;
}
/**
* Returns the current screen location of the Element
* @return Vector2f position
*/
public Vector2f getPosition() {
return position;
}
/**
* Gets the relative x coordinate of the Element from it's parent Element's x
* @return float
*/
public float getX() {
return position.x;
}
/**
* Gets the relative y coordinate of the Element from it's parent Element's y
* @return float
*/
public float getY() {
return position.y;
}
/**
* Returns the x coord of an element from screen x 0, ignoring the nesting order.
* @return float x
*/
public float getAbsoluteX() {
float x = getX();
Element el = this;
while (el.getElementParent() != null) {
el = el.getElementParent();
x += el.getX();
}
return x;
}
/**
* Returns the y coord of an element from screen y 0, ignoring the nesting order.
* @return float
*/
public float getAbsoluteY() {
float y = getY();
Element el = this;
while (el.getElementParent() != null) {
el = el.getElementParent();
y += el.getY();
}
return y;
}
/**
* Sets the width and height of the element
* @param w float
* @param h float
*/
public void setDimensions(float w, float h) {
this.dimensions.setX(w);
this.dimensions.setY(h);
getModel().updateDimensions(dimensions.x, dimensions.y);
if (tileImage) {
float tcW = dimensions.x/getModel().getImageWidth();
float tcH = dimensions.y/getModel().getImageHeight();
getModel().updateTiledTexCoords(0, -tcH, tcW, 0);
}
geom.updateModelBound();
if (textElement != null) {
updateTextElement();
}
updateClipping();
}
/**
* Sets the width and height of the element
* @param dimensions Vector2f
*/
public void setDimensions(Vector2f dimensions) {
this.dimensions.set(dimensions);
getModel().updateDimensions(dimensions.x, dimensions.y);
if (tileImage) {
float tcW = dimensions.x/getModel().getImageWidth();
float tcH = dimensions.y/getModel().getImageHeight();
getModel().updateTiledTexCoords(0, -tcH, tcW, 0);
}
geom.updateModelBound();
if (textElement != null) {
updateTextElement();
}
updateClipping();
}
/**
* Stubbed for future use. This should limit resizing to the minimum dimensions defined
* @param minDimensions The absolute minimum dimensions for this Element.
*/
public void setMinDimensions(Vector2f minDimensions) {
if (this.minDimensions == null) this.minDimensions = new Vector2f();
this.minDimensions.set(minDimensions);
}
/**
* Sets the width of the element
* @param width float
*/
public void setWidth(float width) {
this.dimensions.setX(width);
getModel().updateWidth(dimensions.x);
if (tileImage) {
float tcW = dimensions.x/getModel().getImageWidth();
float tcH = dimensions.y/getModel().getImageHeight();
getModel().updateTiledTexCoords(0, -tcH, tcW, 0);
}
geom.updateModelBound();
if (textElement != null) {
updateTextElement();
}
updateClipping();
}
/**
* Sets the height of the element
* @param height float
*/
public void setHeight(float height) {
this.dimensions.setY(height);
getModel().updateHeight(dimensions.y);
if (tileImage) {
float tcW = dimensions.x/getModel().getImageWidth();
float tcH = dimensions.y/getModel().getImageHeight();
getModel().updateTiledTexCoords(0, -tcH, tcW, 0);
}
geom.updateModelBound();
if (textElement != null) {
updateTextElement();
}
updateClipping();
}
/**
* Returns a Vector2f containing the actual width and height of an Element
* @return float
*/
public Vector2f getDimensions() {
return dimensions;
}
/**
* Returns the dimensions defined at the time of the Element's creation.
* @return
*/
public Vector2f getOrgDimensions() { return this.orgDimensions; }
/**
* Returns the actual width of an Element
* @return float
*/
public float getWidth() {
return dimensions.x;
}
/**
* Returns the actual height of an Element
* @return float
*/
public float getHeight() {
return dimensions.y;
}
/**
* Returns the width of an Element from screen x 0
* @return float
*/
public float getAbsoluteWidth() {
return getAbsoluteX() + getWidth();
}
/**
* Returns the height of an Element from screen y 0
* @return float
*/
public float getAbsoluteHeight() {
return getAbsoluteY() + getHeight();
}
/**
* Stubbed for future use.
*/
public void validateLayout() {
if (getDimensions().x < 1 || getDimensions().y < 1) {
Vector2f dim = getV2fPercentToPixels(getDimensions());
resize(getAbsoluteX()+dim.x, getAbsoluteY()+dim.y, Element.Borders.SE);
}
if (getPosition().x < 1 || getPosition().y < 1) {
Vector2f pos = getV2fPercentToPixels(getPosition());
setPosition(pos.x,pos.y);
}
if (getElementParent() != null)
setY(getElementParent().getHeight()-getHeight()-getY());
else
setY(screen.getHeight()-getHeight()-getY());
for (Element el : elementChildren.values()) {
el.validateLayout();
}
}
/**
* Stubbed for future use.
*/
public void setInitialized() {
this.initialized = true;
}
/**
* Stubbed for future use.
*/
public boolean getInitialized() { return this.initialized; }
/**
* The preferred method for resizing Elements if the resize must effect nested
* Elements as well.
*
* @param x the absolute x coordinate from screen x 0
* @param y the absolute y coordinate from screen y 0
* @param dir The Element.Borders used to determine the direction of the resize event
*/
public void resize(float x, float y, Borders dir) {
float prevWidth = getWidth();
float prevHeight = getHeight();
float oX = x, oY = y;
if (getElementParent() != null) { x -= getAbsoluteX()-getX(); }
if (getElementParent() != null) { y -= getAbsoluteY()-getY(); }
float nextX, nextY;
if (dir == Borders.NW) {
if (getLockToParentBounds()) { if (x <= 0) { x = 0; } }
if (minDimensions != null) {
if (getX()+getWidth()-x <= minDimensions.x) { x = getX()+getWidth()-minDimensions.x; }
}
if (resizeW) {
setWidth(getX()+getWidth()-x);
setX(x);
}
if (getLockToParentBounds()) { if (y <= 0) { y = 0; } }
if (minDimensions != null) {
if (getY()+getHeight()-y <= minDimensions.y) { y = getY()+getHeight()-minDimensions.y; }
}
if (resizeN) {
setHeight(getY()+getHeight()-y);
setY(y);
}
} else if (dir == Borders.N) {
if (getLockToParentBounds()) { if (y <= 0) { y = 0; } }
if (minDimensions != null) {
if (getY()+getHeight()-y <= minDimensions.y) { y = getY()+getHeight()-minDimensions.y; }
}
if (resizeN) {
setHeight(getY()+getHeight()-y);
setY(y);
}
} else if (dir == Borders.NE) {
nextX = oX-getAbsoluteX();
if (getLockToParentBounds()) {
float checkWidth = (getElementParent() == null) ? screen.getWidth() : getElementParent().getWidth();
if (nextX >= checkWidth-getX()) {
nextX = checkWidth-getX();
}
}
if (minDimensions != null) {
if (nextX <= minDimensions.x) { nextX = minDimensions.x; }
}
if (resizeE) {
setWidth(nextX);
}
if (getLockToParentBounds()) { if (y <= 0) { y = 0; } }
if (minDimensions != null) {
if (getY()+getHeight()-y <= minDimensions.y) { y = getY()+getHeight()-minDimensions.y; }
}
if (resizeN) {
setHeight(getY()+getHeight()-y);
setY(y);
}
} else if (dir == Borders.W) {
if (getLockToParentBounds()) { if (x <= 0) { x = 0; } }
if (minDimensions != null) {
if (getX()+getWidth()-x <= minDimensions.x) { x = getX()+getWidth()-minDimensions.x; }
}
if (resizeW) {
setWidth(getX()+getWidth()-x);
setX(x);
}
} else if (dir == Borders.E) {
nextX = oX-getAbsoluteX();
if (getLockToParentBounds()) {
float checkWidth = (getElementParent() == null) ? screen.getWidth() : getElementParent().getWidth();
if (nextX >= checkWidth-getX()) {
nextX = checkWidth-getX();
}
}
if (minDimensions != null) {
if (nextX <= minDimensions.x) { nextX = minDimensions.x; }
}
if (resizeE) {
setWidth(nextX);
}
} else if (dir == Borders.SW) {
if (getLockToParentBounds()) { if (x <= 0) { x = 0; } }
if (minDimensions != null) {
if (getX()+getWidth()-x <= minDimensions.x) { x = getX()+getWidth()-minDimensions.x; }
}
if (resizeW) {
setWidth(getX()+getWidth()-x);
setX(x);
}
nextY = oY-getAbsoluteY();
if (getLockToParentBounds()) {
float checkHeight = (getElementParent() == null) ? screen.getHeight() : getElementParent().getHeight();
if (nextY >= checkHeight-getY()) {
nextY = checkHeight-getY();
}
}
if (minDimensions != null) {
if (nextY <= minDimensions.y) { nextY = minDimensions.y; }
}
if (resizeS) {
setHeight(nextY);
}
} else if (dir == Borders.S) {
nextY = oY-getAbsoluteY();
if (getLockToParentBounds()) {
float checkHeight = (getElementParent() == null) ? screen.getHeight() : getElementParent().getHeight();
if (nextY >= checkHeight-getY()) {
nextY = checkHeight-getY();
}
}
if (minDimensions != null) {
if (nextY <= minDimensions.y) { nextY = minDimensions.y; }
}
if (resizeS) {
setHeight(nextY);
}
} else if (dir == Borders.SE) {
nextX = oX-getAbsoluteX();
if (getLockToParentBounds()) {
float checkWidth = (getElementParent() == null) ? screen.getWidth() : getElementParent().getWidth();
if (nextX >= checkWidth-getX()) {
nextX = checkWidth-getX();
}
}
if (minDimensions != null) {
if (nextX <= minDimensions.x) { nextX = minDimensions.x; }
}
if (resizeE) {
setWidth(nextX);
}
nextY = oY-getAbsoluteY();
if (getLockToParentBounds()) {
float checkHeight = (getElementParent() == null) ? screen.getHeight() : getElementParent().getHeight();
if (nextY >= checkHeight-getY()) {
nextY = checkHeight-getY();
}
}
if (minDimensions != null) {
if (nextY <= minDimensions.y) { nextY = minDimensions.y; }
}
if (resizeS) {
setHeight(nextY);
}
}
float diffX = prevWidth-getWidth();
float diffY = prevHeight-getHeight();
controlResizeHook();
for (Element el : elementChildren.values()) {
el.childResize(diffX,diffY,dir);
el.controlResizeHook();
}
}
// Below are different ideas for implementing minimum dimensions. This will be cleaned up once I decide on the best approach.
/*
private void childResize(float diffX, float diffY, Borders dir) {
if (dir == Borders.N) {
// if (dockS && scaleNS) {
// if (minDimensions == null) {
// setHeight(getHeight()-diffY);
// } else if (getHeight()-diffY > minDimensions.y) {
// setHeight(getHeight()-diffY);
// } else {
// setHeight(minDimensions.y);
// }
// }
} else if (dir == Borders.S) {
if (dockS && scaleNS) {
if (minDimensions == null) {
setHeight(getHeight()-diffY);
} else {
float cY = getElementParent().getHeight()-(getElementParent().getHeight()-orgPosition.y);
if (getY() < cY) setHeight(minDimensions.y);
else setHeight(getHeight()-diffY);
if (getHeight() > minDimensions.y) setY(cY);
else setY(getY()-diffY);
}
} else
setY(getY()-diffY);
}
if (dir == Borders.W) {
if (dockE) {
}
} else if (dir == Borders.E) {
if (dockW) {
}
}
Set<String> keys = elementChildren.keySet();
for (String key : keys) {
elementChildren.get(key).childResize(diffX,diffY,dir);
}
}
*/
/*
private void childResize(float diffX, float diffY, Borders dir) {
if (getElementParent().getDimensions().y > getElementParent().getOrgDimensions().y) {
if (dir == Borders.NW || dir == Borders.N || dir == Borders.NE) {
if (getScaleNS()) { if (getHeight()-diffY > minDimensions.y) { setHeight(getHeight()-diffY); } }
// if (getScaleNS()) setHeight(getHeight()-diffY);
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
} else if (dir == Borders.SW || dir == Borders.S || dir == Borders.SE) {
if (getScaleNS()) { if (getHeight()-diffY > minDimensions.y) { setHeight(getHeight()-diffY); } }
// if (getScaleNS()) setHeight(getHeight()-diffY);
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
}
} else {
setHeight(getOrgDimensions().y);
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
}
if (getElementParent().getDimensions().x > getElementParent().getOrgDimensions().x) {
if (dir == Borders.NW || dir == Borders.W || dir == Borders.SW) {
if (getScaleEW()) { if (getWidth()-diffX > minDimensions.x) { setWidth(getWidth()-diffX); } }
// if (getScaleEW()) setWidth(getWidth()-diffX);
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
} else if (dir == Borders.NE || dir == Borders.E || dir == Borders.SE) {
if (getScaleEW()) { if (getWidth()-diffX > minDimensions.x) { setWidth(getWidth()-diffX); } }
// if (getScaleEW()) setWidth(getWidth()-diffX);
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
}
} else {
setWidth(getOrgDimensions().x);
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
}
for (Element el : elementChildren.values()) {
el.childResize(diffX,diffY,dir);
el.controlResizeHook();
}
}
*/
private void childResize(float diffX, float diffY, Borders dir) {
if (dir == Borders.NW || dir == Borders.N || dir == Borders.NE) {
if (getScaleNS()) setHeight(getHeight()-diffY);
if ((getDocking() == Docking.NW || getDocking() == Docking.NE) && !getScaleNS()) setY(getY()-diffY);
} else if (dir == Borders.SW || dir == Borders.S || dir == Borders.SE) {
if (getScaleNS()) setHeight(getHeight()-diffY);
if ((getDocking() == Docking.NW || getDocking() == Docking.NE) && !getScaleNS()) setY(getY()-diffY);
}
if (dir == Borders.NW || dir == Borders.W || dir == Borders.SW) {
if (getScaleEW()) setWidth(getWidth()-diffX);
if ((getDocking() == Docking.NE || getDocking() == Docking.SE) && !getScaleEW()) setX(getX()-diffX);
} else if (dir == Borders.NE || dir == Borders.E || dir == Borders.SE) {
if (getScaleEW()) setWidth(getWidth()-diffX);
if ((getDocking() == Docking.NE || getDocking() == Docking.SE) && !getScaleEW()) setX(getX()-diffX);
}
for (Element el : elementChildren.values()) {
el.childResize(diffX,diffY,dir);
el.controlResizeHook();
}
}
/*
private void childResize(float diffX, float diffY, Borders dir) {
if (getUID().equals("FirstName")) { System.out.println(orgRelDimensions); }
if (dir == Borders.NW || dir == Borders.N || dir == Borders.NE) {
if (getElementParent().getHeight()*orgRelDimensions.y > minDimensions.y) {
if (getScaleNS()) setHeight(getElementParent().getHeight()*orgRelDimensions.y);//getHeight()-diffY);
} else {
if (getScaleNS()) setHeight(orgDimensions.y);
}
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
} else if (dir == Borders.SW || dir == Borders.S || dir == Borders.SE) {
if (getElementParent().getHeight()*orgRelDimensions.y > minDimensions.y) {
if (getScaleNS()) setHeight(getElementParent().getHeight()*orgRelDimensions.y);//getHeight()-diffY);
} else {
if (getScaleNS()) setHeight(orgDimensions.y);
}
if (getDockN() && !getScaleNS()) setY(getY()-diffY);
}
if (dir == Borders.NW || dir == Borders.W || dir == Borders.SW) {
if (getElementParent().getWidth()*orgRelDimensions.x > minDimensions.x) {
if (getScaleEW()) setWidth(getElementParent().getWidth()*orgRelDimensions.x);//getWidth()-diffX);
} else {
if (getScaleEW()) setWidth(orgDimensions.x);
}
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
} else if (dir == Borders.NE || dir == Borders.E || dir == Borders.SE) {
if (getElementParent().getWidth()*orgRelDimensions.x > minDimensions.x) {
if (getScaleEW()) setWidth(getElementParent().getWidth()*orgRelDimensions.x);//getWidth()-diffX);
} else {
if (getScaleEW()) setWidth(orgDimensions.x);
}
if (getDockE() && !getScaleEW()) setX(getX()-diffX);
}
for (Element el : elementChildren.values()) {
el.childResize(diffX,diffY,dir);
el.controlResizeHook();
}
}
*/
/**
* Overridable method for extending the resize event
*/
public void controlResizeHook() {
}
public void sizeToContent() {
float innerX = 10000, innerY = 10000, innerW = -10000, innerH = -10000;
float currentHeight = getHeight();
Map<Element,Float> newY = new HashMap();
for (Element child : elementChildren.values()) {
float x = child.getX();
float y = currentHeight-(child.getY()+child.getHeight());
float w = child.getX()+child.getWidth();
float h = currentHeight-child.getY();
if (x < innerX) innerX = x;
if (y < innerY) innerY = y;
if (w > innerW) innerW = w;
if (h > innerH) innerH = h;
newY.put(child, h);
}
this.setDimensions(innerW+innerX, innerH+innerY);
for (Element child : elementChildren.values()) {
float diff = newY.get(child);
child.setY(innerH-(diff-innerY));
}
}
/**
* Moves the Element to the specified coordinates
* @param x The new x screen coordinate of the Element
* @param y The new y screen coordinate of the Element
*/
public void moveTo(float x, float y) {
if (getLockToParentBounds()) {
if (x < 0) { x = 0; }
if (y < 0) { y = 0; }
if (getElementParent() != null) {
if (x > getElementParent().getWidth()-getWidth()) {
x = getElementParent().getWidth()-getWidth();
}
if (y > getElementParent().getHeight()-getHeight()) {
y = getElementParent().getHeight()-getHeight();
}
} else {
if (x > screen.getWidth()-getWidth()) {
x = screen.getWidth()-getWidth();
}
if (y > screen.getHeight()-getHeight()) {
y = screen.getHeight()-getHeight();
}
}
}
setX(x);
setY(y);
controlMoveHook();
}
/**
* Overridable method for extending the move event
*/
public void controlMoveHook() {
}
/**
* Centers the Element to it's parent Element. If the parent element is null, it will use the screen's width/height.
*/
public void centerToParent() {
if (elementParent == null) {
setPosition(screen.getWidth()/2-(getWidth()/2),screen.getHeight()/2-(getHeight()/2));
} else {
setPosition(elementParent.getWidth()/2-(getWidth()/2),elementParent.getHeight()/2-(getHeight()/2));
}
}
/**
* Set the north, west, east and south borders in number of pixels
* @param borderSize
*/
public void setResizeBorders(float borderSize) {
borders.set(borderSize,borderSize,borderSize,borderSize);
}
/**
* Set the north, west, east and south borders in number of pixels
* @param nBorder float
* @param wBorder float
* @param eBorder float
* @param sBorder float
*/
public void setResizeBorders(float nBorder, float wBorder, float eBorder, float sBorder) {
borders.setX(nBorder);
borders.setY(wBorder);
borders.setZ(eBorder);
borders.setW(sBorder);
}
/**
* Sets the width of north border in number of pixels
* @param nBorder float
*/
public void setNorthResizeBorder(float nBorder) {
borders.setX(nBorder);
}
/**
* Sets the width of west border in number of pixels
* @param wBorder float
*/
public void setWestResizeBorder(float wBorder) {
borders.setY(wBorder);
}
/**
* Sets the width of east border in number of pixels
* @param eBorder float
*/
public void setEastResizeBorder(float eBorder) {
borders.setZ(eBorder);
}
/**
* Sets the width of south border in number of pixels
* @param sBorder float
*/
public void setSouthResizeBorder(float sBorder) {
borders.setW(sBorder);
}
/**
* Returns the height of the north resize border
*
* @return float
*/
public float getResizeBorderNorthSize() {
return this.borderHandles.x;
}
/**
* Returns the width of the west resize border
*
* @return float
*/
public float getResizeBorderWestSize() {
return this.borderHandles.y;
}
/**
* Returns the width of the east resize border
*
* @return float
*/
public float getResizeBorderEastSize() {
return this.borderHandles.z;
}
/**
* Returns the height of the south resize border
*
* @return float
*/
public float getResizeBorderSouthSize() {
return this.borderHandles.w;
}
/**
* Returns the default material for the element
* @param mat
*/
public void setElementMaterial(Material mat) {
this.mat = mat;
}
/**
* Returns a pointer to the Material used for rendering this Element.
*
* @return Material mat
*/
public Material getElementMaterial() {
return this.mat;
}
/**
* Returns the default Texture for the Element
*
* @return Texture defaultTexture
*/
public Texture getElementTexture() {
return this.defaultTex;
}
/**
* Returns a pointer to the custom mesh used to render the Element.
*
* @return ElementGridQuad model
*/
public ElementQuadGrid getModel() {
return this.model;
}
/**
* Returns the Element's Geometry.
* @return
*/
public Geometry getGeometry() {
return this.geom;
}
// Font & text
/**
* Sets the element's text layer font
* @param fontPath String The font asset path
*/
public void setFont(String fontPath) {
font = app.getAssetManager().loadFont(fontPath);
if (textElement != null) {
String text = this.getText();
textElement.removeFromParent();
textElement = null;
setText(text);
}
}
/**
* Returns the Bitmapfont used by the element's text layer
* @return BitmapFont font
*/
public BitmapFont getFont() {
return this.font;
}
/**
* Sets the element's text layer font size
* @param fontSize float The size to set the font to
*/
public void setFontSize(float fontSize) {
this.fontSize = fontSize;
if (textElement != null) {
textElement.setSize(fontSize);
}
}
/**
* Returns the element's text layer font size
* @return float fontSize
*/
public float getFontSize() {
return this.fontSize;
}
/**
* Sets the element's text layer font color
* @param fontColor ColorRGBA The color to set the font to
*/
public void setFontColor(ColorRGBA fontColor) {
this.fontColor = fontColor;
if (textElement != null) {
textElement.setColor(fontColor);
}
}
/**
* Return the element's text layer font color
* @return ColorRGBA fontColor
*/
public ColorRGBA getFontColor() {
return this.fontColor;
}
/**
* Sets the element's text layer horizontal alignment
*
* @param textAlign
*/
public void setTextAlign(BitmapFont.Align textAlign) {
this.textAlign = textAlign;
if (textElement != null) {
textElement.setAlignment(textAlign);
}
}
/**
* Returns the element's text layer horizontal alignment
* @return Align text Align
*/
public BitmapFont.Align getTextAlign() {
return this.textAlign;
}
/**
* Sets the element's text layer vertical alignment
*
* @param textVAlign
*/
public void setTextVAlign(BitmapFont.VAlign textVAlign) {
this.textVAlign = textVAlign;
if (textElement != null) {
textElement.setVerticalAlignment(textVAlign);
}
}
/**
* Returns the element's text layer vertical alignment
* @return VAlign textVAlign
*/
public BitmapFont.VAlign getTextVAlign() {
return this.textVAlign;
}
/**
* Sets the element's text later wrap mode
* @param textWrap LineWrapMode textWrap
*/
public void setTextWrap(LineWrapMode textWrap) {
this.textWrap = textWrap;
if (textElement != null) {
textElement.setLineWrapMode(textWrap);
}
}
/**
* Returns the element's text layer wrap mode
* @return LineWrapMode textWrap
*/
public LineWrapMode getTextWrap() {
return this.textWrap;
}
/**
* Sets the elements text layer position
* @param x Position's x coord
* @param y Position's y coord
*/
public void setTextPosition(float x, float y) {
this.textPosition = new Vector2f(x,y);
}
/**
* Returns the current x, y coords of the element's text layer
* @return Vector2f textPosition
*/
public Vector2f getTextPosition() {
return this.textPosition;
}
/**
* Sets the padding set for the element's text layer
* @param textPadding
*/
public void setTextPadding(float textPadding) {
this.textPadding = textPadding;
}
/**
* Returns the ammount of padding set for the elements text layer
* @return float textPadding
*/
public float getTextPadding() {
return this.textPadding;
}
/**
* Updates the element's textlayer position and boundary
*/
protected void updateTextElement() {
if (textElement != null) {
textElement.setLocalTranslation(textPosition.x+textPadding, getHeight()-(textPosition.y+textPadding), textElement.getLocalTranslation().z);
textElement.setBox(new Rectangle(0,0,dimensions.x-(textPadding*2),dimensions.y-(textPadding*2)));
// textElement.setPosition(textPadding, textPadding);
// textElement.setDimensions(dimensions.x-(textPadding*2),dimensions.y-(textPadding*2));
// textElement.controlResizeHook();
// textElement.updateAnimText(0);
}
}
/**
* Sets the text of the element.
* @param text String The text to display.
*/
public void setText(String text) {
this.text = text;
if (textElement == null) {
textElement = new BitmapText(font, false);
textElement.setBox(new Rectangle(0,0,dimensions.x,dimensions.y));
// textElement = new TextElement(screen, Vector2f.ZERO, getDimensions());
}
textElement.setLineWrapMode(textWrap);
textElement.setAlignment(textAlign);
textElement.setVerticalAlignment(textVAlign);
textElement.setSize(fontSize);
textElement.setColor(fontColor);
textElement.setText(text);
updateTextElement();
if (textElement.getParent() == null) {
this.attachChild(textElement);
}
}
/**
* Retuns the current visible text of the element.
* @return String text
*/
public String getText() {
return this.text;
}
/**
* Returns a pointer to the BitmapText element of this Element. Returns null
* if setText() has not been called.
*
* @return BitmapText textElement
*/
public BitmapText getTextElement() {
// public TextElement getTextElement() {
return this.textElement;
}
// Clipping
/**
* Adds an alpha map to the Elements material
* @param alphaMap A String path to the alpha map
*/
public void setAlphaMap(String alphaMap) {
Texture alpha = null;
if (screen.getUseTextureAtlas()) {
if (this.getElementTexture() != null) alpha = getElementTexture();
else alpha = screen.getAtlasTexture();
Vector2f alphaOffset = getAtlasTextureOffset(screen.parseAtlasCoords(alphaMap));
mat.setVector2("OffsetAlphaTexCoord", alphaOffset);
} else {
alpha = app.getAssetManager().loadTexture(alphaMap);
alpha.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
alpha.setMagFilter(Texture.MagFilter.Nearest);
alpha.setWrap(Texture.WrapMode.Clamp);
}
this.alphaMap = alpha;
if (defaultTex == null) {
if (!screen.getUseTextureAtlas()) {
float imgWidth = alpha.getImage().getWidth();
float imgHeight = alpha.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
this.model = new ElementQuadGrid(this.dimensions, borders, imgWidth, imgHeight, pixelWidth, pixelHeight, 0, 0, imgWidth, imgHeight);
geom.setMesh(model);
} else {
float[] coords = screen.parseAtlasCoords(alphaMap);
float textureAtlasX = coords[0];
float textureAtlasY = coords[1];
float textureAtlasW = coords[2];
float textureAtlasH = coords[3];
float imgWidth = alpha.getImage().getWidth();
float imgHeight = alpha.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
model = new ElementQuadGrid(this.getDimensions(), borders, imgWidth, imgHeight, pixelWidth, pixelHeight, textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
geom.setMesh(model);
mat.setVector2("OffsetAlphaTexCoord", new Vector2f(0,0));
}
}
mat.setTexture("AlphaMap", alpha);
}
public Texture getAlphaMap() {
return this.alphaMap;
}
public void setColorMap(String colorMap) {
Texture color = null;
if (screen.getUseTextureAtlas()) {
if (this.getElementTexture() != null) color = getElementTexture();
else color = screen.getAtlasTexture();
} else {
color = app.getAssetManager().loadTexture(colorMap);
color.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
color.setMagFilter(Texture.MagFilter.Nearest);
color.setWrap(Texture.WrapMode.Clamp);
}
this.defaultTex = color;
if (!screen.getUseTextureAtlas()) {
float imgWidth = color.getImage().getWidth();
float imgHeight = color.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
this.model = new ElementQuadGrid(this.dimensions, borders, imgWidth, imgHeight, pixelWidth, pixelHeight, 0, 0, imgWidth, imgHeight);
geom.setMesh(model);
} else {
float[] coords = screen.parseAtlasCoords(colorMap);
float textureAtlasX = coords[0];
float textureAtlasY = coords[1];
float textureAtlasW = coords[2];
float textureAtlasH = coords[3];
float imgWidth = color.getImage().getWidth();
float imgHeight = color.getImage().getHeight();
float pixelWidth = 1f/imgWidth;
float pixelHeight = 1f/imgHeight;
textureAtlasY = imgHeight-textureAtlasY-textureAtlasH;
model = new ElementQuadGrid(this.getDimensions(), borders, imgWidth, imgHeight, pixelWidth, pixelHeight, textureAtlasX, textureAtlasY, textureAtlasW, textureAtlasH);
geom.setMesh(model);
}
mat.setTexture("ColorMap", color);
mat.setColor("Color", ColorRGBA.White);
}
/**
* This may be remove soon and probably should not be used as the method of handling
* hide show was updated making this unnecissary.
*
* @param wasVisible boolean
*/
public void setDefaultWasVisible(boolean wasVisible) {
this.wasVisible = wasVisible;
}
/**
* Shows the current Element with the defined Show effect. If no Show effect is defined, the Element will show as normal.
*/
public void showWithEffect() {
Effect effect = getEffect(Effect.EffectEvent.Show);
if (effect != null) {
if (effect.getEffectType() == Effect.EffectType.FadeIn) {
Effect clone = effect.clone();
clone.setAudioFile(null);
this.propagateEffect(clone, false);
} else
screen.getEffectManager().applyEffect(effect);
} else
this.show();
}
/**
* Sets this Element and any Element contained within it's nesting order to visible.
*
* NOTE: Hide and Show relies on shader-based clipping
*/
public void show() {
if (!isVisible) {
screen.updateZOrder(getAbsoluteParent());
this.isVisible = true;
this.isClipped = wasClipped;
updateClipping();
controlShowHook();
if (getParent() == null) {
if (getElementParent() != null) {
getElementParent().attachChild(this);
} else {
screen.getGUINode().attachChild(this);
}
}
for (Element el : elementChildren.values()) {
el.childShow();
}
}
}
public void showAsModal(boolean showWithEffect) {
isVisibleAsModal = true;
screen.showAsModal(this,showWithEffect);
}
/**
* Recursive call for properly showing children of the Element. I'm thinking this
* this needs to be a private method, however I need to verify this before I
* update it.
*/
public void childShow() {
this.isVisible = wasVisible;
this.isClipped = wasClipped;
updateClipping();
controlShowHook();
for (Element el : elementChildren.values()) {
el.childShow();
}
}
/**
* An overridable method for extending the show event.
*/
public void controlShowHook() { }
/**
* Hides the element using the current defined Hide effect. If no Hide effect is defined, the Element will hide as usual.
*/
public void hideWithEffect() {
Effect effect = getEffect(Effect.EffectEvent.Hide);
if (effect != null) {
if (effect.getEffectType() == Effect.EffectType.FadeOut) {
Effect clone = effect.clone();
clone.setAudioFile(null);
this.propagateEffect(clone, true);
} else
screen.getEffectManager().applyEffect(effect);
if (isVisibleAsModal) {
isVisibleAsModal = false;
screen.hideModalBackground();
}
} else
this.hide();
}
/**
* Recursive call that sets this Element and any Element contained within it's
* nesting order to hidden.
*
* NOTE: Hide and Show relies on shader-based clipping
*/
public void hide() {
if (isVisible) {
if (isVisibleAsModal) {
isVisibleAsModal = false;
screen.hideModalBackground();
}
this.wasVisible = isVisible;
this.isVisible = false;
this.isClipped = true;
}
updateClipping();
controlHideHook();
removeFromParent();
for (Element el : elementChildren.values()) {
el.childHide();
}
}
/**
* For internal use. This method should never be called directly.
*/
public void childHide() {
if (isVisible) {
this.wasVisible = isVisible;
this.isVisible = false;
this.isClipped = true;
}
updateClipping();
controlHideHook();
for (Element el : elementChildren.values()) {
el.childHide();
}
}
/**
* Hides or shows the element (true = show, false = hide)
* @param visibleState
*/
public void setIsVisible(boolean visibleState) {
if (visibleState) {
show();
} else {
hide();
}
}
/**
* Toggles the Element's visibility based on the current state.
*/
public void setIsVisible() {
if (getIsVisible()) hide();
else show();
}
/**
* An overridable method for extending the hide event.
*/
public void controlHideHook() { }
public void cleanup() {
controlCleanupHook();
for (Element el : elementChildren.values()) {
el.cleanup();
}
}
/**
* An overridable method for handling control specific cleanup.
*/
public void controlCleanupHook() { }
/**
* For internal use only - DO NOT CALL THIS METHOD
* @param effect Effect
* @param callHide boolean
*/
public void propagateEffect(Effect effect, boolean callHide) {
Effect nEffect = effect.clone();
nEffect.setCallHide(callHide);
nEffect.setElement(this);
screen.getEffectManager().applyEffect(nEffect);
for (Element el : elementChildren.values()) {
el.propagateEffect(effect, false);
}
}
/**
* Return if the Element is visible
*
* @return boolean isVisible
*/
public boolean getIsVisible() {
return this.isVisible;
}
/**
* Sets the elements clipping layer to the provided element.
* @param clippingLayer The element that provides the clipping boundaries.
*/
public void setClippingLayer(Element clippingLayer) {
if (clippingLayer != null) {
this.isClipped = true;
this.wasClipped = true;
this.clippingLayer = clippingLayer;
this.mat.setBoolean("UseClipping", true);
} else {
this.isClipped = false;
this.wasClipped = false;
this.clippingLayer = null;
this.mat.setBoolean("UseClipping", false);
}
}
/**
* Recursive update of all child Elements clipping layer
* @param clippingLayer The clipping layer to apply
*/
public void setControlClippingLayer(Element clippingLayer) {
setClippingLayer(clippingLayer);
for (Element el : elementChildren.values()) {
el.setControlClippingLayer(clippingLayer);
}
}
/**
* Returns if the Element's clipping layer has been set
*
* @return boolean isClipped
*/
public boolean getIsClipped() {
return isClipped;
}
/**
* Returns the elements clipping layer or null is element doesn't use clipping
* @return Element clippingLayer
*/
public Element getClippingLayer() {
return this.clippingLayer;
}
/**
* Returns a Vector4f containing the current boundaries of the element's clipping layer
* @return Vector4f clippingBounds
*/
public Vector4f getClippingBounds() {
return this.clippingBounds;
}
/**
* Adds a padding to the clippinglayer, in effect this contracts the size of the clipping
* bounds by the specified number of pixels
* @param clipPadding The number of pixels to pad the clipping area
*/
public void setClipPadding(float clipPadding) {
this.clipPadding = clipPadding;
}
/**
* Returns the current clipPadding
* @return float clipPadding
*/
public float getClipPadding() {
return clipPadding;
}
/**
* Updates the clipping bounds for any element that has a clipping layer
*
* See updateLocalClipping
*/
public void updateClipping() {
updateLocalClipping();
for (Element el : elementChildren.values()) {
el.updateClipping();
}
}
/**
* Updates the clipping bounds for any element that has a clipping layer
*/
public void updateLocalClipping() {
if (isVisible) {
if (clippingLayer != null) {
float cPadding = 0;
if (clippingLayer != this)
cPadding = clippingLayer.getClipPadding();
clippingBounds.set(
clippingLayer.getAbsoluteX()+cPadding,
clippingLayer.getAbsoluteY()+cPadding,
clippingLayer.getAbsoluteWidth()-cPadding,
clippingLayer.getAbsoluteHeight()-cPadding
);
mat.setVector4("Clipping", clippingBounds);
mat.setBoolean("UseClipping", true);
} else {
mat.setBoolean("UseClipping", false);
}
} else {
clippingBounds.set(0,0,0,0);
mat.setVector4("Clipping", clippingBounds);
mat.setBoolean("UseClipping", true);
}
setFontPages();
}
/**
* Shrinks the clipping area by set number of pixels
*
* @param textClipPadding The number of pixels to pad the clipping area with on each side
*/
public void setTextClipPadding(float textClipPadding) {
this.textClipPadding = textClipPadding;
}
/**
* Updates font materials with any changes to clipping layers
*/
private void setFontPages() {
if (textElement != null) {
if (!isVisible) {
for (int i = 0; i < font.getPageSize(); i++) {
this.font.getPage(i).setVector4("Clipping", clippingBounds);
this.font.getPage(i).setBoolean("UseClipping", true);
}
} else {
if (isClipped) {
for (int i = 0; i < font.getPageSize(); i++) {
this.font.getPage(i).setVector4("Clipping", clippingBounds.add(textClipPadding, textClipPadding, -textClipPadding, -textClipPadding));
this.font.getPage(i).setBoolean("UseClipping", true);
}
} else {
for (int i = 0; i < font.getPageSize(); i++) {
this.font.getPage(i).setBoolean("UseClipping", false);
}
}
}
}
}
// Effects
/**
* Associates an Effect with this Element. Effects are not automatically associated
* with the specified event, but instead, the event type is used to retrieve the Effect
* at a later point
*
* @param effectEvent The Effect.EffectEvent the Effect is to be registered with
* @param effect The Effect to store
*/
public void addEffect(Effect.EffectEvent effectEvent, Effect effect) {
addEffect(effect);
}
/**
* Associates an Effect with this Element. Effects are not automatically associated
* with the specified event, but instead, the event type is used to retrieve the Effect
* at a later point
*
* @param effect The Effect to store
*/
public void addEffect(Effect effect) {
effects.remove(effect.getEffectEvent());
if (!effects.containsKey(effect.getEffectEvent())) {
effect.setElement(this);
effects.put(effect.getEffectEvent(), effect);
}
}
/**
* Removes the Effect associated with the Effect.EffectEvent specified
* @param effectEvent
*/
public void removeEffect(Effect.EffectEvent effectEvent) {
effects.remove(effectEvent);
}
/**
* Retrieves the Effect associated with the specified Effect.EffectEvent
*
* @param effectEvent
* @return effect
*/
public Effect getEffect(Effect.EffectEvent effectEvent) {
Effect effect = null;
if (effects.get(effectEvent) != null)
effect = effects.get(effectEvent).clone();
return effect;
}
/**
* Called by controls during construction to prepopulate effects based on Styles.
*
* @param styleName The String identifier of the Style
*/
protected void populateEffects(String styleName) {
int index = 0;
Effect effect;
while ((effect = screen.getStyle(styleName).getEffect("event" + index)) != null) {
effect = effect.clone();
effect.setElement(this);
this.addEffect(effect);
index++;
}
}
/**
* Overrides the screen global alpha with the specified value. setIngoreGlobalAlpha must be enabled prior to calling this method.
* @param globalAlpha
*/
public void setGlobalAlpha(float globalAlpha) {
if (!ignoreGlobalAlpha) {
getElementMaterial().setFloat("GlobalAlpha", globalAlpha);
for (Element el : elementChildren.values()) {
el.setGlobalAlpha(globalAlpha);
}
} else {
getElementMaterial().setFloat("GlobalAlpha", 1);
}
}
/**
* Will enable or disable the use of the screen defined global alpha setting.
* @param ignoreGlobalAlpha
*/
public void setIgnoreGlobalAlpha(boolean ignoreGlobalAlpha) {
this.ignoreGlobalAlpha = ignoreGlobalAlpha;
}
// Tab focus
/**
* For use by the Form control (Do not call this method directly)
* @param form The form the Element has been added to
*/
public void setForm(Form form) {
this.form = form;
}
/**
* Returns the form the Element is controlled by
* @return Form form
*/
public Form getForm() {
return this.form;
}
/**
* Sets the tab index (This is assigned by the Form control. Do not call this method directly)
* @param tabIndex The tab index assigned to the Element
*/
public void setTabIndex(int tabIndex) {
this.tabIndex = tabIndex;
}
/**
* Returns the tab index assigned by the Form control
* @return tabIndex
*/
public int getTabIndex() {
return tabIndex;
}
// Off Screen Rendering Bridge
public void addOSRBridge(OSRBridge bridge) {
this.bridge = bridge;
addControl(bridge);
getElementMaterial().setTexture("ColorMap", bridge.getTexture());
getElementMaterial().setColor("Color", ColorRGBA.White);
}
// Tool Tip
/**
* Sets the Element's ToolTip text
* @param toolTip String
*/
public void setToolTipText(String toolTip) {
this.toolTipText = toolTip;
}
/**
* Returns the Element's current ToolTip text
* @return String
*/
public String getToolTipText() {
return toolTipText;
}
/**
* For internal use - DO NOT CALL THIS METHOD
* @param hasFocus boolean
*/
public void setHasFocus(boolean hasFocus) {
this.hasFocus = hasFocus;
}
/**
* Returns if the Element currently has input focus
* @return
*/
public boolean getHasFocus() {
return this.hasFocus;
}
public void setResetKeyboardFocus(boolean resetKeyboardFocus) {
this.resetKeyboardFocus = resetKeyboardFocus;
}
public boolean getResetKeyboardFocus() { return this.resetKeyboardFocus; }
// Modal
/**
* Enables standard modal mode for the Element.
* @param isModal
*/
public void setIsModal(boolean isModal) {
this.isModal = isModal;
}
/**
* Returns if the Element is currently modal
* @return Ret
*/
public boolean getIsModal() {
return this.isModal;
}
/**
* For internal use - DO NOT CALL THIS METHOD
* @param hasFocus boolean
*/
public void setIsGlobalModal(boolean isGlobalModal) {
this.isGlobalModal = isGlobalModal;
}
/**
* For internal use - DO NOT CALL THIS METHOD
* @param hasFocus boolean
*/
public boolean getIsGlobalModal() {
return this.isGlobalModal;
}
// User data
/**
* Stores provided data with the Element
* @param elementUserData Object Data to store
*/
public void setElementUserData(Object elementUserData) {
this.elementUserData = elementUserData;
}
/**
* Returns the data stored with this Element
* @return Object
*/
public Object getElementUserData() {
return this.elementUserData;
}
Vector2f origin = new Vector2f(0,0);
/**
* Stubbed for future use
* @param originX
* @param originY
*/
public void setOrigin(float originX, float originY) {
origin.set(originX, originY);
}
/**
* Stubbed for future use.
* @return
*/
public Vector2f getOrigin() {
return this.origin;
}
}
| Fix for text alpha fades effecting text element's visible state when calling show without effect | src/tonegod/gui/core/Element.java | Fix for text alpha fades effecting text element's visible state when calling show without effect | <ide><path>rc/tonegod/gui/core/Element.java
<ide> Effect clone = effect.clone();
<ide> clone.setAudioFile(null);
<ide> this.propagateEffect(clone, false);
<del> } else
<add> } else {
<add> if (getTextElement() != null)
<add> getTextElement().setAlpha(1f);
<ide> screen.getEffectManager().applyEffect(effect);
<add> }
<ide> } else
<ide> this.show();
<ide> }
<ide> updateClipping();
<ide> controlShowHook();
<ide>
<add> if (getTextElement() != null)
<add> getTextElement().setAlpha(1f);
<add>
<ide> if (getParent() == null) {
<ide> if (getElementParent() != null) {
<del> getElementParent().attachChild(this);
<add> getElementParent().attachChild(this);
<ide> } else {
<ide> screen.getGUINode().attachChild(this);
<ide> }
<ide> * update it.
<ide> */
<ide> public void childShow() {
<add> if (getTextElement() != null)
<add> getTextElement().setAlpha(1f);
<add>
<ide> this.isVisible = wasVisible;
<ide> this.isClipped = wasClipped;
<ide> updateClipping(); |
|
JavaScript | mit | d7fe584b166b007ab11d02096534ad4bc8f73881 | 0 | paveldominguez/master,paveldominguez/master | MLS.checkout = {
options: { // minicart options
disableFlyout: true
},
updateShippingOptions: function(zipcode) {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_SHIPPING_OPTIONS,
{
zipcode: zipcode
},
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
$jQ(".shipping-option-radios").html(r.success.responseHTML).find("input[name=shipRadio]").click(MLS.checkout.selectShippingOption);
$jQ('.shipping-option-radios .checkout-dropdown').each(function(){
MLS.ui.dropdownDisplay(this);
});
}
);
},
/* disabled: requirement on hold
selectShippingOption: function() {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_SELECT_SHIPPING,
{
shipping: $jQ(".shipping-option-radios input[name=shipRadio]:checked").val()
},
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.update(r);
}
);
},
*/
// EDIT VALIDATED INFO BUTTON (after next-step click)
editStepCallback: function(e)
{
var $step = $jQ(this).parents('.checkout-step');
$step.parent().siblings("div, form").find('.checkout-step').find('.hide-complete').each(function() { // close open input & open its summary
$jQ(this).not('hidden').addClass('hidden').siblings('.step-info-summary').not('.blank').removeClass('hidden');
});
$jQ(this).parents('.step-info-summary').addClass('hidden'); // close this panel's summary next
// show this panel's inputs & buttons
$step.find('.hide-complete').removeClass('hidden');
// if step 2
if ($jQ(this).hasClass('edit-billing')) {
$jQ('.new-billing-info-form, .billing-detail-content.details-card').find('.checkout-input').removeClass('not'); // make fields validate-able again
$jQ('.sidebar-finish').removeClass('on'); // reverse side bar changes
$jQ('.checkout-accordion.sidebar').find('.acc-info').css('display', 'none');
$jQ('.new-billing-info-form').removeClass("hidden").siblings(".step-info-summary.billing-address").removeClass("hidden");
/*
$infoform
.addClass('hidden')
.removeAttr("style")
.siblings(".step-info-summary.billing-address")
.removeClass("hidden")
.removeAttr("style"); // hide form so edit button in summary works
*/
/*
if ($jQ('#bill-to-account').is(':checked')) { // IF account hide billing summary for pay with account
$step.find('.step-info-summary.billing-address').addClass('hidden');
}
*/
}
// last, scroll page to top of re-opened section
MLS.ui.scrollPgTo($step, 7);
},
initEditStep: function() {
$jQ('.edit-checkout-step').not('#saved-info-edit').unbind("click", this.editStepCallback).click(this.editStepCallback);
},
init : function() {
// don't trigger the first minicart update
MLS.miniCart.started = true;
/* disabled: featured removed from batch 3
$jQ('select[name=final-qty]').change(function() {
MLS.miniCart.updateItem(
$jQ(this).data("cart-id"), // id
null, // size (null = do not change)
null, // color (null = do not change)
$jQ(this).val()
);
});
*/
// ONLOAD ...............................................................................
var pgWidth = document.body.clientWidth; // get page width
// COMMON (cart, minicart & checkout)
MLS.checkout.vzwValidationRules(); // add methods to all validations
$jQ("input:submit, input:checkbox, select.checkout-input, select.cart-revise-qty, .cart-item-qty, .checkout-final, .next-step-input").uniform(); // style form elements
$jQ('.checkout-dropdown').each(function(){ // display rules for inline dropdowns
MLS.ui.dropdownDisplay(this);
});
$jQ('.special-offer-block').each(function(){ // display rules for offer dropdowns
MLS.ui.dropdownDisplay(this);
});
// CHECKOUT only
// MLS.checkout.beginCheckoutValidation();
MLS.checkout.mainCheckoutValidation();
// MLS.checkout.checkoutSidebarScroll(pgWidth); // set scrolling
MLS.checkout.smallScreenContent(); // prepare small device content
$jQ('#checkout-sequence .selector').find('span').addClass('select-placeholder'); // enhance initial uniform.js select style
$jQ('#checkout-sequence .selector').find('select').change(function(){ // enhance uniform.js select performance
$jQ(this).parents('.selector').find('span').removeClass('select-placeholder');
$jQ(this).parents('.selector').removeClass('error-style');
$jQ(this).parents('.selector').find('.select-error-message').remove();
});
// ........................................................................END ONLOAD
// ON RESIZE ......................................................................................
// CHECKOUT
/*
$jQ(window).resize(function(){
var resizePgWidth = document.body.clientWidth;
MLS.checkout.checkoutSidebarScroll(resizePgWidth);
});
*/
// .........................................................................END RESIZE
// CHECKOUT SIGN IN
// MLS.checkout.beginCheckoutEvents(); // signin page
// CHECKOUT EVENTS ........................................................................
/* disabled: requirement on hold
$jQ("#checkout-ship-zip").keyup(function(e) {
if ($jQ(this).val().length == 5)
{
// assume valid zipcode
MLS.checkout.updateShippingOptions($jQ(this).val());
}
});
*/
// checkout sidebar special offer
$jQ('#checkout-sidebar').find('.special-offer-block').each(function(){
MLS.ui.dropdownDisplay(this);
});
// checkout accordions
$jQ('.checkout-accordion .acc-control').click(function() {
if ($jQ(this).parents('.checkout-accordion').hasClass("disabled"))
{
return false;
}
MLS.ui.simpleAcc(this);
});
$jQ('#checkout-where-to-ship').change(function(){ // main checkout sequence : step 1, home/business select
$jQ(this).parents('.step-info-block').find('#destination').children().each(function(){
if ( $jQ(this).hasClass('not') ) {
$jQ(this).removeClass('not');
$jQ(this).find('.checkout-input').removeClass('not');
} else {
$jQ(this).addClass('not');
$jQ(this).find('.checkout-input').addClass('not');
}
})
});
MLS.checkout.stepTwoSequence(); // card & billing decisions
MLS.checkout.giftCardSequence(); // discount code & giftcards
MLS.checkout.nextStepSequence(); // next step button for steps 1 & 2
MLS.checkout.initEditStep(); // 'edit step' button after a step has been completed
// if BTA is selected, disable gift card
MLS.checkout.initGiftCard();
//............................................................................... END CHECKOUT EVENTS
}, // end init
appliedGiftCards: 0,
disabledCallback: function(e)
{
e.preventDefault();
$jQ(e.target).blur();
return false;
},
initGiftCard: function() {
var $form = $jQ("#vzn-checkout-gift"),
$billing = $jQ("#vzn-checkout-billing"),
$bta = $jQ("#bill-to-account"),
$cc = $jQ("#pay-with-card");
// edit billing info disabled
$jQ("#saved-info-edit").hide();
if ($bta.is(":checked"))
{
$billing.find(".billing-address").addClass("hidden");
$form.addClass("disabled");
} else {
$billing.find(".billing-address").removeClass("hidden");
$form.removeClass("disabled");
}
$form.find(".open").click(function() {
return !$form.hasClass("disabled");
});
$billing.find(".bill-account").click(function(e) {
var $self = $jQ(this),
bta = $self.find("input")[0],
cc = $billing.find(".bill-card input")[0];
if ($self.hasClass("disabled"))
{
return false;
}
bta.checked = !bta.checked;
cc.checked = !cc.checked;
setTimeout(function() {
if (!$self.hasClass(".checked"))
{
$form.addClass("disabled");
} else {
$form.removeClass("disabled");
}
}, 100);
$billing.find(".billing-address").addClass("hidden");
return false;
});
$billing.find(".bill-card").click(function(e) {
var $self = $jQ(this),
bta = $billing.find(".bill-account input")[0],
cc = $self.find("input")[0];
bta.checked = !bta.checked;
cc.checked = !cc.checked;
if ($jQ("#choose-saved-card").is(":checked"))
{
$billing.find(".step-info-summary.billing-address").removeClass("hidden");
} else {
$billing.find(".new-billing-info-form.billing-address").removeClass("hidden");
}
setTimeout(function() {
if (!$self.hasClass(".checked"))
{
$form.removeClass("disabled");
} else {
$form.addClass("disabled");
}
}, 100);
});
},
checkBTATabs: function() {
var $billing = $jQ("#vzn-checkout-billing");
if (MLS.checkout.appliedGiftCards <= 0)
{
// enable tab
$billing.find(".bill-account").removeClass("disabled");
} else {
// disable tab
$billing.find(".bill-account").addClass("disabled");
}
},
vzwValidationRules : function() { // ALL VALIDATION add these methods.................... BEGIN FUNCTIONS ...................
jQuery.validator.addMethod("phoneUS", function(phone_number, element) { // phone number format
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
jQuery.validator.addMethod("zipcodeUS", function(value, element) {
return this.optional(element) || /^\d{5}-\d{4}$|^\d{5}$/.test(value);
}, "Please enter a valid zip code");
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^([a-zA-Z0-9]+)$/.test(value);
}, "Please enter a valid card number");
jQuery.validator.addMethod("noPlaceholder", function (value, element) { // don't validate placeholder text
if (value == $jQ(element).attr('placeholder')) {
return false;
} else {
return true;
}
});
jQuery.validator.addMethod("ccRecognize", function (value, element) { // improved credit card recognition
relValue = value.substring(0,2);
if (relValue >= 40 && relValue <= 49 ) { // visa
return true;
} else if (relValue == 34 || relValue == 37) { // amex
return true;
} else if (relValue >= 50 && relValue <=55 ) { // mc
return true;
} else if (relValue == 65 ) { // discover
return true;
} else {
return false;
}
});
},
update: function(r) {
$jQ(".checkout-cart-summary").html("").html(r.success.summaryHTML);
$jQ(".final-cart-table").html("").html(r.success.finalCartHTML);
/* feature removed
$jQ(".final-cart-table").find('select[name=final-qty]').change(function() {
MLS.miniCart.updateItem(
$jQ(this).data("cart-id"), // id
null, // size (null = do not change)
null, // color (null = do not change)
$jQ(this).val()
);
}).uniform();
*/
$jQ(".final-cart-table select[name=final-qty]").uniform();
$jQ(".final-cart-table .checkout-final").click(function(e) {
this.form.action = MLS.ajax.endpoints.CHECKOUT_STEP_3;
return true;
}).uniform();
// checkout accordions
$jQ('.checkout-cart-summary .checkout-accordion .acc-control').click(function() {
MLS.ui.simpleAcc(this);
});
},
/* THIS PIECE SHOULD GO TO THE SIGNIN PAGE
beginCheckoutEvents : function() { // for signin/guest cover page events ..................................................
$jQ('#checkout-sign-in').click(function(e) { // begin checkout : signin button
e.preventDefault();
var form = $jQ(this).parents('form');
$jQ(form).validate();
if (form.valid()) {
alert('Welcome, signed-in guest!');
return false;
}
});
$jQ('.create-login-checkbox').change(function() { // begin checkout : create vzn login checkbox
$jQ('.create-login-message').slideToggle(300);
});
},
*/
/*
checkoutSidebarScroll : function(pgWidth) { // CHECKOUT floating sidebar ..................................................
if (pgWidth > 959){
$jQ(window).scroll(function(){
if($jQ('#checkout').hasClass('visible')) {
var scrollPos = $jQ(this).scrollTop();
var sidebar = $jQ('.visible #checkout-sidebar')
var startTop = sidebar.attr('data-start-top');
if ( scrollPos >= startTop ) {
sidebar.addClass('fixed');
} else {
sidebar.removeClass('fixed');
} // end 'if position'
} // end 'if visible '
});
} // end 'if desktop'
},
*/
smallScreenContent : function() { // CHECKOUT copy to mobile-only fields ....................................................
// top
$jQ('#checkout .checkout-accordion.sidebar').clone().appendTo('#mobile-checkout-summary');
$jQ('#mobile-checkout-summary .checkout-accordion.sidebar .item-color').each(function(){
var newDiv = $jQ(this).next('.item-size');
$jQ(this).appendTo(newDiv);
});
// bottom
$jQ('#checkout .special-offer-block').clone().appendTo('#mobile-checkout-offers');
$jQ('#checkout .sidebar-finish').clone().appendTo('#mobile-checkout-place-cta');
$jQ('#checkout .totals').clone().appendTo('#mobile-checkout-totals');
$jQ('#checkout .checkout-disclaimers').clone().appendTo('#mobile-checkout-disclaimers');
},
stepTwoSequence : function() { // CHECKOUT card & billing choices...............................................................
$jQ('.billing-option', '#billing-info').on('click', function() {
if ($jQ(this).hasClass("disabled"))
{
return false;
}
var $context = $jQ(this),
$billingOpts = $context.siblings(),
$billingOptsInfo = $jQ('.billing-detail-content', '#billing-info .billing-info-block');
$billingOpts.removeClass('checked').find('span').removeClass('checked');
$context.addClass('checked').find('span').addClass('checked');
$billingOptsInfo.hide();
$jQ($billingOptsInfo[$context.index()]).show();
});
$jQ('input[name=cardChoice]').change(function(){ //signed-in new card or saved card
$jQ(this).siblings('.card-choice-detail-block').removeClass('hidden').parent().siblings('.form-input-wrap').find('.card-choice-detail-block').addClass('hidden'); // handle detail block under button
if ($jQ(this).parent().hasClass('new-card')) {
// new card, show form, hide summary
$jQ(".step-info-summary.billing-address").addClass("hidden").hide();
$jQ('.billing-address.new-billing-info-form').removeClass('hidden').show();
} else {
// old card, hide form, show summary
$jQ(".step-info-summary.billing-address").removeClass('hidden').show();
$jQ('.billing-address.new-billing-info-form').addClass('hidden').hide();
}
});
$jQ('.edit-saved-card').click(function(){ // signed-in edit saved card information
// saved card off
$jQ('.saved-card').find('.checkout-radio-input').prop('checked', false).siblings('.card-choice-detail-block').addClass('hidden');
// new card on
$jQ('.new-card').find('.checkout-radio-input').prop('checked', true).siblings('.card-choice-detail-block').removeClass('hidden');
// edit button off
$jQ(this).addClass('hidden');
// handle saved billing/new billing form below
$jQ('.billing-address').each(function(){
$jQ(this).toggleClass('hidden');
});
});
$jQ('#same-as-shipping').change(function() { // billing info same as shipping
if($jQ(this).hasClass('check')){
$jQ(this).removeClass('check');
$jQ('#shipping-info').find('.SaS').each(function(shipI){
var shipValue = $jQ(this).val();
$jQ('.billing-address-block').find('.SaS').each(function(billI){ // paste stuff
if ( shipI == billI ) { //paste it
$jQ(this).val(shipValue).addClass('valid');
$jQ.uniform.update(this);
return false;
}
});
});
} else { // clear all fields
$jQ('.billing-address-block').find('.SaS').each(function(){
$jQ(this).val('').removeClass('valid');
});
$jQ(this).addClass('check');
}
});
// main checkout sequence : step 2, edit saved billing information information
$jQ('#saved-info-edit').click(function(){
$jQ(this).parents('.billing-address').slideToggle(300).next('.billing-address').slideToggle(300);
if ($jQ("#same-as-shipping").is(":checked"))
{
$jQ("#same-as-shipping").click().click();
}
});
// main checkout sequence : step 2, new card info : card icon recognition
$jQ('#card-number, #card-number-gc').on('keyup', function() {
if(this.value.length === 2) {
var number = this.value;
var cardListItem = 0;
if (number >= 40 && number <= 49 ) {
cardListItem = 'visa';
} else if (number == 34 || number == 37) {
cardListItem='amex';
} else if ( number >= 50 && number <=55 ) {
cardListItem='mastercard';
} else if ( number == 65 ) {
cardListItem='discover';
}
$jQ(this).parents('.form-input-wrap').next().find('.' + cardListItem).addClass('entered').siblings().removeClass('entered');
$jQ('.bill-summary-card').find('.card-image').addClass(cardListItem);
} else if(this.value == "" || this.value.length === 1) {
$jQ(this).parents('.form-input-wrap').next().find('li').removeClass('entered');
}
});
},
giftCardSequence : function() { // main checkout sequence : step 2 .............................................................
// toggle the message & form
$jQ('#begin-gift-card').click(function(e){ //grab CC info (if present) and copy to GC form
if ($jQ("#vzn-checkout-gift").hasClass("disabled"))
{
return false;
}
var ecValid = true;
$jQ('#enter-card-info').find('.selector').each(function(){ // validate main cc selects first
var selectsValid = MLS.checkout.validateSelect(this);
if(selectsValid == false) {
ecValid = false;
}
});
$jQ('#vzn-checkout-billing').validate(); // validate the rest
});
$jQ('.checkout-discount-block .add-discount-code').click(function(){ // add another discount code
if ($jQ(this).hasClass("close"))
{
// if there are discount codes implemented,
// and the uses closes the accordion, remove them.
var $remove = $jQ(this).parents("form").next('div').find(".discount-success:visible .discount-remove");
if ($remove.length > 0)
{
$remove.click();
}
}
$jQ(this).toggleClass('close');
$jQ(this).parents("form").next('div').slideToggle(300);
});
$jQ('.checkout-discount-block .add-gift-card').click(function(){ // add another gift card (only when BTA is hidden)
if ($jQ("#vzn-checkout-gift").hasClass("disabled"))
{
return false;
}
if ($jQ(this).hasClass("close"))
{
// if there are discount codes implemented,
// and the uses closes the accordion, remove them.
var $remove = $jQ(this).parents("form").next('form').find(".discount-success:visible .discount-remove");
if ($remove.length > 0)
{
$remove.click();
}
}
$jQ(this).toggleClass('close');
$jQ(this).parents("form").next('form').slideToggle(300);
});
$jQ("#vzn-checkout-code form").each(function() {
var $form = $jQ(this);
$form.find("input[type=submit]").click(function(e) {
var $self = $jQ(this);
e.preventDefault();
$form.validate();
$form.find("input[name*=discountCode]").valid() &&
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_DISCOUNT,
$form.serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
$form.find(".discount-success div:eq(0)").html(r.success.responseHTML).parent().slideToggle(300).find("a.discount-remove").click(function(ev) {
var $remove = $jQ(this);
ev.preventDefault();
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_DISCOUNT,
$remove.attr("href").split("#")[0].split("?")[1],
function(r) {
$form.find("input.valid").removeClass('valid').addClass('hasPlaceholder');
$remove.parents('.discount-success').prev('.discount-input').slideToggle(300);
$remove.parents('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
$self.parents('.discount-input').slideToggle(300);
// $self.parents('.discount-input').next('.discount-success').slideToggle(300);
MLS.checkout.update(r); // update totals
}
);
return false;
});
});
$jQ("#vzn-checkout-gift form").each(function() {
var $form = $jQ(this);
$form.find('input[type=submit]').click(function(e){ // apply & validate gift card 1
e.preventDefault();
if ($jQ("#vzn-checkout-gift").hasClass("disabled"))
{
return false;
}
var gcValid = true,
$self = $jQ(this); // staying optimistic
$self.parents('.checkout-discount-block').find('.selector').each(function(){ // validate selects first
var selectsValid = MLS.checkout.validateSelect(this);
if(selectsValid == false) {
gcValid = false;
}
});
$form.validate(); // validate form
if ($form.find('input[type=text]').valid() && gcValid == true ) {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$form.serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards++; // increase applied discounts
MLS.checkout.checkBTATabs();
$form.find(".discount-success div:eq(0)").html(r.success.responseHTML).parent().slideToggle(300).find("a.discount-remove").click(function(ev) {
// re-initialize remove buttons
var $remove = $jQ(this);
e.preventDefault();
if ($form.hasClass("disabled"))
{
return false;
}
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$remove.attr("href").split("#")[0].split("?")[1],
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards--; // decrease applied discounts
MLS.checkout.checkBTATabs();
$form.find("input.valid").removeClass('valid').addClass('hasPlaceholder');
// $jQ('.gift-card-cc-block').slideToggle(300); // what is this one?
$remove.parents('.discount-success').prev('.discount-input').slideToggle();
$remove.parents('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
// $jQ('.gift-card-cc-block').slideToggle(300); // what's this one?
$self.parents('.discount-input').slideToggle();
// $self.parents('.discount-input').next('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
}
return false;
});
});
/*
$jQ('#apply-discount-code').click(function(e){ // apply & validate discount code
var $self = $jQ(this);
e.preventDefault();
$jQ('#vzn-checkout-code').validate();
if ($jQ('#discount-code-input').valid() == true) {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_DISCOUNT,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
// error, unable to add to cart
// display error response: .append(data.error.responseHTML);
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
$jQ('#checkout-cart-discount-code').html(r.success.responseHTML).slideToggle(300); //removeClass('na');
$self.parents('.discount-input').slideToggle(300);
$self.parents('.discount-input').next('.discount-success').slideToggle(300);
MLS.checkout.update(r); // update totals
}
);
}
return false;
});
// once activated, we need to enable the remove button
$jQ('#remove-discount-code').click(function(e){ // remove discount code
var $self = $jQ(this);
e.preventDefault();
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_DISCOUNT,
$jQ(this).parents("form").serialize(),
function(r) {
$jQ('#discount-code-input').removeClass('valid').addClass('hasPlaceholder');
$jQ('#checkout-cart-discount-code').slideToggle(300);
$self.parents('.discount-success').prev('.discount-input').slideToggle(300);
$self.parents('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
$jQ('#begin-gift-card').click(function(e){ //grab CC info (if present) and copy to GC form
var ecValid = true;
$jQ('#enter-card-info').find('.selector').each(function(){ // validate main cc selects first
var selectsValid = MLS.checkout.validateSelect(this);
if(selectsValid == false) {
ecValid = false;
}
});
$jQ('#vzn-checkout-billing').validate(); // validate the rest
});
$jQ('#apply-gift-card-1').click(function(e){ // apply & validate gift card 1
e.preventDefault();
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
var gcValid = true,
$self = $jQ(this); // staying optimistic
$jQ(this).parents('.checkout-discount-block').find('.selector').each(function(){ // validate selects first
var selectsValid = MLS.checkout.validateSelect(this);
if(selectsValid == false) {
gcValid = false;
}
});
$jQ('#vzn-checkout-gift').validate(); // validate the rest
if ($jQ('.GCV').valid() && gcValid == true ) {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards++; // increase applied discounts
MLS.checkout.checkBTATabs();
$jQ('#checkout-cart-gift-card-1').html(r.success.responseHTML).slideToggle(300); // hide & show
$jQ('.gift-card-cc-block').slideToggle(300);
$self.parents('.discount-input').slideToggle();
$self.parents('.discount-input').next('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
}
return false;
});
$jQ('#remove-gift-card-1').click(function(e){ // remove gift card 1
var $self = $jQ(this);
e.preventDefault();
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards--; // decrease applied discounts
MLS.checkout.checkBTATabs();
$jQ('#checkout-cart-gift-card-1').removeClass('valid').addClass('hasPlaceholder');
$jQ('#checkout-cart-gift-card-1').slideToggle(300);
$jQ('.gift-card-cc-block').slideToggle(300);
$self.parent('.discount-success').prev('.discount-input').slideToggle();
$self.parent('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
$jQ('#add-gift-card-2').click(function(){ // add another gift card
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
$jQ(this).toggleClass('close');
$jQ(this).parent().parent().next('.acc-info').slideToggle(300);
});
$jQ('#apply-gift-card-2').click(function(e){ // apply & validate gift card 2
var $self = $jQ(this);
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
e.preventDefault();
$jQ('#vzn-checkout-gift').validate();
if ($jQ('#gift-card-2-input').valid() == true && $jQ('#gift-card-2-pin').valid() == true){
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards++; // increase applied discounts
MLS.checkout.checkBTATabs();
$jQ('#checkout-cart-gift-card-2').html(r.success.responseHTML).slideToggle(300);
$self.parents('.discount-input').slideToggle();
$self.parents('.discount-input').next('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
}
return false;
});
$jQ('#remove-gift-card-2').click(function(e){ // remove gift card 2
var $self = $jQ(this);
e.preventDefault();
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards--; // decrease applied discounts
MLS.checkout.checkBTATabs();
$jQ('#checkout-cart-gift-card-2').removeClass('valid').addClass('hasPlaceholder');
$jQ('#checkout-cart-gift-card-2').slideToggle(300);
$self.parent('.discount-success').prev('.discount-input').slideToggle();
$self.parent('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
*/
},
validateSelect : function(selector, ignored) { // CHECKOUT validation/error messages for custom selects created with uniform.js
var thisSelect = $jQ(selector).find('select');
if (ignored == undefined) {
var ignoredClass = 0;
} else {
var ignoredClass = ignored;
}
if ($jQ(thisSelect).hasClass(ignoredClass)){
var selectsValid = true; // we're not validating it
} else { // we are
var thisValue = $jQ(selector).find(':selected').val();
var selectsValid = true; // because we're optimists
if (thisValue == 0) {
$jQ(selector).addClass('select-box-error');
if ($jQ(thisSelect).hasClass('error')) { //don't add multiple messages
} else {
$jQ('<div class="select-error-message error">Please click to select </div>').appendTo(selector);
}
$jQ(thisSelect).addClass('error');
selectsValid = false;
} else { // remove any error states & messages & proceed
$jQ(selector).removeClass('select-box-error');
$jQ(selector).find('.select-error-message').remove();
$jQ(thisSelect).removeClass('error');
}
}
return selectsValid;
},
/* HOOK THE AJAX CALLS IN HERE */
nextStepSequence : function(){ // CHECKOUT next step event .................................................................
$jQ('.next-step-input').click(function(e) {
e.preventDefault();
$jQ(this).parents('.checkout-step').find('label.error').each(function(){
$jQ(this).hide().removeClass('success'); // reset all error & success messages on next step click
});
var which = $jQ(this).attr('id'),
valid = true,
$form = "";
if (which == 'ship-info-complete') { // STEP 1 prevalidate
var radios = $jQ(this).parents('.next-step-button-box').siblings('.step-info-block').find('.checkout-radio-input'); // validate step 1 radio buttons
var radioValid = false;
var i = 0;
$jQ(radios).each(function(i) {
if (this.checked) {
radioValid = true;
$jQ('#no-shipping-selected').hide();
var shippingType = $jQ('input[name=shipRadio]:checked').siblings('label').html();
$jQ('#sum-shipping').html(shippingType);
}
}); // end each
if (radioValid == false ) {
$jQ('#no-shipping-selected').show();
MLS.ui.scrollPgTo('#no-shipping-selected', 40);
return false;
}
$form = $jQ("form#vzn-checkout-shipping");
} // endstep 1 prevalidate
if (which == 'billing-info-complete') { // STEP 2 prevalidate
var signedinBranch = 'new';
var seq = $jQ('#checkout');
if($jQ('.billing-complete').is(':not(.blank)')){ // if second time through, remove previous info
$jQ('#name-on-card').empty();
$jQ('#bill-address-summary-name').empty();
}
if ($jQ(seq).hasClass('signed-in')){ // check for saved info
if ($jQ('#bill-to-account').is(':checked') || $jQ('#choose-saved-card').is(':checked')) { // saved info, no validation required
signedinBranch = 'saved';
$jQ('.new-billing-info-form, .billing-detail-content.details-card').find('.checkout-input').addClass('not');
$jQ('.step-info-summary.billing-address').addClass('hidden');
}
}
$form = $jQ("form#vzn-checkout-billing");
} // end if step 2 prevalidate
var validator = $form.validate(); // VALIDATE
var formValid = $form.valid();
var completed;
if (valid && formValid) {
if (which == 'ship-info-complete') { // STEP 1 postvalidate
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_STEP_1,
$form.serialize(),
function (r) {
if (r.hasOwnProperty('error') && r.error.hasOwnProperty("responseHTML") && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
if (r.hasOwnProperty('error') && r.error.hasOwnProperty("inlineHTML")) {
$jQ(".error.success").removeClass("success");
validator.showErrors(r.error.inlineHTML);
return;
}
// billingHTML
// step 2 restart
$jQ("#vzn-checkout-billing").replaceWith(r.success.billingHTML);
$jQ("#vzn-checkout-billing").find("input:submit, input:checkbox, select.checkout-input, select.cart-revise-qty, .cart-item-qty, .checkout-final, .next-step-input").uniform(); // style form elements
$jQ("#vzn-checkout-billing").find('.checkout-dropdown').each(function(){ // display rules for inline dropdowns
MLS.ui.dropdownDisplay(this);
});
$jQ("#vzn-checkout-billing").find('.special-offer-block').each(function(){ // display rules for offer dropdowns
MLS.ui.dropdownDisplay(this);
});
MLS.checkout.mainCheckoutValidation($jQ("#vzn-checkout-billing"));
MLS.checkout.stepTwoSequence();
MLS.checkout.initGiftCard();
// end step 2 restart
$jQ(".step-info-summary:eq(0)").html(r.success.responseHTML);
MLS.checkout.initEditStep();
completed = $jQ('#shipping-info'); // hide/show/scroll ..............
completed.find('.hide-complete').addClass('hidden');
completed.find('.step-info-summary').removeClass('hidden');
var step2Complete = $jQ('#billing-info .billing-complete'); // which part of step 2 to open
if ($jQ(step2Complete).hasClass('blank')){
$jQ('#billing-info .hide-complete').removeClass('hidden');
} else {
$jQ('#confirm-order').find('.hide-complete').removeClass('hidden'); // open step 3 form & leave step 2 alone
}
MLS.ui.scrollPgTo(completed, 7);
MLS.checkout.update(r);
}
);
} // end step 1 postvalidate
if (which == 'billing-info-complete'){ // STEP 2 postvalidate
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_STEP_2,
$form.serialize(),
function (r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "")
{
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
if (r.success.hasOwnProperty("redirectUrl") && r.success.redirectUrl != "")
{
document.location.href = r.success.redirectUrl;
return;
}
$jQ(".step-info-summary.billing-address").html(r.success.savedInfoSummaryHTML);
$jQ('#saved-info-edit').click(function(){
$jQ(this).parents('.billing-address').slideToggle(300).next('.billing-address').slideToggle(300);
if ($jQ("#same-as-shipping").is(":checked"))
{
$jQ("#same-as-shipping").click().click();
}
});
$jQ(".step-info-summary.billing-complete").html(r.success.responseHTML);
MLS.checkout.initEditStep();
completed = $jQ('#billing-info');
$jQ('.sidebar-finish').addClass('on'); // reveal red CTA in sidebar
$jQ('.checkout-accordion.sidebar').find('.acc-info').css('display', 'none'); // close side bar acc
completed.find('.hide-complete').addClass('hidden'); // hide/show/scroll ..............
completed.find('.step-info-summary').removeClass('hidden');
$jQ('#vzn-checkout-confirm .checkout-step .hide-complete').removeClass('hidden');
MLS.ui.scrollPgTo(completed, 7);
var checkoutConfirm = $jQ('#vzn-checkout-confirm').position();
$jQ('#checkout-sidebar').animate({top:"+" + checkoutConfirm.top},600); // align cart summary with step 3
MLS.checkout.update(r);
setTimeout(function() {
$jQ('.billing-complete').removeClass('blank'); // remove flag for first time through
}, 300);
}
);
} // end step 2 postvalidate
} else { // NOT VALID
$jQ('select').each(function(){ // apply error style to select(s) if req
if ($jQ(this).hasClass('error')){
$jQ(this).parents('.selector').addClass('error-style');
}
});
$jQ('.error').each(function(){ // loop through 'input, select', find first error & scroll to
var whichInput = $jQ(this).attr('id');
if (whichInput == undefined) { // do nothing
} else {
MLS.ui.scrollPgTo('#' + whichInput +'', 40);
return false;
}
});
}
return false;
}); // end click
},
/* THIS NEEDS TO GO TO THE SIGNIN PAGE
beginCheckoutValidation : function() { // CHECKOUT signin validation ...........................................................
$jQ('#my-Verizon-login').validate({
onfocusout: true,
success: function(label){
label.toggleClass('success')
},
ignore : '.ignore, :hidden, .not',
rules: {
myVerizonID: {
required: true,
noPlaceholder: true
},
myVerizonPassword: {
required: true,
noPlaceholder: true,
minlength: 4
}
},
messages: {
myVerizonID: "Please enter your User ID",
myVerizonPassword: {
required: "Please enter your password",
noPlaceholder: "Please enter your password!",
minlength: "Your password must be at least 4 characters long"
}
}
});
},
*/
mainCheckoutValidation : function(forms) { // CHECKOUT
$jQ(forms || '#checkout-sequence form').each(function() {
var validationRules = {
checkoutFirstName: {
required: true,
noPlaceholder: true,
},
checkoutLastName: {
required: true,
noPlaceholder: true,
},
checkoutCompany: {
required: true,
noPlaceholder: true,
},
checkoutAttention: {
required: true,
noPlaceholder: true,
},
checkoutEmail: {
required: true,
noPlaceholder: true,
email: true
},
checkoutPhone: {
required: true,
noPlaceholder: true,
phoneUS: true
},
checkoutAddress: {
required: true,
noPlaceholder: true,
},
checkoutAddress2: {
required: false,
noPlaceholder: false,
},
checkoutCity: {
required: true,
noPlaceholder: true,
},
checkoutState: {
required: true
},
checkoutZip: {
required: true,
zipcodeUS: true,
minlength: 5,
noPlaceholder: true
},
cardNumber: {
required: true,
noPlaceholder: true,
rangelength: [15, 16],
ccRecognize: true
},
ccMonth: {
required: true
},
ccYear: {
required: true
},
ccCode: {
required: true,
noPlaceholder: true,
minlength: 3,
maxlength: 4,
digits: true
},
billingFirstName: {
required: true,
noPlaceholder: true,
},
billingLastName: {
required: true,
noPlaceholder: true,
},
billingPhone: {
required: true,
noPlaceholder: true,
phoneUS: true
},
billingAddress: {
required: true,
noPlaceholder: true,
},
billingAddress2: {
},
billingCity: {
required: true,
noPlaceholder: true
},
billingZip: {
required: true,
zipcodeUS: true,
minlength: 5,
noPlaceholder: true
},
cardNumberGC: {
required: false,
noPlaceholder: true,
rangelength: [15, 16],
ccRecognize: true
},
ccCodeGC: {
required: false,
noPlaceholder: true,
minlength: 3,
maxlength: 4,
digits: true
},
},
validationMessages = {
checkoutFirstName: {
required: "Please enter your first name",
noPlaceholder: "Please enter your first name"
},
checkoutLastName: {
required: "Please enter your last name",
noPlaceholder: "Please enter your last name"
},
checkoutCompany: {
required: "Please enter your company name",
noPlaceholder: "Please enter your company name"
},
checkoutAttention: {
required: "Please enter your first and last name",
noPlaceholder: "Please enter your first and last name"
},
checkoutEmail: {
required: "Please enter your email address",
noPlaceholder: "Please enter your email address",
email: "Please enter a valid email address"
},
checkoutPhone: {
required: "Please enter your phone number",
noPlaceholder: "Please enter your phone number",
phoneUS: "Please enter a valid phone number"
},
checkoutAddress: {
required: "Please enter your street address",
noPlaceholder: "Please enter your street address"
},
checkoutAddress2: {
},
checkoutCity: {
required: "Please enter your city",
noPlaceholder: "Please enter your city"
},
checkoutState: {
required: "Please select your state"
},
checkoutZip: {
required: "Please enter your zip code",
noPlaceholder: "Please enter your zip code",
digits: "Please enter your 5 digit zip code",
minlength: "Please enter your 5 digit zip code",
zipcodeUS: "Please enter a valid zip code"
},
cardNumber: {
required: "Please enter your card number",
noPlaceholder: "Please enter your card number",
rangelength: "Please enter a valid card number",
ccRecognize : "Please enter a valid card number"
},
ccMonth: {
required: "Please select month expiry"
},
ccYear: {
required: "Please select year expiry"
},
ccCode: {
required: "Please enter the security code on the back of your card",
noPlaceholder: "Please enter your security code",
minlength: "Please enter a valid security code",
maxlength: "Please enter a valid security code",
digits: "Please enter a valid security code"
},
billingFirstName: {
required: "Please enter your first name",
noPlaceholder: "Please enter your first name"
},
billingLastName: {
required: "Please enter your last name",
noPlaceholder: "Please enter your last name"
},
billingPhone: {
required: "Please enter your phone number",
noPlaceholder: "Please enter your phone number",
phoneUS: "Please enter a valid phone number"
},
billingAddress: {
required: "Please enter your street address",
noPlaceholder: "Please enter your street address"
},
billingAddress2: {
},
billingCity: {
required: "Please enter your city",
noPlaceholder: "Please enter your city"
},
billingState: {
required: "Please select your state",
noPlaceholder: "Please enter your state"
},
billingZip: {
required: "Please enter your zip code",
noPlaceholder: "Please enter your zip code",
digits: "Please enter your 5 digit zip code",
minlength: "Please enter your 5 digit zip code",
zipcodeUS: "Please enter a valid zip code"
},
cardNumberGC: {
required: "Please enter your card number",
noPlaceholder: "Please enter your card number",
rangelength: "Please enter a valid card number",
ccRecognize : "Please enter a valid card number"
},
ccCodeGC: {
required: "Please enter the security code on the back of your card",
noPlaceholder: "Please enter your security code",
minlength: "Please enter a valid security code",
maxlength: "Please enter a valid security code",
digits: "Please enter a valid security code"
}
},
i = 0,
$discountCodes = $jQ("#vzn-checkout-code input[name*=discountCode]"),
$giftCards = $jQ("#vzn-checkout-gift input[name*=giftCard]");
$discountCodes.each(function() {
var n = $jQ(this).attr("name");
validationRules[n] = {
required: false,
noPlaceholder: true,
/* digits: true, */
minlength: 1,
maxlength: 16
};
validationMessages[n] = {
required: "Please enter a valid discount code",
noPlaceholder: "Please enter a valid discount code",
minlength: "Please enter a valid discount code",
maxlength: "Please enter a valid discount code"
};
});
$giftCards.each(function() {
var n = $jQ(this).attr("name");
if (n.substr(n.length-3).toLowerCase() == "pin")
{
validationRules[n] = {
required: false,
noPlaceholder: true,
/* digits: true, */
minlength: 1,
maxlength: 7
};
validationMessages[n] = {
required: "Please enter a valid gift card PIN",
noPlaceholder: "Please enter a valid gift card PIN",
minlength: "Please enter a valid gift card PIN",
maxlength: "Please enter a valid gift card PIN"
};
} else {
validationRules[n] = {
required: false,
noPlaceholder: true,
digits: true,
minlength: 1,
maxlength: 16
};
validationMessages[n] = {
required: "Please enter a valid discount code",
noPlaceholder: "Please enter a valid discount code",
minlength: "Please enter a valid discount code",
maxlength: "Please enter a valid discount code"
};
}
});
$jQ(this).validate({
ignore: '.ignore, :hidden',
success: function(label){
label.addClass('success').text('');
},
highlight: function(element, errorClass, validClass) {
if ( element.type === "radio" ) {
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
$jQ(element).addClass(errorClass).removeClass(validClass);
}
$jQ(element).siblings(".error.success").removeClass('success');
},
focusCleanup: true,
rules: validationRules,
messages: validationMessages
});
});
}
};
| js/checkout.js | MLS.checkout = {
options: { // minicart options
disableFlyout: true
},
updateShippingOptions: function(zipcode) {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_SHIPPING_OPTIONS,
{
zipcode: zipcode
},
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
$jQ(".shipping-option-radios").html(r.success.responseHTML).find("input[name=shipRadio]").click(MLS.checkout.selectShippingOption);
$jQ('.shipping-option-radios .checkout-dropdown').each(function(){
MLS.ui.dropdownDisplay(this);
});
}
);
},
/* disabled: requirement on hold
selectShippingOption: function() {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_SELECT_SHIPPING,
{
shipping: $jQ(".shipping-option-radios input[name=shipRadio]:checked").val()
},
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.update(r);
}
);
},
*/
// EDIT VALIDATED INFO BUTTON (after next-step click)
editStepCallback: function(e)
{
var $step = $jQ(this).parents('.checkout-step');
$step.parent().siblings("div, form").find('.checkout-step').find('.hide-complete').each(function() { // close open input & open its summary
$jQ(this).not('hidden').addClass('hidden').siblings('.step-info-summary').not('.blank').removeClass('hidden');
});
$jQ(this).parents('.step-info-summary').addClass('hidden'); // close this panel's summary next
// show this panel's inputs & buttons
$step.find('.hide-complete').removeClass('hidden');
// if step 2
if ($jQ(this).hasClass('edit-billing')) {
$jQ('.new-billing-info-form, .billing-detail-content.details-card').find('.checkout-input').removeClass('not'); // make fields validate-able again
$jQ('.sidebar-finish').removeClass('on'); // reverse side bar changes
$jQ('.checkout-accordion.sidebar').find('.acc-info').css('display', 'none');
$jQ('.new-billing-info-form').removeClass("hidden").siblings(".step-info-summary.billing-address").removeClass("hidden");
/*
$infoform
.addClass('hidden')
.removeAttr("style")
.siblings(".step-info-summary.billing-address")
.removeClass("hidden")
.removeAttr("style"); // hide form so edit button in summary works
*/
/*
if ($jQ('#bill-to-account').is(':checked')) { // IF account hide billing summary for pay with account
$step.find('.step-info-summary.billing-address').addClass('hidden');
}
*/
}
// last, scroll page to top of re-opened section
MLS.ui.scrollPgTo($step, 7);
},
initEditStep: function() {
$jQ('.edit-checkout-step').not('#saved-info-edit').unbind("click", this.editStepCallback).click(this.editStepCallback);
},
init : function() {
// don't trigger the first minicart update
MLS.miniCart.started = true;
/* disabled: featured removed from batch 3
$jQ('select[name=final-qty]').change(function() {
MLS.miniCart.updateItem(
$jQ(this).data("cart-id"), // id
null, // size (null = do not change)
null, // color (null = do not change)
$jQ(this).val()
);
});
*/
// ONLOAD ...............................................................................
var pgWidth = document.body.clientWidth; // get page width
// COMMON (cart, minicart & checkout)
MLS.checkout.vzwValidationRules(); // add methods to all validations
$jQ("input:submit, input:checkbox, select.checkout-input, select.cart-revise-qty, .cart-item-qty, .checkout-final, .next-step-input").uniform(); // style form elements
$jQ('.checkout-dropdown').each(function(){ // display rules for inline dropdowns
MLS.ui.dropdownDisplay(this);
});
$jQ('.special-offer-block').each(function(){ // display rules for offer dropdowns
MLS.ui.dropdownDisplay(this);
});
// CHECKOUT only
// MLS.checkout.beginCheckoutValidation();
MLS.checkout.mainCheckoutValidation();
// MLS.checkout.checkoutSidebarScroll(pgWidth); // set scrolling
MLS.checkout.smallScreenContent(); // prepare small device content
$jQ('#checkout-sequence .selector').find('span').addClass('select-placeholder'); // enhance initial uniform.js select style
$jQ('#checkout-sequence .selector').find('select').change(function(){ // enhance uniform.js select performance
$jQ(this).parents('.selector').find('span').removeClass('select-placeholder');
$jQ(this).parents('.selector').removeClass('error-style');
$jQ(this).parents('.selector').find('.select-error-message').remove();
});
// ........................................................................END ONLOAD
// ON RESIZE ......................................................................................
// CHECKOUT
/*
$jQ(window).resize(function(){
var resizePgWidth = document.body.clientWidth;
MLS.checkout.checkoutSidebarScroll(resizePgWidth);
});
*/
// .........................................................................END RESIZE
// CHECKOUT SIGN IN
// MLS.checkout.beginCheckoutEvents(); // signin page
// CHECKOUT EVENTS ........................................................................
/* disabled: requirement on hold
$jQ("#checkout-ship-zip").keyup(function(e) {
if ($jQ(this).val().length == 5)
{
// assume valid zipcode
MLS.checkout.updateShippingOptions($jQ(this).val());
}
});
*/
// checkout sidebar special offer
$jQ('#checkout-sidebar').find('.special-offer-block').each(function(){
MLS.ui.dropdownDisplay(this);
});
// checkout accordions
$jQ('.checkout-accordion .acc-control').click(function() {
if ($jQ(this).parents('.checkout-accordion').hasClass("disabled"))
{
return false;
}
MLS.ui.simpleAcc(this);
});
$jQ('#checkout-where-to-ship').change(function(){ // main checkout sequence : step 1, home/business select
$jQ(this).parents('.step-info-block').find('#destination').children().each(function(){
if ( $jQ(this).hasClass('not') ) {
$jQ(this).removeClass('not');
$jQ(this).find('.checkout-input').removeClass('not');
} else {
$jQ(this).addClass('not');
$jQ(this).find('.checkout-input').addClass('not');
}
})
});
MLS.checkout.stepTwoSequence(); // card & billing decisions
MLS.checkout.giftCardSequence(); // discount code & giftcards
MLS.checkout.nextStepSequence(); // next step button for steps 1 & 2
MLS.checkout.initEditStep(); // 'edit step' button after a step has been completed
// if BTA is selected, disable gift card
MLS.checkout.initGiftCard();
//............................................................................... END CHECKOUT EVENTS
}, // end init
appliedGiftCards: 0,
disabledCallback: function(e)
{
e.preventDefault();
$jQ(e.target).blur();
return false;
},
initGiftCard: function() {
var $form = $jQ("#vzn-checkout-gift"),
$billing = $jQ("#vzn-checkout-billing"),
$bta = $jQ("#bill-to-account"),
$cc = $jQ("#pay-with-card");
// edit billing info disabled
$jQ("#saved-info-edit").hide();
if ($bta.is(":checked"))
{
$billing.find(".billing-address").addClass("hidden");
$form.addClass("disabled");
} else {
$billing.find(".billing-address").removeClass("hidden");
$form.removeClass("disabled");
}
$form.find(".open").click(function() {
return !$form.hasClass("disabled");
});
$billing.find(".bill-account").click(function(e) {
var $self = $jQ(this),
bta = $self.find("input")[0],
cc = $billing.find(".bill-card input")[0];
if ($self.hasClass("disabled"))
{
return false;
}
bta.checked = !bta.checked;
cc.checked = !cc.checked;
setTimeout(function() {
if (!$self.hasClass(".checked"))
{
$form.addClass("disabled");
} else {
$form.removeClass("disabled");
}
}, 100);
$billing.find(".billing-address").addClass("hidden");
return false;
});
$billing.find(".bill-card").click(function(e) {
var $self = $jQ(this),
bta = $billing.find(".bill-account input")[0],
cc = $self.find("input")[0];
bta.checked = !bta.checked;
cc.checked = !cc.checked;
if ($jQ("#choose-saved-card").is(":checked"))
{
$billing.find(".step-info-summary.billing-address").removeClass("hidden");
} else {
$billing.find(".new-billing-info-form.billing-address").removeClass("hidden");
}
setTimeout(function() {
if (!$self.hasClass(".checked"))
{
$form.removeClass("disabled");
} else {
$form.addClass("disabled");
}
}, 100);
});
},
checkBTATabs: function() {
var $billing = $jQ("#vzn-checkout-billing");
if (MLS.checkout.appliedGiftCards <= 0)
{
// enable tab
$billing.find(".bill-account").removeClass("disabled");
} else {
// disable tab
$billing.find(".bill-account").addClass("disabled");
}
},
vzwValidationRules : function() { // ALL VALIDATION add these methods.................... BEGIN FUNCTIONS ...................
jQuery.validator.addMethod("phoneUS", function(phone_number, element) { // phone number format
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
jQuery.validator.addMethod("zipcodeUS", function(value, element) {
return this.optional(element) || /^\d{5}-\d{4}$|^\d{5}$/.test(value);
}, "Please enter a valid zip code");
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^([a-zA-Z0-9]+)$/.test(value);
}, "Please enter a valid card number");
jQuery.validator.addMethod("noPlaceholder", function (value, element) { // don't validate placeholder text
if (value == $jQ(element).attr('placeholder')) {
return false;
} else {
return true;
}
});
jQuery.validator.addMethod("ccRecognize", function (value, element) { // improved credit card recognition
relValue = value.substring(0,2);
if (relValue >= 40 && relValue <= 49 ) { // visa
return true;
} else if (relValue == 34 || relValue == 37) { // amex
return true;
} else if (relValue >= 50 && relValue <=55 ) { // mc
return true;
} else if (relValue == 65 ) { // discover
return true;
} else {
return false;
}
});
},
update: function(r) {
$jQ(".checkout-cart-summary").html("").html(r.success.summaryHTML);
$jQ(".final-cart-table").html("").html(r.success.finalCartHTML);
/* feature removed
$jQ(".final-cart-table").find('select[name=final-qty]').change(function() {
MLS.miniCart.updateItem(
$jQ(this).data("cart-id"), // id
null, // size (null = do not change)
null, // color (null = do not change)
$jQ(this).val()
);
}).uniform();
*/
$jQ(".final-cart-table select[name=final-qty]").uniform();
$jQ(".final-cart-table .checkout-final").click(function(e) {
this.form.action = MLS.ajax.endpoints.CHECKOUT_STEP_3;
return true;
}).uniform();
// checkout accordions
$jQ('.checkout-cart-summary .checkout-accordion .acc-control').click(function() {
MLS.ui.simpleAcc(this);
});
},
/* THIS PIECE SHOULD GO TO THE SIGNIN PAGE
beginCheckoutEvents : function() { // for signin/guest cover page events ..................................................
$jQ('#checkout-sign-in').click(function(e) { // begin checkout : signin button
e.preventDefault();
var form = $jQ(this).parents('form');
$jQ(form).validate();
if (form.valid()) {
alert('Welcome, signed-in guest!');
return false;
}
});
$jQ('.create-login-checkbox').change(function() { // begin checkout : create vzn login checkbox
$jQ('.create-login-message').slideToggle(300);
});
},
*/
/*
checkoutSidebarScroll : function(pgWidth) { // CHECKOUT floating sidebar ..................................................
if (pgWidth > 959){
$jQ(window).scroll(function(){
if($jQ('#checkout').hasClass('visible')) {
var scrollPos = $jQ(this).scrollTop();
var sidebar = $jQ('.visible #checkout-sidebar')
var startTop = sidebar.attr('data-start-top');
if ( scrollPos >= startTop ) {
sidebar.addClass('fixed');
} else {
sidebar.removeClass('fixed');
} // end 'if position'
} // end 'if visible '
});
} // end 'if desktop'
},
*/
smallScreenContent : function() { // CHECKOUT copy to mobile-only fields ....................................................
// top
$jQ('#checkout .checkout-accordion.sidebar').clone().appendTo('#mobile-checkout-summary');
$jQ('#mobile-checkout-summary .checkout-accordion.sidebar .item-color').each(function(){
var newDiv = $jQ(this).next('.item-size');
$jQ(this).appendTo(newDiv);
});
// bottom
$jQ('#checkout .special-offer-block').clone().appendTo('#mobile-checkout-offers');
$jQ('#checkout .sidebar-finish').clone().appendTo('#mobile-checkout-place-cta');
$jQ('#checkout .totals').clone().appendTo('#mobile-checkout-totals');
$jQ('#checkout .checkout-disclaimers').clone().appendTo('#mobile-checkout-disclaimers');
},
stepTwoSequence : function() { // CHECKOUT card & billing choices...............................................................
$jQ('.billing-option', '#billing-info').on('click', function() {
if ($jQ(this).hasClass("disabled"))
{
return false;
}
var $context = $jQ(this),
$billingOpts = $context.siblings(),
$billingOptsInfo = $jQ('.billing-detail-content', '#billing-info .billing-info-block');
$billingOpts.removeClass('checked').find('span').removeClass('checked');
$context.addClass('checked').find('span').addClass('checked');
$billingOptsInfo.hide();
$jQ($billingOptsInfo[$context.index()]).show();
});
$jQ('input[name=cardChoice]').change(function(){ //signed-in new card or saved card
$jQ(this).siblings('.card-choice-detail-block').removeClass('hidden').parent().siblings('.form-input-wrap').find('.card-choice-detail-block').addClass('hidden'); // handle detail block under button
if ($jQ(this).parent().hasClass('new-card')) {
// new card, show form, hide summary
$jQ(".step-info-summary.billing-address").addClass("hidden").hide();
$jQ('.billing-address.new-billing-info-form').removeClass('hidden').show();
} else {
// old card, hide form, show summary
$jQ(".step-info-summary.billing-address").removeClass('hidden').show();
$jQ('.billing-address.new-billing-info-form').addClass('hidden').hide();
}
});
$jQ('.edit-saved-card').click(function(){ // signed-in edit saved card information
// saved card off
$jQ('.saved-card').find('.checkout-radio-input').prop('checked', false).siblings('.card-choice-detail-block').addClass('hidden');
// new card on
$jQ('.new-card').find('.checkout-radio-input').prop('checked', true).siblings('.card-choice-detail-block').removeClass('hidden');
// edit button off
$jQ(this).addClass('hidden');
// handle saved billing/new billing form below
$jQ('.billing-address').each(function(){
$jQ(this).toggleClass('hidden');
});
});
$jQ('#same-as-shipping').change(function() { // billing info same as shipping
if($jQ(this).hasClass('check')){
$jQ(this).removeClass('check');
$jQ('#shipping-info').find('.SaS').each(function(shipI){
var shipValue = $jQ(this).val();
$jQ('.billing-address-block').find('.SaS').each(function(billI){ // paste stuff
if ( shipI == billI ) { //paste it
$jQ(this).val(shipValue).addClass('valid');
$jQ.uniform.update(this);
return false;
}
});
});
} else { // clear all fields
$jQ('.billing-address-block').find('.SaS').each(function(){
$jQ(this).val('').removeClass('valid');
});
$jQ(this).addClass('check');
}
});
// main checkout sequence : step 2, edit saved billing information information
$jQ('#saved-info-edit').click(function(){
$jQ(this).parents('.billing-address').slideToggle(300).next('.billing-address').slideToggle(300);
if ($jQ("#same-as-shipping").is(":checked"))
{
$jQ("#same-as-shipping").click().click();
}
});
// main checkout sequence : step 2, new card info : card icon recognition
$jQ('#card-number, #card-number-gc').on('keyup', function() {
if(this.value.length === 2) {
var number = this.value;
var cardListItem = 0;
if (number >= 40 && number <= 49 ) {
cardListItem = 'visa';
} else if (number == 34 || number == 37) {
cardListItem='amex';
} else if ( number >= 50 && number <=55 ) {
cardListItem='mastercard';
} else if ( number == 65 ) {
cardListItem='discover';
}
$jQ(this).parents('.form-input-wrap').next().find('.' + cardListItem).addClass('entered').siblings().removeClass('entered');
$jQ('.bill-summary-card').find('.card-image').addClass(cardListItem);
} else if(this.value == "" || this.value.length === 1) {
$jQ(this).parents('.form-input-wrap').next().find('li').removeClass('entered');
}
});
},
giftCardSequence : function() { // main checkout sequence : step 2 .............................................................
// toggle the message & form
$jQ('#begin-gift-card').click(function(e){ //grab CC info (if present) and copy to GC form
if ($jQ("#vzn-checkout-gift").hasClass("disabled"))
{
return false;
}
var ecValid = true;
$jQ('#enter-card-info').find('.selector').each(function(){ // validate main cc selects first
var selectsValid = MLS.checkout.validateSelect(this);
if(selectsValid == false) {
ecValid = false;
}
});
$jQ('#vzn-checkout-billing').validate(); // validate the rest
});
$jQ('.checkout-discount-block .add-discount-code').click(function(){ // add another discount code
if ($jQ(this).hasClass("close"))
{
// if there are discount codes implemented,
// and the uses closes the accordion, remove them.
var $remove = $jQ(this).parents("form").next('div').find(".discount-success:visible .discount-remove");
if ($remove.length > 0)
{
$remove.click();
}
}
$jQ(this).toggleClass('close');
$jQ(this).parents("form").next('div').slideToggle(300);
});
$jQ('.checkout-discount-block .add-gift-card').click(function(){ // add another gift card (only when BTA is hidden)
if ($jQ("#vzn-checkout-gift").hasClass("disabled"))
{
return false;
}
if ($jQ(this).hasClass("close"))
{
// if there are discount codes implemented,
// and the uses closes the accordion, remove them.
var $remove = $jQ(this).parents("form").next('form').find(".discount-success:visible .discount-remove");
if ($remove.length > 0)
{
$remove.click();
}
}
$jQ(this).toggleClass('close');
$jQ(this).parents("form").next('form').slideToggle(300);
});
$jQ("#vzn-checkout-code form").each(function() {
var $form = $jQ(this);
$form.find("input[type=submit]").click(function(e) {
var $self = $jQ(this);
e.preventDefault();
$form.validate();
$form.find("input[name*=discountCode]").valid() &&
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_DISCOUNT,
$form.serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
$form.find(".discount-success div:eq(0)").html(r.success.responseHTML).parent().slideToggle(300).find("a.discount-remove").click(function(ev) {
var $remove = $jQ(this);
ev.preventDefault();
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_DISCOUNT,
$remove.attr("href").split("#")[0].split("?")[1],
function(r) {
$form.find("input.valid").removeClass('valid').addClass('hasPlaceholder');
$remove.parents('.discount-success').prev('.discount-input').slideToggle(300);
$remove.parents('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
$self.parents('.discount-input').slideToggle(300);
// $self.parents('.discount-input').next('.discount-success').slideToggle(300);
MLS.checkout.update(r); // update totals
}
);
return false;
});
});
$jQ("#vzn-checkout-gift form").each(function() {
var $form = $jQ(this);
$form.find('input[type=submit]').click(function(e){ // apply & validate gift card 1
e.preventDefault();
if ($jQ("#vzn-checkout-gift").hasClass("disabled"))
{
return false;
}
var gcValid = true,
$self = $jQ(this); // staying optimistic
$self.parents('.checkout-discount-block').find('.selector').each(function(){ // validate selects first
var selectsValid = MLS.checkout.validateSelect(this);
if(selectsValid == false) {
gcValid = false;
}
});
$form.validate(); // validate form
if ($form.find('input[type=text]').valid() && gcValid == true ) {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$form.serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards++; // increase applied discounts
MLS.checkout.checkBTATabs();
$form.find(".discount-success div:eq(0)").html(r.success.responseHTML).parent().slideToggle(300).find("a.discount-remove").click(function(ev) {
// re-initialize remove buttons
var $remove = $jQ(this);
e.preventDefault();
if ($form.hasClass("disabled"))
{
return false;
}
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$remove.attr("href").split("#")[0].split("?")[1],
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards--; // decrease applied discounts
MLS.checkout.checkBTATabs();
$form.find("input.valid").removeClass('valid').addClass('hasPlaceholder');
// $jQ('.gift-card-cc-block').slideToggle(300); // what is this one?
$remove.parents('.discount-success').prev('.discount-input').slideToggle();
$remove.parents('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
// $jQ('.gift-card-cc-block').slideToggle(300); // what's this one?
$self.parents('.discount-input').slideToggle();
// $self.parents('.discount-input').next('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
}
return false;
});
});
/*
$jQ('#apply-discount-code').click(function(e){ // apply & validate discount code
var $self = $jQ(this);
e.preventDefault();
$jQ('#vzn-checkout-code').validate();
if ($jQ('#discount-code-input').valid() == true) {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_DISCOUNT,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
// error, unable to add to cart
// display error response: .append(data.error.responseHTML);
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
$jQ('#checkout-cart-discount-code').html(r.success.responseHTML).slideToggle(300); //removeClass('na');
$self.parents('.discount-input').slideToggle(300);
$self.parents('.discount-input').next('.discount-success').slideToggle(300);
MLS.checkout.update(r); // update totals
}
);
}
return false;
});
// once activated, we need to enable the remove button
$jQ('#remove-discount-code').click(function(e){ // remove discount code
var $self = $jQ(this);
e.preventDefault();
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_DISCOUNT,
$jQ(this).parents("form").serialize(),
function(r) {
$jQ('#discount-code-input').removeClass('valid').addClass('hasPlaceholder');
$jQ('#checkout-cart-discount-code').slideToggle(300);
$self.parents('.discount-success').prev('.discount-input').slideToggle(300);
$self.parents('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
$jQ('#begin-gift-card').click(function(e){ //grab CC info (if present) and copy to GC form
var ecValid = true;
$jQ('#enter-card-info').find('.selector').each(function(){ // validate main cc selects first
var selectsValid = MLS.checkout.validateSelect(this);
if(selectsValid == false) {
ecValid = false;
}
});
$jQ('#vzn-checkout-billing').validate(); // validate the rest
});
$jQ('#apply-gift-card-1').click(function(e){ // apply & validate gift card 1
e.preventDefault();
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
var gcValid = true,
$self = $jQ(this); // staying optimistic
$jQ(this).parents('.checkout-discount-block').find('.selector').each(function(){ // validate selects first
var selectsValid = MLS.checkout.validateSelect(this);
if(selectsValid == false) {
gcValid = false;
}
});
$jQ('#vzn-checkout-gift').validate(); // validate the rest
if ($jQ('.GCV').valid() && gcValid == true ) {
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards++; // increase applied discounts
MLS.checkout.checkBTATabs();
$jQ('#checkout-cart-gift-card-1').html(r.success.responseHTML).slideToggle(300); // hide & show
$jQ('.gift-card-cc-block').slideToggle(300);
$self.parents('.discount-input').slideToggle();
$self.parents('.discount-input').next('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
}
return false;
});
$jQ('#remove-gift-card-1').click(function(e){ // remove gift card 1
var $self = $jQ(this);
e.preventDefault();
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards--; // decrease applied discounts
MLS.checkout.checkBTATabs();
$jQ('#checkout-cart-gift-card-1').removeClass('valid').addClass('hasPlaceholder');
$jQ('#checkout-cart-gift-card-1').slideToggle(300);
$jQ('.gift-card-cc-block').slideToggle(300);
$self.parent('.discount-success').prev('.discount-input').slideToggle();
$self.parent('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
$jQ('#add-gift-card-2').click(function(){ // add another gift card
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
$jQ(this).toggleClass('close');
$jQ(this).parent().parent().next('.acc-info').slideToggle(300);
});
$jQ('#apply-gift-card-2').click(function(e){ // apply & validate gift card 2
var $self = $jQ(this);
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
e.preventDefault();
$jQ('#vzn-checkout-gift').validate();
if ($jQ('#gift-card-2-input').valid() == true && $jQ('#gift-card-2-pin').valid() == true){
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards++; // increase applied discounts
MLS.checkout.checkBTATabs();
$jQ('#checkout-cart-gift-card-2').html(r.success.responseHTML).slideToggle(300);
$self.parents('.discount-input').slideToggle();
$self.parents('.discount-input').next('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
}
return false;
});
$jQ('#remove-gift-card-2').click(function(e){ // remove gift card 2
var $self = $jQ(this);
e.preventDefault();
if ($jQ(this).parents("form").hasClass("disabled"))
{
return false;
}
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_APPLY_GIFTCARD,
$jQ(this).parents("form").serialize(),
function(r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
MLS.checkout.appliedGiftCards--; // decrease applied discounts
MLS.checkout.checkBTATabs();
$jQ('#checkout-cart-gift-card-2').removeClass('valid').addClass('hasPlaceholder');
$jQ('#checkout-cart-gift-card-2').slideToggle(300);
$self.parent('.discount-success').prev('.discount-input').slideToggle();
$self.parent('.discount-success').slideToggle();
MLS.checkout.update(r); // update totals
}
);
return false;
});
*/
},
validateSelect : function(selector, ignored) { // CHECKOUT validation/error messages for custom selects created with uniform.js
var thisSelect = $jQ(selector).find('select');
if (ignored == undefined) {
var ignoredClass = 0;
} else {
var ignoredClass = ignored;
}
if ($jQ(thisSelect).hasClass(ignoredClass)){
var selectsValid = true; // we're not validating it
} else { // we are
var thisValue = $jQ(selector).find(':selected').val();
var selectsValid = true; // because we're optimists
if (thisValue == 0) {
$jQ(selector).addClass('select-box-error');
if ($jQ(thisSelect).hasClass('error')) { //don't add multiple messages
} else {
$jQ('<div class="select-error-message error">Please click to select </div>').appendTo(selector);
}
$jQ(thisSelect).addClass('error');
selectsValid = false;
} else { // remove any error states & messages & proceed
$jQ(selector).removeClass('select-box-error');
$jQ(selector).find('.select-error-message').remove();
$jQ(thisSelect).removeClass('error');
}
}
return selectsValid;
},
/* HOOK THE AJAX CALLS IN HERE */
nextStepSequence : function(){ // CHECKOUT next step event .................................................................
$jQ('.next-step-input').click(function(e) {
e.preventDefault();
$jQ(this).parents('.checkout-step').find('label.error').each(function(){
$jQ(this).hide().removeClass('success'); // reset all error & success messages on next step click
});
var which = $jQ(this).attr('id'),
valid = true,
$form = "";
if (which == 'ship-info-complete') { // STEP 1 prevalidate
var radios = $jQ(this).parents('.next-step-button-box').siblings('.step-info-block').find('.checkout-radio-input'); // validate step 1 radio buttons
var radioValid = false;
var i = 0;
$jQ(radios).each(function(i) {
if (this.checked) {
radioValid = true;
$jQ('#no-shipping-selected').hide();
var shippingType = $jQ('input[name=shipRadio]:checked').siblings('label').html();
$jQ('#sum-shipping').html(shippingType);
}
}); // end each
if (radioValid == false ) {
$jQ('#no-shipping-selected').show();
MLS.ui.scrollPgTo('#no-shipping-selected', 40);
return false;
}
$form = $jQ("form#vzn-checkout-shipping");
} // endstep 1 prevalidate
if (which == 'billing-info-complete') { // STEP 2 prevalidate
var signedinBranch = 'new';
var seq = $jQ('#checkout');
if($jQ('.billing-complete').is(':not(.blank)')){ // if second time through, remove previous info
$jQ('#name-on-card').empty();
$jQ('#bill-address-summary-name').empty();
}
if ($jQ(seq).hasClass('signed-in')){ // check for saved info
if ($jQ('#bill-to-account').is(':checked') || $jQ('#choose-saved-card').is(':checked')) { // saved info, no validation required
signedinBranch = 'saved';
$jQ('.new-billing-info-form, .billing-detail-content.details-card').find('.checkout-input').addClass('not');
$jQ('.step-info-summary.billing-address').addClass('hidden');
}
}
$form = $jQ("form#vzn-checkout-billing");
} // end if step 2 prevalidate
var validator = $form.validate(); // VALIDATE
var formValid = $form.valid();
var completed;
if (valid && formValid) {
if (which == 'ship-info-complete') { // STEP 1 postvalidate
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_STEP_1,
$form.serialize(),
function (r) {
if (r.hasOwnProperty('error') && r.error.hasOwnProperty("responseHTML") && r.error.responseHTML != "") {
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
if (r.hasOwnProperty('error') && r.error.hasOwnProperty("inlineHTML")) {
$jQ(".error.success").removeClass("success");
validator.showErrors(r.error.inlineHTML);
return;
}
// billingHTML
// step 2 restart
$jQ("#vzn-checkout-billing").replaceWith(r.success.billingHTML);
$jQ("#vzn-checkout-billing").find("input:submit, input:checkbox, select.checkout-input, select.cart-revise-qty, .cart-item-qty, .checkout-final, .next-step-input").uniform(); // style form elements
$jQ("#vzn-checkout-billing").find('.checkout-dropdown').each(function(){ // display rules for inline dropdowns
MLS.ui.dropdownDisplay(this);
});
$jQ("#vzn-checkout-billing").find('.special-offer-block').each(function(){ // display rules for offer dropdowns
MLS.ui.dropdownDisplay(this);
});
MLS.checkout.mainCheckoutValidation($jQ("#vzn-checkout-billing"));
MLS.checkout.stepTwoSequence();
MLS.checkout.initGiftCard();
// end step 2 restart
$jQ(".step-info-summary:eq(0)").html(r.success.responseHTML);
MLS.checkout.initEditStep();
completed = $jQ('#shipping-info'); // hide/show/scroll ..............
completed.find('.hide-complete').addClass('hidden');
completed.find('.step-info-summary').removeClass('hidden');
var step2Complete = $jQ('#billing-info .billing-complete'); // which part of step 2 to open
if ($jQ(step2Complete).hasClass('blank')){
$jQ('#billing-info .hide-complete').removeClass('hidden');
} else {
$jQ('#confirm-order').find('.hide-complete').removeClass('hidden'); // open step 3 form & leave step 2 alone
}
MLS.ui.scrollPgTo(completed, 7);
MLS.checkout.update(r);
}
);
} // end step 1 postvalidate
if (which == 'billing-info-complete'){ // STEP 2 postvalidate
MLS.ajax.sendRequest(
MLS.ajax.endpoints.CHECKOUT_STEP_2,
$form.serialize(),
function (r) {
if (r.hasOwnProperty('error') && r.error.responseHTML != "")
{
return MLS.modal.open(r.error ? r.error.responseHTML : null);
}
if (r.success.hasOwnProperty("redirectUrl") && r.success.redirectUrl != "")
{
document.location.href = r.success.redirectUrl;
return;
}
$jQ(".step-info-summary.billing-address").html(r.success.savedInfoSummaryHTML);
$jQ('#saved-info-edit').click(function(){
$jQ(this).parents('.billing-address').slideToggle(300).next('.billing-address').slideToggle(300);
if ($jQ("#same-as-shipping").is(":checked"))
{
$jQ("#same-as-shipping").click().click();
}
});
$jQ(".step-info-summary.billing-complete").html(r.success.responseHTML);
MLS.checkout.initEditStep();
completed = $jQ('#billing-info');
$jQ('.sidebar-finish').addClass('on'); // reveal red CTA in sidebar
$jQ('.checkout-accordion.sidebar').find('.acc-info').css('display', 'none'); // close side bar acc
completed.find('.hide-complete').addClass('hidden'); // hide/show/scroll ..............
completed.find('.step-info-summary').removeClass('hidden');
$jQ('#vzn-checkout-confirm .checkout-step .hide-complete').removeClass('hidden');
MLS.ui.scrollPgTo(completed, 7);
var checkoutConfirm = $jQ('#vzn-checkout-confirm').position();
$jQ('#checkout-sidebar').animate({top:"+" + checkoutConfirm.top},600); // align cart summary with step 3
MLS.checkout.update(r);
setTimeout(function() {
$jQ('.billing-complete').removeClass('blank'); // remove flag for first time through
}, 300);
}
);
} // end step 2 postvalidate
} else { // NOT VALID
$jQ('select').each(function(){ // apply error style to select(s) if req
if ($jQ(this).hasClass('error')){
$jQ(this).parents('.selector').addClass('error-style');
}
});
$jQ('.error').each(function(){ // loop through 'input, select', find first error & scroll to
var whichInput = $jQ(this).attr('id');
if (whichInput == undefined) { // do nothing
} else {
MLS.ui.scrollPgTo('#' + whichInput +'', 40);
return false;
}
});
}
return false;
}); // end click
},
/* THIS NEEDS TO GO TO THE SIGNIN PAGE
beginCheckoutValidation : function() { // CHECKOUT signin validation ...........................................................
$jQ('#my-Verizon-login').validate({
onfocusout: true,
success: function(label){
label.toggleClass('success')
},
ignore : '.ignore, :hidden, .not',
rules: {
myVerizonID: {
required: true,
noPlaceholder: true
},
myVerizonPassword: {
required: true,
noPlaceholder: true,
minlength: 4
}
},
messages: {
myVerizonID: "Please enter your User ID",
myVerizonPassword: {
required: "Please enter your password",
noPlaceholder: "Please enter your password!",
minlength: "Your password must be at least 4 characters long"
}
}
});
},
*/
mainCheckoutValidation : function(forms) { // CHECKOUT
$jQ(forms || '#checkout-sequence form').each(function() {
var validationRules = {
checkoutFirstName: {
required: true,
noPlaceholder: true,
},
checkoutLastName: {
required: true,
noPlaceholder: true,
},
checkoutCompany: {
required: true,
noPlaceholder: true,
},
checkoutAttention: {
required: true,
noPlaceholder: true,
},
checkoutEmail: {
required: true,
noPlaceholder: true,
email: true
},
checkoutPhone: {
required: true,
noPlaceholder: true,
phoneUS: true
},
checkoutAddress: {
required: true,
noPlaceholder: true,
},
checkoutAddress2: {
required: false,
noPlaceholder: false,
},
checkoutCity: {
required: true,
noPlaceholder: true,
},
checkoutState: {
required: true
},
checkoutZip: {
required: true,
zipcodeUS: true,
minlength: 5,
noPlaceholder: true
},
cardNumber: {
required: true,
noPlaceholder: true,
rangelength: [15, 16],
ccRecognize: true
},
ccMonth: {
required: true
},
ccYear: {
required: true
},
ccCode: {
required: true,
noPlaceholder: true,
minlength: 3,
maxlength: 4,
digits: true
},
billingFirstName: {
required: true,
noPlaceholder: true,
},
billingLastName: {
required: true,
noPlaceholder: true,
},
billingPhone: {
required: true,
noPlaceholder: true,
phoneUS: true
},
billingAddress: {
required: true,
noPlaceholder: true,
},
billingAddress2: {
},
billingCity: {
required: true,
noPlaceholder: true
},
billingZip: {
required: true,
zipcodeUS: true,
minlength: 5,
noPlaceholder: true
},
cardNumberGC: {
required: false,
noPlaceholder: true,
rangelength: [15, 16],
ccRecognize: true
},
ccCodeGC: {
required: false,
noPlaceholder: true,
minlength: 3,
maxlength: 4,
digits: true
},
},
validationMessages = {
checkoutFirstName: {
required: "Please enter your first name",
noPlaceholder: "Please enter your first name"
},
checkoutLastName: {
required: "Please enter your last name",
noPlaceholder: "Please enter your last name"
},
checkoutCompany: {
required: "Please enter your company name",
noPlaceholder: "Please enter your company name"
},
checkoutAttention: {
required: "Please enter your first and last name",
noPlaceholder: "Please enter your first and last name"
},
checkoutEmail: {
required: "Please enter your email address",
noPlaceholder: "Please enter your email address",
email: "Please enter a valid email address"
},
checkoutPhone: {
required: "Please enter your phone number",
noPlaceholder: "Please enter your phone number",
phoneUS: "Please enter a valid phone number"
},
checkoutAddress: {
required: "Please enter your street address",
noPlaceholder: "Please enter your street address"
},
checkoutAddress2: {
},
checkoutCity: {
required: "Please enter your city",
noPlaceholder: "Please enter your city"
},
checkoutState: {
required: "Please select your state"
},
checkoutZip: {
required: "Please enter your zip code",
noPlaceholder: "Please enter your zip code",
digits: "Please enter your 5 digit zip code",
minlength: "Please enter your 5 digit zip code",
zipcodeUS: "Please enter a valid zip code"
},
cardNumber: {
required: "Please enter your card number",
noPlaceholder: "Please enter your card number",
rangelength: "Please enter a valid card number",
ccRecognize : "Please enter a valid card number"
},
ccMonth: {
required: "Please select month expiry"
},
ccYear: {
required: "Please select year expiry"
},
ccCode: {
required: "Please enter the security code on the back of your card",
noPlaceholder: "Please enter your security code",
minlength: "Please enter a valid security code",
maxlength: "Please enter a valid security code",
digits: "Please enter a valid security code"
},
billingFirstName: {
required: "Please enter your first name",
noPlaceholder: "Please enter your first name"
},
billingLastName: {
required: "Please enter your last name",
noPlaceholder: "Please enter your last name"
},
billingPhone: {
required: "Please enter your phone number",
noPlaceholder: "Please enter your phone number",
phoneUS: "Please enter a valid phone number"
},
billingAddress: {
required: "Please enter your street address",
noPlaceholder: "Please enter your street address"
},
billingAddress2: {
},
billingCity: {
required: "Please enter your city",
noPlaceholder: "Please enter your city"
},
billingState: {
required: "Please select your state",
noPlaceholder: "Please enter your state"
},
billingZip: {
required: "Please enter your zip code",
noPlaceholder: "Please enter your zip code",
digits: "Please enter your 5 digit zip code",
minlength: "Please enter your 5 digit zip code",
zipcodeUS: "Please enter a valid zip code"
},
cardNumberGC: {
required: "Please enter your card number",
noPlaceholder: "Please enter your card number",
rangelength: "Please enter a valid card number",
ccRecognize : "Please enter a valid card number"
},
ccCodeGC: {
required: "Please enter the security code on the back of your card",
noPlaceholder: "Please enter your security code",
minlength: "Please enter a valid security code",
maxlength: "Please enter a valid security code",
digits: "Please enter a valid security code"
}
},
i = 0,
$discountCodes = $jQ("#vzn-checkout-code input[name*=discountCode]"),
$giftCards = $jQ("#vzn-checkout-gift input[name*=giftCard]");
$discountCodes.each(function() {
var n = $jQ(this).attr("name");
validationRules[n] = {
required: false,
noPlaceholder: true,
/* digits: true, */
minlength: 1,
maxlength: 16
};
validationMessages[n] = {
required: "Please enter a valid discount code",
noPlaceholder: "Please enter a valid discount code",
minlength: "Please enter a valid discount code",
maxlength: "Please enter a valid discount code"
};
});
$giftCards.each(function() {
var n = $jQ(this).attr("name");
if (n.substr(n.length-3).toLowerCase() == "pin")
{
validationRules[n] = {
required: false,
noPlaceholder: true,
/* digits: true, */
minlength: 1,
maxlength: 7
};
validationMessages[n] = {
required: "Please enter a valid gift card PIN",
noPlaceholder: "Please enter a valid gift card PIN",
minlength: "Please enter a valid gift card PIN",
maxlength: "Please enter a valid gift card PIN"
};
} else {
validationRules[n] = {
required: false,
noPlaceholder: true,
digits: true,
minlength: 1,
maxlength: 16
};
validationMessages[n] = {
required: "Please enter a valid discount code",
noPlaceholder: "Please enter a valid discount code",
minlength: "Please enter a valid discount code",
maxlength: "Please enter a valid discount code"
};
}
});
$jQ(this).validate({
ignore: '.ignore, :hidden',
success: function(label){
label.addClass('success').text('');
},
focusCleanup: true,
rules: validationRules,
messages: validationMessages
});
});
}
};
| validation patch
| js/checkout.js | validation patch | <ide><path>s/checkout.js
<ide> success: function(label){
<ide> label.addClass('success').text('');
<ide> },
<add> highlight: function(element, errorClass, validClass) {
<add> if ( element.type === "radio" ) {
<add> this.findByName(element.name).addClass(errorClass).removeClass(validClass);
<add> } else {
<add> $jQ(element).addClass(errorClass).removeClass(validClass);
<add> }
<add> $jQ(element).siblings(".error.success").removeClass('success');
<add> },
<ide> focusCleanup: true,
<ide> rules: validationRules,
<ide> messages: validationMessages |
|
JavaScript | agpl-3.0 | ca05eb75c5abda46fded6957c17edfed103f3a18 | 0 | inaes-tic/mbc-common | // Save a reference to the global object (`window` in the browser, `global`
// on the server).
var root = this;
// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var App, server = false;
if (typeof exports !== 'undefined') {
App = exports;
server = true;
} else {
App = root.App = {};
}
// Require Underscore, Backbone & BackboneIO, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
var BackboneIO = root.BackboneIO;
if ((typeof require !== 'undefined')) Backbone = require('backbone');
App.Collection = Backbone.Collection.extend({
urlRoot: 'app',
backend: 'appbackend',
initialize: function () {
if (!server) {
this.bindBackend();
this.bind('backend', function(method, model) {
console.log ('got from backend:', method, model);
});
}
console.log ('creating new App.Collection');
Backbone.Collection.prototype.initialize.call (this);
}
});
App.Status = Backbone.Model.extend ({
backend: 'statusbackend',
urlRoot: 'status',
idAttribute: '_id',
initialize: function () {
if (!server) {
this.bindBackend();
this.bind('backend', function(method, model) {
console.log ('STATUS got from backend:', method, model);
});
}
console.log ('creating new STATUS');
return Backbone.Model.prototype.initialize.call (this);
},
defaults: {
_id: 2,
piece: {
previous: {name: ''},
current: {name: '', progress: '0%'},
next: {name: ''},
},
show: {
previous: {name: ''},
current: {name: '', progress: '0%'},
next: {name: ''},
},
source: null,
on_air: false,
},
});
App.ProgressStatus = Backbone.Model.extend({
urlRoot: 'progress',
backend: 'framebackend',
initialize: function () {
if (!server) {
this.bindBackend();
this.bind('backend', function(method, model) {
//console.log ('got from backend:', method, model);
});
}
console.log ('creating new App.Model');
return Backbone.Model.prototype.initialize.call (this);
},
defaults: {
id: 3,
currentFrame: 0,
totalFrames: 0,
},
});
App.TranscodeProgress = Backbone.Model.extend({
urlRoot: 'transcode',
backend: 'transcodeprogressbackend',
idAttribute: '_id',
initialize: function () {
return Backbone.Model.prototype.initialize.call (this);
},
defaults: {
'input': {
'stat': {
'size': 0,
},
'path': '',
},
'filename': '',
'stage': '',
'progress': '0',
// list of: {name:'', status:'', message:''}
'tasks': [],
}
});
App.TranscodeProgressCollection = Backbone.Collection.extend({
url: 'transcode',
model: App.TranscodeProgress,
backend: 'transcodebackend',
initialize: function () {
if(!server) {
this.bindBackend();
}
},
});
App.TranscodeStatus = Backbone.Model.extend({
urlRoot: 'transcodestatus',
backend: 'transcodestatusbackend',
idAttribute: '_id',
initialize: function () {
if(!server) {
this.bindBackend();
}
return Backbone.Model.prototype.initialize.call (this);
},
defaults: {
'_id': 1,
'running': false,
}
});
// Given a path like 'Caspa.Branding.name', a hash-like with the user config
// and another one with defaults retrieves both.
function get_value (path, conf, defaults) {
var path = path.split('.');
var val = conf;
var dfl = defaults;
var found = false;
var key;
var ret = {
value: null,
default: null,
found: false,
};
do {
key = path.shift();
if (_.has(val, key) ) {
val = val[key];
if (path.length == 0) {
found = true;
}
}
if (_.has(dfl, key) ) {
dfl = dfl[key];
}
} while (path.length);
ret.default = ret.value = dfl;
ret.found = found;
if (found) {
ret.value = val;
}
return ret;
};
// Given three objects like the ones returned from configStore, merge them
// in a structure suitable to parse into nested relational models.
// Guess how big N is...
function flatten_conf (conf, defaults, descriptions, root) {
if (root == undefined) {
var root = {
properties: [],
};
// XXX: _.omit() returns a copy of the object.
_.extend(root, _.omit(descriptions, ['properties', 'type']));
if (!_.has(descriptions, 'properties') || descriptions.properties.length==0) {
if (descriptions.type && !descriptions.type.match(/config|defaults|descriptions/)) {
root.type = descriptions.type;
}
}
}
_.each(descriptions.properties, function(contents, name, par) {
var dfl, dsc, cnf;
var ret = get_value(name, conf, defaults);
dfl = ret.default;
cnf = ret.value;
dsc = contents;
var elm = {
name: name,
properties: [],
};
// XXX: _.omit() returns a copy of the object.
_.extend(elm, _.omit(contents, ['properties', 'type']));
if (!_.has(dsc, 'properties') || dsc.properties.length==0) {
elm.value = cnf;
elm.default = dfl;
if (contents.type && !contents.type.match(/config|defaults|descriptions/)) {
elm.type = contents.type;
}
}
root.properties.push(elm);
flatten_conf(cnf, dfl, dsc, elm);
});
return root;
};
// Given a nested structure like the one from RelationalConfig.toJSON()
// transforms it to the format expected by configStore
function relational_to_server_conf (rel, root) {
var root = root || {};
_.each(rel.properties, function(contents, name, par) {
if (!_.has(contents, 'properties') || contents.properties.length==0) {
root[contents.name] = contents.value;
} else {
var elm = { };
root[contents.name] = elm;
relational_to_server_conf(contents, elm);
}
});
return root;
};
if(!server){
App.RelationalConfig = Backbone.RelationalModel.extend({
idAttribute: '_id',
relations: [{
type: Backbone.HasMany,
key: 'properties',
relatedModel: 'App.RelationalConfig',
collectionType: 'Backbone.Collection',
includeInJSON: true,
}],
initialize: function () {
var self = this;
console.log ('creating new RelationalConfig');
Backbone.RelationalModel.prototype.initialize.call (this);
},
defaults: {
type: null,
widget: 'input',
title: '',
description: '',
name: '',
value: null,
default: null,
properties: [],
},
});
}
if(server) module.exports = App;
else root.App = App;
| models/App.js | // Save a reference to the global object (`window` in the browser, `global`
// on the server).
var root = this;
// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var App, server = false;
if (typeof exports !== 'undefined') {
App = exports;
server = true;
} else {
App = root.App = {};
}
// Require Underscore, Backbone & BackboneIO, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
var BackboneIO = root.BackboneIO;
if ((typeof require !== 'undefined')) Backbone = require('backbone');
App.Collection = Backbone.Collection.extend({
urlRoot: 'app',
backend: 'appbackend',
initialize: function () {
if (!server) {
this.bindBackend();
this.bind('backend', function(method, model) {
console.log ('got from backend:', method, model);
});
}
console.log ('creating new App.Collection');
Backbone.Collection.prototype.initialize.call (this);
}
});
App.Status = Backbone.Model.extend ({
backend: 'statusbackend',
urlRoot: 'status',
idAttribute: '_id',
initialize: function () {
if (!server) {
this.bindBackend();
this.bind('backend', function(method, model) {
console.log ('STATUS got from backend:', method, model);
});
}
console.log ('creating new STATUS');
return Backbone.Model.prototype.initialize.call (this);
},
defaults: {
_id: 2,
piece: {
previous: {name: ''},
current: {name: '', progress: '0%'},
next: {name: ''},
},
show: {
previous: {name: ''},
current: {name: '', progress: '0%'},
next: {name: ''},
},
source: null,
on_air: false,
},
});
App.ProgressStatus = Backbone.Model.extend({
urlRoot: 'progress',
backend: 'framebackend',
initialize: function () {
if (!server) {
this.bindBackend();
this.bind('backend', function(method, model) {
//console.log ('got from backend:', method, model);
});
}
console.log ('creating new App.Model');
return Backbone.Model.prototype.initialize.call (this);
},
defaults: {
id: 3,
currentFrame: 0,
totalFrames: 0,
},
});
App.TranscodeProgress = Backbone.Model.extend({
urlRoot: 'transcode',
backend: 'transcodeprogressbackend',
idAttribute: '_id',
initialize: function () {
return Backbone.Model.prototype.initialize.call (this);
},
defaults: {
'input': {
'stat': {
'size': 0,
},
'path': '',
},
'filename': '',
'stage': '',
'progress': '0',
// list of: {name:'', status:'', message:''}
'tasks': [],
}
});
App.TranscodeProgressCollection = Backbone.Collection.extend({
url: 'transcode',
model: App.TranscodeProgress,
backend: 'transcodebackend',
initialize: function () {
if(!server) {
this.bindBackend();
}
},
});
App.TranscodeStatus = Backbone.Model.extend({
urlRoot: 'transcodestatus',
backend: 'transcodestatusbackend',
idAttribute: '_id',
initialize: function () {
if(!server) {
this.bindBackend();
}
return Backbone.Model.prototype.initialize.call (this);
},
defaults: {
'_id': 1,
'running': false,
}
});
// Given a path like 'Caspa.Branding.name', a hash-like with the user config
// and another one with defaults retrieves both.
function get_value (path, conf, defaults) {
var path = path.split('.');
var val = conf;
var dfl = defaults;
var found = false;
var key;
var ret = {
value: null,
default: null,
found: false,
};
do {
key = path.shift();
if (_.has(val, key) ) {
val = val[key];
if (path.length == 0) {
found = true;
}
}
if (_.has(dfl, key) ) {
dfl = dfl[key];
}
} while (path.length);
ret.default = ret.value = dfl;
ret.found = found;
if (found) {
ret.value = val;
}
return ret;
};
// Given three objects like the ones returned from configStore, merge them
// in a structure suitable to parse into nested relational models.
// Guess how big N is...
function flatten_conf (conf, defaults, descriptions, root) {
if (root == undefined) {
var root = {
properties: [],
};
// XXX: _.omit() returns a copy of the object.
_.extend(root, _.omit(descriptions, ['properties', 'type']));
if (!descriptions.type.match(/config|defaults|descriptions|object/)) {
root.type = descriptions.type;
}
}
_.each(descriptions.properties, function(contents, name, par) {
var dfl, dsc, cnf;
var ret = get_value(name, conf, defaults);
dfl = ret.default;
cnf = ret.value;
dsc = contents;
var elm = {
name: name,
properties: [],
};
// XXX: _.omit() returns a copy of the object.
_.extend(elm, _.omit(contents, ['properties', 'type']));
if (!contents.type.match(/config|defaults|descriptions|object/)) {
elm.type = contents.type;
}
if (!_.has(dsc, 'properties') || dsc.properties.length==0) {
elm.value = cnf;
elm.default = dfl;
}
root.properties.push(elm);
flatten_conf(cnf, dfl, dsc, elm);
});
return root;
};
// Given a nested structure like the one from RelationalConfig.toJSON()
// transforms it to the format expected by configStore
function relational_to_server_conf (rel, root) {
var root = root || {};
_.each(rel.properties, function(contents, name, par) {
if (!_.has(contents, 'properties') || contents.properties.length==0) {
root[contents.name] = contents.value;
} else {
var elm = { };
root[contents.name] = elm;
relational_to_server_conf(contents, elm);
}
});
return root;
};
if(!server){
App.RelationalConfig = Backbone.RelationalModel.extend({
idAttribute: '_id',
relations: [{
type: Backbone.HasMany,
key: 'properties',
relatedModel: 'App.RelationalConfig',
collectionType: 'Backbone.Collection',
includeInJSON: true,
}],
initialize: function () {
var self = this;
console.log ('creating new RelationalConfig');
Backbone.RelationalModel.prototype.initialize.call (this);
},
defaults: {
type: null,
widget: 'input',
title: '',
description: '',
name: '',
value: null,
default: null,
properties: [],
},
});
}
if(server) module.exports = App;
else root.App = App;
| config: correctly handle elements type.
Previously an element of type 'object' would be rendered on a different
level and also without the correct value.
| models/App.js | config: correctly handle elements type. | <ide><path>odels/App.js
<ide>
<ide> // XXX: _.omit() returns a copy of the object.
<ide> _.extend(root, _.omit(descriptions, ['properties', 'type']));
<del> if (!descriptions.type.match(/config|defaults|descriptions|object/)) {
<del> root.type = descriptions.type;
<add> if (!_.has(descriptions, 'properties') || descriptions.properties.length==0) {
<add> if (descriptions.type && !descriptions.type.match(/config|defaults|descriptions/)) {
<add> root.type = descriptions.type;
<add> }
<ide> }
<ide> }
<ide>
<ide>
<ide> // XXX: _.omit() returns a copy of the object.
<ide> _.extend(elm, _.omit(contents, ['properties', 'type']));
<del> if (!contents.type.match(/config|defaults|descriptions|object/)) {
<del> elm.type = contents.type;
<del> }
<del>
<ide> if (!_.has(dsc, 'properties') || dsc.properties.length==0) {
<ide> elm.value = cnf;
<ide> elm.default = dfl;
<add> if (contents.type && !contents.type.match(/config|defaults|descriptions/)) {
<add> elm.type = contents.type;
<add> }
<ide> }
<ide>
<ide> root.properties.push(elm); |
|
Java | apache-2.0 | 15b1f4828cfb60b274250494623f9b83b1a0728d | 0 | javadev/orderdatabase | package com.github.javadev.orderdatabase;
import com.github.underscore.Block;
import com.github.underscore.Function;
import com.github.underscore.Function1;
import com.github.underscore.Predicate;
import com.github.underscore.lodash.$;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.table.AbstractTableModel;
public class NewJDialog9 extends javax.swing.JDialog {
private final Function<List<Map<String, Object>>> databaseDataFunc;
private boolean isApproved;
public NewJDialog9(java.awt.Frame parent, boolean modal,
Function<List<Map<String, Object>>> databaseDataFunc) {
super(parent, modal);
initComponents();
this.databaseDataFunc = databaseDataFunc;
jTable1.setModel(new MyModel(getDatabaseMetrics()));
}
private static class MyModel extends AbstractTableModel {
private static final String[] columnNames = {"Дата создания", "Число созданных заявок",
"Число оплаченных заявок", "Подробности"};
private final List<Map<String, Object>> list;
private MyModel(List<Map<String, Object>> list) {
this.list = list;
}
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
@Override
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int index) {
return columnNames[index];
}
@Override
public int getRowCount() {
return list.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0:
return list.get(rowIndex).get("summaryCreated");
case 1:
return list.get(rowIndex).get("countCreated");
case 2:
return list.get(rowIndex).get("countPayed");
case 3:
return list.get(rowIndex).get("summary");
}
return null;
}
}
public boolean isApproved() {
return isApproved;
}
public List<Map<String, Object>> getDatabaseMetrics() {
Map<String, List<Map<String, Object>>> groupedByOrderNumber = $.chain(databaseDataFunc.apply())
.sortBy(new Function1<Map<String, Object>, Long>() {
public Long apply(Map<String, Object> arg) {
return (Long) arg.get("created");
}
})
.groupBy(new Function1<Map<String, Object>, String>() {
@Override
public String apply(Map<String, Object> arg) {
return (String) arg.get("orderNumber");
}
})
.item();
Map<String, List<Map.Entry<String, List<Map<String, Object>>>>> groupedByDate =
$.chain(groupedByOrderNumber.entrySet())
.groupBy(new Function1<Map.Entry<String, List<Map<String, Object>>>, String>() {
@Override
public String apply(Map.Entry<String, List<Map<String, Object>>> arg) {
return new SimpleDateFormat("dd.MM.yyyy").format(
new Date((Long) arg.getValue().get(0).get("created")));
}
})
.item();
final List<Map<String, Object>> createdOrders =
$.chain(groupedByDate.entrySet())
.map(new Function1<Map.Entry<String, List<Map.Entry<String, List<Map<String, Object>>>>>,
Map<String, Object>>() {
public Map<String, Object> apply(final Map.Entry<String, List<Map.Entry<String, List<Map<String, Object>>>>> arg) {
List<Map.Entry<String, List<Map<String, Object>>>> payedOrders =
$.filter(arg.getValue(), new Predicate<Map.Entry<String, List<Map<String, Object>>>>() {
public Boolean apply(Map.Entry<String, List<Map<String, Object>>> arg) {
String status = (String) $.last(arg.getValue()).get("status");
return status != null && status.equals("оплачено");
}
});
Map<String, Object> map = new LinkedHashMap<>();
map.put("summaryCreated", arg.getKey());
map.put("countCreated", arg.getValue().size());
map.put("countPayed", payedOrders.size());
return map;
}
}).value();
return createdOrders;
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jButton5 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Статистика использования");
jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel1.setText("Статистика использования");
jButton5.setFont(new java.awt.Font("Times New Roman", 2, 18)); // NOI18N
jButton5.setText("ОК");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jTable1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Дата создания", "Число созданных заявок", "Число оплаченных заявок", "Подробности"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane2.setViewportView(jTable1);
jButton1.setFont(new java.awt.Font("Times New Roman", 2, 18)); // NOI18N
jButton1.setText("Обновить");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(42, 42, 42)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 247, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jButton1))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jButton5)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
setVisible(false);
isApproved = true;
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
jTable1.setModel(new MyModel(getDatabaseMetrics()));
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| src/main/java/com/github/javadev/orderdatabase/NewJDialog9.java | package com.github.javadev.orderdatabase;
import com.github.underscore.Block;
import com.github.underscore.Function;
import com.github.underscore.Function1;
import com.github.underscore.lodash.$;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.table.AbstractTableModel;
public class NewJDialog9 extends javax.swing.JDialog {
private final Function<List<Map<String, Object>>> databaseDataFunc;
private boolean isApproved;
public NewJDialog9(java.awt.Frame parent, boolean modal,
Function<List<Map<String, Object>>> databaseDataFunc) {
super(parent, modal);
initComponents();
this.databaseDataFunc = databaseDataFunc;
jTable1.setModel(new MyModel(getDatabaseMetrics()));
}
private static class MyModel extends AbstractTableModel {
private static final String[] columnNames = {"Дата создания", "Число созданных заявок",
"Число оплаченных заявок", "Подробности"};
private final List<Map<String, Object>> list;
private MyModel(List<Map<String, Object>> list) {
this.list = list;
}
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
@Override
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int index) {
return columnNames[index];
}
@Override
public int getRowCount() {
return list.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0:
return list.get(rowIndex).get("summaryCreated");
case 1:
return list.get(rowIndex).get("countCreated");
case 2:
return list.get(rowIndex).get("countPayed");
case 3:
return list.get(rowIndex).get("summary");
}
return null;
}
}
public boolean isApproved() {
return isApproved;
}
public List<Map<String, Object>> getDatabaseMetrics() {
Map<String, List<Map<String, Object>>> groupedByOrderNumber = $.chain(databaseDataFunc.apply())
.sortBy(new Function1<Map<String, Object>, Long>() {
public Long apply(Map<String, Object> arg) {
return (Long) arg.get("created");
}
})
.groupBy(new Function1<Map<String, Object>, String>() {
@Override
public String apply(Map<String, Object> arg) {
return (String) arg.get("orderNumber");
}
})
.item();
Map<String, List<Map.Entry<String, List<Map<String, Object>>>>> groupedByDate =
$.chain(groupedByOrderNumber.entrySet())
.groupBy(new Function1<Map.Entry<String, List<Map<String, Object>>>, String>() {
@Override
public String apply(Map.Entry<String, List<Map<String, Object>>> arg) {
return new SimpleDateFormat("dd.MM.yyyy").format(
new Date((Long) arg.getValue().get(0).get("created")));
}
})
.item();
final List<Map<String, Object>> createdOrders = new ArrayList<>();
$.each(groupedByDate.entrySet(), new Block<Map.Entry<String, List<Map.Entry<String, List<Map<String, Object>>>>>>() {
public void apply(final Map.Entry<String, List<Map.Entry<String, List<Map<String, Object>>>>> arg) {
int found = 0;
for (Map.Entry<String, List<Map<String, Object>>> item : arg.getValue()) {
String status = (String) $.last(item.getValue()).get("status");
if (status != null && status.equals("оплачено")) {
found += 1;
}
}
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("summaryCreated", arg.getKey());
map.put("countCreated", arg.getValue().size());
map.put("countPayed", found);
createdOrders.add(map);
}
});
return createdOrders;
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jButton5 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Статистика использования");
jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel1.setText("Статистика использования");
jButton5.setFont(new java.awt.Font("Times New Roman", 2, 18)); // NOI18N
jButton5.setText("ОК");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jTable1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Дата создания", "Число созданных заявок", "Число оплаченных заявок", "Подробности"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane2.setViewportView(jTable1);
jButton1.setFont(new java.awt.Font("Times New Roman", 2, 18)); // NOI18N
jButton1.setText("Обновить");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(42, 42, 42)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 247, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jButton1))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jButton5)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
setVisible(false);
isApproved = true;
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
jTable1.setModel(new MyModel(getDatabaseMetrics()));
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| Improve metrics calculations.
| src/main/java/com/github/javadev/orderdatabase/NewJDialog9.java | Improve metrics calculations. | <ide><path>rc/main/java/com/github/javadev/orderdatabase/NewJDialog9.java
<ide> import com.github.underscore.Block;
<ide> import com.github.underscore.Function;
<ide> import com.github.underscore.Function1;
<add>import com.github.underscore.Predicate;
<ide> import com.github.underscore.lodash.$;
<ide> import java.text.SimpleDateFormat;
<ide> import java.util.ArrayList;
<ide> }
<ide> })
<ide> .item();
<del> final List<Map<String, Object>> createdOrders = new ArrayList<>();
<del> $.each(groupedByDate.entrySet(), new Block<Map.Entry<String, List<Map.Entry<String, List<Map<String, Object>>>>>>() {
<del> public void apply(final Map.Entry<String, List<Map.Entry<String, List<Map<String, Object>>>>> arg) {
<del> int found = 0;
<del> for (Map.Entry<String, List<Map<String, Object>>> item : arg.getValue()) {
<del> String status = (String) $.last(item.getValue()).get("status");
<del> if (status != null && status.equals("оплачено")) {
<del> found += 1;
<del> }
<del> }
<del> Map<String, Object> map = new LinkedHashMap<String, Object>();
<add> final List<Map<String, Object>> createdOrders =
<add> $.chain(groupedByDate.entrySet())
<add> .map(new Function1<Map.Entry<String, List<Map.Entry<String, List<Map<String, Object>>>>>,
<add> Map<String, Object>>() {
<add> public Map<String, Object> apply(final Map.Entry<String, List<Map.Entry<String, List<Map<String, Object>>>>> arg) {
<add> List<Map.Entry<String, List<Map<String, Object>>>> payedOrders =
<add> $.filter(arg.getValue(), new Predicate<Map.Entry<String, List<Map<String, Object>>>>() {
<add> public Boolean apply(Map.Entry<String, List<Map<String, Object>>> arg) {
<add> String status = (String) $.last(arg.getValue()).get("status");
<add> return status != null && status.equals("оплачено");
<add> }
<add> });
<add> Map<String, Object> map = new LinkedHashMap<>();
<ide> map.put("summaryCreated", arg.getKey());
<ide> map.put("countCreated", arg.getValue().size());
<del> map.put("countPayed", found);
<del> createdOrders.add(map);
<del> }
<del> });
<add> map.put("countPayed", payedOrders.size());
<add> return map;
<add> }
<add> }).value();
<ide> return createdOrders;
<ide> }
<ide> |
|
Java | agpl-3.0 | 8573b4948714c3299de3c76c0b83eff29be8763f | 0 | CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine | package com.splicemachine.derby.transactions;
import com.splicemachine.derby.test.framework.SpliceSchemaWatcher;
import com.splicemachine.derby.test.framework.SpliceTableWatcher;
import com.splicemachine.derby.test.framework.SpliceWatcher;
import com.splicemachine.derby.test.framework.TestConnection;
import com.splicemachine.pipeline.exception.ErrorState;
import com.splicemachine.test.SerialTest;
import com.splicemachine.test.Transactions;
import org.junit.*;
import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import static org.junit.Assert.fail;
/**
* @author Scott Fines
* Date: 9/4/14
*/
@Category({Transactions.class})
public class DropTableTransactionIT {
public static final SpliceSchemaWatcher schemaWatcher = new SpliceSchemaWatcher(DropTableTransactionIT.class.getSimpleName().toUpperCase());
public static final SpliceTableWatcher table = new SpliceTableWatcher("A",schemaWatcher.schemaName,"(a int, b int)");
public static final SpliceWatcher classWatcher = new SpliceWatcher();
@ClassRule
public static TestRule chain = RuleChain.outerRule(classWatcher)
.around(schemaWatcher);
private static TestConnection conn1;
private static TestConnection conn2;
private long conn1Txn;
private long conn2Txn;
@BeforeClass
public static void setUpClass() throws Exception {
conn1 = classWatcher.getOrCreateConnection();
conn2 = classWatcher.createConnection();
}
@AfterClass
public static void tearDownClass() throws Exception {
conn1.close();
conn2.close();
}
@After
public void tearDown() throws Exception {
conn1.rollback();
conn1.reset();
conn2.rollback();
conn2.reset();
}
@Before
public void setUp() throws Exception {
conn1.setAutoCommit(false);
conn2.setAutoCommit(false);
conn1Txn = conn1.getCurrentTransactionId();
conn2Txn = conn2.getCurrentTransactionId();
}
@Test
public void testDropTableIgnoredByOtherTransactions() throws Exception {
//create the table here to make sure that it exists
table.start();
//roll forward the transactions in case they were created before the creation
tearDown();
setUp();
//issue the drop statement
conn1.createStatement().execute("drop table " + table);
//now confirm that you can keep writing and reading data from the table from conn2
int aInt = 1;
int bInt = 1;
PreparedStatement ps = conn2.prepareStatement("insert into " + table+"(a,b) values (?,?)");
ps.setInt(1,aInt);ps.setInt(2,bInt);ps.execute();
long count = conn2.count("select * from "+ table+" where a="+aInt);
Assert.assertEquals("Unable to read data from dropped table!",1l,count);
//commit conn1
conn1.commit();
//confirm we still can write and read from it
ps = conn2.prepareStatement("insert into " + table+"(a,b) values (?,?)");
ps.setInt(1,aInt);ps.setInt(2,bInt);ps.execute();
count = conn2.count("select * from "+ table+" where a="+aInt);
Assert.assertEquals("Unable to read data from dropped table!",2l,count);
//commit conn2. Table should be dropped to conn2 now
conn2.commit();
//we shouldn't be able to see the table now
try{
conn2.prepareStatement("insert into " + table+"(a,b) values (?,?)");
fail("should not be able to see");
}catch(SQLException se){
System.out.printf("%s:%s%n",se.getSQLState(),se.getMessage());
Assert.assertEquals("Incorrect error message!", ErrorState.LANG_TABLE_NOT_FOUND.getSqlState(),se.getSQLState());
}
}
@Test
public void testDropTableRollback() throws Exception {
//create the table here to make sure that it exists
table.start();
//roll forward the transactions in case they were created before the creation
tearDown();
setUp();
conn1.createStatement().execute("drop table "+ table);
conn1.rollback();
//confirm that the table is still visible
int aInt = 2;
int bInt = 2;
PreparedStatement ps = conn1.prepareStatement("insert into " + table+"(a,b) values (?,?)");
ps.setInt(1,aInt);ps.setInt(2,bInt);ps.execute();
long count = conn1.count("select * from "+ table+" where a="+aInt);
Assert.assertEquals("Unable to read data from dropped table!",1l,count);
}
@Test
public void testCanDropUnrelatedTablesConcurrently() throws Exception {
new SpliceTableWatcher("t",schemaWatcher.schemaName,"(a int unique not null, b int)").start();
new SpliceTableWatcher("t2",schemaWatcher.schemaName,"(a int unique not null, b int)").start();
conn1.commit();
conn2.commit(); //roll both connections forward to ensure visibility
/*
* Now try and drop both tables, one table in each transaction, and make sure that they do not conflict
* with each other
*/
conn1.createStatement().execute("drop table "+ schemaWatcher+".t");
conn2.createStatement().execute("drop table "+ schemaWatcher+".t2");
//commit the two transactions to make sure that the tables no longer exist
conn1.commit();
conn2.commit();
}
@Test
public void testDroppingSameTableGivesWriteWriteConflict() throws Exception {
new SpliceTableWatcher("t3",schemaWatcher.schemaName,"(a int unique not null, b int)").start();
conn1.commit();
conn2.commit(); //roll both connections forward to ensure visibility
/*
* Now try and drop both tables, one table in each transaction, and make sure that they do not conflict
* with each other
*/
conn1.createStatement().execute("drop table "+ schemaWatcher+".t3");
try{
conn2.createStatement().execute("drop table "+ schemaWatcher+".t3");
fail("Did not throw a Write/Write conflict");
}catch(SQLException se){
Assert.assertEquals("Incorrect error message!",ErrorState.WRITE_WRITE_CONFLICT.getSqlState(),se.getSQLState());
}finally{
//commit the two transactions to make sure that the tables no longer exist
conn1.commit();
}
}
}
| splice_machine_test/src/test/java/com/splicemachine/derby/transactions/DropTableTransactionIT.java | package com.splicemachine.derby.transactions;
import com.splicemachine.derby.test.framework.SpliceSchemaWatcher;
import com.splicemachine.derby.test.framework.SpliceTableWatcher;
import com.splicemachine.derby.test.framework.SpliceWatcher;
import com.splicemachine.derby.test.framework.TestConnection;
import com.splicemachine.pipeline.exception.ErrorState;
import com.splicemachine.test.SerialTest;
import com.splicemachine.test.Transactions;
import org.junit.*;
import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author Scott Fines
* Date: 9/4/14
*/
@Category({Transactions.class})
public class DropTableTransactionIT {
public static final SpliceSchemaWatcher schemaWatcher = new SpliceSchemaWatcher(DropTableTransactionIT.class.getSimpleName().toUpperCase());
public static final SpliceTableWatcher table = new SpliceTableWatcher("A",schemaWatcher.schemaName,"(a int, b int)");
public static final SpliceWatcher classWatcher = new SpliceWatcher();
@ClassRule
public static TestRule chain = RuleChain.outerRule(classWatcher)
.around(schemaWatcher);
private static TestConnection conn1;
private static TestConnection conn2;
private long conn1Txn;
private long conn2Txn;
@BeforeClass
public static void setUpClass() throws Exception {
conn1 = classWatcher.getOrCreateConnection();
conn2 = classWatcher.createConnection();
}
@AfterClass
public static void tearDownClass() throws Exception {
conn1.close();
conn2.close();
}
@After
public void tearDown() throws Exception {
conn1.rollback();
conn1.reset();
conn2.rollback();
conn2.reset();
}
@Before
public void setUp() throws Exception {
conn1.setAutoCommit(false);
conn2.setAutoCommit(false);
conn1Txn = conn1.getCurrentTransactionId();
conn2Txn = conn2.getCurrentTransactionId();
}
@Test
public void testDropTableIgnoredByOtherTransactions() throws Exception {
//create the table here to make sure that it exists
table.start();
//roll forward the transactions in case they were created before the creation
tearDown();
setUp();
//issue the drop statement
conn1.createStatement().execute("drop table " + table);
//now confirm that you can keep writing and reading data from the table from conn1
int aInt = 1;
int bInt = 1;
PreparedStatement ps = conn2.prepareStatement("insert into " + table+"(a,b) values (?,?)");
ps.setInt(1,aInt);ps.setInt(2,bInt);ps.execute();
long count = conn2.count("select * from "+ table+" where a="+aInt);
Assert.assertEquals("Unable to read data from dropped table!",1l,count);
//commit conn1
conn1.commit();
//confirm we still can write and read from it
ps = conn2.prepareStatement("insert into " + table+"(a,b) values (?,?)");
ps.setInt(1,aInt);ps.setInt(2,bInt);ps.execute();
count = conn2.count("select * from "+ table+" where a="+aInt);
Assert.assertEquals("Unable to read data from dropped table!",2l,count);
//commit conn2. Table should be dropped to conn2 now
conn2.commit();
//we shouldn't be able to see the table now
try{
ps = conn2.prepareStatement("insert into " + table+"(a,b) values (?,?)");
}catch(SQLException se){
System.out.printf("%s:%s%n",se.getSQLState(),se.getMessage());
Assert.assertEquals("Incorrect error message!", ErrorState.LANG_TABLE_NOT_FOUND.getSqlState(),se.getSQLState());
}
}
@Test
public void testDropTableRollback() throws Exception {
//create the table here to make sure that it exists
table.start();
//roll forward the transactions in case they were created before the creation
tearDown();
setUp();
conn1.createStatement().execute("drop table "+ table);
conn1.rollback();
//confirm that the table is still visible
int aInt = 2;
int bInt = 2;
PreparedStatement ps = conn1.prepareStatement("insert into " + table+"(a,b) values (?,?)");
ps.setInt(1,aInt);ps.setInt(2,bInt);ps.execute();
long count = conn1.count("select * from "+ table+" where a="+aInt);
Assert.assertEquals("Unable to read data from dropped table!",1l,count);
}
@Test
public void testCanDropUnrelatedTablesConcurrently() throws Exception {
new SpliceTableWatcher("t",schemaWatcher.schemaName,"(a int unique not null, b int)").start();
new SpliceTableWatcher("t2",schemaWatcher.schemaName,"(a int unique not null, b int)").start();
conn1.commit();
conn2.commit(); //roll both connections forward to ensure visibility
/*
* Now try and drop both tables, one table in each transaction, and make sure that they do not conflict
* with each other
*/
conn1.createStatement().execute("drop table "+ schemaWatcher+".t");
conn2.createStatement().execute("drop table "+ schemaWatcher+".t2");
//commit the two transactions to make sure that the tables no longer exist
conn1.commit();
conn2.commit();
}
@Test
public void testDroppingSameTableGivesWriteWriteConflict() throws Exception {
new SpliceTableWatcher("t3",schemaWatcher.schemaName,"(a int unique not null, b int)").start();
conn1.commit();
conn2.commit(); //roll both connections forward to ensure visibility
/*
* Now try and drop both tables, one table in each transaction, and make sure that they do not conflict
* with each other
*/
conn1.createStatement().execute("drop table "+ schemaWatcher+".t3");
try{
conn2.createStatement().execute("drop table "+ schemaWatcher+".t3");
Assert.fail("Did not throw a Write/Write conflict");
}catch(SQLException se){
Assert.assertEquals("Incorrect error message!",ErrorState.WRITE_WRITE_CONFLICT.getSqlState(),se.getSQLState());
}finally{
//commit the two transactions to make sure that the tables no longer exist
conn1.commit();
}
}
}
| DropTableTransactionIT: add missing fail() assertion
| splice_machine_test/src/test/java/com/splicemachine/derby/transactions/DropTableTransactionIT.java | DropTableTransactionIT: add missing fail() assertion | <ide><path>plice_machine_test/src/test/java/com/splicemachine/derby/transactions/DropTableTransactionIT.java
<ide>
<ide> import java.sql.PreparedStatement;
<ide> import java.sql.SQLException;
<add>
<add>import static org.junit.Assert.fail;
<ide>
<ide> /**
<ide> * @author Scott Fines
<ide> //issue the drop statement
<ide> conn1.createStatement().execute("drop table " + table);
<ide>
<del> //now confirm that you can keep writing and reading data from the table from conn1
<add> //now confirm that you can keep writing and reading data from the table from conn2
<ide> int aInt = 1;
<ide> int bInt = 1;
<ide> PreparedStatement ps = conn2.prepareStatement("insert into " + table+"(a,b) values (?,?)");
<ide>
<ide> //we shouldn't be able to see the table now
<ide> try{
<del> ps = conn2.prepareStatement("insert into " + table+"(a,b) values (?,?)");
<add> conn2.prepareStatement("insert into " + table+"(a,b) values (?,?)");
<add> fail("should not be able to see");
<ide> }catch(SQLException se){
<ide> System.out.printf("%s:%s%n",se.getSQLState(),se.getMessage());
<ide> Assert.assertEquals("Incorrect error message!", ErrorState.LANG_TABLE_NOT_FOUND.getSqlState(),se.getSQLState());
<ide> conn1.createStatement().execute("drop table "+ schemaWatcher+".t3");
<ide> try{
<ide> conn2.createStatement().execute("drop table "+ schemaWatcher+".t3");
<del> Assert.fail("Did not throw a Write/Write conflict");
<add> fail("Did not throw a Write/Write conflict");
<ide> }catch(SQLException se){
<ide> Assert.assertEquals("Incorrect error message!",ErrorState.WRITE_WRITE_CONFLICT.getSqlState(),se.getSQLState());
<ide> }finally{ |
|
Java | epl-1.0 | 37e52a779cd01539b601e39b314d9e28a8d1f38f | 0 | DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base | package at.medevit.elexis.agenda.ui.function;
import java.time.LocalDate;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.eclipse.e4.ui.di.UISynchronize;
import org.eclipse.swt.chromium.Browser;
import org.eclipse.swt.widgets.Display;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import at.medevit.elexis.agenda.ui.composite.ScriptingHelper;
import at.medevit.elexis.agenda.ui.model.Event;
import ch.elexis.core.common.ElexisEventTopics;
import ch.elexis.core.model.IAppointment;
import ch.elexis.core.model.IContact;
import ch.elexis.core.model.IPeriod;
import ch.elexis.core.model.IUser;
import ch.elexis.core.model.ModelPackage;
import ch.elexis.core.services.IQuery;
import ch.elexis.core.services.IQuery.COMPARATOR;
import ch.elexis.core.services.holder.AppointmentServiceHolder;
import ch.elexis.core.services.holder.ContextServiceHolder;
import ch.elexis.core.services.holder.CoreModelServiceHolder;
public class LoadEventsFunction extends AbstractBrowserFunction {
private static Logger logger = LoggerFactory.getLogger(LoadEventsFunction.class);
private Gson gson;
private Set<String> resources = new HashSet<String>();
protected ScriptingHelper scriptingHelper;
private LoadingCache<TimeSpan, EventsJsonValue> cache;
protected long knownLastUpdate = 0;
private TimeSpan currentTimeSpan;
private Timer timer;
private class EventsJsonValue {
private Map<String, Event> eventsMap;
private String jsonString;
private TimeSpan timespan;
public EventsJsonValue(TimeSpan key, List<Event> events){
this.timespan = key;
this.eventsMap =
events.parallelStream().collect(Collectors.toMap(e -> e.getId(), e -> e));
jsonString = gson.toJson(eventsMap.values());
}
public String getJson(){
return jsonString;
}
public boolean updateWith(List<IPeriod> changedPeriods, IContact userContact){
boolean updated = false;
for (IPeriod iPeriod : changedPeriods) {
if (eventsMap.containsKey(iPeriod.getId())) {
boolean deleted = ((IAppointment) iPeriod).isDeleted();
if (deleted || !timespan.contains(iPeriod)) {
// deleted or moved outside timespan
eventsMap.remove(iPeriod.getId());
} else {
// updated still inside timespan
Event event = Event.of(iPeriod, userContact);
eventsMap.put(event.getId(), event);
}
updated = true;
} else if (timespan.contains(iPeriod)) {
// new or moved into timespan
Event event = Event.of(iPeriod, userContact);
eventsMap.put(event.getId(), event);
updated = true;
}
}
if (updated) {
jsonString = gson.toJson(eventsMap.values());
}
return updated;
}
}
private class TimeSpan {
private LocalDate startDate;
private LocalDate endDate;
private IContact userContact;
public TimeSpan(LocalDate startDate, LocalDate endDate, IContact userContact){
this.startDate = startDate;
this.endDate = endDate;
this.userContact = userContact;
}
@Override
public int hashCode(){
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((endDate == null) ? 0 : endDate.hashCode());
result = prime * result + ((startDate == null) ? 0 : startDate.hashCode());
return result;
}
@Override
public boolean equals(Object obj){
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TimeSpan other = (TimeSpan) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (endDate == null) {
if (other.endDate != null)
return false;
} else if (!endDate.equals(other.endDate))
return false;
if (startDate == null) {
if (other.startDate != null)
return false;
} else if (!startDate.equals(other.startDate))
return false;
return true;
}
private LoadEventsFunction getOuterType(){
return LoadEventsFunction.this;
}
public boolean contains(IPeriod iPeriod){
LocalDate periodStartDate = iPeriod.getStartTime().toLocalDate();
return (periodStartDate.isEqual(startDate) || periodStartDate.isAfter(startDate))
&& (periodStartDate.isEqual(endDate) || periodStartDate.isBefore(endDate));
}
@Override
public String toString(){
return "Timespan [" + startDate + " - " + endDate + "]";
}
}
public LoadEventsFunction(Browser browser, String name, ScriptingHelper scriptingHelper,
UISynchronize uiSynchronize){
super(browser, name);
gson = new GsonBuilder().create();
this.scriptingHelper = scriptingHelper;
cache = CacheBuilder.newBuilder().maximumSize(7).build(new TimeSpanLoader());
timer = new Timer("Agenda check for updates", true);
timer.schedule(new CheckForUpdatesTimerTask(this, uiSynchronize), 10000);
}
@Override
public Object function(Object[] arguments){
if (arguments.length == 3) {
try {
IContact userContact = ContextServiceHolder.get().getActiveUser()
.map(IUser::getAssignedContact).orElse(null);
currentTimeSpan =
new TimeSpan(getDateArg(arguments[0]), getDateArg(arguments[1]), userContact);
ContextServiceHolder.get().postEvent(ElexisEventTopics.BASE + "agenda/loadtimespan",
new LoadEventTimeSpan(currentTimeSpan.startDate, currentTimeSpan.endDate));
long currentLastUpdate =
CoreModelServiceHolder.get().getHighestLastUpdate(IAppointment.class);
if (knownLastUpdate == 0) {
knownLastUpdate = currentLastUpdate;
} else if (knownLastUpdate < currentLastUpdate) {
List<IPeriod> changedPeriods = getChangedPeriods();
ConcurrentMap<TimeSpan, EventsJsonValue> cacheAsMap = cache.asMap();
for (TimeSpan timeSpan : cacheAsMap.keySet()) {
EventsJsonValue eventsJson = cache.get(timeSpan);
if (eventsJson.updateWith(changedPeriods, userContact)) {
logger.debug("Updated timespan " + timeSpan);
} else {
logger.debug("No update to timespan " + timeSpan);
}
}
knownLastUpdate = currentLastUpdate;
}
EventsJsonValue eventsJson = cache.get(currentTimeSpan);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run(){
if (!isDisposed()) {
// update calendar height
updateCalendarHeight();
scriptingHelper.scrollToNow();
}
}
});
return eventsJson.getJson();
} catch (ExecutionException e) {
throw new IllegalStateException("Error loading events", e);
}
} else {
throw new IllegalArgumentException("Unexpected arguments");
}
}
/**
* Get all changed {@link IPeriod} since the knownLastUpdate.
*
* @return
*/
@SuppressWarnings("unchecked")
private List<IPeriod> getChangedPeriods(){
IQuery<IAppointment> query =
CoreModelServiceHolder.get().getQuery(IAppointment.class, true, true);
query.and("lastupdate", COMPARATOR.GREATER, Long.valueOf(knownLastUpdate));
if (!resources.isEmpty()) {
String[] resourceArray = resources.toArray(new String[resources.size()]);
query.startGroup();
for (int i = 0; i < resourceArray.length; i++) {
query.or(ModelPackage.Literals.IAPPOINTMENT__SCHEDULE, COMPARATOR.EQUALS,
resourceArray[i]);
}
query.andJoinGroups();
}
return (List<IPeriod>) (List<?>) query.execute();
}
public void addResource(String resource){
this.resources.add(resource);
}
public void removeResource(String resource){
this.resources.remove(resource);
}
public void setResources(List<String> resources){
this.resources.clear();
this.resources.addAll(resources);
cache.invalidateAll();
}
private class TimeSpanLoader extends CacheLoader<TimeSpan, EventsJsonValue> {
@Override
public EventsJsonValue load(TimeSpan key) throws Exception{
List<IPeriod> periods = getPeriods(key);
return new EventsJsonValue(key, periods.parallelStream()
.map(p -> Event.of(p, key.userContact)).collect(Collectors.toList()));
}
@SuppressWarnings("unchecked")
private List<IPeriod> getPeriods(TimeSpan timespan) throws IllegalStateException{
logger.debug("Loading timespan " + timespan);
LocalDate from = timespan.startDate;
LocalDate to = timespan.endDate;
for (String resource : resources) {
LocalDate updateDate = LocalDate.from(from);
do {
AppointmentServiceHolder.get().updateBoundaries(resource, updateDate);
updateDate = updateDate.plusDays(1);
} while (updateDate.isBefore(to) || updateDate.isEqual(to));
}
IQuery<IAppointment> query = CoreModelServiceHolder.get().getQuery(IAppointment.class);
if (!resources.isEmpty()) {
String[] resourceArray = resources.toArray(new String[resources.size()]);
query.startGroup();
for (int i = 0; i < resourceArray.length; i++) {
query.or(ModelPackage.Literals.IAPPOINTMENT__SCHEDULE, COMPARATOR.EQUALS,
resourceArray[i]);
}
query.andJoinGroups();
query.startGroup();
if (from != null) {
query.and("tag", COMPARATOR.GREATER_OR_EQUAL, from);
}
if (to != null) {
query.and("tag", COMPARATOR.LESS, to);
}
query.andJoinGroups();
return (List<IPeriod>) (List<?>) query.execute();
}
logger.debug("Loading timespan " + timespan + " finished");
return Collections.emptyList();
}
}
public List<IPeriod> getCurrentPeriods(){
TimeSpanLoader loader = new TimeSpanLoader();
return loader.getPeriods(currentTimeSpan);
}
/**
* Invalidate all cache entries. This should be done prior to changing the user.
*/
public void invalidateCache(){
cache.invalidateAll();
}
}
| bundles/at.medevit.elexis.agenda.ui/src/at/medevit/elexis/agenda/ui/function/LoadEventsFunction.java | package at.medevit.elexis.agenda.ui.function;
import java.time.LocalDate;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.eclipse.e4.ui.di.UISynchronize;
import org.eclipse.swt.chromium.Browser;
import org.eclipse.swt.widgets.Display;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import at.medevit.elexis.agenda.ui.composite.ScriptingHelper;
import at.medevit.elexis.agenda.ui.model.Event;
import ch.elexis.core.common.ElexisEventTopics;
import ch.elexis.core.model.IAppointment;
import ch.elexis.core.model.IContact;
import ch.elexis.core.model.IPeriod;
import ch.elexis.core.model.IUser;
import ch.elexis.core.model.ModelPackage;
import ch.elexis.core.services.IQuery;
import ch.elexis.core.services.IQuery.COMPARATOR;
import ch.elexis.core.services.holder.AppointmentServiceHolder;
import ch.elexis.core.services.holder.ContextServiceHolder;
import ch.elexis.core.services.holder.CoreModelServiceHolder;
public class LoadEventsFunction extends AbstractBrowserFunction {
private static Logger logger = LoggerFactory.getLogger(LoadEventsFunction.class);
private Gson gson;
private Set<String> resources = new HashSet<String>();
protected ScriptingHelper scriptingHelper;
private LoadingCache<TimeSpan, EventsJsonValue> cache;
protected long knownLastUpdate = 0;
private TimeSpan currentTimeSpan;
private Timer timer;
private class EventsJsonValue {
private Map<String, Event> eventsMap;
private String jsonString;
private TimeSpan timespan;
public EventsJsonValue(TimeSpan key, List<Event> events){
this.timespan = key;
this.eventsMap =
events.parallelStream().collect(Collectors.toMap(e -> e.getId(), e -> e));
jsonString = gson.toJson(eventsMap.values());
}
public String getJson(){
return jsonString;
}
public boolean updateWith(List<IPeriod> changedPeriods, IContact userContact){
boolean updated = false;
for (IPeriod iPeriod : changedPeriods) {
if (eventsMap.containsKey(iPeriod.getId())) {
boolean deleted = ((IAppointment) iPeriod).isDeleted();
if (deleted || !timespan.contains(iPeriod)) {
// deleted or moved outside timespan
eventsMap.remove(iPeriod.getId());
} else {
// updated still inside timespan
Event event = Event.of(iPeriod, userContact);
eventsMap.put(event.getId(), event);
}
updated = true;
} else if (timespan.contains(iPeriod)) {
// new or moved into timespan
Event event = Event.of(iPeriod, userContact);
eventsMap.put(event.getId(), event);
updated = true;
}
}
if (updated) {
jsonString = gson.toJson(eventsMap.values());
}
return updated;
}
}
private class TimeSpan {
private LocalDate startDate;
private LocalDate endDate;
private IContact userContact;
public TimeSpan(LocalDate startDate, LocalDate endDate, IContact userContact){
this.startDate = startDate;
this.endDate = endDate;
this.userContact = userContact;
}
@Override
public int hashCode(){
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((endDate == null) ? 0 : endDate.hashCode());
result = prime * result + ((startDate == null) ? 0 : startDate.hashCode());
return result;
}
@Override
public boolean equals(Object obj){
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TimeSpan other = (TimeSpan) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (endDate == null) {
if (other.endDate != null)
return false;
} else if (!endDate.equals(other.endDate))
return false;
if (startDate == null) {
if (other.startDate != null)
return false;
} else if (!startDate.equals(other.startDate))
return false;
return true;
}
private LoadEventsFunction getOuterType(){
return LoadEventsFunction.this;
}
public boolean contains(IPeriod iPeriod){
LocalDate periodStartDate = iPeriod.getStartTime().toLocalDate();
return (periodStartDate.isEqual(startDate) || periodStartDate.isAfter(startDate))
&& (periodStartDate.isEqual(endDate) || periodStartDate.isBefore(endDate));
}
@Override
public String toString(){
return "Timespan [" + startDate + " - " + endDate + "]";
}
}
public LoadEventsFunction(Browser browser, String name, ScriptingHelper scriptingHelper,
UISynchronize uiSynchronize){
super(browser, name);
gson = new GsonBuilder().create();
this.scriptingHelper = scriptingHelper;
cache = CacheBuilder.newBuilder().maximumSize(7).build(new TimeSpanLoader());
timer = new Timer("Agenda check for updates", true);
timer.schedule(new CheckForUpdatesTimerTask(this, uiSynchronize), 10000);
}
@Override
public Object function(Object[] arguments){
if (arguments.length == 3) {
try {
IContact userContact = ContextServiceHolder.get().getActiveUser()
.map(IUser::getAssignedContact).orElse(null);
currentTimeSpan =
new TimeSpan(getDateArg(arguments[0]), getDateArg(arguments[1]), userContact);
ContextServiceHolder.get().postEvent(ElexisEventTopics.BASE + "agenda/loadtimespan",
new LoadEventTimeSpan(currentTimeSpan.startDate, currentTimeSpan.endDate));
long currentLastUpdate =
CoreModelServiceHolder.get().getHighestLastUpdate(IAppointment.class);
if (knownLastUpdate == 0) {
knownLastUpdate = currentLastUpdate;
} else if (knownLastUpdate < currentLastUpdate) {
List<IPeriod> changedPeriods = getChangedPeriods();
ConcurrentMap<TimeSpan, EventsJsonValue> cacheAsMap = cache.asMap();
for (TimeSpan timeSpan : cacheAsMap.keySet()) {
EventsJsonValue eventsJson = cache.get(timeSpan);
if (eventsJson.updateWith(changedPeriods, userContact)) {
logger.debug("Updated timespan " + timeSpan);
} else {
logger.debug("No update to timespan " + timeSpan);
}
}
knownLastUpdate = currentLastUpdate;
}
EventsJsonValue eventsJson = cache.get(currentTimeSpan);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run(){
if (!isDisposed()) {
// update calendar height
updateCalendarHeight();
scriptingHelper.scrollToNow();
}
}
});
return eventsJson.getJson();
} catch (ExecutionException e) {
throw new IllegalStateException("Error loading events", e);
}
} else {
throw new IllegalArgumentException("Unexpected arguments");
}
}
/**
* Get all changed {@link IPeriod} since the knownLastUpdate.
*
* @return
*/
@SuppressWarnings("unchecked")
private List<IPeriod> getChangedPeriods(){
IQuery<IAppointment> query =
CoreModelServiceHolder.get().getQuery(IAppointment.class, true, true);
query.and("lastupdate", COMPARATOR.GREATER, Long.valueOf(knownLastUpdate));
return (List<IPeriod>) (List<?>) query.execute();
}
public void addResource(String resource){
this.resources.add(resource);
}
public void removeResource(String resource){
this.resources.remove(resource);
}
public void setResources(List<String> resources){
this.resources.clear();
this.resources.addAll(resources);
cache.invalidateAll();
}
private class TimeSpanLoader extends CacheLoader<TimeSpan, EventsJsonValue> {
@Override
public EventsJsonValue load(TimeSpan key) throws Exception{
List<IPeriod> periods = getPeriods(key);
return new EventsJsonValue(key, periods.parallelStream()
.map(p -> Event.of(p, key.userContact)).collect(Collectors.toList()));
}
@SuppressWarnings("unchecked")
private List<IPeriod> getPeriods(TimeSpan timespan) throws IllegalStateException{
logger.debug("Loading timespan " + timespan);
LocalDate from = timespan.startDate;
LocalDate to = timespan.endDate;
for (String resource : resources) {
LocalDate updateDate = LocalDate.from(from);
do {
AppointmentServiceHolder.get().updateBoundaries(resource, updateDate);
updateDate = updateDate.plusDays(1);
} while (updateDate.isBefore(to) || updateDate.isEqual(to));
}
IQuery<IAppointment> query = CoreModelServiceHolder.get().getQuery(IAppointment.class);
if (!resources.isEmpty()) {
String[] resourceArray = resources.toArray(new String[resources.size()]);
query.startGroup();
for (int i = 0; i < resourceArray.length; i++) {
query.or(ModelPackage.Literals.IAPPOINTMENT__SCHEDULE, COMPARATOR.EQUALS,
resourceArray[i]);
}
query.andJoinGroups();
query.startGroup();
if (from != null) {
query.and("tag", COMPARATOR.GREATER_OR_EQUAL, from);
}
if (to != null) {
query.and("tag", COMPARATOR.LESS, to);
}
query.andJoinGroups();
return (List<IPeriod>) (List<?>) query.execute();
}
logger.debug("Loading timespan " + timespan + " finished");
return Collections.emptyList();
}
}
public List<IPeriod> getCurrentPeriods(){
TimeSpanLoader loader = new TimeSpanLoader();
return loader.getPeriods(currentTimeSpan);
}
/**
* Invalidate all cache entries. This should be done prior to changing the user.
*/
public void invalidateCache(){
cache.invalidateAll();
}
}
| [22730] use selected resources to get changed periods for agenda | bundles/at.medevit.elexis.agenda.ui/src/at/medevit/elexis/agenda/ui/function/LoadEventsFunction.java | [22730] use selected resources to get changed periods for agenda | <ide><path>undles/at.medevit.elexis.agenda.ui/src/at/medevit/elexis/agenda/ui/function/LoadEventsFunction.java
<ide> IQuery<IAppointment> query =
<ide> CoreModelServiceHolder.get().getQuery(IAppointment.class, true, true);
<ide> query.and("lastupdate", COMPARATOR.GREATER, Long.valueOf(knownLastUpdate));
<add> if (!resources.isEmpty()) {
<add> String[] resourceArray = resources.toArray(new String[resources.size()]);
<add> query.startGroup();
<add> for (int i = 0; i < resourceArray.length; i++) {
<add> query.or(ModelPackage.Literals.IAPPOINTMENT__SCHEDULE, COMPARATOR.EQUALS,
<add> resourceArray[i]);
<add>
<add> }
<add> query.andJoinGroups();
<add> }
<ide> return (List<IPeriod>) (List<?>) query.execute();
<ide> }
<ide> |
|
Java | mit | 37c17c551258eaf3e4c9bc3961f3c8e3d646e630 | 0 | TulevaEE/onboarding-service,TulevaEE/onboarding-service,TulevaEE/onboarding-service,TulevaEE/onboarding-service | package ee.tuleva.onboarding.mandate.email;
import static ee.tuleva.onboarding.locale.LocaleConfiguration.DEFAULT_LOCALE;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.util.Collections.singletonList;
import com.microtripit.mandrillapp.lutung.view.MandrillMessage;
import ee.tuleva.onboarding.epis.contact.UserPreferences;
import ee.tuleva.onboarding.mandate.Mandate;
import ee.tuleva.onboarding.notification.email.EmailService;
import ee.tuleva.onboarding.user.User;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
@RequiredArgsConstructor
public class MandateEmailService {
private final EmailService emailService;
private final MandateEmailContentService emailContentService;
private final Clock clock;
public void sendMandate(
User user,
Mandate mandate,
PillarSuggestion pillarSuggestion,
UserPreferences contactDetails,
Locale locale) {
switch (pillarSuggestion.getOtherPillar()) {
case 2 -> sendSecondPillarEmail(user, mandate, pillarSuggestion, locale);
case 3 -> sendThirdPillarEmails(user, mandate, pillarSuggestion, contactDetails, locale);
default -> throw new IllegalArgumentException(
"Unknown pillar: " + pillarSuggestion.getOtherPillar());
}
}
private void sendSecondPillarEmail(
User user, Mandate mandate, PillarSuggestion pillarSuggestion, Locale locale) {
MandrillMessage mandrillMessage =
emailService.newMandrillMessage(
emailService.getRecipients(user),
"Pensionifondi avaldus",
getSecondPillarContent(user, mandate, pillarSuggestion, locale),
getMandateTags(pillarSuggestion),
getMandateAttachments(mandate.getSignedFile(), user, mandate.getId()));
emailService.send(user, mandrillMessage);
}
private void sendThirdPillarEmails(
User user,
Mandate mandate,
PillarSuggestion pillarSuggestion,
UserPreferences contactDetails,
Locale locale) {
sendThirdPillarPaymentDetailsEmail(user, mandate, contactDetails, locale);
sendThirdPillarSuggestSecondEmail(user, pillarSuggestion, locale);
}
private String getSecondPillarContent(
User user, Mandate mandate, PillarSuggestion pillarSuggestion, Locale locale) {
if (mandate.isWithdrawalCancellation()) {
return emailContentService.getSecondPillarWithdrawalCancellationHtml(user, locale);
}
if (mandate.isTransferCancellation()) {
return emailContentService.getSecondPillarTransferCancellationHtml(user, mandate, locale);
}
return emailContentService.getSecondPillarHtml(user, pillarSuggestion, locale);
}
private void sendThirdPillarPaymentDetailsEmail(
User user, Mandate mandate, UserPreferences contactDetails, Locale locale) {
String subject =
locale == DEFAULT_LOCALE
? "Sinu 3. samba tähtis info ja avalduse koopia"
: "Important information about your 3rd pillar and a copy of the application";
String content =
emailContentService.getThirdPillarPaymentDetailsHtml(
user, contactDetails.getPensionAccountNumber(), locale);
MandrillMessage mandrillMessage =
emailService.newMandrillMessage(
emailService.getRecipients(user),
subject,
content,
List.of("mandate"),
getMandateAttachments(mandate.getSignedFile(), user, mandate.getId()));
emailService.send(user, mandrillMessage);
}
private void sendThirdPillarSuggestSecondEmail(
User user, PillarSuggestion pillarSuggestion, Locale locale) {
if (!pillarSuggestion.suggestPillar()) return;
String subject =
locale == DEFAULT_LOCALE
? "Vaata oma teine sammas üle!"
: "Check where your second pillar is invested!";
String content = emailContentService.getThirdPillarSuggestSecondHtml(user, locale);
Instant sendAt = Instant.now(clock).plus(3, DAYS);
MandrillMessage message =
emailService.newMandrillMessage(
emailService.getRecipients(user), subject, content, List.of("suggest_2"), null);
emailService.send(user, message, sendAt);
}
List<String> getMandateTags(PillarSuggestion pillarSuggestion) {
List<String> tags = new ArrayList<>();
tags.add("mandate");
tags.add("pillar_" + pillarSuggestion.getOtherPillar());
if (pillarSuggestion.suggestMembership()) {
tags.add("suggest_member");
}
if (pillarSuggestion.suggestPillar()) {
tags.add("suggest_" + pillarSuggestion.getSuggestedPillar());
}
return tags;
}
private List<MandrillMessage.MessageContent> getMandateAttachments(
byte[] file, User user, Long mandateId) {
MandrillMessage.MessageContent attachment = new MandrillMessage.MessageContent();
attachment.setName(getNameSuffix(user) + "_avaldus_" + mandateId + ".bdoc");
attachment.setType("application/bdoc");
attachment.setContent(Base64.getEncoder().encodeToString(file));
return singletonList(attachment);
}
private String getNameSuffix(User user) {
String nameSuffix = user.getFirstName() + "_" + user.getLastName();
nameSuffix = nameSuffix.toLowerCase();
nameSuffix.replace("õ", "o");
nameSuffix.replace("ä", "a");
nameSuffix.replace("ö", "o");
nameSuffix.replace("ü", "u");
nameSuffix.replaceAll("[^a-zA-Z0-9_\\-\\.]", "_");
return nameSuffix;
}
}
| src/main/java/ee/tuleva/onboarding/mandate/email/MandateEmailService.java | package ee.tuleva.onboarding.mandate.email;
import static ee.tuleva.onboarding.locale.LocaleConfiguration.DEFAULT_LOCALE;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.util.Collections.singletonList;
import com.microtripit.mandrillapp.lutung.view.MandrillMessage;
import com.microtripit.mandrillapp.lutung.view.MandrillMessage.Recipient;
import ee.tuleva.onboarding.epis.contact.UserPreferences;
import ee.tuleva.onboarding.mandate.Mandate;
import ee.tuleva.onboarding.notification.email.EmailService;
import ee.tuleva.onboarding.user.User;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
@RequiredArgsConstructor
public class MandateEmailService {
private final EmailService emailService;
private final MandateEmailContentService emailContentService;
private final Clock clock;
public void sendMandate(
User user,
Mandate mandate,
PillarSuggestion pillarSuggestion,
UserPreferences contactDetails,
Locale locale) {
switch (pillarSuggestion.getOtherPillar()) {
case 2 -> sendSecondPillarEmail(user, mandate, pillarSuggestion, locale);
case 3 -> sendThirdPillarEmails(user, mandate, pillarSuggestion, contactDetails, locale);
default -> throw new IllegalArgumentException(
"Unknown pillar: " + pillarSuggestion.getOtherPillar());
}
}
private void sendSecondPillarEmail(
User user, Mandate mandate, PillarSuggestion pillarSuggestion, Locale locale) {
MandrillMessage mandrillMessage =
emailService.newMandrillMessage(
emailService.getRecipients(user),
"Pensionifondi avaldus",
getSecondPillarContent(user, mandate, pillarSuggestion, locale),
getMandateTags(pillarSuggestion),
getMandateAttachments(mandate.getSignedFile(), user, mandate.getId()));
emailService.send(user, mandrillMessage);
}
private void sendThirdPillarEmails(
User user,
Mandate mandate,
PillarSuggestion pillarSuggestion,
UserPreferences contactDetails,
Locale locale) {
sendThirdPillarPaymentDetailsEmail(user, mandate, contactDetails, locale);
sendThirdPillarSuggestSecondEmail(user, pillarSuggestion, locale);
}
private String getSecondPillarContent(
User user, Mandate mandate, PillarSuggestion pillarSuggestion, Locale locale) {
if (mandate.isWithdrawalCancellation()) {
return emailContentService.getSecondPillarWithdrawalCancellationHtml(user, locale);
}
if (mandate.isTransferCancellation()) {
return emailContentService.getSecondPillarTransferCancellationHtml(user, mandate, locale);
}
return emailContentService.getSecondPillarHtml(user, pillarSuggestion, locale);
}
private void sendThirdPillarPaymentDetailsEmail(
User user, Mandate mandate, UserPreferences contactDetails, Locale locale) {
String content =
emailContentService.getThirdPillarPaymentDetailsHtml(
user, contactDetails.getPensionAccountNumber(), locale);
String subject =
locale == DEFAULT_LOCALE
? "Sinu 3. samba tähtis info ja avalduse koopia"
: "Important information about your 3rd pillar and a copy of the application";
MandrillMessage mandrillMessage =
emailService.newMandrillMessage(
emailService.getRecipients(user),
subject,
content,
List.of("mandate"),
getMandateAttachments(mandate.getSignedFile(), user, mandate.getId()));
emailService.send(user, mandrillMessage);
}
private void sendThirdPillarSuggestSecondEmail(
User user, PillarSuggestion pillarSuggestion, Locale locale) {
if (!pillarSuggestion.suggestPillar()) return;
List<Recipient> recipients = emailService.getRecipients(user);
String subject =
locale == DEFAULT_LOCALE
? "Vaata oma teine sammas üle!"
: "Check where your second pillar is invested!";
String content = emailContentService.getThirdPillarSuggestSecondHtml(user, locale);
List<String> tags = List.of("suggest_2");
Instant sendAt = Instant.now(clock).plus(3, DAYS);
MandrillMessage message =
emailService.newMandrillMessage(recipients, subject, content, tags, null);
emailService.send(user, message, sendAt);
}
List<String> getMandateTags(PillarSuggestion pillarSuggestion) {
List<String> tags = new ArrayList<>();
tags.add("mandate");
tags.add("pillar_" + pillarSuggestion.getOtherPillar());
if (pillarSuggestion.suggestMembership()) {
tags.add("suggest_member");
}
if (pillarSuggestion.suggestPillar()) {
tags.add("suggest_" + pillarSuggestion.getSuggestedPillar());
}
return tags;
}
private List<MandrillMessage.MessageContent> getMandateAttachments(
byte[] file, User user, Long mandateId) {
MandrillMessage.MessageContent attachment = new MandrillMessage.MessageContent();
attachment.setName(getNameSuffix(user) + "_avaldus_" + mandateId + ".bdoc");
attachment.setType("application/bdoc");
attachment.setContent(Base64.getEncoder().encodeToString(file));
return singletonList(attachment);
}
private String getNameSuffix(User user) {
String nameSuffix = user.getFirstName() + "_" + user.getLastName();
nameSuffix = nameSuffix.toLowerCase();
nameSuffix.replace("õ", "o");
nameSuffix.replace("ä", "a");
nameSuffix.replace("ö", "o");
nameSuffix.replace("ü", "u");
nameSuffix.replaceAll("[^a-zA-Z0-9_\\-\\.]", "_");
return nameSuffix;
}
}
| Improve code readability
| src/main/java/ee/tuleva/onboarding/mandate/email/MandateEmailService.java | Improve code readability | <ide><path>rc/main/java/ee/tuleva/onboarding/mandate/email/MandateEmailService.java
<ide> import static java.util.Collections.singletonList;
<ide>
<ide> import com.microtripit.mandrillapp.lutung.view.MandrillMessage;
<del>import com.microtripit.mandrillapp.lutung.view.MandrillMessage.Recipient;
<ide> import ee.tuleva.onboarding.epis.contact.UserPreferences;
<ide> import ee.tuleva.onboarding.mandate.Mandate;
<ide> import ee.tuleva.onboarding.notification.email.EmailService;
<ide>
<ide> private void sendThirdPillarPaymentDetailsEmail(
<ide> User user, Mandate mandate, UserPreferences contactDetails, Locale locale) {
<del> String content =
<del> emailContentService.getThirdPillarPaymentDetailsHtml(
<del> user, contactDetails.getPensionAccountNumber(), locale);
<ide> String subject =
<ide> locale == DEFAULT_LOCALE
<ide> ? "Sinu 3. samba tähtis info ja avalduse koopia"
<ide> : "Important information about your 3rd pillar and a copy of the application";
<add> String content =
<add> emailContentService.getThirdPillarPaymentDetailsHtml(
<add> user, contactDetails.getPensionAccountNumber(), locale);
<ide>
<ide> MandrillMessage mandrillMessage =
<ide> emailService.newMandrillMessage(
<ide> User user, PillarSuggestion pillarSuggestion, Locale locale) {
<ide> if (!pillarSuggestion.suggestPillar()) return;
<ide>
<del> List<Recipient> recipients = emailService.getRecipients(user);
<ide> String subject =
<ide> locale == DEFAULT_LOCALE
<ide> ? "Vaata oma teine sammas üle!"
<ide> : "Check where your second pillar is invested!";
<ide> String content = emailContentService.getThirdPillarSuggestSecondHtml(user, locale);
<del> List<String> tags = List.of("suggest_2");
<ide> Instant sendAt = Instant.now(clock).plus(3, DAYS);
<ide>
<ide> MandrillMessage message =
<del> emailService.newMandrillMessage(recipients, subject, content, tags, null);
<add> emailService.newMandrillMessage(
<add> emailService.getRecipients(user), subject, content, List.of("suggest_2"), null);
<ide> emailService.send(user, message, sendAt);
<ide> }
<ide> |
|
Java | apache-2.0 | a0d1b61a1766c811ea8c3fbd39a3ef8f129825c9 | 0 | leveluplunch/levelup-java-exercises | package com.levelup.java.exercises.beginner;
import java.util.List;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
/**
* This java example will demonstrate how to convert a phrase to pig latin.
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/exercises/pig-latin-translator/'>Pig latin translator</a>
*/
public class PigLatin {
public static void main(String[] args) {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Ask user to enter a string to translate
System.out.println("Enter a string to translate to Pig Latin.");
System.out.print("> ");
String input = keyboard.nextLine();
// close the keyboard
keyboard.close();
List<String> elementsInString = Lists.newArrayList(Splitter.on(" ")
.split(input));
Function<String, String> swapFirstLastChar = new Function<String, String>() {
@Override
public String apply(String s) {
if (s.length() <= 1) {
return s;
} else {
return s.substring(1, s.length()) + s.charAt(0);
}
}
};
List<String> translatedString = elementsInString.stream()
.map(String::trim).map(String::toUpperCase)
.map(swapFirstLastChar).map((String s) -> {
return s + "AY";
}).collect(Collectors.toList());
System.out.println("Translated sentence is: "
+ String.join(" ", translatedString));
}
} | src/main/java/com/levelup/java/exercises/beginner/PigLatin.java | package com.levelup.java.exercises.beginner;
import java.util.List;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
/**
* This java example will demonstrate how to convert a phrase to pig latin.
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/exercises/pig-latin-translator/'>Pig latin translator</a>
*/
public class PigLatin {
public static void main(String[] args) {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Ask user to enter a string to translate
System.out.println("Enter a string to translate to Pig Latin.");
System.out.print("> ");
String input = keyboard.nextLine();
// close the keyboard
keyboard.close();
List<String> elementsInString = Lists.newArrayList(Splitter.on(" ")
.split(input));
Function<String, String> swapFirstLastChar = new Function<String, String>() {
@Override
public String apply(String s) {
if (s.length() <= 1) {
return s;
} else {
return s.substring(1, s.length()) + s.charAt(0);
}
}
};
List<String> translatedString = elementsInString.stream()
.map(String::trim).map(String::toUpperCase)
.map(swapFirstLastChar).map((String s) -> {
return s + "AY";
}).collect(Collectors.toList());
System.out.println("Translated sentence is: "
+ String.join(" ", translatedString));
}
} | removed space
| src/main/java/com/levelup/java/exercises/beginner/PigLatin.java | removed space | <ide><path>rc/main/java/com/levelup/java/exercises/beginner/PigLatin.java
<ide> public class PigLatin {
<ide>
<ide> public static void main(String[] args) {
<add>
<ide> // Create a Scanner object for keyboard input.
<ide> Scanner keyboard = new Scanner(System.in);
<ide> |
|
Java | epl-1.0 | 1d975c1324349cda0d41d17ee7aa3ccb2717ea92 | 0 | gnodet/wikitext | /*******************************************************************************
* Copyright (c) 2004 - 2006 Mylar committers and others.
* 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.eclipse.mylar.jira.tests;
import java.io.File;
import java.net.Proxy;
import junit.framework.TestCase;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.mylar.context.tests.support.MylarTestUtils;
import org.eclipse.mylar.context.tests.support.MylarTestUtils.Credentials;
import org.eclipse.mylar.context.tests.support.MylarTestUtils.PrivilegeLevel;
import org.eclipse.mylar.internal.jira.core.model.Attachment;
import org.eclipse.mylar.internal.jira.core.model.Comment;
import org.eclipse.mylar.internal.jira.core.model.Issue;
import org.eclipse.mylar.internal.jira.core.model.Resolution;
import org.eclipse.mylar.internal.jira.core.model.Version;
import org.eclipse.mylar.internal.jira.core.model.filter.FilterDefinition;
import org.eclipse.mylar.internal.jira.core.service.AbstractJiraClient;
import org.eclipse.mylar.internal.jira.core.service.JiraClient;
import org.eclipse.mylar.internal.jira.core.service.JiraException;
import org.eclipse.mylar.internal.jira.core.service.JiraRemoteMessageException;
import org.eclipse.mylar.internal.jira.core.service.soap.JiraRpcClient;
import org.eclipse.mylar.internal.jira.ui.JiraTaskDataHandler;
/**
* @author Steffen Pingel
*/
public class JiraRpcClientTest extends TestCase {
private AbstractJiraClient client;
protected void init(String url, PrivilegeLevel level) throws Exception {
Credentials credentials = MylarTestUtils.readCredentials(level);
client = new JiraRpcClient(url, false, credentials.username, credentials.password, Proxy.NO_PROXY, null, null);
JiraTestUtils.refreshDetails(client);
}
public void testLogin381() throws Exception {
login(JiraTestConstants.JIRA_39_URL);
}
@SuppressWarnings("deprecation")
private void login(String url) throws Exception {
init(url, PrivilegeLevel.USER);
client.login();
client.logout();
// should automatically login
client.refreshDetails(new NullProgressMonitor());
init(url, PrivilegeLevel.GUEST);
client.login();
}
public void testStartStopIssue() throws Exception {
startStopIssue(JiraTestConstants.JIRA_39_URL);
}
private void startStopIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = JiraTestUtils.createIssue(client, "testStartStopIssue");
client.startIssue(issue);
try {
client.startIssue(issue);
fail("Expected JiraRemoteMessageException");
} catch (JiraRemoteMessageException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
client.stopIssue(issue);
try {
client.stopIssue(issue);
fail("Expected JiraRemoteMessageException");
} catch (JiraException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
client.startIssue(issue);
}
public void testResolveCloseReopenIssue() throws Exception {
resolveCloseReopenIssue(JiraTestConstants.JIRA_39_URL);
}
private void resolveCloseReopenIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Resolution resolution = JiraTestUtils.getFixedResolution(client);
Issue issue = JiraTestUtils.createIssue(client, "testStartStopIssue");
client.resolveIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
issue = client.getIssueByKey(issue.getKey());
assertTrue(issue.getStatus().isResolved());
try {
client.resolveIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
fail("Expected JiraRemoteMessageException");
} catch (JiraRemoteMessageException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
client.closeIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
issue = client.getIssueByKey(issue.getKey());
assertTrue(issue.getStatus().isClosed());
try {
client.resolveIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
fail("Expected JiraRemoteMessageException");
} catch (JiraRemoteMessageException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
try {
client.closeIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
fail("Expected JiraRemoteMessageException");
} catch (JiraException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
client.reopenIssue(issue, "comment", JiraClient.ASSIGNEE_DEFAULT, "");
issue = client.getIssueByKey(issue.getKey());
assertTrue(issue.getStatus().isReopened());
}
public void testGetIdFromKey() throws Exception {
getIdFromKey(JiraTestConstants.JIRA_39_URL);
}
private void getIdFromKey(String url) throws Exception {
init(url, PrivilegeLevel.GUEST);
Issue issue = JiraTestUtils.createIssue(client, "getIdFromKey");
String key = client.getKeyFromId(issue.getId());
assertEquals(issue.getKey(), key);
try {
key = client.getKeyFromId("invalid");
fail("Expected JiraException, got: " + key);
} catch (JiraException e) {
}
try {
key = client.getKeyFromId("1");
fail("Expected JiraException, got: " + key);
} catch (JiraException e) {
}
}
public void testReassign() throws Exception {
reassign(JiraTestConstants.JIRA_39_URL);
}
private void reassign(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = JiraTestUtils.createIssue(client, "testReassign");
issue.setAssignee("nonexistantuser");
try {
client.updateIssue(issue, "comment");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
assertEquals("User 'nonexistantuser' cannot be assigned issues.", e.getHtmlMessage());
}
try {
client.assignIssueTo(issue, JiraClient.ASSIGNEE_NONE, "", "");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
assertEquals("Issues must be assigned.", e.getHtmlMessage());
}
try {
client.assignIssueTo(issue, JiraClient.ASSIGNEE_SELF, "", "");
} catch (JiraRemoteMessageException e) {
assertEquals("Issue already assigned to Test User 1 (" + client.getUserName() + ").", e.getHtmlMessage());
}
String guestUsername = MylarTestUtils.readCredentials(PrivilegeLevel.GUEST).username;
try {
client.assignIssueTo(issue, JiraClient.ASSIGNEE_USER, guestUsername, "");
} catch (JiraRemoteMessageException e) {
assertEquals("User '[email protected]' cannot be assigned issues.", e.getHtmlMessage());
}
client.assignIssueTo(issue, JiraClient.ASSIGNEE_DEFAULT, "", "");
issue = client.getIssueByKey(issue.getKey());
assertEquals("[email protected]", issue.getAssignee());
client.assignIssueTo(issue, JiraClient.ASSIGNEE_SELF, "", "");
issue = client.getIssueByKey(issue.getKey());
assertEquals(client.getUserName(), issue.getAssignee());
init(url, PrivilegeLevel.GUEST);
try {
client.assignIssueTo(issue, JiraClient.ASSIGNEE_SELF, "", "");
fail("Expected JiraException");
} catch (JiraException e) {
}
}
public void testFindIssues() throws Exception {
findIssues(JiraTestConstants.JIRA_39_URL);
}
private void findIssues(String url) throws Exception {
init(url, PrivilegeLevel.USER);
FilterDefinition filter = new FilterDefinition();
MockIssueCollector collector = new MockIssueCollector();
client.search(filter, collector);
assertTrue(collector.done);
}
public void testAddComment() throws Exception {
addComment(JiraTestConstants.JIRA_39_URL);
}
private void addComment(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = JiraTestUtils.createIssue(client, "testAddComment");
client.addCommentToIssue(issue, "comment 1");
issue = client.getIssueByKey(issue.getKey());
Comment comment = getComment(issue, "comment 1");
assertNotNull(comment);
assertEquals(client.getUserName(), comment.getAuthor());
init(url, PrivilegeLevel.GUEST);
client.addCommentToIssue(issue, "comment guest");
issue = client.getIssueByKey(issue.getKey());
comment = getComment(issue, "comment guest");
assertNotNull(comment);
assertEquals(client.getUserName(), comment.getAuthor());
}
private Comment getComment(Issue issue, String text) {
for (Comment comment : issue.getComments()) {
if (text.equals(comment.getComment())) {
return comment;
}
}
return null;
}
public void testAttachFile() throws Exception {
attachFile(JiraTestConstants.JIRA_39_URL);
}
private void attachFile(String url) throws Exception {
init(url, PrivilegeLevel.USER);
File file = File.createTempFile("mylar", null);
file.deleteOnExit();
Issue issue = JiraTestUtils.createIssue(client, "testAttachFile");
// test attaching an empty file
try {
client.attachFile(issue, "", file.getName(), file, "application/binary");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
}
client.attachFile(issue, "", "my.filename.1", new byte[] { 'M', 'y', 'l', 'a', 'r' }, "application/binary");
issue = client.getIssueByKey(issue.getKey());
Attachment attachment = getAttachment(issue, "my.filename.1");
assertNotNull(attachment);
assertEquals(client.getUserName(), attachment.getAuthor());
assertEquals(5, attachment.getSize());
assertNotNull(attachment.getCreated());
}
private Attachment getAttachment(Issue issue, String filename) {
for (Attachment attachment : issue.getAttachments()) {
if (filename.equals(attachment.getName())) {
return attachment;
}
}
return null;
}
public void testCreateIssue() throws Exception {
createIssue(JiraTestConstants.JIRA_39_URL);
}
private void createIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = new Issue();
issue.setProject(client.getProjects()[0]);
issue.setType(client.getIssueTypes()[0]);
issue.setSummary("testCreateIssue");
issue.setAssignee(client.getUserName());
Issue createdIssue = client.createIssue(issue);
assertEquals(issue.getProject(), createdIssue.getProject());
assertEquals(issue.getType(), createdIssue.getType());
assertEquals(issue.getSummary(), createdIssue.getSummary());
assertEquals(issue.getAssignee(), createdIssue.getAssignee());
assertEquals(client.getUserName(), createdIssue.getReporter());
// TODO why are these null?
// assertNotNull(issue.getCreated());
// assertNotNull(issue.getUpdated());
init(url, PrivilegeLevel.GUEST);
createdIssue = client.createIssue(issue);
assertEquals(issue.getProject(), createdIssue.getProject());
assertEquals(issue.getType(), createdIssue.getType());
assertEquals(issue.getSummary(), createdIssue.getSummary());
assertEquals("[email protected]", createdIssue.getAssignee());
assertEquals(client.getUserName(), createdIssue.getReporter());
}
public void testGetIssueLeadingSpacesInDescription() throws Exception {
getIssueLeadingSpacesInDescripton(JiraTestConstants.JIRA_39_URL);
}
private void getIssueLeadingSpacesInDescripton(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = new Issue();
issue.setProject(client.getProjects()[0]);
issue.setType(client.getIssueTypes()[0]);
issue.setSummary("testCreateIssue");
String description = " leading spaces\n more spaces";
issue.setDescription(description);
issue.setAssignee(client.getUserName());
issue = client.createIssue(issue);
issue = client.getIssueByKey(issue.getKey());
assertEquals(description, JiraTaskDataHandler.convertHtml(issue.getDescription()));
issue.setDescription(JiraTaskDataHandler.convertHtml(issue.getDescription()));
client.updateIssue(issue, "");
issue = client.getIssueByKey(issue.getKey());
assertEquals(description, JiraTaskDataHandler.convertHtml(issue.getDescription()));
}
public void testUpdateIssue() throws Exception {
updateIssue(JiraTestConstants.JIRA_39_URL);
}
private void updateIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = new Issue();
issue.setProject(client.getProjects()[0]);
issue.setType(client.getIssueTypes()[0]);
issue.setSummary("testUpdateIssue");
issue.setAssignee(client.getUserName());
issue = client.createIssue(issue);
issue.setSummary("testUpdateIssueChanged");
client.updateIssue(issue, "");
issue = client.getIssueByKey(issue.getKey());
assertEquals("testUpdateIssueChanged", issue.getSummary());
assertNotNull(issue.getUpdated());
init(url, PrivilegeLevel.GUEST);
try {
client.updateIssue(issue, "");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
}
init(url, PrivilegeLevel.GUEST);
issue.setSummary("testUpdateIssueGuest");
issue = client.createIssue(issue);
issue.setSummary("testUpdateIssueGuestChanged");
try {
client.updateIssue(issue, "");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
}
}
public void testWatchUnwatchIssue() throws Exception {
watchUnwatchIssue(JiraTestConstants.JIRA_39_URL);
}
private void watchUnwatchIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = JiraTestUtils.createIssue(client, "testWatchUnwatch");
assertFalse(issue.isWatched());
client.watchIssue(issue);
issue = client.getIssueByKey(issue.getKey());
// flag is never set
// assertTrue(issue.isWatched());
client.unwatchIssue(issue);
issue = client.getIssueByKey(issue.getKey());
assertFalse(issue.isWatched());
client.unwatchIssue(issue);
issue = client.getIssueByKey(issue.getKey());
assertFalse(issue.isWatched());
}
}
| org.eclipse.mylyn.jira.tests/src/org/eclipse/mylyn/jira/tests/JiraRpcClientTest.java | /*******************************************************************************
* Copyright (c) 2004 - 2006 Mylar committers and others.
* 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.eclipse.mylar.jira.tests;
import java.io.File;
import java.net.Proxy;
import junit.framework.TestCase;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.mylar.context.tests.support.MylarTestUtils;
import org.eclipse.mylar.context.tests.support.MylarTestUtils.Credentials;
import org.eclipse.mylar.context.tests.support.MylarTestUtils.PrivilegeLevel;
import org.eclipse.mylar.internal.jira.core.model.Attachment;
import org.eclipse.mylar.internal.jira.core.model.Comment;
import org.eclipse.mylar.internal.jira.core.model.Issue;
import org.eclipse.mylar.internal.jira.core.model.Resolution;
import org.eclipse.mylar.internal.jira.core.model.Version;
import org.eclipse.mylar.internal.jira.core.model.filter.FilterDefinition;
import org.eclipse.mylar.internal.jira.core.service.AbstractJiraClient;
import org.eclipse.mylar.internal.jira.core.service.JiraClient;
import org.eclipse.mylar.internal.jira.core.service.JiraException;
import org.eclipse.mylar.internal.jira.core.service.JiraRemoteMessageException;
import org.eclipse.mylar.internal.jira.core.service.soap.JiraRpcClient;
import org.eclipse.mylar.internal.jira.ui.JiraTaskDataHandler;
/**
* @author Steffen Pingel
*/
public class JiraRpcClientTest extends TestCase {
private AbstractJiraClient client;
protected void init(String url, PrivilegeLevel level) throws Exception {
Credentials credentials = MylarTestUtils.readCredentials(level);
client = new JiraRpcClient(url, false, credentials.username, credentials.password, Proxy.NO_PROXY, null, null);
JiraTestUtils.refreshDetails(client);
}
public void testLogin381() throws Exception {
login(JiraTestConstants.JIRA_39_URL);
}
@SuppressWarnings("deprecation")
private void login(String url) throws Exception {
init(url, PrivilegeLevel.USER);
client.login();
client.logout();
// should automatically login
client.refreshDetails(new NullProgressMonitor());
init(url, PrivilegeLevel.GUEST);
client.login();
}
public void testStartStopIssue() throws Exception {
startStopIssue(JiraTestConstants.JIRA_39_URL);
}
private void startStopIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = JiraTestUtils.createIssue(client, "testStartStopIssue");
client.startIssue(issue);
try {
client.startIssue(issue);
fail("Expected JiraRemoteMessageException");
} catch (JiraRemoteMessageException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
client.stopIssue(issue);
try {
client.stopIssue(issue);
fail("Expected JiraRemoteMessageException");
} catch (JiraException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
client.startIssue(issue);
}
public void testResolveCloseReopenIssue() throws Exception {
resolveCloseReopenIssue(JiraTestConstants.JIRA_39_URL);
}
private void resolveCloseReopenIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Resolution resolution = JiraTestUtils.getFixedResolution(client);
Issue issue = JiraTestUtils.createIssue(client, "testStartStopIssue");
client.resolveIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
issue = client.getIssueByKey(issue.getKey());
assertTrue(issue.getStatus().isResolved());
try {
client.resolveIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
fail("Expected JiraRemoteMessageException");
} catch (JiraRemoteMessageException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
client.closeIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
issue = client.getIssueByKey(issue.getKey());
assertTrue(issue.getStatus().isClosed());
try {
client.resolveIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
fail("Expected JiraRemoteMessageException");
} catch (JiraRemoteMessageException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
try {
client.closeIssue(issue, resolution, new Version[0], "comment", JiraClient.ASSIGNEE_DEFAULT, "");
fail("Expected JiraRemoteMessageException");
} catch (JiraException e) {
assertEquals("Workflow Action Invalid", e.getMessage());
}
client.reopenIssue(issue, "comment", JiraClient.ASSIGNEE_DEFAULT, "");
issue = client.getIssueByKey(issue.getKey());
assertTrue(issue.getStatus().isReopened());
}
public void testGetIdFromKey() throws Exception {
getIdFromKey(JiraTestConstants.JIRA_39_URL);
}
private void getIdFromKey(String url) throws Exception {
init(url, PrivilegeLevel.GUEST);
Issue issue = JiraTestUtils.createIssue(client, "getIdFromKey");
String key = client.getKeyFromId(issue.getId());
assertEquals(issue.getKey(), key);
try {
key = client.getKeyFromId("invalid");
fail("Expected JiraException, got: " + key);
} catch (JiraException e) {
}
try {
key = client.getKeyFromId("1");
fail("Expected JiraException, got: " + key);
} catch (JiraException e) {
}
}
public void testReassign() throws Exception {
reassign(JiraTestConstants.JIRA_39_URL);
}
private void reassign(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = JiraTestUtils.createIssue(client, "testReassign");
issue.setAssignee("nonexistantuser");
try {
client.updateIssue(issue, "comment");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
assertEquals("User 'nonexistantuser' cannot be assigned issues.", e.getHtmlMessage());
}
try {
client.assignIssueTo(issue, JiraClient.ASSIGNEE_NONE, "", "");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
assertEquals("Issues must be assigned.", e.getHtmlMessage());
}
try {
client.assignIssueTo(issue, JiraClient.ASSIGNEE_SELF, "", "");
} catch (JiraRemoteMessageException e) {
assertEquals("Issue already assigned to Test User 1 (" + client.getUserName() + ").", e.getHtmlMessage());
}
String guestUsername = MylarTestUtils.readCredentials(PrivilegeLevel.GUEST).username;
try {
client.assignIssueTo(issue, JiraClient.ASSIGNEE_USER, guestUsername, "");
} catch (JiraRemoteMessageException e) {
assertEquals("User '[email protected]' cannot be assigned issues.", e.getHtmlMessage());
}
client.assignIssueTo(issue, JiraClient.ASSIGNEE_DEFAULT, "", "");
issue = client.getIssueByKey(issue.getKey());
assertEquals("[email protected]", issue.getAssignee());
client.assignIssueTo(issue, JiraClient.ASSIGNEE_SELF, "", "");
issue = client.getIssueByKey(issue.getKey());
assertEquals(client.getUserName(), issue.getAssignee());
init(url, PrivilegeLevel.GUEST);
try {
client.assignIssueTo(issue, JiraClient.ASSIGNEE_SELF, "", "");
fail("Expected JiraException");
} catch (JiraException e) {
}
}
public void testFindIssues() throws Exception {
findIssues(JiraTestConstants.JIRA_39_URL);
}
private void findIssues(String url) throws Exception {
init(url, PrivilegeLevel.USER);
FilterDefinition filter = new FilterDefinition();
MockIssueCollector collector = new MockIssueCollector();
client.search(filter, collector);
assertTrue(collector.done);
}
public void testAddComment() throws Exception {
addComment(JiraTestConstants.JIRA_39_URL);
}
private void addComment(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = JiraTestUtils.createIssue(client, "testAddComment");
client.addCommentToIssue(issue, "comment 1");
issue = client.getIssueByKey(issue.getKey());
Comment comment = getComment(issue, "comment 1");
assertNotNull(comment);
assertEquals(client.getUserName(), comment.getAuthor());
init(url, PrivilegeLevel.GUEST);
client.addCommentToIssue(issue, "comment guest");
issue = client.getIssueByKey(issue.getKey());
comment = getComment(issue, "comment guest");
assertNotNull(comment);
assertEquals(client.getUserName(), comment.getAuthor());
}
private Comment getComment(Issue issue, String text) {
for (Comment comment : issue.getComments()) {
if (text.equals(comment.getComment())) {
return comment;
}
}
return null;
}
public void testAttachFile() throws Exception {
attachFile(JiraTestConstants.JIRA_39_URL);
}
private void attachFile(String url) throws Exception {
init(url, PrivilegeLevel.USER);
File file = File.createTempFile("mylar", null);
file.deleteOnExit();
Issue issue = JiraTestUtils.createIssue(client, "testAttachFile");
// test attaching an empty file
try {
client.attachFile(issue, "", file.getName(), file, "application/binary");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
}
client.attachFile(issue, "", "my.filename.1", new byte[] { 'M', 'y', 'l', 'a', 'r' }, "application/binary");
issue = client.getIssueByKey(issue.getKey());
Attachment attachment = getAttachment(issue, "my.filename.1");
assertNotNull(attachment);
assertEquals(client.getUserName(), attachment.getAuthor());
assertEquals(5, attachment.getSize());
assertNotNull(attachment.getCreated());
}
private Attachment getAttachment(Issue issue, String filename) {
for (Attachment attachment : issue.getAttachments()) {
if (filename.equals(attachment.getName())) {
return attachment;
}
}
return null;
}
public void testCreateIssue() throws Exception {
createIssue(JiraTestConstants.JIRA_39_URL);
}
private void createIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = new Issue();
issue.setProject(client.getProjects()[0]);
issue.setType(client.getIssueTypes()[0]);
issue.setSummary("testCreateIssue");
issue.setAssignee(client.getUserName());
Issue createdIssue = client.createIssue(issue);
assertEquals(issue.getProject(), createdIssue.getProject());
assertEquals(issue.getType(), createdIssue.getType());
assertEquals(issue.getSummary(), createdIssue.getSummary());
assertEquals(issue.getAssignee(), createdIssue.getAssignee());
assertEquals(client.getUserName(), createdIssue.getReporter());
// TODO why are these null?
// assertNotNull(issue.getCreated());
// assertNotNull(issue.getUpdated());
init(url, PrivilegeLevel.GUEST);
createdIssue = client.createIssue(issue);
assertEquals(issue.getProject(), createdIssue.getProject());
assertEquals(issue.getType(), createdIssue.getType());
assertEquals(issue.getSummary(), createdIssue.getSummary());
assertEquals("[email protected]", createdIssue.getAssignee());
assertEquals(client.getUserName(), createdIssue.getReporter());
}
public void testGetIssueLeadingSpacesInDescription() throws Exception {
getIssueLeadingSpacesInDescripton(JiraTestConstants.JIRA_39_URL);
}
private void getIssueLeadingSpacesInDescripton(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = new Issue();
issue.setProject(client.getProjects()[0]);
issue.setType(client.getIssueTypes()[0]);
issue.setSummary("testCreateIssue");
String description = " leading spaces\n more spaces";
issue.setDescription(description);
issue.setAssignee(client.getUserName());
issue = client.createIssue(issue);
issue = client.getIssueByKey(issue.getKey());
assertEquals(description, JiraTaskDataHandler.convertHtml(issue.getDescription()));
issue.setDescription(JiraTaskDataHandler.convertHtml(issue.getDescription()));
issue.setDescription(JiraTaskDataHandler.convertHtml(issue.getDescription()));
client.updateIssue(issue, "");
issue = client.getIssueByKey(issue.getKey());
assertEquals(description, JiraTaskDataHandler.convertHtml(issue.getDescription()));
}
public void testUpdateIssue() throws Exception {
updateIssue(JiraTestConstants.JIRA_39_URL);
}
private void updateIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = new Issue();
issue.setProject(client.getProjects()[0]);
issue.setType(client.getIssueTypes()[0]);
issue.setSummary("testUpdateIssue");
issue.setAssignee(client.getUserName());
issue = client.createIssue(issue);
issue.setSummary("testUpdateIssueChanged");
client.updateIssue(issue, "");
issue = client.getIssueByKey(issue.getKey());
assertEquals("testUpdateIssueChanged", issue.getSummary());
assertNotNull(issue.getUpdated());
init(url, PrivilegeLevel.GUEST);
try {
client.updateIssue(issue, "");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
}
init(url, PrivilegeLevel.GUEST);
issue.setSummary("testUpdateIssueGuest");
issue = client.createIssue(issue);
issue.setSummary("testUpdateIssueGuestChanged");
try {
client.updateIssue(issue, "");
fail("Expected JiraException");
} catch (JiraRemoteMessageException e) {
}
}
public void testWatchUnwatchIssue() throws Exception {
watchUnwatchIssue(JiraTestConstants.JIRA_39_URL);
}
private void watchUnwatchIssue(String url) throws Exception {
init(url, PrivilegeLevel.USER);
Issue issue = JiraTestUtils.createIssue(client, "testWatchUnwatch");
assertFalse(issue.isWatched());
client.watchIssue(issue);
issue = client.getIssueByKey(issue.getKey());
// flag is never set
// assertTrue(issue.isWatched());
client.unwatchIssue(issue);
issue = client.getIssueByKey(issue.getKey());
assertFalse(issue.isWatched());
client.unwatchIssue(issue);
issue = client.getIssueByKey(issue.getKey());
assertFalse(issue.isWatched());
}
}
| NEW - bug 189170: Mylar test suite is failing
https://bugs.eclipse.org/bugs/show_bug.cgi?id=189170
| org.eclipse.mylyn.jira.tests/src/org/eclipse/mylyn/jira/tests/JiraRpcClientTest.java | NEW - bug 189170: Mylar test suite is failing https://bugs.eclipse.org/bugs/show_bug.cgi?id=189170 | <ide><path>rg.eclipse.mylyn.jira.tests/src/org/eclipse/mylyn/jira/tests/JiraRpcClientTest.java
<ide> issue = client.createIssue(issue);
<ide> issue = client.getIssueByKey(issue.getKey());
<ide> assertEquals(description, JiraTaskDataHandler.convertHtml(issue.getDescription()));
<del> issue.setDescription(JiraTaskDataHandler.convertHtml(issue.getDescription()));
<ide>
<ide> issue.setDescription(JiraTaskDataHandler.convertHtml(issue.getDescription()));
<ide> client.updateIssue(issue, ""); |
|
Java | apache-2.0 | a0f0c821dc516838a03d428cbe1ef9815fc63236 | 0 | vx/connectbot,vx/connectbot,alphallc/connectbot,vx/connectbot,alphallc/connectbot,vx/connectbot | /*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* 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 sk.vx.connectbot;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import sk.vx.connectbot.bean.SelectionArea;
import sk.vx.connectbot.service.PromptHelper;
import sk.vx.connectbot.service.TerminalBridge;
import sk.vx.connectbot.service.TerminalKeyListener;
import sk.vx.connectbot.service.TerminalManager;
import sk.vx.connectbot.util.FileChooser;
import sk.vx.connectbot.util.FileChooserCallback;
import sk.vx.connectbot.util.PreferenceConstants;
import sk.vx.connectbot.util.TransferThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.text.method.SingleLineTransformationMethod;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import de.mud.terminal.vt320;
public class ConsoleActivity extends Activity implements FileChooserCallback {
public final static String TAG = "ConnectBot.ConsoleActivity";
protected static final int REQUEST_EDIT = 1;
private static final int CLICK_TIME = 400;
private static final float MAX_CLICK_DISTANCE = 25f;
private static final int KEYBOARD_DISPLAY_TIME = 1500;
// Direction to shift the ViewFlipper
private static final int SHIFT_LEFT = 0;
private static final int SHIFT_RIGHT = 1;
protected ViewFlipper flip = null;
protected TerminalManager bound = null;
protected LayoutInflater inflater = null;
private SharedPreferences prefs = null;
// determines whether or not menuitem accelerators are bound
// otherwise they collide with an external keyboard's CTRL-char
private boolean hardKeyboard = false;
// determines whether we are in the fullscreen mode
private static final int FULLSCREEN_ON = 1;
private static final int FULLSCREEN_OFF = 2;
private int fullScreen;
protected Uri requested;
protected ClipboardManager clipboard;
private RelativeLayout stringPromptGroup;
protected EditText stringPrompt;
private TextView stringPromptInstructions;
private RelativeLayout booleanPromptGroup;
private TextView booleanPrompt;
private Button booleanYes, booleanNo;
private TextView empty;
private Animation slide_left_in, slide_left_out, slide_right_in, slide_right_out, fade_stay_hidden, fade_out_delayed;
private Animation keyboard_fade_in, keyboard_fade_out;
private float lastX, lastY;
private InputMethodManager inputManager;
private MenuItem disconnect, copy, paste, portForward, resize, urlscan, screenCapture, download, upload;
protected TerminalBridge copySource = null;
private int lastTouchRow, lastTouchCol;
private boolean forcedOrientation;
private Handler handler = new Handler();
private ImageView mKeyboardButton;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// let manager know about our event handling services
bound.disconnectHandler = disconnectHandler;
Log.d(TAG, String.format("Connected to TerminalManager and found bridges.size=%d", bound.bridges.size()));
bound.setResizeAllowed(true);
bound.hardKeyboardHidden = (getResources().getConfiguration().hardKeyboardHidden ==
Configuration.HARDKEYBOARDHIDDEN_YES);
// set fullscreen value
if (bound.getFullScreen() == 0) {
if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false))
setFullScreen(FULLSCREEN_ON);
else
setFullScreen(FULLSCREEN_OFF);
} else if (fullScreen != bound.getFullScreen())
setFullScreen(bound.getFullScreen());
// clear out any existing bridges and record requested index
flip.removeAllViews();
final String requestedNickname = (requested != null) ? requested.getFragment() : null;
int requestedIndex = -1;
TerminalBridge requestedBridge = bound.getConnectedBridge(requestedNickname);
// If we didn't find the requested connection, try opening it
if (requestedNickname != null && requestedBridge == null) {
try {
Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s), so creating one now", requested.toString(), requestedNickname));
requestedBridge = bound.openConnection(requested);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
}
}
// create views for all bridges on this service
for (TerminalBridge bridge : bound.bridges) {
final int currentIndex = addNewTerminalView(bridge);
// check to see if this bridge was requested
if (bridge == requestedBridge) {
requestedIndex = currentIndex;
// store this bridge as default bridge
bound.defaultBridge = bridge;
}
}
// if no bridge was requested, try using default bridge
if (requestedIndex < 0) {
requestedIndex = getFlipIndex(bound.defaultBridge);
if (requestedIndex < 0)
requestedIndex = 0;
}
setDisplayedTerminal(requestedIndex);
}
public void onServiceDisconnected(ComponentName className) {
// tell each bridge to forget about our prompt handler
synchronized (bound.bridges) {
for(TerminalBridge bridge : bound.bridges)
bridge.promptHelper.setHandler(null);
}
flip.removeAllViews();
updateEmptyVisible();
bound = null;
}
};
protected Handler promptHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// someone below us requested to display a prompt
updatePromptVisible();
}
};
protected Handler disconnectHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "Someone sending HANDLE_DISCONNECT to parentHandler");
// someone below us requested to display a password dialog
// they are sending nickname and requested
TerminalBridge bridge = (TerminalBridge)msg.obj;
if (bridge.isAwaitingClose())
closeBridge(bridge);
}
};
/**
* @param bridge
*/
private void closeBridge(final TerminalBridge bridge) {
synchronized (flip) {
final int flipIndex = getFlipIndex(bridge);
if (flipIndex >= 0) {
if (flip.getDisplayedChild() == flipIndex) {
shiftCurrentTerminal(SHIFT_LEFT);
}
flip.removeViewAt(flipIndex);
/* TODO Remove this workaround when ViewFlipper is fixed to listen
* to view removals. Android Issue 1784
*/
final int numChildren = flip.getChildCount();
if (flip.getDisplayedChild() >= numChildren &&
numChildren > 0) {
flip.setDisplayedChild(numChildren - 1);
}
updateEmptyVisible();
}
// If we just closed the last bridge, go back to the previous activity.
if (flip.getChildCount() == 0) {
finish();
}
}
}
protected View findCurrentView(int id) {
View view = flip.getCurrentView();
if(view == null) return null;
return view.findViewById(id);
}
protected PromptHelper getCurrentPromptHelper() {
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return null;
return ((TerminalView)view).bridge.promptHelper;
}
protected void hideAllPrompts() {
stringPromptGroup.setVisibility(View.GONE);
booleanPromptGroup.setVisibility(View.GONE);
// adjust window back if size was changed during prompt input
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return;
((TerminalView)view).bridge.parentChanged((TerminalView)view);
}
// more like configureLaxMode -- enable network IO on UI thread
private void configureStrictMode() {
try {
Class.forName("android.os.StrictMode");
StrictModeSetup.run();
} catch (ClassNotFoundException e) {
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
configureStrictMode();
hardKeyboard = getResources().getConfiguration().keyboard ==
Configuration.KEYBOARD_QWERTY;
this.setContentView(R.layout.act_console);
clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// hide action bar if requested by user
if (!PreferenceConstants.PRE_HONEYCOMB && prefs.getBoolean(PreferenceConstants.HIDE_ACTIONBAR, false))
this.hideActionBar();
// TODO find proper way to disable volume key beep if it exists.
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// handle requested console from incoming intent
requested = getIntent().getData();
inflater = LayoutInflater.from(this);
flip = (ViewFlipper)findViewById(R.id.console_flip);
empty = (TextView)findViewById(android.R.id.empty);
stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group);
stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions);
stringPrompt = (EditText)findViewById(R.id.console_password);
stringPrompt.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_UP) return false;
if(keyCode != KeyEvent.KEYCODE_ENTER) return false;
// pass collected password down to current terminal
String value = stringPrompt.getText().toString();
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return false;
helper.setResponse(value);
// finally clear password for next user
stringPrompt.setText("");
updatePromptVisible();
return true;
}
});
booleanPromptGroup = (RelativeLayout) findViewById(R.id.console_boolean_group);
booleanPrompt = (TextView)findViewById(R.id.console_prompt);
booleanYes = (Button)findViewById(R.id.console_prompt_yes);
booleanYes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return;
helper.setResponse(Boolean.TRUE);
updatePromptVisible();
}
});
booleanNo = (Button)findViewById(R.id.console_prompt_no);
booleanNo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return;
helper.setResponse(Boolean.FALSE);
updatePromptVisible();
}
});
// preload animations for terminal switching
slide_left_in = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
slide_left_out = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
slide_right_in = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
slide_right_out = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed);
fade_stay_hidden = AnimationUtils.loadAnimation(this, R.anim.fade_stay_hidden);
// Preload animation for keyboard button
keyboard_fade_in = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_in);
keyboard_fade_out = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_out);
inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
final RelativeLayout keyboardGroup = (RelativeLayout) findViewById(R.id.keyboard_group);
mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard);
mKeyboardButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null)
return;
inputManager.showSoftInput(flip, InputMethodManager.SHOW_FORCED);
keyboardGroup.setVisibility(View.GONE);
}
});
final ImageView symButton = (ImageView) findViewById(R.id.button_sym);
symButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
terminal.bridge.showCharPickerDialog();
keyboardGroup.setVisibility(View.GONE);
}
});
symButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return false;
TerminalView terminal = (TerminalView)flip;
terminal.bridge.showArrowsDialog();
return true;
}
});
final ImageView mInputButton = (ImageView) findViewById(R.id.button_input);
mInputButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
final TerminalView terminal = (TerminalView)flip;
Thread promptThread = new Thread(new Runnable() {
public void run() {
String inj = getCurrentPromptHelper().requestStringPrompt(null, "");
terminal.bridge.injectString(inj);
}
});
promptThread.setName("Prompt");
promptThread.setDaemon(true);
promptThread.start();
keyboardGroup.setVisibility(View.GONE);
}
});
final ImageView ctrlButton = (ImageView) findViewById(R.id.button_ctrl);
ctrlButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.metaPress(TerminalKeyListener.META_CTRL_ON);
keyboardGroup.setVisibility(View.GONE);
}
});
ctrlButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return false;
TerminalView terminal = (TerminalView)flip;
terminal.bridge.showCtrlDialog();
return true;
}
});
final ImageView escButton = (ImageView) findViewById(R.id.button_esc);
escButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.sendEscape();
keyboardGroup.setVisibility(View.GONE);
}
});
escButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return false;
TerminalView terminal = (TerminalView)flip;
terminal.bridge.showFKeysDialog();
return true;
}
});
// detect fling gestures to switch between terminals
final GestureDetector detect = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
private float totalY = 0;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
final float distx = e2.getRawX() - e1.getRawX();
final float disty = e2.getRawY() - e1.getRawY();
final int goalwidth = flip.getWidth() / 2;
// need to slide across half of display to trigger console change
// make sure user kept a steady hand horizontally
if (Math.abs(disty) < (flip.getHeight() / 4)) {
if (distx > goalwidth) {
shiftCurrentTerminal(SHIFT_RIGHT);
return true;
}
if (distx < -goalwidth) {
shiftCurrentTerminal(SHIFT_LEFT);
return true;
}
}
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// if copying, then ignore
if (copySource != null && copySource.isSelectingForCopy())
return false;
if (e1 == null || e2 == null)
return false;
// if releasing then reset total scroll
if (e2.getAction() == MotionEvent.ACTION_UP) {
totalY = 0;
}
// activate consider if within x tolerance
if (Math.abs(e1.getX() - e2.getX()) < ViewConfiguration.getTouchSlop() * 4) {
View flip = findCurrentView(R.id.console_flip);
if(flip == null) return false;
TerminalView terminal = (TerminalView)flip;
// estimate how many rows we have scrolled through
// accumulate distance that doesn't trigger immediate scroll
totalY += distanceY;
final int moved = (int)(totalY / terminal.bridge.charHeight);
// consume as scrollback only if towards right half of screen
if (e2.getX() > flip.getWidth() / 2) {
if (moved != 0) {
int base = terminal.bridge.buffer.getWindowBase();
terminal.bridge.buffer.setWindowBase(base + moved);
totalY = 0;
return true;
}
} else {
// otherwise consume as pgup/pgdown for every 5 lines
if (moved > 5) {
((vt320)terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_DOWN, ' ', 0);
terminal.bridge.tryKeyVibrate();
totalY = 0;
return true;
} else if (moved < -5) {
((vt320)terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_UP, ' ', 0);
terminal.bridge.tryKeyVibrate();
totalY = 0;
return true;
}
}
}
return false;
}
/*
* Enables longpress and popups menu
*
* @see
* android.view.GestureDetector.SimpleOnGestureListener#
* onLongPress(android.view.MotionEvent)
*
* @return void
*/
@Override
public void onLongPress(MotionEvent e) {
List<String> itemList = new ArrayList<String>();
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
if (terminalView == null)
return;
final TerminalBridge bridge = terminalView.bridge;
if (fullScreen == FULLSCREEN_ON)
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_disable_full_screen_mode));
else
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_enable_full_screen_mode));
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_change_font_size));
if (prefs.getBoolean(PreferenceConstants.EXTENDED_LONGPRESS,false)) {
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_arrows_dialog));
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_fkeys_dialog));
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_ctrl_dialog));
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_sym_dialog));
}
if (itemList.size() > 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(ConsoleActivity.this);
builder.setTitle(R.string.longpress_select_action);
builder.setItems(itemList.toArray(new CharSequence[itemList.size()]),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
if (fullScreen == FULLSCREEN_ON) {
setFullScreen(FULLSCREEN_OFF);
} else
setFullScreen(FULLSCREEN_ON);
break;
case 1:
bridge.showFontSizeDialog();
break;
case 2:
bridge.showArrowsDialog();
break;
case 3:
bridge.showFKeysDialog();
break;
case 4:
bridge.showCtrlDialog();
break;
case 5:
bridge.showCharPickerDialog();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
flip.setLongClickable(true);
flip.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// when copying, highlight the area
if (copySource != null && copySource.isSelectingForCopy()) {
int row = (int)Math.floor(event.getY() / copySource.charHeight);
int col = (int)Math.floor(event.getX() / copySource.charWidth);
SelectionArea area = copySource.getSelectionArea();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
// recording starting area
if (area.isSelectingOrigin()) {
area.setRow(row);
area.setColumn(col);
lastTouchRow = row;
lastTouchCol = col;
copySource.redraw();
}
return true;
case MotionEvent.ACTION_MOVE:
/* ignore when user hasn't moved since last time so
* we can fine-tune with directional pad
*/
if (row == lastTouchRow && col == lastTouchCol)
return true;
// if the user moves, start the selection for other corner
area.finishSelectingOrigin();
// update selected area
area.setRow(row);
area.setColumn(col);
lastTouchRow = row;
lastTouchCol = col;
copySource.redraw();
return true;
case MotionEvent.ACTION_UP:
/* If they didn't move their finger, maybe they meant to
* select the rest of the text with the directional pad.
*/
if (area.getLeft() == area.getRight() &&
area.getTop() == area.getBottom()) {
return true;
}
// copy selected area to clipboard
String copiedText = area.copyFrom(copySource.buffer);
clipboard.setText(copiedText);
Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_done, copiedText.length()), Toast.LENGTH_LONG).show();
// fall through to clear state
case MotionEvent.ACTION_CANCEL:
// make sure we clear any highlighted area
area.reset();
copySource.setSelectingForCopy(false);
copySource.redraw();
return true;
}
}
Configuration config = getResources().getConfiguration();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
lastX = event.getX();
lastY = event.getY();
} else if (event.getAction() == MotionEvent.ACTION_UP
&& keyboardGroup.getVisibility() == View.GONE
&& event.getEventTime() - event.getDownTime() < CLICK_TIME
&& Math.abs(event.getX() - lastX) < MAX_CLICK_DISTANCE
&& Math.abs(event.getY() - lastY) < MAX_CLICK_DISTANCE) {
keyboardGroup.startAnimation(keyboard_fade_in);
keyboardGroup.setVisibility(View.VISIBLE);
handler.postDelayed(new Runnable() {
public void run() {
if (keyboardGroup.getVisibility() == View.GONE)
return;
keyboardGroup.startAnimation(keyboard_fade_out);
keyboardGroup.setVisibility(View.GONE);
}
}, KEYBOARD_DISPLAY_TIME);
}
// pass any touch events back to detector
return detect.onTouchEvent(event);
}
});
}
/**
*
*/
private void configureOrientation() {
String rotateDefault;
if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_NOKEYS)
rotateDefault = PreferenceConstants.ROTATION_PORTRAIT;
else
rotateDefault = PreferenceConstants.ROTATION_LANDSCAPE;
String rotate = prefs.getString(PreferenceConstants.ROTATION, rotateDefault);
if (PreferenceConstants.ROTATION_DEFAULT.equals(rotate))
rotate = rotateDefault;
// request a forced orientation if requested by user
if (PreferenceConstants.ROTATION_LANDSCAPE.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
forcedOrientation = true;
} else if (PreferenceConstants.ROTATION_PORTRAIT.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
forcedOrientation = true;
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
forcedOrientation = false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
View view = findCurrentView(R.id.console_flip);
final boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
boolean canTransferFiles = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
canTransferFiles = bridge.canTransferFiles();
}
menu.setQwertyMode(true);
disconnect = menu.add(R.string.list_host_disconnect);
if (hardKeyboard)
disconnect.setAlphabeticShortcut('w');
if (!sessionOpen && disconnected)
disconnect.setTitle(R.string.console_menu_close);
disconnect.setEnabled(activeTerminal);
disconnect.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
disconnect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// disconnect or close the currently visible session
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
bridge.dispatchDisconnect(true);
return true;
}
});
copy = menu.add(R.string.console_menu_copy);
if (hardKeyboard)
copy.setAlphabeticShortcut('c');
copy.setIcon(android.R.drawable.ic_menu_set_as);
copy.setEnabled(activeTerminal);
copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// mark as copying and reset any previous bounds
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
copySource = terminalView.bridge;
SelectionArea area = copySource.getSelectionArea();
area.reset();
area.setBounds(copySource.buffer.getColumns(), copySource.buffer.getRows());
copySource.setSelectingForCopy(true);
// Make sure we show the initial selection
copySource.redraw();
Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_start), Toast.LENGTH_LONG).show();
return true;
}
});
paste = menu.add(R.string.console_menu_paste);
if (hardKeyboard)
paste.setAlphabeticShortcut('v');
paste.setIcon(android.R.drawable.ic_menu_edit);
paste.setEnabled(clipboard.hasText() && sessionOpen);
paste.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// force insert of clipboard text into current console
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
// pull string from clipboard and generate all events to force down
String clip = clipboard.getText().toString();
bridge.injectString(clip);
return true;
}
});
resize = menu.add(R.string.console_menu_resize);
if (hardKeyboard)
resize.setAlphabeticShortcut('r');
resize.setIcon(android.R.drawable.ic_menu_crop);
resize.setEnabled(sessionOpen);
resize.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
final View resizeView = inflater.inflate(R.layout.dia_resize, null, false);
((EditText) resizeView.findViewById(R.id.width))
.setText(prefs.getString(PreferenceConstants.DEFAULT_FONT_SIZE_WIDTH, "80"));
((EditText) resizeView.findViewById(R.id.height))
.setText(prefs.getString(PreferenceConstants.DEFAULT_FONT_SIZE_HEIGHT, "25"));
new AlertDialog.Builder(ConsoleActivity.this)
.setView(resizeView)
.setPositiveButton(R.string.button_resize, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
int width, height;
try {
width = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.width))
.getText().toString());
height = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.height))
.getText().toString());
} catch (NumberFormatException nfe) {
// TODO change this to a real dialog where we can
// make the input boxes turn red to indicate an error.
return;
}
if (width > 0 && height > 0) {
terminalView.forceSize(width, height);
}
else {
new AlertDialog.Builder(ConsoleActivity.this)
.setTitle(R.string.resize_error_title)
.setMessage(R.string.resize_error_width_height)
.setNegativeButton(R.string.button_close, null)
.show();
}
}
}).setNeutralButton(R.string.button_resize_reset, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
terminalView.bridge.resetSize(terminalView);
}
}).setNegativeButton(android.R.string.cancel, null)
.create().show();
return true;
}
});
screenCapture = menu.add(R.string.console_menu_screencapture);
if (hardKeyboard)
screenCapture.setAlphabeticShortcut('s');
screenCapture.setIcon(android.R.drawable.ic_menu_camera);
screenCapture.setEnabled(activeTerminal);
screenCapture.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
terminalView.bridge.captureScreen();
return true;
}
});
portForward = menu.add(R.string.console_menu_portforwards);
if (hardKeyboard)
portForward.setAlphabeticShortcut('f');
portForward.setIcon(android.R.drawable.ic_menu_manage);
portForward.setEnabled(sessionOpen && canForwardPorts);
portForward.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
Intent intent = new Intent(ConsoleActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, bridge.host.getId());
ConsoleActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
urlscan = menu.add(R.string.console_menu_urlscan);
if (hardKeyboard)
urlscan.setAlphabeticShortcut('l');
urlscan.setIcon(android.R.drawable.ic_menu_search);
urlscan.setEnabled(activeTerminal);
urlscan.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return true;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.urlScan(terminal);
return true;
}
});
download = menu.add(R.string.console_menu_download);
download.setAlphabeticShortcut('d');
download.setEnabled(sessionOpen && canTransferFiles);
download.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final String downloadFolder = prefs.getString(PreferenceConstants.DOWNLOAD_FOLDER, "");
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
final TerminalBridge bridge = terminalView.bridge;
final EditText textField = new EditText(ConsoleActivity.this);
new AlertDialog.Builder(ConsoleActivity.this)
.setTitle(R.string.transfer_select_remote_download_title)
.setMessage(R.string.transfer_select_remote_download_desc)
.setView(textField)
.setPositiveButton(R.string.transfer_button_download, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
TransferThread transfer = new TransferThread(ConsoleActivity.this, handler);
if (!prefs.getBoolean(PreferenceConstants.BACKGROUND_FILE_TRANSFER,true))
transfer.setProgressDialogMessage(getString(R.string.transfer_downloading));
transfer.download(bridge, textField.getText().toString(), null, downloadFolder);
}
}).setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
upload = menu.add(R.string.console_menu_upload);
upload.setAlphabeticShortcut('u');
upload.setEnabled(sessionOpen && canTransferFiles);
upload.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
FileChooser.selectFile(ConsoleActivity.this, ConsoleActivity.this,
FileChooser.REQUEST_CODE_SELECT_FILE,
getString(R.string.file_chooser_select_file, getString(R.string.select_for_upload)));
return true;
}
});
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case FileChooser.REQUEST_CODE_SELECT_FILE:
if (resultCode == RESULT_OK && intent != null) {
Uri uri = intent.getData();
try {
if (uri != null) {
fileSelected(new File(URI.create(uri.toString())));
} else {
String filename = intent.getDataString();
if (filename != null) {
fileSelected(new File(URI.create(filename)));
}
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Couldn't read from selected file", e);
}
}
break;
}
}
public void fileSelected(final File f) {
String destFileName;
String uploadFolder = prefs.getString(PreferenceConstants.REMOTE_UPLOAD_FOLDER,null);
final TransferThread transfer = new TransferThread(ConsoleActivity.this, handler);
Log.d(TAG, "File chooser returned " + f);
if (uploadFolder == null)
uploadFolder = "";
if (!uploadFolder.equals("") && uploadFolder.charAt(uploadFolder.length()-1) != '/' )
destFileName = uploadFolder + "/" + f.getName();
else
destFileName = uploadFolder + f.getName();
if (prefs.getBoolean(PreferenceConstants.UPLOAD_DESTINATION_PROMPT,true)) {
final EditText fileDest = new EditText(ConsoleActivity.this);
fileDest.setSingleLine();
fileDest.setText(destFileName);
new AlertDialog.Builder(ConsoleActivity.this)
.setTitle(R.string.transfer_select_remote_upload_dest_title)
.setMessage(getResources().getString(R.string.transfer_select_remote_upload_dest_desc) + "\n" + f.getPath())
.setView(fileDest)
.setPositiveButton(R.string.transfer_button_upload, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (!prefs.getBoolean(PreferenceConstants.BACKGROUND_FILE_TRANSFER,true))
transfer.setProgressDialogMessage(getString(R.string.transfer_uploading));
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
File uf = new File(fileDest.getText().toString());
String name = "", parent = "";
if (uf.getParent() != null)
parent = uf.getParent().toString();
if (uf.getName() != null)
name = uf.getName().toString();
transfer.upload(bridge, f.toString(), name, parent);
}
}).setNegativeButton(android.R.string.cancel, null).create().show();
} else {
if (!prefs.getBoolean(PreferenceConstants.BACKGROUND_FILE_TRANSFER,true))
transfer.setProgressDialogMessage(getString(R.string.transfer_uploading));
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
transfer.upload(bridge, f.toString(), null, uploadFolder);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);
final View view = findCurrentView(R.id.console_flip);
boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
boolean canTransferFiles = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
canTransferFiles = bridge.canTransferFiles();
}
disconnect.setEnabled(activeTerminal);
if (sessionOpen || !disconnected)
disconnect.setTitle(R.string.list_host_disconnect);
else
disconnect.setTitle(R.string.console_menu_close);
copy.setEnabled(activeTerminal);
paste.setEnabled(clipboard.hasText() && sessionOpen);
portForward.setEnabled(sessionOpen && canForwardPorts);
urlscan.setEnabled(activeTerminal);
resize.setEnabled(sessionOpen);
download.setEnabled(sessionOpen && canTransferFiles);
upload.setEnabled(sessionOpen && canTransferFiles);
return true;
}
@Override
public void onOptionsMenuClosed(Menu menu) {
super.onOptionsMenuClosed(menu);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
@Override
public void onStart() {
super.onStart();
// connect with manager service to find all bridges
// when connected it will insert all views
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if (getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
this.mKeyboardButton.setVisibility(View.GONE);
}
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause called");
if (forcedOrientation && bound != null)
bound.setResizeAllowed(false);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume called");
// Make sure we don't let the screen fall asleep.
// This also keeps the Wi-Fi chipset from disconnecting us.
if (prefs.getBoolean(PreferenceConstants.KEEP_ALIVE, true)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
configureOrientation();
if (forcedOrientation && bound != null)
bound.setResizeAllowed(true);
}
/* (non-Javadoc)
* @see android.app.Activity#onNewIntent(android.content.Intent)
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "onNewIntent called");
requested = intent.getData();
if (requested == null) {
Log.e(TAG, "Got null intent data in onNewIntent()");
return;
}
if (bound == null) {
Log.e(TAG, "We're not bound in onNewIntent()");
return;
}
TerminalBridge requestedBridge = bound.getConnectedBridge(requested.getFragment());
int requestedIndex = 0;
synchronized (flip) {
if (requestedBridge == null) {
// If we didn't find the requested connection, try opening it
try {
Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s),"+
"so creating one now", requested.toString(), requested.getFragment()));
requestedBridge = bound.openConnection(requested);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
// TODO: We should display an error dialog here.
return;
}
requestedIndex = addNewTerminalView(requestedBridge);
} else {
final int flipIndex = getFlipIndex(requestedBridge);
if (flipIndex > requestedIndex) {
requestedIndex = flipIndex;
}
}
setDisplayedTerminal(requestedIndex);
}
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
}
protected void shiftCurrentTerminal(final int direction) {
View overlay;
synchronized (flip) {
boolean shouldAnimate = flip.getChildCount() > 1;
// Only show animation if there is something else to go to.
if (shouldAnimate) {
// keep current overlay from popping up again
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_stay_hidden);
if (direction == SHIFT_LEFT) {
flip.setInAnimation(slide_left_in);
flip.setOutAnimation(slide_left_out);
flip.showNext();
} else if (direction == SHIFT_RIGHT) {
flip.setInAnimation(slide_right_in);
flip.setOutAnimation(slide_right_out);
flip.showPrevious();
}
}
ConsoleActivity.this.updateDefault();
if (shouldAnimate) {
// show overlay on new slide and start fade
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_out_delayed);
}
updatePromptVisible();
}
}
/**
* Save the currently shown {@link TerminalView} as the default. This is
* saved back down into {@link TerminalManager} where we can read it again
* later.
*/
private void updateDefault() {
// update the current default terminal
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return;
TerminalView terminal = (TerminalView)view;
if(bound == null) return;
bound.defaultBridge = terminal.bridge;
}
protected void updateEmptyVisible() {
// update visibility of empty status message
empty.setVisibility((flip.getChildCount() == 0) ? View.VISIBLE : View.GONE);
}
/**
* Show any prompts requested by the currently visible {@link TerminalView}.
*/
protected void updatePromptVisible() {
// check if our currently-visible terminalbridge is requesting any prompt services
View view = findCurrentView(R.id.console_flip);
// Hide all the prompts in case a prompt request was canceled
hideAllPrompts();
if(!(view instanceof TerminalView)) {
// we dont have an active view, so hide any prompts
return;
}
PromptHelper prompt = ((TerminalView)view).bridge.promptHelper;
if(String.class.equals(prompt.promptRequested)) {
stringPromptGroup.setVisibility(View.VISIBLE);
String instructions = prompt.promptInstructions;
boolean password = prompt.passwordRequested;
if (instructions != null && instructions.length() > 0) {
stringPromptInstructions.setVisibility(View.VISIBLE);
stringPromptInstructions.setText(instructions);
} else
stringPromptInstructions.setVisibility(View.GONE);
if (password) {
stringPrompt.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
stringPrompt.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
stringPrompt.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
stringPrompt.setTransformationMethod(SingleLineTransformationMethod.getInstance());
}
stringPrompt.setText("");
stringPrompt.setHint(prompt.promptHint);
stringPrompt.requestFocus();
} else if(Boolean.class.equals(prompt.promptRequested)) {
booleanPromptGroup.setVisibility(View.VISIBLE);
booleanPrompt.setText(prompt.promptHint);
booleanYes.requestFocus();
} else {
hideAllPrompts();
view.requestFocus();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, String.format("onConfigurationChanged; requestedOrientation=%d, newConfig.orientation=%d", getRequestedOrientation(), newConfig.orientation));
if (bound != null) {
if (forcedOrientation &&
(newConfig.orientation != Configuration.ORIENTATION_LANDSCAPE &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) ||
(newConfig.orientation != Configuration.ORIENTATION_PORTRAIT &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT))
bound.setResizeAllowed(false);
else
bound.setResizeAllowed(true);
bound.hardKeyboardHidden = (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES);
mKeyboardButton.setVisibility(bound.hardKeyboardHidden ? View.VISIBLE : View.GONE);
}
}
/**
* Adds a new TerminalBridge to the current set of views in our ViewFlipper.
*
* @param bridge TerminalBridge to add to our ViewFlipper
* @return the child index of the new view in the ViewFlipper
*/
private int addNewTerminalView(TerminalBridge bridge) {
// let them know about our prompt handler services
bridge.promptHelper.setHandler(promptHandler);
// inflate each terminal view
RelativeLayout view = (RelativeLayout)inflater.inflate(R.layout.item_terminal, flip, false);
// set the terminal overlay text
TextView overlay = (TextView)view.findViewById(R.id.terminal_overlay);
overlay.setText(bridge.host.getNickname());
// and add our terminal view control, using index to place behind overlay
TerminalView terminal = new TerminalView(ConsoleActivity.this, bridge);
terminal.setId(R.id.console_flip);
view.addView(terminal, 0);
synchronized (flip) {
// finally attach to the flipper
flip.addView(view);
return flip.getChildCount() - 1;
}
}
private int getFlipIndex(TerminalBridge bridge) {
synchronized (flip) {
final int children = flip.getChildCount();
for (int i = 0; i < children; i++) {
final View view = flip.getChildAt(i).findViewById(R.id.console_flip);
if (view == null || !(view instanceof TerminalView)) {
// How did that happen?
continue;
}
final TerminalView tv = (TerminalView) view;
if (tv.bridge == bridge) {
return i;
}
}
}
return -1;
}
/**
* Displays the child in the ViewFlipper at the requestedIndex and updates the prompts.
*
* @param requestedIndex the index of the terminal view to display
*/
private void setDisplayedTerminal(int requestedIndex) {
synchronized (flip) {
try {
// show the requested bridge if found, also fade out overlay
flip.setDisplayedChild(requestedIndex);
flip.getCurrentView().findViewById(R.id.terminal_overlay)
.startAnimation(fade_out_delayed);
} catch (NullPointerException npe) {
Log.d(TAG, "View went away when we were about to display it", npe);
}
updatePromptVisible();
updateEmptyVisible();
}
}
private void setFullScreen(int fullScreen) {
if (fullScreen != this.fullScreen) {
if (fullScreen == FULLSCREEN_ON) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (!PreferenceConstants.PRE_HONEYCOMB) {
this.hideActionBar();
}
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (!PreferenceConstants.PRE_HONEYCOMB) {
if (!prefs.getBoolean(PreferenceConstants.HIDE_ACTIONBAR, false))
this.showActionBar();
}
}
this.fullScreen = fullScreen;
if (bound != null)
bound.setFullScreen(this.fullScreen);
}
}
private void showActionBar() {
try {
if (this.getActionBar() != null)
this.getActionBar().show();
} catch (Exception e) {
Log.e(TAG, "Error showing ActionBar", e);
}
}
private void hideActionBar() {
try {
if (this.getActionBar() != null)
this.getActionBar().hide();
} catch (Exception e) {
Log.e(TAG, "Error hiding ActionBar", e);
}
}
} | src/sk/vx/connectbot/ConsoleActivity.java | /*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* 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 sk.vx.connectbot;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import sk.vx.connectbot.bean.SelectionArea;
import sk.vx.connectbot.service.PromptHelper;
import sk.vx.connectbot.service.TerminalBridge;
import sk.vx.connectbot.service.TerminalKeyListener;
import sk.vx.connectbot.service.TerminalManager;
import sk.vx.connectbot.util.FileChooser;
import sk.vx.connectbot.util.FileChooserCallback;
import sk.vx.connectbot.util.PreferenceConstants;
import sk.vx.connectbot.util.TransferThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.text.method.SingleLineTransformationMethod;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import de.mud.terminal.vt320;
public class ConsoleActivity extends Activity implements FileChooserCallback {
public final static String TAG = "ConnectBot.ConsoleActivity";
protected static final int REQUEST_EDIT = 1;
private static final int CLICK_TIME = 400;
private static final float MAX_CLICK_DISTANCE = 25f;
private static final int KEYBOARD_DISPLAY_TIME = 1500;
// Direction to shift the ViewFlipper
private static final int SHIFT_LEFT = 0;
private static final int SHIFT_RIGHT = 1;
protected ViewFlipper flip = null;
protected TerminalManager bound = null;
protected LayoutInflater inflater = null;
private SharedPreferences prefs = null;
// determines whether or not menuitem accelerators are bound
// otherwise they collide with an external keyboard's CTRL-char
private boolean hardKeyboard = false;
// determines whether we are in the fullscreen mode
private static final int FULLSCREEN_ON = 1;
private static final int FULLSCREEN_OFF = 2;
private int fullScreen;
protected Uri requested;
protected ClipboardManager clipboard;
private RelativeLayout stringPromptGroup;
protected EditText stringPrompt;
private TextView stringPromptInstructions;
private RelativeLayout booleanPromptGroup;
private TextView booleanPrompt;
private Button booleanYes, booleanNo;
private TextView empty;
private Animation slide_left_in, slide_left_out, slide_right_in, slide_right_out, fade_stay_hidden, fade_out_delayed;
private Animation keyboard_fade_in, keyboard_fade_out;
private float lastX, lastY;
private InputMethodManager inputManager;
private MenuItem disconnect, copy, paste, portForward, resize, urlscan, screenCapture, download, upload;
protected TerminalBridge copySource = null;
private int lastTouchRow, lastTouchCol;
private boolean forcedOrientation;
private Handler handler = new Handler();
private ImageView mKeyboardButton;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// let manager know about our event handling services
bound.disconnectHandler = disconnectHandler;
Log.d(TAG, String.format("Connected to TerminalManager and found bridges.size=%d", bound.bridges.size()));
bound.setResizeAllowed(true);
// set fullscreen value
if (bound.getFullScreen() == 0) {
if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false))
setFullScreen(FULLSCREEN_ON);
else
setFullScreen(FULLSCREEN_OFF);
} else if (fullScreen != bound.getFullScreen())
setFullScreen(bound.getFullScreen());
// clear out any existing bridges and record requested index
flip.removeAllViews();
final String requestedNickname = (requested != null) ? requested.getFragment() : null;
int requestedIndex = -1;
TerminalBridge requestedBridge = bound.getConnectedBridge(requestedNickname);
// If we didn't find the requested connection, try opening it
if (requestedNickname != null && requestedBridge == null) {
try {
Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s), so creating one now", requested.toString(), requestedNickname));
requestedBridge = bound.openConnection(requested);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
}
}
// create views for all bridges on this service
for (TerminalBridge bridge : bound.bridges) {
final int currentIndex = addNewTerminalView(bridge);
// check to see if this bridge was requested
if (bridge == requestedBridge) {
requestedIndex = currentIndex;
// store this bridge as default bridge
bound.defaultBridge = bridge;
}
}
// if no bridge was requested, try using default bridge
if (requestedIndex < 0) {
requestedIndex = getFlipIndex(bound.defaultBridge);
if (requestedIndex < 0)
requestedIndex = 0;
}
setDisplayedTerminal(requestedIndex);
}
public void onServiceDisconnected(ComponentName className) {
// tell each bridge to forget about our prompt handler
synchronized (bound.bridges) {
for(TerminalBridge bridge : bound.bridges)
bridge.promptHelper.setHandler(null);
}
flip.removeAllViews();
updateEmptyVisible();
bound = null;
}
};
protected Handler promptHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// someone below us requested to display a prompt
updatePromptVisible();
}
};
protected Handler disconnectHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "Someone sending HANDLE_DISCONNECT to parentHandler");
// someone below us requested to display a password dialog
// they are sending nickname and requested
TerminalBridge bridge = (TerminalBridge)msg.obj;
if (bridge.isAwaitingClose())
closeBridge(bridge);
}
};
/**
* @param bridge
*/
private void closeBridge(final TerminalBridge bridge) {
synchronized (flip) {
final int flipIndex = getFlipIndex(bridge);
if (flipIndex >= 0) {
if (flip.getDisplayedChild() == flipIndex) {
shiftCurrentTerminal(SHIFT_LEFT);
}
flip.removeViewAt(flipIndex);
/* TODO Remove this workaround when ViewFlipper is fixed to listen
* to view removals. Android Issue 1784
*/
final int numChildren = flip.getChildCount();
if (flip.getDisplayedChild() >= numChildren &&
numChildren > 0) {
flip.setDisplayedChild(numChildren - 1);
}
updateEmptyVisible();
}
// If we just closed the last bridge, go back to the previous activity.
if (flip.getChildCount() == 0) {
finish();
}
}
}
protected View findCurrentView(int id) {
View view = flip.getCurrentView();
if(view == null) return null;
return view.findViewById(id);
}
protected PromptHelper getCurrentPromptHelper() {
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return null;
return ((TerminalView)view).bridge.promptHelper;
}
protected void hideAllPrompts() {
stringPromptGroup.setVisibility(View.GONE);
booleanPromptGroup.setVisibility(View.GONE);
// adjust window back if size was changed during prompt input
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return;
((TerminalView)view).bridge.parentChanged((TerminalView)view);
}
// more like configureLaxMode -- enable network IO on UI thread
private void configureStrictMode() {
try {
Class.forName("android.os.StrictMode");
StrictModeSetup.run();
} catch (ClassNotFoundException e) {
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
configureStrictMode();
hardKeyboard = getResources().getConfiguration().keyboard ==
Configuration.KEYBOARD_QWERTY;
this.setContentView(R.layout.act_console);
clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// hide action bar if requested by user
if (!PreferenceConstants.PRE_HONEYCOMB && prefs.getBoolean(PreferenceConstants.HIDE_ACTIONBAR, false))
this.hideActionBar();
// TODO find proper way to disable volume key beep if it exists.
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// handle requested console from incoming intent
requested = getIntent().getData();
inflater = LayoutInflater.from(this);
flip = (ViewFlipper)findViewById(R.id.console_flip);
empty = (TextView)findViewById(android.R.id.empty);
stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group);
stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions);
stringPrompt = (EditText)findViewById(R.id.console_password);
stringPrompt.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_UP) return false;
if(keyCode != KeyEvent.KEYCODE_ENTER) return false;
// pass collected password down to current terminal
String value = stringPrompt.getText().toString();
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return false;
helper.setResponse(value);
// finally clear password for next user
stringPrompt.setText("");
updatePromptVisible();
return true;
}
});
booleanPromptGroup = (RelativeLayout) findViewById(R.id.console_boolean_group);
booleanPrompt = (TextView)findViewById(R.id.console_prompt);
booleanYes = (Button)findViewById(R.id.console_prompt_yes);
booleanYes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return;
helper.setResponse(Boolean.TRUE);
updatePromptVisible();
}
});
booleanNo = (Button)findViewById(R.id.console_prompt_no);
booleanNo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return;
helper.setResponse(Boolean.FALSE);
updatePromptVisible();
}
});
// preload animations for terminal switching
slide_left_in = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
slide_left_out = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
slide_right_in = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
slide_right_out = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed);
fade_stay_hidden = AnimationUtils.loadAnimation(this, R.anim.fade_stay_hidden);
// Preload animation for keyboard button
keyboard_fade_in = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_in);
keyboard_fade_out = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_out);
inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
final RelativeLayout keyboardGroup = (RelativeLayout) findViewById(R.id.keyboard_group);
mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard);
mKeyboardButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null)
return;
inputManager.showSoftInput(flip, InputMethodManager.SHOW_FORCED);
keyboardGroup.setVisibility(View.GONE);
}
});
final ImageView symButton = (ImageView) findViewById(R.id.button_sym);
symButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
terminal.bridge.showCharPickerDialog();
keyboardGroup.setVisibility(View.GONE);
}
});
symButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return false;
TerminalView terminal = (TerminalView)flip;
terminal.bridge.showArrowsDialog();
return true;
}
});
final ImageView mInputButton = (ImageView) findViewById(R.id.button_input);
mInputButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
final TerminalView terminal = (TerminalView)flip;
Thread promptThread = new Thread(new Runnable() {
public void run() {
String inj = getCurrentPromptHelper().requestStringPrompt(null, "");
terminal.bridge.injectString(inj);
}
});
promptThread.setName("Prompt");
promptThread.setDaemon(true);
promptThread.start();
keyboardGroup.setVisibility(View.GONE);
}
});
final ImageView ctrlButton = (ImageView) findViewById(R.id.button_ctrl);
ctrlButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.metaPress(TerminalKeyListener.META_CTRL_ON);
keyboardGroup.setVisibility(View.GONE);
}
});
ctrlButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return false;
TerminalView terminal = (TerminalView)flip;
terminal.bridge.showCtrlDialog();
return true;
}
});
final ImageView escButton = (ImageView) findViewById(R.id.button_esc);
escButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.sendEscape();
keyboardGroup.setVisibility(View.GONE);
}
});
escButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return false;
TerminalView terminal = (TerminalView)flip;
terminal.bridge.showFKeysDialog();
return true;
}
});
// detect fling gestures to switch between terminals
final GestureDetector detect = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
private float totalY = 0;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
final float distx = e2.getRawX() - e1.getRawX();
final float disty = e2.getRawY() - e1.getRawY();
final int goalwidth = flip.getWidth() / 2;
// need to slide across half of display to trigger console change
// make sure user kept a steady hand horizontally
if (Math.abs(disty) < (flip.getHeight() / 4)) {
if (distx > goalwidth) {
shiftCurrentTerminal(SHIFT_RIGHT);
return true;
}
if (distx < -goalwidth) {
shiftCurrentTerminal(SHIFT_LEFT);
return true;
}
}
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// if copying, then ignore
if (copySource != null && copySource.isSelectingForCopy())
return false;
if (e1 == null || e2 == null)
return false;
// if releasing then reset total scroll
if (e2.getAction() == MotionEvent.ACTION_UP) {
totalY = 0;
}
// activate consider if within x tolerance
if (Math.abs(e1.getX() - e2.getX()) < ViewConfiguration.getTouchSlop() * 4) {
View flip = findCurrentView(R.id.console_flip);
if(flip == null) return false;
TerminalView terminal = (TerminalView)flip;
// estimate how many rows we have scrolled through
// accumulate distance that doesn't trigger immediate scroll
totalY += distanceY;
final int moved = (int)(totalY / terminal.bridge.charHeight);
// consume as scrollback only if towards right half of screen
if (e2.getX() > flip.getWidth() / 2) {
if (moved != 0) {
int base = terminal.bridge.buffer.getWindowBase();
terminal.bridge.buffer.setWindowBase(base + moved);
totalY = 0;
return true;
}
} else {
// otherwise consume as pgup/pgdown for every 5 lines
if (moved > 5) {
((vt320)terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_DOWN, ' ', 0);
terminal.bridge.tryKeyVibrate();
totalY = 0;
return true;
} else if (moved < -5) {
((vt320)terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_UP, ' ', 0);
terminal.bridge.tryKeyVibrate();
totalY = 0;
return true;
}
}
}
return false;
}
/*
* Enables longpress and popups menu
*
* @see
* android.view.GestureDetector.SimpleOnGestureListener#
* onLongPress(android.view.MotionEvent)
*
* @return void
*/
@Override
public void onLongPress(MotionEvent e) {
List<String> itemList = new ArrayList<String>();
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
if (terminalView == null)
return;
final TerminalBridge bridge = terminalView.bridge;
if (fullScreen == FULLSCREEN_ON)
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_disable_full_screen_mode));
else
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_enable_full_screen_mode));
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_change_font_size));
if (prefs.getBoolean(PreferenceConstants.EXTENDED_LONGPRESS,false)) {
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_arrows_dialog));
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_fkeys_dialog));
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_ctrl_dialog));
itemList.add(ConsoleActivity.this
.getResources().getString(R.string.longpress_sym_dialog));
}
if (itemList.size() > 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(ConsoleActivity.this);
builder.setTitle(R.string.longpress_select_action);
builder.setItems(itemList.toArray(new CharSequence[itemList.size()]),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
if (fullScreen == FULLSCREEN_ON) {
setFullScreen(FULLSCREEN_OFF);
} else
setFullScreen(FULLSCREEN_ON);
break;
case 1:
bridge.showFontSizeDialog();
break;
case 2:
bridge.showArrowsDialog();
break;
case 3:
bridge.showFKeysDialog();
break;
case 4:
bridge.showCtrlDialog();
break;
case 5:
bridge.showCharPickerDialog();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
flip.setLongClickable(true);
flip.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// when copying, highlight the area
if (copySource != null && copySource.isSelectingForCopy()) {
int row = (int)Math.floor(event.getY() / copySource.charHeight);
int col = (int)Math.floor(event.getX() / copySource.charWidth);
SelectionArea area = copySource.getSelectionArea();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
// recording starting area
if (area.isSelectingOrigin()) {
area.setRow(row);
area.setColumn(col);
lastTouchRow = row;
lastTouchCol = col;
copySource.redraw();
}
return true;
case MotionEvent.ACTION_MOVE:
/* ignore when user hasn't moved since last time so
* we can fine-tune with directional pad
*/
if (row == lastTouchRow && col == lastTouchCol)
return true;
// if the user moves, start the selection for other corner
area.finishSelectingOrigin();
// update selected area
area.setRow(row);
area.setColumn(col);
lastTouchRow = row;
lastTouchCol = col;
copySource.redraw();
return true;
case MotionEvent.ACTION_UP:
/* If they didn't move their finger, maybe they meant to
* select the rest of the text with the directional pad.
*/
if (area.getLeft() == area.getRight() &&
area.getTop() == area.getBottom()) {
return true;
}
// copy selected area to clipboard
String copiedText = area.copyFrom(copySource.buffer);
clipboard.setText(copiedText);
Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_done, copiedText.length()), Toast.LENGTH_LONG).show();
// fall through to clear state
case MotionEvent.ACTION_CANCEL:
// make sure we clear any highlighted area
area.reset();
copySource.setSelectingForCopy(false);
copySource.redraw();
return true;
}
}
Configuration config = getResources().getConfiguration();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
lastX = event.getX();
lastY = event.getY();
} else if (event.getAction() == MotionEvent.ACTION_UP
&& keyboardGroup.getVisibility() == View.GONE
&& event.getEventTime() - event.getDownTime() < CLICK_TIME
&& Math.abs(event.getX() - lastX) < MAX_CLICK_DISTANCE
&& Math.abs(event.getY() - lastY) < MAX_CLICK_DISTANCE) {
keyboardGroup.startAnimation(keyboard_fade_in);
keyboardGroup.setVisibility(View.VISIBLE);
handler.postDelayed(new Runnable() {
public void run() {
if (keyboardGroup.getVisibility() == View.GONE)
return;
keyboardGroup.startAnimation(keyboard_fade_out);
keyboardGroup.setVisibility(View.GONE);
}
}, KEYBOARD_DISPLAY_TIME);
}
// pass any touch events back to detector
return detect.onTouchEvent(event);
}
});
}
/**
*
*/
private void configureOrientation() {
String rotateDefault;
if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_NOKEYS)
rotateDefault = PreferenceConstants.ROTATION_PORTRAIT;
else
rotateDefault = PreferenceConstants.ROTATION_LANDSCAPE;
String rotate = prefs.getString(PreferenceConstants.ROTATION, rotateDefault);
if (PreferenceConstants.ROTATION_DEFAULT.equals(rotate))
rotate = rotateDefault;
// request a forced orientation if requested by user
if (PreferenceConstants.ROTATION_LANDSCAPE.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
forcedOrientation = true;
} else if (PreferenceConstants.ROTATION_PORTRAIT.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
forcedOrientation = true;
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
forcedOrientation = false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
View view = findCurrentView(R.id.console_flip);
final boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
boolean canTransferFiles = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
canTransferFiles = bridge.canTransferFiles();
}
menu.setQwertyMode(true);
disconnect = menu.add(R.string.list_host_disconnect);
if (hardKeyboard)
disconnect.setAlphabeticShortcut('w');
if (!sessionOpen && disconnected)
disconnect.setTitle(R.string.console_menu_close);
disconnect.setEnabled(activeTerminal);
disconnect.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
disconnect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// disconnect or close the currently visible session
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
bridge.dispatchDisconnect(true);
return true;
}
});
copy = menu.add(R.string.console_menu_copy);
if (hardKeyboard)
copy.setAlphabeticShortcut('c');
copy.setIcon(android.R.drawable.ic_menu_set_as);
copy.setEnabled(activeTerminal);
copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// mark as copying and reset any previous bounds
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
copySource = terminalView.bridge;
SelectionArea area = copySource.getSelectionArea();
area.reset();
area.setBounds(copySource.buffer.getColumns(), copySource.buffer.getRows());
copySource.setSelectingForCopy(true);
// Make sure we show the initial selection
copySource.redraw();
Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_start), Toast.LENGTH_LONG).show();
return true;
}
});
paste = menu.add(R.string.console_menu_paste);
if (hardKeyboard)
paste.setAlphabeticShortcut('v');
paste.setIcon(android.R.drawable.ic_menu_edit);
paste.setEnabled(clipboard.hasText() && sessionOpen);
paste.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// force insert of clipboard text into current console
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
// pull string from clipboard and generate all events to force down
String clip = clipboard.getText().toString();
bridge.injectString(clip);
return true;
}
});
resize = menu.add(R.string.console_menu_resize);
if (hardKeyboard)
resize.setAlphabeticShortcut('r');
resize.setIcon(android.R.drawable.ic_menu_crop);
resize.setEnabled(sessionOpen);
resize.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
final View resizeView = inflater.inflate(R.layout.dia_resize, null, false);
((EditText) resizeView.findViewById(R.id.width))
.setText(prefs.getString(PreferenceConstants.DEFAULT_FONT_SIZE_WIDTH, "80"));
((EditText) resizeView.findViewById(R.id.height))
.setText(prefs.getString(PreferenceConstants.DEFAULT_FONT_SIZE_HEIGHT, "25"));
new AlertDialog.Builder(ConsoleActivity.this)
.setView(resizeView)
.setPositiveButton(R.string.button_resize, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
int width, height;
try {
width = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.width))
.getText().toString());
height = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.height))
.getText().toString());
} catch (NumberFormatException nfe) {
// TODO change this to a real dialog where we can
// make the input boxes turn red to indicate an error.
return;
}
if (width > 0 && height > 0) {
terminalView.forceSize(width, height);
}
else {
new AlertDialog.Builder(ConsoleActivity.this)
.setTitle(R.string.resize_error_title)
.setMessage(R.string.resize_error_width_height)
.setNegativeButton(R.string.button_close, null)
.show();
}
}
}).setNeutralButton(R.string.button_resize_reset, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
terminalView.bridge.resetSize(terminalView);
}
}).setNegativeButton(android.R.string.cancel, null)
.create().show();
return true;
}
});
screenCapture = menu.add(R.string.console_menu_screencapture);
if (hardKeyboard)
screenCapture.setAlphabeticShortcut('s');
screenCapture.setIcon(android.R.drawable.ic_menu_camera);
screenCapture.setEnabled(activeTerminal);
screenCapture.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
terminalView.bridge.captureScreen();
return true;
}
});
portForward = menu.add(R.string.console_menu_portforwards);
if (hardKeyboard)
portForward.setAlphabeticShortcut('f');
portForward.setIcon(android.R.drawable.ic_menu_manage);
portForward.setEnabled(sessionOpen && canForwardPorts);
portForward.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
Intent intent = new Intent(ConsoleActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, bridge.host.getId());
ConsoleActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
urlscan = menu.add(R.string.console_menu_urlscan);
if (hardKeyboard)
urlscan.setAlphabeticShortcut('l');
urlscan.setIcon(android.R.drawable.ic_menu_search);
urlscan.setEnabled(activeTerminal);
urlscan.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return true;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.urlScan(terminal);
return true;
}
});
download = menu.add(R.string.console_menu_download);
download.setAlphabeticShortcut('d');
download.setEnabled(sessionOpen && canTransferFiles);
download.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final String downloadFolder = prefs.getString(PreferenceConstants.DOWNLOAD_FOLDER, "");
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
final TerminalBridge bridge = terminalView.bridge;
final EditText textField = new EditText(ConsoleActivity.this);
new AlertDialog.Builder(ConsoleActivity.this)
.setTitle(R.string.transfer_select_remote_download_title)
.setMessage(R.string.transfer_select_remote_download_desc)
.setView(textField)
.setPositiveButton(R.string.transfer_button_download, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
TransferThread transfer = new TransferThread(ConsoleActivity.this, handler);
if (!prefs.getBoolean(PreferenceConstants.BACKGROUND_FILE_TRANSFER,true))
transfer.setProgressDialogMessage(getString(R.string.transfer_downloading));
transfer.download(bridge, textField.getText().toString(), null, downloadFolder);
}
}).setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
upload = menu.add(R.string.console_menu_upload);
upload.setAlphabeticShortcut('u');
upload.setEnabled(sessionOpen && canTransferFiles);
upload.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
FileChooser.selectFile(ConsoleActivity.this, ConsoleActivity.this,
FileChooser.REQUEST_CODE_SELECT_FILE,
getString(R.string.file_chooser_select_file, getString(R.string.select_for_upload)));
return true;
}
});
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case FileChooser.REQUEST_CODE_SELECT_FILE:
if (resultCode == RESULT_OK && intent != null) {
Uri uri = intent.getData();
try {
if (uri != null) {
fileSelected(new File(URI.create(uri.toString())));
} else {
String filename = intent.getDataString();
if (filename != null) {
fileSelected(new File(URI.create(filename)));
}
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Couldn't read from selected file", e);
}
}
break;
}
}
public void fileSelected(final File f) {
String destFileName;
String uploadFolder = prefs.getString(PreferenceConstants.REMOTE_UPLOAD_FOLDER,null);
final TransferThread transfer = new TransferThread(ConsoleActivity.this, handler);
Log.d(TAG, "File chooser returned " + f);
if (uploadFolder == null)
uploadFolder = "";
if (!uploadFolder.equals("") && uploadFolder.charAt(uploadFolder.length()-1) != '/' )
destFileName = uploadFolder + "/" + f.getName();
else
destFileName = uploadFolder + f.getName();
if (prefs.getBoolean(PreferenceConstants.UPLOAD_DESTINATION_PROMPT,true)) {
final EditText fileDest = new EditText(ConsoleActivity.this);
fileDest.setSingleLine();
fileDest.setText(destFileName);
new AlertDialog.Builder(ConsoleActivity.this)
.setTitle(R.string.transfer_select_remote_upload_dest_title)
.setMessage(getResources().getString(R.string.transfer_select_remote_upload_dest_desc) + "\n" + f.getPath())
.setView(fileDest)
.setPositiveButton(R.string.transfer_button_upload, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (!prefs.getBoolean(PreferenceConstants.BACKGROUND_FILE_TRANSFER,true))
transfer.setProgressDialogMessage(getString(R.string.transfer_uploading));
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
File uf = new File(fileDest.getText().toString());
String name = "", parent = "";
if (uf.getParent() != null)
parent = uf.getParent().toString();
if (uf.getName() != null)
name = uf.getName().toString();
transfer.upload(bridge, f.toString(), name, parent);
}
}).setNegativeButton(android.R.string.cancel, null).create().show();
} else {
if (!prefs.getBoolean(PreferenceConstants.BACKGROUND_FILE_TRANSFER,true))
transfer.setProgressDialogMessage(getString(R.string.transfer_uploading));
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
transfer.upload(bridge, f.toString(), null, uploadFolder);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);
final View view = findCurrentView(R.id.console_flip);
boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
boolean canTransferFiles = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
canTransferFiles = bridge.canTransferFiles();
}
disconnect.setEnabled(activeTerminal);
if (sessionOpen || !disconnected)
disconnect.setTitle(R.string.list_host_disconnect);
else
disconnect.setTitle(R.string.console_menu_close);
copy.setEnabled(activeTerminal);
paste.setEnabled(clipboard.hasText() && sessionOpen);
portForward.setEnabled(sessionOpen && canForwardPorts);
urlscan.setEnabled(activeTerminal);
resize.setEnabled(sessionOpen);
download.setEnabled(sessionOpen && canTransferFiles);
upload.setEnabled(sessionOpen && canTransferFiles);
return true;
}
@Override
public void onOptionsMenuClosed(Menu menu) {
super.onOptionsMenuClosed(menu);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
@Override
public void onStart() {
super.onStart();
// connect with manager service to find all bridges
// when connected it will insert all views
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if (getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
this.mKeyboardButton.setVisibility(View.GONE);
}
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause called");
if (forcedOrientation && bound != null)
bound.setResizeAllowed(false);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume called");
// Make sure we don't let the screen fall asleep.
// This also keeps the Wi-Fi chipset from disconnecting us.
if (prefs.getBoolean(PreferenceConstants.KEEP_ALIVE, true)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
configureOrientation();
if (forcedOrientation && bound != null)
bound.setResizeAllowed(true);
}
/* (non-Javadoc)
* @see android.app.Activity#onNewIntent(android.content.Intent)
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "onNewIntent called");
requested = intent.getData();
if (requested == null) {
Log.e(TAG, "Got null intent data in onNewIntent()");
return;
}
if (bound == null) {
Log.e(TAG, "We're not bound in onNewIntent()");
return;
}
TerminalBridge requestedBridge = bound.getConnectedBridge(requested.getFragment());
int requestedIndex = 0;
synchronized (flip) {
if (requestedBridge == null) {
// If we didn't find the requested connection, try opening it
try {
Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s),"+
"so creating one now", requested.toString(), requested.getFragment()));
requestedBridge = bound.openConnection(requested);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
// TODO: We should display an error dialog here.
return;
}
requestedIndex = addNewTerminalView(requestedBridge);
} else {
final int flipIndex = getFlipIndex(requestedBridge);
if (flipIndex > requestedIndex) {
requestedIndex = flipIndex;
}
}
setDisplayedTerminal(requestedIndex);
}
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
}
protected void shiftCurrentTerminal(final int direction) {
View overlay;
synchronized (flip) {
boolean shouldAnimate = flip.getChildCount() > 1;
// Only show animation if there is something else to go to.
if (shouldAnimate) {
// keep current overlay from popping up again
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_stay_hidden);
if (direction == SHIFT_LEFT) {
flip.setInAnimation(slide_left_in);
flip.setOutAnimation(slide_left_out);
flip.showNext();
} else if (direction == SHIFT_RIGHT) {
flip.setInAnimation(slide_right_in);
flip.setOutAnimation(slide_right_out);
flip.showPrevious();
}
}
ConsoleActivity.this.updateDefault();
if (shouldAnimate) {
// show overlay on new slide and start fade
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_out_delayed);
}
updatePromptVisible();
}
}
/**
* Save the currently shown {@link TerminalView} as the default. This is
* saved back down into {@link TerminalManager} where we can read it again
* later.
*/
private void updateDefault() {
// update the current default terminal
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return;
TerminalView terminal = (TerminalView)view;
if(bound == null) return;
bound.defaultBridge = terminal.bridge;
}
protected void updateEmptyVisible() {
// update visibility of empty status message
empty.setVisibility((flip.getChildCount() == 0) ? View.VISIBLE : View.GONE);
}
/**
* Show any prompts requested by the currently visible {@link TerminalView}.
*/
protected void updatePromptVisible() {
// check if our currently-visible terminalbridge is requesting any prompt services
View view = findCurrentView(R.id.console_flip);
// Hide all the prompts in case a prompt request was canceled
hideAllPrompts();
if(!(view instanceof TerminalView)) {
// we dont have an active view, so hide any prompts
return;
}
PromptHelper prompt = ((TerminalView)view).bridge.promptHelper;
if(String.class.equals(prompt.promptRequested)) {
stringPromptGroup.setVisibility(View.VISIBLE);
String instructions = prompt.promptInstructions;
boolean password = prompt.passwordRequested;
if (instructions != null && instructions.length() > 0) {
stringPromptInstructions.setVisibility(View.VISIBLE);
stringPromptInstructions.setText(instructions);
} else
stringPromptInstructions.setVisibility(View.GONE);
if (password) {
stringPrompt.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
stringPrompt.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
stringPrompt.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
stringPrompt.setTransformationMethod(SingleLineTransformationMethod.getInstance());
}
stringPrompt.setText("");
stringPrompt.setHint(prompt.promptHint);
stringPrompt.requestFocus();
} else if(Boolean.class.equals(prompt.promptRequested)) {
booleanPromptGroup.setVisibility(View.VISIBLE);
booleanPrompt.setText(prompt.promptHint);
booleanYes.requestFocus();
} else {
hideAllPrompts();
view.requestFocus();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, String.format("onConfigurationChanged; requestedOrientation=%d, newConfig.orientation=%d", getRequestedOrientation(), newConfig.orientation));
if (bound != null) {
if (forcedOrientation &&
(newConfig.orientation != Configuration.ORIENTATION_LANDSCAPE &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) ||
(newConfig.orientation != Configuration.ORIENTATION_PORTRAIT &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT))
bound.setResizeAllowed(false);
else
bound.setResizeAllowed(true);
bound.hardKeyboardHidden = (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES);
mKeyboardButton.setVisibility(bound.hardKeyboardHidden ? View.VISIBLE : View.GONE);
}
}
/**
* Adds a new TerminalBridge to the current set of views in our ViewFlipper.
*
* @param bridge TerminalBridge to add to our ViewFlipper
* @return the child index of the new view in the ViewFlipper
*/
private int addNewTerminalView(TerminalBridge bridge) {
// let them know about our prompt handler services
bridge.promptHelper.setHandler(promptHandler);
// inflate each terminal view
RelativeLayout view = (RelativeLayout)inflater.inflate(R.layout.item_terminal, flip, false);
// set the terminal overlay text
TextView overlay = (TextView)view.findViewById(R.id.terminal_overlay);
overlay.setText(bridge.host.getNickname());
// and add our terminal view control, using index to place behind overlay
TerminalView terminal = new TerminalView(ConsoleActivity.this, bridge);
terminal.setId(R.id.console_flip);
view.addView(terminal, 0);
synchronized (flip) {
// finally attach to the flipper
flip.addView(view);
return flip.getChildCount() - 1;
}
}
private int getFlipIndex(TerminalBridge bridge) {
synchronized (flip) {
final int children = flip.getChildCount();
for (int i = 0; i < children; i++) {
final View view = flip.getChildAt(i).findViewById(R.id.console_flip);
if (view == null || !(view instanceof TerminalView)) {
// How did that happen?
continue;
}
final TerminalView tv = (TerminalView) view;
if (tv.bridge == bridge) {
return i;
}
}
}
return -1;
}
/**
* Displays the child in the ViewFlipper at the requestedIndex and updates the prompts.
*
* @param requestedIndex the index of the terminal view to display
*/
private void setDisplayedTerminal(int requestedIndex) {
synchronized (flip) {
try {
// show the requested bridge if found, also fade out overlay
flip.setDisplayedChild(requestedIndex);
flip.getCurrentView().findViewById(R.id.terminal_overlay)
.startAnimation(fade_out_delayed);
} catch (NullPointerException npe) {
Log.d(TAG, "View went away when we were about to display it", npe);
}
updatePromptVisible();
updateEmptyVisible();
}
}
private void setFullScreen(int fullScreen) {
if (fullScreen != this.fullScreen) {
if (fullScreen == FULLSCREEN_ON) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (!PreferenceConstants.PRE_HONEYCOMB) {
this.hideActionBar();
}
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (!PreferenceConstants.PRE_HONEYCOMB) {
if (!prefs.getBoolean(PreferenceConstants.HIDE_ACTIONBAR, false))
this.showActionBar();
}
}
this.fullScreen = fullScreen;
if (bound != null)
bound.setFullScreen(this.fullScreen);
}
}
private void showActionBar() {
try {
if (this.getActionBar() != null)
this.getActionBar().show();
} catch (Exception e) {
Log.e(TAG, "Error showing ActionBar", e);
}
}
private void hideActionBar() {
try {
if (this.getActionBar() != null)
this.getActionBar().hide();
} catch (Exception e) {
Log.e(TAG, "Error hiding ActionBar", e);
}
}
} | Re-read hardware keyboard status on resume. Fixes #8
| src/sk/vx/connectbot/ConsoleActivity.java | Re-read hardware keyboard status on resume. Fixes #8 | <ide><path>rc/sk/vx/connectbot/ConsoleActivity.java
<ide>
<ide> bound.setResizeAllowed(true);
<ide>
<add> bound.hardKeyboardHidden = (getResources().getConfiguration().hardKeyboardHidden ==
<add> Configuration.HARDKEYBOARDHIDDEN_YES);
<add>
<ide> // set fullscreen value
<ide> if (bound.getFullScreen() == 0) {
<ide> if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false)) |
|
Java | apache-2.0 | de486ab060ea65d046ea00fb541f5cefc8db0856 | 0 | manstis/drools,jomarko/drools,droolsjbpm/drools,winklerm/drools,manstis/drools,droolsjbpm/drools,romartin/drools,lanceleverich/drools,lanceleverich/drools,droolsjbpm/drools,jomarko/drools,jomarko/drools,winklerm/drools,winklerm/drools,jomarko/drools,romartin/drools,manstis/drools,manstis/drools,jomarko/drools,romartin/drools,lanceleverich/drools,lanceleverich/drools,winklerm/drools,manstis/drools,winklerm/drools,romartin/drools,lanceleverich/drools,romartin/drools,droolsjbpm/drools,droolsjbpm/drools | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.compiler.integrationtests;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;
import org.drools.compiler.CommonTestMethodBase;
import org.drools.compiler.compiler.io.Folder;
import org.drools.compiler.compiler.io.memory.MemoryFileSystem;
import org.drools.core.impl.InternalKieContainer;
import org.drools.compiler.kie.builder.impl.MemoryKieModule;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.Message.Level;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.Results;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.definition.type.FactType;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import static org.drools.core.util.DroolsAssert.assertEnumerationSize;
import static org.drools.core.util.DroolsAssert.assertUrlEnumerationContainsMatch;
import static org.junit.Assert.*;
public class KieContainerTest extends CommonTestMethodBase {
@Test
public void testMainKieModule() {
KieServices ks = KieServices.Factory.get();
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = ks.newReleaseId("org.kie", "test-delete", "1.0.0");
createAndDeployJar( ks, releaseId, createDRL("ruleA") );
KieContainer kieContainer = ks.newKieContainer(releaseId);
KieModule kmodule = ((InternalKieContainer) kieContainer).getMainKieModule();
assertEquals( releaseId, kmodule.getReleaseId() );
}
@Test
public void testUpdateToNonExistingRelease() {
// DROOLS-1562
KieServices ks = KieServices.Factory.get();
ReleaseId releaseId = ks.newReleaseId("org.kie", "test-release", "1.0.0");
createAndDeployJar( ks, releaseId, createDRL("ruleA") );
KieContainer kieContainer = ks.newKieContainer(releaseId);
Results results = kieContainer.updateToVersion( ks.newReleaseId( "org.kie", "test-release", "1.0.1" ) );
assertEquals( 1, results.getMessages( Level.ERROR ).size() );
assertEquals( "1.0.0", ( (InternalKieContainer) kieContainer ).getContainerReleaseId().getVersion() );
}
@Test
public void testReleaseIdGetters() {
KieServices ks = KieServices.Factory.get();
ReleaseId releaseId = ks.newReleaseId("org.kie", "test-delete-v", "1.0.1");
createAndDeployJar( ks, releaseId, createDRL("ruleA") );
ReleaseId configuredReleaseId = ks.newReleaseId("org.kie", "test-delete-v", "RELEASE");
KieContainer kieContainer = ks.newKieContainer(configuredReleaseId);
InternalKieContainer iKieContainer = (InternalKieContainer) kieContainer;
assertEquals(configuredReleaseId, iKieContainer.getConfiguredReleaseId());
assertEquals(releaseId, iKieContainer.getResolvedReleaseId());
assertEquals(releaseId, iKieContainer.getReleaseId());
// demonstrate internal API behavior, in the future shall this be enforced?
assertEquals(configuredReleaseId, iKieContainer.getContainerReleaseId());
ReleaseId newReleaseId = ks.newReleaseId("org.kie", "test-delete-v", "1.0.2");
createAndDeployJar( ks, newReleaseId, createDRL("ruleA") );
iKieContainer.updateToVersion(newReleaseId);
assertEquals(configuredReleaseId, iKieContainer.getConfiguredReleaseId());
assertEquals(newReleaseId, iKieContainer.getResolvedReleaseId());
assertEquals(newReleaseId, iKieContainer.getReleaseId());
// demonstrate internal API behavior, in the future shall this be enforced?
assertEquals(newReleaseId, iKieContainer.getContainerReleaseId());
}
@Test
public void testSharedTypeDeclarationsUsingClassLoader() throws Exception {
String type = "package org.drools.test\n" +
"declare Message\n" +
" message : String\n" +
"end\n";
String drl1 = "package org.drools.test\n" +
"rule R1 when\n" +
" $o : Object()\n" +
"then\n" +
" if ($o.getClass().getName().equals(\"org.drools.test.Message\") && $o.getClass() != new Message(\"Test\").getClass()) {\n" +
" throw new RuntimeException();\n" +
" }\n" +
"end\n";
String drl2 = "package org.drools.test\n" +
"rule R2_2 when\n" +
" $m : Message( message == \"Hello World\" )\n" +
"then\n" +
" if ($m.getClass() != new Message(\"Test\").getClass()) {\n" +
" throw new RuntimeException();\n" +
" }\n" +
"end\n";
KieServices ks = KieServices.Factory.get();
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-delete", "1.0.0");
KieModule km = createAndDeployJar( ks, releaseId1, type, drl1, drl2 );
KieContainer kieContainer = ks.newKieContainer(releaseId1);
KieContainer kieContainer2 = ks.newKieContainer(releaseId1);
KieSession ksession = kieContainer.newKieSession();
KieSession ksession2 = kieContainer2.newKieSession();
Class cls1 = kieContainer.getClassLoader().loadClass( "org.drools.test.Message");
Constructor constructor = cls1.getConstructor(String.class);
ksession.insert(constructor.newInstance("Hello World"));
assertEquals( 2, ksession.fireAllRules() );
Class cls2 = kieContainer2.getClassLoader().loadClass( "org.drools.test.Message");
Constructor constructor2 = cls2.getConstructor(String.class);
ksession2.insert(constructor2.newInstance("Hello World"));
assertEquals( 2, ksession2.fireAllRules() );
assertNotSame(cls1, cls2);
}
@Test
public void testSharedTypeDeclarationsUsingFactTypes() throws Exception {
String type = "package org.drools.test\n" +
"declare Message\n" +
" message : String\n" +
"end\n";
String drl1 = "package org.drools.test\n" +
"rule R1 when\n" +
" $m : Message()\n" +
"then\n" +
" if ($m.getClass() != new Message(\"Test\").getClass()) {\n" +
" throw new RuntimeException();\n" +
" }\n" +
"end\n";
String drl2 = "package org.drools.test\n" +
"rule R2_2 when\n" +
" $m : Message( message == \"Hello World\" )\n" +
"then\n" +
" if ($m.getClass() != new Message(\"Test\").getClass()) {\n" +
" throw new RuntimeException();\n" +
" }\n" +
"end\n";
KieServices ks = KieServices.Factory.get();
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-delete", "1.0.0");
createAndDeployJar( ks, releaseId1, type, drl1, drl2 );
KieContainer kieContainer = ks.newKieContainer(releaseId1);
KieContainer kieContainer2 = ks.newKieContainer(releaseId1);
KieSession ksession = kieContainer.newKieSession();
KieSession ksession2 = kieContainer2.newKieSession();
insertMessageFromTypeDeclaration( ksession );
assertEquals( 2, ksession.fireAllRules() );
ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-delete", "1.0.1");
createAndDeployJar( ks, releaseId2, type, null, drl2 );
kieContainer.updateToVersion(releaseId2);
// test with the old ksession ...
ksession = kieContainer.newKieSession();
insertMessageFromTypeDeclaration( ksession );
assertEquals( 1, ksession.fireAllRules() );
// ... and with a brand new one
ksession = kieContainer.newKieSession();
insertMessageFromTypeDeclaration (ksession );
assertEquals( 1, ksession.fireAllRules() );
// check that the second kieContainer hasn't been affected by the update of the first one
insertMessageFromTypeDeclaration( ksession2 );
assertEquals( 2, ksession2.fireAllRules() );
ksession2 = kieContainer2.newKieSession();
insertMessageFromTypeDeclaration( ksession2 );
assertEquals( 2, ksession2.fireAllRules() );
}
private void insertMessageFromTypeDeclaration(KieSession ksession) throws InstantiationException, IllegalAccessException {
FactType messageType = ksession.getKieBase().getFactType("org.drools.test", "Message");
Object message = messageType.newInstance();
messageType.set(message, "message", "Hello World");
ksession.insert(message);
}
@Test(timeout = 20000)
public void testIncrementalCompilationSynchronization() {
final KieServices kieServices = KieServices.Factory.get();
ReleaseId releaseId = kieServices.newReleaseId("org.kie.test", "sync-scanner-test", "1.0.0");
createAndDeployJar( kieServices, releaseId, createDRL("rule0") );
final KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieSession kieSession = kieContainer.newKieSession();
List<String> list = new ArrayList<>();
kieSession.setGlobal("list", list);
kieSession.fireAllRules();
kieSession.dispose();
assertEquals(1, list.size());
Thread t = new Thread(() -> {
for (int i = 1; i < 10; i++) {
ReleaseId releaseId1 = kieServices.newReleaseId("org.kie.test", "sync-scanner-test", "1.0." + i);
createAndDeployJar(kieServices, releaseId1, createDRL("rule" + i) );
kieContainer.updateToVersion(releaseId1);
}
});
t.setDaemon(true);
t.start();
while (true) {
kieSession = kieContainer.newKieSession();
list = new ArrayList<>();
kieSession.setGlobal("list", list);
kieSession.fireAllRules();
kieSession.dispose();
// There can be multiple items in the list if an updateToVersion is triggered during a fireAllRules
// (updateToVersion can be called multiple times during fireAllRules, especially on slower machines)
// in that case it may fire with the old rule and multiple new ones
Assertions.assertThat(list).isNotEmpty();
if (list.get(0).equals("rule9")) {
break;
}
}
}
@Test
public void testMemoryFileSystemFolderUniqueness() {
KieServices kieServices = KieServices.Factory.get();
String drl = "package org.drools.test\n" +
"rule R1 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource = kieServices.getResources().newReaderResource( new StringReader( drl), "UTF-8" );
resource.setTargetPath("org/drools/test/rules.drl");
String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
" <kbase name=\"testKbase\" packages=\"org.drools.test\">\n" +
" <ksession name=\"testKsession\"/>\n" +
" </kbase>\n" +
"</kmodule>";
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-delete", "1.0.0");
createAndDeployJar(kieServices, kmodule, releaseId, resource);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieModule kieModule = ((InternalKieContainer) kieContainer).getMainKieModule();
MemoryFileSystem memoryFileSystem = ((MemoryKieModule) kieModule).getMemoryFileSystem();
Folder rootFolder = memoryFileSystem.getFolder("");
Object[] members = rootFolder.getMembers().toArray();
assertEquals(2, members.length);
Folder firstFolder = (Folder) members[0];
Folder secondFolder = (Folder) members[1];
assertEquals(firstFolder.getParent(), secondFolder.getParent());
}
@Test
public void testClassLoaderGetResources() throws IOException {
KieServices kieServices = KieServices.Factory.get();
String drl1 = "package org.drools.testdrl;\n" +
"rule R1 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource1 = kieServices.getResources().newReaderResource(new StringReader(drl1), "UTF-8");
resource1.setTargetPath("org/drools/testdrl/rules1.drl");
String drl2 = "package org.drools.testdrl;\n" +
"rule R2 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource2 = kieServices.getResources().newReaderResource(new StringReader(drl2), "UTF-8");
resource2.setTargetPath("org/drools/testdrl/rules2.drl");
String java3 = "package org.drools.testjava;\n" +
"public class Message {}";
Resource resource3 = kieServices.getResources().newReaderResource(new StringReader(java3), "UTF-8");
resource3.setTargetPath("org/drools/testjava/Message.java");
resource3.setResourceType(ResourceType.JAVA);
String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
" <kbase name=\"testKbase\" packages=\"org.drools.testdrl\">\n" +
" <ksession name=\"testKsession\"/>\n" +
" </kbase>\n" +
"</kmodule>";
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-delete", "1.0.0");
createAndDeployJar(kieServices, kmodule, releaseId, resource1, resource2, resource3);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
ClassLoader classLoader = kieContainer.getClassLoader();
assertEnumerationSize(1, classLoader.getResources("org/drools/testjava")); // no trailing "/"
assertEnumerationSize(1, classLoader.getResources("org/drools/testdrl/")); // trailing "/" to test both variants
// make sure the package resource correctly lists all its child resources (files in this case)
URL url = classLoader.getResources("org/drools/testdrl").nextElement();
List<String> lines = IOUtils.readLines(url.openStream());
Assertions.assertThat(lines).contains("rules1.drl", "rules1.drl.properties", "rules2.drl", "rules2.drl.properties");
assertUrlEnumerationContainsMatch("^mfs\\:/$", classLoader.getResources(""));
}
@Test
public void testGetDefaultKieSessionModel() {
KieServices kieServices = KieServices.Factory.get();
String drl = "package org.drools.test\n" +
"rule R1 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource = kieServices.getResources().newReaderResource( new StringReader( drl), "UTF-8" );
resource.setTargetPath("org/drools/test/rules.drl");
String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
" <kbase name=\"testKbase\" packages=\"org.drools.test\">\n" +
" <ksession name=\"testKsession\" default=\"true\"/>\n" +
" </kbase>\n" +
"</kmodule>";
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-testGetDefaultKieSessionModel", "1.0.0");
createAndDeployJar(kieServices, kmodule, releaseId, resource);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieSessionModel sessionModel = kieContainer.getKieSessionModel(null);
assertNotNull(sessionModel);
assertEquals("testKsession", sessionModel.getName());
}
@Test
public void testGetDefaultKieSessionModelEmptyKmodule() {
KieServices kieServices = KieServices.Factory.get();
String drl = "package org.drools.test\n" +
"rule R1 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource = kieServices.getResources().newReaderResource( new StringReader( drl), "UTF-8" );
resource.setTargetPath("org/drools/test/rules.drl");
String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
"</kmodule>";
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-testGetDefaultKieSessionModelEmptyKmodule", "1.0.0");
createAndDeployJar(kieServices, kmodule, releaseId, resource);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieSessionModel sessionModel = kieContainer.getKieSessionModel(null);
assertNotNull(sessionModel);
}
private String createDRL(String ruleName) {
return "package org.kie.test\n" +
"global java.util.List list\n" +
"rule " + ruleName + "\n" +
"when\n" +
"then\n" +
"list.add( drools.getRule().getName() );\n" +
"end\n";
}
}
| drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieContainerTest.java | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.compiler.integrationtests;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;
import org.drools.compiler.CommonTestMethodBase;
import org.drools.compiler.compiler.io.Folder;
import org.drools.compiler.compiler.io.memory.MemoryFileSystem;
import org.drools.core.impl.InternalKieContainer;
import org.drools.compiler.kie.builder.impl.MemoryKieModule;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.Message.Level;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.Results;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.definition.type.FactType;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import static org.drools.core.util.DroolsAssert.assertEnumerationSize;
import static org.drools.core.util.DroolsAssert.assertUrlEnumerationContainsMatch;
import static org.junit.Assert.*;
public class KieContainerTest extends CommonTestMethodBase {
@Test
public void testMainKieModule() {
KieServices ks = KieServices.Factory.get();
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = ks.newReleaseId("org.kie", "test-delete", "1.0.0");
createAndDeployJar( ks, releaseId, createDRL("ruleA") );
KieContainer kieContainer = ks.newKieContainer(releaseId);
KieModule kmodule = ((InternalKieContainer) kieContainer).getMainKieModule();
assertEquals( releaseId, kmodule.getReleaseId() );
}
@Test
public void testUpdateToNonExistingRelease() {
// DROOLS-1562
KieServices ks = KieServices.Factory.get();
ReleaseId releaseId = ks.newReleaseId("org.kie", "test-release", "1.0.0");
createAndDeployJar( ks, releaseId, createDRL("ruleA") );
KieContainer kieContainer = ks.newKieContainer(releaseId);
Results results = kieContainer.updateToVersion( ks.newReleaseId( "org.kie", "test-release", "1.0.1" ) );
assertEquals( 1, results.getMessages( Level.ERROR ).size() );
assertEquals( "1.0.0", ( (InternalKieContainer) kieContainer ).getContainerReleaseId().getVersion() );
}
@Test
public void testReleaseIdGetters() {
KieServices ks = KieServices.Factory.get();
ReleaseId releaseId = ks.newReleaseId("org.kie", "test-delete-v", "1.0.1");
createAndDeployJar( ks, releaseId, createDRL("ruleA") );
ReleaseId configuredReleaseId = ks.newReleaseId("org.kie", "test-delete-v", "RELEASE");
KieContainer kieContainer = ks.newKieContainer(configuredReleaseId);
InternalKieContainer iKieContainer = (InternalKieContainer) kieContainer;
assertEquals(configuredReleaseId, iKieContainer.getConfiguredReleaseId());
assertEquals(releaseId, iKieContainer.getResolvedReleaseId());
assertEquals(releaseId, iKieContainer.getReleaseId());
// demonstrate internal API behavior, in the future shall this be enforced?
assertEquals(configuredReleaseId, iKieContainer.getContainerReleaseId());
ReleaseId newReleaseId = ks.newReleaseId("org.kie", "test-delete-v", "1.0.2");
createAndDeployJar( ks, newReleaseId, createDRL("ruleA") );
iKieContainer.updateToVersion(newReleaseId);
assertEquals(configuredReleaseId, iKieContainer.getConfiguredReleaseId());
assertEquals(newReleaseId, iKieContainer.getResolvedReleaseId());
assertEquals(newReleaseId, iKieContainer.getReleaseId());
// demonstrate internal API behavior, in the future shall this be enforced?
assertEquals(newReleaseId, iKieContainer.getContainerReleaseId());
}
@Test
public void testSharedTypeDeclarationsUsingClassLoader() throws Exception {
String type = "package org.drools.test\n" +
"declare Message\n" +
" message : String\n" +
"end\n";
String drl1 = "package org.drools.test\n" +
"rule R1 when\n" +
" $o : Object()\n" +
"then\n" +
" if ($o.getClass().getName().equals(\"org.drools.test.Message\") && $o.getClass() != new Message(\"Test\").getClass()) {\n" +
" throw new RuntimeException();\n" +
" }\n" +
"end\n";
String drl2 = "package org.drools.test\n" +
"rule R2_2 when\n" +
" $m : Message( message == \"Hello World\" )\n" +
"then\n" +
" if ($m.getClass() != new Message(\"Test\").getClass()) {\n" +
" throw new RuntimeException();\n" +
" }\n" +
"end\n";
KieServices ks = KieServices.Factory.get();
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-delete", "1.0.0");
KieModule km = createAndDeployJar( ks, releaseId1, type, drl1, drl2 );
KieContainer kieContainer = ks.newKieContainer(releaseId1);
KieContainer kieContainer2 = ks.newKieContainer(releaseId1);
KieSession ksession = kieContainer.newKieSession();
KieSession ksession2 = kieContainer2.newKieSession();
Class cls1 = kieContainer.getClassLoader().loadClass( "org.drools.test.Message");
Constructor constructor = cls1.getConstructor(String.class);
ksession.insert(constructor.newInstance("Hello World"));
assertEquals( 2, ksession.fireAllRules() );
Class cls2 = kieContainer2.getClassLoader().loadClass( "org.drools.test.Message");
Constructor constructor2 = cls2.getConstructor(String.class);
ksession2.insert(constructor2.newInstance("Hello World"));
assertEquals( 2, ksession2.fireAllRules() );
assertNotSame(cls1, cls2);
}
@Test
public void testSharedTypeDeclarationsUsingFactTypes() throws Exception {
String type = "package org.drools.test\n" +
"declare Message\n" +
" message : String\n" +
"end\n";
String drl1 = "package org.drools.test\n" +
"rule R1 when\n" +
" $m : Message()\n" +
"then\n" +
" if ($m.getClass() != new Message(\"Test\").getClass()) {\n" +
" throw new RuntimeException();\n" +
" }\n" +
"end\n";
String drl2 = "package org.drools.test\n" +
"rule R2_2 when\n" +
" $m : Message( message == \"Hello World\" )\n" +
"then\n" +
" if ($m.getClass() != new Message(\"Test\").getClass()) {\n" +
" throw new RuntimeException();\n" +
" }\n" +
"end\n";
KieServices ks = KieServices.Factory.get();
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-delete", "1.0.0");
createAndDeployJar( ks, releaseId1, type, drl1, drl2 );
KieContainer kieContainer = ks.newKieContainer(releaseId1);
KieContainer kieContainer2 = ks.newKieContainer(releaseId1);
KieSession ksession = kieContainer.newKieSession();
KieSession ksession2 = kieContainer2.newKieSession();
insertMessageFromTypeDeclaration( ksession );
assertEquals( 2, ksession.fireAllRules() );
ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-delete", "1.0.1");
createAndDeployJar( ks, releaseId2, type, null, drl2 );
kieContainer.updateToVersion(releaseId2);
// test with the old ksession ...
ksession = kieContainer.newKieSession();
insertMessageFromTypeDeclaration( ksession );
assertEquals( 1, ksession.fireAllRules() );
// ... and with a brand new one
ksession = kieContainer.newKieSession();
insertMessageFromTypeDeclaration (ksession );
assertEquals( 1, ksession.fireAllRules() );
// check that the second kieContainer hasn't been affected by the update of the first one
insertMessageFromTypeDeclaration( ksession2 );
assertEquals( 2, ksession2.fireAllRules() );
ksession2 = kieContainer2.newKieSession();
insertMessageFromTypeDeclaration( ksession2 );
assertEquals( 2, ksession2.fireAllRules() );
}
private void insertMessageFromTypeDeclaration(KieSession ksession) throws InstantiationException, IllegalAccessException {
FactType messageType = ksession.getKieBase().getFactType("org.drools.test", "Message");
Object message = messageType.newInstance();
messageType.set(message, "message", "Hello World");
ksession.insert(message);
}
@Test(timeout = 10000)
public void testIncrementalCompilationSynchronization() throws Exception {
final KieServices kieServices = KieServices.Factory.get();
ReleaseId releaseId = kieServices.newReleaseId("org.kie.test", "sync-scanner-test", "1.0.0");
createAndDeployJar( kieServices, releaseId, createDRL("rule0") );
final KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieSession kieSession = kieContainer.newKieSession();
List<String> list = new ArrayList<String>();
kieSession.setGlobal("list", list);
kieSession.fireAllRules();
kieSession.dispose();
assertEquals(1, list.size());
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i < 10; i++) {
ReleaseId releaseId = kieServices.newReleaseId("org.kie.test", "sync-scanner-test", "1.0." + i);
createAndDeployJar( kieServices, releaseId, createDRL("rule" + i) );
kieContainer.updateToVersion(releaseId);
}
}
});
t.setDaemon(true);
t.start();
while (true) {
kieSession = kieContainer.newKieSession();
list = new ArrayList<String>();
kieSession.setGlobal("list", list);
kieSession.fireAllRules();
kieSession.dispose();
// There can be multiple items in the list if an updateToVersion is triggered during a fireAllRules
// (updateToVersion can be called multiple times during fireAllRules, especially on slower machines)
// in that case it may fire with the old rule and multiple new ones
Assertions.assertThat(list).isNotEmpty();
if (list.get(0).equals("rule9")) {
break;
}
}
}
@Test
public void testMemoryFileSystemFolderUniqueness() {
KieServices kieServices = KieServices.Factory.get();
String drl = "package org.drools.test\n" +
"rule R1 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource = kieServices.getResources().newReaderResource( new StringReader( drl), "UTF-8" );
resource.setTargetPath("org/drools/test/rules.drl");
String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
" <kbase name=\"testKbase\" packages=\"org.drools.test\">\n" +
" <ksession name=\"testKsession\"/>\n" +
" </kbase>\n" +
"</kmodule>";
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-delete", "1.0.0");
createAndDeployJar(kieServices, kmodule, releaseId, resource);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieModule kieModule = ((InternalKieContainer) kieContainer).getMainKieModule();
MemoryFileSystem memoryFileSystem = ((MemoryKieModule) kieModule).getMemoryFileSystem();
Folder rootFolder = memoryFileSystem.getFolder("");
Object[] members = rootFolder.getMembers().toArray();
assertEquals(2, members.length);
Folder firstFolder = (Folder) members[0];
Folder secondFolder = (Folder) members[1];
assertEquals(firstFolder.getParent(), secondFolder.getParent());
}
@Test
public void testClassLoaderGetResources() throws IOException {
KieServices kieServices = KieServices.Factory.get();
String drl1 = "package org.drools.testdrl;\n" +
"rule R1 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource1 = kieServices.getResources().newReaderResource(new StringReader(drl1), "UTF-8");
resource1.setTargetPath("org/drools/testdrl/rules1.drl");
String drl2 = "package org.drools.testdrl;\n" +
"rule R2 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource2 = kieServices.getResources().newReaderResource(new StringReader(drl2), "UTF-8");
resource2.setTargetPath("org/drools/testdrl/rules2.drl");
String java3 = "package org.drools.testjava;\n" +
"public class Message {}";
Resource resource3 = kieServices.getResources().newReaderResource(new StringReader(java3), "UTF-8");
resource3.setTargetPath("org/drools/testjava/Message.java");
resource3.setResourceType(ResourceType.JAVA);
String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
" <kbase name=\"testKbase\" packages=\"org.drools.testdrl\">\n" +
" <ksession name=\"testKsession\"/>\n" +
" </kbase>\n" +
"</kmodule>";
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-delete", "1.0.0");
createAndDeployJar(kieServices, kmodule, releaseId, resource1, resource2, resource3);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
ClassLoader classLoader = kieContainer.getClassLoader();
assertEnumerationSize(1, classLoader.getResources("org/drools/testjava")); // no trailing "/"
assertEnumerationSize(1, classLoader.getResources("org/drools/testdrl/")); // trailing "/" to test both variants
// make sure the package resource correctly lists all its child resources (files in this case)
URL url = classLoader.getResources("org/drools/testdrl").nextElement();
List<String> lines = IOUtils.readLines(url.openStream());
Assertions.assertThat(lines).contains("rules1.drl", "rules1.drl.properties", "rules2.drl", "rules2.drl.properties");
assertUrlEnumerationContainsMatch("^mfs\\:/$", classLoader.getResources(""));
}
@Test
public void testGetDefaultKieSessionModel() {
KieServices kieServices = KieServices.Factory.get();
String drl = "package org.drools.test\n" +
"rule R1 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource = kieServices.getResources().newReaderResource( new StringReader( drl), "UTF-8" );
resource.setTargetPath("org/drools/test/rules.drl");
String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
" <kbase name=\"testKbase\" packages=\"org.drools.test\">\n" +
" <ksession name=\"testKsession\" default=\"true\"/>\n" +
" </kbase>\n" +
"</kmodule>";
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-testGetDefaultKieSessionModel", "1.0.0");
createAndDeployJar(kieServices, kmodule, releaseId, resource);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieSessionModel sessionModel = kieContainer.getKieSessionModel(null);
assertNotNull(sessionModel);
assertEquals("testKsession", sessionModel.getName());
}
@Test
public void testGetDefaultKieSessionModelEmptyKmodule() {
KieServices kieServices = KieServices.Factory.get();
String drl = "package org.drools.test\n" +
"rule R1 when\n" +
" $m : Object()\n" +
"then\n" +
"end\n";
Resource resource = kieServices.getResources().newReaderResource( new StringReader( drl), "UTF-8" );
resource.setTargetPath("org/drools/test/rules.drl");
String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
"</kmodule>";
// Create an in-memory jar for version 1.0.0
ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-testGetDefaultKieSessionModelEmptyKmodule", "1.0.0");
createAndDeployJar(kieServices, kmodule, releaseId, resource);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieSessionModel sessionModel = kieContainer.getKieSessionModel(null);
assertNotNull(sessionModel);
}
private String createDRL(String ruleName) {
return "package org.kie.test\n" +
"global java.util.List list\n" +
"rule " + ruleName + "\n" +
"when\n" +
"then\n" +
"list.add( drools.getRule().getName() );\n" +
"end\n";
}
}
| DROOLS-3860 Raise timeout of testIncrementalCompilationSynchronization (#2306)
| drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieContainerTest.java | DROOLS-3860 Raise timeout of testIncrementalCompilationSynchronization (#2306) | <ide><path>rools-compiler/src/test/java/org/drools/compiler/integrationtests/KieContainerTest.java
<ide> }
<ide>
<ide>
<del> @Test(timeout = 10000)
<del> public void testIncrementalCompilationSynchronization() throws Exception {
<add> @Test(timeout = 20000)
<add> public void testIncrementalCompilationSynchronization() {
<ide> final KieServices kieServices = KieServices.Factory.get();
<ide>
<ide> ReleaseId releaseId = kieServices.newReleaseId("org.kie.test", "sync-scanner-test", "1.0.0");
<ide> final KieContainer kieContainer = kieServices.newKieContainer(releaseId);
<ide>
<ide> KieSession kieSession = kieContainer.newKieSession();
<del> List<String> list = new ArrayList<String>();
<add> List<String> list = new ArrayList<>();
<ide> kieSession.setGlobal("list", list);
<ide> kieSession.fireAllRules();
<ide> kieSession.dispose();
<ide> assertEquals(1, list.size());
<ide>
<del> Thread t = new Thread(new Runnable() {
<del> @Override
<del> public void run() {
<del> for (int i = 1; i < 10; i++) {
<del> ReleaseId releaseId = kieServices.newReleaseId("org.kie.test", "sync-scanner-test", "1.0." + i);
<del> createAndDeployJar( kieServices, releaseId, createDRL("rule" + i) );
<del> kieContainer.updateToVersion(releaseId);
<del> }
<add> Thread t = new Thread(() -> {
<add> for (int i = 1; i < 10; i++) {
<add> ReleaseId releaseId1 = kieServices.newReleaseId("org.kie.test", "sync-scanner-test", "1.0." + i);
<add> createAndDeployJar(kieServices, releaseId1, createDRL("rule" + i) );
<add> kieContainer.updateToVersion(releaseId1);
<ide> }
<ide> });
<ide>
<ide>
<ide> while (true) {
<ide> kieSession = kieContainer.newKieSession();
<del> list = new ArrayList<String>();
<add> list = new ArrayList<>();
<ide> kieSession.setGlobal("list", list);
<ide> kieSession.fireAllRules();
<ide> kieSession.dispose(); |
|
Java | mit | 66335e682027415d5e1e1ec0294f8be8ceb85152 | 0 | jenkinsci/saltstack-plugin,jenkinsci/saltstack-plugin,spacanowski/saltstack-plugin,spacanowski/saltstack-plugin | package com.waytta;
import hudson.Launcher;
import hudson.Extension;
import hudson.util.FormValidation;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.AbstractProject;
import hudson.tasks.Builder;
import hudson.tasks.BuildStepDescriptor;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import net.sf.json.JSONArray;
import net.sf.json.util.JSONUtils;
import net.sf.json.JSONSerializer;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
public class SaltAPIBuilder extends Builder {
private final String servername;
private final String username;
private final String userpass;
private final String authtype;
private final String target;
private final String targettype;
private final String function;
private final String arguments;
private final String kwarguments;
private final JSONObject clientInterfaces;
private final String clientInterface;
private final Boolean blockbuild;
private final Integer jobPollTime;
private final String batchSize;
private final String mods;
private final Boolean usePillar;
private final String pillarkey;
private final String pillarvalue;
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public SaltAPIBuilder(String servername, String username, String userpass, String authtype, String target, String targettype, String function, String arguments, String kwarguments, JSONObject clientInterfaces, Integer jobPollTime, String mods, String pillarkey, String pillarvalue) {
this.servername = servername;
this.username = username;
this.userpass = userpass;
this.authtype = authtype;
this.target = target;
this.targettype = targettype;
this.function = function;
this.arguments = arguments;
this.kwarguments = kwarguments;
this.clientInterfaces = clientInterfaces;
if (clientInterfaces.has("clientInterface")) {
this.clientInterface = clientInterfaces.get("clientInterface").toString();
} else {
this.clientInterface = "local";
}
if (clientInterface.equals("local")) {
this.blockbuild = clientInterfaces.getBoolean("blockbuild");
this.jobPollTime = clientInterfaces.getInt("jobPollTime");
this.batchSize = "100%";
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
} else if (clientInterface.equals("local_batch")) {
this.batchSize = clientInterfaces.get("batchSize").toString();
this.blockbuild = false;
this.jobPollTime = 10;
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
} else if (clientInterface.equals("runner")) {
this.mods = clientInterfaces.get("mods").toString();
if (clientInterfaces.has("usePillar")) {
this.usePillar = true;
this.pillarkey = clientInterfaces.getJSONObject("usePillar").get("pillarkey").toString();
this.pillarvalue = clientInterfaces.getJSONObject("usePillar").get("pillarvalue").toString();
} else {
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
}
this.blockbuild = false;
this.jobPollTime = 10;
this.batchSize = "100%";
} else {
this.batchSize = "100%";
this.blockbuild = false;
this.jobPollTime = 10;
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
}
}
/*
* We'll use this from the <tt>config.jelly</tt>.
*/
public String getServername() {
return servername;
}
public String getUsername() {
return username;
}
public String getUserpass() {
return userpass;
}
public String getAuthtype() {
return authtype;
}
public String getTarget() {
return target;
}
public String getTargettype() {
return this.targettype;
}
public String getFunction() {
return function;
}
public String getArguments() {
return arguments;
}
public String getKwarguments() {
return kwarguments;
}
public String getClientInterface() {
return clientInterface;
}
public Boolean getBlockbuild() {
return blockbuild;
}
public String getBatchSize() {
return batchSize;
}
public Integer getJobPollTime() {
return jobPollTime;
}
public String getMods() {
return mods;
}
public Boolean getUsePillar() {
return usePillar;
}
public String getPillarkey() {
return pillarkey;
}
public String getPillarvalue() {
return pillarvalue;
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
// This is where you 'build' the project.
// If not not configured, grab the default
int myJobPollTime = 10;
if (jobPollTime == null) {
myJobPollTime = getDescriptor().getPollTime();
} else {
myJobPollTime = jobPollTime;
}
Boolean mySaltMessageDebug = getDescriptor().getSaltMessageDebug();
String myClientInterface = clientInterface;
String mytarget = target;
String myfunction = function;
String myarguments = arguments;
String mykwarguments = kwarguments;
Boolean myBlockBuild = blockbuild;
//listener.getLogger().println("Salt Arguments before: "+myarguments);
mytarget = Utils.paramorize(build, listener, target);
myfunction = Utils.paramorize(build, listener, function);
myarguments = Utils.paramorize(build, listener, arguments);
mykwarguments = Utils.paramorize(build, listener, kwarguments);
//listener.getLogger().println("Salt Arguments after: "+myarguments);
//Setup connection for auth
String token = new String();
JSONObject auth = new JSONObject();
auth.put("username", username);
auth.put("password", userpass);
auth.put("eauth", authtype);
JSONArray authArray = new JSONArray();
authArray.add(auth);
//listener.getLogger().println("Sending auth: "+authArray.toString());
JSONObject httpResponse = new JSONObject();
//Get an auth token
token = Utils.getToken(servername, authArray);
if (token.contains("Error")) {
listener.getLogger().println(token);
return false;
}
//If we got this far, auth must have been pretty good and we've got a token
JSONArray saltArray = new JSONArray();
JSONObject saltFunc = new JSONObject();
// Hardcode clientInterface if not yet set. Once constructor runs, this will not be necessary
if (myClientInterface == null) {
myClientInterface = "local";
}
saltFunc.put("client", myClientInterface);
if (myClientInterface.equals("local_batch")) {
saltFunc.put("batch", batchSize);
listener.getLogger().println("Running in batch mode. Batch size: "+batchSize);
}
if (myClientInterface.equals("runner")) {
saltFunc.put("mods", mods);
if (usePillar) {
String myPillarkey = Utils.paramorize(build, listener, pillarkey);
String myPillarvalue = Utils.paramorize(build, listener, pillarvalue);
JSONObject jPillar = new JSONObject();
jPillar.put(JSONUtils.stripQuotes(myPillarkey), JSONUtils.stripQuotes(myPillarvalue));
saltFunc.put("pillar", jPillar);
}
}
saltFunc.put("tgt", mytarget);
saltFunc.put("expr_form", targettype);
saltFunc.put("fun", myfunction);
if (myarguments.length() > 0){
List saltArguments = new ArrayList();
//spit on comma seperated not inside of quotes
String[] argItems = myarguments.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (String arg : argItems) {
//remove spaces at begining or end
arg = arg.replaceAll("^\\s+|\\s+$", "");
arg = arg.replaceAll("\"|\\\"", "");
saltArguments.add(arg);
}
//Add any args to json message
saltFunc.element("arg", saltArguments);
}
if (mykwarguments.length() > 0){
Map kwArgs = new HashMap();
//spit on comma seperated not inside of quotes
String[] kwargItems = mykwarguments.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (String kwarg : kwargItems) {
//remove spaces at begining or end
kwarg = kwarg.replaceAll("^\\s+|\\s+$", "");
kwarg = kwarg.replaceAll("\"|\\\"", "");
if (kwarg.contains("=")) {
String[] kwString = kwarg.split("=");
if (kwString.length > 2){
//kwarg contained more than one =. Let's put the string back together
String kwFull = new String();
for (String kwItem : kwString){
//Ignore the first item as it will remain the key
if ( kwItem == kwString[0] ) continue;
//add the second item
if ( kwItem == kwString[1] ) {
kwFull += kwItem;
continue;
}
//add all other items with an = to rejoin
kwFull += "="+kwItem;
}
kwArgs.put(kwString[0], kwFull);
} else {
kwArgs.put(kwString[0], kwString[1]);
}
}
}
//Add any kwargs to json message
saltFunc.element("kwarg", kwArgs);
}
saltArray.add(saltFunc);
if (mySaltMessageDebug) {
listener.getLogger().println("Sending JSON: "+saltArray.toString());
}
if (myBlockBuild == null) {
//Set a sane default if uninitialized
myBlockBuild = false;
}
//blocking request
if (myBlockBuild) {
String jid = new String();
//Send request to /minion url. This will give back a jid which we will need to poll and lookup for completion
httpResponse = Utils.getJSON(servername+"/minions", saltArray, token);
try {
JSONArray returnArray = httpResponse.getJSONArray("return");
for (Object o : returnArray ) {
JSONObject line = (JSONObject) o;
jid = line.getString("jid");
}
//Print out success
listener.getLogger().println("Running jid: " + jid);
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+servername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
return false;
}
//Request successfully sent. Now use jid to check if job complete
int numMinions = 0;
int numMinionsDone = 0;
JSONArray returnArray = new JSONArray();
httpResponse = Utils.getJSON(servername+"/jobs/"+jid, null, token);
try {
//info array will tell us how many minions were targeted
returnArray = httpResponse.getJSONArray("info");
for (Object o : returnArray ) {
JSONObject line = (JSONObject) o;
JSONArray minionsArray = line.getJSONArray("Minions");
//Check the info[Minions[]] array to see how many nodes we expect to hear back from
numMinions = minionsArray.size();
listener.getLogger().println("Waiting for " + numMinions + " minions");
}
returnArray = httpResponse.getJSONArray("return");
//Check the return[] array to see how many minions have responded
if (!returnArray.getJSONObject(0).names().isEmpty()) {
numMinionsDone = returnArray.getJSONObject(0).names().size();
} else {
numMinionsDone = 0;
}
listener.getLogger().println(numMinionsDone + " minions are done");
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+servername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
return false;
}
//Now that we know how many minions have responded, and how many we are waiting on. Let's see more have finished
if (numMinionsDone < numMinions) {
//Don't print annying messages unless we really are waiting for more minions to return
listener.getLogger().println("Will check status every "+String.valueOf(myJobPollTime)+" seconds...");
}
while (numMinionsDone < numMinions) {
try {
Thread.sleep(myJobPollTime*1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
//Allow user to cancel job in jenkins interface
listener.getLogger().println("Cancelling job");
return false;
}
httpResponse = Utils.getJSON(servername+"/jobs/"+jid, null, token);
try {
returnArray = httpResponse.getJSONArray("return");
numMinionsDone = returnArray.getJSONObject(0).names().size();
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2).split("\\\\n")[0]);
return false;
}
}
if (returnArray.get(0).toString().contains("TypeError")) {
listener.getLogger().println("Salt reported an error for "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
return false;
}
//Loop is done. We have heard back from everybody. Good work team!
listener.getLogger().println("Response on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
} else {
//Just send a salt request. Don't wait for reply
httpResponse = Utils.getJSON(servername, saltArray, token);
try {
if (!httpResponse.getJSONArray("return").isArray()) {
//Print problem
listener.getLogger().println("Problem on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
return false;
}
} catch (Exception e) {
listener.getLogger().println("Problem with "+myfunction+" "+myarguments+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2).split("\\\\n")[0]);
return false;
}
//valide return
if (httpResponse.toString().contains("TypeError")) {
listener.getLogger().println("Salt reported an error on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
return false;
} else {
listener.getLogger().println("Response on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
}
}
//No fail condition reached. Must be good.
return true;
}
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
private int pollTime=10;
private boolean saltMessageDebug;
public DescriptorImpl() {
load();
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
try {
//Test that value entered in config is an integer
pollTime = formData.getInt("pollTime");
} catch (Exception e) {
//Fall back to default
pollTime = 10;
}
saltMessageDebug = formData.getBoolean("saltMessageDebug");
save();
return super.configure(req,formData);
}
public int getPollTime() {
return pollTime;
}
public boolean getSaltMessageDebug() {
return saltMessageDebug;
}
public FormValidation doTestConnection(@QueryParameter("servername") final String servername,
@QueryParameter("username") final String username,
@QueryParameter("userpass") final String userpass,
@QueryParameter("authtype") final String authtype)
throws IOException, ServletException {
JSONObject httpResponse = new JSONObject();
JSONArray authArray = new JSONArray();
JSONObject auth = new JSONObject();
auth.put("username", username);
auth.put("password", userpass);
auth.put("eauth", authtype);
authArray.add(auth);
String token = Utils.getToken(servername, authArray);
if (token.contains("Error")) {
return FormValidation.error("Client error : "+token);
} else {
return FormValidation.ok("Success");
}
}
public FormValidation doCheckServername(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a name");
if (value.length() < 10)
return FormValidation.warning("Isn't the name too short?");
if (!value.contains("https://") && !value.contains("http://"))
return FormValidation.warning("Missing protocol: Servername should be in the format https://host.domain:8000");
if (!value.substring(7).contains(":"))
return FormValidation.warning("Missing port: Servername should be in the format https://host.domain:8000");
return FormValidation.ok();
}
public FormValidation doCheckUsername(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a name");
if (value.length() < 3)
return FormValidation.warning("Isn't the name too short?");
return FormValidation.ok();
}
public FormValidation doCheckUserpass(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a password");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckTarget(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a salt target");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckFunction(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a salt function");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckPollTime(@QueryParameter String value)
throws IOException, ServletException {
try {
Integer.parseInt(value);
} catch(NumberFormatException e) {
return FormValidation.error("Specify a number larger than 3");
}
if (Integer.parseInt(value) < 3)
return FormValidation.warning("Specify a number larger than 3");
return FormValidation.ok();
}
public FormValidation doCheckBatchSize(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify batch size");
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Send a message to Salt API";
}
}
}
| src/main/java/com/waytta/SaltAPIBuilder.java | package com.waytta;
import hudson.Launcher;
import hudson.Extension;
import hudson.util.FormValidation;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.AbstractProject;
import hudson.tasks.Builder;
import hudson.tasks.BuildStepDescriptor;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import net.sf.json.JSONArray;
import net.sf.json.util.JSONUtils;
import net.sf.json.JSONSerializer;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
public class SaltAPIBuilder extends Builder {
private final String servername;
private final String username;
private final String userpass;
private final String authtype;
private final String target;
private final String targettype;
private final String function;
private final String arguments;
private final String kwarguments;
private final JSONObject clientInterfaces;
private final String clientInterface;
private final Boolean blockbuild;
private final Integer jobPollTime;
private final String batchSize;
private final String mods;
private final Boolean usePillar;
private final String pillarkey;
private final String pillarvalue;
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public SaltAPIBuilder(String servername, String username, String userpass, String authtype, String target, String targettype, String function, String arguments, String kwarguments, JSONObject clientInterfaces, Integer jobPollTime, String mods, String pillarkey, String pillarvalue) {
this.servername = servername;
this.username = username;
this.userpass = userpass;
this.authtype = authtype;
this.target = target;
this.targettype = targettype;
this.function = function;
this.arguments = arguments;
this.kwarguments = kwarguments;
this.clientInterfaces = clientInterfaces;
if (clientInterfaces.has("clientInterface")) {
this.clientInterface = clientInterfaces.get("clientInterface").toString();
} else {
this.clientInterface = "local";
}
if (clientInterface.equals("local")) {
this.blockbuild = clientInterfaces.getBoolean("blockbuild");
this.jobPollTime = clientInterfaces.getInt("jobPollTime");
this.batchSize = "100%";
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
} else if (clientInterface.equals("local_batch")) {
this.batchSize = clientInterfaces.get("batchSize").toString();
this.blockbuild = false;
this.jobPollTime = 10;
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
} else if (clientInterface.equals("runner")) {
this.mods = clientInterfaces.get("mods").toString();
if (clientInterfaces.has("usePillar")) {
this.usePillar = true;
this.pillarkey = clientInterfaces.getJSONObject("usePillar").get("pillarkey").toString();
this.pillarvalue = clientInterfaces.getJSONObject("usePillar").get("pillarvalue").toString();
} else {
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
}
this.blockbuild = false;
this.jobPollTime = 10;
this.batchSize = "100%";
} else {
this.batchSize = "100%";
this.blockbuild = false;
this.jobPollTime = 10;
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
}
}
/*
* We'll use this from the <tt>config.jelly</tt>.
*/
public String getServername() {
return servername;
}
public String getUsername() {
return username;
}
public String getUserpass() {
return userpass;
}
public String getAuthtype() {
return authtype;
}
public String getTarget() {
return target;
}
public String getTargettype() {
return this.targettype;
}
public String getFunction() {
return function;
}
public String getArguments() {
return arguments;
}
public String getKwarguments() {
return kwarguments;
}
public String getClientInterface() {
return clientInterface;
}
public Boolean getBlockbuild() {
return blockbuild;
}
public String getBatchSize() {
return batchSize;
}
public Integer getJobPollTime() {
return jobPollTime;
}
public String getMods() {
return mods;
}
public Boolean getUsePillar() {
return usePillar;
}
public String getPillarkey() {
return pillarkey;
}
public String getPillarvalue() {
return pillarvalue;
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
// This is where you 'build' the project.
// If not not configured, grab the default
int myJobPollTime = 10;
if (jobPollTime == null) {
myJobPollTime = getDescriptor().getPollTime();
} else {
myJobPollTime = jobPollTime;
}
Boolean mySaltMessageDebug = getDescriptor().getSaltMessageDebug();
String myClientInterface = clientInterface;
String mytarget = target;
String myfunction = function;
String myarguments = arguments;
String mykwarguments = kwarguments;
Boolean myBlockBuild = blockbuild;
//listener.getLogger().println("Salt Arguments before: "+myarguments);
mytarget = Utils.paramorize(build, listener, target);
myfunction = Utils.paramorize(build, listener, function);
myarguments = Utils.paramorize(build, listener, arguments);
mykwarguments = Utils.paramorize(build, listener, kwarguments);
//listener.getLogger().println("Salt Arguments after: "+myarguments);
//Setup connection for auth
String token = new String();
JSONObject auth = new JSONObject();
auth.put("username", username);
auth.put("password", userpass);
auth.put("eauth", authtype);
JSONArray authArray = new JSONArray();
authArray.add(auth);
//listener.getLogger().println("Sending auth: "+authArray.toString());
JSONObject httpResponse = new JSONObject();
//Get an auth token
token = Utils.getToken(servername, authArray);
if (token.contains("Error")) {
listener.getLogger().println(token);
return false;
}
//If we got this far, auth must have been pretty good and we've got a token
JSONArray saltArray = new JSONArray();
JSONObject saltFunc = new JSONObject();
// Hardcode clientInterface if not yet set. Once constructor runs, this will not be necessary
if (myClientInterface == null) {
myClientInterface = "local";
}
saltFunc.put("client", myClientInterface);
if (myClientInterface.equals("local_batch")) {
saltFunc.put("batch", batchSize);
listener.getLogger().println("Running in batch mode. Batch size: "+batchSize);
myBlockBuild = true;
}
if (myClientInterface.equals("runner")) {
saltFunc.put("mods", mods);
if (usePillar) {
String myPillarkey = Utils.paramorize(build, listener, pillarkey);
String myPillarvalue = Utils.paramorize(build, listener, pillarvalue);
JSONObject jPillar = new JSONObject();
jPillar.put(JSONUtils.stripQuotes(myPillarkey), JSONUtils.stripQuotes(myPillarvalue));
saltFunc.put("pillar", jPillar);
}
}
saltFunc.put("tgt", mytarget);
saltFunc.put("expr_form", targettype);
saltFunc.put("fun", myfunction);
if (myarguments.length() > 0){
List saltArguments = new ArrayList();
//spit on comma seperated not inside of quotes
String[] argItems = myarguments.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (String arg : argItems) {
//remove spaces at begining or end
arg = arg.replaceAll("^\\s+|\\s+$", "");
arg = arg.replaceAll("\"|\\\"", "");
saltArguments.add(arg);
}
//Add any args to json message
saltFunc.element("arg", saltArguments);
}
if (mykwarguments.length() > 0){
Map kwArgs = new HashMap();
//spit on comma seperated not inside of quotes
String[] kwargItems = mykwarguments.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (String kwarg : kwargItems) {
//remove spaces at begining or end
kwarg = kwarg.replaceAll("^\\s+|\\s+$", "");
kwarg = kwarg.replaceAll("\"|\\\"", "");
if (kwarg.contains("=")) {
String[] kwString = kwarg.split("=");
if (kwString.length > 2){
//kwarg contained more than one =. Let's put the string back together
String kwFull = new String();
for (String kwItem : kwString){
//Ignore the first item as it will remain the key
if ( kwItem == kwString[0] ) continue;
//add the second item
if ( kwItem == kwString[1] ) {
kwFull += kwItem;
continue;
}
//add all other items with an = to rejoin
kwFull += "="+kwItem;
}
kwArgs.put(kwString[0], kwFull);
} else {
kwArgs.put(kwString[0], kwString[1]);
}
}
}
//Add any kwargs to json message
saltFunc.element("kwarg", kwArgs);
}
saltArray.add(saltFunc);
if (mySaltMessageDebug) {
listener.getLogger().println("Sending JSON: "+saltArray.toString());
}
if (myBlockBuild == null) {
//Set a sane default if uninitialized
myBlockBuild = false;
}
//blocking request
if (myBlockBuild) {
String jid = new String();
//Send request to /minion url. This will give back a jid which we will need to poll and lookup for completion
httpResponse = Utils.getJSON(servername+"/minions", saltArray, token);
try {
JSONArray returnArray = httpResponse.getJSONArray("return");
for (Object o : returnArray ) {
JSONObject line = (JSONObject) o;
jid = line.getString("jid");
}
//Print out success
listener.getLogger().println("Running jid: " + jid);
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+servername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
return false;
}
//Request successfully sent. Now use jid to check if job complete
int numMinions = 0;
int numMinionsDone = 0;
JSONArray returnArray = new JSONArray();
httpResponse = Utils.getJSON(servername+"/jobs/"+jid, null, token);
try {
//info array will tell us how many minions were targeted
returnArray = httpResponse.getJSONArray("info");
for (Object o : returnArray ) {
JSONObject line = (JSONObject) o;
JSONArray minionsArray = line.getJSONArray("Minions");
//Check the info[Minions[]] array to see how many nodes we expect to hear back from
numMinions = minionsArray.size();
listener.getLogger().println("Waiting for " + numMinions + " minions");
}
returnArray = httpResponse.getJSONArray("return");
//Check the return[] array to see how many minions have responded
if (!returnArray.getJSONObject(0).names().isEmpty()) {
numMinionsDone = returnArray.getJSONObject(0).names().size();
} else {
numMinionsDone = 0;
}
listener.getLogger().println(numMinionsDone + " minions are done");
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+servername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
return false;
}
//Now that we know how many minions have responded, and how many we are waiting on. Let's see more have finished
if (numMinionsDone < numMinions) {
//Don't print annying messages unless we really are waiting for more minions to return
listener.getLogger().println("Will check status every "+String.valueOf(myJobPollTime)+" seconds...");
}
while (numMinionsDone < numMinions) {
try {
Thread.sleep(myJobPollTime*1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
//Allow user to cancel job in jenkins interface
listener.getLogger().println("Cancelling job");
return false;
}
httpResponse = Utils.getJSON(servername+"/jobs/"+jid, null, token);
try {
returnArray = httpResponse.getJSONArray("return");
numMinionsDone = returnArray.getJSONObject(0).names().size();
if (myClientInterface.equals("local_batch")) {
listener.getLogger().println("Minions finished: " + numMinionsDone);
listener.getLogger().println(returnArray.toString(2));
}
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2).split("\\\\n")[0]);
return false;
}
}
if (returnArray.get(0).toString().contains("TypeError")) {
listener.getLogger().println("Salt reported an error for "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
return false;
}
//Loop is done. We have heard back from everybody. Good work team!
listener.getLogger().println("Response on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
} else {
//Just send a salt request. Don't wait for reply
httpResponse = Utils.getJSON(servername, saltArray, token);
try {
if (!httpResponse.getJSONArray("return").isArray()) {
//Print problem
listener.getLogger().println("Problem on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
return false;
}
} catch (Exception e) {
listener.getLogger().println("Problem with "+myfunction+" "+myarguments+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2).split("\\\\n")[0]);
return false;
}
//valide return
if (httpResponse.toString().contains("TypeError")) {
listener.getLogger().println("Salt reported an error on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
return false;
} else {
listener.getLogger().println("Response on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
}
}
//No fail condition reached. Must be good.
return true;
}
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
private int pollTime=10;
private boolean saltMessageDebug;
public DescriptorImpl() {
load();
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
try {
//Test that value entered in config is an integer
pollTime = formData.getInt("pollTime");
} catch (Exception e) {
//Fall back to default
pollTime = 10;
}
saltMessageDebug = formData.getBoolean("saltMessageDebug");
save();
return super.configure(req,formData);
}
public int getPollTime() {
return pollTime;
}
public boolean getSaltMessageDebug() {
return saltMessageDebug;
}
public FormValidation doTestConnection(@QueryParameter("servername") final String servername,
@QueryParameter("username") final String username,
@QueryParameter("userpass") final String userpass,
@QueryParameter("authtype") final String authtype)
throws IOException, ServletException {
JSONObject httpResponse = new JSONObject();
JSONArray authArray = new JSONArray();
JSONObject auth = new JSONObject();
auth.put("username", username);
auth.put("password", userpass);
auth.put("eauth", authtype);
authArray.add(auth);
String token = Utils.getToken(servername, authArray);
if (token.contains("Error")) {
return FormValidation.error("Client error : "+token);
} else {
return FormValidation.ok("Success");
}
}
public FormValidation doCheckServername(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a name");
if (value.length() < 10)
return FormValidation.warning("Isn't the name too short?");
if (!value.contains("https://") && !value.contains("http://"))
return FormValidation.warning("Missing protocol: Servername should be in the format https://host.domain:8000");
if (!value.substring(7).contains(":"))
return FormValidation.warning("Missing port: Servername should be in the format https://host.domain:8000");
return FormValidation.ok();
}
public FormValidation doCheckUsername(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a name");
if (value.length() < 3)
return FormValidation.warning("Isn't the name too short?");
return FormValidation.ok();
}
public FormValidation doCheckUserpass(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a password");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckTarget(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a salt target");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckFunction(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a salt function");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckPollTime(@QueryParameter String value)
throws IOException, ServletException {
try {
Integer.parseInt(value);
} catch(NumberFormatException e) {
return FormValidation.error("Specify a number larger than 3");
}
if (Integer.parseInt(value) < 3)
return FormValidation.warning("Specify a number larger than 3");
return FormValidation.ok();
}
public FormValidation doCheckBatchSize(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify batch size");
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Send a message to Salt API";
}
}
}
| local_batch operations should be send to root endpoint and not /minions
| src/main/java/com/waytta/SaltAPIBuilder.java | local_batch operations should be send to root endpoint and not /minions | <ide><path>rc/main/java/com/waytta/SaltAPIBuilder.java
<ide> if (myClientInterface.equals("local_batch")) {
<ide> saltFunc.put("batch", batchSize);
<ide> listener.getLogger().println("Running in batch mode. Batch size: "+batchSize);
<del> myBlockBuild = true;
<ide> }
<ide> if (myClientInterface.equals("runner")) {
<ide> saltFunc.put("mods", mods);
<ide> try {
<ide> returnArray = httpResponse.getJSONArray("return");
<ide> numMinionsDone = returnArray.getJSONObject(0).names().size();
<del> if (myClientInterface.equals("local_batch")) {
<del> listener.getLogger().println("Minions finished: " + numMinionsDone);
<del> listener.getLogger().println(returnArray.toString(2));
<del> }
<ide> } catch (Exception e) {
<ide> listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2).split("\\\\n")[0]);
<ide> return false; |
|
Java | bsd-3-clause | 180cd39dc8ddd1ed337fd8cecad8545905ae77b6 | 0 | messagebird/java-rest-api | package com.messagebird;
import com.messagebird.exceptions.GeneralException;
import com.messagebird.exceptions.NotFoundException;
import com.messagebird.exceptions.UnauthorizedException;
import com.messagebird.objects.Balance;
import com.messagebird.objects.Contact;
import com.messagebird.objects.ContactList;
import com.messagebird.objects.ContactRequest;
import com.messagebird.objects.ErrorReport;
import com.messagebird.objects.Group;
import com.messagebird.objects.GroupList;
import com.messagebird.objects.GroupRequest;
import com.messagebird.objects.Hlr;
import com.messagebird.objects.Lookup;
import com.messagebird.objects.LookupHlr;
import com.messagebird.objects.Message;
import com.messagebird.objects.MessageList;
import com.messagebird.objects.MessageResponse;
import com.messagebird.objects.MsgType;
import com.messagebird.objects.PagedPaging;
import com.messagebird.objects.PhoneNumber;
import com.messagebird.objects.PhoneNumbersLookup;
import com.messagebird.objects.PhoneNumbersResponse;
import com.messagebird.objects.PurchasedPhoneNumber;
import com.messagebird.objects.Verify;
import com.messagebird.objects.VerifyRequest;
import com.messagebird.objects.VoiceMessage;
import com.messagebird.objects.VoiceMessageList;
import com.messagebird.objects.VoiceMessageResponse;
import com.messagebird.objects.conversations.Conversation;
import com.messagebird.objects.conversations.ConversationList;
import com.messagebird.objects.conversations.ConversationMessage;
import com.messagebird.objects.conversations.ConversationMessageList;
import com.messagebird.objects.conversations.ConversationMessageRequest;
import com.messagebird.objects.conversations.ConversationStartRequest;
import com.messagebird.objects.conversations.ConversationStatus;
import com.messagebird.objects.conversations.ConversationWebhook;
import com.messagebird.objects.conversations.ConversationWebhookCreateRequest;
import com.messagebird.objects.conversations.ConversationWebhookList;
import com.messagebird.objects.conversations.ConversationWebhookUpdateRequest;
import com.messagebird.objects.voicecalls.RecordingResponse;
import com.messagebird.objects.voicecalls.TranscriptionResponse;
import com.messagebird.objects.voicecalls.VoiceCall;
import com.messagebird.objects.voicecalls.VoiceCallFlowList;
import com.messagebird.objects.voicecalls.VoiceCallFlowRequest;
import com.messagebird.objects.voicecalls.VoiceCallFlowResponse;
import com.messagebird.objects.voicecalls.VoiceCallLeg;
import com.messagebird.objects.voicecalls.VoiceCallLegResponse;
import com.messagebird.objects.voicecalls.VoiceCallResponse;
import com.messagebird.objects.voicecalls.VoiceCallResponseList;
import com.messagebird.objects.voicecalls.Webhook;
import com.messagebird.objects.voicecalls.WebhookList;
import com.messagebird.objects.voicecalls.WebhookResponseData;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Message bird general client
* <p>
* <pre>
* Initialise this class with a MessageBirdService
* // First create your service object
* MessageBirdService wsr = new MessageBirdServiceImpl(args[0]);
* // Add the service to the client
* MessageBirdClient messageBirdClient = new MessageBirdClient(wsr);
*
* Then read your balance like this:
* final Balance balance = messageBirdClient.getBalance();
* </pre>
* <p>
* Created by rvt on 1/5/15.
*/
public class MessageBirdClient {
/**
* The Conversations API has a different URL scheme from the other
* APIs/endpoints. By default, the service prefixes paths with that URL. We
* can, however, override this behaviour by providing absolute URLs
* ourselves.
*/
private static final String BASE_URL_CONVERSATIONS = "https://conversations.messagebird.com/v1";
private static final String BASE_URL_CONVERSATIONS_WHATSAPP_SANDBOX = "https://whatsapp-sandbox.messagebird.com/v1";
static final String VOICE_CALLS_BASE_URL = "https://voice.messagebird.com";
static final String NUMBERS_CALLS_BASE_URL = "https://numbers.messagebird.com";
private static String[] supportedLanguages = {"de-DE", "en-AU", "en-UK", "en-US", "es-ES", "es-LA", "fr-FR", "it-IT", "nl-NL", "pt-BR"};
private static final String BALANCEPATH = "/balance";
private static final String CONTACTPATH = "/contacts";
private static final String GROUPPATH = "/groups";
private static final String HLRPATH = "/hlr";
private static final String LOOKUPHLRPATH = "/lookup/%s/hlr";
private static final String LOOKUPPATH = "/lookup";
private static final String MESSAGESPATH = "/messages";
private static final String VERIFYPATH = "/verify";
private static final String VOICEMESSAGESPATH = "/voicemessages";
private static final String CONVERSATION_PATH = "/conversations";
private static final String CONVERSATION_MESSAGE_PATH = "/messages";
private static final String CONVERSATION_WEBHOOK_PATH = "/webhooks";
static final String VOICECALLSPATH = "/calls";
static final String LEGSPATH = "/legs";
static final String RECORDINGPATH = "/recordings";
static final String TRANSCRIPTIONPATH = "/transcriptions";
static final String WEBHOOKS = "/webhooks";
static final String VOICECALLFLOWPATH = "/call-flows";
private static final String VOICELEGS_SUFFIX_PATH = "/legs";
static final String RECORDING_DOWNLOAD_FORMAT = ".wav";
static final String TRANSCRIPTION_DOWNLOAD_FORMAT = ".txt";
private static final int DEFAULT_MACHINE_TIMEOUT_VALUE = 7000;
private static final int MIN_MACHINE_TIMEOUT_VALUE = 400;
private static final int MAX_MACHINE_TIMEOUT_VALUE = 10000;
private final String DOWNLOADS = "Downloads";
private MessageBirdService messageBirdService;
private String conversationsBaseUrl;
public enum Feature {
ENABLE_CONVERSATION_API_WHATSAPP_SANDBOX
}
public MessageBirdClient(final MessageBirdService messageBirdService) {
this.messageBirdService = messageBirdService;
this.conversationsBaseUrl = BASE_URL_CONVERSATIONS;
}
public MessageBirdClient(final MessageBirdService messageBirdService, List<Feature> features) {
this(messageBirdService);
if(features.indexOf(Feature.ENABLE_CONVERSATION_API_WHATSAPP_SANDBOX) >= 0) {
this.conversationsBaseUrl = BASE_URL_CONVERSATIONS_WHATSAPP_SANDBOX;
}
}
/****************************************************************************************************/
/** Balance and HRL methods **/
/****************************************************************************************************/
/**
* MessageBird provides an API to get the balance information of your account.
*
* @return Balance object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Balance getBalance() throws GeneralException, UnauthorizedException, NotFoundException {
return messageBirdService.requestByID(BALANCEPATH, "", Balance.class);
}
/**
* MessageBird provides an API to send Network Queries to any mobile number across the world.
* An HLR allows you to view which mobile number (MSISDN) belongs to what operator in real time and see whether the number is active.
*
* @param msisdn The telephone number.
* @param reference A client reference
* @return Hlr Object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Hlr getRequestHlr(final BigInteger msisdn, final String reference) throws GeneralException, UnauthorizedException {
if (msisdn == null) {
throw new IllegalArgumentException("msisdn must be specified.");
}
if (reference == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("msisdn", msisdn);
payload.put("reference", reference);
return messageBirdService.sendPayLoad(HLRPATH, payload, Hlr.class);
}
/**
* Retrieves the information of an existing HLR. You only need to supply the unique message id that was returned upon creation or receiving.
*
* @param hlrId ID as returned by getRequestHlr in the id variable
* @return Hlr Object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Hlr getViewHlr(final String hlrId) throws GeneralException, UnauthorizedException, NotFoundException {
if (hlrId == null) {
throw new IllegalArgumentException("Hrl ID must be specified.");
}
return messageBirdService.requestByID(HLRPATH, hlrId, Hlr.class);
}
/****************************************************************************************************/
/** Messaging **/
/****************************************************************************************************/
/**
* Send a message through the messagebird platform
*
* @param message Message object to be send
* @return Message Response
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendMessage(final Message message) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(MESSAGESPATH, new Message(originator, body, recipients), MessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @param reference your reference
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException {
final Message message = new Message(originator, body, recipients);
message.setReference(reference);
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
/**
* Convenient function to send a simple flash message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException {
final Message message = new Message(originator, body, recipients);
message.setType(MsgType.flash);
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
/**
* Convenient function to send a simple flash message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @param reference your reference
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException {
final Message message = new Message(originator, body, recipients);
message.setType(MsgType.flash);
message.setReference(reference);
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
public MessageList listMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
return messageBirdService.requestList(MESSAGESPATH, offset, limit, MessageList.class);
}
/**
* Delete a message from the Messagebird server
*
* @param id A unique random ID which is created on the MessageBird platform
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Message ID must be specified.");
}
messageBirdService.deleteByID(MESSAGESPATH, id);
}
/**
* View a message from the Messagebird server
*
* @param id A unique random ID which is created on the MessageBird platform
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse viewMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Message ID must be specified.");
}
return messageBirdService.requestByID(MESSAGESPATH, id, MessageResponse.class);
}
/****************************************************************************************************/
/** Voice Messaging **/
/****************************************************************************************************/
/**
* Convenient function to send a simple message to a list of recipients
*
* @param voiceMessage Voice message object
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse sendVoiceMessage(final VoiceMessage voiceMessage) throws UnauthorizedException, GeneralException {
addDefaultMachineTimeoutValueIfNotExists(voiceMessage);
checkMachineTimeoutValueIsInRange(voiceMessage);
return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, voiceMessage, VoiceMessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param body Body of the message
* @param recipients List of recipients
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException {
final VoiceMessage message = new VoiceMessage(body, recipients);
addDefaultMachineTimeoutValueIfNotExists(message);
checkMachineTimeoutValueIsInRange(message);
return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param body Body of the message
* @param recipients List of recipients
* @param reference your reference
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException {
final VoiceMessage message = new VoiceMessage(body, recipients);
message.setReference(reference);
addDefaultMachineTimeoutValueIfNotExists(message);
checkMachineTimeoutValueIsInRange(message);
return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class);
}
private void addDefaultMachineTimeoutValueIfNotExists(final VoiceMessage voiceMessage){
if (voiceMessage.getMachineTimeout() == 0){
voiceMessage.setMachineTimeout(DEFAULT_MACHINE_TIMEOUT_VALUE); //default machine timeout value
}
}
private void checkMachineTimeoutValueIsInRange(final VoiceMessage voiceMessage){
if (voiceMessage.getMachineTimeout() < MIN_MACHINE_TIMEOUT_VALUE || voiceMessage.getMachineTimeout() > MAX_MACHINE_TIMEOUT_VALUE){
throw new IllegalArgumentException("Please define machine timeout value between " + MIN_MACHINE_TIMEOUT_VALUE + " and " + MAX_MACHINE_TIMEOUT_VALUE);
}
}
/**
* Delete a voice message from the Messagebird server
*
* @param id A unique random ID which is created on the MessageBird platform
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Message ID must be specified.");
}
messageBirdService.deleteByID(VOICEMESSAGESPATH, id);
}
/**
* View a message from the Messagebird server
*
* @param id A unique random ID which is created on the MessageBird platform
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse viewVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Voice Message ID must be specified.");
}
return messageBirdService.requestByID(VOICEMESSAGESPATH, id, VoiceMessageResponse.class);
}
/**
* List voice messages
*
* @param offset offset for result list
* @param limit limit for result list
* @return VoiceMessageList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageList listVoiceMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
return messageBirdService.requestList(VOICEMESSAGESPATH, offset, limit, VoiceMessageList.class);
}
/**
* @param verifyRequest includes recipient, originator, reference, type, datacoding, template, timeout, tokenLenght, voice, language
* @return Verify object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Verify sendVerifyToken(VerifyRequest verifyRequest) throws UnauthorizedException, GeneralException {
if (verifyRequest == null) {
throw new IllegalArgumentException("Verify request cannot be null");
} else if (verifyRequest.getRecipient() == null || verifyRequest.getRecipient().isEmpty()) {
throw new IllegalArgumentException("Recipient cannot be empty for verify");
}
return messageBirdService.sendPayLoad(VERIFYPATH, verifyRequest, Verify.class);
}
/**
* @param recipient The telephone number that you want to verify.
* @return Verify object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Verify sendVerifyToken(String recipient) throws UnauthorizedException, GeneralException {
if (recipient == null || recipient.isEmpty()) {
throw new IllegalArgumentException("Recipient cannot be empty for verify");
}
VerifyRequest verifyRequest = new VerifyRequest(recipient);
return this.sendVerifyToken(verifyRequest);
}
/**
* @param id A unique random ID which is created on the MessageBird platform
* @param token An unique token which was sent to the recipient upon creation of the object.
* @return Verify object
* @throws NotFoundException if id is not found
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Verify verifyToken(String id, String token) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
} else if (token == null || token.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("token", token);
return messageBirdService.requestByID(VERIFYPATH, id, params, Verify.class);
}
/**
* @param id id is for getting verify object
* @return Verify object
* @throws NotFoundException if id is not found
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
Verify getVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
}
return messageBirdService.requestByID(VERIFYPATH, id, Verify.class);
}
/**
* @param id id for deleting verify object
* @throws NotFoundException if id is not found
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
}
messageBirdService.deleteByID(VERIFYPATH, id);
}
/**
* Send a Lookup request
*
* @param lookup including with country code, country prefix, phone number, type, formats, country code
* @return Lookup
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException if lookup not found
*/
public Lookup viewLookup(final Lookup lookup) throws UnauthorizedException, GeneralException, NotFoundException {
if (lookup.getPhoneNumber() == null) {
throw new IllegalArgumentException("PhoneNumber must be specified.");
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
if (lookup.getCountryCode() != null) {
params.put("countryCode", lookup.getCountryCode());
}
return messageBirdService.requestByID(LOOKUPPATH, String.valueOf(lookup.getPhoneNumber()), params, Lookup.class);
}
/**
* Send a Lookup request
*
* @param phoneNumber phone number is for viewing lookup
* @return Lookup
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Lookup viewLookup(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException {
if (phoneNumber == null) {
throw new IllegalArgumentException("PhoneNumber must be specified.");
}
final Lookup lookup = new Lookup(phoneNumber);
return this.viewLookup(lookup);
}
/**
* Request a Lookup HLR (lookup)
*
* @param lookupHlr country code for request lookup hlr
* @return lookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public LookupHlr requestLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException {
if (lookupHlr.getPhoneNumber() == null) {
throw new IllegalArgumentException("PhoneNumber must be specified.");
}
if (lookupHlr.getReference() == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("phoneNumber", lookupHlr.getPhoneNumber());
payload.put("reference", lookupHlr.getReference());
if (lookupHlr.getCountryCode() != null) {
payload.put("countryCode", lookupHlr.getCountryCode());
}
return messageBirdService.sendPayLoad(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), payload, LookupHlr.class);
}
/**
* Request a Lookup HLR (lookup)
*
* @param phoneNumber phone number is for request hlr
* @param reference reference for request hlr
* @return lookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public LookupHlr requestLookupHlr(final BigInteger phoneNumber, final String reference) throws UnauthorizedException, GeneralException {
if (phoneNumber == null) {
throw new IllegalArgumentException("Phonenumber must be specified.");
}
if (reference == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final LookupHlr lookupHlr = new LookupHlr();
lookupHlr.setPhoneNumber(phoneNumber);
lookupHlr.setReference(reference);
return this.requestLookupHlr(lookupHlr);
}
/**
* View a Lookup HLR (lookup)
*
* @param lookupHlr search with country code
* @return LookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException if there is no lookup hlr with given country code
*/
public LookupHlr viewLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException, NotFoundException {
if (lookupHlr.getPhoneNumber() == null) {
throw new IllegalArgumentException("Phonenumber must be specified");
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
if (lookupHlr.getCountryCode() != null) {
params.put("countryCode", lookupHlr.getCountryCode());
}
return messageBirdService.requestByID(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), "", params, LookupHlr.class);
}
/**
* View a Lookup HLR (lookup)
*
* @param phoneNumber phone number for searching on hlr
* @return LookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException phone number not found on hlr
*/
public LookupHlr viewLookupHlr(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException {
if (phoneNumber == null) {
throw new IllegalArgumentException("phoneNumber must be specified");
}
final LookupHlr lookupHlr = new LookupHlr();
lookupHlr.setPhoneNumber(phoneNumber);
return this.viewLookupHlr(lookupHlr);
}
/**
* Convenient function to list all call flows
*
* @param offset
* @param limit
* @return VoiceCallFlowList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallFlowList listVoiceCallFlows(final Integer offset, final Integer limit)
throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
return messageBirdService.requestList(url, offset, limit, VoiceCallFlowList.class);
}
/**
* Retrieves the information of an existing Call Flow. You only need to supply
* the unique call flow ID that was returned upon creation or receiving.
* @param id String
* @return VoiceCallFlowResponse
* @throws NotFoundException
* @throws GeneralException
* @throws UnauthorizedException
*/
public VoiceCallFlowResponse viewVoiceCallFlow(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Call Flow ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
return messageBirdService.requestByID(url, id, VoiceCallFlowResponse.class);
}
/**
* Convenient function to create a call flow
*
* @param voiceCallFlowRequest VoiceCallFlowRequest
* @return VoiceCallFlowResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallFlowResponse sendVoiceCallFlow(final VoiceCallFlowRequest voiceCallFlowRequest)
throws UnauthorizedException, GeneralException {
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
return messageBirdService.sendPayLoad(url, voiceCallFlowRequest, VoiceCallFlowResponse.class);
}
/**
* Updates an existing Call Flow. You only need to supply the unique id that
* was returned upon creation.
* @param id String
* @param voiceCallFlowRequest VoiceCallFlowRequest
* @return VoiceCallFlowResponse
* @throws UnauthorizedException
* @throws GeneralException
*/
public VoiceCallFlowResponse updateVoiceCallFlow(String id, VoiceCallFlowRequest voiceCallFlowRequest)
throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Call Flow ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
String request = url + "/" + id;
return messageBirdService.sendPayLoad("PUT", request, voiceCallFlowRequest, VoiceCallFlowResponse.class);
}
/**
* Convenient function to delete call flow
*
* @param id String
* @return void
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVoiceCallFlow(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Voice Call Flow ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
messageBirdService.deleteByID(url, id);
}
/**
* Deletes an existing contact. You only need to supply the unique id that
* was returned upon creation.
*/
void deleteContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
messageBirdService.deleteByID(CONTACTPATH, id);
}
/**
* Gets a contact listing with specified pagination options.
*
* @return Listing of Contact objects.
*/
public ContactList listContacts(int offset, int limit) throws UnauthorizedException, GeneralException {
return messageBirdService.requestList(CONTACTPATH, offset, limit, ContactList.class);
}
/**
* Gets a contact listing with default pagination options.
*/
public ContactList listContacts() throws UnauthorizedException, GeneralException {
final int limit = 20;
final int offset = 0;
return listContacts(offset, limit);
}
/**
* Creates a new contact object. MessageBird returns the created contact
* object with each request.
*/
public Contact sendContact(final ContactRequest contactRequest) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(CONTACTPATH, contactRequest, Contact.class);
}
/**
* Updates an existing contact. You only need to supply the unique id that
* was returned upon creation.
*/
public Contact updateContact(final String id, ContactRequest contactRequest) throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
String request = CONTACTPATH + "/" + id;
return messageBirdService.sendPayLoad("PATCH", request, contactRequest, Contact.class);
}
/**
* Retrieves the information of an existing contact. You only need to supply
* the unique contact ID that was returned upon creation or receiving.
*/
public Contact viewContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
return messageBirdService.requestByID(CONTACTPATH, id, Contact.class);
}
/**
* Deletes an existing group. You only need to supply the unique id that
* was returned upon creation.
*/
public void deleteGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
messageBirdService.deleteByID(GROUPPATH, id);
}
/**
* Removes a contact from group. You need to supply the IDs of the group
* and contact. Does not delete the contact.
*/
public void deleteGroupContact(final String groupId, final String contactId) throws NotFoundException, GeneralException, UnauthorizedException {
if (groupId == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
if (contactId == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
String id = String.format("%s%s/%s", groupId, CONTACTPATH, contactId);
messageBirdService.deleteByID(GROUPPATH, id);
}
/**
* Gets a contact listing with specified pagination options.
*/
public GroupList listGroups(final int offset, final int limit) throws UnauthorizedException, GeneralException {
return messageBirdService.requestList(GROUPPATH, offset, limit, GroupList.class);
}
/**
* Gets a contact listing with default pagination options.
*/
public GroupList listGroups() throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 20;
return listGroups(offset, limit);
}
/**
* Creates a new group object. MessageBird returns the created group object
* with each request.
*/
public Group sendGroup(final GroupRequest groupRequest) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(GROUPPATH, groupRequest, Group.class);
}
/**
* Adds contact to group. You need to supply the IDs of the group and
* contact.
*/
public void sendGroupContact(final String groupId, final String[] contactIds) throws NotFoundException, GeneralException, UnauthorizedException {
// reuestByID appends the "ID" to the base path, so this workaround
// lets us add a query string.
String path = String.format("%s%s?%s", groupId, CONTACTPATH, getQueryString(contactIds));
messageBirdService.requestByID(GROUPPATH, path, null);
}
/**
* Builds a query string to add contacts to a group. We're using the
* alternative "/foo?_method=PUT&ids[]=foo&ids[]=bar" format to send the
* contact IDs as GET params. Sending these in the request body would
* require a painful workaround, as sendPayload sends request bodies as
* JSON by default. See also:
* https://developers.messagebird.com/docs/alternatives.
*/
private String getQueryString(final String[] contactIds) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("_method=PUT");
for (String groupId : contactIds) {
stringBuilder.append("&ids[]=").append(groupId);
}
return stringBuilder.toString();
}
/**
* Updates an existing group. You only need to supply the unique ID that
* was returned upon creation.
*/
public Group updateGroup(final String id, final GroupRequest groupRequest) throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
String path = String.format("%s/%s", GROUPPATH, id);
return messageBirdService.sendPayLoad("PATCH", path, groupRequest, Group.class);
}
/**
* Retrieves the information of an existing group. You only need to supply
* the unique group ID that was returned upon creation or receiving.
*/
public Group viewGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
return messageBirdService.requestByID(GROUPPATH, id, Group.class);
}
/**
* Gets a single conversation.
*
* @param id Conversation to retrieved.
* @return The retrieved conversation.
*/
public Conversation viewConversation(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Id must be specified");
}
String url = this.conversationsBaseUrl + CONVERSATION_PATH;
return messageBirdService.requestByID(url, id, Conversation.class);
}
/**
* Updates a conversation.
*
* @param id Conversation to update.
* @param status New status for the conversation.
* @return The updated Conversation.
*/
public Conversation updateConversation(final String id, final ConversationStatus status)
throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Id must be specified.");
}
String url = String.format("%s%s/%s", this.conversationsBaseUrl, CONVERSATION_PATH, id);
return messageBirdService.sendPayLoad("PATCH", url, status, Conversation.class);
}
/**
* Gets a Conversation listing with specified pagination options.
*
* @param offset Number of objects to skip.
* @param limit Number of objects to take.
* @return List of conversations.
*/
public ConversationList listConversations(final int offset, final int limit)
throws UnauthorizedException, GeneralException {
String url = this.conversationsBaseUrl + CONVERSATION_PATH;
return messageBirdService.requestList(url, offset, limit, ConversationList.class);
}
/**
* Gets a contact listing with default pagination options.
*
* @return List of conversations.
*/
public ConversationList listConversations() throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversations(offset, limit);
}
/**
* Starts a conversation by sending an initial message.
*
* @param request Data for this request.
* @return The created Conversation.
*/
public Conversation startConversation(ConversationStartRequest request)
throws UnauthorizedException, GeneralException {
String url = String.format("%s%s/start", this.conversationsBaseUrl, CONVERSATION_PATH);
return messageBirdService.sendPayLoad(url, request, Conversation.class);
}
/**
* Gets a ConversationMessage listing with specified pagination options.
*
* @param conversationId Conversation to get messages for.
* @param offset Number of objects to skip.
* @param limit Number of objects to take.
* @return List of messages.
*/
public ConversationMessageList listConversationMessages(
final String conversationId,
final int offset,
final int limit
) throws UnauthorizedException, GeneralException {
String url = String.format(
"%s%s/%s%s",
this.conversationsBaseUrl,
CONVERSATION_PATH,
conversationId,
CONVERSATION_MESSAGE_PATH
);
return messageBirdService.requestList(url, offset, limit, ConversationMessageList.class);
}
/**
* Gets a ConversationMessage listing with default pagination options.
*
* @param conversationId Conversation to get messages for.
* @return List of messages.
*/
public ConversationMessageList listConversationMessages(
final String conversationId
) throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversationMessages(conversationId, offset, limit);
}
/**
* Gets a single message.
*
* @param messageId Message to retrieve.
* @return The retrieved message.
*/
public ConversationMessage viewConversationMessage(final String messageId)
throws NotFoundException, GeneralException, UnauthorizedException {
String url = this.conversationsBaseUrl + CONVERSATION_MESSAGE_PATH;
return messageBirdService.requestByID(url, messageId, ConversationMessage.class);
}
/**
* Sends a message to an existing Conversation.
*
* @param conversationId Conversation to send message to.
* @param request Message to send.
* @return The newly created message.
*/
public ConversationMessage sendConversationMessage(
final String conversationId,
final ConversationMessageRequest request
) throws UnauthorizedException, GeneralException {
String url = String.format(
"%s%s/%s%s",
this.conversationsBaseUrl,
CONVERSATION_PATH,
conversationId,
CONVERSATION_MESSAGE_PATH
);
return messageBirdService.sendPayLoad(url, request, ConversationMessage.class);
}
/**
* Deletes a webhook.
*
* @param webhookId Webhook to delete.
*/
public void deleteConversationWebhook(final String webhookId)
throws NotFoundException, GeneralException, UnauthorizedException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
messageBirdService.deleteByID(url, webhookId);
}
/**
* Creates a new webhook.
*
* @param request Webhook to create.
* @return Newly created webhook.
*/
public ConversationWebhook sendConversationWebhook(final ConversationWebhookCreateRequest request)
throws UnauthorizedException, GeneralException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
return messageBirdService.sendPayLoad(url, request, ConversationWebhook.class);
}
/**
* Update an existing webhook.
*
* @param request update request.
* @return Updated webhook.
*/
public ConversationWebhook updateConversationWebhook(final String id, final ConversationWebhookUpdateRequest request) throws UnauthorizedException, GeneralException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("Conversation webhook ID must be specified.");
}
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH + "/" + id;
return messageBirdService.sendPayLoad("PATCH", url, request, ConversationWebhook.class);
}
/**
* Gets a single webhook.
*
* @param webhookId Webhook to retrieve.
* @return The retrieved webhook.
*/
public ConversationWebhook viewConversationWebhook(final String webhookId) throws NotFoundException, GeneralException, UnauthorizedException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
return messageBirdService.requestByID(url, webhookId, ConversationWebhook.class);
}
/**
* Gets a ConversationWebhook listing with the specified pagination options.
*
* @param offset Number of objects to skip.
* @param limit Number of objects to skip.
* @return List of webhooks.
*/
public ConversationWebhookList listConversationWebhooks(final int offset, final int limit)
throws UnauthorizedException, GeneralException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
return messageBirdService.requestList(url, offset, limit, ConversationWebhookList.class);
}
/**
* Gets a ConversationWebhook listing with default pagination options.
*
* @return List of webhooks.
*/
public ConversationWebhookList listConversationWebhooks() throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversationWebhooks(offset, limit);
}
/****************************************************************************************************/
/** Voice Calling
/****************************************************************************************************/
/**
* Function for voice call to a number
*
* @param voiceCall Voice call object
* @return VoiceCallResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallResponse sendVoiceCall(final VoiceCall voiceCall) throws UnauthorizedException, GeneralException {
if (voiceCall.getSource() == null) {
throw new IllegalArgumentException("Source of voice call must be specified.");
}
if (voiceCall.getDestination() == null) {
throw new IllegalArgumentException("Destination of voice call must be specified.");
}
if (voiceCall.getCallFlow() == null) {
throw new IllegalArgumentException("Call flow of voice call must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
return messageBirdService.sendPayLoad(url, voiceCall, VoiceCallResponse.class);
}
/**
* Function to list all voice calls
*
* @return VoiceCallResponseList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallResponseList listAllVoiceCalls(Integer page, Integer pageSize) throws GeneralException, UnauthorizedException {
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallResponseList.class);
}
/**
* Function to view voice call by id
*
* @param id Voice call ID
* @return VoiceCallResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallResponse viewVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Voice Message ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
return messageBirdService.requestByID(url, id, VoiceCallResponse.class);
}
/**
* Function to delete voice call by id
*
* @param id Voice call ID
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Voice Message ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
messageBirdService.deleteByID(url, id);
}
/**
* Retrieves a listing of all legs.
*
* @param callId Voice call ID
* @param page page to fetch (can be null - will return first page), number of first page is 1
* @param pageSize page size
* @return VoiceCallLegResponse
* @throws UnsupportedEncodingException no UTF8 supported url
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallLegResponse viewCallLegsByCallId(String callId, Integer page, Integer pageSize) throws UnsupportedEncodingException, UnauthorizedException, GeneralException {
if (callId == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
String url = String.format(
"%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
urlEncode(callId),
VOICELEGS_SUFFIX_PATH);
return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallLegResponse.class);
}
/**
* Retrieves a leg resource.
* The parameters are the unique ID of the call and of the leg that were returned upon their respective creation.
*
* @param callId Voice call ID
* @param legId ID of leg of specified call {callId}
* @return VoiceCallLeg
* @throws UnsupportedEncodingException no UTF8 supported url
* @throws NotFoundException not found with callId and legId
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallLeg viewCallLegByCallIdAndLegId(final String callId, String legId) throws UnsupportedEncodingException, NotFoundException, GeneralException, UnauthorizedException {
if (callId == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
String url = String.format(
"%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
urlEncode(callId),
VOICELEGS_SUFFIX_PATH);
VoiceCallLegResponse response = messageBirdService.requestByID(url, legId, VoiceCallLegResponse.class);
if (response.getData().size() == 1) {
return response.getData().get(0);
} else {
throw new NotFoundException("No such leg", new LinkedList<ErrorReport>());
}
}
private String urlEncode(String s) throws UnsupportedEncodingException {
return URLEncoder.encode(s, String.valueOf(StandardCharsets.UTF_8));
}
/**
* Function to view recording by call id , leg id and recording id
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @return Recording
* @throws NotFoundException not found with callId and legId
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public RecordingResponse viewRecording(String callID, String legId, String recordingId) throws NotFoundException, GeneralException, UnauthorizedException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
Map<String, Object> params = new LinkedHashMap<>();
params.put("legs", legId);
params.put("recordings", recordingId);
return messageBirdService.requestByID(url, callID, params, RecordingResponse.class);
}
/**
* Downloads the record in .wav format by using callId, legId and recordId and stores to basePath. basePath is not mandatory to set.
* If basePath is not set, default download will be the /Download folder in user group.
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param basePath store location. It should be directory. Property is Optional if $HOME is accessible
* @return the path that file is stored
* @throws NotFoundException if the recording does not found
* @throws GeneralException general exception
* @throws UnauthorizedException if client is unauthorized
*/
public String downloadRecording(String callID, String legId, String recordingId, String basePath) throws NotFoundException, GeneralException, UnauthorizedException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
RECORDING_DOWNLOAD_FORMAT
);
String fileName = String.format("%s%s",recordingId, RECORDING_DOWNLOAD_FORMAT);
return messageBirdService.getBinaryData(url, basePath, fileName);
}
/**
* List the all recordings related to CallID and LegId
*
* @param callID Voice call ID
* @param legId Leg ID
* @param offset Number of objects to skip.
* @param limit Number of objects to take.
* @return Recordings for CallID and LegID
* @throws GeneralException if client is unauthorized
* @throws UnauthorizedException general exception
*/
public RecordingResponse listRecordings(String callID, String legId, final Integer offset, final Integer limit)
throws GeneralException, UnauthorizedException {
verifyOffsetAndLimit(offset, limit);
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH);
return messageBirdService.requestList(url, offset, limit, RecordingResponse.class);
}
/**
* Function to view recording by call id , leg id and recording id
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param language Language
* @return TranscriptionResponseList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public TranscriptionResponse createTranscription(String callID, String legId, String recordingId, String language)
throws UnauthorizedException, GeneralException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
if (language == null) {
throw new IllegalArgumentException("Language must be specified.");
}
if (!Arrays.asList(supportedLanguages).contains(language)) {
throw new IllegalArgumentException("Your language is not allowed.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH);
return messageBirdService.sendPayLoad(url, language, TranscriptionResponse.class);
}
/**
* Function to view recording by call id, leg id and recording id
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param transcriptionId Transcription ID
* @return Transcription
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException If transcription is not found
*/
public TranscriptionResponse viewTranscription(String callID, String legId, String recordingId, String transcriptionId) throws UnauthorizedException, GeneralException, NotFoundException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
if(transcriptionId == null) {
throw new IllegalArgumentException("Transcription ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH);
return messageBirdService.requestByID(url, transcriptionId, TranscriptionResponse.class);
}
/**
* Lists the Transcription of callId, legId and recordId
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param page page to fetch (can be null - will return first page), number of first page is 1
* @param pageSize page size
* @return List of Transcription
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public TranscriptionResponse listTranscriptions(String callID, String legId, String recordingId, Integer page, Integer pageSize) throws UnauthorizedException, GeneralException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH);
return messageBirdService.requestList(url, new PagedPaging(page, pageSize), TranscriptionResponse.class);
}
/**
* Downloads the transcription in .txt format by using callId, legId, recordId and transcriptionId and stores to basePath. basePath is not mandatory to set.
* If basePath is not set, default download will be the /Download folder in user group.
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param transcriptionId Transcription ID
* @param basePath store location. It should be directory. Property is Optional if $HOME is accessible
* @return the path that file is stored
* @throws NotFoundException if the recording does not found
* @throws GeneralException general exception
* @throws UnauthorizedException if client is unauthorized
*/
public String downloadTranscription(String callID, String legId, String recordingId, String transcriptionId, String basePath)
throws UnauthorizedException, GeneralException, NotFoundException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
if (transcriptionId == null) {
throw new IllegalArgumentException("Transcription ID must be specified.");
}
String fileName = String.format("%s%s", transcriptionId, TRANSCRIPTION_DOWNLOAD_FORMAT);
String url = String.format(
"%s%s/%s%s/%s%s/%s%s/%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH,
fileName);
return messageBirdService.getBinaryData(url, basePath, fileName);
}
/**
* Function to create a webhook
*
* @param webhook webhook to create
* @return WebhookResponseData created webhook
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookResponseData createWebhook(Webhook webhook) throws UnauthorizedException, GeneralException {
if (webhook.getUrl() == null) {
throw new IllegalArgumentException("URL of webhook must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
return messageBirdService.sendPayLoad(url, webhook, WebhookResponseData.class);
}
/**
* Function to update a webhook
*
* @param webhook webhook fields to update
* @return WebhookResponseData updated webhook
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookResponseData updateWebhook(String id, Webhook webhook) throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Id of webhook must be specified.");
}
String url = String.format("%s%s/%s", VOICE_CALLS_BASE_URL, WEBHOOKS, id);
return messageBirdService.sendPayLoad("PUT", url, webhook, WebhookResponseData.class);
}
/**
* Function to view a webhook
*
* @param id id of a webhook
* @return WebhookResponseData
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookResponseData viewWebhook(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Id of webhook must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
return messageBirdService.requestByID(url, id, WebhookResponseData.class);
}
/**
* Function to list webhooks
*
* @param offset offset for result list
* @param limit limit for result list
* @return WebhookList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookList listWebhooks(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
return messageBirdService.requestList(url, offset, limit, WebhookList.class);
}
/**
* Function to delete a webhook
*
* @param id A unique random ID which is created on the MessageBird platform
* @throws NotFoundException if id is not found
* @throws GeneralException general exception
* @throws UnauthorizedException if client is unauthorized
*/
public void deleteWebhook(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Webhook ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
messageBirdService.deleteByID(url, id);
}
private void verifyOffsetAndLimit(Integer offset, Integer limit) {
if (offset != null && offset < 0) {
throw new IllegalArgumentException("Offset must be > 0");
}
if (limit != null && limit < 0) {
throw new IllegalArgumentException("Limit must be > 0");
}
}
public PhoneNumbersResponse listNumbersForPurchase(String countryCode) throws IllegalArgumentException, GeneralException, UnauthorizedException, NotFoundException {
final String url = String.format("%s/v1/available-phone-numbers", NUMBERS_CALLS_BASE_URL);
return messageBirdService.requestByID(url, countryCode, PhoneNumbersResponse.class);
}
public PhoneNumbersResponse listNumbersForPurchase(String countryCode, PhoneNumbersLookup params) throws IllegalArgumentException, GeneralException, UnauthorizedException, NotFoundException {
final String url = String.format("%s/v1/available-phone-numbers", NUMBERS_CALLS_BASE_URL);
return messageBirdService.requestByID(url, countryCode, params.toHashMap(), PhoneNumbersResponse.class);
}
public PurchasedPhoneNumber purchaseNumber(String number, String countryCode, int billingIntervalMonths) throws UnauthorizedException, GeneralException {
final String url = String.format("%s/v1/phone-numbers", NUMBERS_CALLS_BASE_URL);
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("number", number);
payload.put("countryCode", countryCode);
payload.put("billingIntervalMonths", billingIntervalMonths);
return messageBirdService.sendPayLoad(url, payload, PurchasedPhoneNumber.class);
}
public PhoneNumber updateNumber(String number, String... tags) throws UnauthorizedException, GeneralException {
final String url = String.format("%s/v1/phone-numbers/%s", NUMBERS_CALLS_BASE_URL, number);
final Map<String, List<String>> payload = new HashMap<String, List<String>>();
payload.put("tags", Arrays.asList(tags));
System.out.println(String.format("Payload: %s", payload.toString()));
return messageBirdService.sendPayLoad("PATCH", url, payload, PhoneNumber.class);
}
} | api/src/main/java/com/messagebird/MessageBirdClient.java | package com.messagebird;
import com.messagebird.exceptions.GeneralException;
import com.messagebird.exceptions.NotFoundException;
import com.messagebird.exceptions.UnauthorizedException;
import com.messagebird.objects.Balance;
import com.messagebird.objects.Contact;
import com.messagebird.objects.ContactList;
import com.messagebird.objects.ContactRequest;
import com.messagebird.objects.ErrorReport;
import com.messagebird.objects.Group;
import com.messagebird.objects.GroupList;
import com.messagebird.objects.GroupRequest;
import com.messagebird.objects.Hlr;
import com.messagebird.objects.Lookup;
import com.messagebird.objects.LookupHlr;
import com.messagebird.objects.Message;
import com.messagebird.objects.MessageList;
import com.messagebird.objects.MessageResponse;
import com.messagebird.objects.MsgType;
import com.messagebird.objects.PagedPaging;
import com.messagebird.objects.PhoneNumbersLookup;
import com.messagebird.objects.PhoneNumbersResponse;
import com.messagebird.objects.PurchasedPhoneNumber;
import com.messagebird.objects.Verify;
import com.messagebird.objects.VerifyRequest;
import com.messagebird.objects.VoiceMessage;
import com.messagebird.objects.VoiceMessageList;
import com.messagebird.objects.VoiceMessageResponse;
import com.messagebird.objects.conversations.Conversation;
import com.messagebird.objects.conversations.ConversationList;
import com.messagebird.objects.conversations.ConversationMessage;
import com.messagebird.objects.conversations.ConversationMessageList;
import com.messagebird.objects.conversations.ConversationMessageRequest;
import com.messagebird.objects.conversations.ConversationStartRequest;
import com.messagebird.objects.conversations.ConversationStatus;
import com.messagebird.objects.conversations.ConversationWebhook;
import com.messagebird.objects.conversations.ConversationWebhookCreateRequest;
import com.messagebird.objects.conversations.ConversationWebhookList;
import com.messagebird.objects.conversations.ConversationWebhookUpdateRequest;
import com.messagebird.objects.voicecalls.RecordingResponse;
import com.messagebird.objects.voicecalls.TranscriptionResponse;
import com.messagebird.objects.voicecalls.VoiceCall;
import com.messagebird.objects.voicecalls.VoiceCallFlowList;
import com.messagebird.objects.voicecalls.VoiceCallFlowRequest;
import com.messagebird.objects.voicecalls.VoiceCallFlowResponse;
import com.messagebird.objects.voicecalls.VoiceCallLeg;
import com.messagebird.objects.voicecalls.VoiceCallLegResponse;
import com.messagebird.objects.voicecalls.VoiceCallResponse;
import com.messagebird.objects.voicecalls.VoiceCallResponseList;
import com.messagebird.objects.voicecalls.Webhook;
import com.messagebird.objects.voicecalls.WebhookList;
import com.messagebird.objects.voicecalls.WebhookResponseData;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Message bird general client
* <p>
* <pre>
* Initialise this class with a MessageBirdService
* // First create your service object
* MessageBirdService wsr = new MessageBirdServiceImpl(args[0]);
* // Add the service to the client
* MessageBirdClient messageBirdClient = new MessageBirdClient(wsr);
*
* Then read your balance like this:
* final Balance balance = messageBirdClient.getBalance();
* </pre>
* <p>
* Created by rvt on 1/5/15.
*/
public class MessageBirdClient {
/**
* The Conversations API has a different URL scheme from the other
* APIs/endpoints. By default, the service prefixes paths with that URL. We
* can, however, override this behaviour by providing absolute URLs
* ourselves.
*/
private static final String BASE_URL_CONVERSATIONS = "https://conversations.messagebird.com/v1";
private static final String BASE_URL_CONVERSATIONS_WHATSAPP_SANDBOX = "https://whatsapp-sandbox.messagebird.com/v1";
static final String VOICE_CALLS_BASE_URL = "https://voice.messagebird.com";
static final String NUMBERS_CALLS_BASE_URL = "https://numbers.messagebird.com";
private static String[] supportedLanguages = {"de-DE", "en-AU", "en-UK", "en-US", "es-ES", "es-LA", "fr-FR", "it-IT", "nl-NL", "pt-BR"};
private static final String BALANCEPATH = "/balance";
private static final String CONTACTPATH = "/contacts";
private static final String GROUPPATH = "/groups";
private static final String HLRPATH = "/hlr";
private static final String LOOKUPHLRPATH = "/lookup/%s/hlr";
private static final String LOOKUPPATH = "/lookup";
private static final String MESSAGESPATH = "/messages";
private static final String VERIFYPATH = "/verify";
private static final String VOICEMESSAGESPATH = "/voicemessages";
private static final String CONVERSATION_PATH = "/conversations";
private static final String CONVERSATION_MESSAGE_PATH = "/messages";
private static final String CONVERSATION_WEBHOOK_PATH = "/webhooks";
static final String VOICECALLSPATH = "/calls";
static final String LEGSPATH = "/legs";
static final String RECORDINGPATH = "/recordings";
static final String TRANSCRIPTIONPATH = "/transcriptions";
static final String WEBHOOKS = "/webhooks";
static final String VOICECALLFLOWPATH = "/call-flows";
private static final String VOICELEGS_SUFFIX_PATH = "/legs";
static final String RECORDING_DOWNLOAD_FORMAT = ".wav";
static final String TRANSCRIPTION_DOWNLOAD_FORMAT = ".txt";
private static final int DEFAULT_MACHINE_TIMEOUT_VALUE = 7000;
private static final int MIN_MACHINE_TIMEOUT_VALUE = 400;
private static final int MAX_MACHINE_TIMEOUT_VALUE = 10000;
private final String DOWNLOADS = "Downloads";
private MessageBirdService messageBirdService;
private String conversationsBaseUrl;
public enum Feature {
ENABLE_CONVERSATION_API_WHATSAPP_SANDBOX
}
public MessageBirdClient(final MessageBirdService messageBirdService) {
this.messageBirdService = messageBirdService;
this.conversationsBaseUrl = BASE_URL_CONVERSATIONS;
}
public MessageBirdClient(final MessageBirdService messageBirdService, List<Feature> features) {
this(messageBirdService);
if(features.indexOf(Feature.ENABLE_CONVERSATION_API_WHATSAPP_SANDBOX) >= 0) {
this.conversationsBaseUrl = BASE_URL_CONVERSATIONS_WHATSAPP_SANDBOX;
}
}
/****************************************************************************************************/
/** Balance and HRL methods **/
/****************************************************************************************************/
/**
* MessageBird provides an API to get the balance information of your account.
*
* @return Balance object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Balance getBalance() throws GeneralException, UnauthorizedException, NotFoundException {
return messageBirdService.requestByID(BALANCEPATH, "", Balance.class);
}
/**
* MessageBird provides an API to send Network Queries to any mobile number across the world.
* An HLR allows you to view which mobile number (MSISDN) belongs to what operator in real time and see whether the number is active.
*
* @param msisdn The telephone number.
* @param reference A client reference
* @return Hlr Object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Hlr getRequestHlr(final BigInteger msisdn, final String reference) throws GeneralException, UnauthorizedException {
if (msisdn == null) {
throw new IllegalArgumentException("msisdn must be specified.");
}
if (reference == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("msisdn", msisdn);
payload.put("reference", reference);
return messageBirdService.sendPayLoad(HLRPATH, payload, Hlr.class);
}
/**
* Retrieves the information of an existing HLR. You only need to supply the unique message id that was returned upon creation or receiving.
*
* @param hlrId ID as returned by getRequestHlr in the id variable
* @return Hlr Object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Hlr getViewHlr(final String hlrId) throws GeneralException, UnauthorizedException, NotFoundException {
if (hlrId == null) {
throw new IllegalArgumentException("Hrl ID must be specified.");
}
return messageBirdService.requestByID(HLRPATH, hlrId, Hlr.class);
}
/****************************************************************************************************/
/** Messaging **/
/****************************************************************************************************/
/**
* Send a message through the messagebird platform
*
* @param message Message object to be send
* @return Message Response
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendMessage(final Message message) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(MESSAGESPATH, new Message(originator, body, recipients), MessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @param reference your reference
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException {
final Message message = new Message(originator, body, recipients);
message.setReference(reference);
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
/**
* Convenient function to send a simple flash message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException {
final Message message = new Message(originator, body, recipients);
message.setType(MsgType.flash);
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
/**
* Convenient function to send a simple flash message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @param reference your reference
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException {
final Message message = new Message(originator, body, recipients);
message.setType(MsgType.flash);
message.setReference(reference);
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
public MessageList listMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
return messageBirdService.requestList(MESSAGESPATH, offset, limit, MessageList.class);
}
/**
* Delete a message from the Messagebird server
*
* @param id A unique random ID which is created on the MessageBird platform
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Message ID must be specified.");
}
messageBirdService.deleteByID(MESSAGESPATH, id);
}
/**
* View a message from the Messagebird server
*
* @param id A unique random ID which is created on the MessageBird platform
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse viewMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Message ID must be specified.");
}
return messageBirdService.requestByID(MESSAGESPATH, id, MessageResponse.class);
}
/****************************************************************************************************/
/** Voice Messaging **/
/****************************************************************************************************/
/**
* Convenient function to send a simple message to a list of recipients
*
* @param voiceMessage Voice message object
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse sendVoiceMessage(final VoiceMessage voiceMessage) throws UnauthorizedException, GeneralException {
addDefaultMachineTimeoutValueIfNotExists(voiceMessage);
checkMachineTimeoutValueIsInRange(voiceMessage);
return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, voiceMessage, VoiceMessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param body Body of the message
* @param recipients List of recipients
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException {
final VoiceMessage message = new VoiceMessage(body, recipients);
addDefaultMachineTimeoutValueIfNotExists(message);
checkMachineTimeoutValueIsInRange(message);
return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param body Body of the message
* @param recipients List of recipients
* @param reference your reference
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException {
final VoiceMessage message = new VoiceMessage(body, recipients);
message.setReference(reference);
addDefaultMachineTimeoutValueIfNotExists(message);
checkMachineTimeoutValueIsInRange(message);
return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class);
}
private void addDefaultMachineTimeoutValueIfNotExists(final VoiceMessage voiceMessage){
if (voiceMessage.getMachineTimeout() == 0){
voiceMessage.setMachineTimeout(DEFAULT_MACHINE_TIMEOUT_VALUE); //default machine timeout value
}
}
private void checkMachineTimeoutValueIsInRange(final VoiceMessage voiceMessage){
if (voiceMessage.getMachineTimeout() < MIN_MACHINE_TIMEOUT_VALUE || voiceMessage.getMachineTimeout() > MAX_MACHINE_TIMEOUT_VALUE){
throw new IllegalArgumentException("Please define machine timeout value between " + MIN_MACHINE_TIMEOUT_VALUE + " and " + MAX_MACHINE_TIMEOUT_VALUE);
}
}
/**
* Delete a voice message from the Messagebird server
*
* @param id A unique random ID which is created on the MessageBird platform
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Message ID must be specified.");
}
messageBirdService.deleteByID(VOICEMESSAGESPATH, id);
}
/**
* View a message from the Messagebird server
*
* @param id A unique random ID which is created on the MessageBird platform
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse viewVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Voice Message ID must be specified.");
}
return messageBirdService.requestByID(VOICEMESSAGESPATH, id, VoiceMessageResponse.class);
}
/**
* List voice messages
*
* @param offset offset for result list
* @param limit limit for result list
* @return VoiceMessageList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageList listVoiceMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
return messageBirdService.requestList(VOICEMESSAGESPATH, offset, limit, VoiceMessageList.class);
}
/**
* @param verifyRequest includes recipient, originator, reference, type, datacoding, template, timeout, tokenLenght, voice, language
* @return Verify object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Verify sendVerifyToken(VerifyRequest verifyRequest) throws UnauthorizedException, GeneralException {
if (verifyRequest == null) {
throw new IllegalArgumentException("Verify request cannot be null");
} else if (verifyRequest.getRecipient() == null || verifyRequest.getRecipient().isEmpty()) {
throw new IllegalArgumentException("Recipient cannot be empty for verify");
}
return messageBirdService.sendPayLoad(VERIFYPATH, verifyRequest, Verify.class);
}
/**
* @param recipient The telephone number that you want to verify.
* @return Verify object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Verify sendVerifyToken(String recipient) throws UnauthorizedException, GeneralException {
if (recipient == null || recipient.isEmpty()) {
throw new IllegalArgumentException("Recipient cannot be empty for verify");
}
VerifyRequest verifyRequest = new VerifyRequest(recipient);
return this.sendVerifyToken(verifyRequest);
}
/**
* @param id A unique random ID which is created on the MessageBird platform
* @param token An unique token which was sent to the recipient upon creation of the object.
* @return Verify object
* @throws NotFoundException if id is not found
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Verify verifyToken(String id, String token) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
} else if (token == null || token.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("token", token);
return messageBirdService.requestByID(VERIFYPATH, id, params, Verify.class);
}
/**
* @param id id is for getting verify object
* @return Verify object
* @throws NotFoundException if id is not found
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
Verify getVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
}
return messageBirdService.requestByID(VERIFYPATH, id, Verify.class);
}
/**
* @param id id for deleting verify object
* @throws NotFoundException if id is not found
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
}
messageBirdService.deleteByID(VERIFYPATH, id);
}
/**
* Send a Lookup request
*
* @param lookup including with country code, country prefix, phone number, type, formats, country code
* @return Lookup
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException if lookup not found
*/
public Lookup viewLookup(final Lookup lookup) throws UnauthorizedException, GeneralException, NotFoundException {
if (lookup.getPhoneNumber() == null) {
throw new IllegalArgumentException("PhoneNumber must be specified.");
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
if (lookup.getCountryCode() != null) {
params.put("countryCode", lookup.getCountryCode());
}
return messageBirdService.requestByID(LOOKUPPATH, String.valueOf(lookup.getPhoneNumber()), params, Lookup.class);
}
/**
* Send a Lookup request
*
* @param phoneNumber phone number is for viewing lookup
* @return Lookup
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Lookup viewLookup(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException {
if (phoneNumber == null) {
throw new IllegalArgumentException("PhoneNumber must be specified.");
}
final Lookup lookup = new Lookup(phoneNumber);
return this.viewLookup(lookup);
}
/**
* Request a Lookup HLR (lookup)
*
* @param lookupHlr country code for request lookup hlr
* @return lookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public LookupHlr requestLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException {
if (lookupHlr.getPhoneNumber() == null) {
throw new IllegalArgumentException("PhoneNumber must be specified.");
}
if (lookupHlr.getReference() == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("phoneNumber", lookupHlr.getPhoneNumber());
payload.put("reference", lookupHlr.getReference());
if (lookupHlr.getCountryCode() != null) {
payload.put("countryCode", lookupHlr.getCountryCode());
}
return messageBirdService.sendPayLoad(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), payload, LookupHlr.class);
}
/**
* Request a Lookup HLR (lookup)
*
* @param phoneNumber phone number is for request hlr
* @param reference reference for request hlr
* @return lookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public LookupHlr requestLookupHlr(final BigInteger phoneNumber, final String reference) throws UnauthorizedException, GeneralException {
if (phoneNumber == null) {
throw new IllegalArgumentException("Phonenumber must be specified.");
}
if (reference == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final LookupHlr lookupHlr = new LookupHlr();
lookupHlr.setPhoneNumber(phoneNumber);
lookupHlr.setReference(reference);
return this.requestLookupHlr(lookupHlr);
}
/**
* View a Lookup HLR (lookup)
*
* @param lookupHlr search with country code
* @return LookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException if there is no lookup hlr with given country code
*/
public LookupHlr viewLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException, NotFoundException {
if (lookupHlr.getPhoneNumber() == null) {
throw new IllegalArgumentException("Phonenumber must be specified");
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
if (lookupHlr.getCountryCode() != null) {
params.put("countryCode", lookupHlr.getCountryCode());
}
return messageBirdService.requestByID(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), "", params, LookupHlr.class);
}
/**
* View a Lookup HLR (lookup)
*
* @param phoneNumber phone number for searching on hlr
* @return LookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException phone number not found on hlr
*/
public LookupHlr viewLookupHlr(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException {
if (phoneNumber == null) {
throw new IllegalArgumentException("phoneNumber must be specified");
}
final LookupHlr lookupHlr = new LookupHlr();
lookupHlr.setPhoneNumber(phoneNumber);
return this.viewLookupHlr(lookupHlr);
}
/**
* Convenient function to list all call flows
*
* @param offset
* @param limit
* @return VoiceCallFlowList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallFlowList listVoiceCallFlows(final Integer offset, final Integer limit)
throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
return messageBirdService.requestList(url, offset, limit, VoiceCallFlowList.class);
}
/**
* Retrieves the information of an existing Call Flow. You only need to supply
* the unique call flow ID that was returned upon creation or receiving.
* @param id String
* @return VoiceCallFlowResponse
* @throws NotFoundException
* @throws GeneralException
* @throws UnauthorizedException
*/
public VoiceCallFlowResponse viewVoiceCallFlow(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Call Flow ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
return messageBirdService.requestByID(url, id, VoiceCallFlowResponse.class);
}
/**
* Convenient function to create a call flow
*
* @param voiceCallFlowRequest VoiceCallFlowRequest
* @return VoiceCallFlowResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallFlowResponse sendVoiceCallFlow(final VoiceCallFlowRequest voiceCallFlowRequest)
throws UnauthorizedException, GeneralException {
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
return messageBirdService.sendPayLoad(url, voiceCallFlowRequest, VoiceCallFlowResponse.class);
}
/**
* Updates an existing Call Flow. You only need to supply the unique id that
* was returned upon creation.
* @param id String
* @param voiceCallFlowRequest VoiceCallFlowRequest
* @return VoiceCallFlowResponse
* @throws UnauthorizedException
* @throws GeneralException
*/
public VoiceCallFlowResponse updateVoiceCallFlow(String id, VoiceCallFlowRequest voiceCallFlowRequest)
throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Call Flow ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
String request = url + "/" + id;
return messageBirdService.sendPayLoad("PUT", request, voiceCallFlowRequest, VoiceCallFlowResponse.class);
}
/**
* Convenient function to delete call flow
*
* @param id String
* @return void
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVoiceCallFlow(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Voice Call Flow ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
messageBirdService.deleteByID(url, id);
}
/**
* Deletes an existing contact. You only need to supply the unique id that
* was returned upon creation.
*/
void deleteContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
messageBirdService.deleteByID(CONTACTPATH, id);
}
/**
* Gets a contact listing with specified pagination options.
*
* @return Listing of Contact objects.
*/
public ContactList listContacts(int offset, int limit) throws UnauthorizedException, GeneralException {
return messageBirdService.requestList(CONTACTPATH, offset, limit, ContactList.class);
}
/**
* Gets a contact listing with default pagination options.
*/
public ContactList listContacts() throws UnauthorizedException, GeneralException {
final int limit = 20;
final int offset = 0;
return listContacts(offset, limit);
}
/**
* Creates a new contact object. MessageBird returns the created contact
* object with each request.
*/
public Contact sendContact(final ContactRequest contactRequest) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(CONTACTPATH, contactRequest, Contact.class);
}
/**
* Updates an existing contact. You only need to supply the unique id that
* was returned upon creation.
*/
public Contact updateContact(final String id, ContactRequest contactRequest) throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
String request = CONTACTPATH + "/" + id;
return messageBirdService.sendPayLoad("PATCH", request, contactRequest, Contact.class);
}
/**
* Retrieves the information of an existing contact. You only need to supply
* the unique contact ID that was returned upon creation or receiving.
*/
public Contact viewContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
return messageBirdService.requestByID(CONTACTPATH, id, Contact.class);
}
/**
* Deletes an existing group. You only need to supply the unique id that
* was returned upon creation.
*/
public void deleteGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
messageBirdService.deleteByID(GROUPPATH, id);
}
/**
* Removes a contact from group. You need to supply the IDs of the group
* and contact. Does not delete the contact.
*/
public void deleteGroupContact(final String groupId, final String contactId) throws NotFoundException, GeneralException, UnauthorizedException {
if (groupId == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
if (contactId == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
String id = String.format("%s%s/%s", groupId, CONTACTPATH, contactId);
messageBirdService.deleteByID(GROUPPATH, id);
}
/**
* Gets a contact listing with specified pagination options.
*/
public GroupList listGroups(final int offset, final int limit) throws UnauthorizedException, GeneralException {
return messageBirdService.requestList(GROUPPATH, offset, limit, GroupList.class);
}
/**
* Gets a contact listing with default pagination options.
*/
public GroupList listGroups() throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 20;
return listGroups(offset, limit);
}
/**
* Creates a new group object. MessageBird returns the created group object
* with each request.
*/
public Group sendGroup(final GroupRequest groupRequest) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(GROUPPATH, groupRequest, Group.class);
}
/**
* Adds contact to group. You need to supply the IDs of the group and
* contact.
*/
public void sendGroupContact(final String groupId, final String[] contactIds) throws NotFoundException, GeneralException, UnauthorizedException {
// reuestByID appends the "ID" to the base path, so this workaround
// lets us add a query string.
String path = String.format("%s%s?%s", groupId, CONTACTPATH, getQueryString(contactIds));
messageBirdService.requestByID(GROUPPATH, path, null);
}
/**
* Builds a query string to add contacts to a group. We're using the
* alternative "/foo?_method=PUT&ids[]=foo&ids[]=bar" format to send the
* contact IDs as GET params. Sending these in the request body would
* require a painful workaround, as sendPayload sends request bodies as
* JSON by default. See also:
* https://developers.messagebird.com/docs/alternatives.
*/
private String getQueryString(final String[] contactIds) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("_method=PUT");
for (String groupId : contactIds) {
stringBuilder.append("&ids[]=").append(groupId);
}
return stringBuilder.toString();
}
/**
* Updates an existing group. You only need to supply the unique ID that
* was returned upon creation.
*/
public Group updateGroup(final String id, final GroupRequest groupRequest) throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
String path = String.format("%s/%s", GROUPPATH, id);
return messageBirdService.sendPayLoad("PATCH", path, groupRequest, Group.class);
}
/**
* Retrieves the information of an existing group. You only need to supply
* the unique group ID that was returned upon creation or receiving.
*/
public Group viewGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
return messageBirdService.requestByID(GROUPPATH, id, Group.class);
}
/**
* Gets a single conversation.
*
* @param id Conversation to retrieved.
* @return The retrieved conversation.
*/
public Conversation viewConversation(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Id must be specified");
}
String url = this.conversationsBaseUrl + CONVERSATION_PATH;
return messageBirdService.requestByID(url, id, Conversation.class);
}
/**
* Updates a conversation.
*
* @param id Conversation to update.
* @param status New status for the conversation.
* @return The updated Conversation.
*/
public Conversation updateConversation(final String id, final ConversationStatus status)
throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Id must be specified.");
}
String url = String.format("%s%s/%s", this.conversationsBaseUrl, CONVERSATION_PATH, id);
return messageBirdService.sendPayLoad("PATCH", url, status, Conversation.class);
}
/**
* Gets a Conversation listing with specified pagination options.
*
* @param offset Number of objects to skip.
* @param limit Number of objects to take.
* @return List of conversations.
*/
public ConversationList listConversations(final int offset, final int limit)
throws UnauthorizedException, GeneralException {
String url = this.conversationsBaseUrl + CONVERSATION_PATH;
return messageBirdService.requestList(url, offset, limit, ConversationList.class);
}
/**
* Gets a contact listing with default pagination options.
*
* @return List of conversations.
*/
public ConversationList listConversations() throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversations(offset, limit);
}
/**
* Starts a conversation by sending an initial message.
*
* @param request Data for this request.
* @return The created Conversation.
*/
public Conversation startConversation(ConversationStartRequest request)
throws UnauthorizedException, GeneralException {
String url = String.format("%s%s/start", this.conversationsBaseUrl, CONVERSATION_PATH);
return messageBirdService.sendPayLoad(url, request, Conversation.class);
}
/**
* Gets a ConversationMessage listing with specified pagination options.
*
* @param conversationId Conversation to get messages for.
* @param offset Number of objects to skip.
* @param limit Number of objects to take.
* @return List of messages.
*/
public ConversationMessageList listConversationMessages(
final String conversationId,
final int offset,
final int limit
) throws UnauthorizedException, GeneralException {
String url = String.format(
"%s%s/%s%s",
this.conversationsBaseUrl,
CONVERSATION_PATH,
conversationId,
CONVERSATION_MESSAGE_PATH
);
return messageBirdService.requestList(url, offset, limit, ConversationMessageList.class);
}
/**
* Gets a ConversationMessage listing with default pagination options.
*
* @param conversationId Conversation to get messages for.
* @return List of messages.
*/
public ConversationMessageList listConversationMessages(
final String conversationId
) throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversationMessages(conversationId, offset, limit);
}
/**
* Gets a single message.
*
* @param messageId Message to retrieve.
* @return The retrieved message.
*/
public ConversationMessage viewConversationMessage(final String messageId)
throws NotFoundException, GeneralException, UnauthorizedException {
String url = this.conversationsBaseUrl + CONVERSATION_MESSAGE_PATH;
return messageBirdService.requestByID(url, messageId, ConversationMessage.class);
}
/**
* Sends a message to an existing Conversation.
*
* @param conversationId Conversation to send message to.
* @param request Message to send.
* @return The newly created message.
*/
public ConversationMessage sendConversationMessage(
final String conversationId,
final ConversationMessageRequest request
) throws UnauthorizedException, GeneralException {
String url = String.format(
"%s%s/%s%s",
this.conversationsBaseUrl,
CONVERSATION_PATH,
conversationId,
CONVERSATION_MESSAGE_PATH
);
return messageBirdService.sendPayLoad(url, request, ConversationMessage.class);
}
/**
* Deletes a webhook.
*
* @param webhookId Webhook to delete.
*/
public void deleteConversationWebhook(final String webhookId)
throws NotFoundException, GeneralException, UnauthorizedException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
messageBirdService.deleteByID(url, webhookId);
}
/**
* Creates a new webhook.
*
* @param request Webhook to create.
* @return Newly created webhook.
*/
public ConversationWebhook sendConversationWebhook(final ConversationWebhookCreateRequest request)
throws UnauthorizedException, GeneralException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
return messageBirdService.sendPayLoad(url, request, ConversationWebhook.class);
}
/**
* Update an existing webhook.
*
* @param request update request.
* @return Updated webhook.
*/
public ConversationWebhook updateConversationWebhook(final String id, final ConversationWebhookUpdateRequest request) throws UnauthorizedException, GeneralException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("Conversation webhook ID must be specified.");
}
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH + "/" + id;
return messageBirdService.sendPayLoad("PATCH", url, request, ConversationWebhook.class);
}
/**
* Gets a single webhook.
*
* @param webhookId Webhook to retrieve.
* @return The retrieved webhook.
*/
public ConversationWebhook viewConversationWebhook(final String webhookId) throws NotFoundException, GeneralException, UnauthorizedException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
return messageBirdService.requestByID(url, webhookId, ConversationWebhook.class);
}
/**
* Gets a ConversationWebhook listing with the specified pagination options.
*
* @param offset Number of objects to skip.
* @param limit Number of objects to skip.
* @return List of webhooks.
*/
public ConversationWebhookList listConversationWebhooks(final int offset, final int limit)
throws UnauthorizedException, GeneralException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
return messageBirdService.requestList(url, offset, limit, ConversationWebhookList.class);
}
/**
* Gets a ConversationWebhook listing with default pagination options.
*
* @return List of webhooks.
*/
public ConversationWebhookList listConversationWebhooks() throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversationWebhooks(offset, limit);
}
/****************************************************************************************************/
/** Voice Calling
/****************************************************************************************************/
/**
* Function for voice call to a number
*
* @param voiceCall Voice call object
* @return VoiceCallResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallResponse sendVoiceCall(final VoiceCall voiceCall) throws UnauthorizedException, GeneralException {
if (voiceCall.getSource() == null) {
throw new IllegalArgumentException("Source of voice call must be specified.");
}
if (voiceCall.getDestination() == null) {
throw new IllegalArgumentException("Destination of voice call must be specified.");
}
if (voiceCall.getCallFlow() == null) {
throw new IllegalArgumentException("Call flow of voice call must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
return messageBirdService.sendPayLoad(url, voiceCall, VoiceCallResponse.class);
}
/**
* Function to list all voice calls
*
* @return VoiceCallResponseList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallResponseList listAllVoiceCalls(Integer page, Integer pageSize) throws GeneralException, UnauthorizedException {
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallResponseList.class);
}
/**
* Function to view voice call by id
*
* @param id Voice call ID
* @return VoiceCallResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallResponse viewVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Voice Message ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
return messageBirdService.requestByID(url, id, VoiceCallResponse.class);
}
/**
* Function to delete voice call by id
*
* @param id Voice call ID
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Voice Message ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
messageBirdService.deleteByID(url, id);
}
/**
* Retrieves a listing of all legs.
*
* @param callId Voice call ID
* @param page page to fetch (can be null - will return first page), number of first page is 1
* @param pageSize page size
* @return VoiceCallLegResponse
* @throws UnsupportedEncodingException no UTF8 supported url
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallLegResponse viewCallLegsByCallId(String callId, Integer page, Integer pageSize) throws UnsupportedEncodingException, UnauthorizedException, GeneralException {
if (callId == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
String url = String.format(
"%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
urlEncode(callId),
VOICELEGS_SUFFIX_PATH);
return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallLegResponse.class);
}
/**
* Retrieves a leg resource.
* The parameters are the unique ID of the call and of the leg that were returned upon their respective creation.
*
* @param callId Voice call ID
* @param legId ID of leg of specified call {callId}
* @return VoiceCallLeg
* @throws UnsupportedEncodingException no UTF8 supported url
* @throws NotFoundException not found with callId and legId
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallLeg viewCallLegByCallIdAndLegId(final String callId, String legId) throws UnsupportedEncodingException, NotFoundException, GeneralException, UnauthorizedException {
if (callId == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
String url = String.format(
"%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
urlEncode(callId),
VOICELEGS_SUFFIX_PATH);
VoiceCallLegResponse response = messageBirdService.requestByID(url, legId, VoiceCallLegResponse.class);
if (response.getData().size() == 1) {
return response.getData().get(0);
} else {
throw new NotFoundException("No such leg", new LinkedList<ErrorReport>());
}
}
private String urlEncode(String s) throws UnsupportedEncodingException {
return URLEncoder.encode(s, String.valueOf(StandardCharsets.UTF_8));
}
/**
* Function to view recording by call id , leg id and recording id
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @return Recording
* @throws NotFoundException not found with callId and legId
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public RecordingResponse viewRecording(String callID, String legId, String recordingId) throws NotFoundException, GeneralException, UnauthorizedException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
Map<String, Object> params = new LinkedHashMap<>();
params.put("legs", legId);
params.put("recordings", recordingId);
return messageBirdService.requestByID(url, callID, params, RecordingResponse.class);
}
/**
* Downloads the record in .wav format by using callId, legId and recordId and stores to basePath. basePath is not mandatory to set.
* If basePath is not set, default download will be the /Download folder in user group.
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param basePath store location. It should be directory. Property is Optional if $HOME is accessible
* @return the path that file is stored
* @throws NotFoundException if the recording does not found
* @throws GeneralException general exception
* @throws UnauthorizedException if client is unauthorized
*/
public String downloadRecording(String callID, String legId, String recordingId, String basePath) throws NotFoundException, GeneralException, UnauthorizedException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
RECORDING_DOWNLOAD_FORMAT
);
String fileName = String.format("%s%s",recordingId, RECORDING_DOWNLOAD_FORMAT);
return messageBirdService.getBinaryData(url, basePath, fileName);
}
/**
* List the all recordings related to CallID and LegId
*
* @param callID Voice call ID
* @param legId Leg ID
* @param offset Number of objects to skip.
* @param limit Number of objects to take.
* @return Recordings for CallID and LegID
* @throws GeneralException if client is unauthorized
* @throws UnauthorizedException general exception
*/
public RecordingResponse listRecordings(String callID, String legId, final Integer offset, final Integer limit)
throws GeneralException, UnauthorizedException {
verifyOffsetAndLimit(offset, limit);
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH);
return messageBirdService.requestList(url, offset, limit, RecordingResponse.class);
}
/**
* Function to view recording by call id , leg id and recording id
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param language Language
* @return TranscriptionResponseList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public TranscriptionResponse createTranscription(String callID, String legId, String recordingId, String language)
throws UnauthorizedException, GeneralException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
if (language == null) {
throw new IllegalArgumentException("Language must be specified.");
}
if (!Arrays.asList(supportedLanguages).contains(language)) {
throw new IllegalArgumentException("Your language is not allowed.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH);
return messageBirdService.sendPayLoad(url, language, TranscriptionResponse.class);
}
/**
* Function to view recording by call id, leg id and recording id
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param transcriptionId Transcription ID
* @return Transcription
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException If transcription is not found
*/
public TranscriptionResponse viewTranscription(String callID, String legId, String recordingId, String transcriptionId) throws UnauthorizedException, GeneralException, NotFoundException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
if(transcriptionId == null) {
throw new IllegalArgumentException("Transcription ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH);
return messageBirdService.requestByID(url, transcriptionId, TranscriptionResponse.class);
}
/**
* Lists the Transcription of callId, legId and recordId
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param page page to fetch (can be null - will return first page), number of first page is 1
* @param pageSize page size
* @return List of Transcription
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public TranscriptionResponse listTranscriptions(String callID, String legId, String recordingId, Integer page, Integer pageSize) throws UnauthorizedException, GeneralException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH);
return messageBirdService.requestList(url, new PagedPaging(page, pageSize), TranscriptionResponse.class);
}
/**
* Downloads the transcription in .txt format by using callId, legId, recordId and transcriptionId and stores to basePath. basePath is not mandatory to set.
* If basePath is not set, default download will be the /Download folder in user group.
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param transcriptionId Transcription ID
* @param basePath store location. It should be directory. Property is Optional if $HOME is accessible
* @return the path that file is stored
* @throws NotFoundException if the recording does not found
* @throws GeneralException general exception
* @throws UnauthorizedException if client is unauthorized
*/
public String downloadTranscription(String callID, String legId, String recordingId, String transcriptionId, String basePath)
throws UnauthorizedException, GeneralException, NotFoundException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
if (transcriptionId == null) {
throw new IllegalArgumentException("Transcription ID must be specified.");
}
String fileName = String.format("%s%s", transcriptionId, TRANSCRIPTION_DOWNLOAD_FORMAT);
String url = String.format(
"%s%s/%s%s/%s%s/%s%s/%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH,
fileName);
return messageBirdService.getBinaryData(url, basePath, fileName);
}
/**
* Function to create a webhook
*
* @param webhook webhook to create
* @return WebhookResponseData created webhook
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookResponseData createWebhook(Webhook webhook) throws UnauthorizedException, GeneralException {
if (webhook.getUrl() == null) {
throw new IllegalArgumentException("URL of webhook must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
return messageBirdService.sendPayLoad(url, webhook, WebhookResponseData.class);
}
/**
* Function to update a webhook
*
* @param webhook webhook fields to update
* @return WebhookResponseData updated webhook
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookResponseData updateWebhook(String id, Webhook webhook) throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Id of webhook must be specified.");
}
String url = String.format("%s%s/%s", VOICE_CALLS_BASE_URL, WEBHOOKS, id);
return messageBirdService.sendPayLoad("PUT", url, webhook, WebhookResponseData.class);
}
/**
* Function to view a webhook
*
* @param id id of a webhook
* @return WebhookResponseData
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookResponseData viewWebhook(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Id of webhook must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
return messageBirdService.requestByID(url, id, WebhookResponseData.class);
}
/**
* Function to list webhooks
*
* @param offset offset for result list
* @param limit limit for result list
* @return WebhookList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookList listWebhooks(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
return messageBirdService.requestList(url, offset, limit, WebhookList.class);
}
/**
* Function to delete a webhook
*
* @param id A unique random ID which is created on the MessageBird platform
* @throws NotFoundException if id is not found
* @throws GeneralException general exception
* @throws UnauthorizedException if client is unauthorized
*/
public void deleteWebhook(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Webhook ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
messageBirdService.deleteByID(url, id);
}
private void verifyOffsetAndLimit(Integer offset, Integer limit) {
if (offset != null && offset < 0) {
throw new IllegalArgumentException("Offset must be > 0");
}
if (limit != null && limit < 0) {
throw new IllegalArgumentException("Limit must be > 0");
}
}
public PhoneNumbersResponse listNumbersForPurchase(String countryCode) throws IllegalArgumentException, GeneralException, UnauthorizedException, NotFoundException {
final String url = String.format("%s/v1/available-phone-numbers", NUMBERS_CALLS_BASE_URL);
return messageBirdService.requestByID(url, countryCode, PhoneNumbersResponse.class);
}
public PhoneNumbersResponse listNumbersForPurchase(String countryCode, PhoneNumbersLookup params) throws IllegalArgumentException, GeneralException, UnauthorizedException, NotFoundException {
final String url = String.format("%s/v1/available-phone-numbers", NUMBERS_CALLS_BASE_URL);
return messageBirdService.requestByID(url, countryCode, params.toHashMap(), PhoneNumbersResponse.class);
}
public PurchasedPhoneNumber purchaseNumber(String number, String countryCode, int billingIntervalMonths) throws UnauthorizedException, GeneralException {
final String url = String.format("%s/v1/phone-numbers", NUMBERS_CALLS_BASE_URL);
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("number", number);
payload.put("countryCode", countryCode);
payload.put("billingIntervalMonths", billingIntervalMonths);
return messageBirdService.sendPayLoad(url, payload, PurchasedPhoneNumber.class);
}
} | add updateNumber method
| api/src/main/java/com/messagebird/MessageBirdClient.java | add updateNumber method | <ide><path>pi/src/main/java/com/messagebird/MessageBirdClient.java
<ide> import com.messagebird.objects.MessageResponse;
<ide> import com.messagebird.objects.MsgType;
<ide> import com.messagebird.objects.PagedPaging;
<add>import com.messagebird.objects.PhoneNumber;
<ide> import com.messagebird.objects.PhoneNumbersLookup;
<ide> import com.messagebird.objects.PhoneNumbersResponse;
<ide> import com.messagebird.objects.PurchasedPhoneNumber;
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.net.URLEncoder;
<ide> import java.util.Arrays;
<add>import java.util.HashMap;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.LinkedList;
<ide> import java.util.List;
<ide>
<ide> return messageBirdService.sendPayLoad(url, payload, PurchasedPhoneNumber.class);
<ide> }
<add>
<add> public PhoneNumber updateNumber(String number, String... tags) throws UnauthorizedException, GeneralException {
<add> final String url = String.format("%s/v1/phone-numbers/%s", NUMBERS_CALLS_BASE_URL, number);
<add> final Map<String, List<String>> payload = new HashMap<String, List<String>>();
<add> payload.put("tags", Arrays.asList(tags));
<add> System.out.println(String.format("Payload: %s", payload.toString()));
<add> return messageBirdService.sendPayLoad("PATCH", url, payload, PhoneNumber.class);
<add> }
<ide> } |
|
JavaScript | mit | 1756e2222fc4a679f150d9421c353302d824b599 | 0 | uwwebservices/idcard-webapp-poc,uwwebservices/idcard-webapp-poc | const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: "production",
devtool: '#source-map',
node: {
fs: 'empty',
net: 'empty',
module: 'empty'
},
entry: './src/frontend/App.js',
output: {
path: __dirname + '/dist/assets',
filename: 'index_bundle.js'
},
module: {
rules: [
{ test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: { presets:['react']}
},
{ test: /\.css$/,
use: [ MiniCssExtractPlugin.loader, "css-loader"],
exclude: /node_modules/ },
{ test: /\.scss$/,
use: [ MiniCssExtractPlugin.loader, "css-loader", 'sass-loader'],
exclude: /node_modules/
},
{
test: /\.(png|jp(e*)g)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'img/[hash]-[name].[ext]'
}
}]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]'
}
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css"
}),
new HtmlWebpackPlugin()
],
resolve: {
modules: [
'node_modules',
'./src',
'./src/frontend'
],
extensions: [
'.js',
'.jsx',
'.json',
'.css',
'.scss'
]
},
target: 'web'
}; | webpack.config.js | const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: "production",
devtool: '#source-map',
node: {
fs: 'empty',
net: 'empty',
module: 'empty'
},
entry: './src/frontend/App.js',
output: {
path: __dirname + '/dist/assets',
filename: 'index_bundle.js'
},
module: {
rules: [
{ test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: { presets:['react']}
},
{ test: /\.css$/,
use: [ MiniCssExtractPlugin.loader, "css-loader"],
exclude: /node_modules/ },
{ test: /\.scss$/,
use: [ MiniCssExtractPlugin.loader, "css-loader", 'sass-loader'],
exclude: /node_modules/
},
{
test: /\.(png|jp(e*)g)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'img/[hash]-[name].[ext]'
}
}]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]'
}
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css"
}),
new HtmlWebpackPlugin()
],
resolve: {
modules: ['node_modules', './src', './src/frontend/img'],
extensions: [
'.js',
'.jsx',
'.json',
'.css',
'.scss'
]
},
target: 'web'
}; | fixing base paths for webpack
| webpack.config.js | fixing base paths for webpack | <ide><path>ebpack.config.js
<ide> new HtmlWebpackPlugin()
<ide> ],
<ide> resolve: {
<del> modules: ['node_modules', './src', './src/frontend/img'],
<add> modules: [
<add> 'node_modules',
<add> './src',
<add> './src/frontend'
<add> ],
<ide> extensions: [
<ide> '.js',
<ide> '.jsx', |
|
Java | epl-1.0 | error: pathspec 'src/pp2016/team13/shared/Trank2.java' did not match any file(s) known to git
| 7ed61c4b5798772be758213678407f248f4ff2f4 | 1 | HindiBones/project | package pp2016.team13.shared;
public class Trank2 {
private int wirkung;
//Fuer die Server Engine ; f�r die Trankliste
public static int posX;
public static int posY;
public static boolean aufgehoben;
public static boolean gedroppt;
public static int trankID;
public Trank2(int wirkung) {
this.wirkung = wirkung;
}
//Konstruktor fuer die Server Engine
public Trank2(int trankID, int j, int i) {
trankID = trankID;
setGedroppt(false);
setAufgehoben(false);
setPosX(j);
setPosY(i);
}
// Methoden f�r die Server Engine
//Keine setter-Methode fuer die Trank-ID, da diese nicht veraendert werden soll
//getter-Methode fuer die Trank-ID;
public static int getTrankID(){
return trankID;
}
//setter-Methode, die festlegt, ob der Trank bereits gedroppt wurde
public static void setGedroppt(boolean neuGedroppt){
gedroppt = neuGedroppt;
}
//getter-Methode, die anzeigt, ob der Trank bereits gedroppt wurde
public static boolean getGedroppt(){
return gedroppt;
}
//setter-Methode, die den Zustand des Tranks aendert
public static void setAufgehoben(boolean neuAufgehoben){
aufgehoben=neuAufgehoben;
}
//getter-Methode fuer den Zustand des Tranks
public static boolean getAufgehoben(){
return aufgehoben;
}
//setter-Methode fuer die x-Koordinate des Tranks
public static void setPosX(int neuPosX){
posX=neuPosX;
}
//getter-Methode fuer die x-Koordinate des Tranks
public static int getPosX(){
return posX;
}
//setter-Methode fuer die y-Koordinate des Tranks
public static void setPosY(int neuPosY){
posY=neuPosY;
}
//getter-Methode fuer die y-Koordinate des Tranks
public static int getPosY(){
return posY;
}
//Methoden fuer den Client
public int getWirkung() {
return wirkung;
}
}
| src/pp2016/team13/shared/Trank2.java | Bearbeitung blauer heiltrank | src/pp2016/team13/shared/Trank2.java | Bearbeitung blauer heiltrank | <ide><path>rc/pp2016/team13/shared/Trank2.java
<add>package pp2016.team13.shared;
<add>
<add>public class Trank2 {
<add> private int wirkung;
<add>
<add> //Fuer die Server Engine ; f�r die Trankliste
<add> public static int posX;
<add> public static int posY;
<add> public static boolean aufgehoben;
<add> public static boolean gedroppt;
<add> public static int trankID;
<add>
<add> public Trank2(int wirkung) {
<add> this.wirkung = wirkung;
<add> }
<add>
<add> //Konstruktor fuer die Server Engine
<add> public Trank2(int trankID, int j, int i) {
<add> trankID = trankID;
<add> setGedroppt(false);
<add> setAufgehoben(false);
<add> setPosX(j);
<add> setPosY(i);
<add> }
<add>
<add> // Methoden f�r die Server Engine
<add> //Keine setter-Methode fuer die Trank-ID, da diese nicht veraendert werden soll
<add>
<add> //getter-Methode fuer die Trank-ID;
<add> public static int getTrankID(){
<add> return trankID;
<add> }
<add>
<add> //setter-Methode, die festlegt, ob der Trank bereits gedroppt wurde
<add> public static void setGedroppt(boolean neuGedroppt){
<add> gedroppt = neuGedroppt;
<add> }
<add>
<add> //getter-Methode, die anzeigt, ob der Trank bereits gedroppt wurde
<add> public static boolean getGedroppt(){
<add> return gedroppt;
<add> }
<add>
<add> //setter-Methode, die den Zustand des Tranks aendert
<add> public static void setAufgehoben(boolean neuAufgehoben){
<add> aufgehoben=neuAufgehoben;
<add> }
<add>
<add> //getter-Methode fuer den Zustand des Tranks
<add> public static boolean getAufgehoben(){
<add> return aufgehoben;
<add> }
<add>
<add> //setter-Methode fuer die x-Koordinate des Tranks
<add> public static void setPosX(int neuPosX){
<add> posX=neuPosX;
<add> }
<add>
<add> //getter-Methode fuer die x-Koordinate des Tranks
<add> public static int getPosX(){
<add> return posX;
<add> }
<add>
<add> //setter-Methode fuer die y-Koordinate des Tranks
<add> public static void setPosY(int neuPosY){
<add> posY=neuPosY;
<add> }
<add>
<add> //getter-Methode fuer die y-Koordinate des Tranks
<add> public static int getPosY(){
<add> return posY;
<add> }
<add>
<add> //Methoden fuer den Client
<add> public int getWirkung() {
<add> return wirkung;
<add> }
<add>
<add>
<add>} |
|
JavaScript | mit | 88605f63f5553464274a54d496cc8fa62b179a62 | 0 | kneath/select-autocompleter,kneath/select-autocompleter | /*
Script: select_autocompleter.js
SelectoAutocompleter provides a way to make editable combo box (a select tag in HTML).
License:
MIT-style license.
*/
/*
Class: SelectAutocompleter
To activate the control, call `new SelectAutocompleter(element, options)` on any `<select>`
tag you would like to replace. Your server will receive the same response as if the `<select>`
was not replaced, so no backend work is needed.
Any class names on the `<select>` element will be carried over to the `<input>` that replaces
it as well as the `<ul>` containing the results.
Options:
cutoffScore: A decimal between 0 and 1 determining what Quicksilver score to cut off results
for. Default is 0.1. Use higher values to show more relevant, but less results.
template: A string describing the template for the drop down list item. Default variables
available: rawText, highlightedText. Default value is "{highlightedText}"
Use in conjunction with templateAttributes to build rich autocomplete lists.
templateAttributes: An array of attributes on the `<option>` element SelectAutocompleter should use
for its template
*/
var SelectAutocompleter = new Class({
Implements: [Events, Options],
options:{
cutoffScore: 0.1,
templateAttributes: [],
template: "{highlightedText}"
},
select: null,
// The input element to autocomplete on
element: null,
// The element containing the autocomplete results
dropDown: null,
// JSON object containing key/value for autocompleter
data: {},
// Contains all the searchable terms (strings)
terms: [],
// Contains the current filtered terms from the quicksilver search
filteredTerms: [],
initialize: function(select, options){
this.select = $(select);
this.setOptions(options)
// Setup the autocompleter element
var wrapper = new Element('div', {'class': 'autocomplete'});
this.element = new Element('input', {'class': 'textfield ' + this.select.className});
this.dropDown = new Element('ul', {'class': 'auto-dropdown ' + this.select.className});
this.dropDown.setStyle('display', 'none');
this.element.addEvent('focus', this.onFocus.bind(this));
this.element.addEvent('blur', function(){ this.onBlur.delay(100, this); }.bind(this));
this.element.addEvent('keyup', this.keyListener.bind(this));
// Hide the select tag
this.select.setStyle('display', 'none');
wrapper.appendChild(this.element);
wrapper.appendChild(this.dropDown);
wrapper.inject(this.select, 'after');
// Gather the data from the select tag
this.select.getElements('option').each(function(option){
var dataItem = {}
this.options.templateAttributes.each(function(attr){
dataItem[attr] = option.getAttribute(attr);
});
this.data[option.get('text')] = $merge(dataItem, {value: option.value});
this.terms.push(option.get('text'));
}, this);
// Prepopulate the select tag's selected option
this.element.set('value', $(this.select.options[this.select.selectedIndex]).get('text'));
},
onFocus: function(){
this.element.set('value', '');
this.dropDown.setStyle('display', '');
this.updateTermsList();
this.fireEvent('onFocus');
},
onBlur: function(){
this.dropDown.setStyle('display', 'none');
if (this.termChosen != null){
this.element.set('value', this.termChosen);
this.select.set('value', this.data[this.termChosen].value);
}else{
this.element.set('value', $(this.select.options[this.select.selectedIndex]).get('text'));
}
this.fireEvent('onBlur');
},
keyListener: function(event){
// Escape means we want out!
if (event.key == "esc"){
this.onBlur();
this.element.blur();
// Up/Down arrows to navigate the list
}else if(event.key == "up" || event.key == "down"){
var choices = this.dropDown.getElements('li');
if (choices.length == 0) return;
// If there's no previous choice, or the current choice has been filtered out
if (this.highlightedChoice == null || choices.indexOf(this.highlightedChoice) == -1){
this.highlight(choices[0]);
return;
}
switch(event.key){
case "up":
// Are we at the top of the list already?
if (choices.indexOf(this.highlightedChoice) == 0){
this.highlight(choices[0]);
// Otherwise, move down one choice
}else{
this.highlight(choices[choices.indexOf(this.highlightedChoice) - 1]);
}
break;
case "down":
// Are we at the bottom of the list already?
if(choices.indexOf(this.highlightedChoice) == choices.length - 1){
this.highlight(choices[choices.length - 1]);
// Otherwise, move up one choice
}else{
this.highlight(choices[choices.indexOf(this.highlightedChoice) + 1]);
}
break;
}
// Select an item through the keyboard
}else if (event.key == "return" || event.key == "enter"){
this.termChosen = this.highlightedChoice.getAttribute('rawText');
this.element.blur();
// Regular keys (filtering for something)
}else{
this.updateTermsList();
}
},
highlight: function(elem){
if (this.highlightedChoice) this.highlightedChoice.removeClass('highlighted');
this.highlightedChoice = elem.addClass('highlighted');
},
updateTermsList: function(){
var filterValue = this.element.get('value');
this.buildFilteredTerms(filterValue);
this.dropDown.empty();
var letters = []
for(var i=0; i<filterValue.length; i++){
var letter = filterValue.substr(i, 1);
if (!letters.contains(letter)) letters.push(letter);
}
this.filteredTerms.each(function(scoredTerm){
// Build the regular expression for highlighting matching terms
var regExpString = ""
letters.each(function(letter){
regExpString += letter;
});
// Build a formatted string highlighting matches with <strong>
var formattedString = scoredTerm[1];
if (filterValue.length > 0){
var regexp = new RegExp("([" + regExpString + "])", "ig");
formattedString = formattedString.replace(regexp, "<strong>$1</strong>");
}
// Build the template
var template = {
highlightedText: formattedString,
rawText: scoredTerm[1]
}
this.options.templateAttributes.each(function(attr){
template["attr" + attr.capitalize()] = this.data[template.rawText][attr];
}, this);
// Build the output element for the dropDown
var choice = new Element('li');
choice.innerHTML = this.options.template.substitute(template);
choice.setAttribute('rawText', scoredTerm[1]);
choice.addEvent('click', function(){
this.termChosen = scoredTerm[1];
}.bind(this));
choice.addEvent('mouseover', this.highlight.bind(this, choice));
this.dropDown.appendChild(choice);
}, this);
},
buildFilteredTerms: function(filter){
this.filteredTerms = [];
// Build the terms
this.terms.each(function(term){
var score = term.toLowerCase().score(filter.toLowerCase())
if (score < this.options.cutoffScore) return;
this.filteredTerms.push([score, term]);
}, this);
// Sort the terms
this.filteredTerms.sort(function(a, b) { return b[0] - a[0]; });
}
}); | src/select_autocompleter.js | /*
Script: select_autocompleter.js
SelectoAutocompleter provides a way to make editable combo box (a select tag in HTML).
License:
MIT-style license.
*/
/*
Class: SelectAutocompleter
To activate the control, call `new SelectAutocompleter(element, options)` on any `<select>`
tag you would like to replace. Your server will receive the same response as if the `<select>`
was not replaced, so no backend work is needed.
Any class names on the `<select>` element will be carried over to the `<input>` that replaces
it as well as the `<ul>` containing the results.
Options:
cutoffScore: A decimal between 0 and 1 determining what Quicksilver score to cut off results
for. Default is 0.1. Use higher values to show more relevant, but less results.
template: A string describing the template for the drop down list item. Default variables
available: rawText, highlightedText. Default value is "{highlightedText}"
Use in conjunction with templateAttributes to build rich autocomplete lists.
templateAttributes: An array of attributes on the `<option>` element SelectAutocompleter should use
for its template
*/
var SelectAutocompleter = new Class({
Implements: [Events, Options],
options:{
cutoffScore: 0.1,
templateAttributes: [],
template: "{highlightedText}"
},
select: null,
// The input element to autocomplete on
element: null,
// The element containing the autocomplete results
dropDown: null,
// JSON object containing key/value for autocompleter
data: {},
// Contains all the searchable terms (strings)
terms: [],
// Contains the current filtered terms from the quicksilver search
filteredTerms: [],
initialize: function(select, options){
this.select = $(select);
this.setOptions(options)
// Setup the autocompleter element
var wrapper = new Element('div', {'class': 'autocomplete'});
this.element = new Element('input', {'class': 'textfield ' + this.select.className});
this.dropDown = new Element('ul', {'class': 'auto-dropdown ' + this.select.className});
this.dropDown.setStyle('display', 'none');
this.element.addEvent('focus', this.onFocus.bind(this));
this.element.addEvent('blur', function(){ this.onBlur.delay(100, this); }.bind(this));
this.element.addEvent('keyup', this.keyListener.bind(this));
// Hide the select tag
this.select.setStyle('display', 'none');
wrapper.appendChild(this.element);
wrapper.appendChild(this.dropDown);
wrapper.inject(this.select, 'after');
// Gather the data from the select tag
this.select.getElements('option').each(function(option){
var dataItem = {}
this.options.templateAttributes.each(function(attr){
dataItem[attr] = option.getAttribute(attr);
});
this.data[option.get('text')] = $merge(dataItem, {value: option.value});
this.terms.push(option.get('text'));
}, this);
// Prepopulate the select tag's selected option
this.element.set('value', $(this.select.options[this.select.selectedIndex]).get('text'));
},
onFocus: function(){
this.element.set('value', '');
this.dropDown.setStyle('display', '');
this.updateTermsList();
this.fireEvent('onFocus');
},
onBlur: function(){
this.dropDown.setStyle('display', 'none');
if (this.termChosen != null){
this.element.set('value', this.termChosen);
this.select.set('value', this.data[this.termChosen].value);
}else{
this.element.set('value', $(this.select.options[this.select.selectedIndex]).get('text'));
}
this.fireEvent('onBlur');
},
keyListener: function(event){
// Escape means we want out!
if (event.key == "esc"){
this.onBlur();
this.element.blur();
// Up/Down arrows to navigate the list
}else if(event.key == "up" || event.key == "down"){
var choices = this.dropDown.getElements('li');
if (choices.length == 0) return;
// If there's no previous choice, or the current choice has been filtered out
if (this.highlightedChoice == null || choices.indexOf(this.highlightedChoice) == -1){
this.highlight(choices[0]);
return;
}
switch(event.key){
case "up":
// Are we at the top of the list already?
if (choices.indexOf(this.highlightedChoice) == 0){
this.highlight(choices[0]);
// Otherwise, move down one choice
}else{
this.highlight(choices[choices.indexOf(this.highlightedChoice) - 1]);
}
break;
case "down":
// Are we at the bottom of the list already?
if(choices.indexOf(this.highlightedChoice) == choices.length - 1){
this.highlight(choices[choices.length - 1]);
// Otherwise, move up one choice
}else{
this.highlight(choices[choices.indexOf(this.highlightedChoice) + 1]);
}
break;
}
// Select an item through the keyboard
}else if (event.key == "return" || event.key == "enter"){
this.termChosen = this.highlightedChoice.getAttribute('rawText');
this.element.blur();
// Regular keys (filtering for something)
}else{
this.updateTermsList();
}
},
highlight: function(elem){
if (this.highlightedChoice) this.highlightedChoice.removeClass('highlighted');
this.highlightedChoice = elem.addClass('highlighted');
},
updateTermsList: function(){
var filterValue = this.element.get('value');
this.buildFilteredTerms(filterValue);
this.dropDown.empty();
var letters = []
for(var i=0; i<filterValue.length; i++){
var letter = filterValue.substr(i, 1);
if (!letters.contains(letter)) letters.push(letter);
}
this.filteredTerms.each(function(scoredTerm){
// Build the regular expression for highlighting matching terms
var regExpString = ""
letters.each(function(letter){
regExpString += letter;
});
// Build a formatted string highlighting matches with <strong>
var formattedString = scoredTerm[1];
var regexp = new RegExp("([" + regExpString + "])", "ig");
formattedString = formattedString.replace(regexp, "<strong>$1</strong>");
// Build the template
var template = {
highlightedText: formattedString,
rawText: scoredTerm[1]
}
this.options.templateAttributes.each(function(attr){
template["attr" + attr.capitalize()] = this.data[template.rawText][attr];
}, this);
// Build the output element for the dropDown
var choice = new Element('li');
choice.innerHTML = this.options.template.substitute(template);
choice.setAttribute('rawText', scoredTerm[1]);
choice.addEvent('click', function(){
this.termChosen = scoredTerm[1];
}.bind(this));
choice.addEvent('mouseover', this.highlight.bind(this, choice));
this.dropDown.appendChild(choice);
}, this);
},
buildFilteredTerms: function(filter){
this.filteredTerms = [];
// Build the terms
this.terms.each(function(term){
var score = term.toLowerCase().score(filter.toLowerCase())
if (score < this.options.cutoffScore) return;
this.filteredTerms.push([score, term]);
}, this);
// Sort the terms
this.filteredTerms.sort(function(a, b) { return b[0] - a[0]; });
}
}); | IE/Performance: do not highlight letters when there are none to highlight
| src/select_autocompleter.js | IE/Performance: do not highlight letters when there are none to highlight | <ide><path>rc/select_autocompleter.js
<ide>
<ide> // Build a formatted string highlighting matches with <strong>
<ide> var formattedString = scoredTerm[1];
<del> var regexp = new RegExp("([" + regExpString + "])", "ig");
<del> formattedString = formattedString.replace(regexp, "<strong>$1</strong>");
<add> if (filterValue.length > 0){
<add> var regexp = new RegExp("([" + regExpString + "])", "ig");
<add> formattedString = formattedString.replace(regexp, "<strong>$1</strong>");
<add> }
<ide>
<ide> // Build the template
<ide> var template = { |
|
Java | mit | ac0a87124f8d1cd2e91de3e1359302eeb7df3e63 | 0 | hsyyid/GriefPrevention,MinecraftPortCentral/GriefPrevention | /*
GriefPrevention Server Plugin for Minecraft
Copyright (C) 2012 Ryan Hamshire
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.ryanhamshire.GriefPrevention;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Explosive;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityBreakDoorEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.ExpBottleEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingBreakEvent.RemoveCause;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.vehicle.VehicleDamageEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector;
//handles events related to entities
class EntityEventHandler implements Listener
{
//convenience reference for the singleton datastore
private DataStore dataStore;
public EntityEventHandler(DataStore dataStore)
{
this.dataStore = dataStore;
}
//don't allow endermen to change blocks
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityChangeBLock(EntityChangeBlockEvent event)
{
if(!GriefPrevention.instance.config_endermenMoveBlocks && event.getEntityType() == EntityType.ENDERMAN)
{
event.setCancelled(true);
}
else if(!GriefPrevention.instance.config_silverfishBreakBlocks && event.getEntityType() == EntityType.SILVERFISH)
{
event.setCancelled(true);
}
//don't allow the wither to break blocks, when the wither is determined, too expensive to constantly check for claimed blocks
else if(event.getEntityType() == EntityType.WITHER && GriefPrevention.instance.config_claims_worldModes.get(event.getBlock().getWorld()) != ClaimsMode.Disabled)
{
event.setCancelled(true);
}
//don't allow crops to be trampled
else if(event.getTo() == Material.DIRT && event.getBlock().getType() == Material.SOIL)
{
event.setCancelled(true);
}
//sand cannon fix - when the falling block doesn't fall straight down, take additional anti-grief steps
else if (event.getEntityType() == EntityType.FALLING_BLOCK)
{
FallingBlock entity = (FallingBlock)event.getEntity();
Block block = event.getBlock();
//if changing a block TO air, this is when the falling block formed. note its original location
if(event.getTo() == Material.AIR)
{
entity.setMetadata("GP_FALLINGBLOCK", new FixedMetadataValue(GriefPrevention.instance, block.getLocation()));
}
//otherwise, the falling block is forming a block. compare new location to original source
else
{
List<MetadataValue> values = entity.getMetadata("GP_FALLINGBLOCK");
//if we're not sure where this entity came from (maybe another plugin didn't follow the standard?), allow the block to form
if(values.size() < 1) return;
Location originalLocation = (Location)(values.get(0).value());
Location newLocation = block.getLocation();
//if did not fall straight down
if(originalLocation.getBlockX() != newLocation.getBlockX() || originalLocation.getBlockZ() != newLocation.getBlockZ())
{
//in creative mode worlds, never form the block
if(GriefPrevention.instance.config_claims_worldModes.get(newLocation.getWorld()) == ClaimsMode.Creative)
{
event.setCancelled(true);
return;
}
//in other worlds, if landing in land claim, only allow if source was also in the land claim
Claim claim = this.dataStore.getClaimAt(newLocation, false, null);
if(claim != null && !claim.contains(originalLocation, false, false))
{
//when not allowed, drop as item instead of forming a block
event.setCancelled(true);
ItemStack itemStack = new ItemStack(entity.getMaterial(), 1, entity.getBlockData());
Item item = block.getWorld().dropItem(entity.getLocation(), itemStack);
item.setVelocity(new Vector());
}
}
}
}
}
//don't allow zombies to break down doors
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onZombieBreakDoor(EntityBreakDoorEvent event)
{
if(!GriefPrevention.instance.config_zombiesBreakDoors) event.setCancelled(true);
}
//don't allow entities to trample crops
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityInteract(EntityInteractEvent event)
{
Material material = event.getBlock().getType();
if(material == Material.SOIL)
{
if(!GriefPrevention.instance.config_creaturesTrampleCrops)
{
event.setCancelled(true);
}
else
{
Entity rider = event.getEntity().getPassenger();
if(rider != null && rider.getType() == EntityType.PLAYER)
{
event.setCancelled(true);
}
}
}
}
//when an entity explodes...
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityExplode(EntityExplodeEvent explodeEvent)
{
List<Block> blocks = explodeEvent.blockList();
Location location = explodeEvent.getLocation();
//FEATURE: explosions don't destroy blocks when they explode near or above sea level in standard worlds
boolean isCreeper = (explodeEvent.getEntity() != null && explodeEvent.getEntity() instanceof Creeper);
//exception for some land claims in survival worlds, see notes below
Claim originationClaim = null;
if(!GriefPrevention.instance.creativeRulesApply(location))
{
originationClaim = GriefPrevention.instance.dataStore.getClaimAt(location, false, null);
}
if( location.getWorld().getEnvironment() == Environment.NORMAL && GriefPrevention.instance.claimsEnabledForWorld(location.getWorld()) && ((isCreeper && GriefPrevention.instance.config_blockSurfaceCreeperExplosions) || (!isCreeper && GriefPrevention.instance.config_blockSurfaceOtherExplosions)))
{
for(int i = 0; i < blocks.size(); i++)
{
Block block = blocks.get(i);
if(GriefPrevention.instance.config_mods_explodableIds.Contains(new MaterialInfo(block.getTypeId(), block.getData(), null))) continue;
//in survival worlds, if claim explosions are enabled for the source claim, allow non-creeper explosions to destroy blocks in and under that claim even above sea level.
if(!isCreeper && originationClaim != null && originationClaim.areExplosivesAllowed && originationClaim.contains(block.getLocation(), true, false)) continue;
if(block.getLocation().getBlockY() > GriefPrevention.instance.getSeaLevel(location.getWorld()) - 7)
{
blocks.remove(i--);
}
}
}
//special rule for creative worlds: explosions don't destroy anything
if(GriefPrevention.instance.creativeRulesApply(explodeEvent.getLocation()))
{
for(int i = 0; i < blocks.size(); i++)
{
Block block = blocks.get(i);
if(GriefPrevention.instance.config_mods_explodableIds.Contains(new MaterialInfo(block.getTypeId(), block.getData(), null))) continue;
blocks.remove(i--);
}
}
//FEATURE: explosions don't damage claimed blocks
Claim claim = null;
for(int i = 0; i < blocks.size(); i++) //for each destroyed block
{
Block block = blocks.get(i);
if(block.getType() == Material.AIR) continue; //if it's air, we don't care
if(GriefPrevention.instance.config_mods_explodableIds.Contains(new MaterialInfo(block.getTypeId(), block.getData(), null))) continue;
claim = this.dataStore.getClaimAt(block.getLocation(), false, claim);
//if the block is claimed, remove it from the list of destroyed blocks
if(claim != null && !claim.areExplosivesAllowed)
{
blocks.remove(i--);
}
}
}
//when an item spawns...
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event)
{
//if in a creative world, cancel the event (don't drop items on the ground)
if(GriefPrevention.instance.creativeRulesApply(event.getLocation()))
{
event.setCancelled(true);
}
//if item is on watch list, apply protection
ArrayList<PendingItemProtection> watchList = GriefPrevention.instance.pendingItemWatchList;
Item newItem = event.getEntity();
Long now = null;
for(int i = 0; i < watchList.size(); i++)
{
PendingItemProtection pendingProtection = watchList.get(i);
//ignore and remove any expired pending protections
if(now == null) now = System.currentTimeMillis();
if(pendingProtection.expirationTimestamp < now)
{
watchList.remove(i--);
continue;
}
//skip if item stack doesn't match
if(pendingProtection.itemStack.getAmount() != newItem.getItemStack().getAmount() ||
pendingProtection.itemStack.getType() != newItem.getItemStack().getType())
{
continue;
}
//skip if new item location isn't near the expected spawn area
Location spawn = event.getLocation();
Location expected = pendingProtection.location;
if(!spawn.getWorld().equals(expected.getWorld()) ||
spawn.getX() < expected.getX() - 5 ||
spawn.getX() > expected.getX() + 5 ||
spawn.getZ() < expected.getZ() - 5 ||
spawn.getZ() > expected.getZ() + 5 ||
spawn.getY() < expected.getY() - 15 ||
spawn.getY() > expected.getY() + 3)
{
continue;
}
//otherwise, mark item with protection information
newItem.setMetadata("GP_ITEMOWNER", new FixedMetadataValue(GriefPrevention.instance, pendingProtection.owner));
//and remove pending protection data
watchList.remove(i);
break;
}
}
//when an experience bottle explodes...
@EventHandler(priority = EventPriority.LOWEST)
public void onExpBottle(ExpBottleEvent event)
{
//if in a creative world, cancel the event (don't drop exp on the ground)
if(GriefPrevention.instance.creativeRulesApply(event.getEntity().getLocation()))
{
event.setExperience(0);
}
}
//when a creature spawns...
@EventHandler(priority = EventPriority.LOWEST)
public void onEntitySpawn(CreatureSpawnEvent event)
{
//these rules apply only to creative worlds
if(!GriefPrevention.instance.creativeRulesApply(event.getLocation())) return;
//chicken eggs and breeding could potentially make a mess in the wilderness, once griefers get involved
SpawnReason reason = event.getSpawnReason();
if(reason != SpawnReason.SPAWNER_EGG && reason != SpawnReason.BUILD_IRONGOLEM && reason != SpawnReason.BUILD_SNOWMAN && event.getEntityType() != EntityType.ARMOR_STAND)
{
event.setCancelled(true);
return;
}
//otherwise, just apply the limit on total entities per claim (and no spawning in the wilderness!)
Claim claim = this.dataStore.getClaimAt(event.getLocation(), false, null);
if(claim == null || claim.allowMoreEntities() != null)
{
event.setCancelled(true);
return;
}
}
//when an entity dies...
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDeath(EntityDeathEvent event)
{
LivingEntity entity = event.getEntity();
//don't do the rest in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(entity.getWorld())) return;
//special rule for creative worlds: killed entities don't drop items or experience orbs
if(GriefPrevention.instance.creativeRulesApply(entity.getLocation()))
{
event.setDroppedExp(0);
event.getDrops().clear();
}
//FEATURE: when a player is involved in a siege (attacker or defender role)
//his death will end the siege
if(!(entity instanceof Player)) return; //only tracking players
Player player = (Player)entity;
PlayerData playerData = this.dataStore.getPlayerData(player.getUniqueId());
//if involved in a siege
if(playerData.siegeData != null)
{
//don't drop items as usual, they will be sent to the siege winner
event.getDrops().clear();
//end it, with the dieing player being the loser
this.dataStore.endSiege(playerData.siegeData, null, player.getName(), true /*ended due to death*/);
}
//FEATURE: lock dropped items to player who dropped them
World world = entity.getWorld();
//decide whether or not to apply this feature to this situation (depends on the world where it happens)
boolean isPvPWorld = GriefPrevention.instance.config_pvp_enabledWorlds.contains(world);
if((isPvPWorld && GriefPrevention.instance.config_lockDeathDropsInPvpWorlds) ||
(!isPvPWorld && GriefPrevention.instance.config_lockDeathDropsInNonPvpWorlds))
{
//remember information about these drops so that they can be marked when they spawn as items
long expirationTime = System.currentTimeMillis() + 3000; //now + 3 seconds
Location deathLocation = player.getLocation();
UUID playerID = player.getUniqueId();
List<ItemStack> drops = event.getDrops();
for(ItemStack stack : drops)
{
GriefPrevention.instance.pendingItemWatchList.add(
new PendingItemProtection(deathLocation, playerID, expirationTime, stack));
}
//allow the player to receive a message about how to unlock any drops
playerData.dropsAreUnlocked = false;
playerData.receivedDropUnlockAdvertisement = false;
}
}
//when an entity picks up an item
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityPickup(EntityChangeBlockEvent event)
{
//FEATURE: endermen don't steal claimed blocks
//if its an enderman
if(event.getEntity() instanceof Enderman)
{
//and the block is claimed
if(this.dataStore.getClaimAt(event.getBlock().getLocation(), false, null) != null)
{
//he doesn't get to steal it
event.setCancelled(true);
}
}
}
//when a painting is broken
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onHangingBreak(HangingBreakEvent event)
{
//don't track in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(event.getEntity().getWorld())) return;
//FEATURE: claimed paintings are protected from breakage
//explosions don't destroy hangings
if(event.getCause() == RemoveCause.EXPLOSION)
{
event.setCancelled(true);
return;
}
//only allow players to break paintings, not anything else (like water and explosions)
if(!(event instanceof HangingBreakByEntityEvent))
{
event.setCancelled(true);
return;
}
HangingBreakByEntityEvent entityEvent = (HangingBreakByEntityEvent)event;
//who is removing it?
Entity remover = entityEvent.getRemover();
//again, making sure the breaker is a player
if(!(remover instanceof Player))
{
event.setCancelled(true);
return;
}
//if the player doesn't have build permission, don't allow the breakage
Player playerRemover = (Player)entityEvent.getRemover();
String noBuildReason = GriefPrevention.instance.allowBuild(playerRemover, event.getEntity().getLocation(), Material.AIR);
if(noBuildReason != null)
{
event.setCancelled(true);
GriefPrevention.sendMessage(playerRemover, TextMode.Err, noBuildReason);
}
}
//when a painting is placed...
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPaintingPlace(HangingPlaceEvent event)
{
//don't track in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(event.getBlock().getWorld())) return;
//FEATURE: similar to above, placing a painting requires build permission in the claim
//if the player doesn't have permission, don't allow the placement
String noBuildReason = GriefPrevention.instance.allowBuild(event.getPlayer(), event.getEntity().getLocation(), Material.PAINTING);
if(noBuildReason != null)
{
event.setCancelled(true);
GriefPrevention.sendMessage(event.getPlayer(), TextMode.Err, noBuildReason);
return;
}
//otherwise, apply entity-count limitations for creative worlds
else if(GriefPrevention.instance.creativeRulesApply(event.getEntity().getLocation()))
{
PlayerData playerData = this.dataStore.getPlayerData(event.getPlayer().getUniqueId());
Claim claim = this.dataStore.getClaimAt(event.getBlock().getLocation(), false, playerData.lastClaim);
if(claim == null) return;
String noEntitiesReason = claim.allowMoreEntities();
if(noEntitiesReason != null)
{
GriefPrevention.sendMessage(event.getPlayer(), TextMode.Err, noEntitiesReason);
event.setCancelled(true);
return;
}
}
}
//when an entity is damaged
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityDamage (EntityDamageEvent event)
{
//monsters are never protected
if(event.getEntity() instanceof Monster) return;
//protect pets from environmental damage types which could be easily caused by griefers
if(event.getEntity() instanceof Tameable && !GriefPrevention.instance.config_pvp_enabledWorlds.contains(event.getEntity().getWorld()))
{
Tameable tameable = (Tameable)event.getEntity();
if(tameable.isTamed())
{
DamageCause cause = event.getCause();
if( cause != null && (
cause == DamageCause.ENTITY_EXPLOSION ||
cause == DamageCause.FALLING_BLOCK ||
cause == DamageCause.FIRE ||
cause == DamageCause.FIRE_TICK ||
cause == DamageCause.LAVA ||
cause == DamageCause.SUFFOCATION))
{
event.setCancelled(true);
return;
}
}
}
//the rest is only interested in entities damaging entities (ignoring environmental damage)
if(!(event instanceof EntityDamageByEntityEvent)) return;
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
//determine which player is attacking, if any
Player attacker = null;
Projectile arrow = null;
Entity damageSource = subEvent.getDamager();
if(damageSource != null)
{
if(damageSource instanceof Player)
{
attacker = (Player)damageSource;
}
else if(damageSource instanceof Projectile)
{
arrow = (Projectile)damageSource;
if(arrow.getShooter() instanceof Player)
{
attacker = (Player)arrow.getShooter();
}
}
}
//if the attacker is a player and defender is a player (pvp combat)
if(attacker != null && event.getEntity() instanceof Player && GriefPrevention.instance.config_pvp_enabledWorlds.contains(attacker.getWorld()))
{
//FEATURE: prevent pvp in the first minute after spawn, and prevent pvp when one or both players have no inventory
//doesn't apply when the attacker has the no pvp immunity permission
//this rule is here to allow server owners to have a world with no spawn camp protection by assigning permissions based on the player's world
if(attacker.hasPermission("griefprevention.nopvpimmunity")) return;
Player defender = (Player)(event.getEntity());
if(attacker != defender)
{
PlayerData defenderData = this.dataStore.getPlayerData(((Player)event.getEntity()).getUniqueId());
PlayerData attackerData = this.dataStore.getPlayerData(attacker.getUniqueId());
//otherwise if protecting spawning players
if(GriefPrevention.instance.config_pvp_protectFreshSpawns)
{
if(defenderData.pvpImmune)
{
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.ThatPlayerPvPImmune);
return;
}
if(attackerData.pvpImmune)
{
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.CantFightWhileImmune);
return;
}
}
//FEATURE: prevent players from engaging in PvP combat inside land claims (when it's disabled)
if(GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims || GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims)
{
Claim attackerClaim = this.dataStore.getClaimAt(attacker.getLocation(), false, attackerData.lastClaim);
if( attackerClaim != null &&
(attackerClaim.isAdminClaim() && attackerClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
attackerClaim.isAdminClaim() && attackerClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
!attackerClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
{
attackerData.lastClaim = attackerClaim;
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.CantFightWhileImmune);
return;
}
Claim defenderClaim = this.dataStore.getClaimAt(defender.getLocation(), false, defenderData.lastClaim);
if( defenderClaim != null &&
(defenderClaim.isAdminClaim() && defenderClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
defenderClaim.isAdminClaim() && defenderClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
!defenderClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
{
defenderData.lastClaim = defenderClaim;
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.PlayerInPvPSafeZone);
return;
}
}
//FEATURE: prevent players who very recently participated in pvp combat from hiding inventory to protect it from looting
//FEATURE: prevent players who are in pvp combat from logging out to avoid being defeated
long now = Calendar.getInstance().getTimeInMillis();
defenderData.lastPvpTimestamp = now;
defenderData.lastPvpPlayer = attacker.getName();
attackerData.lastPvpTimestamp = now;
attackerData.lastPvpPlayer = defender.getName();
}
}
//FEATURE: protect claimed animals, boats, minecarts, and items inside item frames
//NOTE: animals can be lead with wheat, vehicles can be pushed around.
//so unless precautions are taken by the owner, a resourceful thief might find ways to steal anyway
//if theft protection is enabled
if(event instanceof EntityDamageByEntityEvent)
{
//don't track in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(event.getEntity().getWorld())) return;
//if the damaged entity is a claimed item frame or armor stand, the damager needs to be a player with container trust in the claim
if(subEvent.getEntityType() == EntityType.ITEM_FRAME
|| subEvent.getEntityType() == EntityType.ARMOR_STAND
|| subEvent.getEntityType() == EntityType.VILLAGER)
{
//decide whether it's claimed
Claim cachedClaim = null;
PlayerData playerData = null;
if(attacker != null)
{
playerData = this.dataStore.getPlayerData(attacker.getUniqueId());
cachedClaim = playerData.lastClaim;
}
Claim claim = this.dataStore.getClaimAt(event.getEntity().getLocation(), false, cachedClaim);
//if it's claimed
if(claim != null)
{
//if attacker isn't a player, cancel
if(attacker == null)
{
event.setCancelled(true);
return;
}
//otherwise player must have container trust in the claim
String failureReason = claim.allowBuild(attacker, Material.AIR);
if(failureReason != null)
{
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, failureReason);
return;
}
}
}
//if the entity is an non-monster creature (remember monsters disqualified above), or a vehicle
if ((subEvent.getEntity() instanceof Creature && GriefPrevention.instance.config_claims_protectCreatures))
{
//if entity is tameable and has an owner, apply special rules
if(subEvent.getEntity() instanceof Tameable && !GriefPrevention.instance.config_pvp_enabledWorlds.contains(subEvent.getEntity().getWorld()))
{
Tameable tameable = (Tameable)subEvent.getEntity();
if(tameable.isTamed() && tameable.getOwner() != null)
{
//limit attacks by players to owners and admins in ignore claims mode
if(attacker != null)
{
UUID ownerID = tameable.getOwner().getUniqueId();
//if the player interacting is the owner, always allow
if(attacker.getUniqueId().equals(ownerID)) return;
//allow for admin override
PlayerData attackerData = this.dataStore.getPlayerData(attacker.getUniqueId());
if(attackerData.ignoreClaims) return;
//otherwise disallow in non-pvp worlds
if(!GriefPrevention.instance.config_pvp_enabledWorlds.contains(subEvent.getEntity().getLocation().getWorld()))
{
OfflinePlayer owner = GriefPrevention.instance.getServer().getOfflinePlayer(ownerID);
String ownerName = owner.getName();
if(ownerName == null) ownerName = "someone";
String message = GriefPrevention.instance.dataStore.getMessage(Messages.NoDamageClaimedEntity, ownerName);
if(attacker.hasPermission("griefprevention.ignoreclaims"))
message += " " + GriefPrevention.instance.dataStore.getMessage(Messages.IgnoreClaimsAdvertisement);
GriefPrevention.sendMessage(attacker, TextMode.Err, message);
event.setCancelled(true);
return;
}
}
}
}
Claim cachedClaim = null;
PlayerData playerData = null;
//if not a player or an explosive, allow
if(attacker == null && damageSource != null && damageSource.getType() != EntityType.CREEPER && !(damageSource instanceof Explosive))
{
return;
}
if(attacker != null)
{
playerData = this.dataStore.getPlayerData(attacker.getUniqueId());
cachedClaim = playerData.lastClaim;
}
Claim claim = this.dataStore.getClaimAt(event.getEntity().getLocation(), false, cachedClaim);
//if it's claimed
if(claim != null)
{
//if damaged by anything other than a player (exception villagers injured by zombies in admin claims), cancel the event
//why exception? so admins can set up a village which can't be CHANGED by players, but must be "protected" by players.
if(attacker == null)
{
//exception case
if(event.getEntity() instanceof Villager && damageSource != null && damageSource instanceof Monster && claim.isAdminClaim())
{
return;
}
//all other cases
else
{
event.setCancelled(true);
}
}
//otherwise the player damaging the entity must have permission
else
{
String noContainersReason = claim.allowContainers(attacker);
if(noContainersReason != null)
{
event.setCancelled(true);
//kill the arrow to avoid infinite bounce between crowded together animals
if(arrow != null) arrow.remove();
String message = GriefPrevention.instance.dataStore.getMessage(Messages.NoDamageClaimedEntity, claim.getOwnerName());
if(attacker.hasPermission("griefprevention.ignoreclaims"))
message += " " + GriefPrevention.instance.dataStore.getMessage(Messages.IgnoreClaimsAdvertisement);
GriefPrevention.sendMessage(attacker, TextMode.Err, message);
event.setCancelled(true);
}
//cache claim for later
if(playerData != null)
{
playerData.lastClaim = claim;
}
}
}
}
}
}
//when a vehicle is damaged
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onVehicleDamage (VehicleDamageEvent event)
{
//all of this is anti theft code
if(!GriefPrevention.instance.config_claims_preventTheft) return;
//input validation
if(event.getVehicle() == null) return;
//don't track in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(event.getVehicle().getWorld())) return;
//determine which player is attacking, if any
Player attacker = null;
Entity damageSource = event.getAttacker();
EntityType damageSourceType = null;
//if damage source is null or a creeper, don't allow the damage when the vehicle is in a land claim
if(damageSource != null)
{
damageSourceType = damageSource.getType();
if(damageSource.getType() == EntityType.PLAYER)
{
attacker = (Player)damageSource;
}
else if(damageSource instanceof Projectile)
{
Projectile arrow = (Projectile)damageSource;
if(arrow.getShooter() instanceof Player)
{
attacker = (Player)arrow.getShooter();
}
}
}
//if not a player and not an explosion, always allow
if(attacker == null && damageSourceType != EntityType.CREEPER && damageSourceType != EntityType.PRIMED_TNT)
{
return;
}
//NOTE: vehicles can be pushed around.
//so unless precautions are taken by the owner, a resourceful thief might find ways to steal anyway
Claim cachedClaim = null;
PlayerData playerData = null;
if(attacker != null)
{
playerData = this.dataStore.getPlayerData(attacker.getUniqueId());
cachedClaim = playerData.lastClaim;
}
Claim claim = this.dataStore.getClaimAt(event.getVehicle().getLocation(), false, cachedClaim);
//if it's claimed
if(claim != null)
{
//if damaged by anything other than a player, cancel the event
if(attacker == null)
{
event.setCancelled(true);
}
//otherwise the player damaging the entity must have permission
else
{
String noContainersReason = claim.allowContainers(attacker);
if(noContainersReason != null)
{
event.setCancelled(true);
String message = GriefPrevention.instance.dataStore.getMessage(Messages.NoDamageClaimedEntity, claim.getOwnerName());
if(attacker.hasPermission("griefprevention.ignoreclaims"))
message += " " + GriefPrevention.instance.dataStore.getMessage(Messages.IgnoreClaimsAdvertisement);
GriefPrevention.sendMessage(attacker, TextMode.Err, message);
event.setCancelled(true);
}
//cache claim for later
if(playerData != null)
{
playerData.lastClaim = claim;
}
}
}
}
//when a splash potion effects one or more entities...
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPotionSplash (PotionSplashEvent event)
{
ThrownPotion potion = event.getPotion();
//ignore potions not thrown by players
ProjectileSource projectileSource = potion.getShooter();
if(projectileSource == null || !(projectileSource instanceof Player)) return;
Player thrower = (Player)projectileSource;
Collection<PotionEffect> effects = potion.getEffects();
for(PotionEffect effect : effects)
{
PotionEffectType effectType = effect.getType();
//restrict jump potions on claimed animals (griefers could use this to steal animals over fences)
if(effectType == PotionEffectType.JUMP)
{
for(LivingEntity effected : event.getAffectedEntities())
{
Claim cachedClaim = null;
if(effected instanceof Animals)
{
Claim claim = this.dataStore.getClaimAt(effected.getLocation(), false, cachedClaim);
if(claim != null)
{
cachedClaim = claim;
if(claim.allowContainers(thrower) != null)
{
event.setCancelled(true);
return;
}
}
}
}
}
//otherwise, no restrictions for positive effects
if(positiveEffects.contains(effectType)) continue;
for(LivingEntity effected : event.getAffectedEntities())
{
//always impact the thrower
if(effected == thrower) continue;
//always impact non players
if(!(effected instanceof Player)) continue;
//otherwise if in no-pvp zone, stop effect
//FEATURE: prevent players from engaging in PvP combat inside land claims (when it's disabled)
else if(GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims || GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims)
{
Player effectedPlayer = (Player)effected;
PlayerData defenderData = this.dataStore.getPlayerData(effectedPlayer.getUniqueId());
PlayerData attackerData = this.dataStore.getPlayerData(thrower.getUniqueId());
Claim attackerClaim = this.dataStore.getClaimAt(thrower.getLocation(), false, attackerData.lastClaim);
if( attackerClaim != null &&
(attackerClaim.isAdminClaim() && attackerClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
attackerClaim.isAdminClaim() && attackerClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
!attackerClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
{
attackerData.lastClaim = attackerClaim;
event.setIntensity(effected, 0);
GriefPrevention.sendMessage(thrower, TextMode.Err, Messages.CantFightWhileImmune);
continue;
}
Claim defenderClaim = this.dataStore.getClaimAt(effectedPlayer.getLocation(), false, defenderData.lastClaim);
if( defenderClaim != null &&
(defenderClaim.isAdminClaim() && defenderClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
defenderClaim.isAdminClaim() && defenderClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
!defenderClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
{
defenderData.lastClaim = defenderClaim;
event.setIntensity(effected, 0);
GriefPrevention.sendMessage(thrower, TextMode.Err, Messages.PlayerInPvPSafeZone);
continue;
}
}
}
}
}
private static final HashSet<PotionEffectType> positiveEffects = new HashSet<PotionEffectType>(Arrays.asList
(
PotionEffectType.ABSORPTION,
PotionEffectType.DAMAGE_RESISTANCE,
PotionEffectType.FAST_DIGGING,
PotionEffectType.FIRE_RESISTANCE,
PotionEffectType.HEAL,
PotionEffectType.HEALTH_BOOST,
PotionEffectType.INCREASE_DAMAGE,
PotionEffectType.INVISIBILITY,
PotionEffectType.JUMP,
PotionEffectType.NIGHT_VISION,
PotionEffectType.REGENERATION,
PotionEffectType.SATURATION,
PotionEffectType.SPEED,
PotionEffectType.WATER_BREATHING
));
}
| src/me/ryanhamshire/GriefPrevention/EntityEventHandler.java | /*
GriefPrevention Server Plugin for Minecraft
Copyright (C) 2012 Ryan Hamshire
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.ryanhamshire.GriefPrevention;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Explosive;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityBreakDoorEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.ExpBottleEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingBreakEvent.RemoveCause;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.vehicle.VehicleDamageEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector;
//handles events related to entities
class EntityEventHandler implements Listener
{
//convenience reference for the singleton datastore
private DataStore dataStore;
public EntityEventHandler(DataStore dataStore)
{
this.dataStore = dataStore;
}
//don't allow endermen to change blocks
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityChangeBLock(EntityChangeBlockEvent event)
{
if(!GriefPrevention.instance.config_endermenMoveBlocks && event.getEntityType() == EntityType.ENDERMAN)
{
event.setCancelled(true);
}
else if(!GriefPrevention.instance.config_silverfishBreakBlocks && event.getEntityType() == EntityType.SILVERFISH)
{
event.setCancelled(true);
}
//don't allow the wither to break blocks, when the wither is determined, too expensive to constantly check for claimed blocks
else if(event.getEntityType() == EntityType.WITHER && GriefPrevention.instance.config_claims_worldModes.get(event.getBlock().getWorld()) != ClaimsMode.Disabled)
{
event.setCancelled(true);
}
//don't allow crops to be trampled
else if(event.getTo() == Material.DIRT && event.getBlock().getType() == Material.SOIL)
{
event.setCancelled(true);
}
//sand cannon fix - when the falling block doesn't fall straight down, take additional anti-grief steps
else if (event.getEntityType() == EntityType.FALLING_BLOCK)
{
FallingBlock entity = (FallingBlock)event.getEntity();
Block block = event.getBlock();
//if changing a block TO air, this is when the falling block formed. note its original location
if(event.getTo() == Material.AIR)
{
entity.setMetadata("GP_FALLINGBLOCK", new FixedMetadataValue(GriefPrevention.instance, block.getLocation()));
}
//otherwise, the falling block is forming a block. compare new location to original source
else
{
List<MetadataValue> values = entity.getMetadata("GP_FALLINGBLOCK");
//if we're not sure where this entity came from (maybe another plugin didn't follow the standard?), allow the block to form
if(values.size() < 1) return;
Location originalLocation = (Location)(values.get(0).value());
Location newLocation = block.getLocation();
//if did not fall straight down
if(originalLocation.getBlockX() != newLocation.getBlockX() || originalLocation.getBlockZ() != newLocation.getBlockZ())
{
//in creative mode worlds, never form the block
if(GriefPrevention.instance.config_claims_worldModes.get(newLocation.getWorld()) == ClaimsMode.Creative)
{
event.setCancelled(true);
return;
}
//in other worlds, if landing in land claim, only allow if source was also in the land claim
Claim claim = this.dataStore.getClaimAt(newLocation, false, null);
if(claim != null && !claim.contains(originalLocation, false, false))
{
//when not allowed, drop as item instead of forming a block
event.setCancelled(true);
ItemStack itemStack = new ItemStack(entity.getMaterial(), 1, entity.getBlockData());
Item item = block.getWorld().dropItem(entity.getLocation(), itemStack);
item.setVelocity(new Vector());
}
}
}
}
}
//don't allow zombies to break down doors
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onZombieBreakDoor(EntityBreakDoorEvent event)
{
if(!GriefPrevention.instance.config_zombiesBreakDoors) event.setCancelled(true);
}
//don't allow entities to trample crops
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityInteract(EntityInteractEvent event)
{
Material material = event.getBlock().getType();
if(material == Material.SOIL)
{
if(!GriefPrevention.instance.config_creaturesTrampleCrops)
{
event.setCancelled(true);
}
else
{
Entity rider = event.getEntity().getPassenger();
if(rider != null && rider.getType() == EntityType.PLAYER)
{
event.setCancelled(true);
}
}
}
}
//when an entity explodes...
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityExplode(EntityExplodeEvent explodeEvent)
{
List<Block> blocks = explodeEvent.blockList();
Location location = explodeEvent.getLocation();
//FEATURE: explosions don't destroy blocks when they explode near or above sea level in standard worlds
boolean isCreeper = (explodeEvent.getEntity() != null && explodeEvent.getEntity() instanceof Creeper);
//exception for some land claims in survival worlds, see notes below
Claim originationClaim = null;
if(!GriefPrevention.instance.creativeRulesApply(location))
{
originationClaim = GriefPrevention.instance.dataStore.getClaimAt(location, false, null);
}
if( location.getWorld().getEnvironment() == Environment.NORMAL && GriefPrevention.instance.claimsEnabledForWorld(location.getWorld()) && ((isCreeper && GriefPrevention.instance.config_blockSurfaceCreeperExplosions) || (!isCreeper && GriefPrevention.instance.config_blockSurfaceOtherExplosions)))
{
for(int i = 0; i < blocks.size(); i++)
{
Block block = blocks.get(i);
if(GriefPrevention.instance.config_mods_explodableIds.Contains(new MaterialInfo(block.getTypeId(), block.getData(), null))) continue;
//in survival worlds, if claim explosions are enabled for the source claim, allow non-creeper explosions to destroy blocks in and under that claim even above sea level.
if(!isCreeper && originationClaim != null && originationClaim.areExplosivesAllowed && originationClaim.contains(block.getLocation(), true, false)) continue;
if(block.getLocation().getBlockY() > GriefPrevention.instance.getSeaLevel(location.getWorld()) - 7)
{
blocks.remove(i--);
}
}
}
//special rule for creative worlds: explosions don't destroy anything
if(GriefPrevention.instance.creativeRulesApply(explodeEvent.getLocation()))
{
for(int i = 0; i < blocks.size(); i++)
{
Block block = blocks.get(i);
if(GriefPrevention.instance.config_mods_explodableIds.Contains(new MaterialInfo(block.getTypeId(), block.getData(), null))) continue;
blocks.remove(i--);
}
}
//FEATURE: explosions don't damage claimed blocks
Claim claim = null;
for(int i = 0; i < blocks.size(); i++) //for each destroyed block
{
Block block = blocks.get(i);
if(block.getType() == Material.AIR) continue; //if it's air, we don't care
if(GriefPrevention.instance.config_mods_explodableIds.Contains(new MaterialInfo(block.getTypeId(), block.getData(), null))) continue;
claim = this.dataStore.getClaimAt(block.getLocation(), false, claim);
//if the block is claimed, remove it from the list of destroyed blocks
if(claim != null && !claim.areExplosivesAllowed)
{
blocks.remove(i--);
}
}
}
//when an item spawns...
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event)
{
//if in a creative world, cancel the event (don't drop items on the ground)
if(GriefPrevention.instance.creativeRulesApply(event.getLocation()))
{
event.setCancelled(true);
}
//if item is on watch list, apply protection
ArrayList<PendingItemProtection> watchList = GriefPrevention.instance.pendingItemWatchList;
Item newItem = event.getEntity();
Long now = null;
for(int i = 0; i < watchList.size(); i++)
{
PendingItemProtection pendingProtection = watchList.get(i);
//ignore and remove any expired pending protections
if(now == null) now = System.currentTimeMillis();
if(pendingProtection.expirationTimestamp < now)
{
watchList.remove(i--);
continue;
}
//skip if item stack doesn't match
if(pendingProtection.itemStack.getAmount() != newItem.getItemStack().getAmount() ||
pendingProtection.itemStack.getType() != newItem.getItemStack().getType())
{
continue;
}
//skip if new item location isn't near the expected spawn area
Location spawn = event.getLocation();
Location expected = pendingProtection.location;
if(!spawn.getWorld().equals(expected.getWorld()) ||
spawn.getX() < expected.getX() - 5 ||
spawn.getX() > expected.getX() + 5 ||
spawn.getZ() < expected.getZ() - 5 ||
spawn.getZ() > expected.getZ() + 5 ||
spawn.getY() < expected.getY() - 15 ||
spawn.getY() > expected.getY() + 3)
{
continue;
}
//otherwise, mark item with protection information
newItem.setMetadata("GP_ITEMOWNER", new FixedMetadataValue(GriefPrevention.instance, pendingProtection.owner));
//and remove pending protection data
watchList.remove(i);
break;
}
}
//when an experience bottle explodes...
@EventHandler(priority = EventPriority.LOWEST)
public void onExpBottle(ExpBottleEvent event)
{
//if in a creative world, cancel the event (don't drop exp on the ground)
if(GriefPrevention.instance.creativeRulesApply(event.getEntity().getLocation()))
{
event.setExperience(0);
}
}
//when a creature spawns...
@EventHandler(priority = EventPriority.LOWEST)
public void onEntitySpawn(CreatureSpawnEvent event)
{
//these rules apply only to creative worlds
if(!GriefPrevention.instance.creativeRulesApply(event.getLocation())) return;
//chicken eggs and breeding could potentially make a mess in the wilderness, once griefers get involved
SpawnReason reason = event.getSpawnReason();
if(reason != SpawnReason.SPAWNER_EGG && reason != SpawnReason.BUILD_IRONGOLEM && reason != SpawnReason.BUILD_SNOWMAN && event.getEntityType() != EntityType.ARMOR_STAND)
{
event.setCancelled(true);
return;
}
//otherwise, just apply the limit on total entities per claim (and no spawning in the wilderness!)
Claim claim = this.dataStore.getClaimAt(event.getLocation(), false, null);
if(claim == null || claim.allowMoreEntities() != null)
{
event.setCancelled(true);
return;
}
}
//when an entity dies...
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDeath(EntityDeathEvent event)
{
LivingEntity entity = event.getEntity();
//don't do the rest in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(entity.getWorld())) return;
//special rule for creative worlds: killed entities don't drop items or experience orbs
if(GriefPrevention.instance.creativeRulesApply(entity.getLocation()))
{
event.setDroppedExp(0);
event.getDrops().clear();
}
//FEATURE: when a player is involved in a siege (attacker or defender role)
//his death will end the siege
if(!(entity instanceof Player)) return; //only tracking players
Player player = (Player)entity;
PlayerData playerData = this.dataStore.getPlayerData(player.getUniqueId());
//if involved in a siege
if(playerData.siegeData != null)
{
//don't drop items as usual, they will be sent to the siege winner
event.getDrops().clear();
//end it, with the dieing player being the loser
this.dataStore.endSiege(playerData.siegeData, null, player.getName(), true /*ended due to death*/);
}
//FEATURE: lock dropped items to player who dropped them
World world = entity.getWorld();
//decide whether or not to apply this feature to this situation (depends on the world where it happens)
boolean isPvPWorld = GriefPrevention.instance.config_pvp_enabledWorlds.contains(world);
if((isPvPWorld && GriefPrevention.instance.config_lockDeathDropsInPvpWorlds) ||
(!isPvPWorld && GriefPrevention.instance.config_lockDeathDropsInNonPvpWorlds))
{
//remember information about these drops so that they can be marked when they spawn as items
long expirationTime = System.currentTimeMillis() + 3000; //now + 3 seconds
Location deathLocation = player.getLocation();
UUID playerID = player.getUniqueId();
List<ItemStack> drops = event.getDrops();
for(ItemStack stack : drops)
{
GriefPrevention.instance.pendingItemWatchList.add(
new PendingItemProtection(deathLocation, playerID, expirationTime, stack));
}
//allow the player to receive a message about how to unlock any drops
playerData.dropsAreUnlocked = false;
playerData.receivedDropUnlockAdvertisement = false;
}
}
//when an entity picks up an item
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityPickup(EntityChangeBlockEvent event)
{
//FEATURE: endermen don't steal claimed blocks
//if its an enderman
if(event.getEntity() instanceof Enderman)
{
//and the block is claimed
if(this.dataStore.getClaimAt(event.getBlock().getLocation(), false, null) != null)
{
//he doesn't get to steal it
event.setCancelled(true);
}
}
}
//when a painting is broken
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onHangingBreak(HangingBreakEvent event)
{
//don't track in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(event.getEntity().getWorld())) return;
//FEATURE: claimed paintings are protected from breakage
//explosions don't destroy hangings
if(event.getCause() == RemoveCause.EXPLOSION)
{
event.setCancelled(true);
return;
}
//only allow players to break paintings, not anything else (like water and explosions)
if(!(event instanceof HangingBreakByEntityEvent))
{
event.setCancelled(true);
return;
}
HangingBreakByEntityEvent entityEvent = (HangingBreakByEntityEvent)event;
//who is removing it?
Entity remover = entityEvent.getRemover();
//again, making sure the breaker is a player
if(!(remover instanceof Player))
{
event.setCancelled(true);
return;
}
//if the player doesn't have build permission, don't allow the breakage
Player playerRemover = (Player)entityEvent.getRemover();
String noBuildReason = GriefPrevention.instance.allowBuild(playerRemover, event.getEntity().getLocation(), Material.AIR);
if(noBuildReason != null)
{
event.setCancelled(true);
GriefPrevention.sendMessage(playerRemover, TextMode.Err, noBuildReason);
}
}
//when a painting is placed...
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPaintingPlace(HangingPlaceEvent event)
{
//don't track in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(event.getBlock().getWorld())) return;
//FEATURE: similar to above, placing a painting requires build permission in the claim
//if the player doesn't have permission, don't allow the placement
String noBuildReason = GriefPrevention.instance.allowBuild(event.getPlayer(), event.getEntity().getLocation(), Material.PAINTING);
if(noBuildReason != null)
{
event.setCancelled(true);
GriefPrevention.sendMessage(event.getPlayer(), TextMode.Err, noBuildReason);
return;
}
//otherwise, apply entity-count limitations for creative worlds
else if(GriefPrevention.instance.creativeRulesApply(event.getEntity().getLocation()))
{
PlayerData playerData = this.dataStore.getPlayerData(event.getPlayer().getUniqueId());
Claim claim = this.dataStore.getClaimAt(event.getBlock().getLocation(), false, playerData.lastClaim);
if(claim == null) return;
String noEntitiesReason = claim.allowMoreEntities();
if(noEntitiesReason != null)
{
GriefPrevention.sendMessage(event.getPlayer(), TextMode.Err, noEntitiesReason);
event.setCancelled(true);
return;
}
}
}
//when an entity is damaged
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityDamage (EntityDamageEvent event)
{
//monsters are never protected
if(event.getEntity() instanceof Monster) return;
//protect pets from environmental damage types which could be easily caused by griefers
if(event.getEntity() instanceof Tameable && !GriefPrevention.instance.config_pvp_enabledWorlds.contains(event.getEntity().getWorld()))
{
Tameable tameable = (Tameable)event.getEntity();
if(tameable.isTamed())
{
DamageCause cause = event.getCause();
if( cause != null && (
cause == DamageCause.ENTITY_EXPLOSION ||
cause == DamageCause.FALLING_BLOCK ||
cause == DamageCause.FIRE ||
cause == DamageCause.FIRE_TICK ||
cause == DamageCause.LAVA ||
cause == DamageCause.SUFFOCATION))
{
event.setCancelled(true);
return;
}
}
}
//the rest is only interested in entities damaging entities (ignoring environmental damage)
if(!(event instanceof EntityDamageByEntityEvent)) return;
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
//determine which player is attacking, if any
Player attacker = null;
Projectile arrow = null;
Entity damageSource = subEvent.getDamager();
if(damageSource != null)
{
if(damageSource instanceof Player)
{
attacker = (Player)damageSource;
}
else if(damageSource instanceof Projectile)
{
arrow = (Projectile)damageSource;
if(arrow.getShooter() instanceof Player)
{
attacker = (Player)arrow.getShooter();
}
}
}
//if the attacker is a player and defender is a player (pvp combat)
if(attacker != null && event.getEntity() instanceof Player && GriefPrevention.instance.config_pvp_enabledWorlds.contains(attacker.getWorld()))
{
//FEATURE: prevent pvp in the first minute after spawn, and prevent pvp when one or both players have no inventory
//doesn't apply when the attacker has the no pvp immunity permission
//this rule is here to allow server owners to have a world with no spawn camp protection by assigning permissions based on the player's world
if(attacker.hasPermission("griefprevention.nopvpimmunity")) return;
Player defender = (Player)(event.getEntity());
PlayerData defenderData = this.dataStore.getPlayerData(((Player)event.getEntity()).getUniqueId());
PlayerData attackerData = this.dataStore.getPlayerData(attacker.getUniqueId());
//otherwise if protecting spawning players
if(GriefPrevention.instance.config_pvp_protectFreshSpawns)
{
if(defenderData.pvpImmune)
{
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.ThatPlayerPvPImmune);
return;
}
if(attackerData.pvpImmune)
{
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.CantFightWhileImmune);
return;
}
}
//FEATURE: prevent players from engaging in PvP combat inside land claims (when it's disabled)
if(GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims || GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims)
{
Claim attackerClaim = this.dataStore.getClaimAt(attacker.getLocation(), false, attackerData.lastClaim);
if( attackerClaim != null &&
(attackerClaim.isAdminClaim() && attackerClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
attackerClaim.isAdminClaim() && attackerClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
!attackerClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
{
attackerData.lastClaim = attackerClaim;
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.CantFightWhileImmune);
return;
}
Claim defenderClaim = this.dataStore.getClaimAt(defender.getLocation(), false, defenderData.lastClaim);
if( defenderClaim != null &&
(defenderClaim.isAdminClaim() && defenderClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
defenderClaim.isAdminClaim() && defenderClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
!defenderClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
{
defenderData.lastClaim = defenderClaim;
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.PlayerInPvPSafeZone);
return;
}
}
//FEATURE: prevent players who very recently participated in pvp combat from hiding inventory to protect it from looting
//FEATURE: prevent players who are in pvp combat from logging out to avoid being defeated
long now = Calendar.getInstance().getTimeInMillis();
defenderData.lastPvpTimestamp = now;
defenderData.lastPvpPlayer = attacker.getName();
attackerData.lastPvpTimestamp = now;
attackerData.lastPvpPlayer = defender.getName();
}
//FEATURE: protect claimed animals, boats, minecarts, and items inside item frames
//NOTE: animals can be lead with wheat, vehicles can be pushed around.
//so unless precautions are taken by the owner, a resourceful thief might find ways to steal anyway
//if theft protection is enabled
if(event instanceof EntityDamageByEntityEvent)
{
//don't track in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(event.getEntity().getWorld())) return;
//if the damaged entity is a claimed item frame or armor stand, the damager needs to be a player with container trust in the claim
if(subEvent.getEntityType() == EntityType.ITEM_FRAME
|| subEvent.getEntityType() == EntityType.ARMOR_STAND
|| subEvent.getEntityType() == EntityType.VILLAGER)
{
//decide whether it's claimed
Claim cachedClaim = null;
PlayerData playerData = null;
if(attacker != null)
{
playerData = this.dataStore.getPlayerData(attacker.getUniqueId());
cachedClaim = playerData.lastClaim;
}
Claim claim = this.dataStore.getClaimAt(event.getEntity().getLocation(), false, cachedClaim);
//if it's claimed
if(claim != null)
{
//if attacker isn't a player, cancel
if(attacker == null)
{
event.setCancelled(true);
return;
}
//otherwise player must have container trust in the claim
String failureReason = claim.allowBuild(attacker, Material.AIR);
if(failureReason != null)
{
event.setCancelled(true);
GriefPrevention.sendMessage(attacker, TextMode.Err, failureReason);
return;
}
}
}
//if the entity is an non-monster creature (remember monsters disqualified above), or a vehicle
if ((subEvent.getEntity() instanceof Creature && GriefPrevention.instance.config_claims_protectCreatures))
{
//if entity is tameable and has an owner, apply special rules
if(subEvent.getEntity() instanceof Tameable && !GriefPrevention.instance.config_pvp_enabledWorlds.contains(subEvent.getEntity().getWorld()))
{
Tameable tameable = (Tameable)subEvent.getEntity();
if(tameable.isTamed() && tameable.getOwner() != null)
{
//limit attacks by players to owners and admins in ignore claims mode
if(attacker != null)
{
UUID ownerID = tameable.getOwner().getUniqueId();
//if the player interacting is the owner, always allow
if(attacker.getUniqueId().equals(ownerID)) return;
//allow for admin override
PlayerData attackerData = this.dataStore.getPlayerData(attacker.getUniqueId());
if(attackerData.ignoreClaims) return;
//otherwise disallow in non-pvp worlds
if(!GriefPrevention.instance.config_pvp_enabledWorlds.contains(subEvent.getEntity().getLocation().getWorld()))
{
OfflinePlayer owner = GriefPrevention.instance.getServer().getOfflinePlayer(ownerID);
String ownerName = owner.getName();
if(ownerName == null) ownerName = "someone";
String message = GriefPrevention.instance.dataStore.getMessage(Messages.NoDamageClaimedEntity, ownerName);
if(attacker.hasPermission("griefprevention.ignoreclaims"))
message += " " + GriefPrevention.instance.dataStore.getMessage(Messages.IgnoreClaimsAdvertisement);
GriefPrevention.sendMessage(attacker, TextMode.Err, message);
event.setCancelled(true);
return;
}
}
}
}
Claim cachedClaim = null;
PlayerData playerData = null;
//if not a player or an explosive, allow
if(attacker == null && damageSource != null && damageSource.getType() != EntityType.CREEPER && !(damageSource instanceof Explosive))
{
return;
}
if(attacker != null)
{
playerData = this.dataStore.getPlayerData(attacker.getUniqueId());
cachedClaim = playerData.lastClaim;
}
Claim claim = this.dataStore.getClaimAt(event.getEntity().getLocation(), false, cachedClaim);
//if it's claimed
if(claim != null)
{
//if damaged by anything other than a player (exception villagers injured by zombies in admin claims), cancel the event
//why exception? so admins can set up a village which can't be CHANGED by players, but must be "protected" by players.
if(attacker == null)
{
//exception case
if(event.getEntity() instanceof Villager && damageSource != null && damageSource instanceof Monster && claim.isAdminClaim())
{
return;
}
//all other cases
else
{
event.setCancelled(true);
}
}
//otherwise the player damaging the entity must have permission
else
{
String noContainersReason = claim.allowContainers(attacker);
if(noContainersReason != null)
{
event.setCancelled(true);
//kill the arrow to avoid infinite bounce between crowded together animals
if(arrow != null) arrow.remove();
String message = GriefPrevention.instance.dataStore.getMessage(Messages.NoDamageClaimedEntity, claim.getOwnerName());
if(attacker.hasPermission("griefprevention.ignoreclaims"))
message += " " + GriefPrevention.instance.dataStore.getMessage(Messages.IgnoreClaimsAdvertisement);
GriefPrevention.sendMessage(attacker, TextMode.Err, message);
event.setCancelled(true);
}
//cache claim for later
if(playerData != null)
{
playerData.lastClaim = claim;
}
}
}
}
}
}
//when a vehicle is damaged
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onVehicleDamage (VehicleDamageEvent event)
{
//all of this is anti theft code
if(!GriefPrevention.instance.config_claims_preventTheft) return;
//input validation
if(event.getVehicle() == null) return;
//don't track in worlds where claims are not enabled
if(!GriefPrevention.instance.claimsEnabledForWorld(event.getVehicle().getWorld())) return;
//determine which player is attacking, if any
Player attacker = null;
Entity damageSource = event.getAttacker();
EntityType damageSourceType = null;
//if damage source is null or a creeper, don't allow the damage when the vehicle is in a land claim
if(damageSource != null)
{
damageSourceType = damageSource.getType();
if(damageSource.getType() == EntityType.PLAYER)
{
attacker = (Player)damageSource;
}
else if(damageSource instanceof Projectile)
{
Projectile arrow = (Projectile)damageSource;
if(arrow.getShooter() instanceof Player)
{
attacker = (Player)arrow.getShooter();
}
}
}
//if not a player and not an explosion, always allow
if(attacker == null && damageSourceType != EntityType.CREEPER && damageSourceType != EntityType.PRIMED_TNT)
{
return;
}
//NOTE: vehicles can be pushed around.
//so unless precautions are taken by the owner, a resourceful thief might find ways to steal anyway
Claim cachedClaim = null;
PlayerData playerData = null;
if(attacker != null)
{
playerData = this.dataStore.getPlayerData(attacker.getUniqueId());
cachedClaim = playerData.lastClaim;
}
Claim claim = this.dataStore.getClaimAt(event.getVehicle().getLocation(), false, cachedClaim);
//if it's claimed
if(claim != null)
{
//if damaged by anything other than a player, cancel the event
if(attacker == null)
{
event.setCancelled(true);
}
//otherwise the player damaging the entity must have permission
else
{
String noContainersReason = claim.allowContainers(attacker);
if(noContainersReason != null)
{
event.setCancelled(true);
String message = GriefPrevention.instance.dataStore.getMessage(Messages.NoDamageClaimedEntity, claim.getOwnerName());
if(attacker.hasPermission("griefprevention.ignoreclaims"))
message += " " + GriefPrevention.instance.dataStore.getMessage(Messages.IgnoreClaimsAdvertisement);
GriefPrevention.sendMessage(attacker, TextMode.Err, message);
event.setCancelled(true);
}
//cache claim for later
if(playerData != null)
{
playerData.lastClaim = claim;
}
}
}
}
//when a splash potion effects one or more entities...
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPotionSplash (PotionSplashEvent event)
{
ThrownPotion potion = event.getPotion();
//ignore potions not thrown by players
ProjectileSource projectileSource = potion.getShooter();
if(projectileSource == null || !(projectileSource instanceof Player)) return;
Player thrower = (Player)projectileSource;
Collection<PotionEffect> effects = potion.getEffects();
for(PotionEffect effect : effects)
{
PotionEffectType effectType = effect.getType();
//restrict jump potions on claimed animals (griefers could use this to steal animals over fences)
if(effectType == PotionEffectType.JUMP)
{
for(LivingEntity effected : event.getAffectedEntities())
{
Claim cachedClaim = null;
if(effected instanceof Animals)
{
Claim claim = this.dataStore.getClaimAt(effected.getLocation(), false, cachedClaim);
if(claim != null)
{
cachedClaim = claim;
if(claim.allowContainers(thrower) != null)
{
event.setCancelled(true);
return;
}
}
}
}
}
//otherwise, no restrictions for positive effects
if(positiveEffects.contains(effectType)) continue;
for(LivingEntity effected : event.getAffectedEntities())
{
//always impact the thrower
if(effected == thrower) continue;
//always impact non players
if(!(effected instanceof Player)) continue;
//otherwise if in no-pvp zone, stop effect
//FEATURE: prevent players from engaging in PvP combat inside land claims (when it's disabled)
else if(GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims || GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims)
{
Player effectedPlayer = (Player)effected;
PlayerData defenderData = this.dataStore.getPlayerData(effectedPlayer.getUniqueId());
PlayerData attackerData = this.dataStore.getPlayerData(thrower.getUniqueId());
Claim attackerClaim = this.dataStore.getClaimAt(thrower.getLocation(), false, attackerData.lastClaim);
if( attackerClaim != null &&
(attackerClaim.isAdminClaim() && attackerClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
attackerClaim.isAdminClaim() && attackerClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
!attackerClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
{
attackerData.lastClaim = attackerClaim;
event.setIntensity(effected, 0);
GriefPrevention.sendMessage(thrower, TextMode.Err, Messages.CantFightWhileImmune);
continue;
}
Claim defenderClaim = this.dataStore.getClaimAt(effectedPlayer.getLocation(), false, defenderData.lastClaim);
if( defenderClaim != null &&
(defenderClaim.isAdminClaim() && defenderClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
defenderClaim.isAdminClaim() && defenderClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
!defenderClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
{
defenderData.lastClaim = defenderClaim;
event.setIntensity(effected, 0);
GriefPrevention.sendMessage(thrower, TextMode.Err, Messages.PlayerInPvPSafeZone);
continue;
}
}
}
}
}
private static final HashSet<PotionEffectType> positiveEffects = new HashSet<PotionEffectType>(Arrays.asList
(
PotionEffectType.ABSORPTION,
PotionEffectType.DAMAGE_RESISTANCE,
PotionEffectType.FAST_DIGGING,
PotionEffectType.FIRE_RESISTANCE,
PotionEffectType.HEAL,
PotionEffectType.HEALTH_BOOST,
PotionEffectType.INCREASE_DAMAGE,
PotionEffectType.INVISIBILITY,
PotionEffectType.JUMP,
PotionEffectType.NIGHT_VISION,
PotionEffectType.REGENERATION,
PotionEffectType.SATURATION,
PotionEffectType.SPEED,
PotionEffectType.WATER_BREATHING
));
}
| Fixed self-damage putting a player "in combat".
Fixes especially ender pearls + immediate disconnect = death.
| src/me/ryanhamshire/GriefPrevention/EntityEventHandler.java | Fixed self-damage putting a player "in combat". | <ide><path>rc/me/ryanhamshire/GriefPrevention/EntityEventHandler.java
<ide>
<ide> Player defender = (Player)(event.getEntity());
<ide>
<del> PlayerData defenderData = this.dataStore.getPlayerData(((Player)event.getEntity()).getUniqueId());
<del> PlayerData attackerData = this.dataStore.getPlayerData(attacker.getUniqueId());
<del>
<del> //otherwise if protecting spawning players
<del> if(GriefPrevention.instance.config_pvp_protectFreshSpawns)
<add> if(attacker != defender)
<ide> {
<del> if(defenderData.pvpImmune)
<del> {
<del> event.setCancelled(true);
<del> GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.ThatPlayerPvPImmune);
<del> return;
<del> }
<del>
<del> if(attackerData.pvpImmune)
<del> {
<del> event.setCancelled(true);
<del> GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.CantFightWhileImmune);
<del> return;
<del> }
<add> PlayerData defenderData = this.dataStore.getPlayerData(((Player)event.getEntity()).getUniqueId());
<add> PlayerData attackerData = this.dataStore.getPlayerData(attacker.getUniqueId());
<add>
<add> //otherwise if protecting spawning players
<add> if(GriefPrevention.instance.config_pvp_protectFreshSpawns)
<add> {
<add> if(defenderData.pvpImmune)
<add> {
<add> event.setCancelled(true);
<add> GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.ThatPlayerPvPImmune);
<add> return;
<add> }
<add>
<add> if(attackerData.pvpImmune)
<add> {
<add> event.setCancelled(true);
<add> GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.CantFightWhileImmune);
<add> return;
<add> }
<add> }
<add>
<add> //FEATURE: prevent players from engaging in PvP combat inside land claims (when it's disabled)
<add> if(GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims || GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims)
<add> {
<add> Claim attackerClaim = this.dataStore.getClaimAt(attacker.getLocation(), false, attackerData.lastClaim);
<add> if( attackerClaim != null &&
<add> (attackerClaim.isAdminClaim() && attackerClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
<add> attackerClaim.isAdminClaim() && attackerClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
<add> !attackerClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
<add> {
<add> attackerData.lastClaim = attackerClaim;
<add> event.setCancelled(true);
<add> GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.CantFightWhileImmune);
<add> return;
<add> }
<add>
<add> Claim defenderClaim = this.dataStore.getClaimAt(defender.getLocation(), false, defenderData.lastClaim);
<add> if( defenderClaim != null &&
<add> (defenderClaim.isAdminClaim() && defenderClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
<add> defenderClaim.isAdminClaim() && defenderClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
<add> !defenderClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
<add> {
<add> defenderData.lastClaim = defenderClaim;
<add> event.setCancelled(true);
<add> GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.PlayerInPvPSafeZone);
<add> return;
<add> }
<add> }
<add>
<add> //FEATURE: prevent players who very recently participated in pvp combat from hiding inventory to protect it from looting
<add> //FEATURE: prevent players who are in pvp combat from logging out to avoid being defeated
<add>
<add> long now = Calendar.getInstance().getTimeInMillis();
<add> defenderData.lastPvpTimestamp = now;
<add> defenderData.lastPvpPlayer = attacker.getName();
<add> attackerData.lastPvpTimestamp = now;
<add> attackerData.lastPvpPlayer = defender.getName();
<ide> }
<del>
<del> //FEATURE: prevent players from engaging in PvP combat inside land claims (when it's disabled)
<del> if(GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims || GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims)
<del> {
<del> Claim attackerClaim = this.dataStore.getClaimAt(attacker.getLocation(), false, attackerData.lastClaim);
<del> if( attackerClaim != null &&
<del> (attackerClaim.isAdminClaim() && attackerClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
<del> attackerClaim.isAdminClaim() && attackerClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
<del> !attackerClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
<del> {
<del> attackerData.lastClaim = attackerClaim;
<del> event.setCancelled(true);
<del> GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.CantFightWhileImmune);
<del> return;
<del> }
<del>
<del> Claim defenderClaim = this.dataStore.getClaimAt(defender.getLocation(), false, defenderData.lastClaim);
<del> if( defenderClaim != null &&
<del> (defenderClaim.isAdminClaim() && defenderClaim.parent == null && GriefPrevention.instance.config_pvp_noCombatInAdminLandClaims ||
<del> defenderClaim.isAdminClaim() && defenderClaim.parent != null && GriefPrevention.instance.config_pvp_noCombatInAdminSubdivisions ||
<del> !defenderClaim.isAdminClaim() && GriefPrevention.instance.config_pvp_noCombatInPlayerLandClaims))
<del> {
<del> defenderData.lastClaim = defenderClaim;
<del> event.setCancelled(true);
<del> GriefPrevention.sendMessage(attacker, TextMode.Err, Messages.PlayerInPvPSafeZone);
<del> return;
<del> }
<del> }
<del>
<del> //FEATURE: prevent players who very recently participated in pvp combat from hiding inventory to protect it from looting
<del> //FEATURE: prevent players who are in pvp combat from logging out to avoid being defeated
<del>
<del> long now = Calendar.getInstance().getTimeInMillis();
<del> defenderData.lastPvpTimestamp = now;
<del> defenderData.lastPvpPlayer = attacker.getName();
<del> attackerData.lastPvpTimestamp = now;
<del> attackerData.lastPvpPlayer = defender.getName();
<ide> }
<ide>
<ide> //FEATURE: protect claimed animals, boats, minecarts, and items inside item frames |
|
Java | apache-2.0 | d75fe52e6c4a999eecb59177ccfee77847383b92 | 0 | thymeleaf/thymeleaf,thymeleaf/thymeleaf | /*
* =============================================================================
*
* Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.util;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.dialect.IProcessorDialect;
import org.thymeleaf.engine.AttributeDefinitions;
import org.thymeleaf.engine.ElementDefinitions;
import org.thymeleaf.engine.IAttributeDefinitionsAware;
import org.thymeleaf.engine.IElementDefinitionsAware;
import org.thymeleaf.engine.ITemplateHandler;
import org.thymeleaf.model.ICDATASection;
import org.thymeleaf.model.IComment;
import org.thymeleaf.model.IDocType;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.model.IProcessingInstruction;
import org.thymeleaf.model.ITemplateEnd;
import org.thymeleaf.model.ITemplateStart;
import org.thymeleaf.model.IText;
import org.thymeleaf.model.IXMLDeclaration;
import org.thymeleaf.postprocessor.IPostProcessor;
import org.thymeleaf.preprocessor.IPreProcessor;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.processor.cdatasection.ICDATASectionProcessor;
import org.thymeleaf.processor.cdatasection.ICDATASectionStructureHandler;
import org.thymeleaf.processor.comment.ICommentProcessor;
import org.thymeleaf.processor.comment.ICommentStructureHandler;
import org.thymeleaf.processor.doctype.IDocTypeProcessor;
import org.thymeleaf.processor.doctype.IDocTypeStructureHandler;
import org.thymeleaf.processor.element.IElementModelProcessor;
import org.thymeleaf.processor.element.IElementModelStructureHandler;
import org.thymeleaf.processor.element.IElementProcessor;
import org.thymeleaf.processor.element.IElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.processor.element.MatchingAttributeName;
import org.thymeleaf.processor.element.MatchingElementName;
import org.thymeleaf.processor.processinginstruction.IProcessingInstructionProcessor;
import org.thymeleaf.processor.processinginstruction.IProcessingInstructionStructureHandler;
import org.thymeleaf.processor.templateboundaries.ITemplateBoundariesProcessor;
import org.thymeleaf.processor.templateboundaries.ITemplateBoundariesStructureHandler;
import org.thymeleaf.processor.text.ITextProcessor;
import org.thymeleaf.processor.text.ITextStructureHandler;
import org.thymeleaf.processor.xmldeclaration.IXMLDeclarationProcessor;
import org.thymeleaf.processor.xmldeclaration.IXMLDeclarationStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;
/**
* <p>
* Utility class containing methods relating to the configuration of processors (e.g. wrapping).
* </p>
* <p>
* This class is mainly for <strong>internal use</strong>.
* </p>
*
*
* @author Daniel Fernández
* @since 3.0.0
*
*/
public final class ProcessorConfigurationUtils {
/**
* <p>
* Wraps an implementation of {@link IElementProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static IElementProcessor wrap(final IElementProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
if (processor instanceof IElementTagProcessor) {
return new ElementTagProcessorWrapper((IElementTagProcessor) processor, dialect);
}
if (processor instanceof IElementModelProcessor) {
return new ElementModelProcessorWrapper((IElementModelProcessor) processor, dialect);
}
throw new IllegalArgumentException("Unknown element processor interface implemented by " + processor + " of " +
"class: " + processor.getClass().getName());
}
/**
* <p>
* Wraps an implementation of {@link ICDATASectionProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static ICDATASectionProcessor wrap(final ICDATASectionProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new CDATASectionProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link ICommentProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static ICommentProcessor wrap(final ICommentProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new CommentProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IDocTypeProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static IDocTypeProcessor wrap(final IDocTypeProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new DocTypeProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IProcessingInstructionProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static IProcessingInstructionProcessor wrap(final IProcessingInstructionProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new ProcessingInstructionProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link ITemplateBoundariesProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static ITemplateBoundariesProcessor wrap(final ITemplateBoundariesProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new TemplateBoundariesProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link ITextProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static ITextProcessor wrap(final ITextProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new TextProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IXMLDeclarationProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static IXMLDeclarationProcessor wrap(final IXMLDeclarationProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new XMLDeclarationProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IPreProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param preProcessor the pre-processor to be wrapped.
* @param dialect the dialect this pre-processor was configured for.
* @return the wrapped pre-processor.
*/
public static IPreProcessor wrap(final IPreProcessor preProcessor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (preProcessor == null) {
return null;
}
return new PreProcessorWrapper(preProcessor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IPostProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param postProcessor the post-processor to be wrapped.
* @param dialect the dialect this post-processor was configured for.
* @return the wrapped post-processor.
*/
public static IPostProcessor wrap(final IPostProcessor postProcessor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (postProcessor == null) {
return null;
}
return new PostProcessorWrapper(postProcessor, dialect);
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IElementProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static IElementProcessor unwrap(final IElementProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (IElementProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link ICDATASectionProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static ICDATASectionProcessor unwrap(final ICDATASectionProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (ICDATASectionProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link ICommentProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static ICommentProcessor unwrap(final ICommentProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (ICommentProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IDocTypeProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static IDocTypeProcessor unwrap(final IDocTypeProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (IDocTypeProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IProcessingInstructionProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static IProcessingInstructionProcessor unwrap(final IProcessingInstructionProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (IProcessingInstructionProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link ITemplateBoundariesProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static ITemplateBoundariesProcessor unwrap(final ITemplateBoundariesProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (ITemplateBoundariesProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link ITextProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static ITextProcessor unwrap(final ITextProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (ITextProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IXMLDeclarationProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static IXMLDeclarationProcessor unwrap(final IXMLDeclarationProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (IXMLDeclarationProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IPreProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param preProcessor the pre-processor to be unwrapped.
* @return the unwrapped pre-processor.
*/
public static IPreProcessor unwrap(final IPreProcessor preProcessor) {
if (preProcessor == null) {
return null;
}
if (preProcessor instanceof PreProcessorWrapper) {
return ((PreProcessorWrapper) preProcessor).unwrap();
}
return preProcessor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IPostProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param postProcessor the post-processor to be unwrapped.
* @return the unwrapped post-processor.
*/
public static IPostProcessor unwrap(final IPostProcessor postProcessor) {
if (postProcessor == null) {
return null;
}
if (postProcessor instanceof PostProcessorWrapper) {
return ((PostProcessorWrapper) postProcessor).unwrap();
}
return postProcessor;
}
private ProcessorConfigurationUtils() {
super();
}
/*
* This is the base class for a hierarchy of wrappers that will be applied to all processors configured
* at the engine in order to add additional information to them (e.g. the dialect they are configured for).
*/
static abstract class AbstractProcessorWrapper implements IProcessor, IAttributeDefinitionsAware, IElementDefinitionsAware {
private final int dialectPrecedence;
private final int processorPrecedence;
private final IProcessorDialect dialect;
private final IProcessor processor;
AbstractProcessorWrapper(final IProcessor processor, final IProcessorDialect dialect) {
super();
this.dialect = dialect;
this.processor = processor;
this.dialectPrecedence = this.dialect.getDialectProcessorPrecedence();
this.processorPrecedence = this.processor.getPrecedence();
}
public final TemplateMode getTemplateMode() {
return this.processor.getTemplateMode();
}
public final int getDialectPrecedence() {
return this.dialectPrecedence;
}
public final int getPrecedence() {
return this.processorPrecedence;
}
public final IProcessorDialect getDialect() {
return this.dialect;
}
public final IProcessor unwrap() {
return this.processor;
}
public final void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
if (this.processor instanceof IAttributeDefinitionsAware) {
((IAttributeDefinitionsAware) this.processor).setAttributeDefinitions(attributeDefinitions);
}
}
public final void setElementDefinitions(final ElementDefinitions elementDefinitions) {
if (this.processor instanceof IElementDefinitionsAware) {
((IElementDefinitionsAware) this.processor).setElementDefinitions(elementDefinitions);
}
}
@Override
public String toString() {
return this.processor.toString();
}
}
static abstract class AbstractElementProcessorWrapper extends AbstractProcessorWrapper implements IElementProcessor {
private final IElementProcessor processor;
AbstractElementProcessorWrapper(final IElementProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public final MatchingElementName getMatchingElementName() {
return this.processor.getMatchingElementName();
}
public final MatchingAttributeName getMatchingAttributeName() {
return this.processor.getMatchingAttributeName();
}
}
static final class ElementTagProcessorWrapper extends AbstractElementProcessorWrapper implements IElementTagProcessor {
private final IElementTagProcessor processor;
ElementTagProcessorWrapper(final IElementTagProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public void process(final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {
this.processor.process(context, tag, structureHandler);
}
}
static final class ElementModelProcessorWrapper extends AbstractElementProcessorWrapper implements IElementModelProcessor {
private final IElementModelProcessor processor;
ElementModelProcessorWrapper(final IElementModelProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public void process(final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler) {
this.processor.process(context, model, structureHandler);
}
}
static final class CDATASectionProcessorWrapper extends AbstractProcessorWrapper implements ICDATASectionProcessor {
private final ICDATASectionProcessor processor;
CDATASectionProcessorWrapper(final ICDATASectionProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public void process(final ITemplateContext context, final ICDATASection cdataSection, final ICDATASectionStructureHandler structureHandler) {
this.processor.process(context, cdataSection, structureHandler);
}
}
static final class CommentProcessorWrapper extends AbstractProcessorWrapper implements ICommentProcessor {
private final ICommentProcessor processor;
CommentProcessorWrapper(final ICommentProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public void process(final ITemplateContext context, final IComment comment, final ICommentStructureHandler structureHandler) {
this.processor.process(context, comment, structureHandler);
}
}
static final class DocTypeProcessorWrapper extends AbstractProcessorWrapper implements IDocTypeProcessor {
private final IDocTypeProcessor processor;
DocTypeProcessorWrapper(final IDocTypeProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public void process(final ITemplateContext context, final IDocType docType, final IDocTypeStructureHandler structureHandler) {
this.processor.process(context, docType, structureHandler);
}
}
static final class ProcessingInstructionProcessorWrapper extends AbstractProcessorWrapper implements IProcessingInstructionProcessor {
private final IProcessingInstructionProcessor processor;
ProcessingInstructionProcessorWrapper(final IProcessingInstructionProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public void process(final ITemplateContext context, final IProcessingInstruction processingInstruction, final IProcessingInstructionStructureHandler structureHandler) {
this.processor.process(context, processingInstruction, structureHandler);
}
}
static final class TemplateBoundariesProcessorWrapper extends AbstractProcessorWrapper implements ITemplateBoundariesProcessor {
private final ITemplateBoundariesProcessor processor;
TemplateBoundariesProcessorWrapper(final ITemplateBoundariesProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public void processTemplateStart(final ITemplateContext context, final ITemplateStart templateStart, final ITemplateBoundariesStructureHandler structureHandler) {
this.processor.processTemplateStart(context, templateStart, structureHandler);
}
public void processTemplateEnd(final ITemplateContext context, final ITemplateEnd templateEnd, final ITemplateBoundariesStructureHandler structureHandler) {
this.processor.processTemplateEnd(context, templateEnd, structureHandler);
}
}
static final class TextProcessorWrapper extends AbstractProcessorWrapper implements ITextProcessor {
private final ITextProcessor processor;
TextProcessorWrapper(final ITextProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public void process(final ITemplateContext context, final IText text, final ITextStructureHandler structureHandler) {
this.processor.process(context, text, structureHandler);
}
}
static final class XMLDeclarationProcessorWrapper extends AbstractProcessorWrapper implements IXMLDeclarationProcessor {
private final IXMLDeclarationProcessor processor;
XMLDeclarationProcessorWrapper(final IXMLDeclarationProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
this.processor = processor;
}
public void process(final ITemplateContext context, final IXMLDeclaration xmlDeclaration, final IXMLDeclarationStructureHandler structureHandler) {
this.processor.process(context, xmlDeclaration, structureHandler);
}
}
static final class PreProcessorWrapper implements IPreProcessor, IElementDefinitionsAware, IAttributeDefinitionsAware {
private final IProcessorDialect dialect;
private final IPreProcessor preProcessor;
PreProcessorWrapper(final IPreProcessor preProcessor, final IProcessorDialect dialect) {
super();
this.preProcessor = preProcessor;
this.dialect = dialect;
}
public TemplateMode getTemplateMode() {
return this.preProcessor.getTemplateMode();
}
public int getPrecedence() {
return this.preProcessor.getPrecedence();
}
public final IProcessorDialect getDialect() {
return this.dialect;
}
public Class<? extends ITemplateHandler> getHandlerClass() {
return this.preProcessor.getHandlerClass();
}
public final IPreProcessor unwrap() {
return this.preProcessor;
}
public final void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
if (this.preProcessor instanceof IAttributeDefinitionsAware) {
((IAttributeDefinitionsAware) this.preProcessor).setAttributeDefinitions(attributeDefinitions);
}
}
public final void setElementDefinitions(final ElementDefinitions elementDefinitions) {
if (this.preProcessor instanceof IElementDefinitionsAware) {
((IElementDefinitionsAware) this.preProcessor).setElementDefinitions(elementDefinitions);
}
}
@Override
public String toString() {
return this.preProcessor.toString();
}
}
static final class PostProcessorWrapper implements IPostProcessor, IElementDefinitionsAware, IAttributeDefinitionsAware {
private final IProcessorDialect dialect;
private final IPostProcessor postProcessor;
PostProcessorWrapper(final IPostProcessor postProcessor, final IProcessorDialect dialect) {
super();
this.postProcessor = postProcessor;
this.dialect = dialect;
}
public TemplateMode getTemplateMode() {
return this.postProcessor.getTemplateMode();
}
public int getPrecedence() {
return this.postProcessor.getPrecedence();
}
public final IProcessorDialect getDialect() {
return this.dialect;
}
public Class<? extends ITemplateHandler> getHandlerClass() {
return this.postProcessor.getHandlerClass();
}
public final IPostProcessor unwrap() {
return this.postProcessor;
}
public final void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
if (this.postProcessor instanceof IAttributeDefinitionsAware) {
((IAttributeDefinitionsAware) this.postProcessor).setAttributeDefinitions(attributeDefinitions);
}
}
public final void setElementDefinitions(final ElementDefinitions elementDefinitions) {
if (this.postProcessor instanceof IElementDefinitionsAware) {
((IElementDefinitionsAware) this.postProcessor).setElementDefinitions(elementDefinitions);
}
}
@Override
public String toString() {
return this.postProcessor.toString();
}
}
}
| src/main/java/org/thymeleaf/util/ProcessorConfigurationUtils.java | /*
* =============================================================================
*
* Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.util;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.dialect.IProcessorDialect;
import org.thymeleaf.engine.AttributeDefinitions;
import org.thymeleaf.engine.ElementDefinitions;
import org.thymeleaf.engine.IAttributeDefinitionsAware;
import org.thymeleaf.engine.IElementDefinitionsAware;
import org.thymeleaf.engine.ITemplateHandler;
import org.thymeleaf.model.ICDATASection;
import org.thymeleaf.model.IComment;
import org.thymeleaf.model.IDocType;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.model.IProcessingInstruction;
import org.thymeleaf.model.ITemplateEnd;
import org.thymeleaf.model.ITemplateStart;
import org.thymeleaf.model.IText;
import org.thymeleaf.model.IXMLDeclaration;
import org.thymeleaf.postprocessor.IPostProcessor;
import org.thymeleaf.preprocessor.IPreProcessor;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.processor.cdatasection.ICDATASectionProcessor;
import org.thymeleaf.processor.cdatasection.ICDATASectionStructureHandler;
import org.thymeleaf.processor.comment.ICommentProcessor;
import org.thymeleaf.processor.comment.ICommentStructureHandler;
import org.thymeleaf.processor.doctype.IDocTypeProcessor;
import org.thymeleaf.processor.doctype.IDocTypeStructureHandler;
import org.thymeleaf.processor.element.IElementModelProcessor;
import org.thymeleaf.processor.element.IElementModelStructureHandler;
import org.thymeleaf.processor.element.IElementProcessor;
import org.thymeleaf.processor.element.IElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.processor.element.MatchingAttributeName;
import org.thymeleaf.processor.element.MatchingElementName;
import org.thymeleaf.processor.processinginstruction.IProcessingInstructionProcessor;
import org.thymeleaf.processor.processinginstruction.IProcessingInstructionStructureHandler;
import org.thymeleaf.processor.templateboundaries.ITemplateBoundariesProcessor;
import org.thymeleaf.processor.templateboundaries.ITemplateBoundariesStructureHandler;
import org.thymeleaf.processor.text.ITextProcessor;
import org.thymeleaf.processor.text.ITextStructureHandler;
import org.thymeleaf.processor.xmldeclaration.IXMLDeclarationProcessor;
import org.thymeleaf.processor.xmldeclaration.IXMLDeclarationStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;
/**
* <p>
* Utility class containing methods relating to the configuration of processors (e.g. wrapping).
* </p>
* <p>
* This class is mainly for <strong>internal use</strong>.
* </p>
*
*
* @author Daniel Fernández
* @since 3.0.0
*
*/
public final class ProcessorConfigurationUtils {
/**
* <p>
* Wraps an implementation of {@link IElementProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static IElementProcessor wrap(final IElementProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
if (processor instanceof IElementTagProcessor) {
return new ElementTagProcessorWrapper((IElementTagProcessor) processor, dialect);
}
if (processor instanceof IElementModelProcessor) {
return new ElementModelProcessorWrapper((IElementModelProcessor) processor, dialect);
}
throw new IllegalArgumentException("Unknown element processor interface implemented by " + processor + " of " +
"class: " + processor.getClass().getName());
}
/**
* <p>
* Wraps an implementation of {@link ICDATASectionProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static ICDATASectionProcessor wrap(final ICDATASectionProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new CDATASectionProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link ICommentProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static ICommentProcessor wrap(final ICommentProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new CommentProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IDocTypeProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static IDocTypeProcessor wrap(final IDocTypeProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new DocTypeProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IProcessingInstructionProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static IProcessingInstructionProcessor wrap(final IProcessingInstructionProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new ProcessingInstructionProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link ITemplateBoundariesProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static ITemplateBoundariesProcessor wrap(final ITemplateBoundariesProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new TemplateBoundariesProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link ITextProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static ITextProcessor wrap(final ITextProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new TextProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IXMLDeclarationProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be wrapped.
* @param dialect the dialect this processor was configured for.
* @return the wrapped processor.
*/
public static IXMLDeclarationProcessor wrap(final IXMLDeclarationProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new XMLDeclarationProcessorWrapper(processor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IPreProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param preProcessor the pre-processor to be wrapped.
* @param dialect the dialect this pre-processor was configured for.
* @return the wrapped pre-processor.
*/
public static IPreProcessor wrap(final IPreProcessor preProcessor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (preProcessor == null) {
return null;
}
return new PreProcessorWrapper(preProcessor, dialect);
}
/**
* <p>
* Wraps an implementation of {@link IPostProcessor} into an object that adds some information
* required internally (like e.g. the dialect this processor was registered for).
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param postProcessor the post-processor to be wrapped.
* @param dialect the dialect this post-processor was configured for.
* @return the wrapped post-processor.
*/
public static IPostProcessor wrap(final IPostProcessor postProcessor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (postProcessor == null) {
return null;
}
return new PostProcessorWrapper(postProcessor, dialect);
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IElementProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static IElementProcessor unwrap(final IElementProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (IElementProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link ICDATASectionProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static ICDATASectionProcessor unwrap(final ICDATASectionProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (ICDATASectionProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link ICommentProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static ICommentProcessor unwrap(final ICommentProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (ICommentProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IDocTypeProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static IDocTypeProcessor unwrap(final IDocTypeProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (IDocTypeProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IProcessingInstructionProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static IProcessingInstructionProcessor unwrap(final IProcessingInstructionProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (IProcessingInstructionProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link ITemplateBoundariesProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static ITemplateBoundariesProcessor unwrap(final ITemplateBoundariesProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (ITemplateBoundariesProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link ITextProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static ITextProcessor unwrap(final ITextProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (ITextProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IXMLDeclarationProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param processor the processor to be unwrapped.
* @return the unwrapped processor.
*/
public static IXMLDeclarationProcessor unwrap(final IXMLDeclarationProcessor processor) {
if (processor == null) {
return null;
}
if (processor instanceof AbstractProcessorWrapper) {
return (IXMLDeclarationProcessor)((AbstractProcessorWrapper) processor).unwrap();
}
return processor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IPreProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param preProcessor the pre-processor to be unwrapped.
* @return the unwrapped pre-processor.
*/
public static IPreProcessor unwrap(final IPreProcessor preProcessor) {
if (preProcessor == null) {
return null;
}
if (preProcessor instanceof PreProcessorWrapper) {
return ((PreProcessorWrapper) preProcessor).unwrap();
}
return preProcessor;
}
/**
* <p>
* Unwraps a wrapped implementation of {@link IPostProcessor}.
* </p>
* <p>
* This method is meant for <strong>internal</strong> use only.
* </p>
*
* @param postProcessor the post-processor to be unwrapped.
* @return the unwrapped post-processor.
*/
public static IPostProcessor unwrap(final IPostProcessor postProcessor) {
if (postProcessor == null) {
return null;
}
if (postProcessor instanceof PostProcessorWrapper) {
return ((PostProcessorWrapper) postProcessor).unwrap();
}
return postProcessor;
}
private ProcessorConfigurationUtils() {
super();
}
/*
* This is the base class for a hierarchy of wrappers that will be applied to all processors configured
* at the engine in order to add additional information to them (e.g. the dialect they are configured for).
*/
static abstract class AbstractProcessorWrapper implements IProcessor, IAttributeDefinitionsAware, IElementDefinitionsAware {
private final int dialectPrecedence;
private final int processorPrecedence;
private final IProcessorDialect dialect;
protected final IProcessor processor;
AbstractProcessorWrapper(final IProcessor processor, final IProcessorDialect dialect) {
super();
this.dialect = dialect;
this.processor = processor;
this.dialectPrecedence = this.dialect.getDialectProcessorPrecedence();
this.processorPrecedence = this.processor.getPrecedence();
}
public final TemplateMode getTemplateMode() {
return this.processor.getTemplateMode();
}
public final int getDialectPrecedence() {
return this.dialectPrecedence;
}
public final int getPrecedence() {
return this.processorPrecedence;
}
public final IProcessorDialect getDialect() {
return this.dialect;
}
public final IProcessor unwrap() {
return this.processor;
}
public final void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
if (this.processor instanceof IAttributeDefinitionsAware) {
((IAttributeDefinitionsAware) this.processor).setAttributeDefinitions(attributeDefinitions);
}
}
public final void setElementDefinitions(final ElementDefinitions elementDefinitions) {
if (this.processor instanceof IElementDefinitionsAware) {
((IElementDefinitionsAware) this.processor).setElementDefinitions(elementDefinitions);
}
}
@Override
public String toString() {
return this.processor.toString();
}
}
static abstract class AbstractElementProcessorWrapper extends AbstractProcessorWrapper implements IElementProcessor {
AbstractElementProcessorWrapper(final IElementProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public final MatchingElementName getMatchingElementName() {
return ((IElementProcessor)this.processor).getMatchingElementName();
}
public final MatchingAttributeName getMatchingAttributeName() {
return ((IElementProcessor)this.processor).getMatchingAttributeName();
}
}
static final class ElementTagProcessorWrapper extends AbstractElementProcessorWrapper implements IElementTagProcessor {
ElementTagProcessorWrapper(final IElementTagProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public void process(final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {
((IElementTagProcessor)this.processor).process(context, tag, structureHandler);
}
}
static final class ElementModelProcessorWrapper extends AbstractElementProcessorWrapper implements IElementModelProcessor {
ElementModelProcessorWrapper(final IElementModelProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public void process(final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler) {
((IElementModelProcessor)this.processor).process(context, model, structureHandler);
}
}
static final class CDATASectionProcessorWrapper extends AbstractProcessorWrapper implements ICDATASectionProcessor {
CDATASectionProcessorWrapper(final ICDATASectionProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public void process(final ITemplateContext context, final ICDATASection cdataSection, final ICDATASectionStructureHandler structureHandler) {
((ICDATASectionProcessor)this.processor).process(context, cdataSection, structureHandler);
}
}
static final class CommentProcessorWrapper extends AbstractProcessorWrapper implements ICommentProcessor {
CommentProcessorWrapper(final ICommentProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public void process(final ITemplateContext context, final IComment comment, final ICommentStructureHandler structureHandler) {
((ICommentProcessor)this.processor).process(context, comment, structureHandler);
}
}
static final class DocTypeProcessorWrapper extends AbstractProcessorWrapper implements IDocTypeProcessor {
DocTypeProcessorWrapper(final IDocTypeProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public void process(final ITemplateContext context, final IDocType docType, final IDocTypeStructureHandler structureHandler) {
((IDocTypeProcessor)this.processor).process(context, docType, structureHandler);
}
}
static final class ProcessingInstructionProcessorWrapper extends AbstractProcessorWrapper implements IProcessingInstructionProcessor {
ProcessingInstructionProcessorWrapper(final IProcessingInstructionProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public void process(final ITemplateContext context, final IProcessingInstruction processingInstruction, final IProcessingInstructionStructureHandler structureHandler) {
((IProcessingInstructionProcessor)this.processor).process(context, processingInstruction, structureHandler);
}
}
static final class TemplateBoundariesProcessorWrapper extends AbstractProcessorWrapper implements ITemplateBoundariesProcessor {
TemplateBoundariesProcessorWrapper(final ITemplateBoundariesProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public void processTemplateStart(final ITemplateContext context, final ITemplateStart templateStart, final ITemplateBoundariesStructureHandler structureHandler) {
((ITemplateBoundariesProcessor)this.processor).processTemplateStart(context, templateStart, structureHandler);
}
public void processTemplateEnd(final ITemplateContext context, final ITemplateEnd templateEnd, final ITemplateBoundariesStructureHandler structureHandler) {
((ITemplateBoundariesProcessor)this.processor).processTemplateEnd(context, templateEnd, structureHandler);
}
}
static final class TextProcessorWrapper extends AbstractProcessorWrapper implements ITextProcessor {
TextProcessorWrapper(final ITextProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public void process(final ITemplateContext context, final IText text, final ITextStructureHandler structureHandler) {
((ITextProcessor)this.processor).process(context, text, structureHandler);
}
}
static final class XMLDeclarationProcessorWrapper extends AbstractProcessorWrapper implements IXMLDeclarationProcessor {
XMLDeclarationProcessorWrapper(final IXMLDeclarationProcessor processor, final IProcessorDialect dialect) {
super(processor, dialect);
}
public void process(final ITemplateContext context, final IXMLDeclaration xmlDeclaration, final IXMLDeclarationStructureHandler structureHandler) {
((IXMLDeclarationProcessor)this.processor).process(context, xmlDeclaration, structureHandler);
}
}
static final class PreProcessorWrapper implements IPreProcessor, IElementDefinitionsAware, IAttributeDefinitionsAware {
private final IProcessorDialect dialect;
private final IPreProcessor preProcessor;
PreProcessorWrapper(final IPreProcessor preProcessor, final IProcessorDialect dialect) {
super();
this.preProcessor = preProcessor;
this.dialect = dialect;
}
public TemplateMode getTemplateMode() {
return this.preProcessor.getTemplateMode();
}
public int getPrecedence() {
return this.preProcessor.getPrecedence();
}
public final IProcessorDialect getDialect() {
return this.dialect;
}
public Class<? extends ITemplateHandler> getHandlerClass() {
return this.preProcessor.getHandlerClass();
}
public final IPreProcessor unwrap() {
return this.preProcessor;
}
public final void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
if (this.preProcessor instanceof IAttributeDefinitionsAware) {
((IAttributeDefinitionsAware) this.preProcessor).setAttributeDefinitions(attributeDefinitions);
}
}
public final void setElementDefinitions(final ElementDefinitions elementDefinitions) {
if (this.preProcessor instanceof IElementDefinitionsAware) {
((IElementDefinitionsAware) this.preProcessor).setElementDefinitions(elementDefinitions);
}
}
@Override
public String toString() {
return this.preProcessor.toString();
}
}
static final class PostProcessorWrapper implements IPostProcessor, IElementDefinitionsAware, IAttributeDefinitionsAware {
private final IProcessorDialect dialect;
private final IPostProcessor postProcessor;
PostProcessorWrapper(final IPostProcessor postProcessor, final IProcessorDialect dialect) {
super();
this.postProcessor = postProcessor;
this.dialect = dialect;
}
public TemplateMode getTemplateMode() {
return this.postProcessor.getTemplateMode();
}
public int getPrecedence() {
return this.postProcessor.getPrecedence();
}
public final IProcessorDialect getDialect() {
return this.dialect;
}
public Class<? extends ITemplateHandler> getHandlerClass() {
return this.postProcessor.getHandlerClass();
}
public final IPostProcessor unwrap() {
return this.postProcessor;
}
public final void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
if (this.postProcessor instanceof IAttributeDefinitionsAware) {
((IAttributeDefinitionsAware) this.postProcessor).setAttributeDefinitions(attributeDefinitions);
}
}
public final void setElementDefinitions(final ElementDefinitions elementDefinitions) {
if (this.postProcessor instanceof IElementDefinitionsAware) {
((IElementDefinitionsAware) this.postProcessor).setElementDefinitions(elementDefinitions);
}
}
@Override
public String toString() {
return this.postProcessor.toString();
}
}
}
| Simplified wrapped processor variable access at runtime
| src/main/java/org/thymeleaf/util/ProcessorConfigurationUtils.java | Simplified wrapped processor variable access at runtime | <ide><path>rc/main/java/org/thymeleaf/util/ProcessorConfigurationUtils.java
<ide> private final int dialectPrecedence;
<ide> private final int processorPrecedence;
<ide> private final IProcessorDialect dialect;
<del> protected final IProcessor processor;
<add> private final IProcessor processor;
<ide>
<ide> AbstractProcessorWrapper(final IProcessor processor, final IProcessorDialect dialect) {
<ide> super();
<ide>
<ide> static abstract class AbstractElementProcessorWrapper extends AbstractProcessorWrapper implements IElementProcessor {
<ide>
<add> private final IElementProcessor processor;
<add>
<ide> AbstractElementProcessorWrapper(final IElementProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public final MatchingElementName getMatchingElementName() {
<del> return ((IElementProcessor)this.processor).getMatchingElementName();
<add> return this.processor.getMatchingElementName();
<ide> }
<ide>
<ide> public final MatchingAttributeName getMatchingAttributeName() {
<del> return ((IElementProcessor)this.processor).getMatchingAttributeName();
<add> return this.processor.getMatchingAttributeName();
<ide> }
<ide>
<ide> }
<ide>
<ide> static final class ElementTagProcessorWrapper extends AbstractElementProcessorWrapper implements IElementTagProcessor {
<ide>
<add> private final IElementTagProcessor processor;
<add>
<ide> ElementTagProcessorWrapper(final IElementTagProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public void process(final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {
<del> ((IElementTagProcessor)this.processor).process(context, tag, structureHandler);
<add> this.processor.process(context, tag, structureHandler);
<ide> }
<ide>
<ide> }
<ide>
<ide> static final class ElementModelProcessorWrapper extends AbstractElementProcessorWrapper implements IElementModelProcessor {
<ide>
<add> private final IElementModelProcessor processor;
<add>
<ide> ElementModelProcessorWrapper(final IElementModelProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public void process(final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler) {
<del> ((IElementModelProcessor)this.processor).process(context, model, structureHandler);
<add> this.processor.process(context, model, structureHandler);
<ide> }
<ide>
<ide> }
<ide>
<ide> static final class CDATASectionProcessorWrapper extends AbstractProcessorWrapper implements ICDATASectionProcessor {
<ide>
<add> private final ICDATASectionProcessor processor;
<add>
<ide> CDATASectionProcessorWrapper(final ICDATASectionProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public void process(final ITemplateContext context, final ICDATASection cdataSection, final ICDATASectionStructureHandler structureHandler) {
<del> ((ICDATASectionProcessor)this.processor).process(context, cdataSection, structureHandler);
<add> this.processor.process(context, cdataSection, structureHandler);
<ide> }
<ide>
<ide> }
<ide>
<ide> static final class CommentProcessorWrapper extends AbstractProcessorWrapper implements ICommentProcessor {
<ide>
<add> private final ICommentProcessor processor;
<add>
<ide> CommentProcessorWrapper(final ICommentProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public void process(final ITemplateContext context, final IComment comment, final ICommentStructureHandler structureHandler) {
<del> ((ICommentProcessor)this.processor).process(context, comment, structureHandler);
<add> this.processor.process(context, comment, structureHandler);
<ide> }
<ide>
<ide> }
<ide>
<ide> static final class DocTypeProcessorWrapper extends AbstractProcessorWrapper implements IDocTypeProcessor {
<ide>
<add> private final IDocTypeProcessor processor;
<add>
<ide> DocTypeProcessorWrapper(final IDocTypeProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public void process(final ITemplateContext context, final IDocType docType, final IDocTypeStructureHandler structureHandler) {
<del> ((IDocTypeProcessor)this.processor).process(context, docType, structureHandler);
<add> this.processor.process(context, docType, structureHandler);
<ide> }
<ide>
<ide> }
<ide>
<ide> static final class ProcessingInstructionProcessorWrapper extends AbstractProcessorWrapper implements IProcessingInstructionProcessor {
<ide>
<add> private final IProcessingInstructionProcessor processor;
<add>
<ide> ProcessingInstructionProcessorWrapper(final IProcessingInstructionProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public void process(final ITemplateContext context, final IProcessingInstruction processingInstruction, final IProcessingInstructionStructureHandler structureHandler) {
<del> ((IProcessingInstructionProcessor)this.processor).process(context, processingInstruction, structureHandler);
<add> this.processor.process(context, processingInstruction, structureHandler);
<ide> }
<ide>
<ide> }
<ide>
<ide> static final class TemplateBoundariesProcessorWrapper extends AbstractProcessorWrapper implements ITemplateBoundariesProcessor {
<ide>
<add> private final ITemplateBoundariesProcessor processor;
<add>
<ide> TemplateBoundariesProcessorWrapper(final ITemplateBoundariesProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public void processTemplateStart(final ITemplateContext context, final ITemplateStart templateStart, final ITemplateBoundariesStructureHandler structureHandler) {
<del> ((ITemplateBoundariesProcessor)this.processor).processTemplateStart(context, templateStart, structureHandler);
<add> this.processor.processTemplateStart(context, templateStart, structureHandler);
<ide> }
<ide>
<ide> public void processTemplateEnd(final ITemplateContext context, final ITemplateEnd templateEnd, final ITemplateBoundariesStructureHandler structureHandler) {
<del> ((ITemplateBoundariesProcessor)this.processor).processTemplateEnd(context, templateEnd, structureHandler);
<add> this.processor.processTemplateEnd(context, templateEnd, structureHandler);
<ide> }
<ide>
<ide> }
<ide>
<ide> static final class TextProcessorWrapper extends AbstractProcessorWrapper implements ITextProcessor {
<ide>
<add> private final ITextProcessor processor;
<add>
<ide> TextProcessorWrapper(final ITextProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public void process(final ITemplateContext context, final IText text, final ITextStructureHandler structureHandler) {
<del> ((ITextProcessor)this.processor).process(context, text, structureHandler);
<add> this.processor.process(context, text, structureHandler);
<ide> }
<ide>
<ide> }
<ide>
<ide> static final class XMLDeclarationProcessorWrapper extends AbstractProcessorWrapper implements IXMLDeclarationProcessor {
<ide>
<add> private final IXMLDeclarationProcessor processor;
<add>
<ide> XMLDeclarationProcessorWrapper(final IXMLDeclarationProcessor processor, final IProcessorDialect dialect) {
<ide> super(processor, dialect);
<add> this.processor = processor;
<ide> }
<ide>
<ide> public void process(final ITemplateContext context, final IXMLDeclaration xmlDeclaration, final IXMLDeclarationStructureHandler structureHandler) {
<del> ((IXMLDeclarationProcessor)this.processor).process(context, xmlDeclaration, structureHandler);
<add> this.processor.process(context, xmlDeclaration, structureHandler);
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | c6210a043248b980845e96bc7088402ed80bcbc3 | 0 | HeroDigital/renditions-servlet | package com.herodigital.wcm.ext.renditions.servlet;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Dictionary;
import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.Rendition;
import com.herodigital.wcm.ext.renditions.model.RenditionMeta;
import com.herodigital.wcm.ext.renditions.service.AssetRenditionResolver;
/**
* Handles fetching of an asset image rendition. Primary advantage over out of the box AEM
* thumbnail servlet is the support of both web, thumbnail, and original renditions.
* <p>
* Resolution of rendition is handled by {@link AssetRenditionResolver}.
* <p>
* 404 response may be returned if requested asset or rendition does not exist (depending on configuration).
*
* @author joelepps
*
*/
@Component(metatype=true, immediate=true, label="Web Image Rendition Servlet", description="Servlet which returns the web image rendition")
@Service(Servlet.class)
@Properties({
@Property(name = "service.description", value = "Servlet which returns the web image rendtions"),
@Property(name = "service.vendor", value = "Hero Digital"),
@Property(name = "sling.servlet.resourceTypes", value="sling/servlet/default", propertyPrivate=true),
@Property(name = "sling.servlet.selectors", value={ImageRenditionServlet.SELECTOR_RENDITION_WEB, ImageRenditionServlet.SELECTOR_RENDITION_THUMB, ImageRenditionServlet.SELECTOR_RENDITION_ORIGINAL }, propertyPrivate=true),
@Property(name = "sling.servlet.extensions", value={ "png", "jpg", "jpeg", "svg", "gif" }, propertyPrivate=true),
@Property(name = "sling.servlet.methods", value={ "GET" }, propertyPrivate=true),
})
public class ImageRenditionServlet extends SlingSafeMethodsServlet {
private static final long serialVersionUID = 7272927969196706776L;
private static final Logger log = LoggerFactory.getLogger(ImageRenditionServlet.class);
protected static final String SELECTOR_RENDITION_WEB = "imgw";
protected static final String SELECTOR_RENDITION_THUMB = "imgt";
protected static final String SELECTOR_RENDITION_ORIGINAL = "imgo";
private static enum Selector { TYPE, WIDTH, HEIGHT } // used for ordinal position of selectors
@Property(label = "Redirect On Unsupported Type", description = "Enabled by default. If request is made to a rendition with the wrong extension, a 302 redirect is returned the the URL with the matching extension. If disabled, then 415 error response is returned.", boolValue = true)
public static final String REDIRECT_ON_WRONG_TYPE = "rendition.servlet.redirect.on.wrong.type";
private boolean redirectOnWrongType;
@Property(label = "Redirect On Missing Rendition", description = "Disabled by default. If requested rendition is not found, 404 error response is returned. If enabled, 302 redirect is returned to the original rendition.", boolValue = false)
public static final String REDIRECT_ON_MISSING_RENDITION = "rendition.servlet.redirect.on.missing.rendition";
private boolean redirectOnMissingRendition;
@Reference
private AssetRenditionResolver assetRenditionResolver;
@Activate
@SuppressWarnings("unchecked")
public void activate(ComponentContext context) {
Dictionary<String, ?> properties = context.getProperties();
redirectOnWrongType = toBoolean(properties.get(REDIRECT_ON_WRONG_TYPE));
redirectOnMissingRendition = toBoolean(properties.get(REDIRECT_ON_MISSING_RENDITION));
}
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
// Convert request to convenience object
RenditionMeta renditionMeta = buildRenditionMeta(request);
if (renditionMeta == null) {
log.debug("Failed to build rendition meta for {}", request.getPathInfo());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Resolve image resource
Resource resource = request.getResource();
if (resource == null) {
log.debug("Missing dam asset at {}", request.getPathInfo());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Adapt image resource to dam object
Asset damAsset = resource.adaptTo(Asset.class);
if (damAsset == null) {
log.debug("Cannot resolve dam asset at {} for {}", resource.getPath(), request.getPathInfo());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Resolve dam asset + meta data to actual rendition
Rendition rendition = assetRenditionResolver.resolveRendition(damAsset, renditionMeta);
if (rendition == null) {
if (redirectOnMissingRendition) {
sendRedirectToOriginalRendition(request, response, damAsset);
return;
} else {
log.debug("Missing rendition for {} and {}", renditionMeta, damAsset.getPath());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
// If extension does not match rendition mime type, redirect or 415 error
if (!rendition.getMimeType().contains(renditionMeta.getExtension())) {
if (redirectOnWrongType) {
sendRedirectToProperExtension(request, response, rendition, renditionMeta);
return;
} else {
log.debug("Wrong extension for {} and request {}", rendition.getMimeType(), renditionMeta.getExtension());
response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
return;
}
}
// Handle potential error
InputStream input = rendition.getStream();
if (input == null) {
log.error("Missing rendition input stream for {} and {}", renditionMeta, damAsset.getPath());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
writeResponse(response, input, rendition.getMimeType());
}
private static RenditionMeta buildRenditionMeta(SlingHttpServletRequest request) {
String[] selectors = request.getRequestPathInfo().getSelectors();
String extension = request.getRequestPathInfo().getExtension();
RenditionSelector renditionSelector = null;
int width = 0;
int height = 0;
if (selectors.length >= 1 && SELECTOR_RENDITION_ORIGINAL.equals(selectors[0])) {
// original rendition does not need or parse width/height
renditionSelector = RenditionSelector.fromSelector(selectors[Selector.TYPE.ordinal()]);
} else if (selectors.length == 3) {
renditionSelector = RenditionSelector.fromSelector(selectors[Selector.TYPE.ordinal()]);
width = NumberUtils.toInt(selectors[Selector.WIDTH.ordinal()]);
height = NumberUtils.toInt(selectors[Selector.HEIGHT.ordinal()]);
} else {
log.debug("Selectors size is not 1 or 3: {}", Arrays.toString(selectors));
return null;
}
if (extension.equals("jpg")) {
log.trace("Updating extension jpg to jpeg");
extension = "jpeg";
}
if (renditionSelector == null) {
log.debug("Rendition type was not recognized: {}", Arrays.toString(selectors));
return null;
}
RenditionMeta meta = new RenditionMeta(renditionSelector.getRenditionType(), width, height, extension);
log.trace("Build rendition meta: {}", meta);
return meta;
}
private static void writeResponse(SlingHttpServletResponse response, InputStream input, String mimeType) throws IOException {
if (mimeType.contains("svg")) {
writeSvg(response, input);
} else {
writeBinaryImage(response, input, mimeType);
}
}
private static void writeBinaryImage(SlingHttpServletResponse response, InputStream input, String mimeType) throws IOException {
String formatName = "JPG";
if (mimeType.contains("png")) formatName = "PNG";
if (mimeType.contains("gif")) formatName = "GIF";
// NOTE: THIS DOES NOT MATTER WHEN DISPATCHER IS IN PLACE
// Dispatcher will use extension of file, it does not save http header
response.setContentType(mimeType);
BufferedImage bi = ImageIO.read(input);
OutputStream out = response.getOutputStream();
ImageIO.write(bi, formatName, out);
out.close();
}
private static void writeSvg(SlingHttpServletResponse response, InputStream input) throws IOException {
response.setContentType("image/svg+xml");
ServletOutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = input.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = input.read(buffer);
}
input.close();
out.close();
}
private static void sendRedirectToOriginalRendition(SlingHttpServletRequest request, SlingHttpServletResponse response, Asset asset) throws IOException {
String requestURL = request.getRequestURL().toString();
String path = asset.getPath();
String ext = getExtension(asset.getMimeType());
String redirect = path + "." + SELECTOR_RENDITION_ORIGINAL + "." + ext;
log.warn("Requested {}, however, rendition not found. Redirecting to {}", requestURL, redirect);
response.sendRedirect(redirect);
}
private static void sendRedirectToProperExtension(SlingHttpServletRequest request, SlingHttpServletResponse response, Rendition rendition, RenditionMeta renditionMeta) throws IOException {
String requestURL = request.getRequestURL().toString();
String requestExt = request.getRequestPathInfo().getExtension();
String newExt = getExtension(rendition.getMimeType());
String redirect = requestURL;
redirect = redirect.replaceAll(requestExt+"$", newExt);
log.warn("Requested {}, however, mime type of rendition is {}. Redirecting to {}", requestURL, rendition.getMimeType(), redirect);
response.sendRedirect(redirect);
}
private static String getExtension(String mimeType) throws IOException {
if (mimeType != null && mimeType.contains("png")) {
return "png";
} else if (mimeType != null && mimeType.contains("jpeg")) {
return "jpg";
} else if (mimeType != null && mimeType.contains("svg")) {
return "svg";
} else if (mimeType != null && mimeType.contains("gif")) {
return "gif";
} else {
throw new IOException("Unsupported mime type " + mimeType);
}
}
private static boolean toBoolean(Object obj) {
if (obj == null) return false;
if (obj instanceof Boolean) return (Boolean) obj;
return BooleanUtils.toBoolean(obj.toString());
}
}
| src/main/java/com/herodigital/wcm/ext/renditions/servlet/ImageRenditionServlet.java | package com.herodigital.wcm.ext.renditions.servlet;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Dictionary;
import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.Rendition;
import com.herodigital.wcm.ext.renditions.model.RenditionMeta;
import com.herodigital.wcm.ext.renditions.service.AssetRenditionResolver;
/**
* Handles fetching of an asset image rendition. Primary advantage over out of the box AEM
* thumbnail servlet is the support of both web, thumbnail, and original renditions.
* <p>
* Resolution of rendition is handled by {@link AssetRenditionResolver}.
* <p>
* 404 response may be returned if requested asset or rendition does not exist (depending on configuration).
*
* @author joelepps
*
*/
@Component(metatype=true, immediate=true, label="Web Image Rendition Servlet", description="Servlet which returns the web image rendition")
@Service(Servlet.class)
@Properties({
@Property(name = "service.description", value = "Servlet which returns the web image rendtions"),
@Property(name = "service.vendor", value = "Hero Digital"),
@Property(name = "sling.servlet.resourceTypes", value="sling/servlet/default", propertyPrivate=true),
@Property(name = "sling.servlet.selectors", value={ImageRenditionServlet.SELECTOR_RENDITION_WEB, ImageRenditionServlet.SELECTOR_RENDITION_THUMB, ImageRenditionServlet.SELECTOR_RENDITION_ORIGINAL }, propertyPrivate=true),
@Property(name = "sling.servlet.extensions", value={ "png", "jpg", "jpeg", "svg" }, propertyPrivate=true),
@Property(name = "sling.servlet.methods", value={ "GET" }, propertyPrivate=true),
})
public class ImageRenditionServlet extends SlingSafeMethodsServlet {
private static final long serialVersionUID = 7272927969196706776L;
private static final Logger log = LoggerFactory.getLogger(ImageRenditionServlet.class);
protected static final String SELECTOR_RENDITION_WEB = "imgw";
protected static final String SELECTOR_RENDITION_THUMB = "imgt";
protected static final String SELECTOR_RENDITION_ORIGINAL = "imgo";
private static enum Selector { TYPE, WIDTH, HEIGHT } // used for ordinal position of selectors
@Property(label = "Redirect On Unsupported Type", description = "Enabled by default. If request is made to a rendition with the wrong extension, a 302 redirect is returned the the URL with the matching extension. If disabled, then 415 error response is returned.", boolValue = true)
public static final String REDIRECT_ON_WRONG_TYPE = "rendition.servlet.redirect.on.wrong.type";
private boolean redirectOnWrongType;
@Property(label = "Redirect On Missing Rendition", description = "Disabled by default. If requested rendition is not found, 404 error response is returned. If enabled, 302 redirect is returned to the original rendition.", boolValue = false)
public static final String REDIRECT_ON_MISSING_RENDITION = "rendition.servlet.redirect.on.missing.rendition";
private boolean redirectOnMissingRendition;
@Reference
private AssetRenditionResolver assetRenditionResolver;
@Activate
@SuppressWarnings("unchecked")
public void activate(ComponentContext context) {
Dictionary<String, ?> properties = context.getProperties();
redirectOnWrongType = toBoolean(properties.get(REDIRECT_ON_WRONG_TYPE));
redirectOnMissingRendition = toBoolean(properties.get(REDIRECT_ON_MISSING_RENDITION));
}
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
// Convert request to convenience object
RenditionMeta renditionMeta = buildRenditionMeta(request);
if (renditionMeta == null) {
log.debug("Failed to build rendition meta for {}", request.getPathInfo());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Resolve image resource
Resource resource = request.getResource();
if (resource == null) {
log.debug("Missing dam asset at {}", request.getPathInfo());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Adapt image resource to dam object
Asset damAsset = resource.adaptTo(Asset.class);
if (damAsset == null) {
log.debug("Cannot resolve dam asset at {} for {}", resource.getPath(), request.getPathInfo());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Resolve dam asset + meta data to actual rendition
Rendition rendition = assetRenditionResolver.resolveRendition(damAsset, renditionMeta);
if (rendition == null) {
if (redirectOnMissingRendition) {
sendRedirectToOriginalRendition(request, response, damAsset);
return;
} else {
log.debug("Missing rendition for {} and {}", renditionMeta, damAsset.getPath());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
// If extension does not match rendition mime type, redirect or 415 error
if (!rendition.getMimeType().contains(renditionMeta.getExtension())) {
if (redirectOnWrongType) {
sendRedirectToProperExtension(request, response, rendition, renditionMeta);
return;
} else {
log.debug("Wrong extension for {} and request {}", rendition.getMimeType(), renditionMeta.getExtension());
response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
return;
}
}
// Handle potential error
InputStream input = rendition.getStream();
if (input == null) {
log.error("Missing rendition input stream for {} and {}", renditionMeta, damAsset.getPath());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
writeResponse(response, input, rendition.getMimeType());
}
private static RenditionMeta buildRenditionMeta(SlingHttpServletRequest request) {
String[] selectors = request.getRequestPathInfo().getSelectors();
String extension = request.getRequestPathInfo().getExtension();
RenditionSelector renditionSelector = null;
int width = 0;
int height = 0;
if (selectors.length >= 1 && SELECTOR_RENDITION_ORIGINAL.equals(selectors[0])) {
// original rendition does not need or parse width/height
renditionSelector = RenditionSelector.fromSelector(selectors[Selector.TYPE.ordinal()]);
} else if (selectors.length == 3) {
renditionSelector = RenditionSelector.fromSelector(selectors[Selector.TYPE.ordinal()]);
width = NumberUtils.toInt(selectors[Selector.WIDTH.ordinal()]);
height = NumberUtils.toInt(selectors[Selector.HEIGHT.ordinal()]);
} else {
log.debug("Selectors size is not 1 or 3: {}", Arrays.toString(selectors));
return null;
}
if (extension.equals("jpg")) {
log.trace("Updating extension jpg to jpeg");
extension = "jpeg";
}
if (renditionSelector == null) {
log.debug("Rendition type was not recognized: {}", Arrays.toString(selectors));
return null;
}
RenditionMeta meta = new RenditionMeta(renditionSelector.getRenditionType(), width, height, extension);
log.trace("Build rendition meta: {}", meta);
return meta;
}
private static void writeResponse(SlingHttpServletResponse response, InputStream input, String mimeType) throws IOException {
if (mimeType.contains("svg")) {
writeSvg(response, input);
} else {
writeBinaryImage(response, input, mimeType);
}
}
private static void writeBinaryImage(SlingHttpServletResponse response, InputStream input, String mimeType) throws IOException {
String formatName = mimeType.contains("png") ? "PNG" : "JPG";
// NOTE: THIS DOES NOT MATTER WITH DISPATCHER IN PLACE
// Dispatcher will use extension of file, it does not save http header
response.setContentType(mimeType);
BufferedImage bi = ImageIO.read(input);
OutputStream out = response.getOutputStream();
ImageIO.write(bi, formatName, out);
out.close();
}
private static void writeSvg(SlingHttpServletResponse response, InputStream input) throws IOException {
response.setContentType("image/svg+xml");
ServletOutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = input.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = input.read(buffer);
}
input.close();
out.close();
}
private static void sendRedirectToOriginalRendition(SlingHttpServletRequest request, SlingHttpServletResponse response, Asset asset) throws IOException {
String requestURL = request.getRequestURL().toString();
String path = asset.getPath();
String ext = getExtension(asset.getMimeType());
String redirect = path + "." + SELECTOR_RENDITION_ORIGINAL + "." + ext;
log.warn("Requested {}, however, rendition not found. Redirecting to {}", requestURL, redirect);
response.sendRedirect(redirect);
}
private static void sendRedirectToProperExtension(SlingHttpServletRequest request, SlingHttpServletResponse response, Rendition rendition, RenditionMeta renditionMeta) throws IOException {
String requestURL = request.getRequestURL().toString();
String requestExt = request.getRequestPathInfo().getExtension();
String newExt = getExtension(rendition.getMimeType());
String redirect = requestURL;
redirect = redirect.replaceAll(requestExt+"$", newExt);
log.warn("Requested {}, however, mime type of rendition is {}. Redirecting to {}", requestURL, rendition.getMimeType(), redirect);
response.sendRedirect(redirect);
}
private static String getExtension(String mimeType) {
if (mimeType != null && mimeType.contains("png")) {
return "png";
} else if (mimeType != null && mimeType.contains("jpeg")) {
return "jpg";
} else if (mimeType != null && mimeType.contains("svg")) {
return "svg";
} else {
log.warn("Unsupported mime type of {}", mimeType);
return "jpg"; // default
}
}
private static boolean toBoolean(Object obj) {
if (obj == null) return false;
if (obj instanceof Boolean) return (Boolean) obj;
return BooleanUtils.toBoolean(obj.toString());
}
}
| Added gif support
| src/main/java/com/herodigital/wcm/ext/renditions/servlet/ImageRenditionServlet.java | Added gif support | <ide><path>rc/main/java/com/herodigital/wcm/ext/renditions/servlet/ImageRenditionServlet.java
<ide> @Property(name = "service.vendor", value = "Hero Digital"),
<ide> @Property(name = "sling.servlet.resourceTypes", value="sling/servlet/default", propertyPrivate=true),
<ide> @Property(name = "sling.servlet.selectors", value={ImageRenditionServlet.SELECTOR_RENDITION_WEB, ImageRenditionServlet.SELECTOR_RENDITION_THUMB, ImageRenditionServlet.SELECTOR_RENDITION_ORIGINAL }, propertyPrivate=true),
<del> @Property(name = "sling.servlet.extensions", value={ "png", "jpg", "jpeg", "svg" }, propertyPrivate=true),
<add> @Property(name = "sling.servlet.extensions", value={ "png", "jpg", "jpeg", "svg", "gif" }, propertyPrivate=true),
<ide> @Property(name = "sling.servlet.methods", value={ "GET" }, propertyPrivate=true),
<ide> })
<ide> public class ImageRenditionServlet extends SlingSafeMethodsServlet {
<ide> }
<ide>
<ide> private static void writeBinaryImage(SlingHttpServletResponse response, InputStream input, String mimeType) throws IOException {
<del> String formatName = mimeType.contains("png") ? "PNG" : "JPG";
<del>
<del> // NOTE: THIS DOES NOT MATTER WITH DISPATCHER IN PLACE
<add> String formatName = "JPG";
<add> if (mimeType.contains("png")) formatName = "PNG";
<add> if (mimeType.contains("gif")) formatName = "GIF";
<add>
<add> // NOTE: THIS DOES NOT MATTER WHEN DISPATCHER IS IN PLACE
<ide> // Dispatcher will use extension of file, it does not save http header
<ide> response.setContentType(mimeType);
<ide>
<ide> response.sendRedirect(redirect);
<ide> }
<ide>
<del> private static String getExtension(String mimeType) {
<add> private static String getExtension(String mimeType) throws IOException {
<ide> if (mimeType != null && mimeType.contains("png")) {
<ide> return "png";
<ide> } else if (mimeType != null && mimeType.contains("jpeg")) {
<ide> return "jpg";
<ide> } else if (mimeType != null && mimeType.contains("svg")) {
<ide> return "svg";
<add> } else if (mimeType != null && mimeType.contains("gif")) {
<add> return "gif";
<ide> } else {
<del> log.warn("Unsupported mime type of {}", mimeType);
<del> return "jpg"; // default
<add> throw new IOException("Unsupported mime type " + mimeType);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 5db5881c66bd7b02ecb81a3cee4b0a7ecb31780a | 0 | gosu-lang/gosu-lang,gosu-lang/gosu-lang,gosu-lang/gosu-lang,gosu-lang/gosu-lang | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.internal.gosu.compiler;
import gw.config.CommonServices;
import gw.internal.gosu.ir.TransformingCompiler;
import gw.internal.gosu.ir.transform.AbstractElementTransformer;
import gw.internal.gosu.parser.ICompilableTypeInternal;
import gw.internal.gosu.parser.IGosuClassInternal;
import gw.internal.gosu.parser.IGosuProgramInternal;
import gw.internal.gosu.parser.ModuleClassLoader;
import gw.internal.gosu.parser.NewIntrospector;
import gw.internal.gosu.parser.TypeLord;
import gw.lang.reflect.IGosuClassLoadingObserver;
import gw.lang.reflect.IHasJavaClass;
import gw.lang.reflect.IType;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.gs.BytecodeOptions;
import gw.lang.reflect.gs.GosuClassPathThing;
import gw.lang.reflect.gs.ICompilableType;
import gw.lang.reflect.gs.IGosuClassLoader;
import gw.lang.reflect.gs.IGosuProgram;
import gw.lang.reflect.java.IJavaBackedType;
import gw.lang.reflect.java.IJavaType;
import gw.lang.reflect.java.JavaTypes;
import gw.lang.reflect.module.TypeSystemLockHelper;
import gw.util.GosuExceptionUtil;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLClassLoader;
import java.util.List;
public class GosuClassLoader implements IGosuClassLoader
{
private ClassLoader _loader;
//## For tests only
public static GosuClassLoader instance()
{
return (GosuClassLoader)TypeSystem.getGosuClassLoader();
}
@Override
public void dumpAllClasses()
{
// We also need to clear out anything added to some static map of random stuff due
// to the compilation of the now-orphaned classes. Side-note: this doesn't need to
// be an instance method, since it's calling static helpers, but it's an instance
// method at the moment so it can appear on IGosuClassLoader and make it through
// the wall and be usable from gosu-core-api
AbstractElementTransformer.clearCustomRuntimes();
}
@Override
public byte[] getBytes( ICompilableType gsClass )
{
try
{
return compileClass( gsClass, false );
}
catch( Exception pre )
{
throw GosuExceptionUtil.forceThrow( new IOException( pre ) );
}
}
public GosuClassLoader( ClassLoader parent )
{
assignParent( parent );
init();
}
// Note this really assigns the actual class loader associated with Gosu (now that Gosu loads its classes in the java App loader)
public void assignParent( ClassLoader parent )
{
if( parent instanceof ModuleClassLoader && ((ModuleClassLoader)parent).isDeferToParent() )
{
// For a given module, the loader that loads Gosu classes *must* also be the loader that loads Java classes.
// In the case where we are using the single default module (the normal mode for Gosu's runtime) the module
// class loader does nothing, it doesn't have a classpath, so we don't want to add our gosuclass protocol to
// its classpath, instead we want to add it to its parent, which has the classpath for the everything, including
// the Java classfiled (and potential Gosu classfiles) in the module.
// The driving force behind doing this is that, if gosu classes are persisted to disk, we want Java to load
// them as a normal class, but we also need for the loader to be able to resolve Gosu classes that may not
// have (or could not have) been written to disk. For instance, fragments and dynamic programs are compiled
// at runtime and therefore can't be precompiled -- they are compiled on demand so the gosuclass protocol,
// being in the classpath of the app class loader, resolves the name and compile the class and produce the
// resource/stream associated with the compiled bytes.
_loader = parent.getParent();
}
else
{
_loader = parent;
}
}
private void init()
{
// Keep parse trees
}
public ClassLoader getLoader()
{
return _loader;
}
@Override
public Class loadClass( String strName ) throws ClassNotFoundException
{
TypeSystemLockHelper.getTypeSystemLockWithMonitor(_loader);
try
{
String strGsName = strName.replace( '$', '.' );
//## hack:
if (strGsName.startsWith("com.guidewire.commons.metadata.proxy._generated.iface.")) {
strGsName = "entity." + strGsName.substring(strName.lastIndexOf('.') + 1);
}
IType type = TypeSystem.getByFullNameIfValid( strGsName );
if( type instanceof IGosuClassInternal )
{
return ((IGosuClassInternal)type).getBackingClass();
}
else if( type instanceof IJavaBackedType )
{
return ((IJavaBackedType)type).getBackingClass();
}
return _loader.loadClass( strName );
}
finally
{
TypeSystem.unlock();
}
}
@Override
public Class<?> findClass( String strName ) throws ClassNotFoundException {
return loadClass( strName );
}
@Override
public IJavaType getFunctionClassForArity(int length)
{
return FunctionClassUtil.getFunctionClassForArity( length );
}
public Class defineClass( ICompilableTypeInternal gsClass, boolean useSingleServingLoader ) throws ClassNotFoundException
{
try
{
if( gsClass instanceof IGosuClassInternal && ((IGosuClassInternal)gsClass).hasBackingClass() )
{
return ((IGosuClassInternal)gsClass).getBackingClass();
}
// there is no point in defining eval classes in a single serving class loader (it wastes memory)
if( useSingleServingLoader || TypeLord.isEvalProgram( gsClass ) || isThrowawayProgram( gsClass ) || isEnclosingTypeInSingleServingLoader( gsClass ) )
{
// These classes are "fire and forget"; they need to be disposable after they run,
// so we load them in a separate class loader so we can unload them -- it's the only
// way to unload a class in java.
return defineClassInLoader( gsClass, true );
}
return findOrDefineClass( gsClass );
}
catch( Exception e )
{
throw GosuExceptionUtil.forceThrow( e, gsClass.getName() );
}
}
private boolean isEnclosingTypeInSingleServingLoader( ICompilableTypeInternal gsClass )
{
ICompilableTypeInternal enclosingType = gsClass.getEnclosingType();
ClassLoader enclosingLoader = getClassLoader( enclosingType );
return enclosingLoader instanceof SingleServingGosuClassLoader;
}
private Class findOrDefineClass( ICompilableTypeInternal gsClass ) throws ClassNotFoundException
{
String strName = getJavaName( gsClass );
Class cls = null;
try
{
cls = _loader.loadClass( strName );
if( cls.getClassLoader() instanceof SingleServingGosuClassLoader )
{
if( ((SingleServingGosuClassLoader)cls.getClassLoader()).isDisposed() )
{
cls = null;
}
}
}
catch( ClassNotFoundException cnfe )
{
TypeSystem.lock();
try
{
cls = defineClassInLoader( gsClass, false );
}
finally
{
TypeSystem.unlock();
}
}
return cls;
}
private Class defineClassInLoader( ICompilableTypeInternal gsClass, boolean forceSingleServingLoader )
{
if( forceSingleServingLoader || shouldUseSingleServingLoader( gsClass ) || BytecodeOptions.isSingleServingLoader() )
{
ICompilableTypeInternal enclosingType = gsClass.getEnclosingType();
ClassLoader enclosingLoader = isOldStyleGosuAnnotationExpression(gsClass) ? null : getClassLoader( enclosingType );
SingleServingGosuClassLoader loader = enclosingLoader instanceof SingleServingGosuClassLoader
? (SingleServingGosuClassLoader)enclosingLoader
: new SingleServingGosuClassLoader( this );
return defineClassInSingleServingLoader( gsClass, loader );
}
else
{
return defineAndMaybeVerify( gsClass );
}
}
private boolean isOldStyleGosuAnnotationExpression(ICompilableTypeInternal gsClass)
{
if( !(gsClass instanceof IGosuProgram) )
{
return false;
}
final IType expectedReturnType = ((IGosuProgram) gsClass).getExpectedReturnType();
return expectedReturnType != null && JavaTypes.IANNOTATION().isAssignableFrom( expectedReturnType );
}
private ClassLoader getClassLoader( ICompilableTypeInternal enclosingType ) {
if( enclosingType == null ) {
return null;
}
Class cached = SingleServingGosuClassLoader.getCached( enclosingType );
if( cached != null ) {
return cached.getClassLoader();
}
return enclosingType instanceof IJavaBackedType
? ((IJavaBackedType)enclosingType).getBackingClass().getClassLoader()
: enclosingType instanceof IHasJavaClass
? ((IHasJavaClass)enclosingType).getBackingClass().getClassLoader()
: null;
}
private Class<?> defineClassInSingleServingLoader( ICompilableTypeInternal gsClass, SingleServingGosuClassLoader loader ) {
Class<?> result = loader._defineClass( gsClass );
// Define all inner classes and blocks, too. Otherwise, they eventually could be loaded through URL handler.
for (int i = 0; i < gsClass.getBlockCount(); i++) {
defineClassInSingleServingLoader( (ICompilableTypeInternal)gsClass.getBlock(i), loader );
}
if( gsClass.getInnerClasses() != null ) {
for( IType inner: gsClass.getInnerClasses() ) {
try {
defineClassInSingleServingLoader( (ICompilableTypeInternal)inner, loader );
}
catch( LinkageError le ) {
// ignore case when we've already loaded the class
}
}
}
return result;
}
private boolean shouldUseSingleServingLoader(ICompilableTypeInternal gsClass) {
List<IGosuClassLoadingObserver> observers = CommonServices.getEntityAccess().getGosuClassLoadingObservers();
if (observers != null) {
for (IGosuClassLoadingObserver observer : observers) {
if (observer.shouldUseSingleServingLoader(gsClass)) {
return true;
}
}
}
return false;
}
boolean shouldDebugClass( ICompilableType gsClass )
{
return BytecodeOptions.shouldDebug( gsClass.getName() );
}
private Class defineAndMaybeVerify( ICompilableTypeInternal gsClass )
{
try
{
GosuClassPathThing.init();
String strJavaClass = getJavaName( gsClass );
Class cls = _loader.loadClass( strJavaClass );
if( BytecodeOptions.aggressivelyVerify() )
{
NewIntrospector.getDeclaredMethods( cls );
cls.getDeclaredMethods(); //force verification
}
return cls;
}
catch( ClassFormatError ve )
{
if( BytecodeOptions.aggressivelyVerify() )
{
compileClass( gsClass, true ); // print the bytecode
}
throw ve;
}
catch( VerifyError ve )
{
if( BytecodeOptions.aggressivelyVerify() )
{
compileClass( gsClass, true ); // print the bytecode
}
throw ve;
}
catch( ClassNotFoundException e )
{
throw new RuntimeException( e );
}
}
private static byte[] compileClass( ICompilableType type, boolean debug )
{
return TransformingCompiler.compileClass( type, debug );
}
private String getJavaName( ICompilableType type )
{
if( type != null )
{
type = TypeLord.getPureGenericType( type );
IType outerType = type.getEnclosingType();
if( outerType != null )
{
return getJavaName( outerType ) + "$" + type.getRelativeName();
}
return type.getName();
}
return null;
}
private boolean isThrowawayProgram( ICompilableType gsClass ) {
return gsClass instanceof IGosuProgramInternal && ((IGosuProgramInternal) gsClass).isThrowaway();
}
@Override
public ClassLoader getActualLoader() {
return getLoader();
}
@Override
public Class defineClass( String name, byte[] bytes )
{
TypeSystem.lock();
try
{
Method defineClass = ClassLoader.class.getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class );
defineClass.setAccessible( true );
return (Class)defineClass.invoke( _loader, name, bytes, 0, bytes.length );
}
catch( Exception e )
{
throw GosuExceptionUtil.forceThrow( e );
}
finally
{
TypeSystem.unlock();
}
}
public static String getJavaName( IType type )
{
if( type != null )
{
type = TypeLord.getPureGenericType( type );
IType outerType = type.getEnclosingType();
if( outerType != null )
{
return getJavaName( outerType ) + "$" + type.getRelativeName();
}
return type.getName();
}
return null;
}
}
| gosu-core/src/main/java/gw/internal/gosu/compiler/GosuClassLoader.java | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.internal.gosu.compiler;
import gw.config.CommonServices;
import gw.internal.gosu.ir.TransformingCompiler;
import gw.internal.gosu.ir.transform.AbstractElementTransformer;
import gw.internal.gosu.parser.ICompilableTypeInternal;
import gw.internal.gosu.parser.IGosuClassInternal;
import gw.internal.gosu.parser.IGosuProgramInternal;
import gw.internal.gosu.parser.ModuleClassLoader;
import gw.internal.gosu.parser.NewIntrospector;
import gw.internal.gosu.parser.TypeLord;
import gw.lang.reflect.IGosuClassLoadingObserver;
import gw.lang.reflect.IHasJavaClass;
import gw.lang.reflect.IType;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.gs.BytecodeOptions;
import gw.lang.reflect.gs.GosuClassPathThing;
import gw.lang.reflect.gs.ICompilableType;
import gw.lang.reflect.gs.IGosuClassLoader;
import gw.lang.reflect.gs.IGosuProgram;
import gw.lang.reflect.java.IJavaBackedType;
import gw.lang.reflect.java.IJavaType;
import gw.lang.reflect.java.JavaTypes;
import gw.lang.reflect.module.TypeSystemLockHelper;
import gw.util.GosuExceptionUtil;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLClassLoader;
import java.util.List;
public class GosuClassLoader implements IGosuClassLoader
{
private ClassLoader _loader;
//## For tests only
public static GosuClassLoader instance()
{
return (GosuClassLoader)TypeSystem.getGosuClassLoader();
}
@Override
public void dumpAllClasses()
{
// We also need to clear out anything added to some static map of random stuff due
// to the compilation of the now-orphaned classes. Side-note: this doesn't need to
// be an instance method, since it's calling static helpers, but it's an instance
// method at the moment so it can appear on IGosuClassLoader and make it through
// the wall and be usable from gosu-core-api
AbstractElementTransformer.clearCustomRuntimes();
}
@Override
public byte[] getBytes( ICompilableType gsClass )
{
try
{
return compileClass( gsClass, false );
}
catch( Exception pre )
{
throw GosuExceptionUtil.forceThrow( new IOException( pre ) );
}
}
public GosuClassLoader( ClassLoader parent )
{
assignParent( parent );
init();
}
// Note this really assigns the actual class loader associated with Gosu (now that Gosu loads its classes in the java App loader)
public void assignParent( ClassLoader parent )
{
if( parent instanceof ModuleClassLoader && ((ModuleClassLoader)parent).isDeferToParent() )
{
// For a given module, the loader that loads Gosu classes *must* also be the loader that loads Java classes.
// In the case where we are using the single default module (the normal mode for Gosu's runtime) the module
// class loader does nothing, it doesn't have a classpath, so we don't want to add our gosuclass protocol to
// its classpath, instead we want to add it to its parent, which has the classpath for the everything, including
// the Java classfiled (and potential Gosu classfiles) in the module.
// The driving force behind doing this is that, if gosu classes are persisted to disk, we want Java to load
// them as a normal class, but we also need for the loader to be able to resolve Gosu classes that may not
// have (or could not have) been written to disk. For instance, fragments and dynamic programs are compiled
// at runtime and therefore can't be precompiled -- they are compiled on demand so the gosuclass protocol,
// being in the classpath of the app class loader, resolves the name and compile the class and produce the
// resource/stream associated with the compiled bytes.
_loader = parent.getParent();
while( _loader instanceof URLClassLoader )
{
if( ((URLClassLoader) _loader).getURLs().length != 0 )
{
break;
}
_loader = _loader.getParent();
}
}
else
{
_loader = parent;
}
}
private void init()
{
// Keep parse trees
}
public ClassLoader getLoader()
{
return _loader;
}
@Override
public Class loadClass( String strName ) throws ClassNotFoundException
{
TypeSystemLockHelper.getTypeSystemLockWithMonitor(_loader);
try
{
String strGsName = strName.replace( '$', '.' );
//## hack:
if (strGsName.startsWith("com.guidewire.commons.metadata.proxy._generated.iface.")) {
strGsName = "entity." + strGsName.substring(strName.lastIndexOf('.') + 1);
}
IType type = TypeSystem.getByFullNameIfValid( strGsName );
if( type instanceof IGosuClassInternal )
{
return ((IGosuClassInternal)type).getBackingClass();
}
else if( type instanceof IJavaBackedType )
{
return ((IJavaBackedType)type).getBackingClass();
}
return _loader.loadClass( strName );
}
finally
{
TypeSystem.unlock();
}
}
@Override
public Class<?> findClass( String strName ) throws ClassNotFoundException {
return loadClass( strName );
}
@Override
public IJavaType getFunctionClassForArity(int length)
{
return FunctionClassUtil.getFunctionClassForArity( length );
}
public Class defineClass( ICompilableTypeInternal gsClass, boolean useSingleServingLoader ) throws ClassNotFoundException
{
try
{
if( gsClass instanceof IGosuClassInternal && ((IGosuClassInternal)gsClass).hasBackingClass() )
{
return ((IGosuClassInternal)gsClass).getBackingClass();
}
// there is no point in defining eval classes in a single serving class loader (it wastes memory)
if( useSingleServingLoader || TypeLord.isEvalProgram( gsClass ) || isThrowawayProgram( gsClass ) || isEnclosingTypeInSingleServingLoader( gsClass ) )
{
// These classes are "fire and forget"; they need to be disposable after they run,
// so we load them in a separate class loader so we can unload them -- it's the only
// way to unload a class in java.
return defineClassInLoader( gsClass, true );
}
return findOrDefineClass( gsClass );
}
catch( Exception e )
{
throw GosuExceptionUtil.forceThrow( e, gsClass.getName() );
}
}
private boolean isEnclosingTypeInSingleServingLoader( ICompilableTypeInternal gsClass )
{
ICompilableTypeInternal enclosingType = gsClass.getEnclosingType();
ClassLoader enclosingLoader = getClassLoader( enclosingType );
return enclosingLoader instanceof SingleServingGosuClassLoader;
}
private Class findOrDefineClass( ICompilableTypeInternal gsClass ) throws ClassNotFoundException
{
String strName = getJavaName( gsClass );
Class cls = null;
try
{
cls = _loader.loadClass( strName );
if( cls.getClassLoader() instanceof SingleServingGosuClassLoader )
{
if( ((SingleServingGosuClassLoader)cls.getClassLoader()).isDisposed() )
{
cls = null;
}
}
}
catch( ClassNotFoundException cnfe )
{
TypeSystem.lock();
try
{
cls = defineClassInLoader( gsClass, false );
}
finally
{
TypeSystem.unlock();
}
}
return cls;
}
private Class defineClassInLoader( ICompilableTypeInternal gsClass, boolean forceSingleServingLoader )
{
if( forceSingleServingLoader || shouldUseSingleServingLoader( gsClass ) || BytecodeOptions.isSingleServingLoader() )
{
ICompilableTypeInternal enclosingType = gsClass.getEnclosingType();
ClassLoader enclosingLoader = isOldStyleGosuAnnotationExpression(gsClass) ? null : getClassLoader( enclosingType );
SingleServingGosuClassLoader loader = enclosingLoader instanceof SingleServingGosuClassLoader
? (SingleServingGosuClassLoader)enclosingLoader
: new SingleServingGosuClassLoader( this );
return defineClassInSingleServingLoader( gsClass, loader );
}
else
{
return defineAndMaybeVerify( gsClass );
}
}
private boolean isOldStyleGosuAnnotationExpression(ICompilableTypeInternal gsClass)
{
if( !(gsClass instanceof IGosuProgram) )
{
return false;
}
final IType expectedReturnType = ((IGosuProgram) gsClass).getExpectedReturnType();
return expectedReturnType != null && JavaTypes.IANNOTATION().isAssignableFrom( expectedReturnType );
}
private ClassLoader getClassLoader( ICompilableTypeInternal enclosingType ) {
if( enclosingType == null ) {
return null;
}
Class cached = SingleServingGosuClassLoader.getCached( enclosingType );
if( cached != null ) {
return cached.getClassLoader();
}
return enclosingType instanceof IJavaBackedType
? ((IJavaBackedType)enclosingType).getBackingClass().getClassLoader()
: enclosingType instanceof IHasJavaClass
? ((IHasJavaClass)enclosingType).getBackingClass().getClassLoader()
: null;
}
private Class<?> defineClassInSingleServingLoader( ICompilableTypeInternal gsClass, SingleServingGosuClassLoader loader ) {
Class<?> result = loader._defineClass( gsClass );
// Define all inner classes and blocks, too. Otherwise, they eventually could be loaded through URL handler.
for (int i = 0; i < gsClass.getBlockCount(); i++) {
defineClassInSingleServingLoader( (ICompilableTypeInternal)gsClass.getBlock(i), loader );
}
if( gsClass.getInnerClasses() != null ) {
for( IType inner: gsClass.getInnerClasses() ) {
try {
defineClassInSingleServingLoader( (ICompilableTypeInternal)inner, loader );
}
catch( LinkageError le ) {
// ignore case when we've already loaded the class
}
}
}
return result;
}
private boolean shouldUseSingleServingLoader(ICompilableTypeInternal gsClass) {
List<IGosuClassLoadingObserver> observers = CommonServices.getEntityAccess().getGosuClassLoadingObservers();
if (observers != null) {
for (IGosuClassLoadingObserver observer : observers) {
if (observer.shouldUseSingleServingLoader(gsClass)) {
return true;
}
}
}
return false;
}
boolean shouldDebugClass( ICompilableType gsClass )
{
return BytecodeOptions.shouldDebug( gsClass.getName() );
}
private Class defineAndMaybeVerify( ICompilableTypeInternal gsClass )
{
try
{
GosuClassPathThing.init();
String strJavaClass = getJavaName( gsClass );
Class cls = _loader.loadClass( strJavaClass );
if( BytecodeOptions.aggressivelyVerify() )
{
NewIntrospector.getDeclaredMethods( cls );
cls.getDeclaredMethods(); //force verification
}
return cls;
}
catch( ClassFormatError ve )
{
if( BytecodeOptions.aggressivelyVerify() )
{
compileClass( gsClass, true ); // print the bytecode
}
throw ve;
}
catch( VerifyError ve )
{
if( BytecodeOptions.aggressivelyVerify() )
{
compileClass( gsClass, true ); // print the bytecode
}
throw ve;
}
catch( ClassNotFoundException e )
{
throw new RuntimeException( e );
}
}
private static byte[] compileClass( ICompilableType type, boolean debug )
{
return TransformingCompiler.compileClass( type, debug );
}
private String getJavaName( ICompilableType type )
{
if( type != null )
{
type = TypeLord.getPureGenericType( type );
IType outerType = type.getEnclosingType();
if( outerType != null )
{
return getJavaName( outerType ) + "$" + type.getRelativeName();
}
return type.getName();
}
return null;
}
private boolean isThrowawayProgram( ICompilableType gsClass ) {
return gsClass instanceof IGosuProgramInternal && ((IGosuProgramInternal) gsClass).isThrowaway();
}
@Override
public ClassLoader getActualLoader() {
return getLoader();
}
@Override
public Class defineClass( String name, byte[] bytes )
{
TypeSystem.lock();
try
{
Method defineClass = ClassLoader.class.getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class );
defineClass.setAccessible( true );
return (Class)defineClass.invoke( _loader, name, bytes, 0, bytes.length );
}
catch( Exception e )
{
throw GosuExceptionUtil.forceThrow( e );
}
finally
{
TypeSystem.unlock();
}
}
public static String getJavaName( IType type )
{
if( type != null )
{
type = TypeLord.getPureGenericType( type );
IType outerType = type.getEnclosingType();
if( outerType != null )
{
return getJavaName( outerType ) + "$" + type.getRelativeName();
}
return type.getName();
}
return null;
}
}
| Revert "Gets the topmost classloader if children are empty"
This reverts commit f288e9c1cd58ce89966a271c64560a160b117ce9.
| gosu-core/src/main/java/gw/internal/gosu/compiler/GosuClassLoader.java | Revert "Gets the topmost classloader if children are empty" | <ide><path>osu-core/src/main/java/gw/internal/gosu/compiler/GosuClassLoader.java
<ide> // being in the classpath of the app class loader, resolves the name and compile the class and produce the
<ide> // resource/stream associated with the compiled bytes.
<ide> _loader = parent.getParent();
<del> while( _loader instanceof URLClassLoader )
<del> {
<del> if( ((URLClassLoader) _loader).getURLs().length != 0 )
<del> {
<del> break;
<del> }
<del> _loader = _loader.getParent();
<del> }
<ide> }
<ide> else
<ide> { |
|
JavaScript | apache-2.0 | fe8138e5f84a32584edb6835be670a3a785a4521 | 0 | gsanthosh91/zeroclickinfo-goodies,karankrishna/zeroclickinfo-goodies,jgkamat/zeroclickinfo-goodies,visal19/zeroclickinfo-goodies,shubhamrajput/zeroclickinfo-goodies,GrandpaCardigan/zeroclickinfo-goodies,comatory/zeroclickinfo-goodies,sagarhani/zeroclickinfo-goodies,aleksandar-todorovic/zeroclickinfo-goodies,chriskaschner/zeroclickinfo-goodies,SvetlanaZem/zeroclickinfo-goodies,ankushg07/zeroclickinfo-goodies,NateBrune/zeroclickinfo-goodies,loganom/zeroclickinfo-goodies,comatory/zeroclickinfo-goodies,glindste/zeroclickinfo-goodies,lxndio/zeroclickinfo-goodies,zblair/zeroclickinfo-goodies,tharunreddysai/zeroclickinfo-goodies,salmanfarisvp/zeroclickinfo-goodies,Kakkoroid/zeroclickinfo-goodies,mr-karan/zeroclickinfo-goodies,NateBrune/zeroclickinfo-goodies,P71/zeroclickinfo-goodies,aasoliz/zeroclickinfo-goodies,PierreZ/zeroclickinfo-goodies,kavithaRajagopalan/zeroclickinfo-goodies,aasoliz/zeroclickinfo-goodies,charles-l/zeroclickinfo-goodies,ecelis/zeroclickinfo-goodies,samskeller/zeroclickinfo-goodies,seisfeld/zeroclickinfo-goodies,technoabh/zeroclickinfo-goodies,NateBrune/zeroclickinfo-goodies,karankrishna/zeroclickinfo-goodies,CuriousLearner/zeroclickinfo-goodies,lights0123/zeroclickinfo-goodies,abinabrahamanchery/zeroclickinfo-goodies,chriskaschner/zeroclickinfo-goodies,GrandpaCardigan/zeroclickinfo-goodies,regagain/zeroclickinfo-goodies,iambibhas/zeroclickinfo-goodies,ecelis/zeroclickinfo-goodies,oliverdunk/zeroclickinfo-goodies,NateBrune/zeroclickinfo-goodies,Edvac/zeroclickinfo-goodies,ankushg07/zeroclickinfo-goodies,samskeller/zeroclickinfo-goodies,viluon/zeroclickinfo-goodies,tagawa/zeroclickinfo-goodies,codenirvana/zeroclickinfo-goodies,weathermaker/zeroclickinfo-goodies,Edvac/zeroclickinfo-goodies,gsanthosh91/zeroclickinfo-goodies,RomainLG/zeroclickinfo-goodies,alohaas/zeroclickinfo-goodies,zblair/zeroclickinfo-goodies,oliverdunk/zeroclickinfo-goodies,Midhun-Jo-Antony/zeroclickinfo-goodies,Edvac/zeroclickinfo-goodies,chriskaschner/zeroclickinfo-goodies,karankrishna/zeroclickinfo-goodies,PierreZ/zeroclickinfo-goodies,paulmolluzzo/zeroclickinfo-goodies,leekinney/zeroclickinfo-goodies,technoabh/zeroclickinfo-goodies,Kr1tya3/zeroclickinfo-goodies,fired334/zeroclickinfo-goodies,alohaas/zeroclickinfo-goodies,loganom/zeroclickinfo-goodies,visal19/zeroclickinfo-goodies,Midhun-Jo-Antony/zeroclickinfo-goodies,ericlake/zeroclickinfo-goodies,dnmfarrell/zeroclickinfo-goodies,Shugabuga/zeroclickinfo-goodies,shubhamrajput/zeroclickinfo-goodies,brianlechthaler/zeroclickinfo-goodies,shyamalschandra/zeroclickinfo-goodies,tagawa/zeroclickinfo-goodies,jophab/zeroclickinfo-goodies,Edvac/zeroclickinfo-goodies,karankrishna/zeroclickinfo-goodies,brianlechthaler/zeroclickinfo-goodies,weathermaker/zeroclickinfo-goodies,sagarhani/zeroclickinfo-goodies,comatory/zeroclickinfo-goodies,jamessun/zeroclickinfo-goodies,chriskaschner/zeroclickinfo-goodies,fired334/zeroclickinfo-goodies,dnmfarrell/zeroclickinfo-goodies,leekinney/zeroclickinfo-goodies,fired334/zeroclickinfo-goodies,gsanthosh91/zeroclickinfo-goodies,pratts/zeroclickinfo-goodies,visal19/zeroclickinfo-goodies,GrandpaCardigan/zeroclickinfo-goodies,loganom/zeroclickinfo-goodies,RomainLG/zeroclickinfo-goodies,kavithaRajagopalan/zeroclickinfo-goodies,alfredmaliakal/zeroclickinfo-goodies,gsanthosh91/zeroclickinfo-goodies,viluon/zeroclickinfo-goodies,zblair/zeroclickinfo-goodies,lamanh/zeroclickinfo-goodies,aleksandar-todorovic/zeroclickinfo-goodies,Kr1tya3/zeroclickinfo-goodies,GrandpaCardigan/zeroclickinfo-goodies,tagawa/zeroclickinfo-goodies,charles-l/zeroclickinfo-goodies,Midhun-Jo-Antony/zeroclickinfo-goodies,leekinney/zeroclickinfo-goodies,Kr1tya3/zeroclickinfo-goodies,urohit011/zeroclickinfo-goodies,GrandpaCardigan/zeroclickinfo-goodies,visal19/zeroclickinfo-goodies,regagain/zeroclickinfo-goodies,shyamalschandra/zeroclickinfo-goodies,aasoliz/zeroclickinfo-goodies,Shugabuga/zeroclickinfo-goodies,codenirvana/zeroclickinfo-goodies,oliverdunk/zeroclickinfo-goodies,ecelis/zeroclickinfo-goodies,comatory/zeroclickinfo-goodies,brianlechthaler/zeroclickinfo-goodies,pratts/zeroclickinfo-goodies,PierreZ/zeroclickinfo-goodies,kavithaRajagopalan/zeroclickinfo-goodies,paulmolluzzo/zeroclickinfo-goodies,iambibhas/zeroclickinfo-goodies,akanshgulati/zeroclickinfo-goodies,synbit/zeroclickinfo-goodies,P71/zeroclickinfo-goodies,lights0123/zeroclickinfo-goodies,chriskaschner/zeroclickinfo-goodies,kavithaRajagopalan/zeroclickinfo-goodies,ankushg07/zeroclickinfo-goodies,jgkamat/zeroclickinfo-goodies,pratts/zeroclickinfo-goodies,codenirvana/zeroclickinfo-goodies,lights0123/zeroclickinfo-goodies,JamyGolden/zeroclickinfo-goodies,gautamkrishnar/zeroclickinfo-goodies,NateBrune/zeroclickinfo-goodies,brianlechthaler/zeroclickinfo-goodies,oliverdunk/zeroclickinfo-goodies,ankushg07/zeroclickinfo-goodies,rahul-raturi/zeroclickinfo-goodies,samskeller/zeroclickinfo-goodies,jgkamat/zeroclickinfo-goodies,weathermaker/zeroclickinfo-goodies,dnmfarrell/zeroclickinfo-goodies,PierreZ/zeroclickinfo-goodies,mohan08p/zeroclickinfo-goodies,alfredmaliakal/zeroclickinfo-goodies,urohit011/zeroclickinfo-goodies,codenirvana/zeroclickinfo-goodies,GrandpaCardigan/zeroclickinfo-goodies,cosimo/zeroclickinfo-goodies,ericlake/zeroclickinfo-goodies,visal19/zeroclickinfo-goodies,Edvac/zeroclickinfo-goodies,mr-karan/zeroclickinfo-goodies,ecelis/zeroclickinfo-goodies,sagarhani/zeroclickinfo-goodies,glindste/zeroclickinfo-goodies,synbit/zeroclickinfo-goodies,iambibhas/zeroclickinfo-goodies,visal19/zeroclickinfo-goodies,abinabrahamanchery/zeroclickinfo-goodies,jophab/zeroclickinfo-goodies,loganom/zeroclickinfo-goodies,regagain/zeroclickinfo-goodies,shubhamrajput/zeroclickinfo-goodies,paulmolluzzo/zeroclickinfo-goodies,jamessun/zeroclickinfo-goodies,aasoliz/zeroclickinfo-goodies,Kr1tya3/zeroclickinfo-goodies,thechunsik/zeroclickinfo-goodies,shubhamrajput/zeroclickinfo-goodies,glindste/zeroclickinfo-goodies,Kakkoroid/zeroclickinfo-goodies,aasoliz/zeroclickinfo-goodies,CuriousLearner/zeroclickinfo-goodies,mohan08p/zeroclickinfo-goodies,alohaas/zeroclickinfo-goodies,regagain/zeroclickinfo-goodies,rahul-raturi/zeroclickinfo-goodies,CuriousLearner/zeroclickinfo-goodies,viluon/zeroclickinfo-goodies,akanshgulati/zeroclickinfo-goodies,Shugabuga/zeroclickinfo-goodies,shyamalschandra/zeroclickinfo-goodies,SvetlanaZem/zeroclickinfo-goodies,shubhamrajput/zeroclickinfo-goodies,abinabrahamanchery/zeroclickinfo-goodies,alfredmaliakal/zeroclickinfo-goodies,lxndio/zeroclickinfo-goodies,loganom/zeroclickinfo-goodies,Edvac/zeroclickinfo-goodies,lights0123/zeroclickinfo-goodies,SvetlanaZem/zeroclickinfo-goodies,thechunsik/zeroclickinfo-goodies,Kakkoroid/zeroclickinfo-goodies,lxndio/zeroclickinfo-goodies,PierreZ/zeroclickinfo-goodies,samskeller/zeroclickinfo-goodies,NateBrune/zeroclickinfo-goodies,mohan08p/zeroclickinfo-goodies,Gabrielt014/zeroclickinfo-goodies,mohan08p/zeroclickinfo-goodies,seisfeld/zeroclickinfo-goodies,lights0123/zeroclickinfo-goodies,jgkamat/zeroclickinfo-goodies,technoabh/zeroclickinfo-goodies,weathermaker/zeroclickinfo-goodies,JamyGolden/zeroclickinfo-goodies,marianosimone/zeroclickinfo-goodies,Midhun-Jo-Antony/zeroclickinfo-goodies,nagromc/zeroclickinfo-goodies,tharunreddysai/zeroclickinfo-goodies,RomainLG/zeroclickinfo-goodies,P71/zeroclickinfo-goodies,leekinney/zeroclickinfo-goodies,gsanthosh91/zeroclickinfo-goodies,akanshgulati/zeroclickinfo-goodies,JamyGolden/zeroclickinfo-goodies,abinabrahamanchery/zeroclickinfo-goodies,charles-l/zeroclickinfo-goodies,JamyGolden/zeroclickinfo-goodies,iambibhas/zeroclickinfo-goodies,dnmfarrell/zeroclickinfo-goodies,thechunsik/zeroclickinfo-goodies,akanshgulati/zeroclickinfo-goodies,lamanh/zeroclickinfo-goodies,lxndio/zeroclickinfo-goodies,P71/zeroclickinfo-goodies,Gabrielt014/zeroclickinfo-goodies,mr-karan/zeroclickinfo-goodies,salmanfarisvp/zeroclickinfo-goodies,gautamkrishnar/zeroclickinfo-goodies,karankrishna/zeroclickinfo-goodies,cosimo/zeroclickinfo-goodies,lights0123/zeroclickinfo-goodies,jophab/zeroclickinfo-goodies,kavithaRajagopalan/zeroclickinfo-goodies,seisfeld/zeroclickinfo-goodies,mohan08p/zeroclickinfo-goodies,rahul-raturi/zeroclickinfo-goodies,salmanfarisvp/zeroclickinfo-goodies,ACMASU/zeroclickinfo-goodies,salmanfarisvp/zeroclickinfo-goodies,nagromc/zeroclickinfo-goodies,dnmfarrell/zeroclickinfo-goodies,pratts/zeroclickinfo-goodies,Gabrielt014/zeroclickinfo-goodies,Kr1tya3/zeroclickinfo-goodies,alohaas/zeroclickinfo-goodies,tagawa/zeroclickinfo-goodies,jamessun/zeroclickinfo-goodies,brianlechthaler/zeroclickinfo-goodies,technoabh/zeroclickinfo-goodies,zblair/zeroclickinfo-goodies,jamessun/zeroclickinfo-goodies,gautamkrishnar/zeroclickinfo-goodies,iambibhas/zeroclickinfo-goodies,thechunsik/zeroclickinfo-goodies,marianosimone/zeroclickinfo-goodies,seisfeld/zeroclickinfo-goodies,cosimo/zeroclickinfo-goodies,oliverdunk/zeroclickinfo-goodies,mohan08p/zeroclickinfo-goodies,MrChrisW/zeroclickinfo-goodies,ACMASU/zeroclickinfo-goodies,paulmolluzzo/zeroclickinfo-goodies,cosimo/zeroclickinfo-goodies,tharunreddysai/zeroclickinfo-goodies,alohaas/zeroclickinfo-goodies,alfredmaliakal/zeroclickinfo-goodies,ACMASU/zeroclickinfo-goodies,P71/zeroclickinfo-goodies,glindste/zeroclickinfo-goodies,CuriousLearner/zeroclickinfo-goodies,fired334/zeroclickinfo-goodies,urohit011/zeroclickinfo-goodies,jamessun/zeroclickinfo-goodies,mr-karan/zeroclickinfo-goodies,charles-l/zeroclickinfo-goodies,urohit011/zeroclickinfo-goodies,Midhun-Jo-Antony/zeroclickinfo-goodies,aleksandar-todorovic/zeroclickinfo-goodies,thechunsik/zeroclickinfo-goodies,Gabrielt014/zeroclickinfo-goodies,Shugabuga/zeroclickinfo-goodies,lamanh/zeroclickinfo-goodies,lxndio/zeroclickinfo-goodies,alohaas/zeroclickinfo-goodies,jamessun/zeroclickinfo-goodies,ericlake/zeroclickinfo-goodies,ericlake/zeroclickinfo-goodies,paulmolluzzo/zeroclickinfo-goodies,aleksandar-todorovic/zeroclickinfo-goodies,rahul-raturi/zeroclickinfo-goodies,Midhun-Jo-Antony/zeroclickinfo-goodies,glindste/zeroclickinfo-goodies,aleksandar-todorovic/zeroclickinfo-goodies,Shugabuga/zeroclickinfo-goodies,MrChrisW/zeroclickinfo-goodies,comatory/zeroclickinfo-goodies,Kakkoroid/zeroclickinfo-goodies,technoabh/zeroclickinfo-goodies,weathermaker/zeroclickinfo-goodies,CuriousLearner/zeroclickinfo-goodies,dnmfarrell/zeroclickinfo-goodies,nagromc/zeroclickinfo-goodies,tharunreddysai/zeroclickinfo-goodies,tharunreddysai/zeroclickinfo-goodies,ericlake/zeroclickinfo-goodies,samskeller/zeroclickinfo-goodies,brianlechthaler/zeroclickinfo-goodies,viluon/zeroclickinfo-goodies,gsanthosh91/zeroclickinfo-goodies,seisfeld/zeroclickinfo-goodies,alfredmaliakal/zeroclickinfo-goodies,codenirvana/zeroclickinfo-goodies,oliverdunk/zeroclickinfo-goodies,shyamalschandra/zeroclickinfo-goodies,ecelis/zeroclickinfo-goodies,Shugabuga/zeroclickinfo-goodies,viluon/zeroclickinfo-goodies,MrChrisW/zeroclickinfo-goodies,sagarhani/zeroclickinfo-goodies,rahul-raturi/zeroclickinfo-goodies,PierreZ/zeroclickinfo-goodies,RomainLG/zeroclickinfo-goodies,SvetlanaZem/zeroclickinfo-goodies,nagromc/zeroclickinfo-goodies,chriskaschner/zeroclickinfo-goodies,akanshgulati/zeroclickinfo-goodies,abinabrahamanchery/zeroclickinfo-goodies,MrChrisW/zeroclickinfo-goodies,comatory/zeroclickinfo-goodies,Kakkoroid/zeroclickinfo-goodies,shyamalschandra/zeroclickinfo-goodies,karankrishna/zeroclickinfo-goodies,ACMASU/zeroclickinfo-goodies,Kakkoroid/zeroclickinfo-goodies,SvetlanaZem/zeroclickinfo-goodies,sagarhani/zeroclickinfo-goodies,marianosimone/zeroclickinfo-goodies,synbit/zeroclickinfo-goodies,cosimo/zeroclickinfo-goodies,Kr1tya3/zeroclickinfo-goodies,marianosimone/zeroclickinfo-goodies,ericlake/zeroclickinfo-goodies,CuriousLearner/zeroclickinfo-goodies,jophab/zeroclickinfo-goodies,synbit/zeroclickinfo-goodies,ankushg07/zeroclickinfo-goodies,sagarhani/zeroclickinfo-goodies,ACMASU/zeroclickinfo-goodies,technoabh/zeroclickinfo-goodies,pratts/zeroclickinfo-goodies,tagawa/zeroclickinfo-goodies,paulmolluzzo/zeroclickinfo-goodies,kavithaRajagopalan/zeroclickinfo-goodies,loganom/zeroclickinfo-goodies,gautamkrishnar/zeroclickinfo-goodies,fired334/zeroclickinfo-goodies,synbit/zeroclickinfo-goodies,glindste/zeroclickinfo-goodies,Gabrielt014/zeroclickinfo-goodies,tharunreddysai/zeroclickinfo-goodies,urohit011/zeroclickinfo-goodies,aasoliz/zeroclickinfo-goodies,alfredmaliakal/zeroclickinfo-goodies,mr-karan/zeroclickinfo-goodies,thechunsik/zeroclickinfo-goodies,weathermaker/zeroclickinfo-goodies,jophab/zeroclickinfo-goodies,gautamkrishnar/zeroclickinfo-goodies,leekinney/zeroclickinfo-goodies,fired334/zeroclickinfo-goodies,marianosimone/zeroclickinfo-goodies,P71/zeroclickinfo-goodies,rahul-raturi/zeroclickinfo-goodies,iambibhas/zeroclickinfo-goodies,Gabrielt014/zeroclickinfo-goodies,nagromc/zeroclickinfo-goodies,charles-l/zeroclickinfo-goodies,MrChrisW/zeroclickinfo-goodies,jgkamat/zeroclickinfo-goodies,RomainLG/zeroclickinfo-goodies,lamanh/zeroclickinfo-goodies,ACMASU/zeroclickinfo-goodies,JamyGolden/zeroclickinfo-goodies,leekinney/zeroclickinfo-goodies,salmanfarisvp/zeroclickinfo-goodies | DDH.cheat_sheets = DDH.cheat_sheets || {};
DDH.cheat_sheets.build = function(ops) {
Spice.registerHelper('cheatsheets_ordered', function(sections, section_order, template_type, options) {
var result = "";
var template = {
type: template_type,
path: template_type ? 'DDH.cheat_sheets.' + template_type : 'DDH.cheat_sheets.keyboard'
};
$.each(section_order, function(i, section) {
if (sections[section]){
var showhide = true;
if (i === 0 ){
showhide = false;
} else if ( i === 1 && !is_mobile ){
showhide = false;
}
result += options.fn({ name: section, items: sections[section], template: template, showhide: showhide });
}
});
return result;
});
var re_brackets = /(?:\[|\{|\}|\])/, // search for [, {, }, or }
re_whitespace = /\s+/, // search for spaces
re_codeblock = /<code>(.+?)<\/code>/g; // search for <code></code>
Spice.registerHelper('cheatsheets_codeblock', function(string, className, options) {
var out;
var codeClass = typeof className === "string" ? className : "bg-clr--white";
// replace escaped slashes and brackets
string = string.replace(/\</g, '<')
.replace(/\>/g, '>')
.replace(/\\\\/, "<bks>")
.replace(/\\\[/g, "<lbr>")
.replace(/\\\{/g, "<lcbr>")
.replace(/\\\]/g, "<rbr>")
.replace(/\\\}/g, "<rcbr>");
// no spaces
// OR
// spaces and no un-escaped brackets
// e.g "?()", ":sp filename"
// --> wrap whole sting in <code></code>
if ( !re_whitespace.test(string) || !re_brackets.test(string) ){
out = "<code class='"+codeClass+"'>" + string + "</code>";
// spaces
// AND
// un-escaped brackets
// e.g "[Ctrl] [B]"
// --> replace [] & {} with <code></code>
} else {
// replace unescaped brackets
out = string
.replace(/\[|\{/g, "<code class='"+codeClass+"'>")
.replace(/\]|\}/g, "</code>");
}
out = out
// re-replace escaped slash
.replace(/<bks>/g, "\\")
// re-replace escaped brackets
.replace(/<lbr>/g, "[")
.replace(/<lcbr>/g, "{")
.replace(/<rbr>/g, "]")
.replace(/<rcbr>/g, "}");
out = out.replace(re_codeblock, function esc_codeblock (match, p1, offset, string, codeClass){
var escaped = Handlebars.Utils.escapeExpression(p1);
return "<code class='"+codeClass+">" + escaped + "</code>";
});
return new Handlebars.SafeString(out);
});
var wasShown = false; // keep track whether onShow was run yet
return {
onShow: function() {
// make sure this function is only run once, the first time
// the IA is shown otherwise things will get initialized more than once
if (wasShown) { return; }
// set the flag to true so it doesn't get run again:
wasShown = true;
var $dom = $("#zci-cheat_sheets"),
$container = $dom.find(".cheatsheet__container"),
$detail = $dom.find(".zci__main--detail"),
$section = $dom.find(".cheatsheet__section"),
$hideRow = $section.find("tbody tr:nth-child(n+4), ul li:nth-child(n+4)"),
$showhide = $container.find(".cheatsheet__section.showhide"),
$more_btn = $dom.find(".chomp--link"),
isExpanded = false,
loadedMasonry = false,
masonryOps = {
itemSelector: '.cheatsheet__section',
columnWidth: 295,
gutter: 30,
isFitWidth: true
},
showMoreLess = function() {
// keep track of whether it's expanded or not:
isExpanded = !isExpanded;
// update the querystring param so the state
// persists across page refreshes or if the link
// is shared to someone else:
if (isExpanded) {
DDG.history.set({ iax: 1 });
} else {
DDG.history.clear('iax');
}
$dom.toggleClass("has-chomp-expanded");
$detail.toggleClass("c-base");
$container.toggleClass("compressed");
$showhide.toggleClass("is-hidden");
$hideRow.toggleClass("is-hidden");
if (window.Masonry) {
$container.masonry(masonryOps);
}
};
// Removes all tr's after the 3rd before masonry fires
if ($container.hasClass("compressed")) {
$hideRow.toggleClass("is-hidden");
}
// if iax=1 is in the querystring, expand
// the cheatsheet automatically when the IA is shown:
if (DDG.history.get('iax')) {
showMoreLess();
}
DDG.require('masonry.js', function(){
$container.masonry(masonryOps);
$more_btn.click(showMoreLess);
});
}
};
};
| share/goodie/cheat_sheets/cheat_sheets.js | DDH.cheat_sheets = DDH.cheat_sheets || {};
DDH.cheat_sheets.build = function(ops) {
Spice.registerHelper('cheatsheets_ordered', function(sections, section_order, template_type, options) {
var result = "";
var template = {
type: template_type,
path: template_type ? 'DDH.cheat_sheets.' + template_type : 'DDH.cheat_sheets.keyboard'
};
$.each(section_order, function(i, section) {
if (sections[section]){
var showhide = true;
if (i === 0 ){
showhide = false;
} else if ( i === 1 && !is_mobile ){
showhide = false;
}
result += options.fn({ name: section, items: sections[section], template: template, showhide: showhide });
}
});
return result;
});
var re_brackets = /(?:\[|\{|\}|\])/, // search for [, {, }, or }
re_whitespace = /\s+/, // search for spaces
re_codeblock = /<code>(.+?)<\/code>/g; // search for <code></code>
Spice.registerHelper('cheatsheets_codeblock', function(string, className, options) {
var out;
var codeClass = typeof className === "string" ? className : "bg-clr--white";
// replace escaped slashes and brackets
string = string.replace(/\\\\/, "<bks>")
.replace(/\\\[/g, "<lbr>")
.replace(/\\\{/g, "<lcbr>")
.replace(/\\\]/g, "<rbr>")
.replace(/\\\}/g, "<rcbr>");
// no spaces
// OR
// spaces and no un-escaped brackets
// e.g "?()", ":sp filename"
// --> wrap whole sting in <code></code>
if ( !re_whitespace.test(string) || !re_brackets.test(string) ){
out = "<code class='"+codeClass+"'>" + string + "</code>";
// spaces
// AND
// un-escaped brackets
// e.g "[Ctrl] [B]"
// --> replace [] & {} with <code></code>
} else {
// replace unescaped brackets
out = string
.replace(/\[|\{/g, "<code class='"+codeClass+"'>")
.replace(/\]|\}/g, "</code>");
}
out = out
// re-replace escaped slash
.replace(/<bks>/g, "\\")
// re-replace escaped brackets
.replace(/<lbr>/g, "[")
.replace(/<lcbr>/g, "{")
.replace(/<rbr>/g, "]")
.replace(/<rcbr>/g, "}");
out = out.replace(re_codeblock, function esc_codeblock (match, p1, offset, string, codeClass){
var escaped = Handlebars.Utils.escapeExpression(p1);
return "<code class='"+codeClass+">" + escaped + "</code>";
});
return new Handlebars.SafeString(out);
});
var wasShown = false; // keep track whether onShow was run yet
return {
onShow: function() {
// make sure this function is only run once, the first time
// the IA is shown otherwise things will get initialized more than once
if (wasShown) { return; }
// set the flag to true so it doesn't get run again:
wasShown = true;
var $dom = $("#zci-cheat_sheets"),
$container = $dom.find(".cheatsheet__container"),
$detail = $dom.find(".zci__main--detail"),
$section = $dom.find(".cheatsheet__section"),
$hideRow = $section.find("tbody tr:nth-child(n+4), ul li:nth-child(n+4)"),
$showhide = $container.find(".cheatsheet__section.showhide"),
$more_btn = $dom.find(".chomp--link"),
isExpanded = false,
loadedMasonry = false,
masonryOps = {
itemSelector: '.cheatsheet__section',
columnWidth: 295,
gutter: 30,
isFitWidth: true
},
showMoreLess = function() {
// keep track of whether it's expanded or not:
isExpanded = !isExpanded;
// update the querystring param so the state
// persists across page refreshes or if the link
// is shared to someone else:
if (isExpanded) {
DDG.history.set({ iax: 1 });
} else {
DDG.history.clear('iax');
}
$dom.toggleClass("has-chomp-expanded");
$detail.toggleClass("c-base");
$container.toggleClass("compressed");
$showhide.toggleClass("is-hidden");
$hideRow.toggleClass("is-hidden");
if (window.Masonry) {
$container.masonry(masonryOps);
}
};
// Removes all tr's after the 3rd before masonry fires
if ($container.hasClass("compressed")) {
$hideRow.toggleClass("is-hidden");
}
// if iax=1 is in the querystring, expand
// the cheatsheet automatically when the IA is shown:
if (DDG.history.get('iax')) {
showMoreLess();
}
DDG.require('masonry.js', function(){
$container.masonry(masonryOps);
$more_btn.click(showMoreLess);
});
}
};
};
| CheatSheets: htmlencode < >, fixes #1414
| share/goodie/cheat_sheets/cheat_sheets.js | CheatSheets: htmlencode < >, fixes #1414 | <ide><path>hare/goodie/cheat_sheets/cheat_sheets.js
<ide> var codeClass = typeof className === "string" ? className : "bg-clr--white";
<ide>
<ide> // replace escaped slashes and brackets
<del> string = string.replace(/\\\\/, "<bks>")
<add> string = string.replace(/\</g, '<')
<add> .replace(/\>/g, '>')
<add> .replace(/\\\\/, "<bks>")
<ide> .replace(/\\\[/g, "<lbr>")
<ide> .replace(/\\\{/g, "<lcbr>")
<ide> .replace(/\\\]/g, "<rbr>") |
|
JavaScript | mit | 58c98bfdbc5880399ac473673135904d572d6ceb | 0 | loadletter/4chan-x,loadletter/4chan-x,loadletter/4chan-x,krynomore/4chan-x,krynomore/4chan-x,krynomore/4chan-x | // ==UserScript==
// @name 4chan x
// @version 2.40.49
// @namespace aeosynth
// @description Adds various features.
// @copyright 2009-2011 James Campos <[email protected]>
// @copyright 2012-2013 Nicolas Stepien <[email protected]>
// @license MIT; http://en.wikipedia.org/wiki/Mit_license
// @include http://boards.4chan.org/*
// @include https://boards.4chan.org/*
// @include http://sys.4chan.org/*
// @include https://sys.4chan.org/*
// @include http://a.4cdn.org/*
// @include https://a.4cdn.org/*
// @include http://i.4cdn.org/*
// @include https://i.4cdn.org/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_openInTab
// @grant GM_xmlhttpRequest
// @run-at document-start
// @updateURL https://github.com/loadletter/4chan-x/raw/master/4chan_x.meta.js
// @downloadURL https://github.com/loadletter/4chan-x/raw/master/4chan_x.user.js
// @icon data:image/gif;base64,R0lGODlhEAAQAKECAAAAAGbMM////////yH5BAEKAAIALAAAAAAQABAAAAIxlI+pq+D9DAgUoFkPDlbs7lGiI2bSVnKglnJMOL6omczxVZK3dH/41AG6Lh7i6qUoAAA7
// ==/UserScript==
/* LICENSE
*
* Copyright (c) 2009-2011 James Campos <[email protected]>
* Copyright (c) 2012-2013 Nicolas Stepien <[email protected]>
* http://mayhemydg.github.io/4chan-x/
* 4chan X 2.39.7
*
* 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.
*
* HACKING
*
* 4chan X is written in CoffeeScript[1], and developed on GitHub[2].
*
* [1]: http://coffeescript.org/
* [2]: https://github.com/MayhemYDG/4chan-x
*
* CONTRIBUTORS
*
* noface - unique ID fixes
* desuwa - Firefox filename upload fix
* seaweed - bottom padding for image hover
* e000 - cooldown sanity check
* ahodesuka - scroll back when unexpanding images, file info formatting
* Shou- - pentadactyl fixes
* ferongr - new favicons
* xat- - new favicons
* Zixaphir - fix qr textarea - captcha-image gap
* Ongpot - sfw favicon
* thisisanon - nsfw + 404 favicons
* Anonymous - empty favicon
* Seiba - chrome quick reply focusing
* herpaderpderp - recaptcha fixes
* WakiMiko - recaptcha tab order http://userscripts.org/scripts/show/82657
* btmcsweeney - allow users to specify text for sauce links
*
* All the people who've taken the time to write bug reports.
*
* Thank you.
*/
(function() {
var $, $$, Anonymize, ArchiveLink, AutoGif, Build, CatalogLinks, Conf, Config, DeleteLink, DownloadLink, ExpandComment, ExpandThread, Favicon, FileInfo, Filter, Get, ImageExpand, ImageHover, Keybinds, Main, Menu, Nav, Options, QR, QuoteBacklink, QuoteCT, QuoteInline, QuoteOP, QuoteYou, QuotePreview, Quotify, Redirect, RelativeDates, RemoveSlug, ReplaceJpg, ReplacePng, ReplyHiding, ReportLink, RevealSpoilers, Sauce, StrikethroughQuotes, ThreadHiding, ThreadStats, Time, TitlePost, UI, Unread, Updater, Watcher, d, g, _base, CaptchaIsSetup;
CaptchaIsSetup = false;
/* Your posts to add (You) backlinks to */
var yourPosts = new Array();
Config = {
main: {
Enhancing: {
'Disable 4chan\'s extension': [true, 'Avoid conflicts between 4chan X and 4chan\'s inline extension'],
'Catalog Links': [true, 'Turn Navigation links into links to each board\'s catalog'],
'404 Redirect': [true, 'Redirect dead threads and images'],
'Keybinds': [true, 'Binds actions to keys'],
'Time Formatting': [true, 'Arbitrarily formatted timestamps, using your local time'],
'Relative Post Dates': [false, 'Display dates as "3 minutes ago" f.e., tooltip shows the timestamp'],
'File Info Formatting': [true, 'Reformats the file information'],
'Comment Expansion': [true, 'Expand too long comments'],
'Comment Auto-Expansion': [false, 'Autoexpand too long comments'],
'Thread Expansion': [true, 'View all replies'],
'Index Navigation': [true, 'Navigate to previous / next thread'],
'Reply Navigation': [false, 'Navigate to top / bottom of thread'],
'Remove Slug': [false, 'Cut useless comment/post from the URL'],
'Check for Updates': [true, 'Check for updated versions of 4chan X']
},
Filtering: {
'Anonymize': [false, 'Make everybody anonymous'],
'Filter': [true, 'Self-moderation placebo'],
'Recursive Filtering': [true, 'Filter replies of filtered posts, recursively'],
'Reply Hiding': [true, 'Hide single replies'],
'Thread Hiding': [true, 'Hide entire threads'],
'Show Stubs': [true, 'Of hidden threads / replies']
},
Imaging: {
'Image Auto-Gif': [false, 'Animate gif thumbnails'],
'Replace PNG': [false, 'Replace thumbnail with original PNG image'],
'Replace JPG': [false, 'Replace thumbnail with original JPG image'],
'Image Expansion': [true, 'Expand images'],
'Image Hover': [false, 'Show full image on mouseover'],
'Sauce': [true, 'Add sauce to images'],
'Reveal Spoilers': [false, 'Replace spoiler thumbnails by the original thumbnail'],
'Expand From Current': [false, 'Expand images from current position to thread end']
},
Menu: {
'Menu': [true, 'Add a drop-down menu in posts'],
'Report Link': [true, 'Add a report link to the menu'],
'Delete Link': [true, 'Add post and image deletion links to the menu'],
'Download Link': [true, 'Add a download with original filename link to the menu'],
'Archive Link': [true, 'Add an archive link to the menu']
},
Monitoring: {
'Thread Updater': [true, 'Update threads. Has more options in its own dialog.'],
'Unread Count': [true, 'Show unread post count in tab title'],
'Unread Favicon': [true, 'Show a different favicon when there are unread posts'],
'Post in Title': [true, 'Show the op\'s post in the tab title'],
'Thread Stats': [true, 'Display reply, image and poster count'],
'Current Page': [true, 'Display position of the thread in the page index'],
'Current Page Position': [false, 'Also display position of the thread in index'],
'Thread Watcher': [true, 'Bookmark threads'],
'Auto Watch': [true, 'Automatically watch threads that you start'],
'Auto Watch Reply': [false, 'Automatically watch threads that you reply to']
},
Posting: {
'Quick Reply': [true, 'Reply without leaving the page'],
'Cooldown': [true, 'Prevent "flood detected" errors'],
'Auto Submit': [true, 'Submit automatically when captcha has been solved'],
'Persistent QR': [false, 'The Quick reply won\'t disappear after posting'],
'Auto Hide QR': [true, 'Automatically hide the quick reply when posting'],
'Open Reply in New Tab': [false, 'Open replies in a new tab that are made from the main board'],
'Remember QR size': [false, 'Remember the size of the Quick reply (Firefox only)'],
'Remember Subject': [false, 'Remember the subject field, instead of resetting after posting'],
'Remember Spoiler': [false, 'Remember the spoiler state, instead of resetting after posting'],
'Hide Original Post Form': [true, 'Replace the normal post form with a shortcut to open the QR']
},
Quoting: {
'Quote Backlinks': [true, 'Add quote backlinks'],
'OP Backlinks': [false, 'Add backlinks to the OP'],
'Quote Highlighting': [true, 'Highlight the previewed post'],
'Quote Inline': [true, 'Show quoted post inline on quote click'],
'Quote Preview': [true, 'Show quote content on hover'],
'Resurrect Quotes': [true, 'Linkify dead quotes to archives'],
'Indicate OP quote': [true, 'Add \'(OP)\' to OP quotes'],
/* Add (You) feature */
'Indicate You quote': [true, 'Add \'(You)\' to your quoted posts'],
'Indicate Cross-thread Quotes': [true, 'Add \'(Cross-thread)\' to cross-threads quotes'],
'Forward Hiding': [true, 'Hide original posts of inlined backlinks']
}
},
filter: {
name: ['# Filter any namefags:', '#/^(?!Anonymous$)/'].join('\n'),
uniqueid: ['# Filter a specific ID:', '#/Txhvk1Tl/'].join('\n'),
tripcode: ['# Filter any tripfags', '#/^!/'].join('\n'),
mod: ['# Set a custom class for mods:', '#/Mod$/;highlight:mod;op:yes', '# Set a custom class for moot:', '#/Admin$/;highlight:moot;op:yes'].join('\n'),
email: ['# Filter any e-mails that are not `sage` on /a/ and /jp/:', '#/^(?!sage$)/;boards:a,jp'].join('\n'),
subject: ['# Filter Generals on /v/:', '#/general/i;boards:v;op:only'].join('\n'),
comment: ['# Filter Stallman copypasta on /g/:', '#/what you\'re refer+ing to as linux/i;boards:g'].join('\n'),
country: [''].join('\n'),
filename: [''].join('\n'),
dimensions: ['# Highlight potential wallpapers:', '#/1920x1080/;op:yes;highlight;top:no;boards:w,wg'].join('\n'),
filesize: [''].join('\n'),
md5: [''].join('\n')
},
sauces: ['http://iqdb.org/?url=$1', 'http://www.google.com/searchbyimage?image_url=$1', '#http://tineye.com/search?url=$1', '#http://saucenao.com/search.php?db=999&url=$1', '#http://3d.iqdb.org/?url=$1', '#http://regex.info/exif.cgi?imgurl=$2', '# uploaders:', '#http://imgur.com/upload?url=$2;text:Upload to imgur', '#http://omploader.org/upload?url1=$2;text:Upload to omploader', '# "View Same" in archives:', '#http://archive.foolz.us/_/search/image/$3/;text:View same on foolz', '#http://archive.foolz.us/$4/search/image/$3/;text:View same on foolz /$4/', '#https://archive.installgentoo.net/$4/image/$3;text:View same on installgentoo /$4/'].join('\n'),
time: '%m/%d/%y(%a)%H:%M',
backlink: '>>%id',
fileInfo: '%l (%p%s, %r)',
favicon: 'ferongr',
hotkeys: {
openQR: ['i', 'Open QR with post number inserted'],
openEmptyQR: ['I', 'Open QR without post number inserted'],
openOptions: ['ctrl+o', 'Open Options'],
close: ['Esc', 'Close Options or QR'],
spoiler: ['ctrl+s', 'Quick spoiler tags'],
sageru: ['alt+n', 'Sage keybind'],
code: ['alt+c', 'Quick code tags'],
submit: ['alt+s', 'Submit post'],
watch: ['w', 'Watch thread'],
update: ['u', 'Update now'],
unreadCountTo0: ['z', 'Mark thread as read'],
expandImage: ['m', 'Expand selected image'],
expandAllImages: ['M', 'Expand all images'],
zero: ['0', 'Jump to page 0'],
nextPage: ['L', 'Jump to the next page'],
previousPage: ['H', 'Jump to the previous page'],
nextThread: ['n', 'See next thread'],
previousThread: ['p', 'See previous thread'],
expandThread: ['e', 'Expand thread'],
openThreadTab: ['o', 'Open thread in current tab'],
openThread: ['O', 'Open thread in new tab'],
nextReply: ['J', 'Select next reply'],
previousReply: ['K', 'Select previous reply'],
hide: ['x', 'Hide thread']
},
updater: {
checkbox: {
'Beep': [false, 'Beep on new post to completely read thread'],
'Scrolling': [false, 'Scroll updated posts into view. Only enabled at bottom of page.'],
'Scroll BG': [false, 'Scroll background tabs'],
'Verbose': [true, 'Show countdown timer, new post count'],
'Auto Update': [true, 'Automatically fetch new posts']
},
'Interval': 30
}
};
Conf = {};
d = document;
g = {};
UI = {
dialog: function(id, position, html) {
var el;
el = d.createElement('div');
el.className = 'reply dialog';
el.innerHTML = html;
el.id = id;
el.style.cssText = localStorage.getItem("" + Main.namespace + id + ".position") || position;
el.querySelector('.move').addEventListener('mousedown', UI.dragstart, false);
return el;
},
dragstart: function(e) {
var el, rect;
e.preventDefault();
UI.el = el = this.parentNode;
d.addEventListener('mousemove', UI.drag, false);
d.addEventListener('mouseup', UI.dragend, false);
rect = el.getBoundingClientRect();
UI.dx = e.clientX - rect.left;
UI.dy = e.clientY - rect.top;
UI.width = d.documentElement.clientWidth - rect.width;
return UI.height = d.documentElement.clientHeight - rect.height;
},
drag: function(e) {
var left, style, top;
left = e.clientX - UI.dx;
top = e.clientY - UI.dy;
left = left < 10 ? '0px' : UI.width - left < 10 ? null : left + 'px';
top = top < 10 ? '0px' : UI.height - top < 10 ? null : top + 'px';
style = UI.el.style;
style.left = left;
style.top = top;
style.right = left === null ? '0px' : null;
return style.bottom = top === null ? '0px' : null;
},
dragend: function() {
localStorage.setItem("" + Main.namespace + UI.el.id + ".position", UI.el.style.cssText);
d.removeEventListener('mousemove', UI.drag, false);
d.removeEventListener('mouseup', UI.dragend, false);
return delete UI.el;
},
hover: function(e) {
var clientHeight, clientWidth, clientX, clientY, height, style, top, _ref;
clientX = e.clientX, clientY = e.clientY;
style = UI.el.style;
_ref = d.documentElement, clientHeight = _ref.clientHeight, clientWidth = _ref.clientWidth;
height = UI.el.offsetHeight;
top = clientY - 120;
style.top = clientHeight <= height || top <= 0 ? '0px' : top + height >= clientHeight ? clientHeight - height + 'px' : top + 'px';
if (clientX <= clientWidth - 400) {
style.left = clientX + 45 + 'px';
return style.right = null;
} else {
style.left = null;
return style.right = clientWidth - clientX + 45 + 'px';
}
},
hoverend: function() {
$.rm(UI.el);
return delete UI.el;
}
};
/*
loosely follows the jquery api:
http://api.jquery.com/
not chainable
*/
$ = function(selector, root) {
if (root == null) {
root = d.body;
}
return root.querySelector(selector);
};
$.extend = function(object, properties) {
var key, val;
for (key in properties) {
val = properties[key];
object[key] = val;
}
};
$.extend($, {
SECOND: 1000,
MINUTE: 1000 * 60,
HOUR: 1000 * 60 * 60,
DAY: 1000 * 60 * 60 * 24,
log: typeof (_base = console.log).bind === "function" ? _base.bind(console) : void 0,
engine: /WebKit|Presto|Gecko/.exec(navigator.userAgent)[0].toLowerCase(),
ready: function(fc) {
var cb;
if (/interactive|complete/.test(d.readyState)) {
return setTimeout(fc);
}
cb = function() {
$.off(d, 'DOMContentLoaded', cb);
return fc();
};
return $.on(d, 'DOMContentLoaded', cb);
},
sync: function(key, cb) {
key = Main.namespace + key;
return $.on(window, 'storage', function(e) {
if (e.key === key) {
return cb(JSON.parse(e.newValue));
}
});
},
id: function(id) {
return d.getElementById(id);
},
formData: function(arg) {
var fd, key, val;
if (arg instanceof HTMLFormElement) {
fd = new FormData(arg);
} else {
fd = new FormData();
for (key in arg) {
val = arg[key];
if (val) {
fd.append(key, val);
}
}
}
return fd;
},
ajax: function(url, callbacks, opts) {
var form, headers, key, r, type, upCallbacks, val;
if (opts == null) {
opts = {};
}
type = opts.type, headers = opts.headers, upCallbacks = opts.upCallbacks, form = opts.form;
r = new XMLHttpRequest();
type || (type = form && 'post' || 'get');
r.open(type, url, true);
for (key in headers) {
val = headers[key];
r.setRequestHeader(key, val);
}
$.extend(r, callbacks);
$.extend(r.upload, upCallbacks);
if (type === 'post') {
r.withCredentials = true;
}
r.send(form);
return r;
},
cache: function(url, cb) {
var req;
if (req = $.cache.requests[url]) {
if (req.readyState === 4) {
return cb.call(req);
} else {
return req.callbacks.push(cb);
}
} else {
req = $.ajax(url, {
onload: function() {
var _i, _len, _ref, _results;
_ref = this.callbacks;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
cb = _ref[_i];
_results.push(cb.call(this));
}
return _results;
},
onabort: function() {
return delete $.cache.requests[url];
},
onerror: function() {
return delete $.cache.requests[url];
}
});
req.callbacks = [cb];
return $.cache.requests[url] = req;
}
},
cb: {
checked: function() {
$.set(this.name, this.checked);
return Conf[this.name] = this.checked;
},
value: function() {
$.set(this.name, this.value.trim());
return Conf[this.name] = this.value;
}
},
addStyle: function(css) {
var f, style;
style = $.el('style', {
textContent: css
});
f = function() {
var root;
if (root = d.head || d.documentElement) {
return $.add(root, style);
} else {
return setTimeout(f, 20);
}
};
f();
return style;
},
x: function(path, root) {
if (root == null) {
root = d.body;
}
return d.evaluate(path, root, null, 8, null).singleNodeValue;
},
addClass: function(el, className) {
return el.classList.add(className);
},
rmClass: function(el, className) {
return el.classList.remove(className);
},
rm: function(el) {
return el.parentNode.removeChild(el);
},
tn: function(s) {
return d.createTextNode(s);
},
nodes: function(nodes) {
var frag, node, _i, _len;
if (!(nodes instanceof Array)) {
return nodes;
}
frag = d.createDocumentFragment();
for (_i = 0, _len = nodes.length; _i < _len; _i++) {
node = nodes[_i];
frag.appendChild(node);
}
return frag;
},
add: function(parent, children) {
return parent.appendChild($.nodes(children));
},
prepend: function(parent, children) {
return parent.insertBefore($.nodes(children), parent.firstChild);
},
after: function(root, el) {
return root.parentNode.insertBefore($.nodes(el), root.nextSibling);
},
before: function(root, el) {
return root.parentNode.insertBefore($.nodes(el), root);
},
replace: function(root, el) {
return root.parentNode.replaceChild($.nodes(el), root);
},
el: function(tag, properties) {
var el;
el = d.createElement(tag);
if (properties) {
$.extend(el, properties);
}
return el;
},
on: function(el, events, handler) {
var event, _i, _len, _ref;
_ref = events.split(' ');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
event = _ref[_i];
el.addEventListener(event, handler, false);
}
},
off: function(el, events, handler) {
var event, _i, _len, _ref;
_ref = events.split(' ');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
event = _ref[_i];
el.removeEventListener(event, handler, false);
}
},
open: function(url) {
return (GM_openInTab || window.open)(location.protocol + url, '_blank');
},
event: function(event, detail, root) {
if (root == null) {
root = d;
}
if ((detail != null) && typeof cloneInto === 'function') {
detail = cloneInto(detail, document.defaultView);
}
return root.dispatchEvent(new CustomEvent(event, {
bubbles: true,
detail: detail
}));
},
globalEval: function(code) {
var script;
script = $.el('script', {
textContent: code
});
$.add(d.head, script);
return $.rm(script);
},
bytesToString: function(size) {
var unit;
unit = 0;
while (size >= 1024) {
size /= 1024;
unit++;
}
size = unit > 1 ? Math.round(size * 100) / 100 : Math.round(size);
return "" + size + " " + ['B', 'KB', 'MB', 'GB'][unit];
},
debounce: function(wait, fn) {
var timeout;
timeout = null;
return function() {
if (timeout) {
clearTimeout(timeout);
} else {
fn.apply(this, arguments);
}
return timeout = setTimeout((function() {
return timeout = null;
}), wait);
};
}
});
$.cache.requests = {};
$.extend($, typeof GM_deleteValue !== "undefined" && GM_deleteValue !== null ? {
"delete": function(name) {
name = Main.namespace + name;
return GM_deleteValue(name);
},
get: function(name, defaultValue) {
var value;
name = Main.namespace + name;
if (value = GM_getValue(name)) {
return JSON.parse(value);
} else {
return defaultValue;
}
},
set: function(name, value) {
name = Main.namespace + name;
localStorage.setItem(name, JSON.stringify(value));
return GM_setValue(name, JSON.stringify(value));
}
} : {
"delete": function(name) {
return localStorage.removeItem(Main.namespace + name);
},
get: function(name, defaultValue) {
var value;
if (value = localStorage.getItem(Main.namespace + name)) {
return JSON.parse(value);
} else {
return defaultValue;
}
},
set: function(name, value) {
return localStorage.setItem(Main.namespace + name, JSON.stringify(value));
}
});
$$ = function(selector, root) {
if (root == null) {
root = d.body;
}
return Array.prototype.slice.call(root.querySelectorAll(selector));
};
Filter = {
filters: {},
init: function() {
var boards, err, filter, hl, key, op, regexp, stub, top, _i, _len, _ref, _ref1, _ref2, _ref3, _ref4;
for (key in Config.filter) {
this.filters[key] = [];
_ref = Conf[key].split('\n');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
filter = _ref[_i];
if (filter[0] === '#') {
continue;
}
if (!(regexp = filter.match(/\/(.+)\/(\w*)/))) {
continue;
}
filter = filter.replace(regexp[0], '');
boards = ((_ref1 = filter.match(/boards:([^;]+)/)) != null ? _ref1[1].toLowerCase() : void 0) || 'global';
if (boards !== 'global' && boards.split(',').indexOf(g.BOARD) === -1) {
continue;
}
if (key === 'md5') {
regexp = regexp[1];
} else {
try {
regexp = RegExp(regexp[1], regexp[2]);
} catch (_error) {
err = _error;
alert(err.message);
continue;
}
}
op = ((_ref2 = filter.match(/[^t]op:(yes|no|only)/)) != null ? _ref2[1] : void 0) || 'no';
stub = (function() {
var _ref3;
switch ((_ref3 = filter.match(/stub:(yes|no)/)) != null ? _ref3[1] : void 0) {
case 'yes':
return true;
case 'no':
return false;
default:
return Conf['Show Stubs'];
}
})();
if (hl = /highlight/.test(filter)) {
hl = ((_ref3 = filter.match(/highlight:(\w+)/)) != null ? _ref3[1] : void 0) || 'filter_highlight';
top = ((_ref4 = filter.match(/top:(yes|no)/)) != null ? _ref4[1] : void 0) || 'yes';
top = top === 'yes';
}
this.filters[key].push(this.createFilter(regexp, op, stub, hl, top));
}
if (!this.filters[key].length) {
delete this.filters[key];
}
}
if (Object.keys(this.filters).length) {
return Main.callbacks.push(this.node);
}
},
createFilter: function(regexp, op, stub, hl, top) {
var settings, test;
test = typeof regexp === 'string' ? function(value) {
return regexp === value;
} : function(value) {
return regexp.test(value);
};
settings = {
hide: !hl,
stub: stub,
"class": hl,
top: top
};
return function(value, isOP) {
if (isOP && op === 'no' || !isOP && op === 'only') {
return false;
}
if (!test(value)) {
return false;
}
return settings;
};
},
node: function(post) {
var filter, firstThread, isOP, key, result, root, thisThread, value, _i, _len, _ref;
if (post.isInlined) {
return;
}
isOP = post.ID === post.threadID;
root = post.root;
for (key in Filter.filters) {
value = Filter[key](post);
if (value === false) {
continue;
}
_ref = Filter.filters[key];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
filter = _ref[_i];
if (!(result = filter(value, isOP))) {
continue;
}
if (result.hide) {
if (isOP) {
if (!g.REPLY) {
ThreadHiding.hide(root.parentNode, result.stub);
} else {
continue;
}
} else {
ReplyHiding.hide(root, result.stub);
}
return;
}
$.addClass(root, result["class"]);
if (isOP && result.top && !g.REPLY) {
thisThread = root.parentNode;
if (firstThread = $('div[class="postContainer opContainer"]')) {
if (firstThread !== root) {
$.before(firstThread.parentNode, [thisThread, thisThread.nextElementSibling]);
}
}
}
}
}
},
name: function(post) {
return $('.name', post.el).textContent;
},
uniqueid: function(post) {
var uid;
if (uid = $('.posteruid', post.el)) {
return uid.firstElementChild.textContent;
}
return false;
},
tripcode: function(post) {
var trip;
if (trip = $('.postertrip', post.el)) {
return trip.textContent;
}
return false;
},
mod: function(post) {
var mod;
if (mod = $('.capcode.hand', post.el)) {
return mod.textContent.replace('## ', '');
}
return false;
},
subject: function(post) {
var subject;
if (subject = $('.postInfo .subject', post.el)) {
return subject.textContent;
}
return false;
},
comment: function(post) {
var data, i, nodes, text, _i, _ref;
text = [];
nodes = d.evaluate('.//br|.//text()', post.blockquote, null, 7, null);
for (i = _i = 0, _ref = nodes.snapshotLength; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
text.push((data = nodes.snapshotItem(i).data) ? data : '\n');
}
return text.join('');
},
country: function(post) {
var flag;
if (flag = $('.flag', post.el)) {
return flag.title;
}
return false;
},
filename: function(post) {
var file, fileInfo, fname;
fileInfo = post.fileInfo;
if (fileInfo) {
if (file = $('.fileText > span', fileInfo)) {
return file.title;
} else {
fname = fileInfo.firstElementChild.childNodes[1] || fileInfo.firstElementChild.childNodes[0];
return fname.textContent;
}
}
return false;
},
dimensions: function(post) {
var fileInfo, match;
fileInfo = post.fileInfo;
if (fileInfo && (match = fileInfo.childNodes[1].textContent.match(/\d+x\d+/))) {
return match[0];
}
return false;
},
filesize: function(post) {
var img;
img = post.img;
if (img) {
return img.alt;
}
return false;
},
md5: function(post) {
var img;
img = post.img;
if (img) {
return img.dataset.md5;
}
return false;
},
menuInit: function() {
var div, entry, type, _i, _len, _ref;
div = $.el('div', {
textContent: 'Filter'
});
entry = {
el: div,
open: function() {
return true;
},
children: []
};
_ref = [['Name', 'name'], ['Unique ID', 'uniqueid'], ['Tripcode', 'tripcode'], ['Admin/Mod', 'mod'], ['Subject', 'subject'], ['Comment', 'comment'], ['Country', 'country'], ['Filename', 'filename'], ['Image dimensions', 'dimensions'], ['Filesize', 'filesize'], ['Image MD5', 'md5']];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
type = _ref[_i];
entry.children.push(Filter.createSubEntry(type[0], type[1]));
}
return Menu.addEntry(entry);
},
createSubEntry: function(text, type) {
var el, onclick, open;
el = $.el('a', {
href: 'javascript:;',
textContent: text
});
onclick = null;
open = function(post) {
var value;
value = Filter[type](post);
if (value === false) {
return false;
}
$.off(el, 'click', onclick);
onclick = function() {
var re, save, select, ta, tl;
re = type === 'md5' ? value : value.replace(/\/|\\|\^|\$|\n|\.|\(|\)|\{|\}|\[|\]|\?|\*|\+|\|/g, function(c) {
if (c === '\n') {
return '\\n';
} else if (c === '\\') {
return '\\\\';
} else {
return "\\" + c;
}
});
re = type === 'md5' ? "/" + value + "/" : "/^" + re + "$/";
if (/\bop\b/.test(post["class"])) {
re += ';op:yes';
}
save = (save = $.get(type, '')) ? "" + save + "\n" + re : re;
$.set(type, save);
Options.dialog();
select = $('select[name=filter]', $.id('options'));
select.value = type;
select.dispatchEvent(new Event('change'));
$.id('filter_tab').checked = true;
ta = select.nextElementSibling;
tl = ta.textLength;
ta.setSelectionRange(tl, tl);
return ta.focus();
};
$.on(el, 'click', onclick);
return true;
};
return {
el: el,
open: open
};
}
};
StrikethroughQuotes = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var el, quote, show_stub, _i, _len, _ref;
if (post.isInlined) {
return;
}
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (!((el = $.id(quote.hash.slice(1))) && quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname) && el.hidden)) {
continue;
}
$.addClass(quote, 'filtered');
if (Conf['Recursive Filtering'] && post.ID !== post.threadID) {
show_stub = !!$.x('preceding-sibling::div[contains(@class,"stub")]', el);
ReplyHiding.hide(post.root, show_stub);
}
}
}
};
ExpandComment = {
init: function() {
var a, _i, _len, _ref;
_ref = $$('.abbr');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
a = _ref[_i];
$.on(a.firstElementChild, 'click', ExpandComment.expand);
if (Conf['Comment Auto-Expansion']) {
a.firstElementChild.click();
}
}
},
expand: function(e) {
var a, replyID, threadID, _, _ref;
e.preventDefault();
_ref = this.href.match(/(\d+)#p(\d+)/), _ = _ref[0], threadID = _ref[1], replyID = _ref[2];
this.textContent = "Loading No." + replyID + "...";
a = this;
return $.cache("//a.4cdn.org" + this.pathname + ".json", function() {
return ExpandComment.parse(this, a, threadID, replyID);
});
},
parse: function(req, a, threadID, replyID) {
var bq, clone, href, post, posts, quote, quotes, spoilerRange, _i, _j, _len, _len1;
if (req.status !== 200) {
a.textContent = "" + req.status + " " + req.statusText;
return;
}
posts = JSON.parse(req.response).posts;
if (spoilerRange = posts[0].custom_spoiler) {
Build.spoilerRange[g.BOARD] = spoilerRange;
}
replyID = +replyID;
for (_i = 0, _len = posts.length; _i < _len; _i++) {
post = posts[_i];
if (post.no === replyID) {
break;
}
}
if (post.no !== replyID) {
a.textContent = 'No.#{replyID} not found.';
return;
}
bq = $.id("m" + replyID);
clone = bq.cloneNode(false);
clone.innerHTML = post.com;
quotes = clone.getElementsByClassName('quotelink');
for (_j = 0, _len1 = quotes.length; _j < _len1; _j++) {
quote = quotes[_j];
href = quote.getAttribute('href');
if (href[0] === '/') {
continue;
}
quote.href = "thread/" + href;
}
post = {
blockquote: clone,
threadID: threadID,
quotes: quotes,
backlinks: []
};
if (Conf['Resurrect Quotes']) {
Quotify.node(post);
}
if (Conf['Quote Preview']) {
QuotePreview.node(post);
}
if (Conf['Quote Inline']) {
QuoteInline.node(post);
}
if (Conf['Indicate OP quote']) {
QuoteOP.node(post);
}
if (Conf['Indicate You quote']) {
QuoteYou.node(post);
}
if (Conf['Indicate Cross-thread Quotes']) {
QuoteCT.node(post);
}
$.replace(bq, clone);
return Main.prettify(clone);
}
};
ExpandThread = {
init: function() {
var a, span, _i, _len, _ref, _results;
_ref = $$('.summary');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
span = _ref[_i];
a = $.el('a', {
textContent: "+ " + span.textContent,
className: 'summary desktop',
href: 'javascript:;'
});
$.on(a, 'click', function() {
return ExpandThread.toggle(this.parentNode);
});
_results.push($.replace(span, a));
}
return _results;
},
toggle: function(thread) {
var a, num, replies, reply, url, _i, _len;
url = "//a.4cdn.org/" + g.BOARD + "/thread/" + thread.id.slice(1) + ".json";
a = $('.summary', thread);
switch (a.textContent[0]) {
case '+':
a.textContent = a.textContent.replace('+', '× Loading...');
$.cache(url, function() {
return ExpandThread.parse(this, thread, a);
});
break;
case '×':
a.textContent = a.textContent.replace('× Loading...', '+');
$.cache.requests[url].abort();
break;
case '-':
a.textContent = a.textContent.replace('-', '+');
num = (function() {
switch (g.BOARD) {
case 'b':
case 'vg':
return 3;
case 't':
return 1;
default:
return 5;
}
})();
replies = $$('.replyContainer', thread);
replies.splice(replies.length - num, num);
for (_i = 0, _len = replies.length; _i < _len; _i++) {
reply = replies[_i];
$.rm(reply);
}
}
},
parse: function(req, thread, a) {
var backlink, id, link, nodes, post, posts, replies, reply, spoilerRange, threadID, _i, _j, _k, _len, _len1, _len2, _ref, _ref1;
if (req.status !== 200) {
a.textContent = "" + req.status + " " + req.statusText;
$.off(a, 'click', ExpandThread.cb.toggle);
return;
}
a.textContent = a.textContent.replace('× Loading...', '-');
posts = JSON.parse(req.response).posts;
if (spoilerRange = posts[0].custom_spoiler) {
Build.spoilerRange[g.BOARD] = spoilerRange;
}
replies = posts.slice(1);
threadID = thread.id.slice(1);
nodes = [];
for (_i = 0, _len = replies.length; _i < _len; _i++) {
reply = replies[_i];
post = Build.postFromObject(reply, g.BOARD);
id = reply.no;
link = $('a[title="Link to this post"]', post);
link.href = "thread/" + threadID + "#p" + id;
link.nextSibling.href = "thread/" + threadID + "#q" + id;
nodes.push(post);
}
_ref = $$('.summary ~ .replyContainer', a.parentNode);
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
post = _ref[_j];
$.rm(post);
}
_ref1 = $$('.backlink', a.previousElementSibling);
for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
backlink = _ref1[_k];
if (!$.id(backlink.hash.slice(1))) {
$.rm(backlink);
}
}
return $.after(a, nodes);
}
};
ThreadHiding = {
init: function() {
var a, hiddenThreads, thread, _i, _len, _ref;
hiddenThreads = ThreadHiding.sync();
if (g.CATALOG) {
return;
}
_ref = $$('.thread');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
thread = _ref[_i];
a = $.el('a', {
className: 'hide_thread_button',
innerHTML: '<span>[ - ]</span>',
href: 'javascript:;'
});
$.on(a, 'click', ThreadHiding.cb);
$.prepend(thread, a);
if (thread.id.slice(1) in hiddenThreads) {
ThreadHiding.hide(thread);
}
}
},
sync: function() {
var hiddenThreads, hiddenThreadsCatalog, id;
hiddenThreads = $.get("hiddenThreads/" + g.BOARD + "/", {});
hiddenThreadsCatalog = JSON.parse(localStorage.getItem("4chan-hide-t-" + g.BOARD)) || {};
if (g.CATALOG) {
for (id in hiddenThreads) {
hiddenThreadsCatalog[id] = true;
}
localStorage.setItem("4chan-hide-t-" + g.BOARD, JSON.stringify(hiddenThreadsCatalog));
} else {
for (id in hiddenThreadsCatalog) {
if (!(id in hiddenThreads)) {
hiddenThreads[id] = Date.now();
}
}
$.set("hiddenThreads/" + g.BOARD + "/", hiddenThreads);
}
return hiddenThreads;
},
cb: function() {
return ThreadHiding.toggle($.x('ancestor::div[parent::div[@class="board"]]', this));
},
toggle: function(thread) {
var hiddenThreads, id;
hiddenThreads = $.get("hiddenThreads/" + g.BOARD + "/", {});
id = thread.id.slice(1);
if (thread.hidden || /\bhidden_thread\b/.test(thread.firstChild.className)) {
ThreadHiding.show(thread);
delete hiddenThreads[id];
} else {
ThreadHiding.hide(thread);
hiddenThreads[id] = Date.now();
}
return $.set("hiddenThreads/" + g.BOARD + "/", hiddenThreads);
},
hide: function(thread, show_stub) {
var a, menuButton, num, opInfo, span, stub, text;
if (show_stub == null) {
show_stub = Conf['Show Stubs'];
}
if (!show_stub) {
thread.hidden = true;
thread.nextElementSibling.hidden = true;
return;
}
if (/\bhidden_thread\b/.test(thread.firstChild.className)) {
return;
}
num = 0;
if (span = $('.summary', thread)) {
num = Number(span.textContent.match(/\d+/));
}
num += $$('.opContainer ~ .replyContainer', thread).length;
text = num === 1 ? '1 reply' : "" + num + " replies";
opInfo = $('.desktop > .nameBlock', thread).textContent;
stub = $.el('div', {
className: 'hide_thread_button hidden_thread',
innerHTML: '<a href="javascript:;"><span>[ + ]</span> </a>'
});
a = stub.firstChild;
$.on(a, 'click', ThreadHiding.cb);
$.add(a, $.tn("" + opInfo + " (" + text + ")"));
if (Conf['Menu']) {
menuButton = Menu.a.cloneNode(true);
$.on(menuButton, 'click', Menu.toggle);
$.add(stub, [$.tn(' '), menuButton]);
}
return $.prepend(thread, stub);
},
show: function(thread) {
var stub;
if (stub = $('.hidden_thread', thread)) {
$.rm(stub);
}
thread.hidden = false;
return thread.nextElementSibling.hidden = false;
}
};
ReplyHiding = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var side;
if (post.isInlined || post.ID === post.threadID) {
return;
}
side = $('.sideArrows', post.root);
$.addClass(side, 'hide_reply_button');
side.innerHTML = '<a href="javascript:;"><span>[ - ]</span></a>';
$.on(side.firstChild, 'click', ReplyHiding.toggle);
if (post.ID in g.hiddenReplies) {
return ReplyHiding.hide(post.root);
}
},
toggle: function() {
var button, id, quote, quotes, root, _i, _j, _len, _len1;
button = this.parentNode;
root = button.parentNode;
id = root.id.slice(2);
quotes = $$(".quotelink[href$='#p" + id + "'], .backlink[href$='#p" + id + "']");
if (/\bstub\b/.test(button.className)) {
ReplyHiding.show(root);
for (_i = 0, _len = quotes.length; _i < _len; _i++) {
quote = quotes[_i];
$.rmClass(quote, 'filtered');
}
delete g.hiddenReplies[id];
} else {
ReplyHiding.hide(root);
for (_j = 0, _len1 = quotes.length; _j < _len1; _j++) {
quote = quotes[_j];
$.addClass(quote, 'filtered');
}
g.hiddenReplies[id] = Date.now();
}
return $.set("hiddenReplies/" + g.BOARD + "/", g.hiddenReplies);
},
hide: function(root, show_stub) {
var a, el, menuButton, side, stub;
if (show_stub == null) {
show_stub = Conf['Show Stubs'];
}
side = $('.sideArrows', root);
if (side.hidden) {
return;
}
side.hidden = true;
el = side.nextElementSibling;
el.hidden = true;
if (!show_stub) {
return;
}
stub = $.el('div', {
className: 'hide_reply_button stub',
innerHTML: '<a href="javascript:;"><span>[ + ]</span> </a>'
});
a = stub.firstChild;
$.on(a, 'click', ReplyHiding.toggle);
$.add(a, $.tn(Conf['Anonymize'] ? 'Anonymous' : $('.desktop > .nameBlock', el).textContent));
if (Conf['Menu']) {
menuButton = Menu.a.cloneNode(true);
$.on(menuButton, 'click', Menu.toggle);
$.add(stub, [$.tn(' '), menuButton]);
}
return $.prepend(root, stub);
},
show: function(root) {
var stub;
if (stub = $('.stub', root)) {
$.rm(stub);
}
$('.sideArrows', root).hidden = false;
return $('.post', root).hidden = false;
}
};
Menu = {
entries: [],
init: function() {
this.a = $.el('a', {
className: 'menu_button',
href: 'javascript:;',
innerHTML: '[<span></span>]'
});
this.el = $.el('div', {
className: 'reply dialog',
id: 'menu',
tabIndex: 0
});
$.on(this.el, 'click', function(e) {
return e.stopPropagation();
});
$.on(this.el, 'keydown', this.keybinds);
$.on(d, 'AddMenuEntry', function(e) {
return Menu.addEntry(e.detail);
});
return Main.callbacks.push(this.node);
},
node: function(post) {
var a;
if (post.isInlined && !post.isCrosspost) {
a = $('.menu_button', post.el);
} else {
a = Menu.a.cloneNode(true);
$.add($('.postInfo', post.el), [$.tn('\u00A0'), a]);
}
return $.on(a, 'click', Menu.toggle);
},
toggle: function(e) {
var lastOpener, post;
e.preventDefault();
e.stopPropagation();
if (Menu.el.parentNode) {
lastOpener = Menu.lastOpener;
Menu.close();
if (lastOpener === this) {
return;
}
}
Menu.lastOpener = this;
post = /\bhidden_thread\b/.test(this.parentNode.className) ? $.x('ancestor::div[parent::div[@class="board"]]/child::div[contains(@class,"opContainer")]', this) : $.x('ancestor::div[contains(@class,"postContainer")][1]', this);
return Menu.open(this, Main.preParse(post));
},
open: function(button, post) {
var bLeft, bRect, bTop, el, entry, funk, mRect, _i, _len, _ref;
el = Menu.el;
el.setAttribute('data-id', post.ID);
el.setAttribute('data-rootid', post.root.id);
funk = function(entry, parent) {
var child, children, subMenu, _i, _len;
children = entry.children;
if (!entry.open(post)) {
return;
}
$.add(parent, entry.el);
if (!children) {
return;
}
if (subMenu = $('.subMenu', entry.el)) {
$.rm(subMenu);
}
subMenu = $.el('div', {
className: 'reply dialog subMenu'
});
$.add(entry.el, subMenu);
for (_i = 0, _len = children.length; _i < _len; _i++) {
child = children[_i];
funk(child, subMenu);
}
};
_ref = Menu.entries;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
entry = _ref[_i];
funk(entry, el);
}
Menu.focus($('.entry', Menu.el));
$.on(d, 'click', Menu.close);
$.add(d.body, el);
mRect = el.getBoundingClientRect();
bRect = button.getBoundingClientRect();
bTop = d.documentElement.scrollTop + d.body.scrollTop + bRect.top;
bLeft = d.documentElement.scrollLeft + d.body.scrollLeft + bRect.left;
el.style.top = bRect.top + bRect.height + mRect.height < d.documentElement.clientHeight ? bTop + bRect.height + 2 + 'px' : bTop - mRect.height - 2 + 'px';
el.style.left = bRect.left + mRect.width < d.documentElement.clientWidth ? bLeft + 'px' : bLeft + bRect.width - mRect.width + 'px';
return el.focus();
},
close: function() {
var el, focused, _i, _len, _ref;
el = Menu.el;
$.rm(el);
_ref = $$('.focused.entry', el);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
focused = _ref[_i];
$.rmClass(focused, 'focused');
}
el.innerHTML = null;
el.removeAttribute('style');
delete Menu.lastOpener;
delete Menu.focusedEntry;
return $.off(d, 'click', Menu.close);
},
keybinds: function(e) {
var el, next, subMenu;
el = Menu.focusedEntry;
switch (Keybinds.keyCode(e) || e.keyCode) {
case 'Esc':
Menu.lastOpener.focus();
Menu.close();
break;
case 13:
case 32:
el.click();
break;
case 'Up':
if (next = el.previousElementSibling) {
Menu.focus(next);
}
break;
case 'Down':
if (next = el.nextElementSibling) {
Menu.focus(next);
}
break;
case 'Right':
if ((subMenu = $('.subMenu', el)) && (next = subMenu.firstElementChild)) {
Menu.focus(next);
}
break;
case 'Left':
if (next = $.x('parent::*[contains(@class,"subMenu")]/parent::*', el)) {
Menu.focus(next);
}
break;
default:
return;
}
e.preventDefault();
return e.stopPropagation();
},
focus: function(el) {
var focused, _i, _len, _ref;
if (focused = $.x('parent::*/child::*[contains(@class,"focused")]', el)) {
$.rmClass(focused, 'focused');
}
_ref = $$('.focused', el);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
focused = _ref[_i];
$.rmClass(focused, 'focused');
}
Menu.focusedEntry = el;
return $.addClass(el, 'focused');
},
addEntry: function(entry) {
var funk;
funk = function(entry) {
var child, children, el, _i, _len;
el = entry.el, children = entry.children;
$.addClass(el, 'entry');
$.on(el, 'focus mouseover', function(e) {
e.stopPropagation();
return Menu.focus(this);
});
if (!children) {
return;
}
$.addClass(el, 'hasSubMenu');
for (_i = 0, _len = children.length; _i < _len; _i++) {
child = children[_i];
funk(child);
}
};
funk(entry);
return Menu.entries.push(entry);
}
};
Keybinds = {
init: function() {
var node, _i, _len, _ref;
_ref = $$('[accesskey]');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
node.removeAttribute('accesskey');
}
return $.on(d, 'keydown', Keybinds.keydown);
},
keydown: function(e) {
var form, key, o, target, thread;
if (!(key = Keybinds.keyCode(e))) {
return;
}
target = e.target;
if (/TEXTAREA|INPUT/.test(target.nodeName)) {
if (!((key === 'Esc') || (/\+/.test(key)))) {
return;
}
}
thread = Nav.getThread();
switch (key) {
case Conf.openQR:
Keybinds.qr(thread, true);
break;
case Conf.openEmptyQR:
Keybinds.qr(thread);
break;
case Conf.openOptions:
if (!$.id('overlay')) {
Options.dialog();
}
break;
case Conf.close:
if (o = $.id('overlay')) {
Options.close.call(o);
} else if (QR.el) {
QR.close();
}
break;
case Conf.submit:
if (QR.el && !QR.status()) {
QR.submit();
}
break;
case Conf.spoiler:
if (target.nodeName !== 'TEXTAREA') {
return;
}
Keybinds.tags('spoiler', target);
break;
case Conf.code:
if (target.nodeName !== 'TEXTAREA') {
return;
}
Keybinds.tags('code', target);
break;
case Conf.sageru:
$("[name=email]", QR.el).value = "sage";
QR.selected.email = "sage";
break;
case Conf.watch:
Watcher.toggle(thread);
break;
case Conf.update:
Updater.update();
break;
case Conf.unreadCountTo0:
Unread.replies = [];
Unread.update(true);
break;
case Conf.expandImage:
Keybinds.img(thread);
break;
case Conf.expandAllImages:
Keybinds.img(thread, true);
break;
case Conf.zero:
window.location = "/" + g.BOARD + "/0#delform";
break;
case Conf.nextPage:
if (form = $('.next form')) {
window.location = form.action;
}
break;
case Conf.previousPage:
if (form = $('.prev form')) {
window.location = form.action;
}
break;
case Conf.nextThread:
if (g.REPLY) {
return;
}
Nav.scroll(+1);
break;
case Conf.previousThread:
if (g.REPLY) {
return;
}
Nav.scroll(-1);
break;
case Conf.expandThread:
ExpandThread.toggle(thread);
break;
case Conf.openThread:
Keybinds.open(thread);
break;
case Conf.openThreadTab:
Keybinds.open(thread, true);
break;
case Conf.nextReply:
Keybinds.hl(+1, thread);
break;
case Conf.previousReply:
Keybinds.hl(-1, thread);
break;
case Conf.hide:
if (/\bthread\b/.test(thread.className)) {
ThreadHiding.toggle(thread);
}
break;
default:
return;
}
return e.preventDefault();
},
keyCode: function(e) {
var c, kc, key;
key = (function() {
switch (kc = e.keyCode) {
case 8:
return '';
case 13:
return 'Enter';
case 27:
return 'Esc';
case 37:
return 'Left';
case 38:
return 'Up';
case 39:
return 'Right';
case 40:
return 'Down';
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
case 65:
case 66:
case 67:
case 68:
case 69:
case 70:
case 71:
case 72:
case 73:
case 74:
case 75:
case 76:
case 77:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 86:
case 87:
case 88:
case 89:
case 90:
c = String.fromCharCode(kc);
if (e.shiftKey) {
return c;
} else {
return c.toLowerCase();
}
break;
default:
return null;
}
})();
if (key) {
if (e.altKey) {
key = 'alt+' + key;
}
if (e.ctrlKey) {
key = 'ctrl+' + key;
}
if (e.metaKey) {
key = 'meta+' + key;
}
}
return key;
},
tags: function(tag, ta) {
var range, selEnd, selStart, value;
value = ta.value;
selStart = ta.selectionStart;
selEnd = ta.selectionEnd;
ta.value = value.slice(0, selStart) + ("[" + tag + "]") + value.slice(selStart, selEnd) + ("[/" + tag + "]") + value.slice(selEnd);
range = ("[" + tag + "]").length + selEnd;
ta.setSelectionRange(range, range);
return ta.dispatchEvent(new Event('input'));
},
img: function(thread, all) {
var thumb;
if (all) {
return $.id('imageExpand').click();
} else {
thumb = $('img[data-md5]', $('.post.highlight', thread) || thread);
return ImageExpand.toggle(thumb.parentNode);
}
},
qr: function(thread, quote) {
if (quote) {
QR.quote.call($('a[title="Reply to this post"]', $('.post.highlight', thread) || thread));
} else {
QR.open();
}
return $('textarea', QR.el).focus();
},
open: function(thread, tab) {
var id, url;
if (g.REPLY) {
return;
}
id = thread.id.slice(1);
url = "//boards.4chan.org/" + g.BOARD + "/thread/" + id;
if (tab) {
return $.open(url);
} else {
return location.href = url;
}
},
hl: function(delta, thread) {
var next, post, rect, replies, reply, _i, _len;
if (post = $('.reply.highlight', thread)) {
$.rmClass(post, 'highlight');
post.removeAttribute('tabindex');
rect = post.getBoundingClientRect();
if (rect.bottom >= 0 && rect.top <= d.documentElement.clientHeight) {
next = $.x('child::div[contains(@class,"post reply")]', delta === +1 ? post.parentNode.nextElementSibling : post.parentNode.previousElementSibling);
if (!next) {
this.focus(post);
return;
}
if (!(g.REPLY || $.x('ancestor::div[parent::div[@class="board"]]', next) === thread)) {
return;
}
rect = next.getBoundingClientRect();
if (rect.top < 0 || rect.bottom > d.documentElement.clientHeight) {
next.scrollIntoView(delta === -1);
}
this.focus(next);
return;
}
}
replies = $$('.reply', thread);
if (delta === -1) {
replies.reverse();
}
for (_i = 0, _len = replies.length; _i < _len; _i++) {
reply = replies[_i];
rect = reply.getBoundingClientRect();
if (delta === +1 && rect.top >= 0 || delta === -1 && rect.bottom <= d.documentElement.clientHeight) {
this.focus(reply);
return;
}
}
},
focus: function(post) {
$.addClass(post, 'highlight');
post.tabIndex = 0;
return post.focus();
}
};
Nav = {
init: function() {
var next, prev, span;
span = $.el('span', {
id: 'navlinks'
});
prev = $.el('a', {
textContent: '▲',
href: 'javascript:;'
});
next = $.el('a', {
textContent: '▼',
href: 'javascript:;'
});
openQR = $.el('a', {
textContent: 'QR',
href: 'javascript:;'
});
$.on(prev, 'click', this.prev);
$.on(next, 'click', this.next);
$.on(openQR, 'click', this.openQR);
$.add(span, [openQR, $.tn(' '), prev, $.tn(' '), next]);
return $.add(d.body, span);
},
prev: function() {
if (g.REPLY) {
return window.scrollTo(0, 0);
} else {
return Nav.scroll(-1);
}
},
next: function() {
if (g.REPLY) {
return window.scrollTo(0, d.body.scrollHeight);
} else {
return Nav.scroll(+1);
}
},
openQR: function() {
QR.open();
if (!g.REPLY) {
QR.threadSelector.value = g.BOARD === 'f' ? '9999' : 'new';
}
return $('textarea', QR.el).focus();
},
getThread: function(full) {
var bottom, i, rect, thread, _i, _len, _ref;
Nav.threads = $$('.thread:not([hidden])');
_ref = Nav.threads;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
thread = _ref[i];
rect = thread.getBoundingClientRect();
bottom = rect.bottom;
if (bottom > 0) {
if (full) {
return [thread, i, rect];
}
return thread;
}
}
return $('.board');
},
scroll: function(delta) {
var i, rect, thread, top, _ref, _ref1;
_ref = Nav.getThread(true), thread = _ref[0], i = _ref[1], rect = _ref[2];
top = rect.top;
if (!((delta === -1 && Math.ceil(top) < 0) || (delta === +1 && top > 1))) {
i += delta;
}
top = (_ref1 = Nav.threads[i]) != null ? _ref1.getBoundingClientRect().top : void 0;
return window.scrollBy(0, top);
}
};
QR = {
mimeTypes: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/x-shockwave-flash', 'video/webm', ''],
init: function() {
if (!$.id('postForm')) {
return;
}
Main.callbacks.push(this.node);
return setTimeout(this.asyncInit);
},
asyncInit: function() {
var link;
if (Conf['Hide Original Post Form']) {
link = $.el('h1', {
innerHTML: "<a href=javascript:;>" + (g.REPLY ? 'Reply to Thread' : 'Start a Thread') + "</a>"
});
$.on(link.firstChild, 'click', function() {
QR.open();
if (!g.REPLY) {
QR.threadSelector.value = g.BOARD === 'f' ? '9999' : 'new';
}
return $('textarea', QR.el).focus();
});
$.before($.id('postForm'), link);
$.id('postForm').style.display = "none";
$.id('togglePostFormLink').style.display = "none";
}
if (Conf['Persistent QR']) {
QR.dialog();
if (Conf['Auto Hide QR']) {
QR.hide();
}
}
$.on(d, 'dragover', QR.dragOver);
$.on(d, 'drop', QR.dropFile);
return $.on(d, 'dragstart dragend', QR.drag);
},
node: function(post) {
return $.on($('a[title="Reply to this post"]', $('.postInfo', post.el)), 'click', QR.quote);
},
open: function() {
if (QR.el) {
QR.el.hidden = false;
return QR.unhide();
} else {
return QR.dialog();
}
},
close: function() {
var i, spoiler, _i, _len, _ref;
QR.el.hidden = true;
QR.abort();
d.activeElement.blur();
$.rmClass(QR.el, 'dump');
_ref = QR.replies;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
i = _ref[_i];
QR.replies[0].rm();
}
QR.cooldown.auto = false;
QR.status();
QR.resetFileInput();
if (!Conf['Remember Spoiler'] && (spoiler = $.id('spoiler')).checked) {
spoiler.click();
}
return QR.cleanError();
},
hide: function() {
d.activeElement.blur();
$.addClass(QR.el, 'autohide');
return $.id('autohide').checked = true;
},
unhide: function() {
$.rmClass(QR.el, 'autohide');
return $.id('autohide').checked = false;
},
toggleHide: function() {
return this.checked && QR.hide() || QR.unhide();
},
error: function(err) {
var el;
el = $('.warning', QR.el);
if (typeof err === 'string') {
el.textContent = err;
} else {
el.innerHTML = null;
$.add(el, err);
}
QR.open();
if (d.hidden) {
return alert(el.textContent);
}
},
cleanError: function() {
return $('.warning', QR.el).textContent = null;
},
status: function(data) {
var disabled, input, value;
if (data == null) {
data = {};
}
if (!QR.el) {
return;
}
if (g.dead) {
value = 404;
disabled = true;
QR.cooldown.auto = false;
}
value = data.progress || QR.cooldown.seconds || value;
input = QR.status.input;
input.value = QR.cooldown.auto && Conf['Cooldown'] ? value ? "Auto " + value : 'Auto' : value || 'Submit';
return input.disabled = disabled || false;
},
cooldown: {
init: function() {
if (!Conf['Cooldown']) {
return;
}
QR.cooldown.types = {
thread: (function() {
switch (g.BOARD) {
case 'jp':
return 3600;
case 'b':
case 'soc':
case 'r9k':
return 600;
default:
return 300;
}
})(),
sage: 60,
file: g.BOARD === 'vg' ? 120 : 60,
post: g.BOARD === 'vg' ? 90 : 60
};
QR.cooldown.cooldowns = $.get("" + g.BOARD + ".cooldown", {});
QR.cooldown.start();
return $.sync("" + g.BOARD + ".cooldown", QR.cooldown.sync);
},
start: function() {
if (QR.cooldown.isCounting) {
return;
}
QR.cooldown.isCounting = true;
return QR.cooldown.count();
},
sync: function(cooldowns) {
var id;
for (id in cooldowns) {
QR.cooldown.cooldowns[id] = cooldowns[id];
}
return QR.cooldown.start();
},
set: function(data) {
var cooldown, hasFile, isReply, isSage, start, type;
if (!Conf['Cooldown']) {
return;
}
start = Date.now();
if (data.delay) {
cooldown = {
delay: data.delay
};
} else {
isSage = /sage/i.test(data.post.email);
hasFile = !!data.post.file;
isReply = data.isReply;
type = !isReply ? 'thread' : isSage ? 'sage' : hasFile ? 'file' : 'post';
cooldown = {
isReply: isReply,
isSage: isSage,
hasFile: hasFile,
timeout: start + QR.cooldown.types[type] * $.SECOND
};
}
QR.cooldown.cooldowns[start] = cooldown;
$.set("" + g.BOARD + ".cooldown", QR.cooldown.cooldowns);
return QR.cooldown.start();
},
unset: function(id) {
delete QR.cooldown.cooldowns[id];
return $.set("" + g.BOARD + ".cooldown", QR.cooldown.cooldowns);
},
count: function() {
var cooldown, cooldowns, elapsed, hasFile, isReply, isSage, now, post, seconds, start, type, types, update, _ref;
if (Object.keys(QR.cooldown.cooldowns).length) {
setTimeout(QR.cooldown.count, 1000);
} else {
$["delete"]("" + g.BOARD + ".cooldown");
delete QR.cooldown.isCounting;
delete QR.cooldown.seconds;
QR.status();
return;
}
if ((isReply = g.REPLY ? true : QR.threadSelector.value !== 'new')) {
post = QR.replies[0];
isSage = /sage/i.test(post.email);
hasFile = !!post.file;
}
now = Date.now();
seconds = null;
_ref = QR.cooldown, types = _ref.types, cooldowns = _ref.cooldowns;
for (start in cooldowns) {
cooldown = cooldowns[start];
if ('delay' in cooldown) {
if (cooldown.delay) {
seconds = Math.max(seconds, cooldown.delay--);
} else {
seconds = Math.max(seconds, 0);
QR.cooldown.unset(start);
}
continue;
}
if (isReply === cooldown.isReply) {
type = !isReply ? 'thread' : isSage && cooldown.isSage ? 'sage' : hasFile && cooldown.hasFile ? 'file' : 'post';
elapsed = Math.floor((now - start) / 1000);
if (elapsed >= 0) {
seconds = Math.max(seconds, types[type] - elapsed);
}
}
if (!((start <= now && now <= cooldown.timeout))) {
QR.cooldown.unset(start);
}
}
update = seconds !== null || !!QR.cooldown.seconds;
QR.cooldown.seconds = seconds;
if (update) {
QR.status();
}
if (seconds === 0 && QR.cooldown.auto) {
return QR.submit();
}
}
},
quote: function(e) {
var caretPos, id, range, s, sel, ta, text, _ref;
if (e != null) {
e.preventDefault();
}
QR.open();
ta = $('textarea', QR.el);
if (!(g.REPLY || ta.value)) {
QR.threadSelector.value = $.x('ancestor::div[parent::div[@class="board"]]', this).id.slice(1);
}
id = this.previousSibling.hash.slice(2);
text = ">>" + id + "\n";
sel = d.getSelection();
if ((s = sel.toString().trim()) && id === ((_ref = $.x('ancestor-or-self::blockquote', sel.anchorNode)) != null ? _ref.id.match(/\d+$/)[0] : void 0)) {
s = s.replace(/\n/g, '\n>');
text += ">" + s + "\n";
}
caretPos = ta.selectionStart;
ta.value = ta.value.slice(0, caretPos) + text + ta.value.slice(ta.selectionEnd);
range = caretPos + text.length;
ta.setSelectionRange(range, range);
ta.focus();
return ta.dispatchEvent(new Event('input'));
},
characterCount: function() {
var count, counter;
counter = QR.charaCounter;
count = this.textLength;
counter.textContent = count;
counter.hidden = count < 1000;
return (count > 1500 ? $.addClass : $.rmClass)(counter, 'warning');
},
drag: function(e) {
var toggle;
toggle = e.type === 'dragstart' ? $.off : $.on;
toggle(d, 'dragover', QR.dragOver);
return toggle(d, 'drop', QR.dropFile);
},
dragOver: function(e) {
e.preventDefault();
return e.dataTransfer.dropEffect = 'copy';
},
dropFile: function(e) {
if (!e.dataTransfer.files.length) {
return;
}
e.preventDefault();
QR.open();
QR.fileInput.call(e.dataTransfer);
return $.addClass(QR.el, 'dump');
},
fileInput: function() {
var file, _i, _len, _ref;
QR.cleanError();
if (this.files.length === 1) {
file = this.files[0];
if (file.size > this.max) {
QR.error('File too large.');
QR.resetFileInput();
} else if (-1 === QR.mimeTypes.indexOf(file.type)) {
QR.error('Unsupported file type.');
QR.resetFileInput();
} else {
QR.selected.setFile(file);
}
return;
}
_ref = this.files;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
file = _ref[_i];
if (file.size > this.max) {
QR.error("File " + file.name + " is too large.");
break;
} else if (-1 === QR.mimeTypes.indexOf(file.type)) {
QR.error("" + file.name + ": Unsupported file type.");
break;
}
if (!QR.replies[QR.replies.length - 1].file) {
QR.replies[QR.replies.length - 1].setFile(file);
} else {
new QR.reply().setFile(file);
}
}
$.addClass(QR.el, 'dump');
return QR.resetFileInput();
},
resetFileInput: function() {
return $('[type=file]', QR.el).value = null;
},
replies: [],
reply: (function() {
function _Class() {
var persona, prev,
_this = this;
prev = QR.replies[QR.replies.length - 1];
persona = $.get('QR.persona', {});
this.name = prev ? prev.name : persona.name || null;
this.email = prev && !/^sage$/.test(prev.email) ? prev.email : persona.email || null;
this.sub = prev && Conf['Remember Subject'] ? prev.sub : Conf['Remember Subject'] ? persona.sub : null;
this.spoiler = prev && Conf['Remember Spoiler'] ? prev.spoiler : false;
this.com = null;
this.el = $.el('a', {
className: 'thumbnail',
draggable: true,
href: 'javascript:;',
innerHTML: '<a class=remove>×</a><label hidden><input type=checkbox> Spoiler</label><span></span>'
});
$('input', this.el).checked = this.spoiler;
$.on(this.el, 'click', function() {
return _this.select();
});
$.on($('.remove', this.el), 'click', function(e) {
e.stopPropagation();
return _this.rm();
});
$.on($('label', this.el), 'click', function(e) {
return e.stopPropagation();
});
$.on($('input', this.el), 'change', function(e) {
_this.spoiler = e.target.checked;
if (_this.el.id === 'selected') {
return $.id('spoiler').checked = _this.spoiler;
}
});
$.before($('#addReply', QR.el), this.el);
$.on(this.el, 'dragstart', this.dragStart);
$.on(this.el, 'dragenter', this.dragEnter);
$.on(this.el, 'dragleave', this.dragLeave);
$.on(this.el, 'dragover', this.dragOver);
$.on(this.el, 'dragend', this.dragEnd);
$.on(this.el, 'drop', this.drop);
QR.replies.push(this);
}
_Class.prototype.setFile = function(file) {
var fileUrl, img, url,
_this = this;
this.file = file;
this.el.title = "" + file.name + " (" + ($.bytesToString(file.size)) + ")";
if (QR.spoiler) {
$('label', this.el).hidden = false;
}
if (!/^image/.test(file.type)) {
this.el.style.backgroundImage = null;
return;
}
if (!(url = window.URL || window.webkitURL)) {
return;
}
url.revokeObjectURL(this.url);
fileUrl = url.createObjectURL(file);
img = $.el('img');
$.on(img, 'load', function() {
var c, data, i, l, s, ui8a, _i;
s = 90 * 3;
if (img.height < s || img.width < s) {
_this.url = fileUrl;
_this.el.style.backgroundImage = "url(" + _this.url + ")";
return;
}
if (img.height <= img.width) {
img.width = s / img.height * img.width;
img.height = s;
} else {
img.height = s / img.width * img.height;
img.width = s;
}
c = $.el('canvas');
c.height = img.height;
c.width = img.width;
c.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
data = atob(c.toDataURL().split(',')[1]);
l = data.length;
ui8a = new Uint8Array(l);
for (i = _i = 0; 0 <= l ? _i < l : _i > l; i = 0 <= l ? ++_i : --_i) {
ui8a[i] = data.charCodeAt(i);
}
_this.url = url.createObjectURL(new Blob([ui8a], {
type: 'image/png'
}));
_this.el.style.backgroundImage = "url(" + _this.url + ")";
return typeof url.revokeObjectURL === "function" ? url.revokeObjectURL(fileUrl) : void 0;
});
return img.src = fileUrl;
};
_Class.prototype.rmFile = function() {
var _base1;
QR.resetFileInput();
delete this.file;
this.el.title = null;
this.el.style.backgroundImage = null;
if (QR.spoiler) {
$('label', this.el).hidden = true;
}
return typeof (_base1 = window.URL || window.webkitURL).revokeObjectURL === "function" ? _base1.revokeObjectURL(this.url) : void 0;
};
_Class.prototype.select = function() {
var data, rectEl, rectList, _i, _len, _ref, _ref1;
if ((_ref = QR.selected) != null) {
_ref.el.id = null;
}
QR.selected = this;
this.el.id = 'selected';
rectEl = this.el.getBoundingClientRect();
rectList = this.el.parentNode.getBoundingClientRect();
this.el.parentNode.scrollLeft += rectEl.left + rectEl.width / 2 - rectList.left - rectList.width / 2;
_ref1 = ['name', 'email', 'sub', 'com'];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
data = _ref1[_i];
$("[name=" + data + "]", QR.el).value = this[data];
}
QR.characterCount.call($('textarea', QR.el));
return $('#spoiler', QR.el).checked = this.spoiler;
};
_Class.prototype.dragStart = function() {
return $.addClass(this, 'drag');
};
_Class.prototype.dragEnter = function() {
return $.addClass(this, 'over');
};
_Class.prototype.dragLeave = function() {
return $.rmClass(this, 'over');
};
_Class.prototype.dragOver = function(e) {
e.preventDefault();
return e.dataTransfer.dropEffect = 'move';
};
_Class.prototype.drop = function() {
var el, index, newIndex, oldIndex, reply;
el = $('.drag', this.parentNode);
index = function(el) {
return Array.prototype.slice.call(el.parentNode.children).indexOf(el);
};
oldIndex = index(el);
newIndex = index(this);
if (oldIndex < newIndex) {
$.after(this, el);
} else {
$.before(this, el);
}
reply = QR.replies.splice(oldIndex, 1)[0];
return QR.replies.splice(newIndex, 0, reply);
};
_Class.prototype.dragEnd = function() {
var el;
$.rmClass(this, 'drag');
if (el = $('.over', this.parentNode)) {
return $.rmClass(el, 'over');
}
};
_Class.prototype.rm = function() {
var index, _base1;
QR.resetFileInput();
$.rm(this.el);
index = QR.replies.indexOf(this);
if (QR.replies.length === 1) {
new QR.reply().select();
} else if (this.el.id === 'selected') {
(QR.replies[index - 1] || QR.replies[index + 1]).select();
}
QR.replies.splice(index, 1);
return typeof (_base1 = window.URL || window.webkitURL).revokeObjectURL === "function" ? _base1.revokeObjectURL(this.url) : void 0;
};
return _Class;
})(),
captcha: {
init: function() {
if (-1 !== d.cookie.indexOf('pass_enabled=')) {
return;
}
if (!(this.isEnabled = !!$.id('g-recaptcha'))) {
return;
}
return this.ready();
},
ready: function() {
if(!CaptchaIsSetup) {
$.addClass(QR.el, 'captcha');
$.globalEval('(function () {window.grecaptcha.render(document.getElementById("g-recaptcha"), {sitekey: "6Ldp2bsSAAAAAAJ5uyx_lx34lJeEpTLVkP5k04qc", theme: "light", callback: (' + (Conf['Auto Submit'] ? 'function (res) {var sb = document.getElementById("x_QR_Submit"); if(sb) sb.click(); }' : 'function (res) {}') + ') });})()');
$.after($('.textarea', QR.el), $.id('g-recaptcha'));
CaptchaIsSetup = true;
}
},
getResponse: function() {
$.globalEval('document.getElementById("captcha_response_field").value = window.grecaptcha.getResponse();');
return $.id("captcha_response_field").value;
},
reset: function() {
$.globalEval('window.grecaptcha.reset();');
}
},
dialog: function() {
var fileInput, id, mimeTypes, name, spoiler, ta, thread, threads, _i, _j, _len, _len1, _ref, _ref1;
QR.el = UI.dialog('qr', 'top:0;right:0;', '\
<div class=move>\
Quick Reply <input type=checkbox id=autohide title=Auto-hide>\
<span> <a class=close title=Close>×</a></span>\
</div>\
<form>\
<div><input id=dump type=button title="Dump list" value=+ class=field><input name=name title=Name placeholder=Name class=field size=1><input name=email title=E-mail placeholder=E-mail class=field size=1><input name=sub title=Subject placeholder=Subject class=field size=1></div>\
<div id=replies><div><a id=addReply href=javascript:; title="Add a reply">+</a></div></div>\
<div class=textarea><textarea name=com title=Comment placeholder=Comment class=field id=commentTextArea></textarea><span id=charCount></span></div>\
<div><input type=file title="Shift+Click to remove the selected file." multiple size=16><input type=submit id="x_QR_Submit"></div>\
<label id=spoilerLabel><input type=checkbox id=spoiler> Spoiler Image</label>\
<div class=warning></div>\
<input type="hidden" name="captcha_response" id="captcha_response_field" value="">\
</form>');
if (Conf['Remember QR size'] && $.engine === 'gecko') {
$.on(ta = $('textarea', QR.el), 'mouseup', function() {
return $.set('QR.size', this.style.cssText);
});
ta.style.cssText = $.get('QR.size', '');
}
fileInput = $('input[type=file]', QR.el);
fileInput.max = $('input[name=MAX_FILE_SIZE]').value;
if ($.engine !== 'presto') {
fileInput.accept = mimeTypes;
}
QR.spoiler = !!$('input[name=spoiler]');
spoiler = $('#spoilerLabel', QR.el);
spoiler.hidden = !QR.spoiler;
QR.charaCounter = $('#charCount', QR.el);
ta = $('textarea', QR.el);
if (!g.REPLY) {
threads = '<option value=new>New thread</option>';
_ref = $$('.thread');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
thread = _ref[_i];
id = thread.id.slice(1);
threads += "<option value=" + id + ">Thread " + id + "</option>";
}
QR.threadSelector = g.BOARD === 'f' ? $('select[name=filetag]').cloneNode(true) : $.el('select', {
innerHTML: threads,
title: 'Create a new thread / Reply to a thread'
});
$.prepend($('.move > span', QR.el), QR.threadSelector);
$.on(QR.threadSelector, 'mousedown', function(e) {
return e.stopPropagation();
});
}
$.on($('#autohide', QR.el), 'change', QR.toggleHide);
$.on($('.close', QR.el), 'click', QR.close);
$.on($('#dump', QR.el), 'click', function() {
return QR.el.classList.toggle('dump');
});
$.on($('#addReply', QR.el), 'click', function() {
return new QR.reply().select();
});
$.on($('form', QR.el), 'submit', QR.submit);
$.on(ta, 'input', function() {
return QR.selected.el.lastChild.textContent = this.value;
});
$.on(ta, 'input', QR.characterCount);
$.on(fileInput, 'change', QR.fileInput);
$.on(fileInput, 'click', function(e) {
if (e.shiftKey) {
return QR.selected.rmFile() || e.preventDefault();
}
});
$.on(spoiler.firstChild, 'change', function() {
return $('input', QR.selected.el).click();
});
$.on($('.warning', QR.el), 'click', QR.cleanError);
new QR.reply().select();
_ref1 = ['name', 'email', 'sub', 'com'];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
name = _ref1[_j];
$.on($("[name=" + name + "]", QR.el), 'input', function() {
var _ref2;
QR.selected[this.name] = this.value;
if (QR.cooldown.auto && QR.selected === QR.replies[0] && (0 < (_ref2 = QR.cooldown.seconds) && _ref2 <= 5)) {
return QR.cooldown.auto = false;
}
});
}
QR.status.input = $('input[type=submit]', QR.el);
QR.status();
QR.cooldown.init();
QR.captcha.init();
$.add(d.body, QR.el);
return $.event('QRDialogCreation', null, QR.el);
},
submit: function(e) {
var callbacks, err, filetag, m, opts, post, reply, response, textOnly, threadID;
if (e != null) {
e.preventDefault();
}
if (QR.cooldown.seconds) {
QR.cooldown.auto = !QR.cooldown.auto;
QR.status();
return;
}
QR.abort();
reply = QR.replies[0];
if (g.BOARD === 'f' && !g.REPLY) {
filetag = QR.threadSelector.value;
threadID = 'new';
} else {
threadID = g.THREAD_ID || QR.threadSelector.value;
}
if (threadID === 'new') {
threadID = null;
if (g.BOARD === 'vg' && !reply.sub) {
err = 'New threads require a subject.';
} else if (!(reply.file || (textOnly = !!$('input[name=textonly]', $.id('postForm'))))) {
err = 'No file selected.';
} else if (g.BOARD === 'f' && filetag === '9999') {
err = 'Invalid tag specified.';
}
} else if (!(reply.com || reply.file)) {
err = 'No file selected.';
}
if (QR.captcha.isEnabled && !err) {
response = QR.captcha.getResponse();
if (!response) {
err = 'No valid captcha.';
}
}
if (err) {
QR.cooldown.auto = false;
QR.status();
QR.error(err);
return;
}
QR.cleanError();
QR.cooldown.auto = QR.replies.length > 1;
if (Conf['Auto Hide QR'] && !QR.cooldown.auto) {
QR.hide();
}
if (!QR.cooldown.auto && $.x('ancestor::div[@id="qr"]', d.activeElement)) {
d.activeElement.blur();
}
QR.status({
progress: '...'
});
post = {
resto: threadID,
name: reply.name,
email: reply.email,
sub: reply.sub,
com: reply.com,
upfile: reply.file,
filetag: filetag,
spoiler: reply.spoiler,
textonly: textOnly,
mode: 'regist',
pwd: (m = d.cookie.match(/4chan_pass=([^;]+)/)) ? decodeURIComponent(m[1]) : $('input[name=pwd]').value,
'g-recaptcha-response': response
};
callbacks = {
onload: function() {
return QR.response(this.response);
},
onerror: function() {
if (QR.captcha.isEnabled) {
QR.captcha.reset();
}
QR.cooldown.auto = false;
QR.status();
return QR.error($.el('a', {
href: '//www.4chan.org/banned',
target: '_blank',
textContent: 'Connection error, or you are banned.'
}));
}
};
opts = {
form: $.formData(post),
upCallbacks: {
onload: function() {
return QR.status({
progress: '...'
});
},
onprogress: function(e) {
return QR.status({
progress: "" + (Math.round(e.loaded / e.total * 100)) + "%"
});
}
}
};
return QR.ajax = $.ajax($.id('postForm').parentNode.action, callbacks, opts);
},
response: function(html) {
var ban, board, clone, doc, err, obj, persona, postID, reply, threadID, _, _ref, _ref1;
if (QR.captcha.isEnabled) {
QR.captcha.reset();
}
doc = d.implementation.createHTMLDocument('');
doc.documentElement.innerHTML = html;
if (ban = $('.banType', doc)) {
board = $('.board', doc).innerHTML;
err = $.el('span', {
innerHTML: ban.textContent.toLowerCase() === 'banned' ? ("You are banned on " + board + "! ;_;<br>") + "Click <a href=//www.4chan.org/banned target=_blank>here</a> to see the reason." : ("You were issued a warning on " + board + " as " + ($('.nameBlock', doc).innerHTML) + ".<br>") + ("Reason: " + ($('.reason', doc).innerHTML))
});
} else if (err = doc.getElementById('errmsg')) {
if ((_ref = $('a', err)) != null) {
_ref.target = '_blank';
}
} else if (doc.title !== 'Post successful!') {
err = 'Connection error with sys.4chan.org.';
}
if (err) {
if (/captcha|verification/i.test(err.textContent) || err === 'Connection error with sys.4chan.org.') {
if (/mistyped/i.test(err.textContent)) {
err = 'Error: You seem to have mistyped the CAPTCHA.';
}
QR.cooldown.auto = false;
QR.cooldown.set({
delay: 2
});
} else {
QR.cooldown.auto = false;
}
QR.status();
QR.error(err);
return;
}
reply = QR.replies[0];
persona = $.get('QR.persona', {});
persona = {
name: reply.name,
email: /^sage$/.test(reply.email) ? persona.email : reply.email,
sub: Conf['Remember Subject'] ? reply.sub : null
};
$.set('QR.persona', persona);
_ref1 = doc.body.lastChild.textContent.match(/thread:(\d+),no:(\d+)/), _ = _ref1[0], threadID = _ref1[1], postID = _ref1[2];
obj = {boardID: g.BOARD, threadID: threadID, postID: postID};
clone = (typeof(cloneInto) === 'function' && cloneInto(obj, document.defaultView)) || obj;
$.event('QRPostSuccessful', clone, QR.el);
/* Add your own replies to yourPosts and storage to watch for replies */
if (Conf['Indicate You quote']) {
yourPosts.push(postID);
sessionStorage.setItem('yourPosts', JSON.stringify(yourPosts));
}
QR.cooldown.set({
post: reply,
isReply: threadID !== '0'
});
if (threadID === '0') {
location.pathname = "/" + g.BOARD + "/thread/" + postID;
} else {
QR.cooldown.auto = QR.replies.length > 1;
if (Conf['Open Reply in New Tab'] && !g.REPLY && !QR.cooldown.auto) {
$.open("//boards.4chan.org/" + g.BOARD + "/thread/" + threadID + "#p" + postID);
}
}
if (Conf['Persistent QR'] || QR.cooldown.auto) {
reply.rm();
} else {
QR.close();
}
QR.status();
return QR.resetFileInput();
},
abort: function() {
var _ref;
if ((_ref = QR.ajax) != null) {
_ref.abort();
}
delete QR.ajax;
return QR.status();
}
};
Options = {
init: function() {
return $.ready(Options.initReady);
},
initReady: function() {
var a, notice, setting;
a = $.el('a', {
href: 'javascript:;',
className: 'settingsWindowLink',
textContent: '4chan X Settings'
});
$.on(a, 'click', Options.dialog);
setting = $.id('navtopright');
if (Conf['Disable 4chan\'s extension']) {
$.replace(setting.firstElementChild, a);
} else {
$.prepend(setting, [$.tn('['), a, $.tn('] ')]);
}
notice = $.el('a', {
textContent: 'v2 is never outdated.',
href: 'https://github.com/loadletter/4chan-x',
target: '_blank'
});
notice.style.color = 'red';
$.prepend(setting, [$.tn('['), notice, $.tn('] ')]);
$.ready(function () {
setTimeout(function () {
var navbotLink = $('#navbotright > .settingsWindowLink');
if (navbotLink) {
$.on(navbotLink, 'click', Options.dialog);
}
}, 0);
});
if (!$.get('firstrun')) {
$.set('firstrun', true);
if (!Favicon.el) {
Favicon.init();
}
return Options.dialog();
}
},
dialog: function() {
var arr, back, checked, description, dialog, favicon, fileInfo, filter, hiddenNum, hiddenThreads, indicator, indicators, input, key, li, obj, overlay, sauce, time, tr, ul, _i, _len, _ref, _ref1, _ref2;
dialog = $.el('div', {
id: 'options',
className: 'reply dialog',
innerHTML: '<div id=optionsbar>\
<div id=credits>\
<a target=_blank href=https://github.com/loadletter/4chan-x>4chan X</a>\
| <a target=_blank href=https://github.com/loadletter/4chan-x/commits/master>' + Main.version + '</a>\
| <a target=_blank href=https://github.com/loadletter/4chan-x/issues>Issues</a>\
</div>\
<div>\
<label for=main_tab>Main</label>\
| <label for=filter_tab>Filter</label>\
| <label for=sauces_tab>Sauce</label>\
| <label for=rice_tab>Rice</label>\
| <label for=keybinds_tab>Keybinds</label>\
</div>\
</div>\
<hr>\
<div id=content>\
<input type=radio name=tab hidden id=main_tab checked>\
<div>\
<div class=imp-exp>\
<button class=export>Export settings</button>\
<button class=import>Import settings</button>\
<input type=file style="visibility:hidden">\
</div>\
<p class=imp-exp-result></p>\
</div>\
<input type=radio name=tab hidden id=sauces_tab>\
<div>\
<div class=warning><code>Sauce</code> is disabled.</div>\
Lines starting with a <code>#</code> will be ignored.<br>\
You can specify a certain display text by appending <code>;text:[text]</code> to the url.\
<ul>These parameters will be replaced by their corresponding values:\
<li>$1: Thumbnail url.</li>\
<li>$2: Full image url.</li>\
<li>$3: MD5 hash.</li>\
<li>$4: Current board.</li>\
</ul>\
<textarea name=sauces id=sauces class=field></textarea>\
</div>\
<input type=radio name=tab hidden id=filter_tab>\
<div>\
<div class=warning><code>Filter</code> is disabled.</div>\
<select name=filter>\
<option value=guide>Guide</option>\
<option value=name>Name</option>\
<option value=uniqueid>Unique ID</option>\
<option value=tripcode>Tripcode</option>\
<option value=mod>Admin/Mod</option>\
<option value=subject>Subject</option>\
<option value=comment>Comment</option>\
<option value=country>Country</option>\
<option value=filename>Filename</option>\
<option value=dimensions>Image dimensions</option>\
<option value=filesize>Filesize</option>\
<option value=md5>Image MD5 (uses exact string matching, not regular expressions)</option>\
</select>\
</div>\
<input type=radio name=tab hidden id=rice_tab>\
<div>\
<div class=warning><code>Quote Backlinks</code> are disabled.</div>\
<ul>\
Backlink formatting\
<li><input name=backlink class=field> : <span id=backlinkPreview></span></li>\
</ul>\
<div class=warning><code>Time Formatting</code> is disabled.</div>\
<ul>\
Time formatting\
<li><input name=time class=field> : <span id=timePreview></span></li>\
<li>Supported <a href=http://en.wikipedia.org/wiki/Date_%28Unix%29#Formatting>format specifiers</a>:</li>\
<li>Day: %a, %A, %d, %e</li>\
<li>Month: %m, %b, %B</li>\
<li>Year: %y</li>\
<li>Hour: %k, %H, %l (lowercase L), %I (uppercase i), %p, %P</li>\
<li>Minutes: %M</li>\
<li>Seconds: %S</li>\
</ul>\
<div class=warning><code>File Info Formatting</code> is disabled.</div>\
<ul>\
File Info Formatting\
<li><input name=fileInfo class=field> : <span id=fileInfoPreview class=fileText></span></li>\
<li>Link: %l (lowercase L, truncated), %L (untruncated), %T (Unix timestamp)</li>\
<li>Original file name: %n (truncated), %N (untruncated), %t (Unix timestamp)</li>\
<li>Spoiler indicator: %p</li>\
<li>Size: %B (Bytes), %K (KB), %M (MB), %s (4chan default)</li>\
<li>Resolution: %r (Displays PDF on /po/, for PDFs)</li>\
</ul>\
<div class=warning><code>Unread Favicon</code> is disabled.</div>\
Unread favicons<br>\
<select name=favicon>\
<option value=ferongr>ferongr</option>\
<option value=xat->xat-</option>\
<option value=Mayhem>Mayhem</option>\
<option value=Original>Original</option>\
</select>\
<span></span>\
</div>\
<input type=radio name=tab hidden id=keybinds_tab>\
<div>\
<div class=warning><code>Keybinds</code> are disabled.</div>\
<div>Allowed keys: Ctrl, Alt, Meta, a-z, A-Z, 0-9, Up, Down, Right, Left.</div>\
<table><tbody>\
<tr><th>Actions</th><th>Keybinds</th></tr>\
</tbody></table>\
</div>\
</div>'
});
$.on($('#main_tab + div .export', dialog), 'click', Options["export"]);
$.on($('#main_tab + div .import', dialog), 'click', Options["import"]);
$.on($('#main_tab + div input', dialog), 'change', Options.onImport);
_ref = Config.main;
for (key in _ref) {
obj = _ref[key];
ul = $.el('ul', {
textContent: key
});
for (key in obj) {
arr = obj[key];
checked = $.get(key, Conf[key]) ? 'checked' : '';
description = arr[1];
li = $.el('li', {
innerHTML: "<label><input type=checkbox name=\"" + key + "\" " + checked + ">" + key + "</label><span class=description>: " + description + "</span>"
});
$.on($('input', li), 'click', $.cb.checked);
$.add(ul, li);
}
$.add($('#main_tab + div', dialog), ul);
}
hiddenThreads = $.get("hiddenThreads/" + g.BOARD + "/", {});
hiddenNum = Object.keys(g.hiddenReplies).length + Object.keys(hiddenThreads).length;
li = $.el('li', {
innerHTML: "<button>hidden: " + hiddenNum + "</button> <span class=description>: Forget all hidden posts. Useful if you accidentally hide a post and have \"Show Stubs\" disabled."
});
$.on($('button', li), 'click', Options.clearHidden);
$.add($('ul:nth-child(2)', dialog), li);
filter = $('select[name=filter]', dialog);
$.on(filter, 'change', Options.filter);
sauce = $('#sauces', dialog);
sauce.value = $.get(sauce.name, Conf[sauce.name]);
$.on(sauce, 'change', $.cb.value);
(back = $('[name=backlink]', dialog)).value = $.get('backlink', Conf['backlink']);
(time = $('[name=time]', dialog)).value = $.get('time', Conf['time']);
(fileInfo = $('[name=fileInfo]', dialog)).value = $.get('fileInfo', Conf['fileInfo']);
$.on(back, 'input', $.cb.value);
$.on(back, 'input', Options.backlink);
$.on(time, 'input', $.cb.value);
$.on(time, 'input', Options.time);
$.on(fileInfo, 'input', $.cb.value);
$.on(fileInfo, 'input', Options.fileInfo);
favicon = $('select[name=favicon]', dialog);
favicon.value = $.get('favicon', Conf['favicon']);
$.on(favicon, 'change', $.cb.value);
$.on(favicon, 'change', Options.favicon);
_ref1 = Config.hotkeys;
for (key in _ref1) {
arr = _ref1[key];
tr = $.el('tr', {
innerHTML: "<td>" + arr[1] + "</td><td><input name=" + key + " class=field></td>"
});
input = $('input', tr);
input.value = $.get(key, Conf[key]);
$.on(input, 'keydown', Options.keybind);
$.add($('#keybinds_tab + div tbody', dialog), tr);
}
indicators = {};
_ref2 = $$('.warning', dialog);
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
indicator = _ref2[_i];
key = indicator.firstChild.textContent;
indicator.hidden = $.get(key, Conf[key]);
indicators[key] = indicator;
$.on($("[name='" + key + "']", dialog), 'click', function() {
return indicators[this.name].hidden = this.checked;
});
}
overlay = $.el('div', {
id: 'overlay'
});
$.on(overlay, 'click', Options.close);
$.on(dialog, 'click', function(e) {
return e.stopPropagation();
});
$.add(overlay, dialog);
$.add(d.body, overlay);
d.body.style.setProperty('width', "" + d.body.clientWidth + "px", null);
$.addClass(d.body, 'unscroll');
Options.filter.call(filter);
Options.backlink.call(back);
Options.time.call(time);
Options.fileInfo.call(fileInfo);
return Options.favicon.call(favicon);
},
close: function() {
$.rm(this);
d.body.style.removeProperty('width');
return $.rmClass(d.body, 'unscroll');
},
clearHidden: function() {
$["delete"]("hiddenReplies/" + g.BOARD + "/");
$["delete"]("hiddenThreads/" + g.BOARD + "/");
this.textContent = "hidden: 0";
return g.hiddenReplies = {};
},
keybind: function(e) {
var key;
if (e.keyCode === 9) {
return;
}
e.preventDefault();
e.stopPropagation();
if ((key = Keybinds.keyCode(e)) == null) {
return;
}
this.value = key;
return $.cb.value.call(this);
},
filter: function() {
var el, name, ta;
el = this.nextSibling;
if ((name = this.value) !== 'guide') {
ta = $.el('textarea', {
name: name,
className: 'field',
value: $.get(name, Conf[name])
});
$.on(ta, 'change', $.cb.value);
$.replace(el, ta);
return;
}
if (el) {
$.rm(el);
}
return $.after(this, $.el('article', {
innerHTML: '<p>Use <a href=https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions>regular expressions</a>, one per line.<br>\
Lines starting with a <code>#</code> will be ignored.<br>\
For example, <code>/weeaboo/i</code> will filter posts containing the string `<code>weeaboo</code>`, case-insensitive.</p>\
<ul>You can use these settings with each regular expression, separate them with semicolons:\
<li>\
Per boards, separate them with commas. It is global if not specified.<br>\
For example: <code>boards:a,jp;</code>.\
</li>\
<li>\
Filter OPs only along with their threads (`only`), replies only (`no`, this is default), or both (`yes`).<br>\
For example: <code>op:only;</code>, <code>op:no;</code> or <code>op:yes;</code>.\
</li>\
<li>\
Overrule the `Show Stubs` setting if specified: create a stub (`yes`) or not (`no`).<br>\
For example: <code>stub:yes;</code> or <code>stub:no;</code>.\
</li>\
<li>\
Highlight instead of hiding. You can specify a class name to use with a userstyle.<br>\
For example: <code>highlight;</code> or <code>highlight:wallpaper;</code>.\
</li>\
<li>\
Highlighted OPs will have their threads put on top of board pages by default.<br>\
For example: <code>top:yes;</code> or <code>top:no;</code>.\
</li>\
</ul>'
}));
},
time: function() {
Time.date = new Date();
return $.id('timePreview').textContent = Time.funk();
},
backlink: function() {
return $.id('backlinkPreview').textContent = Conf['backlink'].replace(/%id/, '123456789');
},
fileInfo: function() {
FileInfo.data = {
link: '//i.4cdn.org/g/1334437723720.jpg',
spoiler: true,
size: '276',
unit: 'KB',
resolution: '1280x720',
fullname: 'd9bb2efc98dd0df141a94399ff5880b7.jpg',
shortname: 'd9bb2efc98dd0df141a94399ff5880(...).jpg'
};
return $.id('fileInfoPreview').innerHTML = FileInfo.funk();
},
favicon: function() {
Favicon["switch"]();
Unread.update(true);
return this.nextElementSibling.innerHTML = "<img src=" + Favicon.unreadSFW + "> <img src=" + Favicon.unreadNSFW + "> <img src=" + Favicon.unreadDead + ">";
},
"export": function() {
var a, data, now, output;
now = Date.now();
data = {
version: Main.version,
date: now,
Conf: Conf,
WatchedThreads: $.get('watched', {})
};
a = $.el('a', {
className: 'warning',
textContent: 'Save me!',
download: "4chan X v" + Main.version + "-" + now + ".json",
href: "data:application/json;base64," + (btoa(unescape(encodeURIComponent(JSON.stringify(data))))),
target: '_blank'
});
if ($.engine !== 'gecko') {
a.click();
return;
}
output = this.parentNode.nextElementSibling;
output.innerHTML = null;
return $.add(output, a);
},
"import": function() {
return this.nextElementSibling.click();
},
onImport: function() {
var file, output, reader;
if (!(file = this.files[0])) {
return;
}
output = this.parentNode.nextElementSibling;
if (!confirm('Your current settings will be entirely overwritten, are you sure?')) {
output.textContent = 'Import aborted.';
return;
}
reader = new FileReader();
reader.onload = function(e) {
var data, err;
try {
data = JSON.parse(e.target.result);
Options.loadSettings(data);
if (confirm('Import successful. Refresh now?')) {
return window.location.reload();
}
} catch (_error) {
err = _error;
return output.textContent = 'Import failed due to an error.';
}
};
return reader.readAsText(file);
},
loadSettings: function(data) {
var key, val, _ref;
_ref = data.Conf;
for (key in _ref) {
val = _ref[key];
$.set(key, val);
}
return $.set('watched', data.WatchedThreads);
}
};
Updater = {
init: function() {
var checkbox, checked, dialog, html, input, name, title, _i, _len, _ref;
html = '<div class=move><span id=count></span> <span id=timer></span></div>';
checkbox = Config.updater.checkbox;
for (name in checkbox) {
title = checkbox[name][1];
checked = Conf[name] ? 'checked' : '';
html += "<div><label title='" + title + "'>" + name + "<input name='" + name + "' type=checkbox " + checked + "></label></div>";
}
checked = Conf['Auto Update'] ? 'checked' : '';
html += " <div><label title='Controls whether *this* thread automatically updates or not'>Auto Update This<input name='Auto Update This' type=checkbox " + checked + "></label></div> <div><label>Interval (s)<input type=number name=Interval class=field min=5></label></div> <div><input value='Update Now' type=button name='Update Now'></div>";
dialog = UI.dialog('updater', 'bottom: 0; right: 0;', html);
this.count = $('#count', dialog);
this.timer = $('#timer', dialog);
this.thread = $.id("t" + g.THREAD_ID);
this.lastModified = '0';
_ref = $$('input', dialog);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
input = _ref[_i];
if (input.type === 'checkbox') {
$.on(input, 'click', $.cb.checked);
}
switch (input.name) {
case 'Scroll BG':
$.on(input, 'click', this.cb.scrollBG);
this.cb.scrollBG.call(input);
break;
case 'Verbose':
$.on(input, 'click', this.cb.verbose);
this.cb.verbose.call(input);
break;
case 'Auto Update This':
$.on(input, 'click', this.cb.autoUpdate);
this.cb.autoUpdate.call(input);
break;
case 'Interval':
input.value = Conf['Interval'];
$.on(input, 'change', this.cb.interval);
this.cb.interval.call(input);
break;
case 'Update Now':
$.on(input, 'click', this.update);
}
}
$.add(d.body, dialog);
$.on(d, 'QRPostSuccessful', this.cb.post);
return $.on(d, 'visibilitychange', this.cb.visibility);
},
/*
http://freesound.org/people/pierrecartoons1979/sounds/90112/
cc-by-nc-3.0
*/
audio: $.el('audio', {
src: 'data:audio/wav;base64,UklGRjQDAABXQVZFZm10IBAAAAABAAEAgD4AAIA+AAABAAgAc21wbDwAAABBAAADAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABkYXRhzAIAAGMms8em0tleMV4zIpLVo8nhfSlcPR102Ki+5JspVEkdVtKzs+K1NEhUIT7DwKrcy0g6WygsrM2k1NpiLl0zIY/WpMrjgCdbPhxw2Kq+5Z4qUkkdU9K1s+K5NkVTITzBwqnczko3WikrqM+l1NxlLF0zIIvXpsnjgydZPhxs2ay95aIrUEkdUdC3suK8N0NUIjq+xKrcz002WioppdGm091pK1w0IIjYp8jkhydXPxxq2K295aUrTkoeTs65suK+OUFUIzi7xqrb0VA0WSoootKm0t5tKlo1H4TYqMfkiydWQBxm16+85actTEseS8y7seHAPD9TIza5yKra01QyWSson9On0d5wKVk2H4DYqcfkjidUQB1j1rG75KsvSkseScu8seDCPz1TJDW2yara1FYxWSwnm9Sn0N9zKVg2H33ZqsXkkihSQR1g1bK65K0wSEsfR8i+seDEQTxUJTOzy6rY1VowWC0mmNWoz993KVc3H3rYq8TklSlRQh1d1LS647AyR0wgRMbAsN/GRDpTJTKwzKrX1l4vVy4lldWpzt97KVY4IXbUr8LZljVPRCxhw7W3z6ZISkw1VK+4sMWvXEhSPk6buay9sm5JVkZNiLWqtrJ+TldNTnquqbCwilZXU1BwpKirrpNgWFhTaZmnpquZbFlbVmWOpaOonHZcXlljhaGhpZ1+YWBdYn2cn6GdhmdhYGN3lp2enIttY2Jjco+bnJuOdGZlZXCImJqakHpoZ2Zug5WYmZJ/bGlobX6RlpeSg3BqaW16jZSVkoZ0bGtteImSk5KIeG5tbnaFkJKRinxxbm91gY2QkIt/c3BwdH6Kj4+LgnZxcXR8iI2OjIR5c3J0e4WLjYuFe3VzdHmCioyLhn52dHR5gIiKioeAeHV1eH+GiYqHgXp2dnh9hIiJh4J8eHd4fIKHiIeDfXl4eHyBhoeHhH96eHmA'
}),
cb: {
post: function() {
if (!Conf['Auto Update This']) {
return;
}
return setTimeout(Updater.update, 500);
},
visibility: function() {
if (d.hidden) {
return;
}
if (Updater.timer.textContent < -Conf['Interval']) {
return Updater.set('timer', -Conf['Interval']);
}
},
interval: function() {
var val;
val = parseInt(this.value, 10);
this.value = val > 5 ? val : 5;
$.cb.value.call(this);
return Updater.set('timer', -Conf['Interval']);
},
verbose: function() {
if (Conf['Verbose']) {
Updater.set('count', '+0');
return Updater.timer.hidden = false;
} else {
Updater.set('count', 'Thread Updater');
Updater.count.className = '';
return Updater.timer.hidden = true;
}
},
autoUpdate: function() {
if (Conf['Auto Update This'] = this.checked) {
return Updater.timeoutID = setTimeout(Updater.timeout, 1000);
} else {
return clearTimeout(Updater.timeoutID);
}
},
scrollBG: function() {
return Updater.scrollBG = this.checked ? function() {
return true;
} : function() {
return !d.hidden;
};
},
buryDead: function() {
Updater.set('timer', '');
Updater.set('count', 404);
Updater.count.className = 'warning';
clearTimeout(Updater.timeoutID);
g.dead = true;
if (Conf['Unread Count']) {
Unread.title = Unread.title.match(/^.+-/)[0] + ' 404';
} else {
d.title = d.title.match(/^.+-/)[0] + ' 404';
}
Unread.update(true);
QR.abort();
return $.event('ThreadUpdate', {
404: true,
threadID: g.THREAD_ID
});
},
load: function() {
switch (this.status) {
case 404:
Updater.cb.buryDead();
break;
case 0:
case 304:
/*
Status Code 304: Not modified
By sending the `If-Modified-Since` header we get a proper status code, and no response.
This saves bandwidth for both the user and the servers and avoid unnecessary computation.
*/
Updater.set('timer', -Conf['Interval']);
if (Conf['Verbose']) {
Updater.set('count', '+0');
Updater.count.className = null;
}
break;
case 200:
Updater.lastModified = this.getResponseHeader('Last-Modified');
var parsed_posts = JSON.parse(this.response).posts;
if ('archived' in parsed_posts[0] && parsed_posts[0].archived === 1) {
Updater.cb.buryDead();
} else {
Updater.cb.update(parsed_posts);
Updater.set('timer', -Conf['Interval']);
}
break;
default:
Updater.set('timer', -Conf['Interval']);
if (Conf['Verbose']) {
Updater.set('count', this.statusText);
Updater.count.className = 'warning';
}
}
return delete Updater.request;
},
update: function(posts) {
var count, id, lastPost, nodes, post, posterCount, scroll, spoilerRange, _i, _len, _ref;
if (spoilerRange = posts[0].custom_spoiler) {
Build.spoilerRange[g.BOARD] = spoilerRange;
}
if (Conf['Thread Stats'] && (posterCount = posts[0].unique_ips)) {
ThreadStats.posterCount(posterCount);
}
lastPost = Updater.thread.lastElementChild;
id = +lastPost.id.slice(2);
nodes = [];
_ref = posts.reverse();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
post = _ref[_i];
if (post.no <= id) {
break;
}
nodes.push(Build.postFromObject(post, g.BOARD));
}
count = nodes.length;
if (Conf['Verbose']) {
Updater.set('count', "+" + count);
Updater.count.className = count ? 'new' : null;
}
if (count && Conf['Beep'] && d.hidden && (Unread.replies.length === 0)) {
Updater.audio.play();
//return;
}
scroll = Conf['Scrolling'] && Updater.scrollBG() && lastPost.getBoundingClientRect().bottom - d.documentElement.clientHeight < 25;
$.add(Updater.thread, nodes.reverse());
if (scroll) {
nodes[0].scrollIntoView();
}
return $.event('ThreadUpdate', {
404: false,
threadID: g.THREAD_ID,
newPosts: nodes.map(function(data) {
return data.id.replace('pc', g.BOARD + '.');
})
});
}
},
set: function(name, text) {
var el, node;
el = Updater[name];
if (node = el.firstChild) {
return node.data = text;
} else {
return el.textContent = text;
}
},
timeout: function() {
var n;
Updater.timeoutID = setTimeout(Updater.timeout, 1000);
n = 1 + Number(Updater.timer.firstChild.data);
if (n === 0) {
return Updater.update();
} else if (n >= Conf['Interval']) {
Updater.set('count', 'Retry');
Updater.count.className = null;
return Updater.update();
} else {
return Updater.set('timer', n);
}
},
update: function() {
var request, url;
Updater.set('timer', 0);
request = Updater.request;
if (request) {
request.onloadend = null;
request.abort();
}
url = "//a.4cdn.org/" + g.BOARD + "/thread/" + g.THREAD_ID + ".json";
return Updater.request = $.ajax(url, {
onloadend: Updater.cb.load
}, {
headers: {
'If-Modified-Since': Updater.lastModified
}
});
}
};
Watcher = {
init: function() {
var favicon, html, input, _i, _len, _ref;
html = '<div class=move>Thread Watcher</div>';
this.dialog = UI.dialog('watcher', 'top: 50px; left: 0px;', html);
$.add(d.body, this.dialog);
_ref = $$('.op input');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
input = _ref[_i];
favicon = $.el('img', {
className: 'favicon'
});
$.on(favicon, 'click', this.cb.toggle);
$.before(input, favicon);
}
if (g.THREAD_ID === $.get('autoWatch', 0)) {
this.watch(g.THREAD_ID);
$["delete"]('autoWatch');
} else {
this.refresh();
}
$.on(d, 'QRPostSuccessful', this.cb.post);
return $.sync('watched', this.refresh);
},
refresh: function(watched) {
var board, div, favicon, id, link, nodes, props, watchedBoard, x, _i, _j, _len, _len1, _ref, _ref1, _ref2;
watched || (watched = $.get('watched', {}));
nodes = [];
for (board in watched) {
_ref = watched[board];
for (id in _ref) {
props = _ref[id];
x = $.el('a', {
textContent: '×',
href: 'javascript:;'
});
$.on(x, 'click', Watcher.cb.x);
link = $.el('a', props);
link.title = link.textContent;
div = $.el('div');
$.add(div, [x, $.tn(' '), link]);
nodes.push(div);
}
}
_ref1 = $$('div:not(.move)', Watcher.dialog);
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
div = _ref1[_i];
$.rm(div);
}
$.add(Watcher.dialog, nodes);
watchedBoard = watched[g.BOARD] || {};
_ref2 = $$('.favicon');
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
favicon = _ref2[_j];
id = favicon.nextSibling.name;
if (id in watchedBoard) {
favicon.src = Favicon["default"];
} else {
favicon.src = Favicon.empty;
}
}
},
cb: {
toggle: function() {
return Watcher.toggle(this.parentNode);
},
x: function() {
var thread;
thread = this.nextElementSibling.pathname.split('/');
return Watcher.unwatch(thread[3], thread[1]);
},
post: function(e) {
var postID, threadID, _ref;
_ref = e.detail, postID = _ref.postID, threadID = _ref.threadID;
if (threadID === '0') {
if (Conf['Auto Watch']) {
return $.set('autoWatch', postID);
}
} else if (Conf['Auto Watch Reply']) {
return Watcher.watch(threadID);
}
}
},
toggle: function(thread) {
var id;
id = $('.favicon + input', thread).name;
return Watcher.watch(id) || Watcher.unwatch(id, g.BOARD);
},
unwatch: function(id, board) {
var watched;
watched = $.get('watched', {});
delete watched[board][id];
$.set('watched', watched);
return Watcher.refresh();
},
watch: function(id) {
var thread, watched, _name;
thread = $.id("t" + id);
if ($('.favicon', thread).src === Favicon["default"]) {
return false;
}
watched = $.get('watched', {});
watched[_name = g.BOARD] || (watched[_name] = {});
watched[g.BOARD][id] = {
href: "/" + g.BOARD + "/thread/" + id,
textContent: Get.title(thread)
};
$.set('watched', watched);
Watcher.refresh();
return true;
}
};
Anonymize = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var name, parent, trip;
if (post.isInlined && !post.isCrosspost) {
return;
}
name = $('.postInfo .name', post.el);
name.textContent = 'Anonymous';
if ((trip = name.nextElementSibling) && trip.className === 'postertrip') {
$.rm(trip);
}
if ((parent = name.parentNode).className === 'useremail' && !/^mailto:sage$/i.test(parent.href)) {
return $.replace(parent, name);
}
}
};
Sauce = {
init: function() {
var link, _i, _len, _ref;
if (g.BOARD === 'f') {
return;
}
this.links = [];
_ref = Conf['sauces'].split('\n');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
link = _ref[_i];
if (link[0] === '#' || link.trim() === '') {
continue;
}
this.links.push(this.createSauceLink(link.trim()));
}
if (!this.links.length) {
return;
}
return Main.callbacks.push(this.node);
},
createSauceLink: function(link) {
var domain, el, href, m;
link = link.replace(/\$4/g, g.BOARD);
domain = (m = link.match(/;text:(.+)$/)) ? m[1] : link.match(/(\w+)\.\w+\//)[1];
href = link.replace(/;text:.+$/, '');
el = $.el('a', {
target: '_blank',
textContent: domain
});
return function(img, isArchived) {
var a;
a = el.cloneNode(true);
a.href = href.replace(/(\$\d)/g, function(parameter) {
switch (parameter) {
case '$1':
return isArchived ? img.firstChild.src : 'http://t.4cdn.org' + img.pathname.replace(/(\d+)\..+$/, '$1s.jpg');
case '$2':
return img.href;
case '$3':
return encodeURIComponent(img.firstChild.dataset.md5);
default:
return parameter;
}
});
return a;
};
},
node: function(post) {
var img, link, nodes, _i, _len, _ref;
img = post.img;
if (post.isInlined && !post.isCrosspost || !img) {
return;
}
img = img.parentNode;
nodes = [];
_ref = Sauce.links;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
link = _ref[_i];
nodes.push($.tn('\u00A0'), link(img, post.isArchived));
}
return $.add(post.fileInfo, nodes);
}
};
RevealSpoilers = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var img, s;
img = post.img;
if (!(img && /^Spoiler/.test(post.fileInfo.firstElementChild.textContent)) || post.isInlined && !post.isCrosspost || post.isArchived) {
return;
}
img.removeAttribute('style');
s = img.style;
s.maxHeight = s.maxWidth = /\bop\b/.test(post["class"]) ? '250px' : '125px';
post.fileInfo.firstElementChild.textContent = post.el.getElementsByClassName('fileText')[0].title;
return img.src = "//t.4cdn.org" + (img.parentNode.pathname.replace(/(\d+).+$/, '$1s.jpg'));
}
};
Time = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var node;
if (post.isInlined && !post.isCrosspost) {
return;
}
node = $('.postInfo > .dateTime', post.el);
Time.date = new Date(node.dataset.utc * 1000);
return node.textContent = Time.funk();
},
funk: function() {
return Conf['time'].replace(/%([A-Za-z])/g, function(s, c) {
if (c in Time.formatters) {
return Time.formatters[c]();
} else {
return s;
}
});
},
day: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
zeroPad: function(n) {
if (n < 10) {
return '0' + n;
} else {
return n;
}
},
formatters: {
a: function() {
return Time.day[Time.date.getDay()].slice(0, 3);
},
A: function() {
return Time.day[Time.date.getDay()];
},
b: function() {
return Time.month[Time.date.getMonth()].slice(0, 3);
},
B: function() {
return Time.month[Time.date.getMonth()];
},
d: function() {
return Time.zeroPad(Time.date.getDate());
},
e: function() {
return Time.date.getDate();
},
H: function() {
return Time.zeroPad(Time.date.getHours());
},
I: function() {
return Time.zeroPad(Time.date.getHours() % 12 || 12);
},
k: function() {
return Time.date.getHours();
},
l: function() {
return Time.date.getHours() % 12 || 12;
},
m: function() {
return Time.zeroPad(Time.date.getMonth() + 1);
},
M: function() {
return Time.zeroPad(Time.date.getMinutes());
},
p: function() {
if (Time.date.getHours() < 12) {
return 'AM';
} else {
return 'PM';
}
},
P: function() {
if (Time.date.getHours() < 12) {
return 'am';
} else {
return 'pm';
}
},
S: function() {
return Time.zeroPad(Time.date.getSeconds());
},
y: function() {
return Time.date.getFullYear() - 2000;
}
}
};
RelativeDates = {
INTERVAL: $.MINUTE,
init: function() {
Main.callbacks.push(this.node);
return $.on(d, 'visibilitychange', this.flush);
},
node: function(post) {
var dateEl, diff, utc;
dateEl = $('.postInfo > .dateTime', post.el);
dateEl.title = dateEl.textContent;
utc = dateEl.dataset.utc * 1000;
diff = Date.now() - utc;
dateEl.textContent = RelativeDates.relative(diff);
RelativeDates.setUpdate(dateEl, utc, diff);
return RelativeDates.flush();
},
relative: function(diff) {
var number, rounded, unit;
unit = (number = diff / $.DAY) > 1 ? 'day' : (number = diff / $.HOUR) > 1 ? 'hour' : (number = diff / $.MINUTE) > 1 ? 'minute' : (number = diff / $.SECOND, 'second');
rounded = Math.round(number);
if (rounded !== 1) {
unit += 's';
}
return "" + rounded + " " + unit + " ago";
},
stale: [],
flush: $.debounce($.SECOND, function() {
var now, update, _i, _len, _ref;
if (d.hidden) {
return;
}
now = Date.now();
_ref = RelativeDates.stale;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
update = _ref[_i];
update(now);
}
RelativeDates.stale = [];
clearTimeout(RelativeDates.timeout);
return RelativeDates.timeout = setTimeout(RelativeDates.flush, RelativeDates.INTERVAL);
}),
setUpdate: function(dateEl, utc, diff) {
var markStale, setOwnTimeout, update;
setOwnTimeout = function(diff) {
var delay;
delay = diff < $.MINUTE ? $.SECOND - (diff + $.SECOND / 2) % $.SECOND : diff < $.HOUR ? $.MINUTE - (diff + $.MINUTE / 2) % $.MINUTE : $.HOUR - (diff + $.HOUR / 2) % $.HOUR;
return setTimeout(markStale, delay);
};
update = function(now) {
if (d.contains(dateEl)) {
diff = now - utc;
dateEl.textContent = RelativeDates.relative(diff);
return setOwnTimeout(diff);
}
};
markStale = function() {
return RelativeDates.stale.push(update);
};
return setOwnTimeout(diff);
}
};
FileInfo = {
init: function() {
if (g.BOARD === 'f') {
return;
}
return Main.callbacks.push(this.node);
},
node: function(post) {
var alt, filename, node, _ref, nameNode;
if (post.isInlined && !post.isCrosspost || !post.fileInfo) {
return;
}
node = post.fileInfo.firstElementChild;
alt = post.img.alt;
filename = (nameNode = $('a', post.fileInfo)) ? nameNode.title || nameNode.textContent : post.fileInfo.title;
FileInfo.data = {
link: post.img.parentNode.href,
spoiler: /^Spoiler/.test(alt),
size: alt.match(/\d+\.?\d*/)[0],
unit: alt.match(/\w+$/)[0],
resolution: post.fileInfo.childNodes[2].textContent.match(/\d+x\d+|PDF/)[0],
fullname: filename,
shortname: Build.shortFilename(filename, post.ID === post.threadID)
};
node.setAttribute('data-filename', filename);
return post.fileInfo.innerHTML = FileInfo.funk();
},
funk: function() {
return Conf['fileInfo'].replace(/%(.)|[^%]+/g, function(s, c) {
if (c in FileInfo.formatters) {
return FileInfo.formatters[c]();
} else {
return Build.escape(s);
}
});
},
convertUnit: function(unitT) {
var i, size, unitF, units;
size = this.data.size;
unitF = this.data.unit;
if (unitF !== unitT) {
units = ['B', 'KB', 'MB'];
i = units.indexOf(unitF) - units.indexOf(unitT);
if (unitT === 'B') {
unitT = 'Bytes';
}
if (i > 0) {
while (i-- > 0) {
size *= 1024;
}
} else if (i < 0) {
while (i++ < 0) {
size /= 1024;
}
}
if (size < 1 && size.toString().length > size.toFixed(2).length) {
size = size.toFixed(2);
}
}
return "" + size + " " + unitT;
},
formatters: {
t: function() {
return FileInfo.data.link.match(/\d+\.\w+$/)[0];
},
T: function() {
return '<a href="' + Build.escape(FileInfo.data.link) + '" target="_blank">' + (this.t()) + '</a>';
},
l: function() {
return '<a href="' + Build.escape(FileInfo.data.link) + '" target="_blank">' + (this.n()) + '</a>';
},
L: function() {
return '<a href="' + Build.escape(FileInfo.data.link) + '" target="_blank">' + (this.N()) + '</a>';
},
n: function() {
if (FileInfo.data.fullname === FileInfo.data.shortname) {
return Build.escape(FileInfo.data.fullname);
} else {
return '<span class="fntrunc">' + Build.escape(FileInfo.data.shortname) + '</span><span class="fnfull">' + Build.escape(FileInfo.data.fullname) + '</span>';
}
},
N: function() {
return Build.escape(FileInfo.data.fullname);
},
p: function() {
if (FileInfo.data.spoiler) {
return 'Spoiler, ';
} else {
return '';
}
},
s: function() {
return "" + FileInfo.data.size + " " + FileInfo.data.unit;
},
B: function() {
return FileInfo.convertUnit('B');
},
K: function() {
return FileInfo.convertUnit('KB');
},
M: function() {
return FileInfo.convertUnit('MB');
},
r: function() {
return FileInfo.data.resolution;
}
}
};
Get = {
post: function(board, threadID, postID, root, cb) {
var post, url;
if (board === g.BOARD && (post = $.id("pc" + postID))) {
$.add(root, Get.cleanPost(post.cloneNode(true)));
return;
}
root.textContent = "Loading post No." + postID + "...";
if (threadID) {
return $.cache("//a.4cdn.org/" + board + "/thread/" + threadID + ".json", function() {
return Get.parsePost(this, board, threadID, postID, root, cb);
});
} else if (url = Redirect.post(board, postID)) {
return $.cache(url, function() {
return Get.parseArchivedPost(this, board, postID, root, cb);
});
}
},
parsePost: function(req, board, threadID, postID, root, cb) {
var post, posts, spoilerRange, status, url, _i, _len;
status = req.status;
if (status !== 200) {
if (url = Redirect.post(board, postID)) {
$.cache(url, function() {
return Get.parseArchivedPost(this, board, postID, root, cb);
});
} else {
$.addClass(root, 'warning');
root.textContent = status === 404 ? "Thread No." + threadID + " 404'd." : "Error " + req.status + ": " + req.statusText + ".";
}
return;
}
posts = JSON.parse(req.response).posts;
if (spoilerRange = posts[0].custom_spoiler) {
Build.spoilerRange[board] = spoilerRange;
}
postID = +postID;
for (_i = 0, _len = posts.length; _i < _len; _i++) {
post = posts[_i];
if (post.no === postID) {
break;
}
if (post.no > postID) {
if (url = Redirect.post(board, postID)) {
$.cache(url, function() {
return Get.parseArchivedPost(this, board, postID, root, cb);
});
} else {
$.addClass(root, 'warning');
root.textContent = "Post No." + postID + " was not found.";
}
return;
}
}
$.replace(root.firstChild, Get.cleanPost(Build.postFromObject(post, board)));
if (cb) {
return cb();
}
},
escape: function(text) {
return (text == null) ? null : Build.escape(text);
},
parseArchivedPost: function(req, board, postID, root, cb) {
var bq, comment, data, o, _ref;
data = JSON.parse(req.response);
if (data.error) {
$.addClass(root, 'warning');
root.textContent = data.error;
return;
}
bq = $.el('blockquote', {
textContent: data.comment
});
bq.innerHTML = bq.innerHTML.replace(/\n|\[\/?b\]|\[\/?spoiler\]|\[\/?code\]|\[\/?moot\]|\[\/?banned\]/g, function(text) {
switch (text) {
case '\n':
return '<br>';
case '[b]':
return '<b>';
case '[/b]':
return '</b>';
case '[spoiler]':
return '<span class=spoiler>';
case '[/spoiler]':
return '</span>';
case '[code]':
return '<pre class=prettyprint>';
case '[/code]':
return '</pre>';
case '[moot]':
return '<div style="padding:5px;margin-left:.5em;border-color:#faa;border:2px dashed rgba(255,0,0,.1);border-radius:2px">';
case '[/moot]':
return '</div>';
case '[banned]':
return '<b style="color: red;">';
case '[/banned]':
return '</b>';
}
});
comment = bq.innerHTML.replace(/(^|>)(>[^<$]*)(<|$)/g, '$1<span class=quote>$2</span>$3');
comment = comment.replace(/((>){2}(>\/[a-z\d]+\/)?\d+)/g, '<span class=deadlink>$1</span>');
o = {
postID: postID,
threadID: Get.escape(data.thread_num),
board: board,
name: Get.escape(data.name),
capcode: (function() {
switch (data.capcode) {
case 'M':
return 'mod';
case 'A':
return 'admin';
case 'D':
return 'developer';
}
})(),
tripcode: Get.escape(data.trip),
uniqueID: Get.escape(data.poster_hash),
email: data.email ? Get.escape(encodeURI(data.email)) : '',
subject: Get.escape(data.title),
flagCode: Get.escape(data.poster_country),
flagName: data.poster_country_name ? Get.escape(data.poster_country_name) : '',
date: Get.escape(data.fourchan_date),
dateUTC: +data.timestamp,
comment: comment
};
if ((_ref = data.media) != null ? _ref.media_filename : void 0) {
o.file = {
name: Get.escape(data.media.media_filename),
timestamp: Get.escape(data.media.media_orig),
url: Get.escape(data.media.media_link || data.media.remote_media_link),
height: Get.escape(data.media.media_h),
width: Get.escape(data.media.media_w),
MD5: Get.escape(data.media.media_hash),
size: Get.escape(data.media.media_size),
turl: Get.escape(data.media.thumb_link || ("//t.4cdn.org/" + board + "/" + data.media.preview_orig)),
theight: Get.escape(data.media.preview_h),
twidth: Get.escape(data.media.preview_w),
isSpoiler: data.media.spoiler === '1'
};
}
$.replace(root.firstChild, Get.cleanPost(Build.post(o, true)));
if (cb) {
return cb();
}
},
cleanPost: function(root) {
var child, el, els, inline, inlined, now, post, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2;
post = $('.post', root);
_ref = Array.prototype.slice.call(root.childNodes);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
if (child !== post) {
$.rm(child);
}
}
_ref1 = $$('.inline', post);
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
inline = _ref1[_j];
$.rm(inline);
}
_ref2 = $$('.inlined', post);
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
inlined = _ref2[_k];
$.rmClass(inlined, 'inlined');
}
now = Date.now();
els = $$('[id]', root);
els.push(root);
for (_l = 0, _len3 = els.length; _l < _len3; _l++) {
el = els[_l];
el.id = "" + now + "_" + el.id;
}
$.rmClass(root, 'forwarded');
$.rmClass(root, 'qphl');
$.rmClass(post, 'highlight');
$.rmClass(post, 'qphl');
root.hidden = post.hidden = false;
return root;
},
title: function(thread) {
var el, op, span;
op = $('.op', thread);
el = $('.postInfo .subject', op);
if (!el.textContent) {
el = $('blockquote', op);
if (!el.textContent) {
el = $('.nameBlock', op);
}
}
span = $.el('span', {
innerHTML: el.innerHTML.replace(/<br>/g, ' ')
});
return "/" + g.BOARD + "/ - " + (span.textContent.trim());
}
};
Build = {
escape: function(text) {
return (text + '').replace(/[&"'<>]/g, function(c) {
return {'&': '&', "'": ''', '"': '"', '<': '<', '>': '>'}[c];
});
},
spoilerRange: {},
shortFilename: function(filename, isOP) {
var threshold;
threshold = isOP ? 40 : 30;
if (filename.length - 4 > threshold) {
return "" + filename.slice(0, threshold - 5) + "(...)." + filename.slice(-3);
} else {
return filename;
}
},
postFromObject: function(data, board) {
var o;
o = {
postID: data.no,
threadID: data.resto || data.no,
board: board,
name: data.name,
capcode: data.capcode,
tripcode: data.trip,
uniqueID: data.id,
email: data.email ? encodeURI(data.email.replace(/"/g, '"')) : '',
subject: data.sub,
flagCode: data.country,
flagName: data.country_name,
date: data.now,
dateUTC: data.time,
comment: data.com,
isSticky: !!data.sticky,
isClosed: !!data.closed
};
if (data.ext || data.filedeleted) {
o.file = {
name: data.filename + data.ext,
timestamp: "" + data.tim + data.ext,
url: board === 'f' ? "//i.4cdn.org/" + board + "/" + (encodeURIComponent(data.filename)) + data.ext : "//i.4cdn.org/" + board + "/" + data.tim + data.ext,
height: data.h,
width: data.w,
MD5: data.md5,
size: data.fsize,
turl: "//t.4cdn.org/" + board + "/" + data.tim + "s.jpg",
theight: data.tn_h,
twidth: data.tn_w,
isSpoiler: !!data.spoiler,
isDeleted: !!data.filedeleted
};
}
return Build.post(o);
},
post: function(o, isArchived) {
/*
This function contains code from 4chan-JS (https://github.com/4chan/4chan-JS).
@license: https://github.com/4chan/4chan-JS/blob/master/LICENSE
*/
var a, board, capcode, capcodeClass, capcodeStart, closed, comment, container, date, dateUTC, email, emailEnd, emailStart, ext, file, fileDims, fileHTML, fileInfo, fileSize, fileThumb, filename, flag, flagCode, flagName, href, imgSrc, isClosed, isOP, isSticky, name, postID, quote, shortFilename, spoilerRange, staticPath, sticky, subject, threadID, tripcode, uniqueID, userID, _i, _len, _ref;
postID = o.postID, threadID = o.threadID, board = o.board, name = o.name, capcode = o.capcode, tripcode = o.tripcode, uniqueID = o.uniqueID, email = o.email, subject = o.subject, flagCode = o.flagCode, flagName = o.flagName, date = o.date, dateUTC = o.dateUTC, isSticky = o.isSticky, isClosed = o.isClosed, comment = o.comment, file = o.file;
isOP = postID === threadID;
staticPath = '//s.4cdn.org';
if (email) {
emailStart = '<a href="mailto:' + email + '" class="useremail">';
emailEnd = '</a>';
} else {
emailStart = '';
emailEnd = '';
}
subject = '<span class="subject">' + (subject || '') + '</span>';
userID = !capcode && uniqueID ? ' <span class="posteruid id_' + uniqueID + '">(ID: <span class="hand" title="Highlight posts by this ID">' + uniqueID + '</span>)</span> ' : '';
switch (capcode) {
case 'admin':
case 'admin_highlight':
capcodeClass = ' capcodeAdmin';
capcodeStart = ' <strong class="capcode hand id_admin" title="Highlight posts by the Administrator">## Admin</strong>';
capcode = ' <img src="' + staticPath + '/image/adminicon.gif" alt="This user is the 4chan Administrator." title="This user is the 4chan Administrator." class="identityIcon">';
break;
case 'mod':
capcodeClass = ' capcodeMod';
capcodeStart = ' <strong class="capcode hand id_mod" title="Highlight posts by Moderators">## Mod</strong>';
capcode = ' <img src="' + staticPath + '/image/modicon.gif" alt="This user is a 4chan Moderator." title="This user is a 4chan Moderator." class="identityIcon">';
break;
case 'developer':
capcodeClass = ' capcodeDeveloper';
capcodeStart = ' <strong class="capcode hand id_developer" title="Highlight posts by Developers">## Developer</strong>';
capcode = ' <img src="' + staticPath + '/image/developericon.gif" alt="This user is a 4chan Developer." title="This user is a 4chan Developer." class="identityIcon">';
break;
default:
capcodeClass = '';
capcodeStart = '';
capcode = '';
}
flag = flagCode ? ' <img src="' + staticPath + '/image/country/' + (board === 'pol' ? 'troll/' : '') + flagCode.toLowerCase() + '.gif" alt="' + flagCode + '" title="' + flagName + '" class="flag">' : '';
if (file != null ? file.isDeleted : void 0) {
fileHTML = isOP ? '<div class="file" id="f' + postID + '"><div class="fileInfo"></div><span class="fileThumb"><img src="' + staticPath + '/image/filedeleted.gif" alt="File deleted." class="fileDeleted retina"></span></div>' : '<div id="f' + postID + '" class="file"><span class="fileThumb"><img src="' + staticPath + '/image/filedeleted-res.gif" alt="File deleted." class="fileDeletedRes retina"></span></div>';
} else if (file) {
ext = file.name.slice(-3);
if (!file.twidth && !file.theight && ext === 'gif') {
file.twidth = file.width;
file.theight = file.height;
}
fileSize = $.bytesToString(file.size);
fileThumb = file.turl;
if (file.isSpoiler) {
fileSize = 'Spoiler Image, ' + fileSize;
if (!isArchived) {
fileThumb = '//s.4cdn.org/image/spoiler';
if (spoilerRange = Build.spoilerRange[board]) {
fileThumb += '-' + board + Math.floor(1 + spoilerRange * Math.random());
}
fileThumb += '.png';
file.twidth = file.theight = 100;
}
}
imgSrc = board === 'f' ? '' : '<a class="fileThumb' + (file.isSpoiler ? ' imgspoiler' : '') + '" href="' + file.url + '" target="_blank"><img src="' + fileThumb + '" alt="' + fileSize + '" data-md5="' + file.MD5 + '" style="width:' + file.twidth + 'px;height:' + file.theight + 'px"></a>';
filename = file.name.replace(/&(amp|#039|quot|lt|gt);/g, function (c) {
return {'&': '&', ''': "'", '"': '"', '<': '<', '>': '>'}[c];
}).replace(/%22/g, '"');
shortFilename = Build.escape(Build.shortFilename(filename));
filename = Build.escape(filename);
fileDims = ext === 'pdf' ? 'PDF' : '' + file.width + 'x' + file.height;
fileInfo = '<div class="fileText" id="fT' + postID + '"' + (file.isSpoiler ? ' title="' + filename + '"' : '') + '>File: <a' + ((filename !== shortFilename && !file.isSpoiler) ? ' title="' + filename + '"' : '') + ' href="' + file.url + '" target="_blank">' + (file.isSpoiler ? 'Spoiler Image' : shortFilename) + '</a>-(' + fileSize + ', ' + fileDims + ')</div>';
fileHTML = '<div class="file" id="f' + postID + '">' + fileInfo + imgSrc + '</div>';
} else {
fileHTML = '';
}
tripcode = tripcode ? ' <span class="postertrip">' + tripcode + '</span>' : '';
sticky = isSticky ? ' <img src="//s.4cdn.org/image/sticky.gif" alt="Sticky" title="Sticky" style="height:16px;width:16px">' : '';
closed = isClosed ? ' <img src="//s.4cdn.org/image/closed.gif" alt="Closed" title="Closed" style="height:16px;width:16px">' : '';
container = $.el('div', {
id: 'pc' + postID,
className: 'postContainer ' + (isOP ? 'op' : 'reply') + 'Container',
innerHTML: (isOP ? '' : '<div class="sideArrows" id="sa' + postID + '">>></div>') + '<div id="p' + postID + '" class="post ' + (isOP ? 'op' : 'reply') + (capcode === 'admin_highlight' ? ' highlightPost' : '') + '"><div class="postInfoM mobile" id="pim' + postID + '"><span class="nameBlock' + capcodeClass + '"><span class="name">' + (name || '') + '</span>' + tripcode + capcodeStart + capcode + userID + flag + sticky + closed + '<br>' + subject + '</span><span class="dateTime postNum" data-utc="' + dateUTC + '">' + date + '<br><em><a href="/' + board + '/thread/' + threadID + '#p' + postID + '">No.</a><a href="' + (g.REPLY && g.THREAD_ID === threadID ? 'javascript:quote(' + postID + ')' : '/' + board + '/thread/' + threadID + '#q' + postID) + '">' + postID + '</a></em></span></div>' + (isOP ? fileHTML : '') + '<div class="postInfo desktop" id="pi' + postID + '"><input type="checkbox" name="' + postID + '" value="delete"> ' + subject + ' <span class="nameBlock' + capcodeClass + '">' + emailStart + '<span class="name">' + (name || '') + '</span>' + tripcode + capcodeStart + emailEnd + capcode + userID + flag + sticky + closed + ' </span> <span class="dateTime" data-utc="' + dateUTC + '">' + date + '</span> <span class="postNum desktop"><a href="/' + board + '/thread/' + threadID + '#p' + postID + '" title="Link to this post">No.</a><a href="' + (g.REPLY && +g.THREAD_ID === threadID ? 'javascript:quote(' + postID + ')' : '/' + board + '/thread/' + threadID + '#q' + postID) + '" title="Reply to this post">' + postID + '</a></span></div>' + (isOP ? '' : fileHTML) + '<blockquote class="postMessage" id="m' + postID + '">' + (comment || '') + '</blockquote> </div>'
});
_ref = $$('.quotelink', container);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
href = quote.getAttribute('href');
if (href[0] === '/') {
continue;
}
quote.href = '/' + board + '/thread/' + threadID + href;
}
return container;
}
};
TitlePost = {
init: function() {
if(Conf['Post in Title']) {
return d.title = Get.title();
}
var boardTitle;
return d.title = ((boardTitle = $('.boardTitle', d)) && boardTitle.textContent) || ((boardTitle = $('#boardNavDesktop .current', d)) && "/" + g.BOARD + "/ - " + boardTitle.title) || ("/" + g.BOARD + "/");
}
};
QuoteBacklink = {
init: function() {
return Main.callbacks.push(this.node);
},
funk: function(id) {
return Conf['backlink'].replace(/%id/g, id);
},
node: function(post) {
var a, container, el, link, qid, quote, quotes, _i, _len, _ref;
if (post.isInlined) {
return;
}
quotes = {};
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (quote.parentNode.parentNode.className === 'capcodeReplies') {
break;
}
if (quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname) && (qid = quote.hash.slice(2))) {
quotes[qid] = true;
}
}
a = $.el('a', {
href: "/" + g.BOARD + "/thread/" + post.threadID + "#p" + post.ID,
className: post.el.hidden ? 'filtered backlink' : 'backlink',
textContent: QuoteBacklink.funk(post.ID)
});
for (qid in quotes) {
if (!(el = $.id("pi" + qid)) || !Conf['OP Backlinks'] && /\bop\b/.test(el.parentNode.className)) {
continue;
}
link = a.cloneNode(true);
if (Conf['Quote Preview']) {
$.on(link, 'mouseover', QuotePreview.mouseover);
}
if (Conf['Quote Inline']) {
$.on(link, 'click', QuoteInline.toggle);
}
if (!(container = $.id("blc" + qid))) {
container = $.el('span', {
className: 'container',
id: "blc" + qid
});
$.add(el, container);
}
$.add(container, [$.tn(' '), link]);
}
}
};
QuoteInline = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var quote, _i, _j, _len, _len1, _ref, _ref1;
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (!(quote.hash && quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname) || /\bdeadlink\b/.test(quote.className))) {
continue;
}
$.on(quote, 'click', QuoteInline.toggle);
}
_ref1 = post.backlinks;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
quote = _ref1[_j];
$.on(quote, 'click', QuoteInline.toggle);
}
},
toggle: function(e) {
var id;
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey || e.button !== 0) {
return;
}
e.preventDefault();
id = this.dataset.id || this.hash.slice(2);
if (/\binlined\b/.test(this.className)) {
QuoteInline.rm(this, id);
} else {
if ($.x("ancestor::div[contains(@id,'p" + id + "')]", this)) {
return;
}
QuoteInline.add(this, id);
}
return this.classList.toggle('inlined');
},
add: function(q, id) {
var board, el, i, inline, isBacklink, path, postID, root, threadID;
if (q.host === 'boards.4chan.org') {
path = q.pathname.split('/');
board = path[1];
threadID = path[3];
postID = id;
} else {
board = q.dataset.board;
threadID = 0;
postID = q.dataset.id;
}
el = board === g.BOARD ? $.id("p" + postID) : false;
inline = $.el('div', {
id: "i" + postID,
className: el ? 'inline' : 'inline crosspost'
});
root = (isBacklink = /\bbacklink\b/.test(q.className)) ? q.parentNode : $.x('ancestor-or-self::*[parent::blockquote][1]', q);
$.after(root, inline);
Get.post(board, threadID, postID, inline);
if (!el) {
return;
}
if (isBacklink && Conf['Forward Hiding']) {
$.addClass(el.parentNode, 'forwarded');
++el.dataset.forwarded || (el.dataset.forwarded = 1);
}
if ((i = Unread.replies.indexOf(el)) !== -1) {
Unread.replies.splice(i, 1);
return Unread.update(true);
}
},
rm: function(q, id) {
var div, inlined, _i, _len, _ref;
div = $.x("following::div[@id='i" + id + "']", q);
$.rm(div);
if (!Conf['Forward Hiding']) {
return;
}
_ref = $$('.backlink.inlined', div);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
inlined = _ref[_i];
div = $.id(inlined.hash.slice(1));
if (!--div.dataset.forwarded) {
$.rmClass(div.parentNode, 'forwarded');
}
}
if (/\bbacklink\b/.test(q.className)) {
div = $.id("p" + id);
if (!--div.dataset.forwarded) {
return $.rmClass(div.parentNode, 'forwarded');
}
}
}
};
QuotePreview = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var quote, _i, _j, _len, _len1, _ref, _ref1;
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (!(quote.hash && quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname) || /\bdeadlink\b/.test(quote.className))) {
continue;
}
$.on(quote, 'mouseover', QuotePreview.mouseover);
}
_ref1 = post.backlinks;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
quote = _ref1[_j];
$.on(quote, 'mouseover', QuotePreview.mouseover);
}
},
mouseover: function(e) {
var board, el, path, postID, qp, quote, quoterID, threadID, _i, _len, _ref;
if (/\binlined\b/.test(this.className)) {
return;
}
if (qp = $.id('qp')) {
if (qp === UI.el) {
delete UI.el;
}
$.rm(qp);
}
if (UI.el) {
return;
}
if (this.host === 'boards.4chan.org') {
path = this.pathname.split('/');
board = path[1];
threadID = path[3];
postID = this.hash.slice(2);
} else {
board = this.dataset.board;
threadID = 0;
postID = this.dataset.id;
}
qp = UI.el = $.el('div', {
id: 'qp',
className: 'reply dialog'
});
UI.hover(e);
$.add(d.body, qp);
if (board === g.BOARD) {
el = $.id("p" + postID);
}
Get.post(board, threadID, postID, qp, function() {
var bq, img, post;
bq = $('blockquote', qp);
Main.prettify(bq);
post = {
el: qp,
blockquote: bq,
isArchived: /\barchivedPost\b/.test(qp.className)
};
if (img = $('img[data-md5]', qp)) {
post.fileInfo = img.parentNode.previousElementSibling;
post.img = img;
}
if (Conf['Reveal Spoilers']) {
RevealSpoilers.node(post);
}
if (Conf['Image Auto-Gif']) {
AutoGif.node(post);
}
if (Conf['Replace PNG']) {
ReplacePng.node(post);
}
if (Conf['Replace JPG']) {
ReplaceJpg.node(post);
}
if (Conf['Time Formatting']) {
Time.node(post);
}
if (Conf['File Info Formatting']) {
FileInfo.node(post);
}
if (Conf['Resurrect Quotes']) {
Quotify.node(post);
}
if (Conf['Anonymize']) {
return Anonymize.node(post);
}
});
$.on(this, 'mousemove', UI.hover);
$.on(this, 'mouseout click', QuotePreview.mouseout);
if (!el) {
return;
}
if (Conf['Quote Highlighting']) {
if (/\bop\b/.test(el.className)) {
$.addClass(el.parentNode, 'qphl');
} else {
$.addClass(el, 'qphl');
}
}
quoterID = $.x('ancestor::*[@id][1]', this).id.match(/\d+$/)[0];
_ref = $$('.quotelink, .backlink', qp);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (quote.hash.slice(2) === quoterID) {
$.addClass(quote, 'forwardlink');
}
}
},
mouseout: function(e) {
var el;
UI.hoverend();
if (el = $.id(this.hash.slice(1))) {
$.rmClass(el, 'qphl');
$.rmClass(el.parentNode, 'qphl');
}
$.off(this, 'mousemove', UI.hover);
return $.off(this, 'mouseout click', QuotePreview.mouseout);
}
};
/* Add (You) to posts function */
QuoteYou = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var quote, _i, _len, _ref;
if (post.isInlined && !post.isCrosspost) {
return;
}
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
yourPostsFromStorage = JSON.parse(sessionStorage.getItem('yourPosts'));
if (yourPostsFromStorage) {
var yourPostsFromStorageLength = yourPostsFromStorage.length;
for (var tempI = 0; tempI < yourPostsFromStorageLength; tempI++) {
if (quote.hash.slice(2) === yourPostsFromStorage[tempI]) {
$.add(quote, $.tn('\u00A0(You)'));
}
}
}
}
}
};
QuoteOP = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var quote, _i, _len, _ref;
if (post.isInlined && !post.isCrosspost) {
return;
}
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (quote.hash.slice(2) === post.threadID) {
$.add(quote, $.tn('\u00A0(OP)'));
}
}
}
};
QuoteCT = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var path, quote, _i, _len, _ref;
if (post.isInlined && !post.isCrosspost) {
return;
}
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (!(quote.hash && quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname))) {
continue;
}
path = quote.pathname.split('/');
if (path[1] === g.BOARD && path[3] !== post.threadID) {
$.add(quote, $.tn('\u00A0(Cross-thread)'));
}
}
}
};
Quotify = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var a, board, deadlink, id, m, postBoard, quote, _i, _len, _ref, _ref1;
if (post.isInlined && !post.isCrosspost) {
return;
}
_ref = $$('.deadlink', post.blockquote);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
deadlink = _ref[_i];
if (deadlink.parentNode.className === 'prettyprint') {
$.replace(deadlink, Array.prototype.slice.call(deadlink.childNodes));
continue;
}
quote = deadlink.textContent;
a = $.el('a', {
textContent: "" + quote + "\u00A0(Dead)"
});
if (!(id = (_ref1 = quote.match(/\d+$/)) != null ? _ref1[0] : void 0)) {
continue;
}
if (m = quote.match(/^>>>\/([a-z\d]+)/)) {
board = m[1];
} else if (postBoard) {
board = postBoard;
} else {
board = postBoard = $('a[title="Link to this post"]', post.el).pathname.split('/')[1];
}
if (board === g.BOARD && $.id("p" + id)) {
a.href = "#p" + id;
a.className = 'quotelink';
} else {
a.href = Redirect.to({
board: board,
threadID: 0,
postID: id
});
a.className = 'deadlink';
a.target = '_blank';
if (Redirect.post(board, id)) {
$.addClass(a, 'quotelink');
a.setAttribute('data-board', board);
a.setAttribute('data-id', id);
}
}
$.replace(deadlink, a);
}
}
};
DeleteLink = {
init: function() {
var aImage, aPost, children, div;
div = $.el('div', {
className: 'delete_link',
textContent: 'Delete'
});
aPost = $.el('a', {
className: 'delete_post',
href: 'javascript:;'
});
aImage = $.el('a', {
className: 'delete_image',
href: 'javascript:;'
});
children = [];
children.push({
el: aPost,
open: function() {
aPost.textContent = 'Post';
$.on(aPost, 'click', DeleteLink["delete"]);
return true;
}
});
children.push({
el: aImage,
open: function(post) {
if (!post.img) {
return false;
}
aImage.textContent = 'Image';
$.on(aImage, 'click', DeleteLink["delete"]);
return true;
}
});
Menu.addEntry({
el: div,
open: function(post) {
var node, seconds;
if (post.isArchived) {
return false;
}
node = div.firstChild;
if (seconds = DeleteLink.cooldown[post.ID]) {
node.textContent = "Delete (" + seconds + ")";
DeleteLink.cooldown.el = node;
} else {
node.textContent = 'Delete';
delete DeleteLink.cooldown.el;
}
return true;
},
children: children
});
return $.on(d, 'QRPostSuccessful', this.cooldown.start);
},
"delete": function() {
var board, form, id, m, menu, pwd, self;
menu = $.id('menu');
id = menu.dataset.id;
if (DeleteLink.cooldown[id]) {
return;
}
$.off(this, 'click', DeleteLink["delete"]);
this.textContent = 'Deleting...';
pwd = (m = d.cookie.match(/4chan_pass=([^;]+)/)) ? decodeURIComponent(m[1]) : $.id('delPassword').value;
board = $('a[title="Link to this post"]', $.id(menu.dataset.rootid)).pathname.split('/')[1];
self = this;
form = {
mode: 'usrdel',
onlyimgdel: /\bdelete_image\b/.test(this.className),
pwd: pwd
};
form[id] = 'delete';
return $.ajax($.id('delform').action.replace("/" + g.BOARD + "/", "/" + board + "/"), {
onload: function() {
return DeleteLink.load(self, this.response);
},
onerror: function() {
return DeleteLink.error(self);
}
}, {
form: $.formData(form)
});
},
load: function(self, html) {
var doc, msg, s;
doc = d.implementation.createHTMLDocument('');
doc.documentElement.innerHTML = html;
if (doc.title === '4chan - Banned') {
s = 'Banned!';
} else if (msg = doc.getElementById('errmsg')) {
s = msg.textContent;
$.on(self, 'click', DeleteLink["delete"]);
} else {
s = 'Deleted';
}
return self.textContent = s;
},
error: function(self) {
self.textContent = 'Connection error, please retry.';
return $.on(self, 'click', DeleteLink["delete"]);
},
cooldown: {
start: function(e) {
var seconds;
seconds = 60;
return DeleteLink.cooldown.count(e.detail.postID, seconds, seconds);
},
count: function(postID, seconds, length) {
var el;
if (!((0 <= seconds && seconds <= length))) {
return;
}
setTimeout(DeleteLink.cooldown.count, 1000, postID, seconds - 1, length);
el = DeleteLink.cooldown.el;
if (seconds === 0) {
if (el != null) {
el.textContent = 'Delete';
}
delete DeleteLink.cooldown[postID];
delete DeleteLink.cooldown.el;
return;
}
if (el != null) {
el.textContent = "Delete (" + seconds + ")";
}
return DeleteLink.cooldown[postID] = seconds;
}
}
};
ReportLink = {
init: function() {
var a;
a = $.el('a', {
className: 'report_link',
href: 'javascript:;',
textContent: 'Report this post'
});
$.on(a, 'click', this.report);
return Menu.addEntry({
el: a,
open: function(post) {
return post.isArchived === false;
}
});
},
report: function() {
var a, id, set, url;
a = $('a[title="Link to this post"]', $.id(this.parentNode.dataset.rootid));
url = "//sys.4chan.org/" + (a.pathname.split('/')[1]) + "/imgboard.php?mode=report&no=" + this.parentNode.dataset.id;
id = Date.now();
set = "toolbar=0,scrollbars=0,location=0,status=1,menubar=0,resizable=1,width=685,height=200";
return window.open(url, id, set);
}
};
DownloadLink = {
init: function() {
var a;
if ($.el('a').download === void 0) {
return;
}
a = $.el('a', {
className: 'download_link',
textContent: 'Download file'
});
if($.engine === "gecko") {
$.on(a, 'click', function(e) {
if (this.protocol === 'blob:') {
return true;
}
e.preventDefault();
return DownloadLink.firefoxDL(this.href, (function(_this) {
return function(blob) {
if (blob) {
_this.href = URL.createObjectURL(blob);
return _this.click();
}
};
})(this));
});
}
return Menu.addEntry({
el: a,
open: function(post) {
var fileText;
if (!post.img) {
return false;
}
a.href = post.img.parentNode.href;
fname = post.fileInfo.firstElementChild.childNodes[1] || post.fileInfo.firstElementChild.childNodes[0];
a.download = Conf['File Info Formatting'] ? fname.textContent : post.fileInfo.firstElementChild.title;
return true;
}
});
},
firefoxDL: (function() {
var makeBlob;
makeBlob = function(urlBlob, contentType, contentDisposition, url) {
var blob, match, mime, name, _ref, _ref1, _ref2;
name = (_ref = url.match(/([^\/]+)\/*$/)) != null ? _ref[1] : void 0;
mime = (contentType != null ? contentType.match(/[^;]*/)[0] : void 0) || 'application/octet-stream';
match = (contentDisposition != null ? (_ref1 = contentDisposition.match(/\bfilename\s*=\s*"((\\"|[^"])+)"/i)) != null ? _ref1[1] : void 0 : void 0) || (contentType != null ? (_ref2 = contentType.match(/\bname\s*=\s*"((\\"|[^"])+)"/i)) != null ? _ref2[1] : void 0 : void 0);
if (match) {
name = match.replace(/\\"/g, '"');
}
blob = new Blob([urlBlob], {
type: mime
});
blob.name = name;
return blob;
};
return function(url, cb) {
return GM_xmlhttpRequest({
method: "GET",
url: url,
overrideMimeType: "text/plain; charset=x-user-defined",
onload: function(xhr) {
var contentDisposition, contentType, data, i, r, _ref, _ref1;
r = xhr.responseText;
data = new Uint8Array(r.length);
i = 0;
while (i < r.length) {
data[i] = r.charCodeAt(i);
i++;
}
contentType = (_ref = xhr.responseHeaders.match(/Content-Type:\s*(.*)/i)) != null ? _ref[1] : void 0;
contentDisposition = (_ref1 = xhr.responseHeaders.match(/Content-Disposition:\s*(.*)/i)) != null ? _ref1[1] : void 0;
return cb(makeBlob(data, contentType, contentDisposition, url));
},
onerror: function() {
return cb(null);
}
});
};
})()
};
ArchiveLink = {
init: function() {
var div, entry, type, _i, _len, _ref;
div = $.el('div', {
textContent: 'Archive'
});
entry = {
el: div,
open: function(post) {
var path;
path = $('a[title="Link to this post"]', post.el).pathname.split('/');
if ((Redirect.to({
board: path[1],
threadID: path[3],
postID: post.ID
})) === ("//boards.4chan.org/" + path[1] + "/")) {
return false;
}
post.info = [path[1], path[3]];
return true;
},
children: []
};
_ref = [['Post', 'apost'], ['Name', 'name'], ['Tripcode', 'tripcode'], ['Subject', 'subject'], ['Filename', 'filename'], ['Image MD5', 'md5']];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
type = _ref[_i];
entry.children.push(this.createSubEntry(type[0], type[1]));
}
return Menu.addEntry(entry);
},
createSubEntry: function(text, type) {
var el, open;
el = $.el('a', {
textContent: text,
target: '_blank'
});
open = function(post) {
var value;
if (type === 'apost') {
el.href = Redirect.to({
board: post.info[0],
threadID: post.info[1],
postID: post.ID
});
return true;
}
value = Filter[type](post);
if (!value) {
return false;
}
return el.href = Redirect.to({
board: post.info[0],
type: type,
value: value,
isSearch: true
});
};
return {
el: el,
open: open
};
}
};
ThreadStats = {
init: function() {
var dialog;
dialog = UI.dialog('stats', 'bottom: 0; left: 0;', '<div class=move><span id=postcount>0</span> / <span id=imagecount>0</span><span id=postercount></span><span id=currentpage></span></div>');
dialog.className = 'dialog';
$.add(d.body, dialog);
this.posts = this.images = 0;
this.imgLimit = (function() {
switch (g.BOARD) {
case 'a':
case 'b':
case 'v':
case 'co':
case 'mlp':
return 251;
case 'jp':
return 301;
case 'vg':
return 376;
default:
return 151;
}
})();
this.pageGradients = {
10 : 'FF0000',
9 : 'E50019',
8 : 'CC0033',
7 : 'B2004C',
6 : '990066',
5 : '7F007F',
4 : '650099',
3 : '4C00B2',
2 : '3300CC',
1 : '1900E5'
};
this.pageposGradients = {
15 : 'FF0011',
14 : 'EE0022',
13 : 'DD0033',
12 : 'CC0044',
11 : 'BB0055',
10 : 'AA0066',
9 : '990077',
8 : '880088',
7 : '770099',
6 : '6600AA',
5 : '5500BB',
4 : '4400CC',
3 : '3300DD',
2 : '2200EE',
1 : '1100FF'
};
if (Conf['Current Page']) {
this.pageInterval = setInterval(ThreadStats.fetchPages, 2 * $.MINUTE);
setTimeout(ThreadStats.fetchPages, 2 * $.SECOND); /* Interval starts with the timeout, so execute it this way the first time */
}
return Main.callbacks.push(this.node);
},
node: function(post) {
var imgcount;
if (post.isInlined) {
return;
}
$.id('postcount').textContent = ++ThreadStats.posts;
if (!post.img) {
return;
}
imgcount = $.id('imagecount');
imgcount.textContent = ++ThreadStats.images;
if (ThreadStats.images > ThreadStats.imgLimit) {
return $.addClass(imgcount, 'warning');
}
},
posterCount: function(poster_count) {
$.id('postercount').textContent = ' / ' + poster_count;
},
fetchPages: function() {
var request, url;
request = ThreadStats.request;
if (request) {
request.onloadend = null;
request.abort();
}
url = "//a.4cdn.org/" + g.BOARD + "/threads.json";
return ThreadStats.request = $.ajax(url, {
onloadend: ThreadStats.updatePage
});
},
updatePage: function() {
if (!(Conf['Current Page'] && this.status === 200)) {
return delete ThreadStats.request;
}
var newcontent, page, page_color, pagepos, pagepos_color, thread, _i, _j, _len, _len1, _ref1;
var parsed_threads = JSON.parse(this.response);
for (_i = 0, _len = parsed_threads.length; _i < _len; _i++) {
page = parsed_threads[_i];
_ref1 = page.threads;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
thread = _ref1[_j];
if (!(thread.no == g.THREAD_ID)) {
continue; /* == because g.THREAD_ID is a string */
}
page_color = page.page in ThreadStats.pageGradients ? ThreadStats.pageGradients[page.page] : '000000';
newcontent = ' / ' + '<span style="color:#' + page_color + ';">' + parseInt(page.page) + '</span>'; /* parseInt just to escape */
if (Conf['Current Page Position']) {
pagepos = _j + 1;
pagepos_color = pagepos in ThreadStats.pageposGradients ? ThreadStats.pageposGradients[pagepos] : '000000';
newcontent += ' (' + '<span style="color:#' + pagepos_color + ';">' + pagepos + '</span>' + '∕' + _ref1.length + ')';
}
$.id('currentpage').innerHTML = newcontent;
return delete ThreadStats.request;
}
}
/* If we get here the thread was not found in the catalog, stop updating */
clearInterval(ThreadStats.pageInterval);
$.id('currentpage').textContent = ' / X';
delete ThreadStats.request;
}
};
Unread = {
init: function() {
this.title = d.title;
$.on(d, 'QRPostSuccessful', this.post);
this.update();
$.on(window, 'scroll', Unread.scroll);
return Main.callbacks.push(this.node);
},
replies: [],
foresee: [],
post: function(e) {
return Unread.foresee.push(e.detail.postID);
},
node: function(post) {
var count, el, index;
if ((index = Unread.foresee.indexOf(post.ID)) !== -1) {
Unread.foresee.splice(index, 1);
return;
}
el = post.el;
if (el.hidden || /\bop\b/.test(post["class"]) || post.isInlined) {
return;
}
count = Unread.replies.push(el);
return Unread.update(count === 1);
},
scroll: function() {
var bottom, height, i, reply, _i, _len, _ref;
height = d.documentElement.clientHeight;
_ref = Unread.replies;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
reply = _ref[i];
bottom = reply.getBoundingClientRect().bottom;
if (bottom > height) {
break;
}
}
if (i === 0) {
return;
}
Unread.replies = Unread.replies.slice(i);
return Unread.update(Unread.replies.length === 0);
},
setTitle: function(count) {
if (this.scheduled) {
clearTimeout(this.scheduled);
delete Unread.scheduled;
this.setTitle(count);
return;
}
return this.scheduled = setTimeout((function() {
return d.title = "(" + count + ") " + Unread.title;
}), 5);
},
update: function(updateFavicon) {
var count;
if (!g.REPLY) {
return;
}
count = this.replies.length;
if (Conf['Unread Count']) {
this.setTitle(count);
}
if (!(Conf['Unread Favicon'] && updateFavicon)) {
return;
}
if ($.engine === 'presto') {
$.rm(Favicon.el);
}
Favicon.el.href = g.dead ? count ? Favicon.unreadDead : Favicon.dead : count ? Favicon.unread : Favicon["default"];
if (g.dead) {
$.addClass(Favicon.el, 'dead');
} else {
$.rmClass(Favicon.el, 'dead');
}
if (count) {
$.addClass(Favicon.el, 'unread');
} else {
$.rmClass(Favicon.el, 'unread');
}
if ($.engine !== 'webkit') {
return $.add(d.head, Favicon.el);
}
}
};
Favicon = {
init: function() {
var href;
if (this.el) {
return;
}
this.el = $('link[rel="shortcut icon"]', d.head);
this.el.type = 'image/x-icon';
href = this.el.href;
this.SFW = /ws.ico$/.test(href);
this["default"] = href;
return this["switch"]();
},
"switch": function() {
switch (Conf['favicon']) {
case 'ferongr':
this.unreadDead = 'data:image/gif;base64,R0lGODlhEAAQAOMHAOgLAnMFAL8AAOgLAukMA/+AgP+rq////////////////////////////////////yH5BAEKAAcALAAAAAAQABAAAARZ8MhJ6xwDWIBv+AM1fEEIBIVRlNKYrtpIECuGzuwpCLg974EYiXUYkUItjGbC6VQ4omXFiKROA6qSy0A8nAo9GS3YCswIWnOvLAi0be23Z1QtdSUaqXcviQAAOw==';
this.unreadSFW = 'data:image/gif;base64,R0lGODlhEAAQAOMHAADX8QBwfgC2zADX8QDY8nnl8qLp8v///////////////////////////////////yH5BAEKAAcALAAAAAAQABAAAARZ8MhJ6xwDWIBv+AM1fEEIBIVRlNKYrtpIECuGzuwpCLg974EYiXUYkUItjGbC6VQ4omXFiKROA6qSy0A8nAo9GS3YCswIWnOvLAi0be23Z1QtdSUaqXcviQAAOw==';
this.unreadNSFW = 'data:image/gif;base64,R0lGODlhEAAQAOMHAFT+ACh5AEncAFT+AFX/Acz/su7/5v///////////////////////////////////yH5BAEKAAcALAAAAAAQABAAAARZ8MhJ6xwDWIBv+AM1fEEIBIVRlNKYrtpIECuGzuwpCLg974EYiXUYkUItjGbC6VQ4omXFiKROA6qSy0A8nAo9GS3YCswIWnOvLAi0be23Z1QtdSUaqXcviQAAOw==';
break;
case 'xat-':
this.unreadDead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA2ElEQVQ4y61TQQrCMBDMQ8WDIEV6LbT2A4og2Hq0veo7fIAH04dY9N4xmyYlpGmI2MCQTWYy3Wy2DAD7B2wWAzWgcTgVeZKlZRxHNYFi2jM18oBh0IcKtC6ixf22WT4IFLs0owxswXu9egm0Ls6bwfCFfNsJYJKfqoEkd3vgUgFVLWObtzNgVKyruC+ljSzr5OEnBzjvjcQecaQhbZgBb4CmGQw+PoMkTUtdbd8VSEPakcGxPOcsoIgUKy0LecY29BmdBrqRfjIwZ93KLs5loHvBnL3cLH/jF+C/+z5dgUysAAAAAElFTkSuQmCC';
this.unreadSFW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA30lEQVQ4y2P4//8/AyWYgSoGQMF/GJ7Y11VVUVoyKTM9ey4Ig9ggMWQ1YA1IBvzXm34YjkH8mPyJB+Nqlp8FYRAbmxoMF6ArSNrw6T0Qf8Amh9cFMEWVR/7/A+L/uORxhgEIt5/+/3/2lf//5wAxiI0uj+4CBlBgxVUvOwtydgXQZpDmi2/+/7/0GmIQSAwkB1IDUkuUAZeABlx+g2zAZ9wGlAOjChba+LwAUgNSi2HA5Am9VciBhSsQQWyoWgZiovEDsdGI1QBYQiLJAGQalpSxyWEzAJYWkGm8clTJjQCZ1hkoVG0CygAAAABJRU5ErkJggg==';
this.unreadNSFW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA4ElEQVQ4y2P4//8/AyWYgSoGQMF/GJ7YNbGqrKRiUnp21lwQBrFBYshqwBqQDPifdsYYjkH8mInxB+OWx58FYRAbmxoMF6ArKPmU9B6IP2CTw+sCmKKe/5X/gPg/LnmcYQDCs/63/1/9fzYQzwGz0eXRXcAACqy4ZfFnQc7u+V/xD6T55v+LQHwJbBBIDCQHUgNSS5QBt4Cab/2/jDDgMx4DykrKJ8FCG58XQGpAajEMmNw7uQo5sHAFIogNVctATDR+IDYasRoAS0gkGYBMw5IyNjlsBsDSAjKNV44quREAx58Mr9vt5wQAAAAASUVORK5CYII=';
break;
case 'Mayhem':
this.unreadDead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABIUlEQVQ4jZ2ScWuDMBDFgw4pIkU0WsoQkWAYIkXZH4N9/+/V3dmfXSrKYIFHwt17j8vdGWNMIkgFuaDgzgQnwRs4EQs5KdolUQtagRN0givEDBTEOjgtGs0Zq8F7cKqqusVxrMQLaDUWcjBSrXkn8gs51tpJSWLk9b3HUa0aNIL5gPBR1/V4kJvR7lTwl8GmAm1Gf9+c3S+89qBHa8502AsmSrtBaEBPbIbj0ah2madlNAPEccdgJDfAtWifBjqWKShRBT6KoiH8QlEUn/qt0CCjnNdmPUwmFWzj9Oe6LpKuZXcwqq88z78Pch3aZU3dPwwc2sWlfZKCW5tWluV8kGvXClLm6dYN4/aUqfCbnEOzNDGhGZbNargvxCzvMGfRJD8UaDVvgkzo6QAAAABJRU5ErkJggg==';
this.unreadSFW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABCElEQVQ4jZ2S4crCMAxF+0OGDJEPKYrIGKOsiJSx/fJRfSAfTJNyKqXfiuDg0C25N2RJjTGmEVrhTzhw7oStsIEtsVzT4o2Jo9ALThiEM8IdHIgNaHo8mjNWg6/ske8bohPo+63QOLzmooHp8fyAICBSQkVz0QKdsFQEV6WSW/D+7+BbgbIDHcb4Kp61XyjyI16zZ8JemGltQtDBSGxB4/GoN+7TpkkjDCsFArm0IYv3U0BbnYtf8BCy+JytsE0X6VyuKhPPK/GAJ14kvZZDZVV3pZIb8MZr6n4o4PDGKn0S5SdDmyq5PnXQsk+Xbhinp03FFzmHJw6xYRiWm9VxnohZ3vOcxdO8ARmXRvbWdtzQAAAAAElFTkSuQmCC';
this.unreadNSFW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABCklEQVQ4jZ2S0WrDMAxF/TBCCKWMYhZKCSGYmFJMSNjD/mhf239qJXNcjBdTWODgRLpXKJKNMaYROuFTOHEehFb4gJZYrunwxsSXMApOmIQzwgOciE1oRjyaM1aDj+yR7xuiHvT9VmgcXnPRwO/9+wWCgEgJFc1FCwzCVhFclUpuw/u3g3cFyg50GPOjePZ+ocjPeM2RCXthpbUFwQAzsQ2Nx6PeuE+bJo0w7BQI5NKGLN5XAW11LX7BQ8jia7bCLl2kc7mqTLzuxAOeeJH0Wk6VVf0oldyEN15T948CDm+sMiZRfjK0pZIbUwcd+3TphnF62lR8kXN44hAbhmG5WQNnT8zynucsnuYJhFpBfkMzqD4AAAAASUVORK5CYII=';
break;
case 'Original':
this.unreadDead = 'data:image/gif;base64,R0lGODlhEAAQAKECAAAAAP8AAP///////yH5BAEKAAMALAAAAAAQABAAAAI/nI95wsqygIRxDgGCBhTrwF3Zxowg5H1cSopS6FrGQ82PU1951ckRmYKJVCXizLRC9kAnT0aIiR6lCFT1cigAADs=';
this.unreadSFW = 'data:image/gif;base64,R0lGODlhEAAQAKECAAAAAC6Xw////////yH5BAEKAAMALAAAAAAQABAAAAI/nI95wsqygIRxDgGCBhTrwF3Zxowg5H1cSopS6FrGQ82PU1951ckRmYKJVCXizLRC9kAnT0aIiR6lCFT1cigAADs=';
this.unreadNSFW = 'data:image/gif;base64,R0lGODlhEAAQAKECAAAAAGbMM////////yH5BAEKAAMALAAAAAAQABAAAAI/nI95wsqygIRxDgGCBhTrwF3Zxowg5H1cSopS6FrGQ82PU1951ckRmYKJVCXizLRC9kAnT0aIiR6lCFT1cigAADs=';
}
return this.unread = this.SFW ? this.unreadSFW : this.unreadNSFW;
},
empty: 'data:image/gif;base64,R0lGODlhEAAQAJEAAAAAAP///9vb2////yH5BAEAAAMALAAAAAAQABAAAAIvnI+pq+D9DBAUoFkPFnbs7lFZKIJOJJ3MyraoB14jFpOcVMpzrnF3OKlZYsMWowAAOw==',
dead: 'data:image/gif;base64,R0lGODlhEAAQAKECAAAAAP8AAP///////yH5BAEKAAIALAAAAAAQABAAAAIvlI+pq+D9DAgUoFkPDlbs7lFZKIJOJJ3MyraoB14jFpOcVMpzrnF3OKlZYsMWowAAOw=='
};
Redirect = {
image: function(board, filename) {
switch (board) {
case 'a':
case 'biz':
case 'c':
case 'co':
case 'diy':
case 'gd':
case 'jp':
case 'k':
case 'm':
case 'mlp':
case 'po':
case 'qa':
case 'sci':
case 'tg':
case 'u':
case 'v':
case 'vg':
case 'vp':
case 'vr':
case 'wsg':
return "https://archive.moe/" + board + "/full_image/" + filename;
case 'adv':
case 'f':
case 'hr':
case 'o':
case 'pol':
case 's4s':
case 'trv':
case 'tv':
case 'x':
return "//archive.4plebs.org/" + board + "/full_image/" + filename;
case 'd':
case 'e':
case 'i':
case 'lgbt':
case 't':
case 'w':
case 'wg':
return "//archive.loveisover.me/" + board + "/full_image/" + filename;
case 'cgl':
case 'g':
case 'mu':
return "https://archive.rebeccablacktech.com/" + board + "/full_image/" + filename;
case '3':
case 'ck':
case 'fa':
case 'ic':
case 'lit':
return "https://warosu.org/" + board + "/full_image/" + filename;
case 'asp':
case 'cm':
case 'h':
case 'hc':
case 'hm':
case 'n':
case 'p':
case 'r':
case 's':
case 'soc':
case 'y':
return "//fgts.jp/" + board + "/full_image/" + filename;
case 'an':
case 'fit':
case 'gif':
case 'int':
case 'out':
case 'r9k':
case 'toy':
return "http://imcute.yt/" + board + "/full_image/" + filename;
}
},
post: function(board, postID) {
switch (board) {
case 'a':
case 'biz':
case 'c':
case 'co':
case 'diy':
case 'gd':
case 'int':
case 'jp':
case 'k':
case 'm':
case 'mlp':
case 'out':
case 'po':
case 'qa':
case 'r9k':
case 'sci':
case 'tg':
case 'tv':
case 'u':
case 'v':
case 'vg':
case 'vp':
case 'vr':
case 'wsg':
return "https://archive.moe/_/api/chan/post/?board=" + board + "&num=" + postID;
case 'adv':
case 'f':
case 'hr':
case 'o':
case 'pol':
case 's4s':
case 'trv':
case 'x':
return "//archive.4plebs.org/_/api/chan/post/?board=" + board + "&num=" + postID;
case 'd':
case 'e':
case 'i':
case 'lgbt':
case 't':
case 'w':
case 'wg':
return "//archive.loveisover.me/_/api/chan/post/?board=" + board + "&num=" + postID;
case 'asp':
case 'cm':
case 'h':
case 'hc':
case 'hm':
case 'n':
case 'p':
case 'r':
case 's':
case 'soc':
case 'y':
return "//fgts.jp/_/api/chan/post/?board=" + board + "&num=" + postID;
case 'an':
case 'fit':
case 'gif':
case 'toy':
return "http://imcute.yt/_/api/chan/post/?board=" + board + "&num=" + postID;
}
},
to: function(data) {
var board, threadID, url;
if (!data.isSearch) {
threadID = data.threadID;
}
board = data.board;
switch (board) {
case 'a':
case 'biz':
case 'c':
case 'co':
case 'diy':
case 'gd':
case 'int':
case 'jp':
case 'k':
case 'm':
case 'mlp':
case 'out':
case 'po':
case 'qa':
case 'r9k':
case 'sci':
case 'tg':
case 'tv':
case 'u':
case 'v':
case 'vg':
case 'vp':
case 'vr':
case 'wsg':
url = Redirect.path('https://archive.moe', 'foolfuuka', data);
break;
case 'adv':
case 'f':
case 'hr':
case 'o':
case 'pol':
case 's4s':
case 'trv':
case 'x':
url = Redirect.path('//archive.4plebs.org', 'foolfuuka', data);
break;
case 'd':
case 'e':
case 'i':
case 'lgbt':
case 't':
case 'w':
case 'wg':
url = Redirect.path('//archive.loveisover.me', 'foolfuuka', data);
break;
case 'cgl':
case 'mu':
url = Redirect.path('https://archive.rebeccablacktech.com', 'fuuka', data);
break;
case '3':
case 'ck':
case 'fa':
case 'g':
case 'ic':
case 'lit':
url = Redirect.path('https://warosu.org', 'fuuka', data);
break;
case 'asp':
case 'cm':
case 'h':
case 'hc':
case 'hm':
case 'n':
case 'p':
case 'r':
case 's':
case 'soc':
case 'y':
url = Redirect.path('//fgts.jp', 'foolfuuka', data);
break;
case 'an':
case 'fit':
case 'gif':
case 'toy':
url = Redirect.path('http://imcute.yt', 'foolfuuka', data);
break;
default:
if (threadID) {
url = "//boards.4chan.org/" + board + "/";
}
}
return url || null;
},
path: function(base, archiver, data) {
var board, path, postID, threadID, type, value;
if (data.isSearch) {
board = data.board, type = data.type, value = data.value;
type = type === 'name' ? 'username' : type === 'md5' ? 'image' : type;
value = encodeURIComponent(value);
if (archiver === 'foolfuuka') {
return "" + base + "/" + board + "/search/" + type + "/" + value;
} else if (type === 'image') {
return "" + base + "/" + board + "/?task=search2&search_media_hash=" + value;
} else {
return "" + base + "/" + board + "/?task=search2&search_" + type + "=" + value;
}
}
board = data.board, threadID = data.threadID, postID = data.postID;
if (postID) {
postID = postID.match(/\d+/)[0];
}
path = threadID ? "" + board + "/thread/" + threadID : "" + board + "/post/" + postID;
if (archiver === 'foolfuuka') {
path += '/';
}
if (threadID && postID) {
path += archiver === 'foolfuuka' ? "#" + postID : "#p" + postID;
}
return "" + base + "/" + path;
}
};
ImageHover = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
if (!post.img || post.hasPdf) {
return;
}
return $.on(post.img, 'mouseover', ImageHover.mouseover);
},
mouseover: function() {
var el;
if (el = $.id('ihover')) {
if (el === UI.el) {
delete UI.el;
}
$.rm(el);
}
if (UI.el) {
return;
}
if (/\.webm$/.test(this.parentNode.href)) {
el = UI.el = $.el('video', {
id: 'ihover',
src: this.parentNode.href,
type: 'video/webm',
autoplay: true,
loop: true
});
} else {
el = UI.el = $.el('img', {
id: 'ihover',
src: this.parentNode.href
});
}
$.add(d.body, el);
$.on(el, 'load', ImageHover.load);
$.on(el, 'error', ImageHover.error);
$.on(this, 'mousemove', UI.hover);
return $.on(this, 'mouseout', ImageHover.mouseout);
},
load: function() {
var style;
if (!this.parentNode) {
return;
}
style = this.style;
return UI.hover({
clientX: -45 + parseInt(style.left),
clientY: 120 + parseInt(style.top)
});
},
error: function() {
var src, timeoutID, url,
_this = this;
src = this.src.split('/');
if (!(src[2] === 'i.4cdn.org' && (url = Redirect.image(src[3], src[4])))) {
if (g.dead) {
return;
}
url = "//i.4cdn.org/" + src[3] + "/" + src[4];
}
if ($.engine !== 'webkit' && url.split('/')[2] === 'i.4cdn.org') {
return;
}
timeoutID = setTimeout((function() {
return _this.src = url;
}), 3000);
if ($.engine !== 'webkit' || url.split('/')[2] !== 'i.4cdn.org') {
return;
}
return $.ajax(url, {
onreadystatechange: (function() {
if (this.status === 404) {
return clearTimeout(timeoutID);
}
})
}, {
type: 'head'
});
},
mouseout: function() {
UI.hoverend();
$.off(this, 'mousemove', UI.hover);
return $.off(this, 'mouseout', ImageHover.mouseout);
}
};
AutoGif = {
init: function() {
var _ref;
if ((_ref = g.BOARD) === 'gif' || _ref === 'wsg') {
return;
}
return Main.callbacks.push(this.node);
},
node: function(post) {
var gif, img, src;
img = post.img;
if (post.el.hidden || !img) {
return;
}
src = img.parentNode.href;
if (/gif$/.test(src) && !/spoiler/.test(img.src)) {
gif = $.el('img');
$.on(gif, 'load', function() {
return img.src = src;
});
return gif.src = src;
}
}
};
ReplacePng = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var png, img, src;
img = post.img;
if (post.el.hidden || !img) {
return;
}
src = img.parentNode.href;
if (/png$/.test(src) && !/spoiler/.test(img.src)) {
png = $.el('img');
$.on(png, 'load', function() {
return img.src = src;
});
return png.src = src;
}
}
};
ReplaceJpg = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var jpg, img, src;
img = post.img;
if (post.el.hidden || !img) {
return;
}
src = img.parentNode.href;
if (/jpg$/.test(src) && !/spoiler/.test(img.src)) {
jpg = $.el('img');
$.on(jpg, 'load', function() {
return img.src = src;
});
return jpg.src = src;
}
}
};
ImageExpand = {
init: function() {
Main.callbacks.push(this.node);
return this.dialog();
},
node: function(post) {
var a;
if (!post.img || post.hasPdf) {
return;
}
a = post.img.parentNode;
$.on(a, 'click', ImageExpand.cb.toggle);
if (ImageExpand.on && !post.el.hidden) {
return ImageExpand.expand(post.img);
}
},
cb: {
toggle: function(e) {
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey || e.button !== 0) {
return;
}
e.preventDefault();
return ImageExpand.toggle(this);
},
all: function() {
var i, thumb, thumbs, _i, _j, _k, _len, _len1, _len2, _ref;
ImageExpand.on = this.checked;
if (ImageExpand.on) {
thumbs = $$('img[data-md5]');
if (Conf['Expand From Current']) {
for (i = _i = 0, _len = thumbs.length; _i < _len; i = ++_i) {
thumb = thumbs[i];
if (thumb.getBoundingClientRect().top > 0) {
break;
}
}
thumbs = thumbs.slice(i);
}
for (_j = 0, _len1 = thumbs.length; _j < _len1; _j++) {
thumb = thumbs[_j];
ImageExpand.expand(thumb);
}
} else {
_ref = $$('img[data-md5][hidden]');
for (_k = 0, _len2 = _ref.length; _k < _len2; _k++) {
thumb = _ref[_k];
ImageExpand.contract(thumb);
}
}
},
typeChange: function() {
var klass;
switch (this.value) {
case 'full':
klass = '';
break;
case 'fit width':
klass = 'fitwidth';
break;
case 'fit height':
klass = 'fitheight';
break;
case 'fit screen':
klass = 'fitwidth fitheight';
}
$.id('delform').className = klass;
if (/\bfitheight\b/.test(klass)) {
$.on(window, 'resize', ImageExpand.resize);
if (!ImageExpand.style) {
ImageExpand.style = $.addStyle('');
}
return ImageExpand.resize();
} else if (ImageExpand.style) {
return $.off(window, 'resize', ImageExpand.resize);
}
}
},
toggle: function(a) {
var rect, thumb;
thumb = a.firstChild;
if (thumb.hidden) {
rect = a.getBoundingClientRect();
if (rect.bottom > 0) {
if ($.engine === 'webkit') {
if (rect.top < 0) {
d.body.scrollTop += rect.top - 42;
}
if (rect.left < 0) {
d.body.scrollLeft += rect.left;
}
} else {
if (rect.top < 0) {
d.documentElement.scrollTop += rect.top - 42;
}
if (rect.left < 0) {
d.documentElement.scrollLeft += rect.left;
}
}
}
return ImageExpand.contract(thumb);
} else {
return ImageExpand.expand(thumb);
}
},
contract: function(thumb) {
thumb.hidden = false;
thumb.nextSibling.hidden = true;
if (thumb.nextSibling.nodeName === 'VIDEO') {
thumb.nextSibling.pause();
thumb.nextSibling.remove();
}
return $.rmClass(thumb.parentNode.parentNode.parentNode, 'image_expanded');
},
expand: function(thumb, src) {
var a, img;
if ($.x('ancestor-or-self::*[@hidden]', thumb)) {
return;
}
a = thumb.parentNode;
src || (src = a.href);
if (/\.pdf$/.test(src)) {
return;
}
thumb.hidden = true;
$.addClass(thumb.parentNode.parentNode.parentNode, 'image_expanded');
if ((img = thumb.nextSibling) && img.nodeName === 'IMG') {
img.hidden = false;
return;
}
/* a video in your img? it's more likely than you think */
if (/\.webm$/.test(src)) {
img = $.el('video', {
src: src,
type: 'video/webm',
autoplay: true,
loop: true
});
} else {
img = $.el('img', {
src: src
});
}
$.on(img, 'error', ImageExpand.error);
return $.after(thumb, img);
},
error: function() {
var src, thumb, timeoutID, url;
thumb = this.previousSibling;
ImageExpand.contract(thumb);
$.rm(this);
src = this.src.split('/');
if (!(src[2] === 'i.4cdn.org' && (url = Redirect.image(src[3], src[4])))) {
if (g.dead) {
return;
}
url = "//i.4cdn.org/" + src[3] + "/" + src[4];
}
if ($.engine !== 'webkit' && url.split('/')[2] === 'i.4cdn.org') {
return;
}
timeoutID = setTimeout(ImageExpand.expand, 10000, thumb, url);
if ($.engine !== 'webkit' || url.split('/')[2] !== 'i.4cdn.org') {
return;
}
return $.ajax(url, {
onreadystatechange: (function() {
if (this.status === 404) {
return clearTimeout(timeoutID);
}
})
}, {
type: 'head'
});
},
dialog: function() {
var controls, imageType, select;
controls = $.el('div', {
id: 'imgControls',
innerHTML: "<select id=imageType name=imageType><option value=full>Full</option><option value='fit width'>Fit Width</option><option value='fit height'>Fit Height</option value='fit screen'><option value='fit screen'>Fit Screen</option></select><label>Expand Images<input type=checkbox id=imageExpand></label>"
});
imageType = $.get('imageType', 'full');
select = $('select', controls);
select.value = imageType;
ImageExpand.cb.typeChange.call(select);
$.on(select, 'change', $.cb.value);
$.on(select, 'change', ImageExpand.cb.typeChange);
$.on($('input', controls), 'click', ImageExpand.cb.all);
return $.prepend($.id('delform'), controls);
},
resize: function() {
return ImageExpand.style.textContent = ".fitheight img[data-md5] + img {max-height:" + d.documentElement.clientHeight + "px;} .fitheight img[data-md5] + video {max-height:" + d.documentElement.clientHeight + "px;}";
}
};
RemoveSlug = {
init: function() {
var catalogdiv;
var threads = [];
if (g.CATALOG) {
catalogdiv = document.getElementsByClassName('thread');
for (var i = 0; i < catalogdiv.length; i++) {
threads.push(catalogdiv[i].firstElementChild);
}
} else {
threads = document.getElementsByClassName('replylink');
}
return RemoveSlug.deslug(threads);
},
deslug: function(els) {
var el;
for (var i = 0; i < els.length; i++) {
el = els[i];
path = el.pathname;
if (path.slice(1).split('/').length > 3) {
el.pathname = path.substring(0, path.lastIndexOf('/'));
}
}
return;
}
};
CatalogLinks = {
init: function() {
var clone, el, nav, _i, _len, _ref;
el = $.el('span', {
className: 'toggleCatalog',
innerHTML: '[<a href=javascript:;></a>]'
});
_ref = ['boardNavDesktop', 'boardNavDesktopFoot'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
nav = _ref[_i];
clone = el.cloneNode(true);
$.on(clone.firstElementChild, 'click', CatalogLinks.toggle);
$.add($.id(nav), clone);
}
return CatalogLinks.toggle(true);
},
toggle: function(onLoad) {
var a, board, nav, root, useCatalog, _i, _j, _len, _len1, _ref, _ref1;
if (onLoad === true) {
useCatalog = $.get('CatalogIsToggled', g.CATALOG);
} else {
useCatalog = this.textContent === 'Catalog Off';
$.set('CatalogIsToggled', useCatalog);
}
_ref = ['boardNavDesktop', 'boardNavDesktopFoot'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
nav = _ref[_i];
root = $.id(nav);
_ref1 = $$('a[href]', root.getElementsByClassName('boardList')[0]);
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
a = _ref1[_j];
board = a.pathname.split('/')[1];
if (board === 'f') {
a.pathname = '/f/';
continue;
}
a.pathname = "/" + board + "/" + (useCatalog ? 'catalog' : '');
}
a = $('.toggleCatalog', root).firstElementChild;
a.textContent = "Catalog " + (useCatalog ? 'On' : 'Off');
a.title = "Turn catalog links " + (useCatalog ? 'off' : 'on') + ".";
}
}
};
Main = {
init: function() {
var asap, key, path, pathname, settings, temp, val;
Main.flatten(null, Config);
path = location.pathname;
pathname = path.slice(1).split('/');
g.BOARD = pathname[0], temp = pathname[1];
switch (temp) {
case 'thread':
g.REPLY = true;
g.THREAD_ID = pathname[2];
break;
case 'catalog':
g.CATALOG = true;
}
for (key in Conf) {
val = Conf[key];
Conf[key] = $.get(key, val);
}
if (location.hostname === 'i.4cdn.org') {
$.ready(function() {
var url;
if (/^4chan - 404/.test(d.title) && Conf['404 Redirect']) {
path = location.pathname.split('/');
url = Redirect.image(path[1], path[2]);
if (url) {
return location.href = url;
}
}
});
return;
}
if (g.REPLY && pathname.length > 3 && Conf['Remove Slug']) {
window.location.pathname = path.substring(0, path.lastIndexOf('/')) + location.hash;
return;
}
if (Conf['Disable 4chan\'s extension']) {
settings = JSON.parse(localStorage.getItem('4chan-settings')) || {};
settings.disableAll = true;
settings.dropDownNav = false;
localStorage.setItem('4chan-settings', JSON.stringify(settings));
$.ready(function() { $.globalEval('window.removeEventListener("message", Report.onMessage, false);') });
}
Main.polyfill();
if (g.CATALOG) {
return $.ready(Main.catalog);
} else {
return Main.features();
}
},
polyfill: function() {
var event, prefix, property;
if (!('visibilityState' in document)) {
prefix = 'mozVisibilityState' in document ? 'moz' : 'webkitVisibilityState' in document ? 'webkit' : 'o';
property = prefix + 'VisibilityState';
event = prefix + 'visibilitychange';
d.visibilityState = d[property];
d.hidden = d.visibilityState === 'hidden';
return $.on(d, event, function() {
d.visibilityState = d[property];
d.hidden = d.visibilityState === 'hidden';
return $.event('visibilitychange', null, d);
});
}
},
catalog: function() {
if (Conf['Remove Slug']) {
$.ready(RemoveSlug.init);
}
if (Conf['Catalog Links']) {
$.ready(CatalogLinks.init);
}
if (Conf['Thread Hiding']) {
return ThreadHiding.init();
}
},
features: function() {
var cutoff, hiddenThreads, id, now, timestamp, _ref;
Options.init();
if (Conf['Quick Reply'] && Conf['Hide Original Post Form']) {
Main.css += '#postForm { display: none; }';
}
$.addStyle(Main.css);
now = Date.now();
if (Conf['Check for Updates'] && $.get('lastUpdate', 0) < now - 6 * $.HOUR) {
$.ready(function() {
$.on(window, 'message', Main.message);
$.set('lastUpdate', now);
return $.add(d.head, $.el('script', {
src: 'https://loadletter.github.io/4chan-x/latest.js'
}));
});
}
g.hiddenReplies = $.get("hiddenReplies/" + g.BOARD + "/", {});
if ($.get('lastChecked', 0) < now - 1 * $.DAY) {
$.set('lastChecked', now);
cutoff = now - 7 * $.DAY;
hiddenThreads = $.get("hiddenThreads/" + g.BOARD + "/", {});
for (id in hiddenThreads) {
timestamp = hiddenThreads[id];
if (timestamp < cutoff) {
delete hiddenThreads[id];
}
}
_ref = g.hiddenReplies;
for (id in _ref) {
timestamp = _ref[id];
if (timestamp < cutoff) {
delete g.hiddenReplies[id];
}
}
$.set("hiddenThreads/" + g.BOARD + "/", hiddenThreads);
$.set("hiddenReplies/" + g.BOARD + "/", g.hiddenReplies);
}
if (Conf['Filter']) {
Filter.init();
}
if (Conf['Reply Hiding']) {
ReplyHiding.init();
}
if (Conf['Filter'] || Conf['Reply Hiding']) {
StrikethroughQuotes.init();
}
if (Conf['Anonymize']) {
Anonymize.init();
}
if (Conf['Time Formatting']) {
Time.init();
}
if (Conf['Relative Post Dates']) {
RelativeDates.init();
}
if (Conf['File Info Formatting']) {
FileInfo.init();
}
if (Conf['Sauce']) {
Sauce.init();
}
if (Conf['Reveal Spoilers']) {
RevealSpoilers.init();
}
if (Conf['Image Auto-Gif']) {
AutoGif.init();
}
if (Conf['Replace PNG']) {
ReplacePng.init();
}
if (Conf['Replace JPG']) {
ReplaceJpg.init();
}
if (Conf['Image Hover']) {
ImageHover.init();
}
if (Conf['Menu']) {
Menu.init();
if (Conf['Report Link']) {
ReportLink.init();
}
if (Conf['Delete Link']) {
DeleteLink.init();
}
if (Conf['Filter']) {
Filter.menuInit();
}
if (Conf['Download Link']) {
DownloadLink.init();
}
if (Conf['Archive Link']) {
ArchiveLink.init();
}
}
if (Conf['Resurrect Quotes']) {
Quotify.init();
}
if (Conf['Quote Inline']) {
QuoteInline.init();
}
if (Conf['Quote Preview']) {
QuotePreview.init();
}
if (Conf['Quote Backlinks']) {
QuoteBacklink.init();
}
if (Conf['Indicate OP quote']) {
QuoteOP.init();
}
if (Conf['Indicate You quote']) {
QuoteYou.init();
}
if (Conf['Indicate Cross-thread Quotes']) {
QuoteCT.init();
}
return $.ready(Main.featuresReady);
},
featuresReady: function() {
var MutationObserver, a, board, node, nodes, observer, _j, _len1, _ref1;
if (/^4chan - 404/.test(d.title)) {
if (Conf['404 Redirect'] && /^\d+$/.test(g.THREAD_ID)) {
location.href = Redirect.to({
board: g.BOARD,
threadID: g.THREAD_ID,
postID: location.hash
});
}
return;
}
if (!$.id('navtopright')) {
return;
}
$.addClass(d.body, $.engine);
$.addClass(d.body, 'fourchan_x');
if (a = $("a[href$='/" + g.BOARD + "/']", $.id('boardNavDesktop'))) {
$.addClass(a, 'current');
}
$.ready(function () {
if (a = $("a[href$='/" + g.BOARD + "/']", $.id('boardNavDesktopFoot'))) {
$.addClass(a, 'current');
}
});
Favicon.init();
if (Conf['Quick Reply']) {
QR.init();
}
if (Conf['Image Expansion']) {
ImageExpand.init();
}
if (Conf['Catalog Links']) {
$.ready(CatalogLinks.init);
}
if (Conf['Thread Watcher']) {
setTimeout(function() {
return Watcher.init();
});
}
if (Conf['Keybinds']) {
setTimeout(function() {
return Keybinds.init();
});
}
if (g.REPLY) {
if (Conf['Thread Updater']) {
setTimeout(function() {
return Updater.init();
});
}
if (Conf['Thread Stats']) {
ThreadStats.init();
}
if (Conf['Reply Navigation']) {
setTimeout(function() {
return Nav.init();
});
}
TitlePost.init();
if (Conf['Unread Count'] || Conf['Unread Favicon']) {
Unread.init();
}
} else {
if (Conf['Remove Slug']) {
RemoveSlug.init();
}
if (Conf['Thread Hiding']) {
ThreadHiding.init();
}
if (Conf['Thread Expansion']) {
setTimeout(function() {
return ExpandThread.init();
});
}
if (Conf['Comment Expansion']) {
setTimeout(function() {
return ExpandComment.init();
});
}
if (Conf['Index Navigation']) {
setTimeout(function() {
return Nav.init();
});
}
}
board = $('.board');
nodes = [];
_ref1 = $$('.postContainer', board);
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
node = _ref1[_j];
nodes.push(Main.preParse(node));
}
Main.node(nodes, true);
Main.hasCodeTags = !!$('script[src^="//s.4cdn.org/js/prettify/prettify"]');
if (MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.OMutationObserver) {
observer = new MutationObserver(Main.observer);
observer.observe(board, {
childList: true,
subtree: true
});
} else {
$.on(board, 'DOMNodeInserted', Main.listener);
}
},
flatten: function(parent, obj) {
var key, val;
if (obj instanceof Array) {
Conf[parent] = obj[0];
} else if (typeof obj === 'object') {
for (key in obj) {
val = obj[key];
Main.flatten(key, val);
}
} else {
Conf[parent] = obj;
}
},
message: function(e) {
var version;
version = e.data.version;
if (version && version !== Main.version && confirm('An updated version of 4chan X is available, would you like to install it now?')) {
return window.location = "https://raw.github.com/loadletter/4chan-x/" + version + "/4chan_x.user.js";
}
},
preParse: function(node) {
var el, img, imgParent, parentClass, post;
parentClass = node.parentNode.className;
el = $('.post', node);
post = {
root: node,
el: el,
"class": el.className,
ID: el.id.match(/\d+$/)[0],
threadID: g.THREAD_ID || $.x('ancestor::div[parent::div[@class="board"]]', node).id.match(/\d+$/)[0],
isArchived: /\barchivedPost\b/.test(parentClass),
isInlined: /\binline\b/.test(parentClass),
isCrosspost: /\bcrosspost\b/.test(parentClass),
blockquote: el.lastElementChild,
quotes: el.getElementsByClassName('quotelink'),
backlinks: el.getElementsByClassName('backlink'),
fileInfo: false,
img: false
};
if (img = $('img[data-md5]', el)) {
imgParent = img.parentNode;
post.img = img;
post.fileInfo = imgParent.previousElementSibling;
post.hasPdf = /\.pdf$/.test(imgParent.href);
}
Main.prettify(post.blockquote);
return post;
},
node: function(nodes, notify) {
var callback, err, node, _i, _j, _len, _len1, _ref;
_ref = Main.callbacks;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
callback = _ref[_i];
try {
for (_j = 0, _len1 = nodes.length; _j < _len1; _j++) {
node = nodes[_j];
callback(node);
}
} catch (_error) {
err = _error;
if (notify) {
alert("4chan X (" + Main.version + ") error: " + err.message + "\nReport the bug at github.com/loadletter/4chan-x/issues\n\nURL: " + window.location + "\n" + err.stack);
}
}
}
},
observer: function(mutations) {
var addedNode, mutation, nodes, _i, _j, _len, _len1, _ref;
nodes = [];
for (_i = 0, _len = mutations.length; _i < _len; _i++) {
mutation = mutations[_i];
_ref = mutation.addedNodes;
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
addedNode = _ref[_j];
if (/\bpostContainer\b/.test(addedNode.className)) {
nodes.push(Main.preParse(addedNode));
}
}
}
if (nodes.length) {
return Main.node(nodes);
}
},
listener: function(e) {
var target;
target = e.target;
if (/\bpostContainer\b/.test(target.className)) {
return Main.node([Main.preParse(target)]);
}
},
prettify: function(bq) {
var code;
if (!Main.hasCodeTags) {
return;
}
code = function() {
var pre, _i, _len, _ref;
_ref = document.getElementById('_id_').getElementsByClassName('prettyprint');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
pre = _ref[_i];
pre.innerHTML = prettyPrintOne(pre.innerHTML.replace(/\s/g, ' '));
}
};
return $.globalEval(("(" + code + ")()").replace('_id_', bq.id));
},
namespace: '4chan_x.',
version: '2.40.49',
callbacks: [],
css: '\
/* dialog styling */\
.dialog.reply {\
display: block;\
border: 1px solid rgba(0,0,0,.25);\
padding: 0;\
}\
.move {\
cursor: move;\
}\
label, .favicon {\
cursor: pointer;\
}\
a[href="javascript:;"] {\
text-decoration: none;\
}\
.warning {\
color: red;\
}\
\
.hide_thread_button:not(.hidden_thread) {\
float: left;\
}\
\
.thread > .hidden_thread ~ *,\
[hidden],\
#content > [name=tab]:not(:checked) + div,\
#updater:not(:hover) > :not(.move),\
.autohide:not(:hover) > form,\
#qp input, .forwarded {\
display: none !important;\
}\
\
.menu_button {\
display: inline-block;\
}\
.menu_button > span {\
border-top: .5em solid;\
border-right: .3em solid transparent;\
border-left: .3em solid transparent;\
display: inline-block;\
margin: 2px;\
vertical-align: middle;\
}\
#menu {\
position: absolute;\
outline: none;\
}\
.entry {\
border-bottom: 1px solid rgba(0, 0, 0, .25);\
cursor: pointer;\
display: block;\
outline: none;\
padding: 3px 7px;\
position: relative;\
text-decoration: none;\
white-space: nowrap;\
}\
.entry:last-child {\
border: none;\
}\
.focused.entry {\
background: rgba(255, 255, 255, .33);\
}\
.entry.hasSubMenu {\
padding-right: 1.5em;\
}\
.hasSubMenu::after {\
content: "";\
border-left: .5em solid;\
border-top: .3em solid transparent;\
border-bottom: .3em solid transparent;\
display: inline-block;\
margin: .3em;\
position: absolute;\
right: 3px;\
}\
.hasSubMenu:not(.focused) > .subMenu {\
display: none;\
}\
.subMenu {\
position: absolute;\
left: 100%;\
top: 0;\
margin-top: -1px;\
}\
\
h1 {\
text-align: center;\
}\
#qr > .move {\
min-width: 300px;\
overflow: hidden;\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
padding: 0 2px;\
}\
#qr > .move > span {\
float: right;\
}\
#autohide, .close, #qr select, #dump, .remove, .captchaimg, #qr div.warning {\
cursor: pointer;\
}\
#qr select,\
#qr > form {\
margin: 0;\
}\
#dump {\
background: -webkit-linear-gradient(#EEE, #CCC);\
background: -moz-linear-gradient(#EEE, #CCC);\
background: -o-linear-gradient(#EEE, #CCC);\
background: linear-gradient(#EEE, #CCC);\
width: 10%;\
}\
.gecko #dump {\
padding: 1px 0 2px;\
}\
#dump:hover, #dump:focus {\
background: -webkit-linear-gradient(#FFF, #DDD);\
background: -moz-linear-gradient(#FFF, #DDD);\
background: -o-linear-gradient(#FFF, #DDD);\
background: linear-gradient(#FFF, #DDD);\
}\
#dump:active, .dump #dump:not(:hover):not(:focus) {\
background: -webkit-linear-gradient(#CCC, #DDD);\
background: -moz-linear-gradient(#CCC, #DDD);\
background: -o-linear-gradient(#CCC, #DDD);\
background: linear-gradient(#CCC, #DDD);\
}\
#qr:not(.dump) #replies, .dump > form > label {\
display: none;\
}\
#replies {\
display: block;\
height: 100px;\
position: relative;\
-webkit-user-select: none;\
-moz-user-select: none;\
-o-user-select: none;\
user-select: none;\
}\
#replies > div {\
counter-reset: thumbnails;\
top: 0; right: 0; bottom: 0; left: 0;\
margin: 0; padding: 0;\
overflow: hidden;\
position: absolute;\
white-space: pre;\
}\
#replies > div:hover {\
bottom: -10px;\
overflow-x: auto;\
z-index: 1;\
}\
.thumbnail {\
background-color: rgba(0,0,0,.2) !important;\
background-position: 50% 20% !important;\
background-size: cover !important;\
border: 1px solid #666;\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
cursor: move;\
display: inline-block;\
height: 90px; width: 90px;\
margin: 5px; padding: 2px;\
opacity: .5;\
outline: none;\
overflow: hidden;\
position: relative;\
text-shadow: 0 1px 1px #000;\
-webkit-transition: opacity .25s ease-in-out;\
-moz-transition: opacity .25s ease-in-out;\
-o-transition: opacity .25s ease-in-out;\
transition: opacity .25s ease-in-out;\
vertical-align: top;\
}\
.thumbnail:hover, .thumbnail:focus {\
opacity: .9;\
}\
.thumbnail#selected {\
opacity: 1;\
}\
.thumbnail::before {\
counter-increment: thumbnails;\
content: counter(thumbnails);\
color: #FFF;\
font-weight: 700;\
padding: 3px;\
position: absolute;\
top: 0;\
right: 0;\
text-shadow: 0 0 3px #000, 0 0 8px #000;\
}\
.thumbnail.drag {\
box-shadow: 0 0 10px rgba(0,0,0,.5);\
}\
.thumbnail.over {\
border-color: #FFF;\
}\
.thumbnail > span {\
color: #FFF;\
}\
.remove {\
background: none;\
color: #E00;\
font-weight: 700;\
padding: 3px;\
}\
.remove:hover::after {\
content: " Remove";\
}\
.thumbnail > label {\
background: rgba(0,0,0,.5);\
color: #FFF;\
right: 0; bottom: 0; left: 0;\
position: absolute;\
text-align: center;\
}\
.thumbnail > label > input {\
margin: 0;\
}\
#addReply {\
color: #333;\
font-size: 3.5em;\
line-height: 100px;\
}\
#addReply:hover, #addReply:focus {\
color: #000;\
}\
.field {\
border: 1px solid #CCC;\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
color: #333;\
font: 13px sans-serif;\
margin: 0;\
padding: 2px 4px 3px;\
-webkit-transition: color .25s, border .25s;\
-moz-transition: color .25s, border .25s;\
-o-transition: color .25s, border .25s;\
transition: color .25s, border .25s;\
}\
.field:-moz-placeholder,\
.field:hover:-moz-placeholder {\
color: #AAA;\
}\
.field:hover, .field:focus {\
border-color: #999;\
color: #000;\
outline: none;\
}\
#qr > form > div:first-child > .field:not(#dump) {\
width: 30%;\
}\
#qr textarea.field {\
display: -webkit-box;\
min-height: 160px;\
min-width: 100%;\
}\
#qr.captcha textarea.field {\
min-height: 120px;\
}\
.textarea {\
position: relative;\
}\
#charCount {\
color: #000;\
background: hsla(0, 0%, 100%, .5);\
font-size: 8pt;\
margin: 1px;\
position: absolute;\
bottom: 0;\
right: 0;\
pointer-events: none;\
}\
#charCount.warning {\
color: red;\
}\
#qr [type=file] {\
margin: 1px 0;\
width: 70%;\
}\
#qr [type=submit] {\
margin: 1px 0;\
padding: 1px; /* not Gecko */\
width: 30%;\
}\
.gecko #qr [type=submit] {\
padding: 0 1px; /* Gecko does not respect box-sizing: border-box */\
}\
\
.fileText:hover .fntrunc,\
.fileText:not(:hover) .fnfull {\
display: none;\
}\
.reply > .file > .fileText {\
margin: 0 20px;\
}\
\
.fitwidth img[data-md5] + img {\
max-width: 100%;\
}\
.gecko .fitwidth img[data-md5] + img,\
.presto .fitwidth img[data-md5] + img {\
width: 100%;\
}\
\
.fitwidth img[data-md5] + video {\
max-width: 100%;\
}\
.gecko .fitwidth img[data-md5] + video,\
.presto .fitwidth img[data-md5] + video {\
width: 100%;\
}\
\
#qr, #qp, #updater, #stats, #ihover, #overlay, #navlinks {\
position: fixed;\
}\
\
#ihover {\
max-height: 97%;\
max-width: 75%;\
padding-bottom: 18px;\
}\
\
#navlinks {\
font-size: 16px;\
top: 25px;\
right: 5px;\
}\
\
body {\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
}\
body.unscroll {\
overflow: hidden;\
}\
#overlay {\
top: 0;\
left: 0;\
width: 100%;\
height: 100%;\
text-align: center;\
background: rgba(0,0,0,.5);\
z-index: 1;\
}\
#overlay::after {\
content: "";\
display: inline-block;\
height: 100%;\
vertical-align: middle;\
}\
#options {\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
display: inline-block;\
padding: 5px;\
position: relative;\
text-align: left;\
vertical-align: middle;\
width: 600px;\
max-width: 100%;\
height: 500px;\
max-height: 100%;\
}\
#credits {\
float: right;\
}\
#options ul {\
padding: 0;\
}\
#options article li {\
margin: 10px 0 10px 2em;\
}\
#options code {\
background: hsla(0, 0%, 100%, .5);\
color: #000;\
padding: 0 1px;\
}\
#options label {\
text-decoration: underline;\
}\
#content {\
overflow: auto;\
position: absolute;\
top: 2.5em;\
right: 5px;\
bottom: 5px;\
left: 5px;\
}\
#content textarea {\
font-family: monospace;\
min-height: 350px;\
resize: vertical;\
width: 100%;\
}\
\
#updater {\
text-align: right;\
}\
#updater:not(:hover) {\
border: none;\
background: transparent;\
}\
#updater input[type=number] {\
width: 4em;\
}\
.new {\
background: lime;\
}\
\
#watcher {\
padding-bottom: 5px;\
position: absolute;\
overflow: hidden;\
white-space: nowrap;\
}\
#watcher:not(:hover) {\
max-height: 220px;\
}\
#watcher > div {\
max-width: 200px;\
overflow: hidden;\
padding-left: 5px;\
padding-right: 5px;\
text-overflow: ellipsis;\
}\
#watcher > .move {\
padding-top: 5px;\
text-decoration: underline;\
}\
\
#qp {\
padding: 2px 2px 5px;\
}\
#qp .post {\
border: none;\
margin: 0;\
padding: 0;\
}\
#qp img {\
max-height: 300px;\
max-width: 500px;\
}\
.qphl {\
box-shadow: 0 0 0 2px rgba(216, 94, 49, .7);\
}\
.quotelink.deadlink {\
text-decoration: underline !important;\
}\
.deadlink:not(.quotelink) {\
text-decoration: none !important;\
}\
.inlined {\
opacity: .5;\
}\
.inline {\
background-color: rgba(255, 255, 255, 0.15);\
border: 1px solid rgba(128, 128, 128, 0.5);\
display: table;\
margin: 2px;\
padding: 2px;\
}\
.inline .post {\
background: none;\
border: none;\
margin: 0;\
padding: 0;\
}\
div.opContainer {\
display: block !important;\
}\
.opContainer.filter_highlight {\
box-shadow: inset 5px 0 rgba(255, 0, 0, .5);\
}\
.opContainer.filter_highlight.qphl {\
box-shadow: inset 5px 0 rgba(255, 0, 0, .5),\
0 0 0 2px rgba(216, 94, 49, .7);\
}\
.filter_highlight > .reply {\
box-shadow: -5px 0 rgba(255, 0, 0, .5);\
}\
.filter_highlight > .reply.qphl {\
box-shadow: -5px 0 rgba(255, 0, 0, .5),\
0 0 0 2px rgba(216, 94, 49, .7)\
}\
.filtered {\
text-decoration: underline line-through;\
}\
.quotelink.forwardlink,\
.backlink.forwardlink {\
text-decoration: none;\
border-bottom: 1px dashed;\
}\
'
};
Main.init();
}).call(this);
| 4chan_x.user.js | // ==UserScript==
// @name 4chan x
// @version 2.40.49
// @namespace aeosynth
// @description Adds various features.
// @copyright 2009-2011 James Campos <[email protected]>
// @copyright 2012-2013 Nicolas Stepien <[email protected]>
// @license MIT; http://en.wikipedia.org/wiki/Mit_license
// @include http://boards.4chan.org/*
// @include https://boards.4chan.org/*
// @include http://sys.4chan.org/*
// @include https://sys.4chan.org/*
// @include http://a.4cdn.org/*
// @include https://a.4cdn.org/*
// @include http://i.4cdn.org/*
// @include https://i.4cdn.org/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_openInTab
// @grant GM_xmlhttpRequest
// @run-at document-start
// @updateURL https://github.com/loadletter/4chan-x/raw/master/4chan_x.meta.js
// @downloadURL https://github.com/loadletter/4chan-x/raw/master/4chan_x.user.js
// @icon data:image/gif;base64,R0lGODlhEAAQAKECAAAAAGbMM////////yH5BAEKAAIALAAAAAAQABAAAAIxlI+pq+D9DAgUoFkPDlbs7lGiI2bSVnKglnJMOL6omczxVZK3dH/41AG6Lh7i6qUoAAA7
// ==/UserScript==
/* LICENSE
*
* Copyright (c) 2009-2011 James Campos <[email protected]>
* Copyright (c) 2012-2013 Nicolas Stepien <[email protected]>
* http://mayhemydg.github.io/4chan-x/
* 4chan X 2.39.7
*
* 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.
*
* HACKING
*
* 4chan X is written in CoffeeScript[1], and developed on GitHub[2].
*
* [1]: http://coffeescript.org/
* [2]: https://github.com/MayhemYDG/4chan-x
*
* CONTRIBUTORS
*
* noface - unique ID fixes
* desuwa - Firefox filename upload fix
* seaweed - bottom padding for image hover
* e000 - cooldown sanity check
* ahodesuka - scroll back when unexpanding images, file info formatting
* Shou- - pentadactyl fixes
* ferongr - new favicons
* xat- - new favicons
* Zixaphir - fix qr textarea - captcha-image gap
* Ongpot - sfw favicon
* thisisanon - nsfw + 404 favicons
* Anonymous - empty favicon
* Seiba - chrome quick reply focusing
* herpaderpderp - recaptcha fixes
* WakiMiko - recaptcha tab order http://userscripts.org/scripts/show/82657
* btmcsweeney - allow users to specify text for sauce links
*
* All the people who've taken the time to write bug reports.
*
* Thank you.
*/
(function() {
var $, $$, Anonymize, ArchiveLink, AutoGif, Build, CatalogLinks, Conf, Config, DeleteLink, DownloadLink, ExpandComment, ExpandThread, Favicon, FileInfo, Filter, Get, ImageExpand, ImageHover, Keybinds, Main, Menu, Nav, Options, QR, QuoteBacklink, QuoteCT, QuoteInline, QuoteOP, QuoteYou, QuotePreview, Quotify, Redirect, RelativeDates, RemoveSlug, ReplaceJpg, ReplacePng, ReplyHiding, ReportLink, RevealSpoilers, Sauce, StrikethroughQuotes, ThreadHiding, ThreadStats, Time, TitlePost, UI, Unread, Updater, Watcher, d, g, _base, CaptchaIsSetup;
CaptchaIsSetup = false;
/* Your posts to add (You) backlinks to */
var yourPosts = new Array();
Config = {
main: {
Enhancing: {
'Disable 4chan\'s extension': [true, 'Avoid conflicts between 4chan X and 4chan\'s inline extension'],
'Catalog Links': [true, 'Turn Navigation links into links to each board\'s catalog'],
'404 Redirect': [true, 'Redirect dead threads and images'],
'Keybinds': [true, 'Binds actions to keys'],
'Time Formatting': [true, 'Arbitrarily formatted timestamps, using your local time'],
'Relative Post Dates': [false, 'Display dates as "3 minutes ago" f.e., tooltip shows the timestamp'],
'File Info Formatting': [true, 'Reformats the file information'],
'Comment Expansion': [true, 'Expand too long comments'],
'Thread Expansion': [true, 'View all replies'],
'Index Navigation': [true, 'Navigate to previous / next thread'],
'Reply Navigation': [false, 'Navigate to top / bottom of thread'],
'Remove Slug': [false, 'Cut useless comment/post from the URL'],
'Check for Updates': [true, 'Check for updated versions of 4chan X']
},
Filtering: {
'Anonymize': [false, 'Make everybody anonymous'],
'Filter': [true, 'Self-moderation placebo'],
'Recursive Filtering': [true, 'Filter replies of filtered posts, recursively'],
'Reply Hiding': [true, 'Hide single replies'],
'Thread Hiding': [true, 'Hide entire threads'],
'Show Stubs': [true, 'Of hidden threads / replies']
},
Imaging: {
'Image Auto-Gif': [false, 'Animate gif thumbnails'],
'Replace PNG': [false, 'Replace thumbnail with original PNG image'],
'Replace JPG': [false, 'Replace thumbnail with original JPG image'],
'Image Expansion': [true, 'Expand images'],
'Image Hover': [false, 'Show full image on mouseover'],
'Sauce': [true, 'Add sauce to images'],
'Reveal Spoilers': [false, 'Replace spoiler thumbnails by the original thumbnail'],
'Expand From Current': [false, 'Expand images from current position to thread end']
},
Menu: {
'Menu': [true, 'Add a drop-down menu in posts'],
'Report Link': [true, 'Add a report link to the menu'],
'Delete Link': [true, 'Add post and image deletion links to the menu'],
'Download Link': [true, 'Add a download with original filename link to the menu'],
'Archive Link': [true, 'Add an archive link to the menu']
},
Monitoring: {
'Thread Updater': [true, 'Update threads. Has more options in its own dialog.'],
'Unread Count': [true, 'Show unread post count in tab title'],
'Unread Favicon': [true, 'Show a different favicon when there are unread posts'],
'Post in Title': [true, 'Show the op\'s post in the tab title'],
'Thread Stats': [true, 'Display reply, image and poster count'],
'Current Page': [true, 'Display position of the thread in the page index'],
'Current Page Position': [false, 'Also display position of the thread in index'],
'Thread Watcher': [true, 'Bookmark threads'],
'Auto Watch': [true, 'Automatically watch threads that you start'],
'Auto Watch Reply': [false, 'Automatically watch threads that you reply to']
},
Posting: {
'Quick Reply': [true, 'Reply without leaving the page'],
'Cooldown': [true, 'Prevent "flood detected" errors'],
'Auto Submit': [true, 'Submit automatically when captcha has been solved'],
'Persistent QR': [false, 'The Quick reply won\'t disappear after posting'],
'Auto Hide QR': [true, 'Automatically hide the quick reply when posting'],
'Open Reply in New Tab': [false, 'Open replies in a new tab that are made from the main board'],
'Remember QR size': [false, 'Remember the size of the Quick reply (Firefox only)'],
'Remember Subject': [false, 'Remember the subject field, instead of resetting after posting'],
'Remember Spoiler': [false, 'Remember the spoiler state, instead of resetting after posting'],
'Hide Original Post Form': [true, 'Replace the normal post form with a shortcut to open the QR']
},
Quoting: {
'Quote Backlinks': [true, 'Add quote backlinks'],
'OP Backlinks': [false, 'Add backlinks to the OP'],
'Quote Highlighting': [true, 'Highlight the previewed post'],
'Quote Inline': [true, 'Show quoted post inline on quote click'],
'Quote Preview': [true, 'Show quote content on hover'],
'Resurrect Quotes': [true, 'Linkify dead quotes to archives'],
'Indicate OP quote': [true, 'Add \'(OP)\' to OP quotes'],
/* Add (You) feature */
'Indicate You quote': [true, 'Add \'(You)\' to your quoted posts'],
'Indicate Cross-thread Quotes': [true, 'Add \'(Cross-thread)\' to cross-threads quotes'],
'Forward Hiding': [true, 'Hide original posts of inlined backlinks']
}
},
filter: {
name: ['# Filter any namefags:', '#/^(?!Anonymous$)/'].join('\n'),
uniqueid: ['# Filter a specific ID:', '#/Txhvk1Tl/'].join('\n'),
tripcode: ['# Filter any tripfags', '#/^!/'].join('\n'),
mod: ['# Set a custom class for mods:', '#/Mod$/;highlight:mod;op:yes', '# Set a custom class for moot:', '#/Admin$/;highlight:moot;op:yes'].join('\n'),
email: ['# Filter any e-mails that are not `sage` on /a/ and /jp/:', '#/^(?!sage$)/;boards:a,jp'].join('\n'),
subject: ['# Filter Generals on /v/:', '#/general/i;boards:v;op:only'].join('\n'),
comment: ['# Filter Stallman copypasta on /g/:', '#/what you\'re refer+ing to as linux/i;boards:g'].join('\n'),
country: [''].join('\n'),
filename: [''].join('\n'),
dimensions: ['# Highlight potential wallpapers:', '#/1920x1080/;op:yes;highlight;top:no;boards:w,wg'].join('\n'),
filesize: [''].join('\n'),
md5: [''].join('\n')
},
sauces: ['http://iqdb.org/?url=$1', 'http://www.google.com/searchbyimage?image_url=$1', '#http://tineye.com/search?url=$1', '#http://saucenao.com/search.php?db=999&url=$1', '#http://3d.iqdb.org/?url=$1', '#http://regex.info/exif.cgi?imgurl=$2', '# uploaders:', '#http://imgur.com/upload?url=$2;text:Upload to imgur', '#http://omploader.org/upload?url1=$2;text:Upload to omploader', '# "View Same" in archives:', '#http://archive.foolz.us/_/search/image/$3/;text:View same on foolz', '#http://archive.foolz.us/$4/search/image/$3/;text:View same on foolz /$4/', '#https://archive.installgentoo.net/$4/image/$3;text:View same on installgentoo /$4/'].join('\n'),
time: '%m/%d/%y(%a)%H:%M',
backlink: '>>%id',
fileInfo: '%l (%p%s, %r)',
favicon: 'ferongr',
hotkeys: {
openQR: ['i', 'Open QR with post number inserted'],
openEmptyQR: ['I', 'Open QR without post number inserted'],
openOptions: ['ctrl+o', 'Open Options'],
close: ['Esc', 'Close Options or QR'],
spoiler: ['ctrl+s', 'Quick spoiler tags'],
sageru: ['alt+n', 'Sage keybind'],
code: ['alt+c', 'Quick code tags'],
submit: ['alt+s', 'Submit post'],
watch: ['w', 'Watch thread'],
update: ['u', 'Update now'],
unreadCountTo0: ['z', 'Mark thread as read'],
expandImage: ['m', 'Expand selected image'],
expandAllImages: ['M', 'Expand all images'],
zero: ['0', 'Jump to page 0'],
nextPage: ['L', 'Jump to the next page'],
previousPage: ['H', 'Jump to the previous page'],
nextThread: ['n', 'See next thread'],
previousThread: ['p', 'See previous thread'],
expandThread: ['e', 'Expand thread'],
openThreadTab: ['o', 'Open thread in current tab'],
openThread: ['O', 'Open thread in new tab'],
nextReply: ['J', 'Select next reply'],
previousReply: ['K', 'Select previous reply'],
hide: ['x', 'Hide thread']
},
updater: {
checkbox: {
'Beep': [false, 'Beep on new post to completely read thread'],
'Scrolling': [false, 'Scroll updated posts into view. Only enabled at bottom of page.'],
'Scroll BG': [false, 'Scroll background tabs'],
'Verbose': [true, 'Show countdown timer, new post count'],
'Auto Update': [true, 'Automatically fetch new posts']
},
'Interval': 30
}
};
Conf = {};
d = document;
g = {};
UI = {
dialog: function(id, position, html) {
var el;
el = d.createElement('div');
el.className = 'reply dialog';
el.innerHTML = html;
el.id = id;
el.style.cssText = localStorage.getItem("" + Main.namespace + id + ".position") || position;
el.querySelector('.move').addEventListener('mousedown', UI.dragstart, false);
return el;
},
dragstart: function(e) {
var el, rect;
e.preventDefault();
UI.el = el = this.parentNode;
d.addEventListener('mousemove', UI.drag, false);
d.addEventListener('mouseup', UI.dragend, false);
rect = el.getBoundingClientRect();
UI.dx = e.clientX - rect.left;
UI.dy = e.clientY - rect.top;
UI.width = d.documentElement.clientWidth - rect.width;
return UI.height = d.documentElement.clientHeight - rect.height;
},
drag: function(e) {
var left, style, top;
left = e.clientX - UI.dx;
top = e.clientY - UI.dy;
left = left < 10 ? '0px' : UI.width - left < 10 ? null : left + 'px';
top = top < 10 ? '0px' : UI.height - top < 10 ? null : top + 'px';
style = UI.el.style;
style.left = left;
style.top = top;
style.right = left === null ? '0px' : null;
return style.bottom = top === null ? '0px' : null;
},
dragend: function() {
localStorage.setItem("" + Main.namespace + UI.el.id + ".position", UI.el.style.cssText);
d.removeEventListener('mousemove', UI.drag, false);
d.removeEventListener('mouseup', UI.dragend, false);
return delete UI.el;
},
hover: function(e) {
var clientHeight, clientWidth, clientX, clientY, height, style, top, _ref;
clientX = e.clientX, clientY = e.clientY;
style = UI.el.style;
_ref = d.documentElement, clientHeight = _ref.clientHeight, clientWidth = _ref.clientWidth;
height = UI.el.offsetHeight;
top = clientY - 120;
style.top = clientHeight <= height || top <= 0 ? '0px' : top + height >= clientHeight ? clientHeight - height + 'px' : top + 'px';
if (clientX <= clientWidth - 400) {
style.left = clientX + 45 + 'px';
return style.right = null;
} else {
style.left = null;
return style.right = clientWidth - clientX + 45 + 'px';
}
},
hoverend: function() {
$.rm(UI.el);
return delete UI.el;
}
};
/*
loosely follows the jquery api:
http://api.jquery.com/
not chainable
*/
$ = function(selector, root) {
if (root == null) {
root = d.body;
}
return root.querySelector(selector);
};
$.extend = function(object, properties) {
var key, val;
for (key in properties) {
val = properties[key];
object[key] = val;
}
};
$.extend($, {
SECOND: 1000,
MINUTE: 1000 * 60,
HOUR: 1000 * 60 * 60,
DAY: 1000 * 60 * 60 * 24,
log: typeof (_base = console.log).bind === "function" ? _base.bind(console) : void 0,
engine: /WebKit|Presto|Gecko/.exec(navigator.userAgent)[0].toLowerCase(),
ready: function(fc) {
var cb;
if (/interactive|complete/.test(d.readyState)) {
return setTimeout(fc);
}
cb = function() {
$.off(d, 'DOMContentLoaded', cb);
return fc();
};
return $.on(d, 'DOMContentLoaded', cb);
},
sync: function(key, cb) {
key = Main.namespace + key;
return $.on(window, 'storage', function(e) {
if (e.key === key) {
return cb(JSON.parse(e.newValue));
}
});
},
id: function(id) {
return d.getElementById(id);
},
formData: function(arg) {
var fd, key, val;
if (arg instanceof HTMLFormElement) {
fd = new FormData(arg);
} else {
fd = new FormData();
for (key in arg) {
val = arg[key];
if (val) {
fd.append(key, val);
}
}
}
return fd;
},
ajax: function(url, callbacks, opts) {
var form, headers, key, r, type, upCallbacks, val;
if (opts == null) {
opts = {};
}
type = opts.type, headers = opts.headers, upCallbacks = opts.upCallbacks, form = opts.form;
r = new XMLHttpRequest();
type || (type = form && 'post' || 'get');
r.open(type, url, true);
for (key in headers) {
val = headers[key];
r.setRequestHeader(key, val);
}
$.extend(r, callbacks);
$.extend(r.upload, upCallbacks);
if (type === 'post') {
r.withCredentials = true;
}
r.send(form);
return r;
},
cache: function(url, cb) {
var req;
if (req = $.cache.requests[url]) {
if (req.readyState === 4) {
return cb.call(req);
} else {
return req.callbacks.push(cb);
}
} else {
req = $.ajax(url, {
onload: function() {
var _i, _len, _ref, _results;
_ref = this.callbacks;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
cb = _ref[_i];
_results.push(cb.call(this));
}
return _results;
},
onabort: function() {
return delete $.cache.requests[url];
},
onerror: function() {
return delete $.cache.requests[url];
}
});
req.callbacks = [cb];
return $.cache.requests[url] = req;
}
},
cb: {
checked: function() {
$.set(this.name, this.checked);
return Conf[this.name] = this.checked;
},
value: function() {
$.set(this.name, this.value.trim());
return Conf[this.name] = this.value;
}
},
addStyle: function(css) {
var f, style;
style = $.el('style', {
textContent: css
});
f = function() {
var root;
if (root = d.head || d.documentElement) {
return $.add(root, style);
} else {
return setTimeout(f, 20);
}
};
f();
return style;
},
x: function(path, root) {
if (root == null) {
root = d.body;
}
return d.evaluate(path, root, null, 8, null).singleNodeValue;
},
addClass: function(el, className) {
return el.classList.add(className);
},
rmClass: function(el, className) {
return el.classList.remove(className);
},
rm: function(el) {
return el.parentNode.removeChild(el);
},
tn: function(s) {
return d.createTextNode(s);
},
nodes: function(nodes) {
var frag, node, _i, _len;
if (!(nodes instanceof Array)) {
return nodes;
}
frag = d.createDocumentFragment();
for (_i = 0, _len = nodes.length; _i < _len; _i++) {
node = nodes[_i];
frag.appendChild(node);
}
return frag;
},
add: function(parent, children) {
return parent.appendChild($.nodes(children));
},
prepend: function(parent, children) {
return parent.insertBefore($.nodes(children), parent.firstChild);
},
after: function(root, el) {
return root.parentNode.insertBefore($.nodes(el), root.nextSibling);
},
before: function(root, el) {
return root.parentNode.insertBefore($.nodes(el), root);
},
replace: function(root, el) {
return root.parentNode.replaceChild($.nodes(el), root);
},
el: function(tag, properties) {
var el;
el = d.createElement(tag);
if (properties) {
$.extend(el, properties);
}
return el;
},
on: function(el, events, handler) {
var event, _i, _len, _ref;
_ref = events.split(' ');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
event = _ref[_i];
el.addEventListener(event, handler, false);
}
},
off: function(el, events, handler) {
var event, _i, _len, _ref;
_ref = events.split(' ');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
event = _ref[_i];
el.removeEventListener(event, handler, false);
}
},
open: function(url) {
return (GM_openInTab || window.open)(location.protocol + url, '_blank');
},
event: function(event, detail, root) {
if (root == null) {
root = d;
}
if ((detail != null) && typeof cloneInto === 'function') {
detail = cloneInto(detail, document.defaultView);
}
return root.dispatchEvent(new CustomEvent(event, {
bubbles: true,
detail: detail
}));
},
globalEval: function(code) {
var script;
script = $.el('script', {
textContent: code
});
$.add(d.head, script);
return $.rm(script);
},
bytesToString: function(size) {
var unit;
unit = 0;
while (size >= 1024) {
size /= 1024;
unit++;
}
size = unit > 1 ? Math.round(size * 100) / 100 : Math.round(size);
return "" + size + " " + ['B', 'KB', 'MB', 'GB'][unit];
},
debounce: function(wait, fn) {
var timeout;
timeout = null;
return function() {
if (timeout) {
clearTimeout(timeout);
} else {
fn.apply(this, arguments);
}
return timeout = setTimeout((function() {
return timeout = null;
}), wait);
};
}
});
$.cache.requests = {};
$.extend($, typeof GM_deleteValue !== "undefined" && GM_deleteValue !== null ? {
"delete": function(name) {
name = Main.namespace + name;
return GM_deleteValue(name);
},
get: function(name, defaultValue) {
var value;
name = Main.namespace + name;
if (value = GM_getValue(name)) {
return JSON.parse(value);
} else {
return defaultValue;
}
},
set: function(name, value) {
name = Main.namespace + name;
localStorage.setItem(name, JSON.stringify(value));
return GM_setValue(name, JSON.stringify(value));
}
} : {
"delete": function(name) {
return localStorage.removeItem(Main.namespace + name);
},
get: function(name, defaultValue) {
var value;
if (value = localStorage.getItem(Main.namespace + name)) {
return JSON.parse(value);
} else {
return defaultValue;
}
},
set: function(name, value) {
return localStorage.setItem(Main.namespace + name, JSON.stringify(value));
}
});
$$ = function(selector, root) {
if (root == null) {
root = d.body;
}
return Array.prototype.slice.call(root.querySelectorAll(selector));
};
Filter = {
filters: {},
init: function() {
var boards, err, filter, hl, key, op, regexp, stub, top, _i, _len, _ref, _ref1, _ref2, _ref3, _ref4;
for (key in Config.filter) {
this.filters[key] = [];
_ref = Conf[key].split('\n');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
filter = _ref[_i];
if (filter[0] === '#') {
continue;
}
if (!(regexp = filter.match(/\/(.+)\/(\w*)/))) {
continue;
}
filter = filter.replace(regexp[0], '');
boards = ((_ref1 = filter.match(/boards:([^;]+)/)) != null ? _ref1[1].toLowerCase() : void 0) || 'global';
if (boards !== 'global' && boards.split(',').indexOf(g.BOARD) === -1) {
continue;
}
if (key === 'md5') {
regexp = regexp[1];
} else {
try {
regexp = RegExp(regexp[1], regexp[2]);
} catch (_error) {
err = _error;
alert(err.message);
continue;
}
}
op = ((_ref2 = filter.match(/[^t]op:(yes|no|only)/)) != null ? _ref2[1] : void 0) || 'no';
stub = (function() {
var _ref3;
switch ((_ref3 = filter.match(/stub:(yes|no)/)) != null ? _ref3[1] : void 0) {
case 'yes':
return true;
case 'no':
return false;
default:
return Conf['Show Stubs'];
}
})();
if (hl = /highlight/.test(filter)) {
hl = ((_ref3 = filter.match(/highlight:(\w+)/)) != null ? _ref3[1] : void 0) || 'filter_highlight';
top = ((_ref4 = filter.match(/top:(yes|no)/)) != null ? _ref4[1] : void 0) || 'yes';
top = top === 'yes';
}
this.filters[key].push(this.createFilter(regexp, op, stub, hl, top));
}
if (!this.filters[key].length) {
delete this.filters[key];
}
}
if (Object.keys(this.filters).length) {
return Main.callbacks.push(this.node);
}
},
createFilter: function(regexp, op, stub, hl, top) {
var settings, test;
test = typeof regexp === 'string' ? function(value) {
return regexp === value;
} : function(value) {
return regexp.test(value);
};
settings = {
hide: !hl,
stub: stub,
"class": hl,
top: top
};
return function(value, isOP) {
if (isOP && op === 'no' || !isOP && op === 'only') {
return false;
}
if (!test(value)) {
return false;
}
return settings;
};
},
node: function(post) {
var filter, firstThread, isOP, key, result, root, thisThread, value, _i, _len, _ref;
if (post.isInlined) {
return;
}
isOP = post.ID === post.threadID;
root = post.root;
for (key in Filter.filters) {
value = Filter[key](post);
if (value === false) {
continue;
}
_ref = Filter.filters[key];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
filter = _ref[_i];
if (!(result = filter(value, isOP))) {
continue;
}
if (result.hide) {
if (isOP) {
if (!g.REPLY) {
ThreadHiding.hide(root.parentNode, result.stub);
} else {
continue;
}
} else {
ReplyHiding.hide(root, result.stub);
}
return;
}
$.addClass(root, result["class"]);
if (isOP && result.top && !g.REPLY) {
thisThread = root.parentNode;
if (firstThread = $('div[class="postContainer opContainer"]')) {
if (firstThread !== root) {
$.before(firstThread.parentNode, [thisThread, thisThread.nextElementSibling]);
}
}
}
}
}
},
name: function(post) {
return $('.name', post.el).textContent;
},
uniqueid: function(post) {
var uid;
if (uid = $('.posteruid', post.el)) {
return uid.firstElementChild.textContent;
}
return false;
},
tripcode: function(post) {
var trip;
if (trip = $('.postertrip', post.el)) {
return trip.textContent;
}
return false;
},
mod: function(post) {
var mod;
if (mod = $('.capcode.hand', post.el)) {
return mod.textContent.replace('## ', '');
}
return false;
},
subject: function(post) {
var subject;
if (subject = $('.postInfo .subject', post.el)) {
return subject.textContent;
}
return false;
},
comment: function(post) {
var data, i, nodes, text, _i, _ref;
text = [];
nodes = d.evaluate('.//br|.//text()', post.blockquote, null, 7, null);
for (i = _i = 0, _ref = nodes.snapshotLength; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
text.push((data = nodes.snapshotItem(i).data) ? data : '\n');
}
return text.join('');
},
country: function(post) {
var flag;
if (flag = $('.flag', post.el)) {
return flag.title;
}
return false;
},
filename: function(post) {
var file, fileInfo, fname;
fileInfo = post.fileInfo;
if (fileInfo) {
if (file = $('.fileText > span', fileInfo)) {
return file.title;
} else {
fname = fileInfo.firstElementChild.childNodes[1] || fileInfo.firstElementChild.childNodes[0];
return fname.textContent;
}
}
return false;
},
dimensions: function(post) {
var fileInfo, match;
fileInfo = post.fileInfo;
if (fileInfo && (match = fileInfo.childNodes[1].textContent.match(/\d+x\d+/))) {
return match[0];
}
return false;
},
filesize: function(post) {
var img;
img = post.img;
if (img) {
return img.alt;
}
return false;
},
md5: function(post) {
var img;
img = post.img;
if (img) {
return img.dataset.md5;
}
return false;
},
menuInit: function() {
var div, entry, type, _i, _len, _ref;
div = $.el('div', {
textContent: 'Filter'
});
entry = {
el: div,
open: function() {
return true;
},
children: []
};
_ref = [['Name', 'name'], ['Unique ID', 'uniqueid'], ['Tripcode', 'tripcode'], ['Admin/Mod', 'mod'], ['Subject', 'subject'], ['Comment', 'comment'], ['Country', 'country'], ['Filename', 'filename'], ['Image dimensions', 'dimensions'], ['Filesize', 'filesize'], ['Image MD5', 'md5']];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
type = _ref[_i];
entry.children.push(Filter.createSubEntry(type[0], type[1]));
}
return Menu.addEntry(entry);
},
createSubEntry: function(text, type) {
var el, onclick, open;
el = $.el('a', {
href: 'javascript:;',
textContent: text
});
onclick = null;
open = function(post) {
var value;
value = Filter[type](post);
if (value === false) {
return false;
}
$.off(el, 'click', onclick);
onclick = function() {
var re, save, select, ta, tl;
re = type === 'md5' ? value : value.replace(/\/|\\|\^|\$|\n|\.|\(|\)|\{|\}|\[|\]|\?|\*|\+|\|/g, function(c) {
if (c === '\n') {
return '\\n';
} else if (c === '\\') {
return '\\\\';
} else {
return "\\" + c;
}
});
re = type === 'md5' ? "/" + value + "/" : "/^" + re + "$/";
if (/\bop\b/.test(post["class"])) {
re += ';op:yes';
}
save = (save = $.get(type, '')) ? "" + save + "\n" + re : re;
$.set(type, save);
Options.dialog();
select = $('select[name=filter]', $.id('options'));
select.value = type;
select.dispatchEvent(new Event('change'));
$.id('filter_tab').checked = true;
ta = select.nextElementSibling;
tl = ta.textLength;
ta.setSelectionRange(tl, tl);
return ta.focus();
};
$.on(el, 'click', onclick);
return true;
};
return {
el: el,
open: open
};
}
};
StrikethroughQuotes = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var el, quote, show_stub, _i, _len, _ref;
if (post.isInlined) {
return;
}
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (!((el = $.id(quote.hash.slice(1))) && quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname) && el.hidden)) {
continue;
}
$.addClass(quote, 'filtered');
if (Conf['Recursive Filtering'] && post.ID !== post.threadID) {
show_stub = !!$.x('preceding-sibling::div[contains(@class,"stub")]', el);
ReplyHiding.hide(post.root, show_stub);
}
}
}
};
ExpandComment = {
init: function() {
var a, _i, _len, _ref;
_ref = $$('.abbr');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
a = _ref[_i];
$.on(a.firstElementChild, 'click', ExpandComment.expand);
}
},
expand: function(e) {
var a, replyID, threadID, _, _ref;
e.preventDefault();
_ref = this.href.match(/(\d+)#p(\d+)/), _ = _ref[0], threadID = _ref[1], replyID = _ref[2];
this.textContent = "Loading No." + replyID + "...";
a = this;
return $.cache("//a.4cdn.org" + this.pathname + ".json", function() {
return ExpandComment.parse(this, a, threadID, replyID);
});
},
parse: function(req, a, threadID, replyID) {
var bq, clone, href, post, posts, quote, quotes, spoilerRange, _i, _j, _len, _len1;
if (req.status !== 200) {
a.textContent = "" + req.status + " " + req.statusText;
return;
}
posts = JSON.parse(req.response).posts;
if (spoilerRange = posts[0].custom_spoiler) {
Build.spoilerRange[g.BOARD] = spoilerRange;
}
replyID = +replyID;
for (_i = 0, _len = posts.length; _i < _len; _i++) {
post = posts[_i];
if (post.no === replyID) {
break;
}
}
if (post.no !== replyID) {
a.textContent = 'No.#{replyID} not found.';
return;
}
bq = $.id("m" + replyID);
clone = bq.cloneNode(false);
clone.innerHTML = post.com;
quotes = clone.getElementsByClassName('quotelink');
for (_j = 0, _len1 = quotes.length; _j < _len1; _j++) {
quote = quotes[_j];
href = quote.getAttribute('href');
if (href[0] === '/') {
continue;
}
quote.href = "thread/" + href;
}
post = {
blockquote: clone,
threadID: threadID,
quotes: quotes,
backlinks: []
};
if (Conf['Resurrect Quotes']) {
Quotify.node(post);
}
if (Conf['Quote Preview']) {
QuotePreview.node(post);
}
if (Conf['Quote Inline']) {
QuoteInline.node(post);
}
if (Conf['Indicate OP quote']) {
QuoteOP.node(post);
}
if (Conf['Indicate You quote']) {
QuoteYou.node(post);
}
if (Conf['Indicate Cross-thread Quotes']) {
QuoteCT.node(post);
}
$.replace(bq, clone);
return Main.prettify(clone);
}
};
ExpandThread = {
init: function() {
var a, span, _i, _len, _ref, _results;
_ref = $$('.summary');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
span = _ref[_i];
a = $.el('a', {
textContent: "+ " + span.textContent,
className: 'summary desktop',
href: 'javascript:;'
});
$.on(a, 'click', function() {
return ExpandThread.toggle(this.parentNode);
});
_results.push($.replace(span, a));
}
return _results;
},
toggle: function(thread) {
var a, num, replies, reply, url, _i, _len;
url = "//a.4cdn.org/" + g.BOARD + "/thread/" + thread.id.slice(1) + ".json";
a = $('.summary', thread);
switch (a.textContent[0]) {
case '+':
a.textContent = a.textContent.replace('+', '× Loading...');
$.cache(url, function() {
return ExpandThread.parse(this, thread, a);
});
break;
case '×':
a.textContent = a.textContent.replace('× Loading...', '+');
$.cache.requests[url].abort();
break;
case '-':
a.textContent = a.textContent.replace('-', '+');
num = (function() {
switch (g.BOARD) {
case 'b':
case 'vg':
return 3;
case 't':
return 1;
default:
return 5;
}
})();
replies = $$('.replyContainer', thread);
replies.splice(replies.length - num, num);
for (_i = 0, _len = replies.length; _i < _len; _i++) {
reply = replies[_i];
$.rm(reply);
}
}
},
parse: function(req, thread, a) {
var backlink, id, link, nodes, post, posts, replies, reply, spoilerRange, threadID, _i, _j, _k, _len, _len1, _len2, _ref, _ref1;
if (req.status !== 200) {
a.textContent = "" + req.status + " " + req.statusText;
$.off(a, 'click', ExpandThread.cb.toggle);
return;
}
a.textContent = a.textContent.replace('× Loading...', '-');
posts = JSON.parse(req.response).posts;
if (spoilerRange = posts[0].custom_spoiler) {
Build.spoilerRange[g.BOARD] = spoilerRange;
}
replies = posts.slice(1);
threadID = thread.id.slice(1);
nodes = [];
for (_i = 0, _len = replies.length; _i < _len; _i++) {
reply = replies[_i];
post = Build.postFromObject(reply, g.BOARD);
id = reply.no;
link = $('a[title="Link to this post"]', post);
link.href = "thread/" + threadID + "#p" + id;
link.nextSibling.href = "thread/" + threadID + "#q" + id;
nodes.push(post);
}
_ref = $$('.summary ~ .replyContainer', a.parentNode);
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
post = _ref[_j];
$.rm(post);
}
_ref1 = $$('.backlink', a.previousElementSibling);
for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
backlink = _ref1[_k];
if (!$.id(backlink.hash.slice(1))) {
$.rm(backlink);
}
}
return $.after(a, nodes);
}
};
ThreadHiding = {
init: function() {
var a, hiddenThreads, thread, _i, _len, _ref;
hiddenThreads = ThreadHiding.sync();
if (g.CATALOG) {
return;
}
_ref = $$('.thread');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
thread = _ref[_i];
a = $.el('a', {
className: 'hide_thread_button',
innerHTML: '<span>[ - ]</span>',
href: 'javascript:;'
});
$.on(a, 'click', ThreadHiding.cb);
$.prepend(thread, a);
if (thread.id.slice(1) in hiddenThreads) {
ThreadHiding.hide(thread);
}
}
},
sync: function() {
var hiddenThreads, hiddenThreadsCatalog, id;
hiddenThreads = $.get("hiddenThreads/" + g.BOARD + "/", {});
hiddenThreadsCatalog = JSON.parse(localStorage.getItem("4chan-hide-t-" + g.BOARD)) || {};
if (g.CATALOG) {
for (id in hiddenThreads) {
hiddenThreadsCatalog[id] = true;
}
localStorage.setItem("4chan-hide-t-" + g.BOARD, JSON.stringify(hiddenThreadsCatalog));
} else {
for (id in hiddenThreadsCatalog) {
if (!(id in hiddenThreads)) {
hiddenThreads[id] = Date.now();
}
}
$.set("hiddenThreads/" + g.BOARD + "/", hiddenThreads);
}
return hiddenThreads;
},
cb: function() {
return ThreadHiding.toggle($.x('ancestor::div[parent::div[@class="board"]]', this));
},
toggle: function(thread) {
var hiddenThreads, id;
hiddenThreads = $.get("hiddenThreads/" + g.BOARD + "/", {});
id = thread.id.slice(1);
if (thread.hidden || /\bhidden_thread\b/.test(thread.firstChild.className)) {
ThreadHiding.show(thread);
delete hiddenThreads[id];
} else {
ThreadHiding.hide(thread);
hiddenThreads[id] = Date.now();
}
return $.set("hiddenThreads/" + g.BOARD + "/", hiddenThreads);
},
hide: function(thread, show_stub) {
var a, menuButton, num, opInfo, span, stub, text;
if (show_stub == null) {
show_stub = Conf['Show Stubs'];
}
if (!show_stub) {
thread.hidden = true;
thread.nextElementSibling.hidden = true;
return;
}
if (/\bhidden_thread\b/.test(thread.firstChild.className)) {
return;
}
num = 0;
if (span = $('.summary', thread)) {
num = Number(span.textContent.match(/\d+/));
}
num += $$('.opContainer ~ .replyContainer', thread).length;
text = num === 1 ? '1 reply' : "" + num + " replies";
opInfo = $('.desktop > .nameBlock', thread).textContent;
stub = $.el('div', {
className: 'hide_thread_button hidden_thread',
innerHTML: '<a href="javascript:;"><span>[ + ]</span> </a>'
});
a = stub.firstChild;
$.on(a, 'click', ThreadHiding.cb);
$.add(a, $.tn("" + opInfo + " (" + text + ")"));
if (Conf['Menu']) {
menuButton = Menu.a.cloneNode(true);
$.on(menuButton, 'click', Menu.toggle);
$.add(stub, [$.tn(' '), menuButton]);
}
return $.prepend(thread, stub);
},
show: function(thread) {
var stub;
if (stub = $('.hidden_thread', thread)) {
$.rm(stub);
}
thread.hidden = false;
return thread.nextElementSibling.hidden = false;
}
};
ReplyHiding = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var side;
if (post.isInlined || post.ID === post.threadID) {
return;
}
side = $('.sideArrows', post.root);
$.addClass(side, 'hide_reply_button');
side.innerHTML = '<a href="javascript:;"><span>[ - ]</span></a>';
$.on(side.firstChild, 'click', ReplyHiding.toggle);
if (post.ID in g.hiddenReplies) {
return ReplyHiding.hide(post.root);
}
},
toggle: function() {
var button, id, quote, quotes, root, _i, _j, _len, _len1;
button = this.parentNode;
root = button.parentNode;
id = root.id.slice(2);
quotes = $$(".quotelink[href$='#p" + id + "'], .backlink[href$='#p" + id + "']");
if (/\bstub\b/.test(button.className)) {
ReplyHiding.show(root);
for (_i = 0, _len = quotes.length; _i < _len; _i++) {
quote = quotes[_i];
$.rmClass(quote, 'filtered');
}
delete g.hiddenReplies[id];
} else {
ReplyHiding.hide(root);
for (_j = 0, _len1 = quotes.length; _j < _len1; _j++) {
quote = quotes[_j];
$.addClass(quote, 'filtered');
}
g.hiddenReplies[id] = Date.now();
}
return $.set("hiddenReplies/" + g.BOARD + "/", g.hiddenReplies);
},
hide: function(root, show_stub) {
var a, el, menuButton, side, stub;
if (show_stub == null) {
show_stub = Conf['Show Stubs'];
}
side = $('.sideArrows', root);
if (side.hidden) {
return;
}
side.hidden = true;
el = side.nextElementSibling;
el.hidden = true;
if (!show_stub) {
return;
}
stub = $.el('div', {
className: 'hide_reply_button stub',
innerHTML: '<a href="javascript:;"><span>[ + ]</span> </a>'
});
a = stub.firstChild;
$.on(a, 'click', ReplyHiding.toggle);
$.add(a, $.tn(Conf['Anonymize'] ? 'Anonymous' : $('.desktop > .nameBlock', el).textContent));
if (Conf['Menu']) {
menuButton = Menu.a.cloneNode(true);
$.on(menuButton, 'click', Menu.toggle);
$.add(stub, [$.tn(' '), menuButton]);
}
return $.prepend(root, stub);
},
show: function(root) {
var stub;
if (stub = $('.stub', root)) {
$.rm(stub);
}
$('.sideArrows', root).hidden = false;
return $('.post', root).hidden = false;
}
};
Menu = {
entries: [],
init: function() {
this.a = $.el('a', {
className: 'menu_button',
href: 'javascript:;',
innerHTML: '[<span></span>]'
});
this.el = $.el('div', {
className: 'reply dialog',
id: 'menu',
tabIndex: 0
});
$.on(this.el, 'click', function(e) {
return e.stopPropagation();
});
$.on(this.el, 'keydown', this.keybinds);
$.on(d, 'AddMenuEntry', function(e) {
return Menu.addEntry(e.detail);
});
return Main.callbacks.push(this.node);
},
node: function(post) {
var a;
if (post.isInlined && !post.isCrosspost) {
a = $('.menu_button', post.el);
} else {
a = Menu.a.cloneNode(true);
$.add($('.postInfo', post.el), [$.tn('\u00A0'), a]);
}
return $.on(a, 'click', Menu.toggle);
},
toggle: function(e) {
var lastOpener, post;
e.preventDefault();
e.stopPropagation();
if (Menu.el.parentNode) {
lastOpener = Menu.lastOpener;
Menu.close();
if (lastOpener === this) {
return;
}
}
Menu.lastOpener = this;
post = /\bhidden_thread\b/.test(this.parentNode.className) ? $.x('ancestor::div[parent::div[@class="board"]]/child::div[contains(@class,"opContainer")]', this) : $.x('ancestor::div[contains(@class,"postContainer")][1]', this);
return Menu.open(this, Main.preParse(post));
},
open: function(button, post) {
var bLeft, bRect, bTop, el, entry, funk, mRect, _i, _len, _ref;
el = Menu.el;
el.setAttribute('data-id', post.ID);
el.setAttribute('data-rootid', post.root.id);
funk = function(entry, parent) {
var child, children, subMenu, _i, _len;
children = entry.children;
if (!entry.open(post)) {
return;
}
$.add(parent, entry.el);
if (!children) {
return;
}
if (subMenu = $('.subMenu', entry.el)) {
$.rm(subMenu);
}
subMenu = $.el('div', {
className: 'reply dialog subMenu'
});
$.add(entry.el, subMenu);
for (_i = 0, _len = children.length; _i < _len; _i++) {
child = children[_i];
funk(child, subMenu);
}
};
_ref = Menu.entries;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
entry = _ref[_i];
funk(entry, el);
}
Menu.focus($('.entry', Menu.el));
$.on(d, 'click', Menu.close);
$.add(d.body, el);
mRect = el.getBoundingClientRect();
bRect = button.getBoundingClientRect();
bTop = d.documentElement.scrollTop + d.body.scrollTop + bRect.top;
bLeft = d.documentElement.scrollLeft + d.body.scrollLeft + bRect.left;
el.style.top = bRect.top + bRect.height + mRect.height < d.documentElement.clientHeight ? bTop + bRect.height + 2 + 'px' : bTop - mRect.height - 2 + 'px';
el.style.left = bRect.left + mRect.width < d.documentElement.clientWidth ? bLeft + 'px' : bLeft + bRect.width - mRect.width + 'px';
return el.focus();
},
close: function() {
var el, focused, _i, _len, _ref;
el = Menu.el;
$.rm(el);
_ref = $$('.focused.entry', el);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
focused = _ref[_i];
$.rmClass(focused, 'focused');
}
el.innerHTML = null;
el.removeAttribute('style');
delete Menu.lastOpener;
delete Menu.focusedEntry;
return $.off(d, 'click', Menu.close);
},
keybinds: function(e) {
var el, next, subMenu;
el = Menu.focusedEntry;
switch (Keybinds.keyCode(e) || e.keyCode) {
case 'Esc':
Menu.lastOpener.focus();
Menu.close();
break;
case 13:
case 32:
el.click();
break;
case 'Up':
if (next = el.previousElementSibling) {
Menu.focus(next);
}
break;
case 'Down':
if (next = el.nextElementSibling) {
Menu.focus(next);
}
break;
case 'Right':
if ((subMenu = $('.subMenu', el)) && (next = subMenu.firstElementChild)) {
Menu.focus(next);
}
break;
case 'Left':
if (next = $.x('parent::*[contains(@class,"subMenu")]/parent::*', el)) {
Menu.focus(next);
}
break;
default:
return;
}
e.preventDefault();
return e.stopPropagation();
},
focus: function(el) {
var focused, _i, _len, _ref;
if (focused = $.x('parent::*/child::*[contains(@class,"focused")]', el)) {
$.rmClass(focused, 'focused');
}
_ref = $$('.focused', el);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
focused = _ref[_i];
$.rmClass(focused, 'focused');
}
Menu.focusedEntry = el;
return $.addClass(el, 'focused');
},
addEntry: function(entry) {
var funk;
funk = function(entry) {
var child, children, el, _i, _len;
el = entry.el, children = entry.children;
$.addClass(el, 'entry');
$.on(el, 'focus mouseover', function(e) {
e.stopPropagation();
return Menu.focus(this);
});
if (!children) {
return;
}
$.addClass(el, 'hasSubMenu');
for (_i = 0, _len = children.length; _i < _len; _i++) {
child = children[_i];
funk(child);
}
};
funk(entry);
return Menu.entries.push(entry);
}
};
Keybinds = {
init: function() {
var node, _i, _len, _ref;
_ref = $$('[accesskey]');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
node.removeAttribute('accesskey');
}
return $.on(d, 'keydown', Keybinds.keydown);
},
keydown: function(e) {
var form, key, o, target, thread;
if (!(key = Keybinds.keyCode(e))) {
return;
}
target = e.target;
if (/TEXTAREA|INPUT/.test(target.nodeName)) {
if (!((key === 'Esc') || (/\+/.test(key)))) {
return;
}
}
thread = Nav.getThread();
switch (key) {
case Conf.openQR:
Keybinds.qr(thread, true);
break;
case Conf.openEmptyQR:
Keybinds.qr(thread);
break;
case Conf.openOptions:
if (!$.id('overlay')) {
Options.dialog();
}
break;
case Conf.close:
if (o = $.id('overlay')) {
Options.close.call(o);
} else if (QR.el) {
QR.close();
}
break;
case Conf.submit:
if (QR.el && !QR.status()) {
QR.submit();
}
break;
case Conf.spoiler:
if (target.nodeName !== 'TEXTAREA') {
return;
}
Keybinds.tags('spoiler', target);
break;
case Conf.code:
if (target.nodeName !== 'TEXTAREA') {
return;
}
Keybinds.tags('code', target);
break;
case Conf.sageru:
$("[name=email]", QR.el).value = "sage";
QR.selected.email = "sage";
break;
case Conf.watch:
Watcher.toggle(thread);
break;
case Conf.update:
Updater.update();
break;
case Conf.unreadCountTo0:
Unread.replies = [];
Unread.update(true);
break;
case Conf.expandImage:
Keybinds.img(thread);
break;
case Conf.expandAllImages:
Keybinds.img(thread, true);
break;
case Conf.zero:
window.location = "/" + g.BOARD + "/0#delform";
break;
case Conf.nextPage:
if (form = $('.next form')) {
window.location = form.action;
}
break;
case Conf.previousPage:
if (form = $('.prev form')) {
window.location = form.action;
}
break;
case Conf.nextThread:
if (g.REPLY) {
return;
}
Nav.scroll(+1);
break;
case Conf.previousThread:
if (g.REPLY) {
return;
}
Nav.scroll(-1);
break;
case Conf.expandThread:
ExpandThread.toggle(thread);
break;
case Conf.openThread:
Keybinds.open(thread);
break;
case Conf.openThreadTab:
Keybinds.open(thread, true);
break;
case Conf.nextReply:
Keybinds.hl(+1, thread);
break;
case Conf.previousReply:
Keybinds.hl(-1, thread);
break;
case Conf.hide:
if (/\bthread\b/.test(thread.className)) {
ThreadHiding.toggle(thread);
}
break;
default:
return;
}
return e.preventDefault();
},
keyCode: function(e) {
var c, kc, key;
key = (function() {
switch (kc = e.keyCode) {
case 8:
return '';
case 13:
return 'Enter';
case 27:
return 'Esc';
case 37:
return 'Left';
case 38:
return 'Up';
case 39:
return 'Right';
case 40:
return 'Down';
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
case 65:
case 66:
case 67:
case 68:
case 69:
case 70:
case 71:
case 72:
case 73:
case 74:
case 75:
case 76:
case 77:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 86:
case 87:
case 88:
case 89:
case 90:
c = String.fromCharCode(kc);
if (e.shiftKey) {
return c;
} else {
return c.toLowerCase();
}
break;
default:
return null;
}
})();
if (key) {
if (e.altKey) {
key = 'alt+' + key;
}
if (e.ctrlKey) {
key = 'ctrl+' + key;
}
if (e.metaKey) {
key = 'meta+' + key;
}
}
return key;
},
tags: function(tag, ta) {
var range, selEnd, selStart, value;
value = ta.value;
selStart = ta.selectionStart;
selEnd = ta.selectionEnd;
ta.value = value.slice(0, selStart) + ("[" + tag + "]") + value.slice(selStart, selEnd) + ("[/" + tag + "]") + value.slice(selEnd);
range = ("[" + tag + "]").length + selEnd;
ta.setSelectionRange(range, range);
return ta.dispatchEvent(new Event('input'));
},
img: function(thread, all) {
var thumb;
if (all) {
return $.id('imageExpand').click();
} else {
thumb = $('img[data-md5]', $('.post.highlight', thread) || thread);
return ImageExpand.toggle(thumb.parentNode);
}
},
qr: function(thread, quote) {
if (quote) {
QR.quote.call($('a[title="Reply to this post"]', $('.post.highlight', thread) || thread));
} else {
QR.open();
}
return $('textarea', QR.el).focus();
},
open: function(thread, tab) {
var id, url;
if (g.REPLY) {
return;
}
id = thread.id.slice(1);
url = "//boards.4chan.org/" + g.BOARD + "/thread/" + id;
if (tab) {
return $.open(url);
} else {
return location.href = url;
}
},
hl: function(delta, thread) {
var next, post, rect, replies, reply, _i, _len;
if (post = $('.reply.highlight', thread)) {
$.rmClass(post, 'highlight');
post.removeAttribute('tabindex');
rect = post.getBoundingClientRect();
if (rect.bottom >= 0 && rect.top <= d.documentElement.clientHeight) {
next = $.x('child::div[contains(@class,"post reply")]', delta === +1 ? post.parentNode.nextElementSibling : post.parentNode.previousElementSibling);
if (!next) {
this.focus(post);
return;
}
if (!(g.REPLY || $.x('ancestor::div[parent::div[@class="board"]]', next) === thread)) {
return;
}
rect = next.getBoundingClientRect();
if (rect.top < 0 || rect.bottom > d.documentElement.clientHeight) {
next.scrollIntoView(delta === -1);
}
this.focus(next);
return;
}
}
replies = $$('.reply', thread);
if (delta === -1) {
replies.reverse();
}
for (_i = 0, _len = replies.length; _i < _len; _i++) {
reply = replies[_i];
rect = reply.getBoundingClientRect();
if (delta === +1 && rect.top >= 0 || delta === -1 && rect.bottom <= d.documentElement.clientHeight) {
this.focus(reply);
return;
}
}
},
focus: function(post) {
$.addClass(post, 'highlight');
post.tabIndex = 0;
return post.focus();
}
};
Nav = {
init: function() {
var next, prev, span;
span = $.el('span', {
id: 'navlinks'
});
prev = $.el('a', {
textContent: '▲',
href: 'javascript:;'
});
next = $.el('a', {
textContent: '▼',
href: 'javascript:;'
});
openQR = $.el('a', {
textContent: 'QR',
href: 'javascript:;'
});
$.on(prev, 'click', this.prev);
$.on(next, 'click', this.next);
$.on(openQR, 'click', this.openQR);
$.add(span, [openQR, $.tn(' '), prev, $.tn(' '), next]);
return $.add(d.body, span);
},
prev: function() {
if (g.REPLY) {
return window.scrollTo(0, 0);
} else {
return Nav.scroll(-1);
}
},
next: function() {
if (g.REPLY) {
return window.scrollTo(0, d.body.scrollHeight);
} else {
return Nav.scroll(+1);
}
},
openQR: function() {
QR.open();
if (!g.REPLY) {
QR.threadSelector.value = g.BOARD === 'f' ? '9999' : 'new';
}
return $('textarea', QR.el).focus();
},
getThread: function(full) {
var bottom, i, rect, thread, _i, _len, _ref;
Nav.threads = $$('.thread:not([hidden])');
_ref = Nav.threads;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
thread = _ref[i];
rect = thread.getBoundingClientRect();
bottom = rect.bottom;
if (bottom > 0) {
if (full) {
return [thread, i, rect];
}
return thread;
}
}
return $('.board');
},
scroll: function(delta) {
var i, rect, thread, top, _ref, _ref1;
_ref = Nav.getThread(true), thread = _ref[0], i = _ref[1], rect = _ref[2];
top = rect.top;
if (!((delta === -1 && Math.ceil(top) < 0) || (delta === +1 && top > 1))) {
i += delta;
}
top = (_ref1 = Nav.threads[i]) != null ? _ref1.getBoundingClientRect().top : void 0;
return window.scrollBy(0, top);
}
};
QR = {
mimeTypes: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/x-shockwave-flash', 'video/webm', ''],
init: function() {
if (!$.id('postForm')) {
return;
}
Main.callbacks.push(this.node);
return setTimeout(this.asyncInit);
},
asyncInit: function() {
var link;
if (Conf['Hide Original Post Form']) {
link = $.el('h1', {
innerHTML: "<a href=javascript:;>" + (g.REPLY ? 'Reply to Thread' : 'Start a Thread') + "</a>"
});
$.on(link.firstChild, 'click', function() {
QR.open();
if (!g.REPLY) {
QR.threadSelector.value = g.BOARD === 'f' ? '9999' : 'new';
}
return $('textarea', QR.el).focus();
});
$.before($.id('postForm'), link);
$.id('postForm').style.display = "none";
$.id('togglePostFormLink').style.display = "none";
}
if (Conf['Persistent QR']) {
QR.dialog();
if (Conf['Auto Hide QR']) {
QR.hide();
}
}
$.on(d, 'dragover', QR.dragOver);
$.on(d, 'drop', QR.dropFile);
return $.on(d, 'dragstart dragend', QR.drag);
},
node: function(post) {
return $.on($('a[title="Reply to this post"]', $('.postInfo', post.el)), 'click', QR.quote);
},
open: function() {
if (QR.el) {
QR.el.hidden = false;
return QR.unhide();
} else {
return QR.dialog();
}
},
close: function() {
var i, spoiler, _i, _len, _ref;
QR.el.hidden = true;
QR.abort();
d.activeElement.blur();
$.rmClass(QR.el, 'dump');
_ref = QR.replies;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
i = _ref[_i];
QR.replies[0].rm();
}
QR.cooldown.auto = false;
QR.status();
QR.resetFileInput();
if (!Conf['Remember Spoiler'] && (spoiler = $.id('spoiler')).checked) {
spoiler.click();
}
return QR.cleanError();
},
hide: function() {
d.activeElement.blur();
$.addClass(QR.el, 'autohide');
return $.id('autohide').checked = true;
},
unhide: function() {
$.rmClass(QR.el, 'autohide');
return $.id('autohide').checked = false;
},
toggleHide: function() {
return this.checked && QR.hide() || QR.unhide();
},
error: function(err) {
var el;
el = $('.warning', QR.el);
if (typeof err === 'string') {
el.textContent = err;
} else {
el.innerHTML = null;
$.add(el, err);
}
QR.open();
if (d.hidden) {
return alert(el.textContent);
}
},
cleanError: function() {
return $('.warning', QR.el).textContent = null;
},
status: function(data) {
var disabled, input, value;
if (data == null) {
data = {};
}
if (!QR.el) {
return;
}
if (g.dead) {
value = 404;
disabled = true;
QR.cooldown.auto = false;
}
value = data.progress || QR.cooldown.seconds || value;
input = QR.status.input;
input.value = QR.cooldown.auto && Conf['Cooldown'] ? value ? "Auto " + value : 'Auto' : value || 'Submit';
return input.disabled = disabled || false;
},
cooldown: {
init: function() {
if (!Conf['Cooldown']) {
return;
}
QR.cooldown.types = {
thread: (function() {
switch (g.BOARD) {
case 'jp':
return 3600;
case 'b':
case 'soc':
case 'r9k':
return 600;
default:
return 300;
}
})(),
sage: 60,
file: g.BOARD === 'vg' ? 120 : 60,
post: g.BOARD === 'vg' ? 90 : 60
};
QR.cooldown.cooldowns = $.get("" + g.BOARD + ".cooldown", {});
QR.cooldown.start();
return $.sync("" + g.BOARD + ".cooldown", QR.cooldown.sync);
},
start: function() {
if (QR.cooldown.isCounting) {
return;
}
QR.cooldown.isCounting = true;
return QR.cooldown.count();
},
sync: function(cooldowns) {
var id;
for (id in cooldowns) {
QR.cooldown.cooldowns[id] = cooldowns[id];
}
return QR.cooldown.start();
},
set: function(data) {
var cooldown, hasFile, isReply, isSage, start, type;
if (!Conf['Cooldown']) {
return;
}
start = Date.now();
if (data.delay) {
cooldown = {
delay: data.delay
};
} else {
isSage = /sage/i.test(data.post.email);
hasFile = !!data.post.file;
isReply = data.isReply;
type = !isReply ? 'thread' : isSage ? 'sage' : hasFile ? 'file' : 'post';
cooldown = {
isReply: isReply,
isSage: isSage,
hasFile: hasFile,
timeout: start + QR.cooldown.types[type] * $.SECOND
};
}
QR.cooldown.cooldowns[start] = cooldown;
$.set("" + g.BOARD + ".cooldown", QR.cooldown.cooldowns);
return QR.cooldown.start();
},
unset: function(id) {
delete QR.cooldown.cooldowns[id];
return $.set("" + g.BOARD + ".cooldown", QR.cooldown.cooldowns);
},
count: function() {
var cooldown, cooldowns, elapsed, hasFile, isReply, isSage, now, post, seconds, start, type, types, update, _ref;
if (Object.keys(QR.cooldown.cooldowns).length) {
setTimeout(QR.cooldown.count, 1000);
} else {
$["delete"]("" + g.BOARD + ".cooldown");
delete QR.cooldown.isCounting;
delete QR.cooldown.seconds;
QR.status();
return;
}
if ((isReply = g.REPLY ? true : QR.threadSelector.value !== 'new')) {
post = QR.replies[0];
isSage = /sage/i.test(post.email);
hasFile = !!post.file;
}
now = Date.now();
seconds = null;
_ref = QR.cooldown, types = _ref.types, cooldowns = _ref.cooldowns;
for (start in cooldowns) {
cooldown = cooldowns[start];
if ('delay' in cooldown) {
if (cooldown.delay) {
seconds = Math.max(seconds, cooldown.delay--);
} else {
seconds = Math.max(seconds, 0);
QR.cooldown.unset(start);
}
continue;
}
if (isReply === cooldown.isReply) {
type = !isReply ? 'thread' : isSage && cooldown.isSage ? 'sage' : hasFile && cooldown.hasFile ? 'file' : 'post';
elapsed = Math.floor((now - start) / 1000);
if (elapsed >= 0) {
seconds = Math.max(seconds, types[type] - elapsed);
}
}
if (!((start <= now && now <= cooldown.timeout))) {
QR.cooldown.unset(start);
}
}
update = seconds !== null || !!QR.cooldown.seconds;
QR.cooldown.seconds = seconds;
if (update) {
QR.status();
}
if (seconds === 0 && QR.cooldown.auto) {
return QR.submit();
}
}
},
quote: function(e) {
var caretPos, id, range, s, sel, ta, text, _ref;
if (e != null) {
e.preventDefault();
}
QR.open();
ta = $('textarea', QR.el);
if (!(g.REPLY || ta.value)) {
QR.threadSelector.value = $.x('ancestor::div[parent::div[@class="board"]]', this).id.slice(1);
}
id = this.previousSibling.hash.slice(2);
text = ">>" + id + "\n";
sel = d.getSelection();
if ((s = sel.toString().trim()) && id === ((_ref = $.x('ancestor-or-self::blockquote', sel.anchorNode)) != null ? _ref.id.match(/\d+$/)[0] : void 0)) {
s = s.replace(/\n/g, '\n>');
text += ">" + s + "\n";
}
caretPos = ta.selectionStart;
ta.value = ta.value.slice(0, caretPos) + text + ta.value.slice(ta.selectionEnd);
range = caretPos + text.length;
ta.setSelectionRange(range, range);
ta.focus();
return ta.dispatchEvent(new Event('input'));
},
characterCount: function() {
var count, counter;
counter = QR.charaCounter;
count = this.textLength;
counter.textContent = count;
counter.hidden = count < 1000;
return (count > 1500 ? $.addClass : $.rmClass)(counter, 'warning');
},
drag: function(e) {
var toggle;
toggle = e.type === 'dragstart' ? $.off : $.on;
toggle(d, 'dragover', QR.dragOver);
return toggle(d, 'drop', QR.dropFile);
},
dragOver: function(e) {
e.preventDefault();
return e.dataTransfer.dropEffect = 'copy';
},
dropFile: function(e) {
if (!e.dataTransfer.files.length) {
return;
}
e.preventDefault();
QR.open();
QR.fileInput.call(e.dataTransfer);
return $.addClass(QR.el, 'dump');
},
fileInput: function() {
var file, _i, _len, _ref;
QR.cleanError();
if (this.files.length === 1) {
file = this.files[0];
if (file.size > this.max) {
QR.error('File too large.');
QR.resetFileInput();
} else if (-1 === QR.mimeTypes.indexOf(file.type)) {
QR.error('Unsupported file type.');
QR.resetFileInput();
} else {
QR.selected.setFile(file);
}
return;
}
_ref = this.files;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
file = _ref[_i];
if (file.size > this.max) {
QR.error("File " + file.name + " is too large.");
break;
} else if (-1 === QR.mimeTypes.indexOf(file.type)) {
QR.error("" + file.name + ": Unsupported file type.");
break;
}
if (!QR.replies[QR.replies.length - 1].file) {
QR.replies[QR.replies.length - 1].setFile(file);
} else {
new QR.reply().setFile(file);
}
}
$.addClass(QR.el, 'dump');
return QR.resetFileInput();
},
resetFileInput: function() {
return $('[type=file]', QR.el).value = null;
},
replies: [],
reply: (function() {
function _Class() {
var persona, prev,
_this = this;
prev = QR.replies[QR.replies.length - 1];
persona = $.get('QR.persona', {});
this.name = prev ? prev.name : persona.name || null;
this.email = prev && !/^sage$/.test(prev.email) ? prev.email : persona.email || null;
this.sub = prev && Conf['Remember Subject'] ? prev.sub : Conf['Remember Subject'] ? persona.sub : null;
this.spoiler = prev && Conf['Remember Spoiler'] ? prev.spoiler : false;
this.com = null;
this.el = $.el('a', {
className: 'thumbnail',
draggable: true,
href: 'javascript:;',
innerHTML: '<a class=remove>×</a><label hidden><input type=checkbox> Spoiler</label><span></span>'
});
$('input', this.el).checked = this.spoiler;
$.on(this.el, 'click', function() {
return _this.select();
});
$.on($('.remove', this.el), 'click', function(e) {
e.stopPropagation();
return _this.rm();
});
$.on($('label', this.el), 'click', function(e) {
return e.stopPropagation();
});
$.on($('input', this.el), 'change', function(e) {
_this.spoiler = e.target.checked;
if (_this.el.id === 'selected') {
return $.id('spoiler').checked = _this.spoiler;
}
});
$.before($('#addReply', QR.el), this.el);
$.on(this.el, 'dragstart', this.dragStart);
$.on(this.el, 'dragenter', this.dragEnter);
$.on(this.el, 'dragleave', this.dragLeave);
$.on(this.el, 'dragover', this.dragOver);
$.on(this.el, 'dragend', this.dragEnd);
$.on(this.el, 'drop', this.drop);
QR.replies.push(this);
}
_Class.prototype.setFile = function(file) {
var fileUrl, img, url,
_this = this;
this.file = file;
this.el.title = "" + file.name + " (" + ($.bytesToString(file.size)) + ")";
if (QR.spoiler) {
$('label', this.el).hidden = false;
}
if (!/^image/.test(file.type)) {
this.el.style.backgroundImage = null;
return;
}
if (!(url = window.URL || window.webkitURL)) {
return;
}
url.revokeObjectURL(this.url);
fileUrl = url.createObjectURL(file);
img = $.el('img');
$.on(img, 'load', function() {
var c, data, i, l, s, ui8a, _i;
s = 90 * 3;
if (img.height < s || img.width < s) {
_this.url = fileUrl;
_this.el.style.backgroundImage = "url(" + _this.url + ")";
return;
}
if (img.height <= img.width) {
img.width = s / img.height * img.width;
img.height = s;
} else {
img.height = s / img.width * img.height;
img.width = s;
}
c = $.el('canvas');
c.height = img.height;
c.width = img.width;
c.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
data = atob(c.toDataURL().split(',')[1]);
l = data.length;
ui8a = new Uint8Array(l);
for (i = _i = 0; 0 <= l ? _i < l : _i > l; i = 0 <= l ? ++_i : --_i) {
ui8a[i] = data.charCodeAt(i);
}
_this.url = url.createObjectURL(new Blob([ui8a], {
type: 'image/png'
}));
_this.el.style.backgroundImage = "url(" + _this.url + ")";
return typeof url.revokeObjectURL === "function" ? url.revokeObjectURL(fileUrl) : void 0;
});
return img.src = fileUrl;
};
_Class.prototype.rmFile = function() {
var _base1;
QR.resetFileInput();
delete this.file;
this.el.title = null;
this.el.style.backgroundImage = null;
if (QR.spoiler) {
$('label', this.el).hidden = true;
}
return typeof (_base1 = window.URL || window.webkitURL).revokeObjectURL === "function" ? _base1.revokeObjectURL(this.url) : void 0;
};
_Class.prototype.select = function() {
var data, rectEl, rectList, _i, _len, _ref, _ref1;
if ((_ref = QR.selected) != null) {
_ref.el.id = null;
}
QR.selected = this;
this.el.id = 'selected';
rectEl = this.el.getBoundingClientRect();
rectList = this.el.parentNode.getBoundingClientRect();
this.el.parentNode.scrollLeft += rectEl.left + rectEl.width / 2 - rectList.left - rectList.width / 2;
_ref1 = ['name', 'email', 'sub', 'com'];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
data = _ref1[_i];
$("[name=" + data + "]", QR.el).value = this[data];
}
QR.characterCount.call($('textarea', QR.el));
return $('#spoiler', QR.el).checked = this.spoiler;
};
_Class.prototype.dragStart = function() {
return $.addClass(this, 'drag');
};
_Class.prototype.dragEnter = function() {
return $.addClass(this, 'over');
};
_Class.prototype.dragLeave = function() {
return $.rmClass(this, 'over');
};
_Class.prototype.dragOver = function(e) {
e.preventDefault();
return e.dataTransfer.dropEffect = 'move';
};
_Class.prototype.drop = function() {
var el, index, newIndex, oldIndex, reply;
el = $('.drag', this.parentNode);
index = function(el) {
return Array.prototype.slice.call(el.parentNode.children).indexOf(el);
};
oldIndex = index(el);
newIndex = index(this);
if (oldIndex < newIndex) {
$.after(this, el);
} else {
$.before(this, el);
}
reply = QR.replies.splice(oldIndex, 1)[0];
return QR.replies.splice(newIndex, 0, reply);
};
_Class.prototype.dragEnd = function() {
var el;
$.rmClass(this, 'drag');
if (el = $('.over', this.parentNode)) {
return $.rmClass(el, 'over');
}
};
_Class.prototype.rm = function() {
var index, _base1;
QR.resetFileInput();
$.rm(this.el);
index = QR.replies.indexOf(this);
if (QR.replies.length === 1) {
new QR.reply().select();
} else if (this.el.id === 'selected') {
(QR.replies[index - 1] || QR.replies[index + 1]).select();
}
QR.replies.splice(index, 1);
return typeof (_base1 = window.URL || window.webkitURL).revokeObjectURL === "function" ? _base1.revokeObjectURL(this.url) : void 0;
};
return _Class;
})(),
captcha: {
init: function() {
if (-1 !== d.cookie.indexOf('pass_enabled=')) {
return;
}
if (!(this.isEnabled = !!$.id('g-recaptcha'))) {
return;
}
return this.ready();
},
ready: function() {
if(!CaptchaIsSetup) {
$.addClass(QR.el, 'captcha');
$.globalEval('(function () {window.grecaptcha.render(document.getElementById("g-recaptcha"), {sitekey: "6Ldp2bsSAAAAAAJ5uyx_lx34lJeEpTLVkP5k04qc", theme: "light", callback: (' + (Conf['Auto Submit'] ? 'function (res) {var sb = document.getElementById("x_QR_Submit"); if(sb) sb.click(); }' : 'function (res) {}') + ') });})()');
$.after($('.textarea', QR.el), $.id('g-recaptcha'));
CaptchaIsSetup = true;
}
},
getResponse: function() {
$.globalEval('document.getElementById("captcha_response_field").value = window.grecaptcha.getResponse();');
return $.id("captcha_response_field").value;
},
reset: function() {
$.globalEval('window.grecaptcha.reset();');
}
},
dialog: function() {
var fileInput, id, mimeTypes, name, spoiler, ta, thread, threads, _i, _j, _len, _len1, _ref, _ref1;
QR.el = UI.dialog('qr', 'top:0;right:0;', '\
<div class=move>\
Quick Reply <input type=checkbox id=autohide title=Auto-hide>\
<span> <a class=close title=Close>×</a></span>\
</div>\
<form>\
<div><input id=dump type=button title="Dump list" value=+ class=field><input name=name title=Name placeholder=Name class=field size=1><input name=email title=E-mail placeholder=E-mail class=field size=1><input name=sub title=Subject placeholder=Subject class=field size=1></div>\
<div id=replies><div><a id=addReply href=javascript:; title="Add a reply">+</a></div></div>\
<div class=textarea><textarea name=com title=Comment placeholder=Comment class=field id=commentTextArea></textarea><span id=charCount></span></div>\
<div><input type=file title="Shift+Click to remove the selected file." multiple size=16><input type=submit id="x_QR_Submit"></div>\
<label id=spoilerLabel><input type=checkbox id=spoiler> Spoiler Image</label>\
<div class=warning></div>\
<input type="hidden" name="captcha_response" id="captcha_response_field" value="">\
</form>');
if (Conf['Remember QR size'] && $.engine === 'gecko') {
$.on(ta = $('textarea', QR.el), 'mouseup', function() {
return $.set('QR.size', this.style.cssText);
});
ta.style.cssText = $.get('QR.size', '');
}
fileInput = $('input[type=file]', QR.el);
fileInput.max = $('input[name=MAX_FILE_SIZE]').value;
if ($.engine !== 'presto') {
fileInput.accept = mimeTypes;
}
QR.spoiler = !!$('input[name=spoiler]');
spoiler = $('#spoilerLabel', QR.el);
spoiler.hidden = !QR.spoiler;
QR.charaCounter = $('#charCount', QR.el);
ta = $('textarea', QR.el);
if (!g.REPLY) {
threads = '<option value=new>New thread</option>';
_ref = $$('.thread');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
thread = _ref[_i];
id = thread.id.slice(1);
threads += "<option value=" + id + ">Thread " + id + "</option>";
}
QR.threadSelector = g.BOARD === 'f' ? $('select[name=filetag]').cloneNode(true) : $.el('select', {
innerHTML: threads,
title: 'Create a new thread / Reply to a thread'
});
$.prepend($('.move > span', QR.el), QR.threadSelector);
$.on(QR.threadSelector, 'mousedown', function(e) {
return e.stopPropagation();
});
}
$.on($('#autohide', QR.el), 'change', QR.toggleHide);
$.on($('.close', QR.el), 'click', QR.close);
$.on($('#dump', QR.el), 'click', function() {
return QR.el.classList.toggle('dump');
});
$.on($('#addReply', QR.el), 'click', function() {
return new QR.reply().select();
});
$.on($('form', QR.el), 'submit', QR.submit);
$.on(ta, 'input', function() {
return QR.selected.el.lastChild.textContent = this.value;
});
$.on(ta, 'input', QR.characterCount);
$.on(fileInput, 'change', QR.fileInput);
$.on(fileInput, 'click', function(e) {
if (e.shiftKey) {
return QR.selected.rmFile() || e.preventDefault();
}
});
$.on(spoiler.firstChild, 'change', function() {
return $('input', QR.selected.el).click();
});
$.on($('.warning', QR.el), 'click', QR.cleanError);
new QR.reply().select();
_ref1 = ['name', 'email', 'sub', 'com'];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
name = _ref1[_j];
$.on($("[name=" + name + "]", QR.el), 'input', function() {
var _ref2;
QR.selected[this.name] = this.value;
if (QR.cooldown.auto && QR.selected === QR.replies[0] && (0 < (_ref2 = QR.cooldown.seconds) && _ref2 <= 5)) {
return QR.cooldown.auto = false;
}
});
}
QR.status.input = $('input[type=submit]', QR.el);
QR.status();
QR.cooldown.init();
QR.captcha.init();
$.add(d.body, QR.el);
return $.event('QRDialogCreation', null, QR.el);
},
submit: function(e) {
var callbacks, err, filetag, m, opts, post, reply, response, textOnly, threadID;
if (e != null) {
e.preventDefault();
}
if (QR.cooldown.seconds) {
QR.cooldown.auto = !QR.cooldown.auto;
QR.status();
return;
}
QR.abort();
reply = QR.replies[0];
if (g.BOARD === 'f' && !g.REPLY) {
filetag = QR.threadSelector.value;
threadID = 'new';
} else {
threadID = g.THREAD_ID || QR.threadSelector.value;
}
if (threadID === 'new') {
threadID = null;
if (g.BOARD === 'vg' && !reply.sub) {
err = 'New threads require a subject.';
} else if (!(reply.file || (textOnly = !!$('input[name=textonly]', $.id('postForm'))))) {
err = 'No file selected.';
} else if (g.BOARD === 'f' && filetag === '9999') {
err = 'Invalid tag specified.';
}
} else if (!(reply.com || reply.file)) {
err = 'No file selected.';
}
if (QR.captcha.isEnabled && !err) {
response = QR.captcha.getResponse();
if (!response) {
err = 'No valid captcha.';
}
}
if (err) {
QR.cooldown.auto = false;
QR.status();
QR.error(err);
return;
}
QR.cleanError();
QR.cooldown.auto = QR.replies.length > 1;
if (Conf['Auto Hide QR'] && !QR.cooldown.auto) {
QR.hide();
}
if (!QR.cooldown.auto && $.x('ancestor::div[@id="qr"]', d.activeElement)) {
d.activeElement.blur();
}
QR.status({
progress: '...'
});
post = {
resto: threadID,
name: reply.name,
email: reply.email,
sub: reply.sub,
com: reply.com,
upfile: reply.file,
filetag: filetag,
spoiler: reply.spoiler,
textonly: textOnly,
mode: 'regist',
pwd: (m = d.cookie.match(/4chan_pass=([^;]+)/)) ? decodeURIComponent(m[1]) : $('input[name=pwd]').value,
'g-recaptcha-response': response
};
callbacks = {
onload: function() {
return QR.response(this.response);
},
onerror: function() {
if (QR.captcha.isEnabled) {
QR.captcha.reset();
}
QR.cooldown.auto = false;
QR.status();
return QR.error($.el('a', {
href: '//www.4chan.org/banned',
target: '_blank',
textContent: 'Connection error, or you are banned.'
}));
}
};
opts = {
form: $.formData(post),
upCallbacks: {
onload: function() {
return QR.status({
progress: '...'
});
},
onprogress: function(e) {
return QR.status({
progress: "" + (Math.round(e.loaded / e.total * 100)) + "%"
});
}
}
};
return QR.ajax = $.ajax($.id('postForm').parentNode.action, callbacks, opts);
},
response: function(html) {
var ban, board, clone, doc, err, obj, persona, postID, reply, threadID, _, _ref, _ref1;
if (QR.captcha.isEnabled) {
QR.captcha.reset();
}
doc = d.implementation.createHTMLDocument('');
doc.documentElement.innerHTML = html;
if (ban = $('.banType', doc)) {
board = $('.board', doc).innerHTML;
err = $.el('span', {
innerHTML: ban.textContent.toLowerCase() === 'banned' ? ("You are banned on " + board + "! ;_;<br>") + "Click <a href=//www.4chan.org/banned target=_blank>here</a> to see the reason." : ("You were issued a warning on " + board + " as " + ($('.nameBlock', doc).innerHTML) + ".<br>") + ("Reason: " + ($('.reason', doc).innerHTML))
});
} else if (err = doc.getElementById('errmsg')) {
if ((_ref = $('a', err)) != null) {
_ref.target = '_blank';
}
} else if (doc.title !== 'Post successful!') {
err = 'Connection error with sys.4chan.org.';
}
if (err) {
if (/captcha|verification/i.test(err.textContent) || err === 'Connection error with sys.4chan.org.') {
if (/mistyped/i.test(err.textContent)) {
err = 'Error: You seem to have mistyped the CAPTCHA.';
}
QR.cooldown.auto = false;
QR.cooldown.set({
delay: 2
});
} else {
QR.cooldown.auto = false;
}
QR.status();
QR.error(err);
return;
}
reply = QR.replies[0];
persona = $.get('QR.persona', {});
persona = {
name: reply.name,
email: /^sage$/.test(reply.email) ? persona.email : reply.email,
sub: Conf['Remember Subject'] ? reply.sub : null
};
$.set('QR.persona', persona);
_ref1 = doc.body.lastChild.textContent.match(/thread:(\d+),no:(\d+)/), _ = _ref1[0], threadID = _ref1[1], postID = _ref1[2];
obj = {boardID: g.BOARD, threadID: threadID, postID: postID};
clone = (typeof(cloneInto) === 'function' && cloneInto(obj, document.defaultView)) || obj;
$.event('QRPostSuccessful', clone, QR.el);
/* Add your own replies to yourPosts and storage to watch for replies */
if (Conf['Indicate You quote']) {
yourPosts.push(postID);
sessionStorage.setItem('yourPosts', JSON.stringify(yourPosts));
}
QR.cooldown.set({
post: reply,
isReply: threadID !== '0'
});
if (threadID === '0') {
location.pathname = "/" + g.BOARD + "/thread/" + postID;
} else {
QR.cooldown.auto = QR.replies.length > 1;
if (Conf['Open Reply in New Tab'] && !g.REPLY && !QR.cooldown.auto) {
$.open("//boards.4chan.org/" + g.BOARD + "/thread/" + threadID + "#p" + postID);
}
}
if (Conf['Persistent QR'] || QR.cooldown.auto) {
reply.rm();
} else {
QR.close();
}
QR.status();
return QR.resetFileInput();
},
abort: function() {
var _ref;
if ((_ref = QR.ajax) != null) {
_ref.abort();
}
delete QR.ajax;
return QR.status();
}
};
Options = {
init: function() {
return $.ready(Options.initReady);
},
initReady: function() {
var a, notice, setting;
a = $.el('a', {
href: 'javascript:;',
className: 'settingsWindowLink',
textContent: '4chan X Settings'
});
$.on(a, 'click', Options.dialog);
setting = $.id('navtopright');
if (Conf['Disable 4chan\'s extension']) {
$.replace(setting.firstElementChild, a);
} else {
$.prepend(setting, [$.tn('['), a, $.tn('] ')]);
}
notice = $.el('a', {
textContent: 'v2 is never outdated.',
href: 'https://github.com/loadletter/4chan-x',
target: '_blank'
});
notice.style.color = 'red';
$.prepend(setting, [$.tn('['), notice, $.tn('] ')]);
$.ready(function () {
setTimeout(function () {
var navbotLink = $('#navbotright > .settingsWindowLink');
if (navbotLink) {
$.on(navbotLink, 'click', Options.dialog);
}
}, 0);
});
if (!$.get('firstrun')) {
$.set('firstrun', true);
if (!Favicon.el) {
Favicon.init();
}
return Options.dialog();
}
},
dialog: function() {
var arr, back, checked, description, dialog, favicon, fileInfo, filter, hiddenNum, hiddenThreads, indicator, indicators, input, key, li, obj, overlay, sauce, time, tr, ul, _i, _len, _ref, _ref1, _ref2;
dialog = $.el('div', {
id: 'options',
className: 'reply dialog',
innerHTML: '<div id=optionsbar>\
<div id=credits>\
<a target=_blank href=https://github.com/loadletter/4chan-x>4chan X</a>\
| <a target=_blank href=https://github.com/loadletter/4chan-x/commits/master>' + Main.version + '</a>\
| <a target=_blank href=https://github.com/loadletter/4chan-x/issues>Issues</a>\
</div>\
<div>\
<label for=main_tab>Main</label>\
| <label for=filter_tab>Filter</label>\
| <label for=sauces_tab>Sauce</label>\
| <label for=rice_tab>Rice</label>\
| <label for=keybinds_tab>Keybinds</label>\
</div>\
</div>\
<hr>\
<div id=content>\
<input type=radio name=tab hidden id=main_tab checked>\
<div>\
<div class=imp-exp>\
<button class=export>Export settings</button>\
<button class=import>Import settings</button>\
<input type=file style="visibility:hidden">\
</div>\
<p class=imp-exp-result></p>\
</div>\
<input type=radio name=tab hidden id=sauces_tab>\
<div>\
<div class=warning><code>Sauce</code> is disabled.</div>\
Lines starting with a <code>#</code> will be ignored.<br>\
You can specify a certain display text by appending <code>;text:[text]</code> to the url.\
<ul>These parameters will be replaced by their corresponding values:\
<li>$1: Thumbnail url.</li>\
<li>$2: Full image url.</li>\
<li>$3: MD5 hash.</li>\
<li>$4: Current board.</li>\
</ul>\
<textarea name=sauces id=sauces class=field></textarea>\
</div>\
<input type=radio name=tab hidden id=filter_tab>\
<div>\
<div class=warning><code>Filter</code> is disabled.</div>\
<select name=filter>\
<option value=guide>Guide</option>\
<option value=name>Name</option>\
<option value=uniqueid>Unique ID</option>\
<option value=tripcode>Tripcode</option>\
<option value=mod>Admin/Mod</option>\
<option value=subject>Subject</option>\
<option value=comment>Comment</option>\
<option value=country>Country</option>\
<option value=filename>Filename</option>\
<option value=dimensions>Image dimensions</option>\
<option value=filesize>Filesize</option>\
<option value=md5>Image MD5 (uses exact string matching, not regular expressions)</option>\
</select>\
</div>\
<input type=radio name=tab hidden id=rice_tab>\
<div>\
<div class=warning><code>Quote Backlinks</code> are disabled.</div>\
<ul>\
Backlink formatting\
<li><input name=backlink class=field> : <span id=backlinkPreview></span></li>\
</ul>\
<div class=warning><code>Time Formatting</code> is disabled.</div>\
<ul>\
Time formatting\
<li><input name=time class=field> : <span id=timePreview></span></li>\
<li>Supported <a href=http://en.wikipedia.org/wiki/Date_%28Unix%29#Formatting>format specifiers</a>:</li>\
<li>Day: %a, %A, %d, %e</li>\
<li>Month: %m, %b, %B</li>\
<li>Year: %y</li>\
<li>Hour: %k, %H, %l (lowercase L), %I (uppercase i), %p, %P</li>\
<li>Minutes: %M</li>\
<li>Seconds: %S</li>\
</ul>\
<div class=warning><code>File Info Formatting</code> is disabled.</div>\
<ul>\
File Info Formatting\
<li><input name=fileInfo class=field> : <span id=fileInfoPreview class=fileText></span></li>\
<li>Link: %l (lowercase L, truncated), %L (untruncated), %T (Unix timestamp)</li>\
<li>Original file name: %n (truncated), %N (untruncated), %t (Unix timestamp)</li>\
<li>Spoiler indicator: %p</li>\
<li>Size: %B (Bytes), %K (KB), %M (MB), %s (4chan default)</li>\
<li>Resolution: %r (Displays PDF on /po/, for PDFs)</li>\
</ul>\
<div class=warning><code>Unread Favicon</code> is disabled.</div>\
Unread favicons<br>\
<select name=favicon>\
<option value=ferongr>ferongr</option>\
<option value=xat->xat-</option>\
<option value=Mayhem>Mayhem</option>\
<option value=Original>Original</option>\
</select>\
<span></span>\
</div>\
<input type=radio name=tab hidden id=keybinds_tab>\
<div>\
<div class=warning><code>Keybinds</code> are disabled.</div>\
<div>Allowed keys: Ctrl, Alt, Meta, a-z, A-Z, 0-9, Up, Down, Right, Left.</div>\
<table><tbody>\
<tr><th>Actions</th><th>Keybinds</th></tr>\
</tbody></table>\
</div>\
</div>'
});
$.on($('#main_tab + div .export', dialog), 'click', Options["export"]);
$.on($('#main_tab + div .import', dialog), 'click', Options["import"]);
$.on($('#main_tab + div input', dialog), 'change', Options.onImport);
_ref = Config.main;
for (key in _ref) {
obj = _ref[key];
ul = $.el('ul', {
textContent: key
});
for (key in obj) {
arr = obj[key];
checked = $.get(key, Conf[key]) ? 'checked' : '';
description = arr[1];
li = $.el('li', {
innerHTML: "<label><input type=checkbox name=\"" + key + "\" " + checked + ">" + key + "</label><span class=description>: " + description + "</span>"
});
$.on($('input', li), 'click', $.cb.checked);
$.add(ul, li);
}
$.add($('#main_tab + div', dialog), ul);
}
hiddenThreads = $.get("hiddenThreads/" + g.BOARD + "/", {});
hiddenNum = Object.keys(g.hiddenReplies).length + Object.keys(hiddenThreads).length;
li = $.el('li', {
innerHTML: "<button>hidden: " + hiddenNum + "</button> <span class=description>: Forget all hidden posts. Useful if you accidentally hide a post and have \"Show Stubs\" disabled."
});
$.on($('button', li), 'click', Options.clearHidden);
$.add($('ul:nth-child(2)', dialog), li);
filter = $('select[name=filter]', dialog);
$.on(filter, 'change', Options.filter);
sauce = $('#sauces', dialog);
sauce.value = $.get(sauce.name, Conf[sauce.name]);
$.on(sauce, 'change', $.cb.value);
(back = $('[name=backlink]', dialog)).value = $.get('backlink', Conf['backlink']);
(time = $('[name=time]', dialog)).value = $.get('time', Conf['time']);
(fileInfo = $('[name=fileInfo]', dialog)).value = $.get('fileInfo', Conf['fileInfo']);
$.on(back, 'input', $.cb.value);
$.on(back, 'input', Options.backlink);
$.on(time, 'input', $.cb.value);
$.on(time, 'input', Options.time);
$.on(fileInfo, 'input', $.cb.value);
$.on(fileInfo, 'input', Options.fileInfo);
favicon = $('select[name=favicon]', dialog);
favicon.value = $.get('favicon', Conf['favicon']);
$.on(favicon, 'change', $.cb.value);
$.on(favicon, 'change', Options.favicon);
_ref1 = Config.hotkeys;
for (key in _ref1) {
arr = _ref1[key];
tr = $.el('tr', {
innerHTML: "<td>" + arr[1] + "</td><td><input name=" + key + " class=field></td>"
});
input = $('input', tr);
input.value = $.get(key, Conf[key]);
$.on(input, 'keydown', Options.keybind);
$.add($('#keybinds_tab + div tbody', dialog), tr);
}
indicators = {};
_ref2 = $$('.warning', dialog);
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
indicator = _ref2[_i];
key = indicator.firstChild.textContent;
indicator.hidden = $.get(key, Conf[key]);
indicators[key] = indicator;
$.on($("[name='" + key + "']", dialog), 'click', function() {
return indicators[this.name].hidden = this.checked;
});
}
overlay = $.el('div', {
id: 'overlay'
});
$.on(overlay, 'click', Options.close);
$.on(dialog, 'click', function(e) {
return e.stopPropagation();
});
$.add(overlay, dialog);
$.add(d.body, overlay);
d.body.style.setProperty('width', "" + d.body.clientWidth + "px", null);
$.addClass(d.body, 'unscroll');
Options.filter.call(filter);
Options.backlink.call(back);
Options.time.call(time);
Options.fileInfo.call(fileInfo);
return Options.favicon.call(favicon);
},
close: function() {
$.rm(this);
d.body.style.removeProperty('width');
return $.rmClass(d.body, 'unscroll');
},
clearHidden: function() {
$["delete"]("hiddenReplies/" + g.BOARD + "/");
$["delete"]("hiddenThreads/" + g.BOARD + "/");
this.textContent = "hidden: 0";
return g.hiddenReplies = {};
},
keybind: function(e) {
var key;
if (e.keyCode === 9) {
return;
}
e.preventDefault();
e.stopPropagation();
if ((key = Keybinds.keyCode(e)) == null) {
return;
}
this.value = key;
return $.cb.value.call(this);
},
filter: function() {
var el, name, ta;
el = this.nextSibling;
if ((name = this.value) !== 'guide') {
ta = $.el('textarea', {
name: name,
className: 'field',
value: $.get(name, Conf[name])
});
$.on(ta, 'change', $.cb.value);
$.replace(el, ta);
return;
}
if (el) {
$.rm(el);
}
return $.after(this, $.el('article', {
innerHTML: '<p>Use <a href=https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions>regular expressions</a>, one per line.<br>\
Lines starting with a <code>#</code> will be ignored.<br>\
For example, <code>/weeaboo/i</code> will filter posts containing the string `<code>weeaboo</code>`, case-insensitive.</p>\
<ul>You can use these settings with each regular expression, separate them with semicolons:\
<li>\
Per boards, separate them with commas. It is global if not specified.<br>\
For example: <code>boards:a,jp;</code>.\
</li>\
<li>\
Filter OPs only along with their threads (`only`), replies only (`no`, this is default), or both (`yes`).<br>\
For example: <code>op:only;</code>, <code>op:no;</code> or <code>op:yes;</code>.\
</li>\
<li>\
Overrule the `Show Stubs` setting if specified: create a stub (`yes`) or not (`no`).<br>\
For example: <code>stub:yes;</code> or <code>stub:no;</code>.\
</li>\
<li>\
Highlight instead of hiding. You can specify a class name to use with a userstyle.<br>\
For example: <code>highlight;</code> or <code>highlight:wallpaper;</code>.\
</li>\
<li>\
Highlighted OPs will have their threads put on top of board pages by default.<br>\
For example: <code>top:yes;</code> or <code>top:no;</code>.\
</li>\
</ul>'
}));
},
time: function() {
Time.date = new Date();
return $.id('timePreview').textContent = Time.funk();
},
backlink: function() {
return $.id('backlinkPreview').textContent = Conf['backlink'].replace(/%id/, '123456789');
},
fileInfo: function() {
FileInfo.data = {
link: '//i.4cdn.org/g/1334437723720.jpg',
spoiler: true,
size: '276',
unit: 'KB',
resolution: '1280x720',
fullname: 'd9bb2efc98dd0df141a94399ff5880b7.jpg',
shortname: 'd9bb2efc98dd0df141a94399ff5880(...).jpg'
};
return $.id('fileInfoPreview').innerHTML = FileInfo.funk();
},
favicon: function() {
Favicon["switch"]();
Unread.update(true);
return this.nextElementSibling.innerHTML = "<img src=" + Favicon.unreadSFW + "> <img src=" + Favicon.unreadNSFW + "> <img src=" + Favicon.unreadDead + ">";
},
"export": function() {
var a, data, now, output;
now = Date.now();
data = {
version: Main.version,
date: now,
Conf: Conf,
WatchedThreads: $.get('watched', {})
};
a = $.el('a', {
className: 'warning',
textContent: 'Save me!',
download: "4chan X v" + Main.version + "-" + now + ".json",
href: "data:application/json;base64," + (btoa(unescape(encodeURIComponent(JSON.stringify(data))))),
target: '_blank'
});
if ($.engine !== 'gecko') {
a.click();
return;
}
output = this.parentNode.nextElementSibling;
output.innerHTML = null;
return $.add(output, a);
},
"import": function() {
return this.nextElementSibling.click();
},
onImport: function() {
var file, output, reader;
if (!(file = this.files[0])) {
return;
}
output = this.parentNode.nextElementSibling;
if (!confirm('Your current settings will be entirely overwritten, are you sure?')) {
output.textContent = 'Import aborted.';
return;
}
reader = new FileReader();
reader.onload = function(e) {
var data, err;
try {
data = JSON.parse(e.target.result);
Options.loadSettings(data);
if (confirm('Import successful. Refresh now?')) {
return window.location.reload();
}
} catch (_error) {
err = _error;
return output.textContent = 'Import failed due to an error.';
}
};
return reader.readAsText(file);
},
loadSettings: function(data) {
var key, val, _ref;
_ref = data.Conf;
for (key in _ref) {
val = _ref[key];
$.set(key, val);
}
return $.set('watched', data.WatchedThreads);
}
};
Updater = {
init: function() {
var checkbox, checked, dialog, html, input, name, title, _i, _len, _ref;
html = '<div class=move><span id=count></span> <span id=timer></span></div>';
checkbox = Config.updater.checkbox;
for (name in checkbox) {
title = checkbox[name][1];
checked = Conf[name] ? 'checked' : '';
html += "<div><label title='" + title + "'>" + name + "<input name='" + name + "' type=checkbox " + checked + "></label></div>";
}
checked = Conf['Auto Update'] ? 'checked' : '';
html += " <div><label title='Controls whether *this* thread automatically updates or not'>Auto Update This<input name='Auto Update This' type=checkbox " + checked + "></label></div> <div><label>Interval (s)<input type=number name=Interval class=field min=5></label></div> <div><input value='Update Now' type=button name='Update Now'></div>";
dialog = UI.dialog('updater', 'bottom: 0; right: 0;', html);
this.count = $('#count', dialog);
this.timer = $('#timer', dialog);
this.thread = $.id("t" + g.THREAD_ID);
this.lastModified = '0';
_ref = $$('input', dialog);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
input = _ref[_i];
if (input.type === 'checkbox') {
$.on(input, 'click', $.cb.checked);
}
switch (input.name) {
case 'Scroll BG':
$.on(input, 'click', this.cb.scrollBG);
this.cb.scrollBG.call(input);
break;
case 'Verbose':
$.on(input, 'click', this.cb.verbose);
this.cb.verbose.call(input);
break;
case 'Auto Update This':
$.on(input, 'click', this.cb.autoUpdate);
this.cb.autoUpdate.call(input);
break;
case 'Interval':
input.value = Conf['Interval'];
$.on(input, 'change', this.cb.interval);
this.cb.interval.call(input);
break;
case 'Update Now':
$.on(input, 'click', this.update);
}
}
$.add(d.body, dialog);
$.on(d, 'QRPostSuccessful', this.cb.post);
return $.on(d, 'visibilitychange', this.cb.visibility);
},
/*
http://freesound.org/people/pierrecartoons1979/sounds/90112/
cc-by-nc-3.0
*/
audio: $.el('audio', {
src: 'data:audio/wav;base64,UklGRjQDAABXQVZFZm10IBAAAAABAAEAgD4AAIA+AAABAAgAc21wbDwAAABBAAADAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABkYXRhzAIAAGMms8em0tleMV4zIpLVo8nhfSlcPR102Ki+5JspVEkdVtKzs+K1NEhUIT7DwKrcy0g6WygsrM2k1NpiLl0zIY/WpMrjgCdbPhxw2Kq+5Z4qUkkdU9K1s+K5NkVTITzBwqnczko3WikrqM+l1NxlLF0zIIvXpsnjgydZPhxs2ay95aIrUEkdUdC3suK8N0NUIjq+xKrcz002WioppdGm091pK1w0IIjYp8jkhydXPxxq2K295aUrTkoeTs65suK+OUFUIzi7xqrb0VA0WSoootKm0t5tKlo1H4TYqMfkiydWQBxm16+85actTEseS8y7seHAPD9TIza5yKra01QyWSson9On0d5wKVk2H4DYqcfkjidUQB1j1rG75KsvSkseScu8seDCPz1TJDW2yara1FYxWSwnm9Sn0N9zKVg2H33ZqsXkkihSQR1g1bK65K0wSEsfR8i+seDEQTxUJTOzy6rY1VowWC0mmNWoz993KVc3H3rYq8TklSlRQh1d1LS647AyR0wgRMbAsN/GRDpTJTKwzKrX1l4vVy4lldWpzt97KVY4IXbUr8LZljVPRCxhw7W3z6ZISkw1VK+4sMWvXEhSPk6buay9sm5JVkZNiLWqtrJ+TldNTnquqbCwilZXU1BwpKirrpNgWFhTaZmnpquZbFlbVmWOpaOonHZcXlljhaGhpZ1+YWBdYn2cn6GdhmdhYGN3lp2enIttY2Jjco+bnJuOdGZlZXCImJqakHpoZ2Zug5WYmZJ/bGlobX6RlpeSg3BqaW16jZSVkoZ0bGtteImSk5KIeG5tbnaFkJKRinxxbm91gY2QkIt/c3BwdH6Kj4+LgnZxcXR8iI2OjIR5c3J0e4WLjYuFe3VzdHmCioyLhn52dHR5gIiKioeAeHV1eH+GiYqHgXp2dnh9hIiJh4J8eHd4fIKHiIeDfXl4eHyBhoeHhH96eHmA'
}),
cb: {
post: function() {
if (!Conf['Auto Update This']) {
return;
}
return setTimeout(Updater.update, 500);
},
visibility: function() {
if (d.hidden) {
return;
}
if (Updater.timer.textContent < -Conf['Interval']) {
return Updater.set('timer', -Conf['Interval']);
}
},
interval: function() {
var val;
val = parseInt(this.value, 10);
this.value = val > 5 ? val : 5;
$.cb.value.call(this);
return Updater.set('timer', -Conf['Interval']);
},
verbose: function() {
if (Conf['Verbose']) {
Updater.set('count', '+0');
return Updater.timer.hidden = false;
} else {
Updater.set('count', 'Thread Updater');
Updater.count.className = '';
return Updater.timer.hidden = true;
}
},
autoUpdate: function() {
if (Conf['Auto Update This'] = this.checked) {
return Updater.timeoutID = setTimeout(Updater.timeout, 1000);
} else {
return clearTimeout(Updater.timeoutID);
}
},
scrollBG: function() {
return Updater.scrollBG = this.checked ? function() {
return true;
} : function() {
return !d.hidden;
};
},
buryDead: function() {
Updater.set('timer', '');
Updater.set('count', 404);
Updater.count.className = 'warning';
clearTimeout(Updater.timeoutID);
g.dead = true;
if (Conf['Unread Count']) {
Unread.title = Unread.title.match(/^.+-/)[0] + ' 404';
} else {
d.title = d.title.match(/^.+-/)[0] + ' 404';
}
Unread.update(true);
QR.abort();
return $.event('ThreadUpdate', {
404: true,
threadID: g.THREAD_ID
});
},
load: function() {
switch (this.status) {
case 404:
Updater.cb.buryDead();
break;
case 0:
case 304:
/*
Status Code 304: Not modified
By sending the `If-Modified-Since` header we get a proper status code, and no response.
This saves bandwidth for both the user and the servers and avoid unnecessary computation.
*/
Updater.set('timer', -Conf['Interval']);
if (Conf['Verbose']) {
Updater.set('count', '+0');
Updater.count.className = null;
}
break;
case 200:
Updater.lastModified = this.getResponseHeader('Last-Modified');
var parsed_posts = JSON.parse(this.response).posts;
if ('archived' in parsed_posts[0] && parsed_posts[0].archived === 1) {
Updater.cb.buryDead();
} else {
Updater.cb.update(parsed_posts);
Updater.set('timer', -Conf['Interval']);
}
break;
default:
Updater.set('timer', -Conf['Interval']);
if (Conf['Verbose']) {
Updater.set('count', this.statusText);
Updater.count.className = 'warning';
}
}
return delete Updater.request;
},
update: function(posts) {
var count, id, lastPost, nodes, post, posterCount, scroll, spoilerRange, _i, _len, _ref;
if (spoilerRange = posts[0].custom_spoiler) {
Build.spoilerRange[g.BOARD] = spoilerRange;
}
if (Conf['Thread Stats'] && (posterCount = posts[0].unique_ips)) {
ThreadStats.posterCount(posterCount);
}
lastPost = Updater.thread.lastElementChild;
id = +lastPost.id.slice(2);
nodes = [];
_ref = posts.reverse();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
post = _ref[_i];
if (post.no <= id) {
break;
}
nodes.push(Build.postFromObject(post, g.BOARD));
}
count = nodes.length;
if (Conf['Verbose']) {
Updater.set('count', "+" + count);
Updater.count.className = count ? 'new' : null;
}
if (count && Conf['Beep'] && d.hidden && (Unread.replies.length === 0)) {
Updater.audio.play();
//return;
}
scroll = Conf['Scrolling'] && Updater.scrollBG() && lastPost.getBoundingClientRect().bottom - d.documentElement.clientHeight < 25;
$.add(Updater.thread, nodes.reverse());
if (scroll) {
nodes[0].scrollIntoView();
}
return $.event('ThreadUpdate', {
404: false,
threadID: g.THREAD_ID,
newPosts: nodes.map(function(data) {
return data.id.replace('pc', g.BOARD + '.');
})
});
}
},
set: function(name, text) {
var el, node;
el = Updater[name];
if (node = el.firstChild) {
return node.data = text;
} else {
return el.textContent = text;
}
},
timeout: function() {
var n;
Updater.timeoutID = setTimeout(Updater.timeout, 1000);
n = 1 + Number(Updater.timer.firstChild.data);
if (n === 0) {
return Updater.update();
} else if (n >= Conf['Interval']) {
Updater.set('count', 'Retry');
Updater.count.className = null;
return Updater.update();
} else {
return Updater.set('timer', n);
}
},
update: function() {
var request, url;
Updater.set('timer', 0);
request = Updater.request;
if (request) {
request.onloadend = null;
request.abort();
}
url = "//a.4cdn.org/" + g.BOARD + "/thread/" + g.THREAD_ID + ".json";
return Updater.request = $.ajax(url, {
onloadend: Updater.cb.load
}, {
headers: {
'If-Modified-Since': Updater.lastModified
}
});
}
};
Watcher = {
init: function() {
var favicon, html, input, _i, _len, _ref;
html = '<div class=move>Thread Watcher</div>';
this.dialog = UI.dialog('watcher', 'top: 50px; left: 0px;', html);
$.add(d.body, this.dialog);
_ref = $$('.op input');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
input = _ref[_i];
favicon = $.el('img', {
className: 'favicon'
});
$.on(favicon, 'click', this.cb.toggle);
$.before(input, favicon);
}
if (g.THREAD_ID === $.get('autoWatch', 0)) {
this.watch(g.THREAD_ID);
$["delete"]('autoWatch');
} else {
this.refresh();
}
$.on(d, 'QRPostSuccessful', this.cb.post);
return $.sync('watched', this.refresh);
},
refresh: function(watched) {
var board, div, favicon, id, link, nodes, props, watchedBoard, x, _i, _j, _len, _len1, _ref, _ref1, _ref2;
watched || (watched = $.get('watched', {}));
nodes = [];
for (board in watched) {
_ref = watched[board];
for (id in _ref) {
props = _ref[id];
x = $.el('a', {
textContent: '×',
href: 'javascript:;'
});
$.on(x, 'click', Watcher.cb.x);
link = $.el('a', props);
link.title = link.textContent;
div = $.el('div');
$.add(div, [x, $.tn(' '), link]);
nodes.push(div);
}
}
_ref1 = $$('div:not(.move)', Watcher.dialog);
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
div = _ref1[_i];
$.rm(div);
}
$.add(Watcher.dialog, nodes);
watchedBoard = watched[g.BOARD] || {};
_ref2 = $$('.favicon');
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
favicon = _ref2[_j];
id = favicon.nextSibling.name;
if (id in watchedBoard) {
favicon.src = Favicon["default"];
} else {
favicon.src = Favicon.empty;
}
}
},
cb: {
toggle: function() {
return Watcher.toggle(this.parentNode);
},
x: function() {
var thread;
thread = this.nextElementSibling.pathname.split('/');
return Watcher.unwatch(thread[3], thread[1]);
},
post: function(e) {
var postID, threadID, _ref;
_ref = e.detail, postID = _ref.postID, threadID = _ref.threadID;
if (threadID === '0') {
if (Conf['Auto Watch']) {
return $.set('autoWatch', postID);
}
} else if (Conf['Auto Watch Reply']) {
return Watcher.watch(threadID);
}
}
},
toggle: function(thread) {
var id;
id = $('.favicon + input', thread).name;
return Watcher.watch(id) || Watcher.unwatch(id, g.BOARD);
},
unwatch: function(id, board) {
var watched;
watched = $.get('watched', {});
delete watched[board][id];
$.set('watched', watched);
return Watcher.refresh();
},
watch: function(id) {
var thread, watched, _name;
thread = $.id("t" + id);
if ($('.favicon', thread).src === Favicon["default"]) {
return false;
}
watched = $.get('watched', {});
watched[_name = g.BOARD] || (watched[_name] = {});
watched[g.BOARD][id] = {
href: "/" + g.BOARD + "/thread/" + id,
textContent: Get.title(thread)
};
$.set('watched', watched);
Watcher.refresh();
return true;
}
};
Anonymize = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var name, parent, trip;
if (post.isInlined && !post.isCrosspost) {
return;
}
name = $('.postInfo .name', post.el);
name.textContent = 'Anonymous';
if ((trip = name.nextElementSibling) && trip.className === 'postertrip') {
$.rm(trip);
}
if ((parent = name.parentNode).className === 'useremail' && !/^mailto:sage$/i.test(parent.href)) {
return $.replace(parent, name);
}
}
};
Sauce = {
init: function() {
var link, _i, _len, _ref;
if (g.BOARD === 'f') {
return;
}
this.links = [];
_ref = Conf['sauces'].split('\n');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
link = _ref[_i];
if (link[0] === '#' || link.trim() === '') {
continue;
}
this.links.push(this.createSauceLink(link.trim()));
}
if (!this.links.length) {
return;
}
return Main.callbacks.push(this.node);
},
createSauceLink: function(link) {
var domain, el, href, m;
link = link.replace(/\$4/g, g.BOARD);
domain = (m = link.match(/;text:(.+)$/)) ? m[1] : link.match(/(\w+)\.\w+\//)[1];
href = link.replace(/;text:.+$/, '');
el = $.el('a', {
target: '_blank',
textContent: domain
});
return function(img, isArchived) {
var a;
a = el.cloneNode(true);
a.href = href.replace(/(\$\d)/g, function(parameter) {
switch (parameter) {
case '$1':
return isArchived ? img.firstChild.src : 'http://t.4cdn.org' + img.pathname.replace(/(\d+)\..+$/, '$1s.jpg');
case '$2':
return img.href;
case '$3':
return encodeURIComponent(img.firstChild.dataset.md5);
default:
return parameter;
}
});
return a;
};
},
node: function(post) {
var img, link, nodes, _i, _len, _ref;
img = post.img;
if (post.isInlined && !post.isCrosspost || !img) {
return;
}
img = img.parentNode;
nodes = [];
_ref = Sauce.links;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
link = _ref[_i];
nodes.push($.tn('\u00A0'), link(img, post.isArchived));
}
return $.add(post.fileInfo, nodes);
}
};
RevealSpoilers = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var img, s;
img = post.img;
if (!(img && /^Spoiler/.test(post.fileInfo.firstElementChild.textContent)) || post.isInlined && !post.isCrosspost || post.isArchived) {
return;
}
img.removeAttribute('style');
s = img.style;
s.maxHeight = s.maxWidth = /\bop\b/.test(post["class"]) ? '250px' : '125px';
post.fileInfo.firstElementChild.textContent = post.el.getElementsByClassName('fileText')[0].title;
return img.src = "//t.4cdn.org" + (img.parentNode.pathname.replace(/(\d+).+$/, '$1s.jpg'));
}
};
Time = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var node;
if (post.isInlined && !post.isCrosspost) {
return;
}
node = $('.postInfo > .dateTime', post.el);
Time.date = new Date(node.dataset.utc * 1000);
return node.textContent = Time.funk();
},
funk: function() {
return Conf['time'].replace(/%([A-Za-z])/g, function(s, c) {
if (c in Time.formatters) {
return Time.formatters[c]();
} else {
return s;
}
});
},
day: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
zeroPad: function(n) {
if (n < 10) {
return '0' + n;
} else {
return n;
}
},
formatters: {
a: function() {
return Time.day[Time.date.getDay()].slice(0, 3);
},
A: function() {
return Time.day[Time.date.getDay()];
},
b: function() {
return Time.month[Time.date.getMonth()].slice(0, 3);
},
B: function() {
return Time.month[Time.date.getMonth()];
},
d: function() {
return Time.zeroPad(Time.date.getDate());
},
e: function() {
return Time.date.getDate();
},
H: function() {
return Time.zeroPad(Time.date.getHours());
},
I: function() {
return Time.zeroPad(Time.date.getHours() % 12 || 12);
},
k: function() {
return Time.date.getHours();
},
l: function() {
return Time.date.getHours() % 12 || 12;
},
m: function() {
return Time.zeroPad(Time.date.getMonth() + 1);
},
M: function() {
return Time.zeroPad(Time.date.getMinutes());
},
p: function() {
if (Time.date.getHours() < 12) {
return 'AM';
} else {
return 'PM';
}
},
P: function() {
if (Time.date.getHours() < 12) {
return 'am';
} else {
return 'pm';
}
},
S: function() {
return Time.zeroPad(Time.date.getSeconds());
},
y: function() {
return Time.date.getFullYear() - 2000;
}
}
};
RelativeDates = {
INTERVAL: $.MINUTE,
init: function() {
Main.callbacks.push(this.node);
return $.on(d, 'visibilitychange', this.flush);
},
node: function(post) {
var dateEl, diff, utc;
dateEl = $('.postInfo > .dateTime', post.el);
dateEl.title = dateEl.textContent;
utc = dateEl.dataset.utc * 1000;
diff = Date.now() - utc;
dateEl.textContent = RelativeDates.relative(diff);
RelativeDates.setUpdate(dateEl, utc, diff);
return RelativeDates.flush();
},
relative: function(diff) {
var number, rounded, unit;
unit = (number = diff / $.DAY) > 1 ? 'day' : (number = diff / $.HOUR) > 1 ? 'hour' : (number = diff / $.MINUTE) > 1 ? 'minute' : (number = diff / $.SECOND, 'second');
rounded = Math.round(number);
if (rounded !== 1) {
unit += 's';
}
return "" + rounded + " " + unit + " ago";
},
stale: [],
flush: $.debounce($.SECOND, function() {
var now, update, _i, _len, _ref;
if (d.hidden) {
return;
}
now = Date.now();
_ref = RelativeDates.stale;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
update = _ref[_i];
update(now);
}
RelativeDates.stale = [];
clearTimeout(RelativeDates.timeout);
return RelativeDates.timeout = setTimeout(RelativeDates.flush, RelativeDates.INTERVAL);
}),
setUpdate: function(dateEl, utc, diff) {
var markStale, setOwnTimeout, update;
setOwnTimeout = function(diff) {
var delay;
delay = diff < $.MINUTE ? $.SECOND - (diff + $.SECOND / 2) % $.SECOND : diff < $.HOUR ? $.MINUTE - (diff + $.MINUTE / 2) % $.MINUTE : $.HOUR - (diff + $.HOUR / 2) % $.HOUR;
return setTimeout(markStale, delay);
};
update = function(now) {
if (d.contains(dateEl)) {
diff = now - utc;
dateEl.textContent = RelativeDates.relative(diff);
return setOwnTimeout(diff);
}
};
markStale = function() {
return RelativeDates.stale.push(update);
};
return setOwnTimeout(diff);
}
};
FileInfo = {
init: function() {
if (g.BOARD === 'f') {
return;
}
return Main.callbacks.push(this.node);
},
node: function(post) {
var alt, filename, node, _ref, nameNode;
if (post.isInlined && !post.isCrosspost || !post.fileInfo) {
return;
}
node = post.fileInfo.firstElementChild;
alt = post.img.alt;
filename = (nameNode = $('a', post.fileInfo)) ? nameNode.title || nameNode.textContent : post.fileInfo.title;
FileInfo.data = {
link: post.img.parentNode.href,
spoiler: /^Spoiler/.test(alt),
size: alt.match(/\d+\.?\d*/)[0],
unit: alt.match(/\w+$/)[0],
resolution: post.fileInfo.childNodes[2].textContent.match(/\d+x\d+|PDF/)[0],
fullname: filename,
shortname: Build.shortFilename(filename, post.ID === post.threadID)
};
node.setAttribute('data-filename', filename);
return post.fileInfo.innerHTML = FileInfo.funk();
},
funk: function() {
return Conf['fileInfo'].replace(/%(.)|[^%]+/g, function(s, c) {
if (c in FileInfo.formatters) {
return FileInfo.formatters[c]();
} else {
return Build.escape(s);
}
});
},
convertUnit: function(unitT) {
var i, size, unitF, units;
size = this.data.size;
unitF = this.data.unit;
if (unitF !== unitT) {
units = ['B', 'KB', 'MB'];
i = units.indexOf(unitF) - units.indexOf(unitT);
if (unitT === 'B') {
unitT = 'Bytes';
}
if (i > 0) {
while (i-- > 0) {
size *= 1024;
}
} else if (i < 0) {
while (i++ < 0) {
size /= 1024;
}
}
if (size < 1 && size.toString().length > size.toFixed(2).length) {
size = size.toFixed(2);
}
}
return "" + size + " " + unitT;
},
formatters: {
t: function() {
return FileInfo.data.link.match(/\d+\.\w+$/)[0];
},
T: function() {
return '<a href="' + Build.escape(FileInfo.data.link) + '" target="_blank">' + (this.t()) + '</a>';
},
l: function() {
return '<a href="' + Build.escape(FileInfo.data.link) + '" target="_blank">' + (this.n()) + '</a>';
},
L: function() {
return '<a href="' + Build.escape(FileInfo.data.link) + '" target="_blank">' + (this.N()) + '</a>';
},
n: function() {
if (FileInfo.data.fullname === FileInfo.data.shortname) {
return Build.escape(FileInfo.data.fullname);
} else {
return '<span class="fntrunc">' + Build.escape(FileInfo.data.shortname) + '</span><span class="fnfull">' + Build.escape(FileInfo.data.fullname) + '</span>';
}
},
N: function() {
return Build.escape(FileInfo.data.fullname);
},
p: function() {
if (FileInfo.data.spoiler) {
return 'Spoiler, ';
} else {
return '';
}
},
s: function() {
return "" + FileInfo.data.size + " " + FileInfo.data.unit;
},
B: function() {
return FileInfo.convertUnit('B');
},
K: function() {
return FileInfo.convertUnit('KB');
},
M: function() {
return FileInfo.convertUnit('MB');
},
r: function() {
return FileInfo.data.resolution;
}
}
};
Get = {
post: function(board, threadID, postID, root, cb) {
var post, url;
if (board === g.BOARD && (post = $.id("pc" + postID))) {
$.add(root, Get.cleanPost(post.cloneNode(true)));
return;
}
root.textContent = "Loading post No." + postID + "...";
if (threadID) {
return $.cache("//a.4cdn.org/" + board + "/thread/" + threadID + ".json", function() {
return Get.parsePost(this, board, threadID, postID, root, cb);
});
} else if (url = Redirect.post(board, postID)) {
return $.cache(url, function() {
return Get.parseArchivedPost(this, board, postID, root, cb);
});
}
},
parsePost: function(req, board, threadID, postID, root, cb) {
var post, posts, spoilerRange, status, url, _i, _len;
status = req.status;
if (status !== 200) {
if (url = Redirect.post(board, postID)) {
$.cache(url, function() {
return Get.parseArchivedPost(this, board, postID, root, cb);
});
} else {
$.addClass(root, 'warning');
root.textContent = status === 404 ? "Thread No." + threadID + " 404'd." : "Error " + req.status + ": " + req.statusText + ".";
}
return;
}
posts = JSON.parse(req.response).posts;
if (spoilerRange = posts[0].custom_spoiler) {
Build.spoilerRange[board] = spoilerRange;
}
postID = +postID;
for (_i = 0, _len = posts.length; _i < _len; _i++) {
post = posts[_i];
if (post.no === postID) {
break;
}
if (post.no > postID) {
if (url = Redirect.post(board, postID)) {
$.cache(url, function() {
return Get.parseArchivedPost(this, board, postID, root, cb);
});
} else {
$.addClass(root, 'warning');
root.textContent = "Post No." + postID + " was not found.";
}
return;
}
}
$.replace(root.firstChild, Get.cleanPost(Build.postFromObject(post, board)));
if (cb) {
return cb();
}
},
escape: function(text) {
return (text == null) ? null : Build.escape(text);
},
parseArchivedPost: function(req, board, postID, root, cb) {
var bq, comment, data, o, _ref;
data = JSON.parse(req.response);
if (data.error) {
$.addClass(root, 'warning');
root.textContent = data.error;
return;
}
bq = $.el('blockquote', {
textContent: data.comment
});
bq.innerHTML = bq.innerHTML.replace(/\n|\[\/?b\]|\[\/?spoiler\]|\[\/?code\]|\[\/?moot\]|\[\/?banned\]/g, function(text) {
switch (text) {
case '\n':
return '<br>';
case '[b]':
return '<b>';
case '[/b]':
return '</b>';
case '[spoiler]':
return '<span class=spoiler>';
case '[/spoiler]':
return '</span>';
case '[code]':
return '<pre class=prettyprint>';
case '[/code]':
return '</pre>';
case '[moot]':
return '<div style="padding:5px;margin-left:.5em;border-color:#faa;border:2px dashed rgba(255,0,0,.1);border-radius:2px">';
case '[/moot]':
return '</div>';
case '[banned]':
return '<b style="color: red;">';
case '[/banned]':
return '</b>';
}
});
comment = bq.innerHTML.replace(/(^|>)(>[^<$]*)(<|$)/g, '$1<span class=quote>$2</span>$3');
comment = comment.replace(/((>){2}(>\/[a-z\d]+\/)?\d+)/g, '<span class=deadlink>$1</span>');
o = {
postID: postID,
threadID: Get.escape(data.thread_num),
board: board,
name: Get.escape(data.name),
capcode: (function() {
switch (data.capcode) {
case 'M':
return 'mod';
case 'A':
return 'admin';
case 'D':
return 'developer';
}
})(),
tripcode: Get.escape(data.trip),
uniqueID: Get.escape(data.poster_hash),
email: data.email ? Get.escape(encodeURI(data.email)) : '',
subject: Get.escape(data.title),
flagCode: Get.escape(data.poster_country),
flagName: data.poster_country_name ? Get.escape(data.poster_country_name) : '',
date: Get.escape(data.fourchan_date),
dateUTC: +data.timestamp,
comment: comment
};
if ((_ref = data.media) != null ? _ref.media_filename : void 0) {
o.file = {
name: Get.escape(data.media.media_filename),
timestamp: Get.escape(data.media.media_orig),
url: Get.escape(data.media.media_link || data.media.remote_media_link),
height: Get.escape(data.media.media_h),
width: Get.escape(data.media.media_w),
MD5: Get.escape(data.media.media_hash),
size: Get.escape(data.media.media_size),
turl: Get.escape(data.media.thumb_link || ("//t.4cdn.org/" + board + "/" + data.media.preview_orig)),
theight: Get.escape(data.media.preview_h),
twidth: Get.escape(data.media.preview_w),
isSpoiler: data.media.spoiler === '1'
};
}
$.replace(root.firstChild, Get.cleanPost(Build.post(o, true)));
if (cb) {
return cb();
}
},
cleanPost: function(root) {
var child, el, els, inline, inlined, now, post, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2;
post = $('.post', root);
_ref = Array.prototype.slice.call(root.childNodes);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
if (child !== post) {
$.rm(child);
}
}
_ref1 = $$('.inline', post);
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
inline = _ref1[_j];
$.rm(inline);
}
_ref2 = $$('.inlined', post);
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
inlined = _ref2[_k];
$.rmClass(inlined, 'inlined');
}
now = Date.now();
els = $$('[id]', root);
els.push(root);
for (_l = 0, _len3 = els.length; _l < _len3; _l++) {
el = els[_l];
el.id = "" + now + "_" + el.id;
}
$.rmClass(root, 'forwarded');
$.rmClass(root, 'qphl');
$.rmClass(post, 'highlight');
$.rmClass(post, 'qphl');
root.hidden = post.hidden = false;
return root;
},
title: function(thread) {
var el, op, span;
op = $('.op', thread);
el = $('.postInfo .subject', op);
if (!el.textContent) {
el = $('blockquote', op);
if (!el.textContent) {
el = $('.nameBlock', op);
}
}
span = $.el('span', {
innerHTML: el.innerHTML.replace(/<br>/g, ' ')
});
return "/" + g.BOARD + "/ - " + (span.textContent.trim());
}
};
Build = {
escape: function(text) {
return (text + '').replace(/[&"'<>]/g, function(c) {
return {'&': '&', "'": ''', '"': '"', '<': '<', '>': '>'}[c];
});
},
spoilerRange: {},
shortFilename: function(filename, isOP) {
var threshold;
threshold = isOP ? 40 : 30;
if (filename.length - 4 > threshold) {
return "" + filename.slice(0, threshold - 5) + "(...)." + filename.slice(-3);
} else {
return filename;
}
},
postFromObject: function(data, board) {
var o;
o = {
postID: data.no,
threadID: data.resto || data.no,
board: board,
name: data.name,
capcode: data.capcode,
tripcode: data.trip,
uniqueID: data.id,
email: data.email ? encodeURI(data.email.replace(/"/g, '"')) : '',
subject: data.sub,
flagCode: data.country,
flagName: data.country_name,
date: data.now,
dateUTC: data.time,
comment: data.com,
isSticky: !!data.sticky,
isClosed: !!data.closed
};
if (data.ext || data.filedeleted) {
o.file = {
name: data.filename + data.ext,
timestamp: "" + data.tim + data.ext,
url: board === 'f' ? "//i.4cdn.org/" + board + "/" + (encodeURIComponent(data.filename)) + data.ext : "//i.4cdn.org/" + board + "/" + data.tim + data.ext,
height: data.h,
width: data.w,
MD5: data.md5,
size: data.fsize,
turl: "//t.4cdn.org/" + board + "/" + data.tim + "s.jpg",
theight: data.tn_h,
twidth: data.tn_w,
isSpoiler: !!data.spoiler,
isDeleted: !!data.filedeleted
};
}
return Build.post(o);
},
post: function(o, isArchived) {
/*
This function contains code from 4chan-JS (https://github.com/4chan/4chan-JS).
@license: https://github.com/4chan/4chan-JS/blob/master/LICENSE
*/
var a, board, capcode, capcodeClass, capcodeStart, closed, comment, container, date, dateUTC, email, emailEnd, emailStart, ext, file, fileDims, fileHTML, fileInfo, fileSize, fileThumb, filename, flag, flagCode, flagName, href, imgSrc, isClosed, isOP, isSticky, name, postID, quote, shortFilename, spoilerRange, staticPath, sticky, subject, threadID, tripcode, uniqueID, userID, _i, _len, _ref;
postID = o.postID, threadID = o.threadID, board = o.board, name = o.name, capcode = o.capcode, tripcode = o.tripcode, uniqueID = o.uniqueID, email = o.email, subject = o.subject, flagCode = o.flagCode, flagName = o.flagName, date = o.date, dateUTC = o.dateUTC, isSticky = o.isSticky, isClosed = o.isClosed, comment = o.comment, file = o.file;
isOP = postID === threadID;
staticPath = '//s.4cdn.org';
if (email) {
emailStart = '<a href="mailto:' + email + '" class="useremail">';
emailEnd = '</a>';
} else {
emailStart = '';
emailEnd = '';
}
subject = '<span class="subject">' + (subject || '') + '</span>';
userID = !capcode && uniqueID ? ' <span class="posteruid id_' + uniqueID + '">(ID: <span class="hand" title="Highlight posts by this ID">' + uniqueID + '</span>)</span> ' : '';
switch (capcode) {
case 'admin':
case 'admin_highlight':
capcodeClass = ' capcodeAdmin';
capcodeStart = ' <strong class="capcode hand id_admin" title="Highlight posts by the Administrator">## Admin</strong>';
capcode = ' <img src="' + staticPath + '/image/adminicon.gif" alt="This user is the 4chan Administrator." title="This user is the 4chan Administrator." class="identityIcon">';
break;
case 'mod':
capcodeClass = ' capcodeMod';
capcodeStart = ' <strong class="capcode hand id_mod" title="Highlight posts by Moderators">## Mod</strong>';
capcode = ' <img src="' + staticPath + '/image/modicon.gif" alt="This user is a 4chan Moderator." title="This user is a 4chan Moderator." class="identityIcon">';
break;
case 'developer':
capcodeClass = ' capcodeDeveloper';
capcodeStart = ' <strong class="capcode hand id_developer" title="Highlight posts by Developers">## Developer</strong>';
capcode = ' <img src="' + staticPath + '/image/developericon.gif" alt="This user is a 4chan Developer." title="This user is a 4chan Developer." class="identityIcon">';
break;
default:
capcodeClass = '';
capcodeStart = '';
capcode = '';
}
flag = flagCode ? ' <img src="' + staticPath + '/image/country/' + (board === 'pol' ? 'troll/' : '') + flagCode.toLowerCase() + '.gif" alt="' + flagCode + '" title="' + flagName + '" class="flag">' : '';
if (file != null ? file.isDeleted : void 0) {
fileHTML = isOP ? '<div class="file" id="f' + postID + '"><div class="fileInfo"></div><span class="fileThumb"><img src="' + staticPath + '/image/filedeleted.gif" alt="File deleted." class="fileDeleted retina"></span></div>' : '<div id="f' + postID + '" class="file"><span class="fileThumb"><img src="' + staticPath + '/image/filedeleted-res.gif" alt="File deleted." class="fileDeletedRes retina"></span></div>';
} else if (file) {
ext = file.name.slice(-3);
if (!file.twidth && !file.theight && ext === 'gif') {
file.twidth = file.width;
file.theight = file.height;
}
fileSize = $.bytesToString(file.size);
fileThumb = file.turl;
if (file.isSpoiler) {
fileSize = 'Spoiler Image, ' + fileSize;
if (!isArchived) {
fileThumb = '//s.4cdn.org/image/spoiler';
if (spoilerRange = Build.spoilerRange[board]) {
fileThumb += '-' + board + Math.floor(1 + spoilerRange * Math.random());
}
fileThumb += '.png';
file.twidth = file.theight = 100;
}
}
imgSrc = board === 'f' ? '' : '<a class="fileThumb' + (file.isSpoiler ? ' imgspoiler' : '') + '" href="' + file.url + '" target="_blank"><img src="' + fileThumb + '" alt="' + fileSize + '" data-md5="' + file.MD5 + '" style="width:' + file.twidth + 'px;height:' + file.theight + 'px"></a>';
filename = file.name.replace(/&(amp|#039|quot|lt|gt);/g, function (c) {
return {'&': '&', ''': "'", '"': '"', '<': '<', '>': '>'}[c];
}).replace(/%22/g, '"');
shortFilename = Build.escape(Build.shortFilename(filename));
filename = Build.escape(filename);
fileDims = ext === 'pdf' ? 'PDF' : '' + file.width + 'x' + file.height;
fileInfo = '<div class="fileText" id="fT' + postID + '"' + (file.isSpoiler ? ' title="' + filename + '"' : '') + '>File: <a' + ((filename !== shortFilename && !file.isSpoiler) ? ' title="' + filename + '"' : '') + ' href="' + file.url + '" target="_blank">' + (file.isSpoiler ? 'Spoiler Image' : shortFilename) + '</a>-(' + fileSize + ', ' + fileDims + ')</div>';
fileHTML = '<div class="file" id="f' + postID + '">' + fileInfo + imgSrc + '</div>';
} else {
fileHTML = '';
}
tripcode = tripcode ? ' <span class="postertrip">' + tripcode + '</span>' : '';
sticky = isSticky ? ' <img src="//s.4cdn.org/image/sticky.gif" alt="Sticky" title="Sticky" style="height:16px;width:16px">' : '';
closed = isClosed ? ' <img src="//s.4cdn.org/image/closed.gif" alt="Closed" title="Closed" style="height:16px;width:16px">' : '';
container = $.el('div', {
id: 'pc' + postID,
className: 'postContainer ' + (isOP ? 'op' : 'reply') + 'Container',
innerHTML: (isOP ? '' : '<div class="sideArrows" id="sa' + postID + '">>></div>') + '<div id="p' + postID + '" class="post ' + (isOP ? 'op' : 'reply') + (capcode === 'admin_highlight' ? ' highlightPost' : '') + '"><div class="postInfoM mobile" id="pim' + postID + '"><span class="nameBlock' + capcodeClass + '"><span class="name">' + (name || '') + '</span>' + tripcode + capcodeStart + capcode + userID + flag + sticky + closed + '<br>' + subject + '</span><span class="dateTime postNum" data-utc="' + dateUTC + '">' + date + '<br><em><a href="/' + board + '/thread/' + threadID + '#p' + postID + '">No.</a><a href="' + (g.REPLY && g.THREAD_ID === threadID ? 'javascript:quote(' + postID + ')' : '/' + board + '/thread/' + threadID + '#q' + postID) + '">' + postID + '</a></em></span></div>' + (isOP ? fileHTML : '') + '<div class="postInfo desktop" id="pi' + postID + '"><input type="checkbox" name="' + postID + '" value="delete"> ' + subject + ' <span class="nameBlock' + capcodeClass + '">' + emailStart + '<span class="name">' + (name || '') + '</span>' + tripcode + capcodeStart + emailEnd + capcode + userID + flag + sticky + closed + ' </span> <span class="dateTime" data-utc="' + dateUTC + '">' + date + '</span> <span class="postNum desktop"><a href="/' + board + '/thread/' + threadID + '#p' + postID + '" title="Link to this post">No.</a><a href="' + (g.REPLY && +g.THREAD_ID === threadID ? 'javascript:quote(' + postID + ')' : '/' + board + '/thread/' + threadID + '#q' + postID) + '" title="Reply to this post">' + postID + '</a></span></div>' + (isOP ? '' : fileHTML) + '<blockquote class="postMessage" id="m' + postID + '">' + (comment || '') + '</blockquote> </div>'
});
_ref = $$('.quotelink', container);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
href = quote.getAttribute('href');
if (href[0] === '/') {
continue;
}
quote.href = '/' + board + '/thread/' + threadID + href;
}
return container;
}
};
TitlePost = {
init: function() {
if(Conf['Post in Title']) {
return d.title = Get.title();
}
var boardTitle;
return d.title = ((boardTitle = $('.boardTitle', d)) && boardTitle.textContent) || ((boardTitle = $('#boardNavDesktop .current', d)) && "/" + g.BOARD + "/ - " + boardTitle.title) || ("/" + g.BOARD + "/");
}
};
QuoteBacklink = {
init: function() {
return Main.callbacks.push(this.node);
},
funk: function(id) {
return Conf['backlink'].replace(/%id/g, id);
},
node: function(post) {
var a, container, el, link, qid, quote, quotes, _i, _len, _ref;
if (post.isInlined) {
return;
}
quotes = {};
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (quote.parentNode.parentNode.className === 'capcodeReplies') {
break;
}
if (quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname) && (qid = quote.hash.slice(2))) {
quotes[qid] = true;
}
}
a = $.el('a', {
href: "/" + g.BOARD + "/thread/" + post.threadID + "#p" + post.ID,
className: post.el.hidden ? 'filtered backlink' : 'backlink',
textContent: QuoteBacklink.funk(post.ID)
});
for (qid in quotes) {
if (!(el = $.id("pi" + qid)) || !Conf['OP Backlinks'] && /\bop\b/.test(el.parentNode.className)) {
continue;
}
link = a.cloneNode(true);
if (Conf['Quote Preview']) {
$.on(link, 'mouseover', QuotePreview.mouseover);
}
if (Conf['Quote Inline']) {
$.on(link, 'click', QuoteInline.toggle);
}
if (!(container = $.id("blc" + qid))) {
container = $.el('span', {
className: 'container',
id: "blc" + qid
});
$.add(el, container);
}
$.add(container, [$.tn(' '), link]);
}
}
};
QuoteInline = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var quote, _i, _j, _len, _len1, _ref, _ref1;
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (!(quote.hash && quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname) || /\bdeadlink\b/.test(quote.className))) {
continue;
}
$.on(quote, 'click', QuoteInline.toggle);
}
_ref1 = post.backlinks;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
quote = _ref1[_j];
$.on(quote, 'click', QuoteInline.toggle);
}
},
toggle: function(e) {
var id;
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey || e.button !== 0) {
return;
}
e.preventDefault();
id = this.dataset.id || this.hash.slice(2);
if (/\binlined\b/.test(this.className)) {
QuoteInline.rm(this, id);
} else {
if ($.x("ancestor::div[contains(@id,'p" + id + "')]", this)) {
return;
}
QuoteInline.add(this, id);
}
return this.classList.toggle('inlined');
},
add: function(q, id) {
var board, el, i, inline, isBacklink, path, postID, root, threadID;
if (q.host === 'boards.4chan.org') {
path = q.pathname.split('/');
board = path[1];
threadID = path[3];
postID = id;
} else {
board = q.dataset.board;
threadID = 0;
postID = q.dataset.id;
}
el = board === g.BOARD ? $.id("p" + postID) : false;
inline = $.el('div', {
id: "i" + postID,
className: el ? 'inline' : 'inline crosspost'
});
root = (isBacklink = /\bbacklink\b/.test(q.className)) ? q.parentNode : $.x('ancestor-or-self::*[parent::blockquote][1]', q);
$.after(root, inline);
Get.post(board, threadID, postID, inline);
if (!el) {
return;
}
if (isBacklink && Conf['Forward Hiding']) {
$.addClass(el.parentNode, 'forwarded');
++el.dataset.forwarded || (el.dataset.forwarded = 1);
}
if ((i = Unread.replies.indexOf(el)) !== -1) {
Unread.replies.splice(i, 1);
return Unread.update(true);
}
},
rm: function(q, id) {
var div, inlined, _i, _len, _ref;
div = $.x("following::div[@id='i" + id + "']", q);
$.rm(div);
if (!Conf['Forward Hiding']) {
return;
}
_ref = $$('.backlink.inlined', div);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
inlined = _ref[_i];
div = $.id(inlined.hash.slice(1));
if (!--div.dataset.forwarded) {
$.rmClass(div.parentNode, 'forwarded');
}
}
if (/\bbacklink\b/.test(q.className)) {
div = $.id("p" + id);
if (!--div.dataset.forwarded) {
return $.rmClass(div.parentNode, 'forwarded');
}
}
}
};
QuotePreview = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var quote, _i, _j, _len, _len1, _ref, _ref1;
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (!(quote.hash && quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname) || /\bdeadlink\b/.test(quote.className))) {
continue;
}
$.on(quote, 'mouseover', QuotePreview.mouseover);
}
_ref1 = post.backlinks;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
quote = _ref1[_j];
$.on(quote, 'mouseover', QuotePreview.mouseover);
}
},
mouseover: function(e) {
var board, el, path, postID, qp, quote, quoterID, threadID, _i, _len, _ref;
if (/\binlined\b/.test(this.className)) {
return;
}
if (qp = $.id('qp')) {
if (qp === UI.el) {
delete UI.el;
}
$.rm(qp);
}
if (UI.el) {
return;
}
if (this.host === 'boards.4chan.org') {
path = this.pathname.split('/');
board = path[1];
threadID = path[3];
postID = this.hash.slice(2);
} else {
board = this.dataset.board;
threadID = 0;
postID = this.dataset.id;
}
qp = UI.el = $.el('div', {
id: 'qp',
className: 'reply dialog'
});
UI.hover(e);
$.add(d.body, qp);
if (board === g.BOARD) {
el = $.id("p" + postID);
}
Get.post(board, threadID, postID, qp, function() {
var bq, img, post;
bq = $('blockquote', qp);
Main.prettify(bq);
post = {
el: qp,
blockquote: bq,
isArchived: /\barchivedPost\b/.test(qp.className)
};
if (img = $('img[data-md5]', qp)) {
post.fileInfo = img.parentNode.previousElementSibling;
post.img = img;
}
if (Conf['Reveal Spoilers']) {
RevealSpoilers.node(post);
}
if (Conf['Image Auto-Gif']) {
AutoGif.node(post);
}
if (Conf['Replace PNG']) {
ReplacePng.node(post);
}
if (Conf['Replace JPG']) {
ReplaceJpg.node(post);
}
if (Conf['Time Formatting']) {
Time.node(post);
}
if (Conf['File Info Formatting']) {
FileInfo.node(post);
}
if (Conf['Resurrect Quotes']) {
Quotify.node(post);
}
if (Conf['Anonymize']) {
return Anonymize.node(post);
}
});
$.on(this, 'mousemove', UI.hover);
$.on(this, 'mouseout click', QuotePreview.mouseout);
if (!el) {
return;
}
if (Conf['Quote Highlighting']) {
if (/\bop\b/.test(el.className)) {
$.addClass(el.parentNode, 'qphl');
} else {
$.addClass(el, 'qphl');
}
}
quoterID = $.x('ancestor::*[@id][1]', this).id.match(/\d+$/)[0];
_ref = $$('.quotelink, .backlink', qp);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (quote.hash.slice(2) === quoterID) {
$.addClass(quote, 'forwardlink');
}
}
},
mouseout: function(e) {
var el;
UI.hoverend();
if (el = $.id(this.hash.slice(1))) {
$.rmClass(el, 'qphl');
$.rmClass(el.parentNode, 'qphl');
}
$.off(this, 'mousemove', UI.hover);
return $.off(this, 'mouseout click', QuotePreview.mouseout);
}
};
/* Add (You) to posts function */
QuoteYou = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var quote, _i, _len, _ref;
if (post.isInlined && !post.isCrosspost) {
return;
}
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
yourPostsFromStorage = JSON.parse(sessionStorage.getItem('yourPosts'));
if (yourPostsFromStorage) {
var yourPostsFromStorageLength = yourPostsFromStorage.length;
for (var tempI = 0; tempI < yourPostsFromStorageLength; tempI++) {
if (quote.hash.slice(2) === yourPostsFromStorage[tempI]) {
$.add(quote, $.tn('\u00A0(You)'));
}
}
}
}
}
};
QuoteOP = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var quote, _i, _len, _ref;
if (post.isInlined && !post.isCrosspost) {
return;
}
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (quote.hash.slice(2) === post.threadID) {
$.add(quote, $.tn('\u00A0(OP)'));
}
}
}
};
QuoteCT = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var path, quote, _i, _len, _ref;
if (post.isInlined && !post.isCrosspost) {
return;
}
_ref = post.quotes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
quote = _ref[_i];
if (!(quote.hash && quote.hostname === 'boards.4chan.org' && !/catalog$/.test(quote.pathname))) {
continue;
}
path = quote.pathname.split('/');
if (path[1] === g.BOARD && path[3] !== post.threadID) {
$.add(quote, $.tn('\u00A0(Cross-thread)'));
}
}
}
};
Quotify = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var a, board, deadlink, id, m, postBoard, quote, _i, _len, _ref, _ref1;
if (post.isInlined && !post.isCrosspost) {
return;
}
_ref = $$('.deadlink', post.blockquote);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
deadlink = _ref[_i];
if (deadlink.parentNode.className === 'prettyprint') {
$.replace(deadlink, Array.prototype.slice.call(deadlink.childNodes));
continue;
}
quote = deadlink.textContent;
a = $.el('a', {
textContent: "" + quote + "\u00A0(Dead)"
});
if (!(id = (_ref1 = quote.match(/\d+$/)) != null ? _ref1[0] : void 0)) {
continue;
}
if (m = quote.match(/^>>>\/([a-z\d]+)/)) {
board = m[1];
} else if (postBoard) {
board = postBoard;
} else {
board = postBoard = $('a[title="Link to this post"]', post.el).pathname.split('/')[1];
}
if (board === g.BOARD && $.id("p" + id)) {
a.href = "#p" + id;
a.className = 'quotelink';
} else {
a.href = Redirect.to({
board: board,
threadID: 0,
postID: id
});
a.className = 'deadlink';
a.target = '_blank';
if (Redirect.post(board, id)) {
$.addClass(a, 'quotelink');
a.setAttribute('data-board', board);
a.setAttribute('data-id', id);
}
}
$.replace(deadlink, a);
}
}
};
DeleteLink = {
init: function() {
var aImage, aPost, children, div;
div = $.el('div', {
className: 'delete_link',
textContent: 'Delete'
});
aPost = $.el('a', {
className: 'delete_post',
href: 'javascript:;'
});
aImage = $.el('a', {
className: 'delete_image',
href: 'javascript:;'
});
children = [];
children.push({
el: aPost,
open: function() {
aPost.textContent = 'Post';
$.on(aPost, 'click', DeleteLink["delete"]);
return true;
}
});
children.push({
el: aImage,
open: function(post) {
if (!post.img) {
return false;
}
aImage.textContent = 'Image';
$.on(aImage, 'click', DeleteLink["delete"]);
return true;
}
});
Menu.addEntry({
el: div,
open: function(post) {
var node, seconds;
if (post.isArchived) {
return false;
}
node = div.firstChild;
if (seconds = DeleteLink.cooldown[post.ID]) {
node.textContent = "Delete (" + seconds + ")";
DeleteLink.cooldown.el = node;
} else {
node.textContent = 'Delete';
delete DeleteLink.cooldown.el;
}
return true;
},
children: children
});
return $.on(d, 'QRPostSuccessful', this.cooldown.start);
},
"delete": function() {
var board, form, id, m, menu, pwd, self;
menu = $.id('menu');
id = menu.dataset.id;
if (DeleteLink.cooldown[id]) {
return;
}
$.off(this, 'click', DeleteLink["delete"]);
this.textContent = 'Deleting...';
pwd = (m = d.cookie.match(/4chan_pass=([^;]+)/)) ? decodeURIComponent(m[1]) : $.id('delPassword').value;
board = $('a[title="Link to this post"]', $.id(menu.dataset.rootid)).pathname.split('/')[1];
self = this;
form = {
mode: 'usrdel',
onlyimgdel: /\bdelete_image\b/.test(this.className),
pwd: pwd
};
form[id] = 'delete';
return $.ajax($.id('delform').action.replace("/" + g.BOARD + "/", "/" + board + "/"), {
onload: function() {
return DeleteLink.load(self, this.response);
},
onerror: function() {
return DeleteLink.error(self);
}
}, {
form: $.formData(form)
});
},
load: function(self, html) {
var doc, msg, s;
doc = d.implementation.createHTMLDocument('');
doc.documentElement.innerHTML = html;
if (doc.title === '4chan - Banned') {
s = 'Banned!';
} else if (msg = doc.getElementById('errmsg')) {
s = msg.textContent;
$.on(self, 'click', DeleteLink["delete"]);
} else {
s = 'Deleted';
}
return self.textContent = s;
},
error: function(self) {
self.textContent = 'Connection error, please retry.';
return $.on(self, 'click', DeleteLink["delete"]);
},
cooldown: {
start: function(e) {
var seconds;
seconds = 60;
return DeleteLink.cooldown.count(e.detail.postID, seconds, seconds);
},
count: function(postID, seconds, length) {
var el;
if (!((0 <= seconds && seconds <= length))) {
return;
}
setTimeout(DeleteLink.cooldown.count, 1000, postID, seconds - 1, length);
el = DeleteLink.cooldown.el;
if (seconds === 0) {
if (el != null) {
el.textContent = 'Delete';
}
delete DeleteLink.cooldown[postID];
delete DeleteLink.cooldown.el;
return;
}
if (el != null) {
el.textContent = "Delete (" + seconds + ")";
}
return DeleteLink.cooldown[postID] = seconds;
}
}
};
ReportLink = {
init: function() {
var a;
a = $.el('a', {
className: 'report_link',
href: 'javascript:;',
textContent: 'Report this post'
});
$.on(a, 'click', this.report);
return Menu.addEntry({
el: a,
open: function(post) {
return post.isArchived === false;
}
});
},
report: function() {
var a, id, set, url;
a = $('a[title="Link to this post"]', $.id(this.parentNode.dataset.rootid));
url = "//sys.4chan.org/" + (a.pathname.split('/')[1]) + "/imgboard.php?mode=report&no=" + this.parentNode.dataset.id;
id = Date.now();
set = "toolbar=0,scrollbars=0,location=0,status=1,menubar=0,resizable=1,width=685,height=200";
return window.open(url, id, set);
}
};
DownloadLink = {
init: function() {
var a;
if ($.el('a').download === void 0) {
return;
}
a = $.el('a', {
className: 'download_link',
textContent: 'Download file'
});
if($.engine === "gecko") {
$.on(a, 'click', function(e) {
if (this.protocol === 'blob:') {
return true;
}
e.preventDefault();
return DownloadLink.firefoxDL(this.href, (function(_this) {
return function(blob) {
if (blob) {
_this.href = URL.createObjectURL(blob);
return _this.click();
}
};
})(this));
});
}
return Menu.addEntry({
el: a,
open: function(post) {
var fileText;
if (!post.img) {
return false;
}
a.href = post.img.parentNode.href;
fname = post.fileInfo.firstElementChild.childNodes[1] || post.fileInfo.firstElementChild.childNodes[0];
a.download = Conf['File Info Formatting'] ? fname.textContent : post.fileInfo.firstElementChild.title;
return true;
}
});
},
firefoxDL: (function() {
var makeBlob;
makeBlob = function(urlBlob, contentType, contentDisposition, url) {
var blob, match, mime, name, _ref, _ref1, _ref2;
name = (_ref = url.match(/([^\/]+)\/*$/)) != null ? _ref[1] : void 0;
mime = (contentType != null ? contentType.match(/[^;]*/)[0] : void 0) || 'application/octet-stream';
match = (contentDisposition != null ? (_ref1 = contentDisposition.match(/\bfilename\s*=\s*"((\\"|[^"])+)"/i)) != null ? _ref1[1] : void 0 : void 0) || (contentType != null ? (_ref2 = contentType.match(/\bname\s*=\s*"((\\"|[^"])+)"/i)) != null ? _ref2[1] : void 0 : void 0);
if (match) {
name = match.replace(/\\"/g, '"');
}
blob = new Blob([urlBlob], {
type: mime
});
blob.name = name;
return blob;
};
return function(url, cb) {
return GM_xmlhttpRequest({
method: "GET",
url: url,
overrideMimeType: "text/plain; charset=x-user-defined",
onload: function(xhr) {
var contentDisposition, contentType, data, i, r, _ref, _ref1;
r = xhr.responseText;
data = new Uint8Array(r.length);
i = 0;
while (i < r.length) {
data[i] = r.charCodeAt(i);
i++;
}
contentType = (_ref = xhr.responseHeaders.match(/Content-Type:\s*(.*)/i)) != null ? _ref[1] : void 0;
contentDisposition = (_ref1 = xhr.responseHeaders.match(/Content-Disposition:\s*(.*)/i)) != null ? _ref1[1] : void 0;
return cb(makeBlob(data, contentType, contentDisposition, url));
},
onerror: function() {
return cb(null);
}
});
};
})()
};
ArchiveLink = {
init: function() {
var div, entry, type, _i, _len, _ref;
div = $.el('div', {
textContent: 'Archive'
});
entry = {
el: div,
open: function(post) {
var path;
path = $('a[title="Link to this post"]', post.el).pathname.split('/');
if ((Redirect.to({
board: path[1],
threadID: path[3],
postID: post.ID
})) === ("//boards.4chan.org/" + path[1] + "/")) {
return false;
}
post.info = [path[1], path[3]];
return true;
},
children: []
};
_ref = [['Post', 'apost'], ['Name', 'name'], ['Tripcode', 'tripcode'], ['Subject', 'subject'], ['Filename', 'filename'], ['Image MD5', 'md5']];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
type = _ref[_i];
entry.children.push(this.createSubEntry(type[0], type[1]));
}
return Menu.addEntry(entry);
},
createSubEntry: function(text, type) {
var el, open;
el = $.el('a', {
textContent: text,
target: '_blank'
});
open = function(post) {
var value;
if (type === 'apost') {
el.href = Redirect.to({
board: post.info[0],
threadID: post.info[1],
postID: post.ID
});
return true;
}
value = Filter[type](post);
if (!value) {
return false;
}
return el.href = Redirect.to({
board: post.info[0],
type: type,
value: value,
isSearch: true
});
};
return {
el: el,
open: open
};
}
};
ThreadStats = {
init: function() {
var dialog;
dialog = UI.dialog('stats', 'bottom: 0; left: 0;', '<div class=move><span id=postcount>0</span> / <span id=imagecount>0</span><span id=postercount></span><span id=currentpage></span></div>');
dialog.className = 'dialog';
$.add(d.body, dialog);
this.posts = this.images = 0;
this.imgLimit = (function() {
switch (g.BOARD) {
case 'a':
case 'b':
case 'v':
case 'co':
case 'mlp':
return 251;
case 'jp':
return 301;
case 'vg':
return 376;
default:
return 151;
}
})();
this.pageGradients = {
10 : 'FF0000',
9 : 'E50019',
8 : 'CC0033',
7 : 'B2004C',
6 : '990066',
5 : '7F007F',
4 : '650099',
3 : '4C00B2',
2 : '3300CC',
1 : '1900E5'
};
this.pageposGradients = {
15 : 'FF0011',
14 : 'EE0022',
13 : 'DD0033',
12 : 'CC0044',
11 : 'BB0055',
10 : 'AA0066',
9 : '990077',
8 : '880088',
7 : '770099',
6 : '6600AA',
5 : '5500BB',
4 : '4400CC',
3 : '3300DD',
2 : '2200EE',
1 : '1100FF'
};
if (Conf['Current Page']) {
this.pageInterval = setInterval(ThreadStats.fetchPages, 2 * $.MINUTE);
setTimeout(ThreadStats.fetchPages, 2 * $.SECOND); /* Interval starts with the timeout, so execute it this way the first time */
}
return Main.callbacks.push(this.node);
},
node: function(post) {
var imgcount;
if (post.isInlined) {
return;
}
$.id('postcount').textContent = ++ThreadStats.posts;
if (!post.img) {
return;
}
imgcount = $.id('imagecount');
imgcount.textContent = ++ThreadStats.images;
if (ThreadStats.images > ThreadStats.imgLimit) {
return $.addClass(imgcount, 'warning');
}
},
posterCount: function(poster_count) {
$.id('postercount').textContent = ' / ' + poster_count;
},
fetchPages: function() {
var request, url;
request = ThreadStats.request;
if (request) {
request.onloadend = null;
request.abort();
}
url = "//a.4cdn.org/" + g.BOARD + "/threads.json";
return ThreadStats.request = $.ajax(url, {
onloadend: ThreadStats.updatePage
});
},
updatePage: function() {
if (!(Conf['Current Page'] && this.status === 200)) {
return delete ThreadStats.request;
}
var newcontent, page, page_color, pagepos, pagepos_color, thread, _i, _j, _len, _len1, _ref1;
var parsed_threads = JSON.parse(this.response);
for (_i = 0, _len = parsed_threads.length; _i < _len; _i++) {
page = parsed_threads[_i];
_ref1 = page.threads;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
thread = _ref1[_j];
if (!(thread.no == g.THREAD_ID)) {
continue; /* == because g.THREAD_ID is a string */
}
page_color = page.page in ThreadStats.pageGradients ? ThreadStats.pageGradients[page.page] : '000000';
newcontent = ' / ' + '<span style="color:#' + page_color + ';">' + parseInt(page.page) + '</span>'; /* parseInt just to escape */
if (Conf['Current Page Position']) {
pagepos = _j + 1;
pagepos_color = pagepos in ThreadStats.pageposGradients ? ThreadStats.pageposGradients[pagepos] : '000000';
newcontent += ' (' + '<span style="color:#' + pagepos_color + ';">' + pagepos + '</span>' + '∕' + _ref1.length + ')';
}
$.id('currentpage').innerHTML = newcontent;
return delete ThreadStats.request;
}
}
/* If we get here the thread was not found in the catalog, stop updating */
clearInterval(ThreadStats.pageInterval);
$.id('currentpage').textContent = ' / X';
delete ThreadStats.request;
}
};
Unread = {
init: function() {
this.title = d.title;
$.on(d, 'QRPostSuccessful', this.post);
this.update();
$.on(window, 'scroll', Unread.scroll);
return Main.callbacks.push(this.node);
},
replies: [],
foresee: [],
post: function(e) {
return Unread.foresee.push(e.detail.postID);
},
node: function(post) {
var count, el, index;
if ((index = Unread.foresee.indexOf(post.ID)) !== -1) {
Unread.foresee.splice(index, 1);
return;
}
el = post.el;
if (el.hidden || /\bop\b/.test(post["class"]) || post.isInlined) {
return;
}
count = Unread.replies.push(el);
return Unread.update(count === 1);
},
scroll: function() {
var bottom, height, i, reply, _i, _len, _ref;
height = d.documentElement.clientHeight;
_ref = Unread.replies;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
reply = _ref[i];
bottom = reply.getBoundingClientRect().bottom;
if (bottom > height) {
break;
}
}
if (i === 0) {
return;
}
Unread.replies = Unread.replies.slice(i);
return Unread.update(Unread.replies.length === 0);
},
setTitle: function(count) {
if (this.scheduled) {
clearTimeout(this.scheduled);
delete Unread.scheduled;
this.setTitle(count);
return;
}
return this.scheduled = setTimeout((function() {
return d.title = "(" + count + ") " + Unread.title;
}), 5);
},
update: function(updateFavicon) {
var count;
if (!g.REPLY) {
return;
}
count = this.replies.length;
if (Conf['Unread Count']) {
this.setTitle(count);
}
if (!(Conf['Unread Favicon'] && updateFavicon)) {
return;
}
if ($.engine === 'presto') {
$.rm(Favicon.el);
}
Favicon.el.href = g.dead ? count ? Favicon.unreadDead : Favicon.dead : count ? Favicon.unread : Favicon["default"];
if (g.dead) {
$.addClass(Favicon.el, 'dead');
} else {
$.rmClass(Favicon.el, 'dead');
}
if (count) {
$.addClass(Favicon.el, 'unread');
} else {
$.rmClass(Favicon.el, 'unread');
}
if ($.engine !== 'webkit') {
return $.add(d.head, Favicon.el);
}
}
};
Favicon = {
init: function() {
var href;
if (this.el) {
return;
}
this.el = $('link[rel="shortcut icon"]', d.head);
this.el.type = 'image/x-icon';
href = this.el.href;
this.SFW = /ws.ico$/.test(href);
this["default"] = href;
return this["switch"]();
},
"switch": function() {
switch (Conf['favicon']) {
case 'ferongr':
this.unreadDead = 'data:image/gif;base64,R0lGODlhEAAQAOMHAOgLAnMFAL8AAOgLAukMA/+AgP+rq////////////////////////////////////yH5BAEKAAcALAAAAAAQABAAAARZ8MhJ6xwDWIBv+AM1fEEIBIVRlNKYrtpIECuGzuwpCLg974EYiXUYkUItjGbC6VQ4omXFiKROA6qSy0A8nAo9GS3YCswIWnOvLAi0be23Z1QtdSUaqXcviQAAOw==';
this.unreadSFW = 'data:image/gif;base64,R0lGODlhEAAQAOMHAADX8QBwfgC2zADX8QDY8nnl8qLp8v///////////////////////////////////yH5BAEKAAcALAAAAAAQABAAAARZ8MhJ6xwDWIBv+AM1fEEIBIVRlNKYrtpIECuGzuwpCLg974EYiXUYkUItjGbC6VQ4omXFiKROA6qSy0A8nAo9GS3YCswIWnOvLAi0be23Z1QtdSUaqXcviQAAOw==';
this.unreadNSFW = 'data:image/gif;base64,R0lGODlhEAAQAOMHAFT+ACh5AEncAFT+AFX/Acz/su7/5v///////////////////////////////////yH5BAEKAAcALAAAAAAQABAAAARZ8MhJ6xwDWIBv+AM1fEEIBIVRlNKYrtpIECuGzuwpCLg974EYiXUYkUItjGbC6VQ4omXFiKROA6qSy0A8nAo9GS3YCswIWnOvLAi0be23Z1QtdSUaqXcviQAAOw==';
break;
case 'xat-':
this.unreadDead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA2ElEQVQ4y61TQQrCMBDMQ8WDIEV6LbT2A4og2Hq0veo7fIAH04dY9N4xmyYlpGmI2MCQTWYy3Wy2DAD7B2wWAzWgcTgVeZKlZRxHNYFi2jM18oBh0IcKtC6ixf22WT4IFLs0owxswXu9egm0Ls6bwfCFfNsJYJKfqoEkd3vgUgFVLWObtzNgVKyruC+ljSzr5OEnBzjvjcQecaQhbZgBb4CmGQw+PoMkTUtdbd8VSEPakcGxPOcsoIgUKy0LecY29BmdBrqRfjIwZ93KLs5loHvBnL3cLH/jF+C/+z5dgUysAAAAAElFTkSuQmCC';
this.unreadSFW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA30lEQVQ4y2P4//8/AyWYgSoGQMF/GJ7Y11VVUVoyKTM9ey4Ig9ggMWQ1YA1IBvzXm34YjkH8mPyJB+Nqlp8FYRAbmxoMF6ArSNrw6T0Qf8Amh9cFMEWVR/7/A+L/uORxhgEIt5/+/3/2lf//5wAxiI0uj+4CBlBgxVUvOwtydgXQZpDmi2/+/7/0GmIQSAwkB1IDUkuUAZeABlx+g2zAZ9wGlAOjChba+LwAUgNSi2HA5Am9VciBhSsQQWyoWgZiovEDsdGI1QBYQiLJAGQalpSxyWEzAJYWkGm8clTJjQCZ1hkoVG0CygAAAABJRU5ErkJggg==';
this.unreadNSFW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA4ElEQVQ4y2P4//8/AyWYgSoGQMF/GJ7YNbGqrKRiUnp21lwQBrFBYshqwBqQDPifdsYYjkH8mInxB+OWx58FYRAbmxoMF6ArKPmU9B6IP2CTw+sCmKKe/5X/gPg/LnmcYQDCs/63/1/9fzYQzwGz0eXRXcAACqy4ZfFnQc7u+V/xD6T55v+LQHwJbBBIDCQHUgNSS5QBt4Cab/2/jDDgMx4DykrKJ8FCG58XQGpAajEMmNw7uQo5sHAFIogNVctATDR+IDYasRoAS0gkGYBMw5IyNjlsBsDSAjKNV44quREAx58Mr9vt5wQAAAAASUVORK5CYII=';
break;
case 'Mayhem':
this.unreadDead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABIUlEQVQ4jZ2ScWuDMBDFgw4pIkU0WsoQkWAYIkXZH4N9/+/V3dmfXSrKYIFHwt17j8vdGWNMIkgFuaDgzgQnwRs4EQs5KdolUQtagRN0givEDBTEOjgtGs0Zq8F7cKqqusVxrMQLaDUWcjBSrXkn8gs51tpJSWLk9b3HUa0aNIL5gPBR1/V4kJvR7lTwl8GmAm1Gf9+c3S+89qBHa8502AsmSrtBaEBPbIbj0ah2madlNAPEccdgJDfAtWifBjqWKShRBT6KoiH8QlEUn/qt0CCjnNdmPUwmFWzj9Oe6LpKuZXcwqq88z78Pch3aZU3dPwwc2sWlfZKCW5tWluV8kGvXClLm6dYN4/aUqfCbnEOzNDGhGZbNargvxCzvMGfRJD8UaDVvgkzo6QAAAABJRU5ErkJggg==';
this.unreadSFW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABCElEQVQ4jZ2S4crCMAxF+0OGDJEPKYrIGKOsiJSx/fJRfSAfTJNyKqXfiuDg0C25N2RJjTGmEVrhTzhw7oStsIEtsVzT4o2Jo9ALThiEM8IdHIgNaHo8mjNWg6/ske8bohPo+63QOLzmooHp8fyAICBSQkVz0QKdsFQEV6WSW/D+7+BbgbIDHcb4Kp61XyjyI16zZ8JemGltQtDBSGxB4/GoN+7TpkkjDCsFArm0IYv3U0BbnYtf8BCy+JytsE0X6VyuKhPPK/GAJ14kvZZDZVV3pZIb8MZr6n4o4PDGKn0S5SdDmyq5PnXQsk+Xbhinp03FFzmHJw6xYRiWm9VxnohZ3vOcxdO8ARmXRvbWdtzQAAAAAElFTkSuQmCC';
this.unreadNSFW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABCklEQVQ4jZ2S0WrDMAxF/TBCCKWMYhZKCSGYmFJMSNjD/mhf239qJXNcjBdTWODgRLpXKJKNMaYROuFTOHEehFb4gJZYrunwxsSXMApOmIQzwgOciE1oRjyaM1aDj+yR7xuiHvT9VmgcXnPRwO/9+wWCgEgJFc1FCwzCVhFclUpuw/u3g3cFyg50GPOjePZ+ocjPeM2RCXthpbUFwQAzsQ2Nx6PeuE+bJo0w7BQI5NKGLN5XAW11LX7BQ8jia7bCLl2kc7mqTLzuxAOeeJH0Wk6VVf0oldyEN15T948CDm+sMiZRfjK0pZIbUwcd+3TphnF62lR8kXN44hAbhmG5WQNnT8zynucsnuYJhFpBfkMzqD4AAAAASUVORK5CYII=';
break;
case 'Original':
this.unreadDead = 'data:image/gif;base64,R0lGODlhEAAQAKECAAAAAP8AAP///////yH5BAEKAAMALAAAAAAQABAAAAI/nI95wsqygIRxDgGCBhTrwF3Zxowg5H1cSopS6FrGQ82PU1951ckRmYKJVCXizLRC9kAnT0aIiR6lCFT1cigAADs=';
this.unreadSFW = 'data:image/gif;base64,R0lGODlhEAAQAKECAAAAAC6Xw////////yH5BAEKAAMALAAAAAAQABAAAAI/nI95wsqygIRxDgGCBhTrwF3Zxowg5H1cSopS6FrGQ82PU1951ckRmYKJVCXizLRC9kAnT0aIiR6lCFT1cigAADs=';
this.unreadNSFW = 'data:image/gif;base64,R0lGODlhEAAQAKECAAAAAGbMM////////yH5BAEKAAMALAAAAAAQABAAAAI/nI95wsqygIRxDgGCBhTrwF3Zxowg5H1cSopS6FrGQ82PU1951ckRmYKJVCXizLRC9kAnT0aIiR6lCFT1cigAADs=';
}
return this.unread = this.SFW ? this.unreadSFW : this.unreadNSFW;
},
empty: 'data:image/gif;base64,R0lGODlhEAAQAJEAAAAAAP///9vb2////yH5BAEAAAMALAAAAAAQABAAAAIvnI+pq+D9DBAUoFkPFnbs7lFZKIJOJJ3MyraoB14jFpOcVMpzrnF3OKlZYsMWowAAOw==',
dead: 'data:image/gif;base64,R0lGODlhEAAQAKECAAAAAP8AAP///////yH5BAEKAAIALAAAAAAQABAAAAIvlI+pq+D9DAgUoFkPDlbs7lFZKIJOJJ3MyraoB14jFpOcVMpzrnF3OKlZYsMWowAAOw=='
};
Redirect = {
image: function(board, filename) {
switch (board) {
case 'a':
case 'biz':
case 'c':
case 'co':
case 'diy':
case 'gd':
case 'jp':
case 'k':
case 'm':
case 'mlp':
case 'po':
case 'qa':
case 'sci':
case 'tg':
case 'u':
case 'v':
case 'vg':
case 'vp':
case 'vr':
case 'wsg':
return "https://archive.moe/" + board + "/full_image/" + filename;
case 'adv':
case 'f':
case 'hr':
case 'o':
case 'pol':
case 's4s':
case 'trv':
case 'tv':
case 'x':
return "//archive.4plebs.org/" + board + "/full_image/" + filename;
case 'd':
case 'e':
case 'i':
case 'lgbt':
case 't':
case 'w':
case 'wg':
return "//archive.loveisover.me/" + board + "/full_image/" + filename;
case 'cgl':
case 'g':
case 'mu':
return "https://archive.rebeccablacktech.com/" + board + "/full_image/" + filename;
case '3':
case 'ck':
case 'fa':
case 'ic':
case 'lit':
return "https://warosu.org/" + board + "/full_image/" + filename;
case 'asp':
case 'cm':
case 'h':
case 'hc':
case 'hm':
case 'n':
case 'p':
case 'r':
case 's':
case 'soc':
case 'y':
return "//fgts.jp/" + board + "/full_image/" + filename;
case 'an':
case 'fit':
case 'gif':
case 'int':
case 'out':
case 'r9k':
case 'toy':
return "http://imcute.yt/" + board + "/full_image/" + filename;
}
},
post: function(board, postID) {
switch (board) {
case 'a':
case 'biz':
case 'c':
case 'co':
case 'diy':
case 'gd':
case 'int':
case 'jp':
case 'k':
case 'm':
case 'mlp':
case 'out':
case 'po':
case 'qa':
case 'r9k':
case 'sci':
case 'tg':
case 'tv':
case 'u':
case 'v':
case 'vg':
case 'vp':
case 'vr':
case 'wsg':
return "https://archive.moe/_/api/chan/post/?board=" + board + "&num=" + postID;
case 'adv':
case 'f':
case 'hr':
case 'o':
case 'pol':
case 's4s':
case 'trv':
case 'x':
return "//archive.4plebs.org/_/api/chan/post/?board=" + board + "&num=" + postID;
case 'd':
case 'e':
case 'i':
case 'lgbt':
case 't':
case 'w':
case 'wg':
return "//archive.loveisover.me/_/api/chan/post/?board=" + board + "&num=" + postID;
case 'asp':
case 'cm':
case 'h':
case 'hc':
case 'hm':
case 'n':
case 'p':
case 'r':
case 's':
case 'soc':
case 'y':
return "//fgts.jp/_/api/chan/post/?board=" + board + "&num=" + postID;
case 'an':
case 'fit':
case 'gif':
case 'toy':
return "http://imcute.yt/_/api/chan/post/?board=" + board + "&num=" + postID;
}
},
to: function(data) {
var board, threadID, url;
if (!data.isSearch) {
threadID = data.threadID;
}
board = data.board;
switch (board) {
case 'a':
case 'biz':
case 'c':
case 'co':
case 'diy':
case 'gd':
case 'int':
case 'jp':
case 'k':
case 'm':
case 'mlp':
case 'out':
case 'po':
case 'qa':
case 'r9k':
case 'sci':
case 'tg':
case 'tv':
case 'u':
case 'v':
case 'vg':
case 'vp':
case 'vr':
case 'wsg':
url = Redirect.path('https://archive.moe', 'foolfuuka', data);
break;
case 'adv':
case 'f':
case 'hr':
case 'o':
case 'pol':
case 's4s':
case 'trv':
case 'x':
url = Redirect.path('//archive.4plebs.org', 'foolfuuka', data);
break;
case 'd':
case 'e':
case 'i':
case 'lgbt':
case 't':
case 'w':
case 'wg':
url = Redirect.path('//archive.loveisover.me', 'foolfuuka', data);
break;
case 'cgl':
case 'mu':
url = Redirect.path('https://archive.rebeccablacktech.com', 'fuuka', data);
break;
case '3':
case 'ck':
case 'fa':
case 'g':
case 'ic':
case 'lit':
url = Redirect.path('https://warosu.org', 'fuuka', data);
break;
case 'asp':
case 'cm':
case 'h':
case 'hc':
case 'hm':
case 'n':
case 'p':
case 'r':
case 's':
case 'soc':
case 'y':
url = Redirect.path('//fgts.jp', 'foolfuuka', data);
break;
case 'an':
case 'fit':
case 'gif':
case 'toy':
url = Redirect.path('http://imcute.yt', 'foolfuuka', data);
break;
default:
if (threadID) {
url = "//boards.4chan.org/" + board + "/";
}
}
return url || null;
},
path: function(base, archiver, data) {
var board, path, postID, threadID, type, value;
if (data.isSearch) {
board = data.board, type = data.type, value = data.value;
type = type === 'name' ? 'username' : type === 'md5' ? 'image' : type;
value = encodeURIComponent(value);
if (archiver === 'foolfuuka') {
return "" + base + "/" + board + "/search/" + type + "/" + value;
} else if (type === 'image') {
return "" + base + "/" + board + "/?task=search2&search_media_hash=" + value;
} else {
return "" + base + "/" + board + "/?task=search2&search_" + type + "=" + value;
}
}
board = data.board, threadID = data.threadID, postID = data.postID;
if (postID) {
postID = postID.match(/\d+/)[0];
}
path = threadID ? "" + board + "/thread/" + threadID : "" + board + "/post/" + postID;
if (archiver === 'foolfuuka') {
path += '/';
}
if (threadID && postID) {
path += archiver === 'foolfuuka' ? "#" + postID : "#p" + postID;
}
return "" + base + "/" + path;
}
};
ImageHover = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
if (!post.img || post.hasPdf) {
return;
}
return $.on(post.img, 'mouseover', ImageHover.mouseover);
},
mouseover: function() {
var el;
if (el = $.id('ihover')) {
if (el === UI.el) {
delete UI.el;
}
$.rm(el);
}
if (UI.el) {
return;
}
if (/\.webm$/.test(this.parentNode.href)) {
el = UI.el = $.el('video', {
id: 'ihover',
src: this.parentNode.href,
type: 'video/webm',
autoplay: true,
loop: true
});
} else {
el = UI.el = $.el('img', {
id: 'ihover',
src: this.parentNode.href
});
}
$.add(d.body, el);
$.on(el, 'load', ImageHover.load);
$.on(el, 'error', ImageHover.error);
$.on(this, 'mousemove', UI.hover);
return $.on(this, 'mouseout', ImageHover.mouseout);
},
load: function() {
var style;
if (!this.parentNode) {
return;
}
style = this.style;
return UI.hover({
clientX: -45 + parseInt(style.left),
clientY: 120 + parseInt(style.top)
});
},
error: function() {
var src, timeoutID, url,
_this = this;
src = this.src.split('/');
if (!(src[2] === 'i.4cdn.org' && (url = Redirect.image(src[3], src[4])))) {
if (g.dead) {
return;
}
url = "//i.4cdn.org/" + src[3] + "/" + src[4];
}
if ($.engine !== 'webkit' && url.split('/')[2] === 'i.4cdn.org') {
return;
}
timeoutID = setTimeout((function() {
return _this.src = url;
}), 3000);
if ($.engine !== 'webkit' || url.split('/')[2] !== 'i.4cdn.org') {
return;
}
return $.ajax(url, {
onreadystatechange: (function() {
if (this.status === 404) {
return clearTimeout(timeoutID);
}
})
}, {
type: 'head'
});
},
mouseout: function() {
UI.hoverend();
$.off(this, 'mousemove', UI.hover);
return $.off(this, 'mouseout', ImageHover.mouseout);
}
};
AutoGif = {
init: function() {
var _ref;
if ((_ref = g.BOARD) === 'gif' || _ref === 'wsg') {
return;
}
return Main.callbacks.push(this.node);
},
node: function(post) {
var gif, img, src;
img = post.img;
if (post.el.hidden || !img) {
return;
}
src = img.parentNode.href;
if (/gif$/.test(src) && !/spoiler/.test(img.src)) {
gif = $.el('img');
$.on(gif, 'load', function() {
return img.src = src;
});
return gif.src = src;
}
}
};
ReplacePng = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var png, img, src;
img = post.img;
if (post.el.hidden || !img) {
return;
}
src = img.parentNode.href;
if (/png$/.test(src) && !/spoiler/.test(img.src)) {
png = $.el('img');
$.on(png, 'load', function() {
return img.src = src;
});
return png.src = src;
}
}
};
ReplaceJpg = {
init: function() {
return Main.callbacks.push(this.node);
},
node: function(post) {
var jpg, img, src;
img = post.img;
if (post.el.hidden || !img) {
return;
}
src = img.parentNode.href;
if (/jpg$/.test(src) && !/spoiler/.test(img.src)) {
jpg = $.el('img');
$.on(jpg, 'load', function() {
return img.src = src;
});
return jpg.src = src;
}
}
};
ImageExpand = {
init: function() {
Main.callbacks.push(this.node);
return this.dialog();
},
node: function(post) {
var a;
if (!post.img || post.hasPdf) {
return;
}
a = post.img.parentNode;
$.on(a, 'click', ImageExpand.cb.toggle);
if (ImageExpand.on && !post.el.hidden) {
return ImageExpand.expand(post.img);
}
},
cb: {
toggle: function(e) {
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey || e.button !== 0) {
return;
}
e.preventDefault();
return ImageExpand.toggle(this);
},
all: function() {
var i, thumb, thumbs, _i, _j, _k, _len, _len1, _len2, _ref;
ImageExpand.on = this.checked;
if (ImageExpand.on) {
thumbs = $$('img[data-md5]');
if (Conf['Expand From Current']) {
for (i = _i = 0, _len = thumbs.length; _i < _len; i = ++_i) {
thumb = thumbs[i];
if (thumb.getBoundingClientRect().top > 0) {
break;
}
}
thumbs = thumbs.slice(i);
}
for (_j = 0, _len1 = thumbs.length; _j < _len1; _j++) {
thumb = thumbs[_j];
ImageExpand.expand(thumb);
}
} else {
_ref = $$('img[data-md5][hidden]');
for (_k = 0, _len2 = _ref.length; _k < _len2; _k++) {
thumb = _ref[_k];
ImageExpand.contract(thumb);
}
}
},
typeChange: function() {
var klass;
switch (this.value) {
case 'full':
klass = '';
break;
case 'fit width':
klass = 'fitwidth';
break;
case 'fit height':
klass = 'fitheight';
break;
case 'fit screen':
klass = 'fitwidth fitheight';
}
$.id('delform').className = klass;
if (/\bfitheight\b/.test(klass)) {
$.on(window, 'resize', ImageExpand.resize);
if (!ImageExpand.style) {
ImageExpand.style = $.addStyle('');
}
return ImageExpand.resize();
} else if (ImageExpand.style) {
return $.off(window, 'resize', ImageExpand.resize);
}
}
},
toggle: function(a) {
var rect, thumb;
thumb = a.firstChild;
if (thumb.hidden) {
rect = a.getBoundingClientRect();
if (rect.bottom > 0) {
if ($.engine === 'webkit') {
if (rect.top < 0) {
d.body.scrollTop += rect.top - 42;
}
if (rect.left < 0) {
d.body.scrollLeft += rect.left;
}
} else {
if (rect.top < 0) {
d.documentElement.scrollTop += rect.top - 42;
}
if (rect.left < 0) {
d.documentElement.scrollLeft += rect.left;
}
}
}
return ImageExpand.contract(thumb);
} else {
return ImageExpand.expand(thumb);
}
},
contract: function(thumb) {
thumb.hidden = false;
thumb.nextSibling.hidden = true;
if (thumb.nextSibling.nodeName === 'VIDEO') {
thumb.nextSibling.pause();
thumb.nextSibling.remove();
}
return $.rmClass(thumb.parentNode.parentNode.parentNode, 'image_expanded');
},
expand: function(thumb, src) {
var a, img;
if ($.x('ancestor-or-self::*[@hidden]', thumb)) {
return;
}
a = thumb.parentNode;
src || (src = a.href);
if (/\.pdf$/.test(src)) {
return;
}
thumb.hidden = true;
$.addClass(thumb.parentNode.parentNode.parentNode, 'image_expanded');
if ((img = thumb.nextSibling) && img.nodeName === 'IMG') {
img.hidden = false;
return;
}
/* a video in your img? it's more likely than you think */
if (/\.webm$/.test(src)) {
img = $.el('video', {
src: src,
type: 'video/webm',
autoplay: true,
loop: true
});
} else {
img = $.el('img', {
src: src
});
}
$.on(img, 'error', ImageExpand.error);
return $.after(thumb, img);
},
error: function() {
var src, thumb, timeoutID, url;
thumb = this.previousSibling;
ImageExpand.contract(thumb);
$.rm(this);
src = this.src.split('/');
if (!(src[2] === 'i.4cdn.org' && (url = Redirect.image(src[3], src[4])))) {
if (g.dead) {
return;
}
url = "//i.4cdn.org/" + src[3] + "/" + src[4];
}
if ($.engine !== 'webkit' && url.split('/')[2] === 'i.4cdn.org') {
return;
}
timeoutID = setTimeout(ImageExpand.expand, 10000, thumb, url);
if ($.engine !== 'webkit' || url.split('/')[2] !== 'i.4cdn.org') {
return;
}
return $.ajax(url, {
onreadystatechange: (function() {
if (this.status === 404) {
return clearTimeout(timeoutID);
}
})
}, {
type: 'head'
});
},
dialog: function() {
var controls, imageType, select;
controls = $.el('div', {
id: 'imgControls',
innerHTML: "<select id=imageType name=imageType><option value=full>Full</option><option value='fit width'>Fit Width</option><option value='fit height'>Fit Height</option value='fit screen'><option value='fit screen'>Fit Screen</option></select><label>Expand Images<input type=checkbox id=imageExpand></label>"
});
imageType = $.get('imageType', 'full');
select = $('select', controls);
select.value = imageType;
ImageExpand.cb.typeChange.call(select);
$.on(select, 'change', $.cb.value);
$.on(select, 'change', ImageExpand.cb.typeChange);
$.on($('input', controls), 'click', ImageExpand.cb.all);
return $.prepend($.id('delform'), controls);
},
resize: function() {
return ImageExpand.style.textContent = ".fitheight img[data-md5] + img {max-height:" + d.documentElement.clientHeight + "px;} .fitheight img[data-md5] + video {max-height:" + d.documentElement.clientHeight + "px;}";
}
};
RemoveSlug = {
init: function() {
var catalogdiv;
var threads = [];
if (g.CATALOG) {
catalogdiv = document.getElementsByClassName('thread');
for (var i = 0; i < catalogdiv.length; i++) {
threads.push(catalogdiv[i].firstElementChild);
}
} else {
threads = document.getElementsByClassName('replylink');
}
return RemoveSlug.deslug(threads);
},
deslug: function(els) {
var el;
for (var i = 0; i < els.length; i++) {
el = els[i];
path = el.pathname;
if (path.slice(1).split('/').length > 3) {
el.pathname = path.substring(0, path.lastIndexOf('/'));
}
}
return;
}
};
CatalogLinks = {
init: function() {
var clone, el, nav, _i, _len, _ref;
el = $.el('span', {
className: 'toggleCatalog',
innerHTML: '[<a href=javascript:;></a>]'
});
_ref = ['boardNavDesktop', 'boardNavDesktopFoot'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
nav = _ref[_i];
clone = el.cloneNode(true);
$.on(clone.firstElementChild, 'click', CatalogLinks.toggle);
$.add($.id(nav), clone);
}
return CatalogLinks.toggle(true);
},
toggle: function(onLoad) {
var a, board, nav, root, useCatalog, _i, _j, _len, _len1, _ref, _ref1;
if (onLoad === true) {
useCatalog = $.get('CatalogIsToggled', g.CATALOG);
} else {
useCatalog = this.textContent === 'Catalog Off';
$.set('CatalogIsToggled', useCatalog);
}
_ref = ['boardNavDesktop', 'boardNavDesktopFoot'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
nav = _ref[_i];
root = $.id(nav);
_ref1 = $$('a[href]', root.getElementsByClassName('boardList')[0]);
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
a = _ref1[_j];
board = a.pathname.split('/')[1];
if (board === 'f') {
a.pathname = '/f/';
continue;
}
a.pathname = "/" + board + "/" + (useCatalog ? 'catalog' : '');
}
a = $('.toggleCatalog', root).firstElementChild;
a.textContent = "Catalog " + (useCatalog ? 'On' : 'Off');
a.title = "Turn catalog links " + (useCatalog ? 'off' : 'on') + ".";
}
}
};
Main = {
init: function() {
var asap, key, path, pathname, settings, temp, val;
Main.flatten(null, Config);
path = location.pathname;
pathname = path.slice(1).split('/');
g.BOARD = pathname[0], temp = pathname[1];
switch (temp) {
case 'thread':
g.REPLY = true;
g.THREAD_ID = pathname[2];
break;
case 'catalog':
g.CATALOG = true;
}
for (key in Conf) {
val = Conf[key];
Conf[key] = $.get(key, val);
}
if (location.hostname === 'i.4cdn.org') {
$.ready(function() {
var url;
if (/^4chan - 404/.test(d.title) && Conf['404 Redirect']) {
path = location.pathname.split('/');
url = Redirect.image(path[1], path[2]);
if (url) {
return location.href = url;
}
}
});
return;
}
if (g.REPLY && pathname.length > 3 && Conf['Remove Slug']) {
window.location.pathname = path.substring(0, path.lastIndexOf('/')) + location.hash;
return;
}
if (Conf['Disable 4chan\'s extension']) {
settings = JSON.parse(localStorage.getItem('4chan-settings')) || {};
settings.disableAll = true;
settings.dropDownNav = false;
localStorage.setItem('4chan-settings', JSON.stringify(settings));
$.ready(function() { $.globalEval('window.removeEventListener("message", Report.onMessage, false);') });
}
Main.polyfill();
if (g.CATALOG) {
return $.ready(Main.catalog);
} else {
return Main.features();
}
},
polyfill: function() {
var event, prefix, property;
if (!('visibilityState' in document)) {
prefix = 'mozVisibilityState' in document ? 'moz' : 'webkitVisibilityState' in document ? 'webkit' : 'o';
property = prefix + 'VisibilityState';
event = prefix + 'visibilitychange';
d.visibilityState = d[property];
d.hidden = d.visibilityState === 'hidden';
return $.on(d, event, function() {
d.visibilityState = d[property];
d.hidden = d.visibilityState === 'hidden';
return $.event('visibilitychange', null, d);
});
}
},
catalog: function() {
if (Conf['Remove Slug']) {
$.ready(RemoveSlug.init);
}
if (Conf['Catalog Links']) {
$.ready(CatalogLinks.init);
}
if (Conf['Thread Hiding']) {
return ThreadHiding.init();
}
},
features: function() {
var cutoff, hiddenThreads, id, now, timestamp, _ref;
Options.init();
if (Conf['Quick Reply'] && Conf['Hide Original Post Form']) {
Main.css += '#postForm { display: none; }';
}
$.addStyle(Main.css);
now = Date.now();
if (Conf['Check for Updates'] && $.get('lastUpdate', 0) < now - 6 * $.HOUR) {
$.ready(function() {
$.on(window, 'message', Main.message);
$.set('lastUpdate', now);
return $.add(d.head, $.el('script', {
src: 'https://loadletter.github.io/4chan-x/latest.js'
}));
});
}
g.hiddenReplies = $.get("hiddenReplies/" + g.BOARD + "/", {});
if ($.get('lastChecked', 0) < now - 1 * $.DAY) {
$.set('lastChecked', now);
cutoff = now - 7 * $.DAY;
hiddenThreads = $.get("hiddenThreads/" + g.BOARD + "/", {});
for (id in hiddenThreads) {
timestamp = hiddenThreads[id];
if (timestamp < cutoff) {
delete hiddenThreads[id];
}
}
_ref = g.hiddenReplies;
for (id in _ref) {
timestamp = _ref[id];
if (timestamp < cutoff) {
delete g.hiddenReplies[id];
}
}
$.set("hiddenThreads/" + g.BOARD + "/", hiddenThreads);
$.set("hiddenReplies/" + g.BOARD + "/", g.hiddenReplies);
}
if (Conf['Filter']) {
Filter.init();
}
if (Conf['Reply Hiding']) {
ReplyHiding.init();
}
if (Conf['Filter'] || Conf['Reply Hiding']) {
StrikethroughQuotes.init();
}
if (Conf['Anonymize']) {
Anonymize.init();
}
if (Conf['Time Formatting']) {
Time.init();
}
if (Conf['Relative Post Dates']) {
RelativeDates.init();
}
if (Conf['File Info Formatting']) {
FileInfo.init();
}
if (Conf['Sauce']) {
Sauce.init();
}
if (Conf['Reveal Spoilers']) {
RevealSpoilers.init();
}
if (Conf['Image Auto-Gif']) {
AutoGif.init();
}
if (Conf['Replace PNG']) {
ReplacePng.init();
}
if (Conf['Replace JPG']) {
ReplaceJpg.init();
}
if (Conf['Image Hover']) {
ImageHover.init();
}
if (Conf['Menu']) {
Menu.init();
if (Conf['Report Link']) {
ReportLink.init();
}
if (Conf['Delete Link']) {
DeleteLink.init();
}
if (Conf['Filter']) {
Filter.menuInit();
}
if (Conf['Download Link']) {
DownloadLink.init();
}
if (Conf['Archive Link']) {
ArchiveLink.init();
}
}
if (Conf['Resurrect Quotes']) {
Quotify.init();
}
if (Conf['Quote Inline']) {
QuoteInline.init();
}
if (Conf['Quote Preview']) {
QuotePreview.init();
}
if (Conf['Quote Backlinks']) {
QuoteBacklink.init();
}
if (Conf['Indicate OP quote']) {
QuoteOP.init();
}
if (Conf['Indicate You quote']) {
QuoteYou.init();
}
if (Conf['Indicate Cross-thread Quotes']) {
QuoteCT.init();
}
return $.ready(Main.featuresReady);
},
featuresReady: function() {
var MutationObserver, a, board, node, nodes, observer, _j, _len1, _ref1;
if (/^4chan - 404/.test(d.title)) {
if (Conf['404 Redirect'] && /^\d+$/.test(g.THREAD_ID)) {
location.href = Redirect.to({
board: g.BOARD,
threadID: g.THREAD_ID,
postID: location.hash
});
}
return;
}
if (!$.id('navtopright')) {
return;
}
$.addClass(d.body, $.engine);
$.addClass(d.body, 'fourchan_x');
if (a = $("a[href$='/" + g.BOARD + "/']", $.id('boardNavDesktop'))) {
$.addClass(a, 'current');
}
$.ready(function () {
if (a = $("a[href$='/" + g.BOARD + "/']", $.id('boardNavDesktopFoot'))) {
$.addClass(a, 'current');
}
});
Favicon.init();
if (Conf['Quick Reply']) {
QR.init();
}
if (Conf['Image Expansion']) {
ImageExpand.init();
}
if (Conf['Catalog Links']) {
$.ready(CatalogLinks.init);
}
if (Conf['Thread Watcher']) {
setTimeout(function() {
return Watcher.init();
});
}
if (Conf['Keybinds']) {
setTimeout(function() {
return Keybinds.init();
});
}
if (g.REPLY) {
if (Conf['Thread Updater']) {
setTimeout(function() {
return Updater.init();
});
}
if (Conf['Thread Stats']) {
ThreadStats.init();
}
if (Conf['Reply Navigation']) {
setTimeout(function() {
return Nav.init();
});
}
TitlePost.init();
if (Conf['Unread Count'] || Conf['Unread Favicon']) {
Unread.init();
}
} else {
if (Conf['Remove Slug']) {
RemoveSlug.init();
}
if (Conf['Thread Hiding']) {
ThreadHiding.init();
}
if (Conf['Thread Expansion']) {
setTimeout(function() {
return ExpandThread.init();
});
}
if (Conf['Comment Expansion']) {
setTimeout(function() {
return ExpandComment.init();
});
}
if (Conf['Index Navigation']) {
setTimeout(function() {
return Nav.init();
});
}
}
board = $('.board');
nodes = [];
_ref1 = $$('.postContainer', board);
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
node = _ref1[_j];
nodes.push(Main.preParse(node));
}
Main.node(nodes, true);
Main.hasCodeTags = !!$('script[src^="//s.4cdn.org/js/prettify/prettify"]');
if (MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.OMutationObserver) {
observer = new MutationObserver(Main.observer);
observer.observe(board, {
childList: true,
subtree: true
});
} else {
$.on(board, 'DOMNodeInserted', Main.listener);
}
},
flatten: function(parent, obj) {
var key, val;
if (obj instanceof Array) {
Conf[parent] = obj[0];
} else if (typeof obj === 'object') {
for (key in obj) {
val = obj[key];
Main.flatten(key, val);
}
} else {
Conf[parent] = obj;
}
},
message: function(e) {
var version;
version = e.data.version;
if (version && version !== Main.version && confirm('An updated version of 4chan X is available, would you like to install it now?')) {
return window.location = "https://raw.github.com/loadletter/4chan-x/" + version + "/4chan_x.user.js";
}
},
preParse: function(node) {
var el, img, imgParent, parentClass, post;
parentClass = node.parentNode.className;
el = $('.post', node);
post = {
root: node,
el: el,
"class": el.className,
ID: el.id.match(/\d+$/)[0],
threadID: g.THREAD_ID || $.x('ancestor::div[parent::div[@class="board"]]', node).id.match(/\d+$/)[0],
isArchived: /\barchivedPost\b/.test(parentClass),
isInlined: /\binline\b/.test(parentClass),
isCrosspost: /\bcrosspost\b/.test(parentClass),
blockquote: el.lastElementChild,
quotes: el.getElementsByClassName('quotelink'),
backlinks: el.getElementsByClassName('backlink'),
fileInfo: false,
img: false
};
if (img = $('img[data-md5]', el)) {
imgParent = img.parentNode;
post.img = img;
post.fileInfo = imgParent.previousElementSibling;
post.hasPdf = /\.pdf$/.test(imgParent.href);
}
Main.prettify(post.blockquote);
return post;
},
node: function(nodes, notify) {
var callback, err, node, _i, _j, _len, _len1, _ref;
_ref = Main.callbacks;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
callback = _ref[_i];
try {
for (_j = 0, _len1 = nodes.length; _j < _len1; _j++) {
node = nodes[_j];
callback(node);
}
} catch (_error) {
err = _error;
if (notify) {
alert("4chan X (" + Main.version + ") error: " + err.message + "\nReport the bug at github.com/loadletter/4chan-x/issues\n\nURL: " + window.location + "\n" + err.stack);
}
}
}
},
observer: function(mutations) {
var addedNode, mutation, nodes, _i, _j, _len, _len1, _ref;
nodes = [];
for (_i = 0, _len = mutations.length; _i < _len; _i++) {
mutation = mutations[_i];
_ref = mutation.addedNodes;
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
addedNode = _ref[_j];
if (/\bpostContainer\b/.test(addedNode.className)) {
nodes.push(Main.preParse(addedNode));
}
}
}
if (nodes.length) {
return Main.node(nodes);
}
},
listener: function(e) {
var target;
target = e.target;
if (/\bpostContainer\b/.test(target.className)) {
return Main.node([Main.preParse(target)]);
}
},
prettify: function(bq) {
var code;
if (!Main.hasCodeTags) {
return;
}
code = function() {
var pre, _i, _len, _ref;
_ref = document.getElementById('_id_').getElementsByClassName('prettyprint');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
pre = _ref[_i];
pre.innerHTML = prettyPrintOne(pre.innerHTML.replace(/\s/g, ' '));
}
};
return $.globalEval(("(" + code + ")()").replace('_id_', bq.id));
},
namespace: '4chan_x.',
version: '2.40.49',
callbacks: [],
css: '\
/* dialog styling */\
.dialog.reply {\
display: block;\
border: 1px solid rgba(0,0,0,.25);\
padding: 0;\
}\
.move {\
cursor: move;\
}\
label, .favicon {\
cursor: pointer;\
}\
a[href="javascript:;"] {\
text-decoration: none;\
}\
.warning {\
color: red;\
}\
\
.hide_thread_button:not(.hidden_thread) {\
float: left;\
}\
\
.thread > .hidden_thread ~ *,\
[hidden],\
#content > [name=tab]:not(:checked) + div,\
#updater:not(:hover) > :not(.move),\
.autohide:not(:hover) > form,\
#qp input, .forwarded {\
display: none !important;\
}\
\
.menu_button {\
display: inline-block;\
}\
.menu_button > span {\
border-top: .5em solid;\
border-right: .3em solid transparent;\
border-left: .3em solid transparent;\
display: inline-block;\
margin: 2px;\
vertical-align: middle;\
}\
#menu {\
position: absolute;\
outline: none;\
}\
.entry {\
border-bottom: 1px solid rgba(0, 0, 0, .25);\
cursor: pointer;\
display: block;\
outline: none;\
padding: 3px 7px;\
position: relative;\
text-decoration: none;\
white-space: nowrap;\
}\
.entry:last-child {\
border: none;\
}\
.focused.entry {\
background: rgba(255, 255, 255, .33);\
}\
.entry.hasSubMenu {\
padding-right: 1.5em;\
}\
.hasSubMenu::after {\
content: "";\
border-left: .5em solid;\
border-top: .3em solid transparent;\
border-bottom: .3em solid transparent;\
display: inline-block;\
margin: .3em;\
position: absolute;\
right: 3px;\
}\
.hasSubMenu:not(.focused) > .subMenu {\
display: none;\
}\
.subMenu {\
position: absolute;\
left: 100%;\
top: 0;\
margin-top: -1px;\
}\
\
h1 {\
text-align: center;\
}\
#qr > .move {\
min-width: 300px;\
overflow: hidden;\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
padding: 0 2px;\
}\
#qr > .move > span {\
float: right;\
}\
#autohide, .close, #qr select, #dump, .remove, .captchaimg, #qr div.warning {\
cursor: pointer;\
}\
#qr select,\
#qr > form {\
margin: 0;\
}\
#dump {\
background: -webkit-linear-gradient(#EEE, #CCC);\
background: -moz-linear-gradient(#EEE, #CCC);\
background: -o-linear-gradient(#EEE, #CCC);\
background: linear-gradient(#EEE, #CCC);\
width: 10%;\
}\
.gecko #dump {\
padding: 1px 0 2px;\
}\
#dump:hover, #dump:focus {\
background: -webkit-linear-gradient(#FFF, #DDD);\
background: -moz-linear-gradient(#FFF, #DDD);\
background: -o-linear-gradient(#FFF, #DDD);\
background: linear-gradient(#FFF, #DDD);\
}\
#dump:active, .dump #dump:not(:hover):not(:focus) {\
background: -webkit-linear-gradient(#CCC, #DDD);\
background: -moz-linear-gradient(#CCC, #DDD);\
background: -o-linear-gradient(#CCC, #DDD);\
background: linear-gradient(#CCC, #DDD);\
}\
#qr:not(.dump) #replies, .dump > form > label {\
display: none;\
}\
#replies {\
display: block;\
height: 100px;\
position: relative;\
-webkit-user-select: none;\
-moz-user-select: none;\
-o-user-select: none;\
user-select: none;\
}\
#replies > div {\
counter-reset: thumbnails;\
top: 0; right: 0; bottom: 0; left: 0;\
margin: 0; padding: 0;\
overflow: hidden;\
position: absolute;\
white-space: pre;\
}\
#replies > div:hover {\
bottom: -10px;\
overflow-x: auto;\
z-index: 1;\
}\
.thumbnail {\
background-color: rgba(0,0,0,.2) !important;\
background-position: 50% 20% !important;\
background-size: cover !important;\
border: 1px solid #666;\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
cursor: move;\
display: inline-block;\
height: 90px; width: 90px;\
margin: 5px; padding: 2px;\
opacity: .5;\
outline: none;\
overflow: hidden;\
position: relative;\
text-shadow: 0 1px 1px #000;\
-webkit-transition: opacity .25s ease-in-out;\
-moz-transition: opacity .25s ease-in-out;\
-o-transition: opacity .25s ease-in-out;\
transition: opacity .25s ease-in-out;\
vertical-align: top;\
}\
.thumbnail:hover, .thumbnail:focus {\
opacity: .9;\
}\
.thumbnail#selected {\
opacity: 1;\
}\
.thumbnail::before {\
counter-increment: thumbnails;\
content: counter(thumbnails);\
color: #FFF;\
font-weight: 700;\
padding: 3px;\
position: absolute;\
top: 0;\
right: 0;\
text-shadow: 0 0 3px #000, 0 0 8px #000;\
}\
.thumbnail.drag {\
box-shadow: 0 0 10px rgba(0,0,0,.5);\
}\
.thumbnail.over {\
border-color: #FFF;\
}\
.thumbnail > span {\
color: #FFF;\
}\
.remove {\
background: none;\
color: #E00;\
font-weight: 700;\
padding: 3px;\
}\
.remove:hover::after {\
content: " Remove";\
}\
.thumbnail > label {\
background: rgba(0,0,0,.5);\
color: #FFF;\
right: 0; bottom: 0; left: 0;\
position: absolute;\
text-align: center;\
}\
.thumbnail > label > input {\
margin: 0;\
}\
#addReply {\
color: #333;\
font-size: 3.5em;\
line-height: 100px;\
}\
#addReply:hover, #addReply:focus {\
color: #000;\
}\
.field {\
border: 1px solid #CCC;\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
color: #333;\
font: 13px sans-serif;\
margin: 0;\
padding: 2px 4px 3px;\
-webkit-transition: color .25s, border .25s;\
-moz-transition: color .25s, border .25s;\
-o-transition: color .25s, border .25s;\
transition: color .25s, border .25s;\
}\
.field:-moz-placeholder,\
.field:hover:-moz-placeholder {\
color: #AAA;\
}\
.field:hover, .field:focus {\
border-color: #999;\
color: #000;\
outline: none;\
}\
#qr > form > div:first-child > .field:not(#dump) {\
width: 30%;\
}\
#qr textarea.field {\
display: -webkit-box;\
min-height: 160px;\
min-width: 100%;\
}\
#qr.captcha textarea.field {\
min-height: 120px;\
}\
.textarea {\
position: relative;\
}\
#charCount {\
color: #000;\
background: hsla(0, 0%, 100%, .5);\
font-size: 8pt;\
margin: 1px;\
position: absolute;\
bottom: 0;\
right: 0;\
pointer-events: none;\
}\
#charCount.warning {\
color: red;\
}\
#qr [type=file] {\
margin: 1px 0;\
width: 70%;\
}\
#qr [type=submit] {\
margin: 1px 0;\
padding: 1px; /* not Gecko */\
width: 30%;\
}\
.gecko #qr [type=submit] {\
padding: 0 1px; /* Gecko does not respect box-sizing: border-box */\
}\
\
.fileText:hover .fntrunc,\
.fileText:not(:hover) .fnfull {\
display: none;\
}\
.reply > .file > .fileText {\
margin: 0 20px;\
}\
\
.fitwidth img[data-md5] + img {\
max-width: 100%;\
}\
.gecko .fitwidth img[data-md5] + img,\
.presto .fitwidth img[data-md5] + img {\
width: 100%;\
}\
\
.fitwidth img[data-md5] + video {\
max-width: 100%;\
}\
.gecko .fitwidth img[data-md5] + video,\
.presto .fitwidth img[data-md5] + video {\
width: 100%;\
}\
\
#qr, #qp, #updater, #stats, #ihover, #overlay, #navlinks {\
position: fixed;\
}\
\
#ihover {\
max-height: 97%;\
max-width: 75%;\
padding-bottom: 18px;\
}\
\
#navlinks {\
font-size: 16px;\
top: 25px;\
right: 5px;\
}\
\
body {\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
}\
body.unscroll {\
overflow: hidden;\
}\
#overlay {\
top: 0;\
left: 0;\
width: 100%;\
height: 100%;\
text-align: center;\
background: rgba(0,0,0,.5);\
z-index: 1;\
}\
#overlay::after {\
content: "";\
display: inline-block;\
height: 100%;\
vertical-align: middle;\
}\
#options {\
box-sizing: border-box;\
-moz-box-sizing: border-box;\
display: inline-block;\
padding: 5px;\
position: relative;\
text-align: left;\
vertical-align: middle;\
width: 600px;\
max-width: 100%;\
height: 500px;\
max-height: 100%;\
}\
#credits {\
float: right;\
}\
#options ul {\
padding: 0;\
}\
#options article li {\
margin: 10px 0 10px 2em;\
}\
#options code {\
background: hsla(0, 0%, 100%, .5);\
color: #000;\
padding: 0 1px;\
}\
#options label {\
text-decoration: underline;\
}\
#content {\
overflow: auto;\
position: absolute;\
top: 2.5em;\
right: 5px;\
bottom: 5px;\
left: 5px;\
}\
#content textarea {\
font-family: monospace;\
min-height: 350px;\
resize: vertical;\
width: 100%;\
}\
\
#updater {\
text-align: right;\
}\
#updater:not(:hover) {\
border: none;\
background: transparent;\
}\
#updater input[type=number] {\
width: 4em;\
}\
.new {\
background: lime;\
}\
\
#watcher {\
padding-bottom: 5px;\
position: absolute;\
overflow: hidden;\
white-space: nowrap;\
}\
#watcher:not(:hover) {\
max-height: 220px;\
}\
#watcher > div {\
max-width: 200px;\
overflow: hidden;\
padding-left: 5px;\
padding-right: 5px;\
text-overflow: ellipsis;\
}\
#watcher > .move {\
padding-top: 5px;\
text-decoration: underline;\
}\
\
#qp {\
padding: 2px 2px 5px;\
}\
#qp .post {\
border: none;\
margin: 0;\
padding: 0;\
}\
#qp img {\
max-height: 300px;\
max-width: 500px;\
}\
.qphl {\
box-shadow: 0 0 0 2px rgba(216, 94, 49, .7);\
}\
.quotelink.deadlink {\
text-decoration: underline !important;\
}\
.deadlink:not(.quotelink) {\
text-decoration: none !important;\
}\
.inlined {\
opacity: .5;\
}\
.inline {\
background-color: rgba(255, 255, 255, 0.15);\
border: 1px solid rgba(128, 128, 128, 0.5);\
display: table;\
margin: 2px;\
padding: 2px;\
}\
.inline .post {\
background: none;\
border: none;\
margin: 0;\
padding: 0;\
}\
div.opContainer {\
display: block !important;\
}\
.opContainer.filter_highlight {\
box-shadow: inset 5px 0 rgba(255, 0, 0, .5);\
}\
.opContainer.filter_highlight.qphl {\
box-shadow: inset 5px 0 rgba(255, 0, 0, .5),\
0 0 0 2px rgba(216, 94, 49, .7);\
}\
.filter_highlight > .reply {\
box-shadow: -5px 0 rgba(255, 0, 0, .5);\
}\
.filter_highlight > .reply.qphl {\
box-shadow: -5px 0 rgba(255, 0, 0, .5),\
0 0 0 2px rgba(216, 94, 49, .7)\
}\
.filtered {\
text-decoration: underline line-through;\
}\
.quotelink.forwardlink,\
.backlink.forwardlink {\
text-decoration: none;\
border-bottom: 1px dashed;\
}\
'
};
Main.init();
}).call(this);
| Added option to run autoexpand automatically
| 4chan_x.user.js | Added option to run autoexpand automatically | <ide><path>chan_x.user.js
<ide> 'Relative Post Dates': [false, 'Display dates as "3 minutes ago" f.e., tooltip shows the timestamp'],
<ide> 'File Info Formatting': [true, 'Reformats the file information'],
<ide> 'Comment Expansion': [true, 'Expand too long comments'],
<add> 'Comment Auto-Expansion': [false, 'Autoexpand too long comments'],
<ide> 'Thread Expansion': [true, 'View all replies'],
<ide> 'Index Navigation': [true, 'Navigate to previous / next thread'],
<ide> 'Reply Navigation': [false, 'Navigate to top / bottom of thread'],
<ide> for (_i = 0, _len = _ref.length; _i < _len; _i++) {
<ide> a = _ref[_i];
<ide> $.on(a.firstElementChild, 'click', ExpandComment.expand);
<add> if (Conf['Comment Auto-Expansion']) {
<add> a.firstElementChild.click();
<add> }
<ide> }
<ide> },
<ide> expand: function(e) { |
|
Java | lgpl-2.1 | 611185728206737b635becf7e122b9cd1ab9d94f | 0 | codelibs/jcifs,AgNO3/jcifs-ng | /*
* © 2017 AgNO3 Gmbh & Co. KG
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package jcifs.smb;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jcifs.CIFSContext;
import jcifs.CIFSException;
import jcifs.Configuration;
import jcifs.DfsReferralData;
import jcifs.RuntimeCIFSException;
import jcifs.SmbConstants;
import jcifs.SmbResourceLocator;
import jcifs.SmbTreeHandle;
import jcifs.internal.CommonServerMessageBlockRequest;
import jcifs.internal.CommonServerMessageBlockResponse;
import jcifs.internal.RequestWithPath;
import jcifs.internal.dfs.DfsReferralDataInternal;
import jcifs.internal.smb1.com.SmbComClose;
import jcifs.internal.smb1.com.SmbComFindClose2;
import jcifs.internal.smb1.trans.nt.NtTransQuerySecurityDesc;
import jcifs.util.transport.TransportException;
/**
* This class encapsulates the logic for switching tree connections
*
* Switching trees can occur either when the tree has been disconnected by failure or idle-timeout - as well as on
* DFS referrals.
*
* @author mbechler
*
*/
class SmbTreeConnection {
private static final Logger log = LoggerFactory.getLogger(SmbTreeConnection.class);
private final CIFSContext ctx;
private final SmbTreeConnection delegate;
private SmbTreeImpl tree;
private volatile boolean treeAcquired;
private volatile boolean delegateAcquired;
private SmbTransportInternal exclusiveTransport;
private boolean nonPooled;
private final AtomicLong usageCount = new AtomicLong();
private static final Random RAND = new Random();
/**
* @param ctx
*
*/
public SmbTreeConnection ( CIFSContext ctx ) {
this.ctx = ctx;
this.delegate = null;
}
/**
* @param treeConnection
*/
public SmbTreeConnection ( SmbTreeConnection treeConnection ) {
this.ctx = treeConnection.ctx;
this.delegate = treeConnection;
}
/**
* @return the active configuration
*/
public Configuration getConfig () {
return this.ctx.getConfig();
}
private synchronized SmbTreeImpl getTree () {
SmbTreeImpl t = this.tree;
if ( t != null ) {
return t.acquire(false);
}
else if ( this.delegate != null ) {
this.tree = this.delegate.getTree();
return this.tree;
}
return t;
}
/**
* @return
*/
private synchronized SmbTreeImpl getTreeInternal () {
SmbTreeImpl t = this.tree;
if ( t != null ) {
return t;
}
if ( this.delegate != null ) {
return this.delegate.getTreeInternal();
}
return null;
}
/**
* @param t
*/
private synchronized void switchTree ( SmbTreeImpl t ) {
try ( SmbTreeImpl old = getTree() ) {
if ( old == t ) {
return;
}
boolean wasAcquired = this.treeAcquired;
log.debug("Switching tree");
if ( t != null ) {
log.debug("Acquired tree on switch " + t);
t.acquire();
this.treeAcquired = true;
}
else {
this.treeAcquired = false;
}
this.tree = t;
if ( old != null ) {
if ( wasAcquired ) {
// release
old.release(true);
}
}
if ( this.delegate != null && this.delegateAcquired ) {
log.debug("Releasing delegate");
this.delegateAcquired = false;
this.delegate.release();
}
}
}
/**
* @return tree connection with increased usage count
*/
public SmbTreeConnection acquire () {
long usage = this.usageCount.incrementAndGet();
if ( log.isTraceEnabled() ) {
log.trace("Acquire tree connection " + usage + " " + this);
}
if ( usage == 1 ) {
synchronized ( this ) {
try ( SmbTreeImpl t = getTree() ) {
if ( t != null ) {
if ( !this.treeAcquired ) {
if ( log.isDebugEnabled() ) {
log.debug("Acquire tree on first usage " + t);
}
t.acquire();
this.treeAcquired = true;
}
}
}
if ( this.delegate != null && !this.delegateAcquired ) {
log.debug("Acquire delegate on first usage");
this.delegate.acquire();
this.delegateAcquired = true;
}
}
}
return this;
}
/**
*
*/
public void release () {
long usage = this.usageCount.decrementAndGet();
if ( log.isTraceEnabled() ) {
log.trace("Release tree connection " + usage + " " + this);
}
if ( usage == 0 ) {
synchronized ( this ) {
try ( SmbTreeImpl t = getTree() ) {
if ( this.treeAcquired && t != null ) {
if ( log.isDebugEnabled() ) {
log.debug("Tree connection no longer in use, release tree " + t);
}
this.treeAcquired = false;
t.release();
}
}
if ( this.delegate != null && this.delegateAcquired ) {
this.delegateAcquired = false;
this.delegate.release();
}
}
SmbTransportInternal et = this.exclusiveTransport;
if ( et != null ) {
synchronized ( this ) {
try {
log.debug("Disconnecting exclusive transport");
this.exclusiveTransport = null;
this.tree = null;
this.treeAcquired = false;
et.close();
et.disconnect(false, false);
}
catch ( Exception e ) {
log.error("Failed to close exclusive transport", e);
}
}
}
}
else if ( usage < 0 ) {
log.error("Usage count dropped below zero " + this);
throw new RuntimeCIFSException("Usage count dropped below zero");
}
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize () throws Throwable {
if ( isConnected() && this.usageCount.get() != 0 ) {
log.warn("Tree connection was not properly released " + this);
}
}
synchronized void disconnect ( boolean inError ) {
try ( SmbSessionImpl session = getSession() ) {
if ( session == null ) {
return;
}
try ( SmbTransportImpl transport = session.getTransport() ) {
synchronized ( transport ) {
SmbTreeImpl t = getTreeInternal();
if ( t != null ) {
try {
t.treeDisconnect(inError, true);
}
finally {
this.tree = null;
this.treeAcquired = false;
}
}
else {
this.delegate.disconnect(inError);
}
}
}
}
}
<T extends CommonServerMessageBlockResponse> T send ( SmbResourceLocatorImpl loc, CommonServerMessageBlockRequest request, T response,
RequestParam... params ) throws CIFSException {
return send(loc, request, response, params.length == 0 ? EnumSet.noneOf(RequestParam.class) : EnumSet.copyOf(Arrays.asList(params)));
}
<T extends CommonServerMessageBlockResponse> T send ( SmbResourceLocatorImpl loc, CommonServerMessageBlockRequest request, T response,
Set<RequestParam> params ) throws CIFSException {
CIFSException last = null;
RequestWithPath rpath = ( request instanceof RequestWithPath ) ? (RequestWithPath) request : null;
String savedPath = rpath != null ? rpath.getPath() : null;
String savedFullPath = rpath != null ? rpath.getFullUNCPath() : null;
String fullPath = "\\" + loc.getServer() + "\\" + loc.getShare() + loc.getUNCPath();
int maxRetries = this.ctx.getConfig().getMaxRequestRetries();
for ( int retries = 1; retries <= maxRetries; retries++ ) {
if ( rpath != null ) {
rpath.setFullUNCPath(null, null, fullPath);
}
try {
return send0(loc, request, response, params);
}
catch ( SmbException smbe ) {
// Retrying only makes sense if the invalid parameter is an tree id. If we have a stale file descriptor
// retrying make no sense, as it will never become available again.
if ( params.contains(RequestParam.NO_RETRY)
|| ( ! ( smbe.getCause() instanceof TransportException ) ) && smbe.getNtStatus() != NtStatus.NT_STATUS_INVALID_PARAMETER ) {
log.debug("Not retrying", smbe);
throw smbe;
}
log.debug("send", smbe);
last = smbe;
}
catch ( CIFSException e ) {
log.debug("send", e);
last = e;
}
// If we get here, we got the 'The Parameter is incorrect' error or a transport exception
// Disconnect and try again from scratch.
if ( log.isDebugEnabled() ) {
log.debug(String.format("Retrying (%d/%d) request %s", retries, maxRetries, request));
}
// should we disconnect the transport here? otherwise we make an additional attempt to detect that if the
// server closed the connection as a result
log.debug("Disconnecting tree on send retry", last);
disconnect(true);
if ( retries >= maxRetries ) {
break;
}
try {
if ( retries != 1 ) {
// backoff, but don't delay the first attempt as there are various reasons that can be fixed
// immediately
Thread.sleep(500 + RAND.nextInt(1000));
}
}
catch ( InterruptedException e ) {
log.debug("interrupted sleep in send", e);
}
if ( request != null ) {
request.reset();
}
if ( rpath != null ) {
// resolveDfs() and tree.send() modify the request packet.
// I want to restore it before retrying. request.reset()
// restores almost everything that was modified, except the path.
rpath.setPath(savedPath);
rpath.setFullUNCPath(rpath.getDomain(), rpath.getServer(), savedFullPath);
}
if ( response != null ) {
response.reset();
}
try ( SmbTreeHandle th = connectWrapException(loc) ) {
log.debug("Have new tree connection for retry");
}
catch ( SmbException e ) {
log.debug("Failed to connect tree on retry", e);
last = e;
}
}
if ( last != null ) {
log.debug("All attempts have failed, last exception", last);
throw last;
}
throw new SmbException("All attempts failed, but no exception");
}
private <T extends CommonServerMessageBlockResponse> T send0 ( SmbResourceLocatorImpl loc, CommonServerMessageBlockRequest request, T response,
Set<RequestParam> params ) throws CIFSException, DfsReferral {
for ( int limit = 10; limit > 0; limit-- ) {
if ( request instanceof RequestWithPath ) {
ensureDFSResolved(loc, (RequestWithPath) request);
}
try ( SmbTreeImpl t = getTree() ) {
if ( t == null ) {
throw new CIFSException("Failed to get tree connection");
} ;
return t.send(request, response, params);
}
catch ( DfsReferral dre ) {
if ( dre.getData().unwrap(DfsReferralDataInternal.class).isResolveHashes() ) {
throw dre;
}
request.reset();
log.trace("send0", dre);
}
}
throw new CIFSException("Loop in DFS referrals");
}
/**
* @param loc
* @return tree handle
* @throws SmbException
*/
public SmbTreeHandleImpl connectWrapException ( SmbResourceLocatorImpl loc ) throws SmbException {
try {
return connect(loc);
}
catch ( UnknownHostException uhe ) {
throw new SmbException("Failed to connect to server", uhe);
}
catch ( SmbException se ) {
throw se;
}
catch ( IOException ioe ) {
throw new SmbException("Failed to connect to server", ioe);
}
}
/**
* @param loc
* @return tree handle
* @throws IOException
*/
public synchronized SmbTreeHandleImpl connect ( SmbResourceLocatorImpl loc ) throws IOException {
try ( SmbSessionImpl session = getSession() ) {
if ( isConnected() ) {
try ( SmbTransportImpl transport = session.getTransport() ) {
if ( transport.isDisconnected() || transport.getRemoteHostName() == null ) {
/*
* Tree/session thinks it is connected but transport disconnected
* under it, reset tree to reflect the truth.
*/
log.debug("Disconnecting failed tree and session");
disconnect(true);
}
}
}
if ( isConnected() ) {
log.trace("Already connected");
return new SmbTreeHandleImpl(loc, this);
}
return connectHost(loc, loc.getServerWithDfs());
}
}
/**
* @return whether we have a valid tree connection
*/
@SuppressWarnings ( "resource" )
public synchronized boolean isConnected () {
SmbTreeImpl t = getTreeInternal();
return t != null && t.isConnected();
}
/**
*
* @param loc
* @param host
* @return tree handle
* @throws IOException
*/
public synchronized SmbTreeHandleImpl connectHost ( SmbResourceLocatorImpl loc, String host ) throws IOException {
return connectHost(loc, host, null);
}
/**
*
* @param loc
* @param host
* @param referral
* @return tree handle
* @throws IOException
*/
public synchronized SmbTreeHandleImpl connectHost ( SmbResourceLocatorImpl loc, String host, DfsReferralData referral ) throws IOException {
String targetDomain = null;
try ( SmbTreeImpl t = getTree() ) {
if ( t != null ) {
if ( log.isDebugEnabled() ) {
log.debug("Tree is " + t);
}
if ( loc.getShare().equals(t.getShare()) ) {
try ( SmbSessionImpl session = t.getSession() ) {
targetDomain = session.getTargetDomain();
if ( !session.isFailed() ) {
try ( SmbTransportImpl trans = session.getTransport();
SmbTreeImpl ct = connectTree(loc, host, t.getShare(), trans, t, null) ) {
switchTree(ct);
return new SmbTreeHandleImpl(loc, this);
}
}
log.debug("Session no longer valid");
}
}
}
}
String hostName = loc.getServerWithDfs();
String path = ( loc.getType() == SmbConstants.TYPE_SHARE || loc.getUNCPath() == null || "\\".equals(loc.getUNCPath()) ) ? null
: loc.getUNCPath();
String share = loc.getShare();
DfsReferralData start = referral != null ? referral : this.ctx.getDfs().resolve(this.ctx, hostName, loc.getShare(), path);
DfsReferralData dr = start;
IOException last = null;
do {
if ( dr != null ) {
targetDomain = dr.getDomain();
host = dr.getServer().toLowerCase(Locale.ROOT);
share = dr.getShare();
}
try {
if ( this.nonPooled ) {
if ( log.isDebugEnabled() ) {
log.debug("Using exclusive transport for " + this);
}
this.exclusiveTransport = this.ctx.getTransportPool()
.getSmbTransport(this.ctx, host, loc.getPort(), true, loc.shouldForceSigning()).unwrap(SmbTransportInternal.class);
SmbTransportInternal trans = this.exclusiveTransport;
try ( SmbSessionInternal smbSession = trans.getSmbSession(this.ctx, host, targetDomain).unwrap(SmbSessionInternal.class);
SmbTreeImpl uct = smbSession.getSmbTree(share, null).unwrap(SmbTreeImpl.class);
SmbTreeImpl ct = connectTree(loc, host, share, trans, uct, dr) ) {
if ( dr != null ) {
ct.setTreeReferral(dr);
if ( dr != start ) {
dr.unwrap(DfsReferralDataInternal.class).replaceCache();
}
}
switchTree(ct);
return new SmbTreeHandleImpl(loc, this);
}
}
try ( SmbTransportInternal trans = this.ctx.getTransportPool()
.getSmbTransport(this.ctx, host, loc.getPort(), false, loc.shouldForceSigning()).unwrap(SmbTransportInternal.class);
SmbSessionInternal smbSession = trans.getSmbSession(this.ctx, host, targetDomain).unwrap(SmbSessionInternal.class);
SmbTreeImpl uct = smbSession.getSmbTree(share, null).unwrap(SmbTreeImpl.class);
SmbTreeImpl ct = connectTree(loc, host, share, trans, uct, dr) ) {
if ( dr != null ) {
ct.setTreeReferral(dr);
if ( dr != start ) {
dr.unwrap(DfsReferralDataInternal.class).replaceCache();
}
}
switchTree(ct);
return new SmbTreeHandleImpl(loc, this);
}
}
catch ( IOException e ) {
last = e;
log.debug("Referral failed, trying next", e);
}
if ( dr != null ) {
dr = dr.next();
}
}
while ( dr != start );
throw last;
}
/**
* @param loc
* @param addr
* @param trans
* @param t
* @throws CIFSException
*/
private SmbTreeImpl connectTree ( SmbResourceLocatorImpl loc, String addr, String share, SmbTransportInternal trans, SmbTreeImpl t,
DfsReferralData referral ) throws CIFSException {
if ( log.isDebugEnabled() && trans.isSigningOptional() && !loc.isIPC() && !this.ctx.getConfig().isSigningEnforced() ) {
log.debug("Signatures for file enabled but not required " + this);
}
if ( referral != null ) {
t.markDomainDfs();
}
try {
if ( log.isTraceEnabled() ) {
log.trace("doConnect: " + addr);
}
t.treeConnect(null, null);
return t.acquire();
}
catch ( SmbAuthException sae ) {
log.debug("Authentication failed", sae);
if ( t.getSession().getCredentials().isAnonymous() ) { // anonymous session, refresh
try ( SmbSessionInternal s = trans.getSmbSession(this.ctx.withAnonymousCredentials()).unwrap(SmbSessionInternal.class);
SmbTreeImpl tr = s.getSmbTree(null, null).unwrap(SmbTreeImpl.class) ) {
tr.treeConnect(null, null);
return tr.acquire();
}
}
else if ( this.ctx.renewCredentials(loc.getURL().toString(), sae) ) {
log.debug("Trying to renew credentials after auth error");
try ( SmbSessionInternal s = trans.getSmbSession(this.ctx, t.getSession().getTargetHost(), t.getSession().getTargetDomain())
.unwrap(SmbSessionInternal.class);
SmbTreeImpl tr = s.getSmbTree(share, null).unwrap(SmbTreeImpl.class) ) {
if ( referral != null ) {
tr.markDomainDfs();
}
tr.treeConnect(null, null);
return tr.acquire();
}
}
else {
throw sae;
}
}
}
SmbResourceLocator ensureDFSResolved ( SmbResourceLocatorImpl loc ) throws CIFSException {
return ensureDFSResolved(loc, null);
}
SmbResourceLocator ensureDFSResolved ( SmbResourceLocatorImpl loc, RequestWithPath request ) throws CIFSException {
if ( request instanceof SmbComClose )
return loc;
for ( int retries = 0; retries < 1 + this.ctx.getConfig().getMaxRequestRetries(); retries++ ) {
try {
return resolveDfs0(loc, request);
}
catch ( SmbException smbe ) {
// The connection may have been dropped?
if ( smbe.getNtStatus() != NtStatus.NT_STATUS_NOT_FOUND && ! ( smbe.getCause() instanceof TransportException ) ) {
throw smbe;
}
log.debug("resolveDfs", smbe);
}
// If we get here, we apparently have a bad connection.
// Disconnect and try again.
if ( log.isDebugEnabled() ) {
log.debug("Retrying (" + retries + ") resolveDfs: " + request);
}
log.debug("Disconnecting tree on DFS retry");
disconnect(true);
try {
Thread.sleep(500 + RAND.nextInt(5000));
}
catch ( InterruptedException e ) {
log.debug("resolveDfs", e);
}
try ( SmbTreeHandle th = connectWrapException(loc) ) {}
}
return loc;
}
private SmbResourceLocator resolveDfs0 ( SmbResourceLocatorImpl loc, RequestWithPath request ) throws CIFSException {
try ( SmbTreeHandleImpl th = connectWrapException(loc);
SmbSessionImpl session = th.getSession();
SmbTransportImpl transport = session.getTransport();
SmbTreeImpl t = getTree() ) {
transport.ensureConnected();
String rpath = request != null ? request.getPath() : loc.getUNCPath();
String rfullpath = request != null ? request.getFullUNCPath() : ( '\\' + loc.getServer() + '\\' + loc.getShare() + loc.getUNCPath() );
if ( t.isInDomainDfs() || !t.isPossiblyDfs() ) {
if ( t.isInDomainDfs() ) {
// need to adjust request path
DfsReferralData dr = t.getTreeReferral();
if ( dr != null ) {
if ( log.isDebugEnabled() ) {
log.debug(String.format("Need to adjust request path %s (full: %s) -> %s", rpath, rfullpath, dr));
}
String dunc = loc.handleDFSReferral(dr, rpath);
if ( request != null ) {
request.setPath(dunc);
}
return loc;
}
// fallthrough to normal handling
log.debug("No tree referral but in DFS");
}
else {
log.trace("Not in DFS");
return loc;
}
}
if ( request != null ) {
request.setFullUNCPath(session.getTargetDomain(), session.getTargetHost(), rfullpath);
}
// for standalone DFS we could be checking for a referral here, too
DfsReferralData dr = this.ctx.getDfs().resolve(this.ctx, loc.getServer(), loc.getShare(), loc.getUNCPath());
if ( dr != null ) {
if ( log.isDebugEnabled() ) {
log.debug("Resolved " + rfullpath + " -> " + dr);
}
String dunc = loc.handleDFSReferral(dr, rpath);
if ( request != null ) {
request.setPath(dunc);
}
if ( !t.getShare().equals(dr.getShare()) ) {
// this should only happen for standalone roots or if the DC/domain root lookup failed
IOException last;
DfsReferralData start = dr;
do {
if ( log.isDebugEnabled() ) {
log.debug("Need to switch tree for " + dr);
}
try ( SmbTreeHandleImpl nt = connectHost(loc, session.getTargetHost(), dr) ) {
log.debug("Switched tree");
return loc;
}
catch ( IOException e ) {
log.debug("Failed to connect tree", e);
last = e;
}
dr = dr.next();
}
while ( dr != start );
throw new CIFSException("All referral tree connections failed", last);
}
return loc;
}
else if ( t.isInDomainDfs() && ! ( request instanceof NtTransQuerySecurityDesc ) && ! ( request instanceof SmbComClose )
&& ! ( request instanceof SmbComFindClose2 ) ) {
if ( log.isDebugEnabled() ) {
log.debug("No referral available for " + rfullpath);
}
throw new CIFSException("No referral but in domain DFS " + rfullpath);
}
else {
log.trace("Not in DFS");
return loc;
}
}
}
/**
* Use a exclusive connection for this tree
*
* If an exclusive connection is used the caller must make sure that the tree handle is kept alive,
* otherwise the connection will be disconnected once the usage drops to zero.
*
* @param np
* whether to use an exclusive connection
*/
void setNonPooled ( boolean np ) {
this.nonPooled = np;
}
/**
* @return the currently connected tid
*/
@SuppressWarnings ( "resource" )
public long getTreeId () {
SmbTreeImpl t = getTreeInternal();
if ( t == null ) {
return -1;
}
return t.getTreeNum();
}
/**
*
* Only call this method while holding a tree handle
*
* @return session that this file has been loaded through
*/
@SuppressWarnings ( "resource" )
public SmbSessionImpl getSession () {
SmbTreeImpl t = getTreeInternal();
if ( t != null ) {
return t.getSession();
}
return null;
}
/**
*
* Only call this method while holding a tree handle
*
* @param cap
* @return whether the capability is available
* @throws SmbException
*/
public boolean hasCapability ( int cap ) throws SmbException {
try ( SmbSessionImpl s = getSession() ) {
if ( s != null ) {
try ( SmbTransportImpl transport = s.getTransport() ) {
return transport.hasCapability(cap);
}
}
throw new SmbException("Not connected");
}
}
/**
* Only call this method while holding a tree handle
*
* @return the connected tree type
*/
public int getTreeType () {
try ( SmbTreeImpl t = getTree() ) {
return t.getTreeType();
}
}
/**
*
* Only call this method while holding a tree handle
*
* @return the share we are connected to
*/
public String getConnectedShare () {
try ( SmbTreeImpl t = getTree() ) {
return t.getShare();
}
}
/**
*
* Only call this method while holding a tree handle
*
* @param other
* @return whether the connection refers to the same tree
*/
public boolean isSame ( SmbTreeConnection other ) {
try ( SmbTreeImpl t1 = getTree();
SmbTreeImpl t2 = other.getTree() ) {
return t1.equals(t2);
}
}
}
| src/main/java/jcifs/smb/SmbTreeConnection.java | /*
* © 2017 AgNO3 Gmbh & Co. KG
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package jcifs.smb;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jcifs.CIFSContext;
import jcifs.CIFSException;
import jcifs.Configuration;
import jcifs.DfsReferralData;
import jcifs.RuntimeCIFSException;
import jcifs.SmbConstants;
import jcifs.SmbResourceLocator;
import jcifs.SmbTreeHandle;
import jcifs.internal.CommonServerMessageBlockRequest;
import jcifs.internal.CommonServerMessageBlockResponse;
import jcifs.internal.RequestWithPath;
import jcifs.internal.dfs.DfsReferralDataInternal;
import jcifs.internal.smb1.com.SmbComClose;
import jcifs.internal.smb1.com.SmbComFindClose2;
import jcifs.internal.smb1.trans.nt.NtTransQuerySecurityDesc;
import jcifs.util.transport.TransportException;
/**
* This class encapsulates the logic for switching tree connections
*
* Switching trees can occur either when the tree has been disconnected by failure or idle-timeout - as well as on
* DFS referrals.
*
* @author mbechler
*
*/
class SmbTreeConnection {
private static final Logger log = LoggerFactory.getLogger(SmbTreeConnection.class);
private final CIFSContext ctx;
private final SmbTreeConnection delegate;
private SmbTreeImpl tree;
private volatile boolean treeAcquired;
private volatile boolean delegateAcquired;
private SmbTransportInternal exclusiveTransport;
private boolean nonPooled;
private final AtomicLong usageCount = new AtomicLong();
private static final Random RAND = new Random();
/**
* @param ctx
*
*/
public SmbTreeConnection ( CIFSContext ctx ) {
this.ctx = ctx;
this.delegate = null;
}
/**
* @param treeConnection
*/
public SmbTreeConnection ( SmbTreeConnection treeConnection ) {
this.ctx = treeConnection.ctx;
this.delegate = treeConnection;
}
/**
* @return the active configuration
*/
public Configuration getConfig () {
return this.ctx.getConfig();
}
private synchronized SmbTreeImpl getTree () {
SmbTreeImpl t = this.tree;
if ( t != null ) {
return t.acquire(false);
}
else if ( this.delegate != null ) {
this.tree = this.delegate.getTree();
return this.tree;
}
return t;
}
/**
* @return
*/
private synchronized SmbTreeImpl getTreeInternal () {
SmbTreeImpl t = this.tree;
if ( t != null ) {
return t;
}
if ( this.delegate != null ) {
return this.delegate.getTreeInternal();
}
return null;
}
/**
* @param t
*/
private synchronized void switchTree ( SmbTreeImpl t ) {
try ( SmbTreeImpl old = getTree() ) {
if ( old == t ) {
return;
}
boolean wasAcquired = this.treeAcquired;
log.debug("Switching tree");
if ( t != null ) {
log.debug("Acquired tree on switch " + t);
t.acquire();
this.treeAcquired = true;
}
else {
this.treeAcquired = false;
}
this.tree = t;
if ( old != null ) {
if ( wasAcquired ) {
// release
old.release(true);
}
}
if ( this.delegate != null && this.delegateAcquired ) {
log.debug("Releasing delegate");
this.delegateAcquired = false;
this.delegate.release();
}
}
}
/**
* @return tree connection with increased usage count
*/
public SmbTreeConnection acquire () {
long usage = this.usageCount.incrementAndGet();
if ( log.isTraceEnabled() ) {
log.trace("Acquire tree connection " + usage + " " + this);
}
if ( usage == 1 ) {
synchronized ( this ) {
try ( SmbTreeImpl t = getTree() ) {
if ( t != null ) {
if ( !this.treeAcquired ) {
if ( log.isDebugEnabled() ) {
log.debug("Acquire tree on first usage " + t);
}
t.acquire();
this.treeAcquired = true;
}
}
}
if ( this.delegate != null && !this.delegateAcquired ) {
log.debug("Acquire delegate on first usage");
this.delegate.acquire();
this.delegateAcquired = true;
}
}
}
return this;
}
/**
*
*/
public void release () {
long usage = this.usageCount.decrementAndGet();
if ( log.isTraceEnabled() ) {
log.trace("Release tree connection " + usage + " " + this);
}
if ( usage == 0 ) {
synchronized ( this ) {
try ( SmbTreeImpl t = getTree() ) {
if ( this.treeAcquired && t != null ) {
if ( log.isDebugEnabled() ) {
log.debug("Tree connection no longer in use, release tree " + t);
}
this.treeAcquired = false;
t.release();
}
}
if ( this.delegate != null && this.delegateAcquired ) {
this.delegateAcquired = false;
this.delegate.release();
}
}
SmbTransportInternal et = this.exclusiveTransport;
if ( et != null ) {
synchronized ( this ) {
try {
log.debug("Disconnecting exclusive transport");
this.exclusiveTransport = null;
this.tree = null;
this.treeAcquired = false;
et.close();
et.disconnect(false, false);
}
catch ( Exception e ) {
log.error("Failed to close exclusive transport", e);
}
}
}
}
else if ( usage < 0 ) {
log.error("Usage count dropped below zero " + this);
throw new RuntimeCIFSException("Usage count dropped below zero");
}
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize () throws Throwable {
if ( isConnected() && this.usageCount.get() != 0 ) {
log.warn("Tree connection was not properly released " + this);
}
}
synchronized void disconnect ( boolean inError ) {
try ( SmbSessionImpl session = getSession() ) {
if ( session == null ) {
return;
}
try ( SmbTransportImpl transport = session.getTransport() ) {
synchronized ( transport ) {
SmbTreeImpl t = getTreeInternal();
if ( t != null ) {
try {
t.treeDisconnect(inError, true);
}
finally {
this.tree = null;
this.treeAcquired = false;
}
}
else {
this.delegate.disconnect(inError);
}
}
}
}
}
<T extends CommonServerMessageBlockResponse> T send ( SmbResourceLocatorImpl loc, CommonServerMessageBlockRequest request, T response,
RequestParam... params ) throws CIFSException {
return send(loc, request, response, params.length == 0 ? EnumSet.noneOf(RequestParam.class) : EnumSet.copyOf(Arrays.asList(params)));
}
<T extends CommonServerMessageBlockResponse> T send ( SmbResourceLocatorImpl loc, CommonServerMessageBlockRequest request, T response,
Set<RequestParam> params ) throws CIFSException {
CIFSException last = null;
RequestWithPath rpath = ( request instanceof RequestWithPath ) ? (RequestWithPath) request : null;
String savedPath = rpath != null ? rpath.getPath() : null;
String savedFullPath = rpath != null ? rpath.getFullUNCPath() : null;
String fullPath = "\\" + loc.getServer() + "\\" + loc.getShare() + loc.getUNCPath();
int maxRetries = this.ctx.getConfig().getMaxRequestRetries();
for ( int retries = 1; retries <= maxRetries; retries++ ) {
if ( rpath != null ) {
rpath.setFullUNCPath(null, null, fullPath);
}
try {
return send0(loc, request, response, params);
}
catch ( SmbException smbe ) {
// Retrying only makes sense if the invalid parameter is an tree id. If we have a stale file descriptor
// retrying make no sense, as it will never become available again.
if ( params.contains(RequestParam.NO_RETRY)
|| ( ! ( smbe.getCause() instanceof TransportException ) ) && smbe.getNtStatus() != NtStatus.NT_STATUS_INVALID_PARAMETER ) {
log.debug("Not retrying", smbe);
throw smbe;
}
log.debug("send", smbe);
last = smbe;
}
catch ( CIFSException e ) {
log.debug("send", e);
last = e;
}
// If we get here, we got the 'The Parameter is incorrect' error or a transport exception
// Disconnect and try again from scratch.
if ( log.isDebugEnabled() ) {
log.debug(String.format("Retrying (%d/%d) request %s", retries, maxRetries, request));
}
// should we disconnect the transport here? otherwise we make an additional attempt to detect that if the
// server closed the connection as a result
log.debug("Disconnecting tree on send retry", last);
disconnect(true);
if ( retries >= maxRetries ) {
break;
}
try {
if ( retries != 1 ) {
// backoff, but don't delay the first attempt as there are various reasons that can be fixed
// immediately
Thread.sleep(500 + RAND.nextInt(1000));
}
}
catch ( InterruptedException e ) {
log.debug("interrupted sleep in send", e);
}
if ( request != null ) {
request.reset();
}
if ( rpath != null ) {
// resolveDfs() and tree.send() modify the request packet.
// I want to restore it before retrying. request.reset()
// restores almost everything that was modified, except the path.
rpath.setPath(savedPath);
rpath.setFullUNCPath(rpath.getDomain(), rpath.getServer(), savedFullPath);
}
if ( response != null ) {
response.reset();
}
try ( SmbTreeHandle th = connectWrapException(loc) ) {
log.debug("Have new tree connection for retry");
}
catch ( SmbException e ) {
log.debug("Failed to connect tree on retry", e);
last = e;
}
}
if ( last != null ) {
log.debug("All attempts have failed, last exception", last);
throw last;
}
throw new SmbException("All attempts failed, but no exception");
}
private <T extends CommonServerMessageBlockResponse> T send0 ( SmbResourceLocatorImpl loc, CommonServerMessageBlockRequest request, T response,
Set<RequestParam> params ) throws CIFSException, DfsReferral {
for ( int limit = 10; limit > 0; limit-- ) {
if ( request instanceof RequestWithPath ) {
ensureDFSResolved(loc, (RequestWithPath) request);
}
try ( SmbTreeImpl t = getTree() ) {
if ( t == null ) {
throw new CIFSException("Failed to get tree connection");
} ;
return t.send(request, response, params);
}
catch ( DfsReferral dre ) {
if ( dre.getData().unwrap(DfsReferralDataInternal.class).isResolveHashes() ) {
throw dre;
}
request.reset();
log.trace("send0", dre);
}
}
throw new CIFSException("Loop in DFS referrals");
}
/**
* @param loc
* @return tree handle
* @throws SmbException
*/
public SmbTreeHandleImpl connectWrapException ( SmbResourceLocatorImpl loc ) throws SmbException {
try {
return connect(loc);
}
catch ( UnknownHostException uhe ) {
throw new SmbException("Failed to connect to server", uhe);
}
catch ( SmbException se ) {
throw se;
}
catch ( IOException ioe ) {
throw new SmbException("Failed to connect to server", ioe);
}
}
/**
* @param loc
* @return tree handle
* @throws IOException
*/
public synchronized SmbTreeHandleImpl connect ( SmbResourceLocatorImpl loc ) throws IOException {
try ( SmbSessionImpl session = getSession() ) {
if ( isConnected() ) {
try ( SmbTransportImpl transport = session.getTransport() ) {
if ( transport.isDisconnected() || transport.getRemoteHostName() == null ) {
/*
* Tree/session thinks it is connected but transport disconnected
* under it, reset tree to reflect the truth.
*/
log.debug("Disconnecting failed tree and session");
disconnect(true);
}
}
}
if ( isConnected() ) {
log.trace("Already connected");
return new SmbTreeHandleImpl(loc, this);
}
return connectHost(loc, loc.getServerWithDfs());
}
}
/**
* @return whether we have a valid tree connection
*/
@SuppressWarnings ( "resource" )
public synchronized boolean isConnected () {
SmbTreeImpl t = getTreeInternal();
return t != null && t.isConnected();
}
/**
*
* @param loc
* @param host
* @return tree handle
* @throws IOException
*/
public synchronized SmbTreeHandleImpl connectHost ( SmbResourceLocatorImpl loc, String host ) throws IOException {
return connectHost(loc, host, null);
}
/**
*
* @param loc
* @param host
* @param referral
* @return tree handle
* @throws IOException
*/
public synchronized SmbTreeHandleImpl connectHost ( SmbResourceLocatorImpl loc, String host, DfsReferralData referral ) throws IOException {
String targetDomain = null;
try ( SmbTreeImpl t = getTree() ) {
if ( t != null ) {
if ( log.isDebugEnabled() ) {
log.debug("Tree is " + t);
}
if ( loc.getShare().equals(t.getShare()) ) {
try ( SmbSessionImpl session = t.getSession() ) {
targetDomain = session.getTargetDomain();
if ( !session.isFailed() ) {
try ( SmbTransportImpl trans = session.getTransport();
SmbTreeImpl ct = connectTree(loc, host, t.getShare(), trans, t, null) ) {
switchTree(ct);
return new SmbTreeHandleImpl(loc, this);
}
}
log.debug("Session no longer valid");
}
}
}
}
String hostName = loc.getServerWithDfs();
String path = ( loc.getType() == SmbConstants.TYPE_SHARE || loc.getUNCPath() == null || "\\".equals(loc.getUNCPath()) ) ? null
: loc.getUNCPath();
String share = loc.getShare();
DfsReferralData start = referral != null ? referral : this.ctx.getDfs().resolve(this.ctx, hostName, loc.getShare(), path);
DfsReferralData dr = start;
IOException last = null;
do {
if ( dr != null ) {
targetDomain = dr.getDomain();
host = dr.getServer().toLowerCase(Locale.ROOT);
share = dr.getShare();
}
try {
if ( this.nonPooled ) {
if ( log.isDebugEnabled() ) {
log.debug("Using exclusive transport for " + this);
}
this.exclusiveTransport = this.ctx.getTransportPool()
.getSmbTransport(this.ctx, host, loc.getPort(), true, loc.shouldForceSigning()).unwrap(SmbTransportInternal.class);
SmbTransportInternal trans = this.exclusiveTransport;
try ( SmbSessionInternal smbSession = trans.getSmbSession(this.ctx, host, targetDomain).unwrap(SmbSessionInternal.class);
SmbTreeImpl uct = smbSession.getSmbTree(share, null).unwrap(SmbTreeImpl.class);
SmbTreeImpl ct = connectTree(loc, host, share, trans, uct, dr) ) {
if ( dr != null ) {
ct.setTreeReferral(dr);
if ( dr != start ) {
dr.unwrap(DfsReferralDataInternal.class).replaceCache();
}
}
switchTree(ct);
return new SmbTreeHandleImpl(loc, this);
}
}
try ( SmbTransportInternal trans = this.ctx.getTransportPool()
.getSmbTransport(this.ctx, host, loc.getPort(), false, loc.shouldForceSigning()).unwrap(SmbTransportInternal.class);
SmbSessionInternal smbSession = trans.getSmbSession(this.ctx, host, targetDomain).unwrap(SmbSessionInternal.class);
SmbTreeImpl uct = smbSession.getSmbTree(share, null).unwrap(SmbTreeImpl.class);
SmbTreeImpl ct = connectTree(loc, host, share, trans, uct, dr) ) {
if ( dr != null ) {
ct.setTreeReferral(dr);
if ( dr != start ) {
dr.unwrap(DfsReferralDataInternal.class).replaceCache();
}
}
switchTree(ct);
return new SmbTreeHandleImpl(loc, this);
}
}
catch ( IOException e ) {
last = e;
log.warn("Referral failed, trying next", e);
}
if ( dr != null ) {
dr = dr.next();
}
}
while ( dr != start );
throw last;
}
/**
* @param loc
* @param addr
* @param trans
* @param t
* @throws CIFSException
*/
private SmbTreeImpl connectTree ( SmbResourceLocatorImpl loc, String addr, String share, SmbTransportInternal trans, SmbTreeImpl t,
DfsReferralData referral ) throws CIFSException {
if ( log.isDebugEnabled() && trans.isSigningOptional() && !loc.isIPC() && !this.ctx.getConfig().isSigningEnforced() ) {
log.debug("Signatures for file enabled but not required " + this);
}
if ( referral != null ) {
t.markDomainDfs();
}
try {
if ( log.isTraceEnabled() ) {
log.trace("doConnect: " + addr);
}
t.treeConnect(null, null);
return t.acquire();
}
catch ( SmbAuthException sae ) {
log.debug("Authentication failed", sae);
if ( t.getSession().getCredentials().isAnonymous() ) { // anonymous session, refresh
try ( SmbSessionInternal s = trans.getSmbSession(this.ctx.withAnonymousCredentials()).unwrap(SmbSessionInternal.class);
SmbTreeImpl tr = s.getSmbTree(null, null).unwrap(SmbTreeImpl.class) ) {
tr.treeConnect(null, null);
return tr.acquire();
}
}
else if ( this.ctx.renewCredentials(loc.getURL().toString(), sae) ) {
log.debug("Trying to renew credentials after auth error");
try ( SmbSessionInternal s = trans.getSmbSession(this.ctx, t.getSession().getTargetHost(), t.getSession().getTargetDomain())
.unwrap(SmbSessionInternal.class);
SmbTreeImpl tr = s.getSmbTree(share, null).unwrap(SmbTreeImpl.class) ) {
if ( referral != null ) {
tr.markDomainDfs();
}
tr.treeConnect(null, null);
return tr.acquire();
}
}
else {
throw sae;
}
}
}
SmbResourceLocator ensureDFSResolved ( SmbResourceLocatorImpl loc ) throws CIFSException {
return ensureDFSResolved(loc, null);
}
SmbResourceLocator ensureDFSResolved ( SmbResourceLocatorImpl loc, RequestWithPath request ) throws CIFSException {
if ( request instanceof SmbComClose )
return loc;
for ( int retries = 0; retries < 1 + this.ctx.getConfig().getMaxRequestRetries(); retries++ ) {
try {
return resolveDfs0(loc, request);
}
catch ( SmbException smbe ) {
// The connection may have been dropped?
if ( smbe.getNtStatus() != NtStatus.NT_STATUS_NOT_FOUND && ! ( smbe.getCause() instanceof TransportException ) ) {
throw smbe;
}
log.debug("resolveDfs", smbe);
}
// If we get here, we apparently have a bad connection.
// Disconnect and try again.
if ( log.isDebugEnabled() ) {
log.debug("Retrying (" + retries + ") resolveDfs: " + request);
}
log.debug("Disconnecting tree on DFS retry");
disconnect(true);
try {
Thread.sleep(500 + RAND.nextInt(5000));
}
catch ( InterruptedException e ) {
log.debug("resolveDfs", e);
}
try ( SmbTreeHandle th = connectWrapException(loc) ) {}
}
return loc;
}
private SmbResourceLocator resolveDfs0 ( SmbResourceLocatorImpl loc, RequestWithPath request ) throws CIFSException {
try ( SmbTreeHandleImpl th = connectWrapException(loc);
SmbSessionImpl session = th.getSession();
SmbTransportImpl transport = session.getTransport();
SmbTreeImpl t = getTree() ) {
transport.ensureConnected();
String rpath = request != null ? request.getPath() : loc.getUNCPath();
String rfullpath = request != null ? request.getFullUNCPath() : ( '\\' + loc.getServer() + '\\' + loc.getShare() + loc.getUNCPath() );
if ( t.isInDomainDfs() || !t.isPossiblyDfs() ) {
if ( t.isInDomainDfs() ) {
// need to adjust request path
DfsReferralData dr = t.getTreeReferral();
if ( dr != null ) {
if ( log.isDebugEnabled() ) {
log.debug(String.format("Need to adjust request path %s (full: %s) -> %s", rpath, rfullpath, dr));
}
String dunc = loc.handleDFSReferral(dr, rpath);
if ( request != null ) {
request.setPath(dunc);
}
return loc;
}
// fallthrough to normal handling
log.debug("No tree referral but in DFS");
}
else {
log.trace("Not in DFS");
return loc;
}
}
if ( request != null ) {
request.setFullUNCPath(session.getTargetDomain(), session.getTargetHost(), rfullpath);
}
// for standalone DFS we could be checking for a referral here, too
DfsReferralData dr = this.ctx.getDfs().resolve(this.ctx, loc.getServer(), loc.getShare(), loc.getUNCPath());
if ( dr != null ) {
if ( log.isDebugEnabled() ) {
log.debug("Resolved " + rfullpath + " -> " + dr);
}
String dunc = loc.handleDFSReferral(dr, rpath);
if ( request != null ) {
request.setPath(dunc);
}
if ( !t.getShare().equals(dr.getShare()) ) {
// this should only happen for standalone roots or if the DC/domain root lookup failed
IOException last;
DfsReferralData start = dr;
do {
if ( log.isDebugEnabled() ) {
log.debug("Need to switch tree for " + dr);
}
try ( SmbTreeHandleImpl nt = connectHost(loc, session.getTargetHost(), dr) ) {
log.debug("Switched tree");
return loc;
}
catch ( IOException e ) {
log.debug("Failed to connect tree", e);
last = e;
}
dr = dr.next();
}
while ( dr != start );
throw new CIFSException("All referral tree connections failed", last);
}
return loc;
}
else if ( t.isInDomainDfs() && ! ( request instanceof NtTransQuerySecurityDesc ) && ! ( request instanceof SmbComClose )
&& ! ( request instanceof SmbComFindClose2 ) ) {
if ( log.isDebugEnabled() ) {
log.debug("No referral available for " + rfullpath);
}
throw new CIFSException("No referral but in domain DFS " + rfullpath);
}
else {
log.trace("Not in DFS");
return loc;
}
}
}
/**
* Use a exclusive connection for this tree
*
* If an exclusive connection is used the caller must make sure that the tree handle is kept alive,
* otherwise the connection will be disconnected once the usage drops to zero.
*
* @param np
* whether to use an exclusive connection
*/
void setNonPooled ( boolean np ) {
this.nonPooled = np;
}
/**
* @return the currently connected tid
*/
@SuppressWarnings ( "resource" )
public long getTreeId () {
SmbTreeImpl t = getTreeInternal();
if ( t == null ) {
return -1;
}
return t.getTreeNum();
}
/**
*
* Only call this method while holding a tree handle
*
* @return session that this file has been loaded through
*/
@SuppressWarnings ( "resource" )
public SmbSessionImpl getSession () {
SmbTreeImpl t = getTreeInternal();
if ( t != null ) {
return t.getSession();
}
return null;
}
/**
*
* Only call this method while holding a tree handle
*
* @param cap
* @return whether the capability is available
* @throws SmbException
*/
public boolean hasCapability ( int cap ) throws SmbException {
try ( SmbSessionImpl s = getSession() ) {
if ( s != null ) {
try ( SmbTransportImpl transport = s.getTransport() ) {
return transport.hasCapability(cap);
}
}
throw new SmbException("Not connected");
}
}
/**
* Only call this method while holding a tree handle
*
* @return the connected tree type
*/
public int getTreeType () {
try ( SmbTreeImpl t = getTree() ) {
return t.getTreeType();
}
}
/**
*
* Only call this method while holding a tree handle
*
* @return the share we are connected to
*/
public String getConnectedShare () {
try ( SmbTreeImpl t = getTree() ) {
return t.getShare();
}
}
/**
*
* Only call this method while holding a tree handle
*
* @param other
* @return whether the connection refers to the same tree
*/
public boolean isSame ( SmbTreeConnection other ) {
try ( SmbTreeImpl t1 = getTree();
SmbTreeImpl t2 = other.getTree() ) {
return t1.equals(t2);
}
}
}
| Silence tree connect failure logging a bit
| src/main/java/jcifs/smb/SmbTreeConnection.java | Silence tree connect failure logging a bit | <ide><path>rc/main/java/jcifs/smb/SmbTreeConnection.java
<ide> }
<ide> catch ( IOException e ) {
<ide> last = e;
<del> log.warn("Referral failed, trying next", e);
<add> log.debug("Referral failed, trying next", e);
<ide> }
<ide>
<ide> if ( dr != null ) { |
|
JavaScript | mit | d136945b4501342a3d7cb112be6e9e3c3a669aed | 0 | wejs/we-core | /**
* We.js database controllers
*
* This file load default database config, and core models
*/
var Sequelize = require('sequelize');
var async = require('async');
var path = require('path');
var env = require('../env.js');
var _ = require('lodash');
var loadDatabaseConfig = require('./loadDatabaseConfig.js');
var db = {};
db.loadDatabaseConfig = loadDatabaseConfig;
db.defaultConnection = null;
db.models = {};
db.modelsConfigs = null;
db.Sequelize = Sequelize;
db.projectFolder = process.cwd();
/**
* Connect in database
*
* @param {object} we
* @return {object} sequelize database connection
*/
db.connect = function connect() {
var dbC = loadDatabaseConfig( db.projectFolder );
var configs = dbC[env];
// set we.js core define config
_.merge(configs, {
define: {
// table configs
timestamps: true,
createdAt: 'createdAt',
updatedAt: 'updatedAt',
deletedAt: 'deletedAt',
paranoid: true,
classMethods: {
/**
* Context loader, preload current request record and related data
*
* @param {Object} req express.js request
* @param {Object} res express.js response
* @param {Function} done callback
*/
contextLoader: function contextLoader(req, res, done) {
if (!res.locals.id || !res.locals.loadCurrentRecord) return done();
this.find(res.locals.id)
.done(function (err, record) {
if (err) return done(err);
res.locals.record = record;
if (record && record.dataValues.creatorId && req.isAuthenticated()) {
// ser role owner
if (req.user.id == record.dataValues.creatorId)
if(req.userRoleNames.indexOf('owner') == -1 ) req.userRoleNames.push('owner');
}
return done();
})
}
},
instanceMethods: {
toJSON: function() {
var obj = this.get();
return obj;
},
fetchAssociatedIds: function(cb) {
var sql = '';
//console.log('fetchAssociatedIds.this', this);
var modelName = this.__options.name.singular;
var associations = db.models[modelName].associations;
for (var associationName in associations ) {
// get bellongs to from values id
if ( associations[associationName].associationType == 'BelongsTo' ) {
this.dataValues[associationName] = this.dataValues[ associations[associationName].identifier ];
} else {
//console.log('fetchAssociatedIds unknow join>>', associations);
}
}
cb();
}
}
}
});
return new Sequelize( configs.database, configs.username, configs.password, configs );
}
/**
* we.js db define | is a alias to current sequelize connection define
*
* @param {String} name model name
* @param {object} configs model configs
* @return {Object} sequelize model
*/
db.define = function defineModel(name, definition, options) {
return db.defaultConnection.define(name, definition, options);
}
/**
* Load we.js core models
*
* @return {Object} models db.models var
*/
db.loadCoreModels = function loadCoreModels() {
// - sys_configuration model
db.models.user_configuration = db.define('user_configuration', {
name: {
type: Sequelize.STRING
},
value: {
type: Sequelize.STRING
}
}, {
// Model tableName will be the same as the model name
freezeTableName: true
});
return db.models;
}
/**
* Sync all db models | create table if now exists
*
* @param {Function} cb callback
*/
db.syncAllModels = function syncAllModels(cd, cb) {
if (cd && !cb) {
cb = cd;
cd = null;
}
// cb is optional
if (!cb) cb = function(){};
if (env == 'test' || (env != 'prod' && cd.resetAllData)) {
db.defaultConnection.sync({force: true}).then(function(){ cb(); }).catch(cb);
} else {
db.defaultConnection.sync().then(function(){ cb(); }).catch(cb);
}
}
db.setModelAllJoins = function setModelAllJoins() {
var attrConfig;
for ( var modelName in db.modelsConfigs) {
for (var attributeName in db.modelsConfigs[modelName].associations) {
attrConfig = db.modelsConfigs[modelName].associations[attributeName];
// skip if are emberOnly
if (attrConfig.emberOnly) continue;
var config = {};
config.as = attributeName;
if (attrConfig.through) {
if (typeof attrConfig.through == 'object') {
config.through = attrConfig.through;
config.through.model = db.models[attrConfig.through.model];
} else {
config.through = attrConfig.through;
}
}
if (attrConfig.otherKey) config.otherKey = attrConfig.otherKey;
if (attrConfig.onDelete) config.onDelete = attrConfig.onDelete;
if (attrConfig.onUpdate) config.onUpdate = attrConfig.onUpdate;
if (attrConfig.constraints === false) config.constraints = false;
if (attrConfig.otherKey) config.otherKey = attrConfig.otherKey;
if (attrConfig.foreignKey) config.foreignKey = attrConfig.foreignKey;
db.models[modelName][attrConfig.type]( db.models[attrConfig.model], config);
}
}
}
// - init
db.defaultConnection = db.connect(env);
db.loadCoreModels();
module.exports = db; | lib/database/index.js | /**
* We.js database controllers
*
* This file load default database config, and core models
*/
var Sequelize = require('sequelize');
var async = require('async');
var path = require('path');
var env = require('../env.js');
var _ = require('lodash');
var loadDatabaseConfig = require('./loadDatabaseConfig.js');
var db = {};
db.defaultConnection = null;
db.models = {};
db.modelsConfigs = null;
db.Sequelize = Sequelize;
db.projectFolder = process.cwd();
/**
* Connect in database
*
* @param {object} we
* @return {object} sequelize database connection
*/
db.connect = function connect() {
var dbC = loadDatabaseConfig( db.projectFolder );
var configs = dbC[env];
// set we.js core define config
_.merge(configs, {
define: {
// table configs
timestamps: true,
createdAt: 'createdAt',
updatedAt: 'updatedAt',
deletedAt: 'deletedAt',
paranoid: true,
classMethods: {
/**
* Context loader, preload current request record and related data
*
* @param {Object} req express.js request
* @param {Object} res express.js response
* @param {Function} done callback
*/
contextLoader: function contextLoader(req, res, done) {
if (!res.locals.id || !res.locals.loadCurrentRecord) return done();
this.find(res.locals.id)
.done(function (err, record) {
if (err) return done(err);
res.locals.record = record;
if (record && record.dataValues.creatorId && req.isAuthenticated()) {
// ser role owner
if (req.user.id == record.dataValues.creatorId)
if(req.userRoleNames.indexOf('owner') == -1 ) req.userRoleNames.push('owner');
}
return done();
})
}
},
instanceMethods: {
toJSON: function() {
var obj = this.get();
return obj;
},
fetchAssociatedIds: function(cb) {
var sql = '';
//console.log('fetchAssociatedIds.this', this);
var modelName = this.__options.name.singular;
var associations = db.models[modelName].associations;
for (var associationName in associations ) {
// get bellongs to from values id
if ( associations[associationName].associationType == 'BelongsTo' ) {
this.dataValues[associationName] = this.dataValues[ associations[associationName].identifier ];
} else {
//console.log('fetchAssociatedIds unknow join>>', associations);
}
}
cb();
}
}
}
});
return new Sequelize( configs.database, configs.username, configs.password, configs );
}
/**
* we.js db define | is a alias to current sequelize connection define
*
* @param {String} name model name
* @param {object} configs model configs
* @return {Object} sequelize model
*/
db.define = function defineModel(name, definition, options) {
return db.defaultConnection.define(name, definition, options);
}
/**
* Load we.js core models
*
* @return {Object} models db.models var
*/
db.loadCoreModels = function loadCoreModels() {
// - sys_configuration model
db.models.user_configuration = db.define('user_configuration', {
name: {
type: Sequelize.STRING
},
value: {
type: Sequelize.STRING
}
}, {
// Model tableName will be the same as the model name
freezeTableName: true
});
return db.models;
}
/**
* Sync all db models | create table if now exists
*
* @param {Function} cb callback
*/
db.syncAllModels = function syncAllModels(cd, cb) {
if (cd && !cb) {
cb = cd;
cd = null;
}
// cb is optional
if (!cb) cb = function(){};
if (env == 'test' || (env != 'prod' && cd.resetAllData)) {
db.defaultConnection.sync({force: true}).then(function(){ cb(); }).catch(cb);
} else {
db.defaultConnection.sync().then(function(){ cb(); }).catch(cb);
}
}
db.setModelAllJoins = function setModelAllJoins() {
var attrConfig;
for ( var modelName in db.modelsConfigs) {
for (var attributeName in db.modelsConfigs[modelName].associations) {
attrConfig = db.modelsConfigs[modelName].associations[attributeName];
// skip if are emberOnly
if (attrConfig.emberOnly) continue;
var config = {};
config.as = attributeName;
if (attrConfig.through) {
if (typeof attrConfig.through == 'object') {
config.through = attrConfig.through;
config.through.model = db.models[attrConfig.through.model];
} else {
config.through = attrConfig.through;
}
}
if (attrConfig.otherKey) config.otherKey = attrConfig.otherKey;
if (attrConfig.onDelete) config.onDelete = attrConfig.onDelete;
if (attrConfig.onUpdate) config.onUpdate = attrConfig.onUpdate;
if (attrConfig.constraints === false) config.constraints = false;
if (attrConfig.otherKey) config.otherKey = attrConfig.otherKey;
if (attrConfig.foreignKey) config.foreignKey = attrConfig.foreignKey;
db.models[modelName][attrConfig.type]( db.models[attrConfig.model], config);
}
}
}
// - init
db.defaultConnection = db.connect(env);
db.loadCoreModels();
module.exports = db; | set db.loadDatabaseConfig
| lib/database/index.js | set db.loadDatabaseConfig | <ide><path>ib/database/index.js
<ide> var loadDatabaseConfig = require('./loadDatabaseConfig.js');
<ide>
<ide> var db = {};
<add>
<add>db.loadDatabaseConfig = loadDatabaseConfig;
<ide>
<ide> db.defaultConnection = null;
<ide> |
|
Java | apache-2.0 | e4a2a90f57e545c0ece57825bf3ab3c1dd6b3090 | 0 | theseyi/WhereHows,mars-lan/WhereHows,alyiwang/WhereHows,alyiwang/WhereHows,linkedin/WhereHows,mars-lan/WhereHows,linkedin/WhereHows,mars-lan/WhereHows,camelliazhang/WhereHows,theseyi/WhereHows,camelliazhang/WhereHows,alyiwang/WhereHows,camelliazhang/WhereHows,theseyi/WhereHows,mars-lan/WhereHows,linkedin/WhereHows,mars-lan/WhereHows,alyiwang/WhereHows,theseyi/WhereHows,alyiwang/WhereHows,theseyi/WhereHows,camelliazhang/WhereHows,alyiwang/WhereHows,camelliazhang/WhereHows,theseyi/WhereHows,mars-lan/WhereHows,linkedin/WhereHows,linkedin/WhereHows,camelliazhang/WhereHows,linkedin/WhereHows | /**
* Copyright 2015 LinkedIn Corp. 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.
*/
package wherehows.dao.table;
import javax.annotation.Nonnull;
import wherehows.models.view.DatasetExportPolicy;
public class ExportPolicyDao {
/**
* Get datset health by dataset urn
*/
@Nonnull
public DatasetExportPolicy getDatasetExportPolicy(@Nonnull String datasetUrn) throws Exception {
throw new UnsupportedOperationException("Not implemented yet");
}
public void updateDatasetExportPolicy(@Nonnull String datasetUrn, @Nonnull DatasetExportPolicy record, @Nonnull String user) throws Exception {
throw new UnsupportedOperationException("Not implemented yet");
}
} | wherehows-dao/src/main/java/wherehows/dao/table/ExportPolicyDao.java | /**
* Copyright 2015 LinkedIn Corp. 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.
*/
package wherehows.dao.table;
import javax.annotation.Nonnull;
import wherehows.models.view.DatasetExportPolicy;
public class ExportPolicyDao {
/**
* Get datset health by dataset urn
*/
@Nonnull
public DatasetExportPolicy getDatasetExportPolicy(@Nonnull String datasetUrn) throws Exception {
throw new UnsupportedOperationException("Not implemented yet");
}
public void updateDatasetExportPolicy(@Nonnull datasetUrn, @Nonnull DatasetExportPolicy record, @Nonnull String user) throws Exception {
throw new UnsupportedOperationException("Not implemented yet");
}
} | Fix typo
| wherehows-dao/src/main/java/wherehows/dao/table/ExportPolicyDao.java | Fix typo | <ide><path>herehows-dao/src/main/java/wherehows/dao/table/ExportPolicyDao.java
<ide> throw new UnsupportedOperationException("Not implemented yet");
<ide> }
<ide>
<del> public void updateDatasetExportPolicy(@Nonnull datasetUrn, @Nonnull DatasetExportPolicy record, @Nonnull String user) throws Exception {
<add> public void updateDatasetExportPolicy(@Nonnull String datasetUrn, @Nonnull DatasetExportPolicy record, @Nonnull String user) throws Exception {
<ide> throw new UnsupportedOperationException("Not implemented yet");
<ide>
<ide> } |
|
Java | apache-2.0 | 50ede23a1079271cd21c338968bf936623416a16 | 0 | f7753/ignite,ptupitsyn/ignite,WilliamDo/ignite,apache/ignite,leveyj/ignite,VladimirErshov/ignite,alexzaitzev/ignite,ptupitsyn/ignite,StalkXT/ignite,vladisav/ignite,rfqu/ignite,a1vanov/ignite,voipp/ignite,agura/incubator-ignite,StalkXT/ignite,vladisav/ignite,murador/ignite,VladimirErshov/ignite,pperalta/ignite,vladisav/ignite,agura/incubator-ignite,apacheignite/ignite,irudyak/ignite,NSAmelchev/ignite,DoudTechData/ignite,leveyj/ignite,ntikhonov/ignite,tkpanther/ignite,daradurvs/ignite,sk0x50/ignite,vadopolski/ignite,alexzaitzev/ignite,StalkXT/ignite,daradurvs/ignite,nizhikov/ignite,chandresh-pancholi/ignite,BiryukovVA/ignite,voipp/ignite,voipp/ignite,psadusumilli/ignite,andrey-kuznetsov/ignite,ascherbakoff/ignite,ptupitsyn/ignite,apache/ignite,daradurvs/ignite,samaitra/ignite,NSAmelchev/ignite,vladisav/ignite,shroman/ignite,xtern/ignite,murador/ignite,a1vanov/ignite,rfqu/ignite,shroman/ignite,nivanov/ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,tkpanther/ignite,ascherbakoff/ignite,vldpyatkov/ignite,apache/ignite,murador/ignite,xtern/ignite,shroman/ignite,leveyj/ignite,apacheignite/ignite,ptupitsyn/ignite,kromulan/ignite,StalkXT/ignite,afinka77/ignite,voipp/ignite,vldpyatkov/ignite,StalkXT/ignite,DoudTechData/ignite,nivanov/ignite,mcherkasov/ignite,f7753/ignite,sk0x50/ignite,andrey-kuznetsov/ignite,NSAmelchev/ignite,VladimirErshov/ignite,StalkXT/ignite,vladisav/ignite,BiryukovVA/ignite,wmz7year/ignite,ryanzz/ignite,wmz7year/ignite,nizhikov/ignite,psadusumilli/ignite,shroman/ignite,kromulan/ignite,ilantukh/ignite,alexzaitzev/ignite,rfqu/ignite,rfqu/ignite,SomeFire/ignite,StalkXT/ignite,ilantukh/ignite,amirakhmedov/ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,VladimirErshov/ignite,ntikhonov/ignite,afinka77/ignite,NSAmelchev/ignite,samaitra/ignite,dream-x/ignite,vadopolski/ignite,chandresh-pancholi/ignite,psadusumilli/ignite,ascherbakoff/ignite,f7753/ignite,ryanzz/ignite,chandresh-pancholi/ignite,alexzaitzev/ignite,vadopolski/ignite,ascherbakoff/ignite,StalkXT/ignite,SharplEr/ignite,psadusumilli/ignite,ilantukh/ignite,apache/ignite,tkpanther/ignite,sk0x50/ignite,ntikhonov/ignite,psadusumilli/ignite,endian675/ignite,andrey-kuznetsov/ignite,pperalta/ignite,BiryukovVA/ignite,vladisav/ignite,mcherkasov/ignite,samaitra/ignite,a1vanov/ignite,vadopolski/ignite,andrey-kuznetsov/ignite,tkpanther/ignite,samaitra/ignite,afinka77/ignite,f7753/ignite,sk0x50/ignite,SharplEr/ignite,nizhikov/ignite,ntikhonov/ignite,tkpanther/ignite,andrey-kuznetsov/ignite,f7753/ignite,voipp/ignite,daradurvs/ignite,murador/ignite,ryanzz/ignite,irudyak/ignite,daradurvs/ignite,chandresh-pancholi/ignite,ryanzz/ignite,rfqu/ignite,samaitra/ignite,ascherbakoff/ignite,ptupitsyn/ignite,vadopolski/ignite,BiryukovVA/ignite,endian675/ignite,vsisko/incubator-ignite,tkpanther/ignite,wmz7year/ignite,kromulan/ignite,dmagda/incubator-ignite,kromulan/ignite,daradurvs/ignite,agura/incubator-ignite,vsisko/incubator-ignite,SomeFire/ignite,irudyak/ignite,voipp/ignite,mcherkasov/ignite,vldpyatkov/ignite,NSAmelchev/ignite,WilliamDo/ignite,ptupitsyn/ignite,psadusumilli/ignite,dream-x/ignite,afinka77/ignite,andrey-kuznetsov/ignite,sk0x50/ignite,ilantukh/ignite,DoudTechData/ignite,xtern/ignite,BiryukovVA/ignite,ryanzz/ignite,ntikhonov/ignite,shroman/ignite,pperalta/ignite,leveyj/ignite,endian675/ignite,xtern/ignite,a1vanov/ignite,DoudTechData/ignite,vsisko/incubator-ignite,BiryukovVA/ignite,ptupitsyn/ignite,nivanov/ignite,NSAmelchev/ignite,apacheignite/ignite,leveyj/ignite,WilliamDo/ignite,irudyak/ignite,SomeFire/ignite,daradurvs/ignite,voipp/ignite,agura/incubator-ignite,wmz7year/ignite,ilantukh/ignite,nizhikov/ignite,endian675/ignite,irudyak/ignite,SharplEr/ignite,a1vanov/ignite,dmagda/incubator-ignite,pperalta/ignite,nivanov/ignite,dmagda/incubator-ignite,nizhikov/ignite,vsisko/incubator-ignite,ptupitsyn/ignite,VladimirErshov/ignite,amirakhmedov/ignite,xtern/ignite,f7753/ignite,ptupitsyn/ignite,psadusumilli/ignite,vadopolski/ignite,chandresh-pancholi/ignite,dmagda/incubator-ignite,apache/ignite,ryanzz/ignite,vldpyatkov/ignite,dream-x/ignite,dream-x/ignite,amirakhmedov/ignite,SharplEr/ignite,samaitra/ignite,tkpanther/ignite,daradurvs/ignite,dream-x/ignite,NSAmelchev/ignite,ryanzz/ignite,VladimirErshov/ignite,mcherkasov/ignite,f7753/ignite,andrey-kuznetsov/ignite,SharplEr/ignite,BiryukovVA/ignite,endian675/ignite,samaitra/ignite,ascherbakoff/ignite,apacheignite/ignite,nizhikov/ignite,dream-x/ignite,ascherbakoff/ignite,wmz7year/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,andrey-kuznetsov/ignite,ryanzz/ignite,endian675/ignite,xtern/ignite,shroman/ignite,nizhikov/ignite,vsisko/incubator-ignite,vldpyatkov/ignite,endian675/ignite,mcherkasov/ignite,alexzaitzev/ignite,WilliamDo/ignite,irudyak/ignite,samaitra/ignite,apache/ignite,rfqu/ignite,nizhikov/ignite,SomeFire/ignite,DoudTechData/ignite,dream-x/ignite,mcherkasov/ignite,ilantukh/ignite,tkpanther/ignite,wmz7year/ignite,pperalta/ignite,a1vanov/ignite,SomeFire/ignite,afinka77/ignite,ntikhonov/ignite,endian675/ignite,dmagda/incubator-ignite,ntikhonov/ignite,apacheignite/ignite,alexzaitzev/ignite,agura/incubator-ignite,shroman/ignite,dmagda/incubator-ignite,vladisav/ignite,daradurvs/ignite,sk0x50/ignite,vadopolski/ignite,amirakhmedov/ignite,nivanov/ignite,voipp/ignite,StalkXT/ignite,samaitra/ignite,agura/incubator-ignite,irudyak/ignite,sk0x50/ignite,daradurvs/ignite,apache/ignite,pperalta/ignite,murador/ignite,alexzaitzev/ignite,amirakhmedov/ignite,SharplEr/ignite,ilantukh/ignite,nivanov/ignite,andrey-kuznetsov/ignite,SharplEr/ignite,rfqu/ignite,pperalta/ignite,kromulan/ignite,shroman/ignite,irudyak/ignite,leveyj/ignite,SomeFire/ignite,kromulan/ignite,vladisav/ignite,murador/ignite,sk0x50/ignite,shroman/ignite,VladimirErshov/ignite,samaitra/ignite,chandresh-pancholi/ignite,vldpyatkov/ignite,xtern/ignite,andrey-kuznetsov/ignite,apache/ignite,BiryukovVA/ignite,murador/ignite,SharplEr/ignite,nivanov/ignite,pperalta/ignite,SomeFire/ignite,BiryukovVA/ignite,dmagda/incubator-ignite,agura/incubator-ignite,afinka77/ignite,leveyj/ignite,SomeFire/ignite,NSAmelchev/ignite,rfqu/ignite,nivanov/ignite,mcherkasov/ignite,murador/ignite,wmz7year/ignite,amirakhmedov/ignite,voipp/ignite,dream-x/ignite,mcherkasov/ignite,kromulan/ignite,DoudTechData/ignite,afinka77/ignite,WilliamDo/ignite,f7753/ignite,vldpyatkov/ignite,kromulan/ignite,vldpyatkov/ignite,ilantukh/ignite,WilliamDo/ignite,apacheignite/ignite,shroman/ignite,ntikhonov/ignite,a1vanov/ignite,vsisko/incubator-ignite,VladimirErshov/ignite,NSAmelchev/ignite,agura/incubator-ignite,alexzaitzev/ignite,amirakhmedov/ignite,vadopolski/ignite,vsisko/incubator-ignite,SomeFire/ignite,ilantukh/ignite,irudyak/ignite,xtern/ignite,DoudTechData/ignite,BiryukovVA/ignite,amirakhmedov/ignite,alexzaitzev/ignite,amirakhmedov/ignite,ilantukh/ignite,a1vanov/ignite,DoudTechData/ignite,leveyj/ignite,WilliamDo/ignite,apacheignite/ignite,SomeFire/ignite,wmz7year/ignite,WilliamDo/ignite,SharplEr/ignite,nizhikov/ignite,dmagda/incubator-ignite,psadusumilli/ignite,vsisko/incubator-ignite,afinka77/ignite,apacheignite/ignite,apache/ignite,sk0x50/ignite,xtern/ignite | /*
* 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.ignite.internal.processors.cache.store;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.cache.Cache;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.cache.store.CacheStore;
import org.apache.ignite.cache.store.CacheStoreSession;
import org.apache.ignite.cache.store.CacheStoreSessionListener;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.processors.cache.CacheEntryImpl;
import org.apache.ignite.internal.processors.cache.CacheStoreBalancingWrapper;
import org.apache.ignite.internal.processors.cache.CacheStorePartialUpdateException;
import org.apache.ignite.internal.processors.cache.GridCacheInternal;
import org.apache.ignite.internal.processors.cache.GridCacheManagerAdapter;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.util.GridLeanMap;
import org.apache.ignite.internal.util.GridSetWrapper;
import org.apache.ignite.internal.util.lang.GridInClosure3;
import org.apache.ignite.internal.util.lang.GridMetadataAwareAdapter;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.C1;
import org.apache.ignite.internal.util.typedef.CI2;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.LT;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.lifecycle.LifecycleAware;
import org.apache.ignite.transactions.Transaction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Store manager.
*/
@SuppressWarnings({"AssignmentToCatchBlockParameter", "unchecked"})
public abstract class GridCacheStoreManagerAdapter extends GridCacheManagerAdapter implements CacheStoreManager {
/** */
private static final int SES_ATTR = GridMetadataAwareAdapter.EntryKey.CACHE_STORE_MANAGER_KEY.key();
/** */
protected CacheStore<Object, Object> store;
/** */
protected CacheStore<?, ?> cfgStore;
/** */
private CacheStoreBalancingWrapper<Object, Object> singleThreadGate;
/** */
private ThreadLocal<SessionData> sesHolder;
/** */
private ThreadLocalSession locSes;
/** */
private boolean locStore;
/** */
private boolean writeThrough;
/** */
private Collection<CacheStoreSessionListener> sesLsnrs;
/** */
private boolean globalSesLsnrs;
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public void initialize(@Nullable CacheStore cfgStore, Map sesHolders) throws IgniteCheckedException {
GridKernalContext ctx = igniteContext();
CacheConfiguration cfg = cacheConfiguration();
writeThrough = cfg.isWriteThrough();
this.cfgStore = cfgStore;
store = cacheStoreWrapper(ctx, cfgStore, cfg);
singleThreadGate = store == null ? null : new CacheStoreBalancingWrapper<>(store);
ThreadLocal<SessionData> sesHolder0 = null;
if (cfgStore != null) {
sesHolder0 = ((Map<CacheStore, ThreadLocal>)sesHolders).get(cfgStore);
if (sesHolder0 == null) {
sesHolder0 = new ThreadLocal<>();
locSes = new ThreadLocalSession(sesHolder0);
if (ctx.resource().injectStoreSession(cfgStore, locSes))
sesHolders.put(cfgStore, sesHolder0);
}
else
locSes = new ThreadLocalSession(sesHolder0);
}
sesHolder = sesHolder0;
locStore = U.hasAnnotation(cfgStore, CacheLocalStore.class);
}
/** {@inheritDoc} */
@Override public boolean isWriteThrough() {
return writeThrough;
}
/**
* Creates a wrapped cache store if write-behind cache is configured.
*
* @param ctx Kernal context.
* @param cfgStore Store provided in configuration.
* @param cfg Cache configuration.
* @return Instance if {@link GridCacheWriteBehindStore} if write-behind store is configured,
* or user-defined cache store.
*/
@SuppressWarnings({"unchecked"})
private CacheStore cacheStoreWrapper(GridKernalContext ctx,
@Nullable CacheStore cfgStore,
CacheConfiguration cfg) {
if (cfgStore == null || !cfg.isWriteBehindEnabled())
return cfgStore;
GridCacheWriteBehindStore store = new GridCacheWriteBehindStore(this,
ctx.gridName(),
cfg.getName(),
ctx.log(GridCacheWriteBehindStore.class),
cfgStore);
store.setFlushSize(cfg.getWriteBehindFlushSize());
store.setFlushThreadCount(cfg.getWriteBehindFlushThreadCount());
store.setFlushFrequency(cfg.getWriteBehindFlushFrequency());
store.setBatchSize(cfg.getWriteBehindBatchSize());
return store;
}
/** {@inheritDoc} */
@Override protected void start0() throws IgniteCheckedException {
if (store instanceof LifecycleAware) {
try {
// Avoid second start() call on store in case when near cache is enabled.
if (cctx.config().isWriteBehindEnabled()) {
if (!cctx.isNear())
((LifecycleAware)store).start();
}
}
catch (Exception e) {
throw new IgniteCheckedException("Failed to start cache store: " + e, e);
}
}
CacheConfiguration cfg = cctx.config();
if (cfgStore != null) {
if (!cfg.isWriteThrough() && !cfg.isReadThrough()) {
U.quietAndWarn(log,
"Persistence store is configured, but both read-through and write-through are disabled. This " +
"configuration makes sense if the store implements loadCache method only. If this is the " +
"case, ignore this warning. Otherwise, fix the configuration for the cache: " + cfg.getName(),
"Persistence store is configured, but both read-through and write-through are disabled " +
"for cache: " + cfg.getName());
}
if (!cfg.isWriteThrough() && cfg.isWriteBehindEnabled()) {
U.quietAndWarn(log,
"To enable write-behind mode for the cache store it's also required to set " +
"CacheConfiguration.setWriteThrough(true) property, otherwise the persistence " +
"store will be never updated. Consider fixing configuration for the cache: " + cfg.getName(),
"Write-behind mode for the cache store also requires CacheConfiguration.setWriteThrough(true) " +
"property. Fix configuration for the cache: " + cfg.getName());
}
}
sesLsnrs = CU.startStoreSessionListeners(cctx.kernalContext(), cfg.getCacheStoreSessionListenerFactories());
if (sesLsnrs == null) {
sesLsnrs = cctx.shared().storeSessionListeners();
globalSesLsnrs = true;
}
}
/** {@inheritDoc} */
@Override protected void stop0(boolean cancel) {
if (store instanceof LifecycleAware) {
try {
// Avoid second start() call on store in case when near cache is enabled.
if (cctx.config().isWriteBehindEnabled()) {
if (!cctx.isNear())
((LifecycleAware)store).stop();
}
}
catch (Exception e) {
U.error(log(), "Failed to stop cache store.", e);
}
}
if (!globalSesLsnrs) {
try {
CU.stopStoreSessionListeners(cctx.kernalContext(), sesLsnrs);
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to stop store session listeners for cache: " + cctx.name(), e);
}
}
}
/** {@inheritDoc} */
@Override public boolean isLocal() {
return locStore;
}
/** {@inheritDoc} */
@Override public boolean configured() {
return store != null;
}
/** {@inheritDoc} */
@Override public CacheStore<?, ?> configuredStore() {
return cfgStore;
}
/** {@inheritDoc} */
@Override @Nullable public Object load(@Nullable IgniteInternalTx tx, KeyCacheObject key)
throws IgniteCheckedException {
return loadFromStore(tx, key, true);
}
/**
* Loads data from persistent store.
*
* @param tx Cache transaction.
* @param key Cache key.
* @param convert Convert flag.
* @return Loaded value, possibly <tt>null</tt>.
* @throws IgniteCheckedException If data loading failed.
*/
@Nullable private Object loadFromStore(@Nullable IgniteInternalTx tx,
KeyCacheObject key,
boolean convert)
throws IgniteCheckedException {
if (store != null) {
if (key.internal())
// Never load internal keys from store as they are never persisted.
return null;
Object storeKey = key.value(cctx.cacheObjectContext(), false);
if (convertPortable())
storeKey = cctx.unwrapPortableIfNeeded(storeKey, false);
if (log.isDebugEnabled())
log.debug("Loading value from store for key: " + storeKey);
sessionInit0(tx);
boolean threwEx = true;
Object val = null;
try {
val = singleThreadGate.load(storeKey);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (CacheLoaderException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheLoaderException(e));
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Loaded value from store [key=" + key + ", val=" + val + ']');
if (convert) {
val = convert(val);
return val;
}
else
return val;
}
return null;
}
/**
* @param val Internal value.
* @return User value.
*/
private Object convert(Object val) {
if (val == null)
return null;
return locStore ? ((IgniteBiTuple<Object, GridCacheVersion>)val).get1() : val;
}
/** {@inheritDoc} */
@Override public boolean isWriteBehind() {
return cctx.config().isWriteBehindEnabled();
}
/** {@inheritDoc} */
@Override public boolean isWriteToStoreFromDht() {
return isWriteBehind() || locStore;
}
/** {@inheritDoc} */
@Override public void localStoreLoadAll(@Nullable IgniteInternalTx tx, Collection keys, GridInClosure3 vis)
throws IgniteCheckedException {
assert store != null;
assert locStore;
loadAllFromStore(tx, keys, null, vis);
}
/** {@inheritDoc} */
@Override public boolean loadAll(@Nullable IgniteInternalTx tx, Collection keys, IgniteBiInClosure vis)
throws IgniteCheckedException {
if (store != null) {
loadAllFromStore(tx, keys, vis, null);
return true;
}
else {
for (Object key : keys)
vis.apply(key, null);
}
return false;
}
/**
* @param tx Cache transaction.
* @param keys Keys to load.
* @param vis Key/value closure (only one of vis or verVis can be specified).
* @param verVis Key/value/version closure (only one of vis or verVis can be specified).
* @throws IgniteCheckedException If failed.
*/
private void loadAllFromStore(@Nullable IgniteInternalTx tx,
Collection<? extends KeyCacheObject> keys,
@Nullable final IgniteBiInClosure<KeyCacheObject, Object> vis,
@Nullable final GridInClosure3<KeyCacheObject, Object, GridCacheVersion> verVis)
throws IgniteCheckedException {
assert vis != null ^ verVis != null;
assert verVis == null || locStore;
final boolean convert = verVis == null;
if (!keys.isEmpty()) {
if (keys.size() == 1) {
KeyCacheObject key = F.first(keys);
if (convert)
vis.apply(key, load(tx, key));
else {
IgniteBiTuple<Object, GridCacheVersion> t =
(IgniteBiTuple<Object, GridCacheVersion>)loadFromStore(tx, key, false);
if (t != null)
verVis.apply(key, t.get1(), t.get2());
}
return;
}
Collection<Object> keys0;
if (convertPortable()) {
keys0 = F.viewReadOnly(keys, new C1<KeyCacheObject, Object>() {
@Override public Object apply(KeyCacheObject key) {
return cctx.unwrapPortableIfNeeded(key.value(cctx.cacheObjectContext(), false), false);
}
});
}
else {
keys0 = F.viewReadOnly(keys, new C1<KeyCacheObject, Object>() {
@Override public Object apply(KeyCacheObject key) {
return key.value(cctx.cacheObjectContext(), false);
}
});
}
if (log.isDebugEnabled())
log.debug("Loading values from store for keys: " + keys0);
sessionInit0(tx);
boolean threwEx = true;
try {
IgniteBiInClosure<Object, Object> c = new CI2<Object, Object>() {
@SuppressWarnings("ConstantConditions")
@Override public void apply(Object k, Object val) {
if (convert) {
Object v = convert(val);
vis.apply(cctx.toCacheKeyObject(k), v);
}
else {
IgniteBiTuple<Object, GridCacheVersion> v = (IgniteBiTuple<Object, GridCacheVersion>)val;
if (v != null)
verVis.apply(cctx.toCacheKeyObject(k), v.get1(), v.get2());
}
}
};
if (keys.size() > singleThreadGate.loadAllThreshold()) {
Map<Object, Object> map = store.loadAll(keys0);
if (map != null) {
for (Map.Entry<Object, Object> e : map.entrySet())
c.apply(cctx.toCacheKeyObject(e.getKey()), e.getValue());
}
}
else
singleThreadGate.loadAll(keys0, c);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (CacheLoaderException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheLoaderException(e));
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Loaded values from store for keys: " + keys0);
}
}
/** {@inheritDoc} */
@Override public boolean loadCache(final GridInClosure3 vis, Object[] args) throws IgniteCheckedException {
if (store != null) {
if (log.isDebugEnabled())
log.debug("Loading all values from store.");
sessionInit0(null);
boolean threwEx = true;
try {
store.loadCache(new IgniteBiInClosure<Object, Object>() {
@Override public void apply(Object k, Object o) {
Object v;
GridCacheVersion ver = null;
if (locStore) {
IgniteBiTuple<Object, GridCacheVersion> t = (IgniteBiTuple<Object, GridCacheVersion>)o;
v = t.get1();
ver = t.get2();
}
else
v = o;
KeyCacheObject cacheKey = cctx.toCacheKeyObject(k);
vis.apply(cacheKey, v, ver);
}
}, args);
threwEx = false;
}
catch (CacheLoaderException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheLoaderException(e));
}
finally {
sessionEnd0(null, threwEx);
}
if (log.isDebugEnabled())
log.debug("Loaded all values from store.");
return true;
}
LT.warn(log, null, "Calling Cache.loadCache() method will have no effect, " +
"CacheConfiguration.getStore() is not defined for cache: " + cctx.namexx());
return false;
}
/** {@inheritDoc} */
@Override public boolean put(@Nullable IgniteInternalTx tx, Object key, Object val, GridCacheVersion ver)
throws IgniteCheckedException {
if (store != null) {
// Never persist internal keys.
if (key instanceof GridCacheInternal)
return true;
if (convertPortable()) {
key = cctx.unwrapPortableIfNeeded(key, false);
val = cctx.unwrapPortableIfNeeded(val, false);
}
if (log.isDebugEnabled())
log.debug("Storing value in cache store [key=" + key + ", val=" + val + ']');
sessionInit0(tx);
boolean threwEx = true;
try {
store.write(new CacheEntryImpl<>(key, locStore ? F.t(val, ver) : val));
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (CacheWriterException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheWriterException(e));
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Stored value in cache store [key=" + key + ", val=" + val + ']');
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public boolean putAll(@Nullable IgniteInternalTx tx, Map map) throws IgniteCheckedException {
if (F.isEmpty(map))
return true;
if (map.size() == 1) {
Map.Entry<Object, IgniteBiTuple<Object, GridCacheVersion>> e =
((Map<Object, IgniteBiTuple<Object, GridCacheVersion>>)map).entrySet().iterator().next();
return put(tx, e.getKey(), e.getValue().get1(), e.getValue().get2());
}
else {
if (store != null) {
EntriesView entries = new EntriesView(map);
if (log.isDebugEnabled())
log.debug("Storing values in cache store [entries=" + entries + ']');
sessionInit0(tx);
boolean threwEx = true;
try {
store.writeAll(entries);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (Exception e) {
if (!(e instanceof CacheWriterException))
e = new CacheWriterException(e);
if (!entries.isEmpty()) {
List<Object> keys = new ArrayList<>(entries.size());
for (Cache.Entry<?, ?> entry : entries)
keys.add(entry.getKey());
throw new CacheStorePartialUpdateException(keys, e);
}
throw new IgniteCheckedException(e);
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Stored value in cache store [entries=" + entries + ']');
return true;
}
return false;
}
}
/** {@inheritDoc} */
@Override public boolean remove(@Nullable IgniteInternalTx tx, Object key) throws IgniteCheckedException {
if (store != null) {
// Never remove internal key from store as it is never persisted.
if (key instanceof GridCacheInternal)
return false;
if (convertPortable())
key = cctx.unwrapPortableIfNeeded(key, false);
if (log.isDebugEnabled())
log.debug("Removing value from cache store [key=" + key + ']');
sessionInit0(tx);
boolean threwEx = true;
try {
store.delete(key);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (CacheWriterException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheWriterException(e));
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Removed value from cache store [key=" + key + ']');
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public boolean removeAll(@Nullable IgniteInternalTx tx, Collection keys) throws IgniteCheckedException {
if (F.isEmpty(keys))
return true;
if (keys.size() == 1) {
Object key = keys.iterator().next();
return remove(tx, key);
}
if (store != null) {
Collection<Object> keys0 = convertPortable() ? cctx.unwrapPortablesIfNeeded(keys, false) : keys;
if (log.isDebugEnabled())
log.debug("Removing values from cache store [keys=" + keys0 + ']');
sessionInit0(tx);
boolean threwEx = true;
try {
store.deleteAll(keys0);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (Exception e) {
if (!(e instanceof CacheWriterException))
e = new CacheWriterException(e);
if (!keys0.isEmpty())
throw new CacheStorePartialUpdateException(keys0, e);
throw new IgniteCheckedException(e);
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Removed values from cache store [keys=" + keys0 + ']');
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public CacheStore<Object, Object> store() {
return store;
}
/** {@inheritDoc} */
@Override public void forceFlush() throws IgniteCheckedException {
if (store instanceof GridCacheWriteBehindStore)
((GridCacheWriteBehindStore)store).forceFlush();
}
/** {@inheritDoc} */
@Override public void sessionEnd(IgniteInternalTx tx, boolean commit, boolean last) throws IgniteCheckedException {
assert store != null;
sessionInit0(tx);
try {
if (sesLsnrs != null) {
for (CacheStoreSessionListener lsnr : sesLsnrs)
lsnr.onSessionEnd(locSes, commit);
}
if (!sesHolder.get().ended(store))
store.sessionEnd(commit);
}
catch (Throwable e) {
last = true;
throw e;
}
finally {
if (last && sesHolder != null) {
sesHolder.set(null);
tx.removeMeta(SES_ATTR);
}
}
}
/**
* @param e Class cast exception.
* @throws IgniteCheckedException Thrown exception.
*/
private void handleClassCastException(ClassCastException e) throws IgniteCheckedException {
assert e != null;
if (e.getMessage() != null) {
throw new IgniteCheckedException("Cache store must work with portable objects if portables are " +
"enabled for cache [cacheName=" + cctx.namex() + ']', e);
}
else
throw e;
}
/** {@inheritDoc} */
@Override public void writeBehindSessionInit() {
sessionInit0(null);
}
/** {@inheritDoc} */
@Override public void writeBehindSessionEnd(boolean threwEx) throws IgniteCheckedException {
sessionEnd0(null, threwEx);
}
/**
* @param tx Current transaction.
*/
private void sessionInit0(@Nullable IgniteInternalTx tx) {
assert sesHolder != null;
SessionData ses;
if (tx != null) {
ses = tx.meta(SES_ATTR);
if (ses == null) {
ses = new SessionData(tx, cctx.name());
tx.addMeta(SES_ATTR, ses);
}
else
// Session cache name may change in cross-cache transaction.
ses.cacheName(cctx.name());
}
else
ses = new SessionData(null, cctx.name());
sesHolder.set(ses);
if (sesLsnrs != null && !ses.started(this)) {
for (CacheStoreSessionListener lsnr : sesLsnrs)
lsnr.onSessionStart(locSes);
}
}
/**
* Clears session holder.
*/
private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException {
try {
if (tx == null) {
if (sesLsnrs != null) {
for (CacheStoreSessionListener lsnr : sesLsnrs)
lsnr.onSessionEnd(locSes, !threwEx);
}
assert !sesHolder.get().ended(store);
store.sessionEnd(!threwEx);
}
}
catch (Exception e) {
if (!threwEx)
throw U.cast(e);
}
finally {
if (sesHolder != null)
sesHolder.set(null);
}
}
/**
* @return Ignite context.
*/
protected abstract GridKernalContext igniteContext();
/**
* @return Cache configuration.
*/
protected abstract CacheConfiguration cacheConfiguration();
/**
*
*/
private static class SessionData {
/** */
@GridToStringExclude
private final IgniteInternalTx tx;
/** */
private String cacheName;
/** */
@GridToStringInclude
private Map<Object, Object> props;
/** */
private Object attachment;
/** */
private final Set<CacheStoreManager> started =
new GridSetWrapper<>(new IdentityHashMap<CacheStoreManager, Object>());
/** */
private final Set<CacheStore> ended = new GridSetWrapper<>(new IdentityHashMap<CacheStore, Object>());
/**
* @param tx Current transaction.
* @param cacheName Cache name.
*/
private SessionData(@Nullable IgniteInternalTx tx, @Nullable String cacheName) {
this.tx = tx;
this.cacheName = cacheName;
}
/**
* @return Transaction.
*/
@Nullable private Transaction transaction() {
return tx != null ? tx.proxy() : null;
}
/**
* @return Properties.
*/
private Map<Object, Object> properties() {
if (props == null)
props = new GridLeanMap<>();
return props;
}
/**
* @param attachment Attachment.
*/
private Object attach(Object attachment) {
Object prev = this.attachment;
this.attachment = attachment;
return prev;
}
/**
* @return Attachment.
*/
private Object attachment() {
return attachment;
}
/**
* @return Cache name.
*/
private String cacheName() {
return cacheName;
}
/**
* @param cacheName Cache name.
*/
private void cacheName(String cacheName) {
this.cacheName = cacheName;
}
/**
* @return If session is started.
*/
private boolean started(CacheStoreManager mgr) {
return !started.add(mgr);
}
/**
* @param store Cache store.
* @return Whether session already ended on this store instance.
*/
private boolean ended(CacheStore store) {
return !ended.add(store);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(SessionData.class, this, "tx", CU.txString(tx));
}
}
/**
*
*/
private static class ThreadLocalSession implements CacheStoreSession {
/** */
private final ThreadLocal<SessionData> sesHolder;
/**
* @param sesHolder Session holder.
*/
private ThreadLocalSession(ThreadLocal<SessionData> sesHolder) {
this.sesHolder = sesHolder;
}
/** {@inheritDoc} */
@Nullable @Override public Transaction transaction() {
SessionData ses0 = sesHolder.get();
return ses0 != null ? ses0.transaction() : null;
}
/** {@inheritDoc} */
@Override public boolean isWithinTransaction() {
return transaction() != null;
}
/** {@inheritDoc} */
@Override public Object attach(@Nullable Object attachment) {
SessionData ses0 = sesHolder.get();
return ses0 != null ? ses0.attach(attachment) : null;
}
/** {@inheritDoc} */
@Nullable @Override public <T> T attachment() {
SessionData ses0 = sesHolder.get();
return ses0 != null ? (T)ses0.attachment() : null;
}
/** {@inheritDoc} */
@Override public <K1, V1> Map<K1, V1> properties() {
SessionData ses0 = sesHolder.get();
return ses0 != null ? (Map<K1, V1>)ses0.properties() : null;
}
/** {@inheritDoc} */
@Nullable @Override public String cacheName() {
SessionData ses0 = sesHolder.get();
return ses0 != null ? ses0.cacheName() : null;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(ThreadLocalSession.class, this);
}
}
/**
*
*/
private class EntriesView extends AbstractCollection<Cache.Entry<?, ?>> {
/** */
private final Map<?, IgniteBiTuple<?, GridCacheVersion>> map;
/** */
private Set<Object> rmvd;
/** */
private boolean cleared;
/**
* @param map Map.
*/
private EntriesView(Map<?, IgniteBiTuple<?, GridCacheVersion>> map) {
assert map != null;
this.map = map;
}
/** {@inheritDoc} */
@Override public int size() {
return cleared ? 0 : (map.size() - (rmvd != null ? rmvd.size() : 0));
}
/** {@inheritDoc} */
@Override public boolean isEmpty() {
return cleared || !iterator().hasNext();
}
/** {@inheritDoc} */
@Override public boolean contains(Object o) {
if (cleared || !(o instanceof Cache.Entry))
return false;
Cache.Entry<?, ?> e = (Cache.Entry<?, ?>)o;
return map.containsKey(e.getKey());
}
/** {@inheritDoc} */
@NotNull @Override public Iterator<Cache.Entry<?, ?>> iterator() {
if (cleared)
return F.emptyIterator();
final Iterator<Map.Entry<?, IgniteBiTuple<?, GridCacheVersion>>> it0 = (Iterator)map.entrySet().iterator();
return new Iterator<Cache.Entry<?, ?>>() {
/** */
private Cache.Entry<?, ?> cur;
/** */
private Cache.Entry<?, ?> next;
/**
*
*/
{
checkNext();
}
/**
*
*/
private void checkNext() {
while (it0.hasNext()) {
Map.Entry<?, IgniteBiTuple<?, GridCacheVersion>> e = it0.next();
Object k = e.getKey();
if (rmvd != null && rmvd.contains(k))
continue;
Object v = locStore ? e.getValue() : e.getValue().get1();
if (convertPortable()) {
k = cctx.unwrapPortableIfNeeded(k, false);
v = cctx.unwrapPortableIfNeeded(v, false);
}
next = new CacheEntryImpl<>(k, v);
break;
}
}
@Override public boolean hasNext() {
return next != null;
}
@Override public Cache.Entry<?, ?> next() {
if (next == null)
throw new NoSuchElementException();
cur = next;
next = null;
checkNext();
return cur;
}
@Override public void remove() {
if (cur == null)
throw new IllegalStateException();
addRemoved(cur);
cur = null;
}
};
}
/** {@inheritDoc} */
@Override public boolean add(Cache.Entry<?, ?> entry) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public boolean addAll(Collection<? extends Cache.Entry<?, ?>> col) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public boolean remove(Object o) {
if (cleared || !(o instanceof Cache.Entry))
return false;
Cache.Entry<?, ?> e = (Cache.Entry<?, ?>)o;
if (rmvd != null && rmvd.contains(e.getKey()))
return false;
if (mapContains(e)) {
addRemoved(e);
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public boolean containsAll(Collection<?> col) {
if (cleared)
return false;
for (Object o : col) {
if (contains(o))
return false;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean removeAll(Collection<?> col) {
if (cleared)
return false;
boolean modified = false;
for (Object o : col) {
if (remove(o))
modified = true;
}
return modified;
}
/** {@inheritDoc} */
@Override public boolean retainAll(Collection<?> col) {
if (cleared)
return false;
boolean modified = false;
for (Cache.Entry<?, ?> e : this) {
if (!col.contains(e)) {
addRemoved(e);
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
@Override public void clear() {
cleared = true;
}
/**
* @param e Entry.
*/
private void addRemoved(Cache.Entry<?, ?> e) {
if (rmvd == null)
rmvd = new HashSet<>();
rmvd.add(e.getKey());
}
/**
* @param e Entry.
* @return {@code True} if original map contains entry.
*/
private boolean mapContains(Cache.Entry<?, ?> e) {
return map.containsKey(e.getKey());
}
/** {@inheritDoc} */
public String toString() {
Iterator<Cache.Entry<?, ?>> it = iterator();
if (!it.hasNext())
return "[]";
SB sb = new SB("[");
while (true) {
Cache.Entry<?, ?> e = it.next();
sb.a(e.toString());
if (!it.hasNext())
return sb.a(']').toString();
sb.a(", ");
}
}
}
}
| modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.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.ignite.internal.processors.cache.store;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.cache.Cache;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.cache.store.CacheStore;
import org.apache.ignite.cache.store.CacheStoreSession;
import org.apache.ignite.cache.store.CacheStoreSessionListener;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.processors.cache.CacheEntryImpl;
import org.apache.ignite.internal.processors.cache.CacheStoreBalancingWrapper;
import org.apache.ignite.internal.processors.cache.CacheStorePartialUpdateException;
import org.apache.ignite.internal.processors.cache.GridCacheInternal;
import org.apache.ignite.internal.processors.cache.GridCacheManagerAdapter;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.util.GridLeanMap;
import org.apache.ignite.internal.util.GridSetWrapper;
import org.apache.ignite.internal.util.lang.GridInClosure3;
import org.apache.ignite.internal.util.lang.GridMetadataAwareAdapter;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.C1;
import org.apache.ignite.internal.util.typedef.CI2;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.LT;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.lifecycle.LifecycleAware;
import org.apache.ignite.transactions.Transaction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Store manager.
*/
@SuppressWarnings({"AssignmentToCatchBlockParameter", "unchecked"})
public abstract class GridCacheStoreManagerAdapter extends GridCacheManagerAdapter implements CacheStoreManager {
/** */
private static final int SES_ATTR = GridMetadataAwareAdapter.EntryKey.CACHE_STORE_MANAGER_KEY.key();
/** */
protected CacheStore<Object, Object> store;
/** */
protected CacheStore<?, ?> cfgStore;
/** */
private CacheStoreBalancingWrapper<Object, Object> singleThreadGate;
/** */
private ThreadLocal<SessionData> sesHolder;
/** */
private ThreadLocalSession locSes;
/** */
private boolean locStore;
/** */
private boolean writeThrough;
/** */
private Collection<CacheStoreSessionListener> sesLsnrs;
/** */
private boolean globalSesLsnrs;
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public void initialize(@Nullable CacheStore cfgStore, Map sesHolders) throws IgniteCheckedException {
GridKernalContext ctx = igniteContext();
CacheConfiguration cfg = cacheConfiguration();
writeThrough = cfg.isWriteThrough();
this.cfgStore = cfgStore;
store = cacheStoreWrapper(ctx, cfgStore, cfg);
singleThreadGate = store == null ? null : new CacheStoreBalancingWrapper<>(store);
ThreadLocal<SessionData> sesHolder0 = null;
if (cfgStore != null) {
sesHolder0 = ((Map<CacheStore, ThreadLocal>)sesHolders).get(cfgStore);
if (sesHolder0 == null) {
sesHolder0 = new ThreadLocal<>();
locSes = new ThreadLocalSession(sesHolder0);
if (ctx.resource().injectStoreSession(cfgStore, locSes))
sesHolders.put(cfgStore, sesHolder0);
}
else
locSes = new ThreadLocalSession(sesHolder0);
}
sesHolder = sesHolder0;
locStore = U.hasAnnotation(cfgStore, CacheLocalStore.class);
}
/** {@inheritDoc} */
@Override public boolean isWriteThrough() {
return writeThrough;
}
/**
* Creates a wrapped cache store if write-behind cache is configured.
*
* @param ctx Kernal context.
* @param cfgStore Store provided in configuration.
* @param cfg Cache configuration.
* @return Instance if {@link GridCacheWriteBehindStore} if write-behind store is configured,
* or user-defined cache store.
*/
@SuppressWarnings({"unchecked"})
private CacheStore cacheStoreWrapper(GridKernalContext ctx,
@Nullable CacheStore cfgStore,
CacheConfiguration cfg) {
if (cfgStore == null || !cfg.isWriteBehindEnabled())
return cfgStore;
GridCacheWriteBehindStore store = new GridCacheWriteBehindStore(this,
ctx.gridName(),
cfg.getName(),
ctx.log(GridCacheWriteBehindStore.class),
cfgStore);
store.setFlushSize(cfg.getWriteBehindFlushSize());
store.setFlushThreadCount(cfg.getWriteBehindFlushThreadCount());
store.setFlushFrequency(cfg.getWriteBehindFlushFrequency());
store.setBatchSize(cfg.getWriteBehindBatchSize());
return store;
}
/** {@inheritDoc} */
@Override protected void start0() throws IgniteCheckedException {
if (store instanceof LifecycleAware) {
try {
// Avoid second start() call on store in case when near cache is enabled.
if (cctx.config().isWriteBehindEnabled()) {
if (!cctx.isNear())
((LifecycleAware)store).start();
}
}
catch (Exception e) {
throw new IgniteCheckedException("Failed to start cache store: " + e, e);
}
}
CacheConfiguration cfg = cctx.config();
if (cfgStore != null && !cfg.isWriteThrough() && !cfg.isReadThrough()) {
U.quietAndWarn(log,
"Persistence store is configured, but both read-through and write-through are disabled. This " +
"configuration makes sense if the store implements loadCache method only. If this is the " +
"case, ignore this warning. Otherwise, fix the configuration for cache: " + cfg.getName(),
"Persistence store is configured, but both read-through and write-through are disabled.");
}
sesLsnrs = CU.startStoreSessionListeners(cctx.kernalContext(), cfg.getCacheStoreSessionListenerFactories());
if (sesLsnrs == null) {
sesLsnrs = cctx.shared().storeSessionListeners();
globalSesLsnrs = true;
}
}
/** {@inheritDoc} */
@Override protected void stop0(boolean cancel) {
if (store instanceof LifecycleAware) {
try {
// Avoid second start() call on store in case when near cache is enabled.
if (cctx.config().isWriteBehindEnabled()) {
if (!cctx.isNear())
((LifecycleAware)store).stop();
}
}
catch (Exception e) {
U.error(log(), "Failed to stop cache store.", e);
}
}
if (!globalSesLsnrs) {
try {
CU.stopStoreSessionListeners(cctx.kernalContext(), sesLsnrs);
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to stop store session listeners for cache: " + cctx.name(), e);
}
}
}
/** {@inheritDoc} */
@Override public boolean isLocal() {
return locStore;
}
/** {@inheritDoc} */
@Override public boolean configured() {
return store != null;
}
/** {@inheritDoc} */
@Override public CacheStore<?, ?> configuredStore() {
return cfgStore;
}
/** {@inheritDoc} */
@Override @Nullable public Object load(@Nullable IgniteInternalTx tx, KeyCacheObject key)
throws IgniteCheckedException {
return loadFromStore(tx, key, true);
}
/**
* Loads data from persistent store.
*
* @param tx Cache transaction.
* @param key Cache key.
* @param convert Convert flag.
* @return Loaded value, possibly <tt>null</tt>.
* @throws IgniteCheckedException If data loading failed.
*/
@Nullable private Object loadFromStore(@Nullable IgniteInternalTx tx,
KeyCacheObject key,
boolean convert)
throws IgniteCheckedException {
if (store != null) {
if (key.internal())
// Never load internal keys from store as they are never persisted.
return null;
Object storeKey = key.value(cctx.cacheObjectContext(), false);
if (convertPortable())
storeKey = cctx.unwrapPortableIfNeeded(storeKey, false);
if (log.isDebugEnabled())
log.debug("Loading value from store for key: " + storeKey);
sessionInit0(tx);
boolean threwEx = true;
Object val = null;
try {
val = singleThreadGate.load(storeKey);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (CacheLoaderException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheLoaderException(e));
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Loaded value from store [key=" + key + ", val=" + val + ']');
if (convert) {
val = convert(val);
return val;
}
else
return val;
}
return null;
}
/**
* @param val Internal value.
* @return User value.
*/
private Object convert(Object val) {
if (val == null)
return null;
return locStore ? ((IgniteBiTuple<Object, GridCacheVersion>)val).get1() : val;
}
/** {@inheritDoc} */
@Override public boolean isWriteBehind() {
return cctx.config().isWriteBehindEnabled();
}
/** {@inheritDoc} */
@Override public boolean isWriteToStoreFromDht() {
return isWriteBehind() || locStore;
}
/** {@inheritDoc} */
@Override public void localStoreLoadAll(@Nullable IgniteInternalTx tx, Collection keys, GridInClosure3 vis)
throws IgniteCheckedException {
assert store != null;
assert locStore;
loadAllFromStore(tx, keys, null, vis);
}
/** {@inheritDoc} */
@Override public boolean loadAll(@Nullable IgniteInternalTx tx, Collection keys, IgniteBiInClosure vis)
throws IgniteCheckedException {
if (store != null) {
loadAllFromStore(tx, keys, vis, null);
return true;
}
else {
for (Object key : keys)
vis.apply(key, null);
}
return false;
}
/**
* @param tx Cache transaction.
* @param keys Keys to load.
* @param vis Key/value closure (only one of vis or verVis can be specified).
* @param verVis Key/value/version closure (only one of vis or verVis can be specified).
* @throws IgniteCheckedException If failed.
*/
private void loadAllFromStore(@Nullable IgniteInternalTx tx,
Collection<? extends KeyCacheObject> keys,
@Nullable final IgniteBiInClosure<KeyCacheObject, Object> vis,
@Nullable final GridInClosure3<KeyCacheObject, Object, GridCacheVersion> verVis)
throws IgniteCheckedException {
assert vis != null ^ verVis != null;
assert verVis == null || locStore;
final boolean convert = verVis == null;
if (!keys.isEmpty()) {
if (keys.size() == 1) {
KeyCacheObject key = F.first(keys);
if (convert)
vis.apply(key, load(tx, key));
else {
IgniteBiTuple<Object, GridCacheVersion> t =
(IgniteBiTuple<Object, GridCacheVersion>)loadFromStore(tx, key, false);
if (t != null)
verVis.apply(key, t.get1(), t.get2());
}
return;
}
Collection<Object> keys0;
if (convertPortable()) {
keys0 = F.viewReadOnly(keys, new C1<KeyCacheObject, Object>() {
@Override public Object apply(KeyCacheObject key) {
return cctx.unwrapPortableIfNeeded(key.value(cctx.cacheObjectContext(), false), false);
}
});
}
else {
keys0 = F.viewReadOnly(keys, new C1<KeyCacheObject, Object>() {
@Override public Object apply(KeyCacheObject key) {
return key.value(cctx.cacheObjectContext(), false);
}
});
}
if (log.isDebugEnabled())
log.debug("Loading values from store for keys: " + keys0);
sessionInit0(tx);
boolean threwEx = true;
try {
IgniteBiInClosure<Object, Object> c = new CI2<Object, Object>() {
@SuppressWarnings("ConstantConditions")
@Override public void apply(Object k, Object val) {
if (convert) {
Object v = convert(val);
vis.apply(cctx.toCacheKeyObject(k), v);
}
else {
IgniteBiTuple<Object, GridCacheVersion> v = (IgniteBiTuple<Object, GridCacheVersion>)val;
if (v != null)
verVis.apply(cctx.toCacheKeyObject(k), v.get1(), v.get2());
}
}
};
if (keys.size() > singleThreadGate.loadAllThreshold()) {
Map<Object, Object> map = store.loadAll(keys0);
if (map != null) {
for (Map.Entry<Object, Object> e : map.entrySet())
c.apply(cctx.toCacheKeyObject(e.getKey()), e.getValue());
}
}
else
singleThreadGate.loadAll(keys0, c);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (CacheLoaderException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheLoaderException(e));
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Loaded values from store for keys: " + keys0);
}
}
/** {@inheritDoc} */
@Override public boolean loadCache(final GridInClosure3 vis, Object[] args) throws IgniteCheckedException {
if (store != null) {
if (log.isDebugEnabled())
log.debug("Loading all values from store.");
sessionInit0(null);
boolean threwEx = true;
try {
store.loadCache(new IgniteBiInClosure<Object, Object>() {
@Override public void apply(Object k, Object o) {
Object v;
GridCacheVersion ver = null;
if (locStore) {
IgniteBiTuple<Object, GridCacheVersion> t = (IgniteBiTuple<Object, GridCacheVersion>)o;
v = t.get1();
ver = t.get2();
}
else
v = o;
KeyCacheObject cacheKey = cctx.toCacheKeyObject(k);
vis.apply(cacheKey, v, ver);
}
}, args);
threwEx = false;
}
catch (CacheLoaderException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheLoaderException(e));
}
finally {
sessionEnd0(null, threwEx);
}
if (log.isDebugEnabled())
log.debug("Loaded all values from store.");
return true;
}
LT.warn(log, null, "Calling Cache.loadCache() method will have no effect, " +
"CacheConfiguration.getStore() is not defined for cache: " + cctx.namexx());
return false;
}
/** {@inheritDoc} */
@Override public boolean put(@Nullable IgniteInternalTx tx, Object key, Object val, GridCacheVersion ver)
throws IgniteCheckedException {
if (store != null) {
// Never persist internal keys.
if (key instanceof GridCacheInternal)
return true;
if (convertPortable()) {
key = cctx.unwrapPortableIfNeeded(key, false);
val = cctx.unwrapPortableIfNeeded(val, false);
}
if (log.isDebugEnabled())
log.debug("Storing value in cache store [key=" + key + ", val=" + val + ']');
sessionInit0(tx);
boolean threwEx = true;
try {
store.write(new CacheEntryImpl<>(key, locStore ? F.t(val, ver) : val));
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (CacheWriterException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheWriterException(e));
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Stored value in cache store [key=" + key + ", val=" + val + ']');
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public boolean putAll(@Nullable IgniteInternalTx tx, Map map) throws IgniteCheckedException {
if (F.isEmpty(map))
return true;
if (map.size() == 1) {
Map.Entry<Object, IgniteBiTuple<Object, GridCacheVersion>> e =
((Map<Object, IgniteBiTuple<Object, GridCacheVersion>>)map).entrySet().iterator().next();
return put(tx, e.getKey(), e.getValue().get1(), e.getValue().get2());
}
else {
if (store != null) {
EntriesView entries = new EntriesView(map);
if (log.isDebugEnabled())
log.debug("Storing values in cache store [entries=" + entries + ']');
sessionInit0(tx);
boolean threwEx = true;
try {
store.writeAll(entries);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (Exception e) {
if (!(e instanceof CacheWriterException))
e = new CacheWriterException(e);
if (!entries.isEmpty()) {
List<Object> keys = new ArrayList<>(entries.size());
for (Cache.Entry<?, ?> entry : entries)
keys.add(entry.getKey());
throw new CacheStorePartialUpdateException(keys, e);
}
throw new IgniteCheckedException(e);
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Stored value in cache store [entries=" + entries + ']');
return true;
}
return false;
}
}
/** {@inheritDoc} */
@Override public boolean remove(@Nullable IgniteInternalTx tx, Object key) throws IgniteCheckedException {
if (store != null) {
// Never remove internal key from store as it is never persisted.
if (key instanceof GridCacheInternal)
return false;
if (convertPortable())
key = cctx.unwrapPortableIfNeeded(key, false);
if (log.isDebugEnabled())
log.debug("Removing value from cache store [key=" + key + ']');
sessionInit0(tx);
boolean threwEx = true;
try {
store.delete(key);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (CacheWriterException e) {
throw new IgniteCheckedException(e);
}
catch (Exception e) {
throw new IgniteCheckedException(new CacheWriterException(e));
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Removed value from cache store [key=" + key + ']');
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public boolean removeAll(@Nullable IgniteInternalTx tx, Collection keys) throws IgniteCheckedException {
if (F.isEmpty(keys))
return true;
if (keys.size() == 1) {
Object key = keys.iterator().next();
return remove(tx, key);
}
if (store != null) {
Collection<Object> keys0 = convertPortable() ? cctx.unwrapPortablesIfNeeded(keys, false) : keys;
if (log.isDebugEnabled())
log.debug("Removing values from cache store [keys=" + keys0 + ']');
sessionInit0(tx);
boolean threwEx = true;
try {
store.deleteAll(keys0);
threwEx = false;
}
catch (ClassCastException e) {
handleClassCastException(e);
}
catch (Exception e) {
if (!(e instanceof CacheWriterException))
e = new CacheWriterException(e);
if (!keys0.isEmpty())
throw new CacheStorePartialUpdateException(keys0, e);
throw new IgniteCheckedException(e);
}
finally {
sessionEnd0(tx, threwEx);
}
if (log.isDebugEnabled())
log.debug("Removed values from cache store [keys=" + keys0 + ']');
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public CacheStore<Object, Object> store() {
return store;
}
/** {@inheritDoc} */
@Override public void forceFlush() throws IgniteCheckedException {
if (store instanceof GridCacheWriteBehindStore)
((GridCacheWriteBehindStore)store).forceFlush();
}
/** {@inheritDoc} */
@Override public void sessionEnd(IgniteInternalTx tx, boolean commit, boolean last) throws IgniteCheckedException {
assert store != null;
sessionInit0(tx);
try {
if (sesLsnrs != null) {
for (CacheStoreSessionListener lsnr : sesLsnrs)
lsnr.onSessionEnd(locSes, commit);
}
if (!sesHolder.get().ended(store))
store.sessionEnd(commit);
}
catch (Throwable e) {
last = true;
throw e;
}
finally {
if (last && sesHolder != null) {
sesHolder.set(null);
tx.removeMeta(SES_ATTR);
}
}
}
/**
* @param e Class cast exception.
* @throws IgniteCheckedException Thrown exception.
*/
private void handleClassCastException(ClassCastException e) throws IgniteCheckedException {
assert e != null;
if (e.getMessage() != null) {
throw new IgniteCheckedException("Cache store must work with portable objects if portables are " +
"enabled for cache [cacheName=" + cctx.namex() + ']', e);
}
else
throw e;
}
/** {@inheritDoc} */
@Override public void writeBehindSessionInit() {
sessionInit0(null);
}
/** {@inheritDoc} */
@Override public void writeBehindSessionEnd(boolean threwEx) throws IgniteCheckedException {
sessionEnd0(null, threwEx);
}
/**
* @param tx Current transaction.
*/
private void sessionInit0(@Nullable IgniteInternalTx tx) {
assert sesHolder != null;
SessionData ses;
if (tx != null) {
ses = tx.meta(SES_ATTR);
if (ses == null) {
ses = new SessionData(tx, cctx.name());
tx.addMeta(SES_ATTR, ses);
}
else
// Session cache name may change in cross-cache transaction.
ses.cacheName(cctx.name());
}
else
ses = new SessionData(null, cctx.name());
sesHolder.set(ses);
if (sesLsnrs != null && !ses.started(this)) {
for (CacheStoreSessionListener lsnr : sesLsnrs)
lsnr.onSessionStart(locSes);
}
}
/**
* Clears session holder.
*/
private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException {
try {
if (tx == null) {
if (sesLsnrs != null) {
for (CacheStoreSessionListener lsnr : sesLsnrs)
lsnr.onSessionEnd(locSes, !threwEx);
}
assert !sesHolder.get().ended(store);
store.sessionEnd(!threwEx);
}
}
catch (Exception e) {
if (!threwEx)
throw U.cast(e);
}
finally {
if (sesHolder != null)
sesHolder.set(null);
}
}
/**
* @return Ignite context.
*/
protected abstract GridKernalContext igniteContext();
/**
* @return Cache configuration.
*/
protected abstract CacheConfiguration cacheConfiguration();
/**
*
*/
private static class SessionData {
/** */
@GridToStringExclude
private final IgniteInternalTx tx;
/** */
private String cacheName;
/** */
@GridToStringInclude
private Map<Object, Object> props;
/** */
private Object attachment;
/** */
private final Set<CacheStoreManager> started =
new GridSetWrapper<>(new IdentityHashMap<CacheStoreManager, Object>());
/** */
private final Set<CacheStore> ended = new GridSetWrapper<>(new IdentityHashMap<CacheStore, Object>());
/**
* @param tx Current transaction.
* @param cacheName Cache name.
*/
private SessionData(@Nullable IgniteInternalTx tx, @Nullable String cacheName) {
this.tx = tx;
this.cacheName = cacheName;
}
/**
* @return Transaction.
*/
@Nullable private Transaction transaction() {
return tx != null ? tx.proxy() : null;
}
/**
* @return Properties.
*/
private Map<Object, Object> properties() {
if (props == null)
props = new GridLeanMap<>();
return props;
}
/**
* @param attachment Attachment.
*/
private Object attach(Object attachment) {
Object prev = this.attachment;
this.attachment = attachment;
return prev;
}
/**
* @return Attachment.
*/
private Object attachment() {
return attachment;
}
/**
* @return Cache name.
*/
private String cacheName() {
return cacheName;
}
/**
* @param cacheName Cache name.
*/
private void cacheName(String cacheName) {
this.cacheName = cacheName;
}
/**
* @return If session is started.
*/
private boolean started(CacheStoreManager mgr) {
return !started.add(mgr);
}
/**
* @param store Cache store.
* @return Whether session already ended on this store instance.
*/
private boolean ended(CacheStore store) {
return !ended.add(store);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(SessionData.class, this, "tx", CU.txString(tx));
}
}
/**
*
*/
private static class ThreadLocalSession implements CacheStoreSession {
/** */
private final ThreadLocal<SessionData> sesHolder;
/**
* @param sesHolder Session holder.
*/
private ThreadLocalSession(ThreadLocal<SessionData> sesHolder) {
this.sesHolder = sesHolder;
}
/** {@inheritDoc} */
@Nullable @Override public Transaction transaction() {
SessionData ses0 = sesHolder.get();
return ses0 != null ? ses0.transaction() : null;
}
/** {@inheritDoc} */
@Override public boolean isWithinTransaction() {
return transaction() != null;
}
/** {@inheritDoc} */
@Override public Object attach(@Nullable Object attachment) {
SessionData ses0 = sesHolder.get();
return ses0 != null ? ses0.attach(attachment) : null;
}
/** {@inheritDoc} */
@Nullable @Override public <T> T attachment() {
SessionData ses0 = sesHolder.get();
return ses0 != null ? (T)ses0.attachment() : null;
}
/** {@inheritDoc} */
@Override public <K1, V1> Map<K1, V1> properties() {
SessionData ses0 = sesHolder.get();
return ses0 != null ? (Map<K1, V1>)ses0.properties() : null;
}
/** {@inheritDoc} */
@Nullable @Override public String cacheName() {
SessionData ses0 = sesHolder.get();
return ses0 != null ? ses0.cacheName() : null;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(ThreadLocalSession.class, this);
}
}
/**
*
*/
private class EntriesView extends AbstractCollection<Cache.Entry<?, ?>> {
/** */
private final Map<?, IgniteBiTuple<?, GridCacheVersion>> map;
/** */
private Set<Object> rmvd;
/** */
private boolean cleared;
/**
* @param map Map.
*/
private EntriesView(Map<?, IgniteBiTuple<?, GridCacheVersion>> map) {
assert map != null;
this.map = map;
}
/** {@inheritDoc} */
@Override public int size() {
return cleared ? 0 : (map.size() - (rmvd != null ? rmvd.size() : 0));
}
/** {@inheritDoc} */
@Override public boolean isEmpty() {
return cleared || !iterator().hasNext();
}
/** {@inheritDoc} */
@Override public boolean contains(Object o) {
if (cleared || !(o instanceof Cache.Entry))
return false;
Cache.Entry<?, ?> e = (Cache.Entry<?, ?>)o;
return map.containsKey(e.getKey());
}
/** {@inheritDoc} */
@NotNull @Override public Iterator<Cache.Entry<?, ?>> iterator() {
if (cleared)
return F.emptyIterator();
final Iterator<Map.Entry<?, IgniteBiTuple<?, GridCacheVersion>>> it0 = (Iterator)map.entrySet().iterator();
return new Iterator<Cache.Entry<?, ?>>() {
/** */
private Cache.Entry<?, ?> cur;
/** */
private Cache.Entry<?, ?> next;
/**
*
*/
{
checkNext();
}
/**
*
*/
private void checkNext() {
while (it0.hasNext()) {
Map.Entry<?, IgniteBiTuple<?, GridCacheVersion>> e = it0.next();
Object k = e.getKey();
if (rmvd != null && rmvd.contains(k))
continue;
Object v = locStore ? e.getValue() : e.getValue().get1();
if (convertPortable()) {
k = cctx.unwrapPortableIfNeeded(k, false);
v = cctx.unwrapPortableIfNeeded(v, false);
}
next = new CacheEntryImpl<>(k, v);
break;
}
}
@Override public boolean hasNext() {
return next != null;
}
@Override public Cache.Entry<?, ?> next() {
if (next == null)
throw new NoSuchElementException();
cur = next;
next = null;
checkNext();
return cur;
}
@Override public void remove() {
if (cur == null)
throw new IllegalStateException();
addRemoved(cur);
cur = null;
}
};
}
/** {@inheritDoc} */
@Override public boolean add(Cache.Entry<?, ?> entry) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public boolean addAll(Collection<? extends Cache.Entry<?, ?>> col) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public boolean remove(Object o) {
if (cleared || !(o instanceof Cache.Entry))
return false;
Cache.Entry<?, ?> e = (Cache.Entry<?, ?>)o;
if (rmvd != null && rmvd.contains(e.getKey()))
return false;
if (mapContains(e)) {
addRemoved(e);
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public boolean containsAll(Collection<?> col) {
if (cleared)
return false;
for (Object o : col) {
if (contains(o))
return false;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean removeAll(Collection<?> col) {
if (cleared)
return false;
boolean modified = false;
for (Object o : col) {
if (remove(o))
modified = true;
}
return modified;
}
/** {@inheritDoc} */
@Override public boolean retainAll(Collection<?> col) {
if (cleared)
return false;
boolean modified = false;
for (Cache.Entry<?, ?> e : this) {
if (!col.contains(e)) {
addRemoved(e);
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
@Override public void clear() {
cleared = true;
}
/**
* @param e Entry.
*/
private void addRemoved(Cache.Entry<?, ?> e) {
if (rmvd == null)
rmvd = new HashSet<>();
rmvd.add(e.getKey());
}
/**
* @param e Entry.
* @return {@code True} if original map contains entry.
*/
private boolean mapContains(Cache.Entry<?, ?> e) {
return map.containsKey(e.getKey());
}
/** {@inheritDoc} */
public String toString() {
Iterator<Cache.Entry<?, ?>> it = iterator();
if (!it.hasNext())
return "[]";
SB sb = new SB("[");
while (true) {
Cache.Entry<?, ?> e = it.next();
sb.a(e.toString());
if (!it.hasNext())
return sb.a(']').toString();
sb.a(", ");
}
}
}
} | Warning is writeThrough==false && writeBehind==true
| modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java | Warning is writeThrough==false && writeBehind==true | <ide><path>odules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java
<ide>
<ide> CacheConfiguration cfg = cctx.config();
<ide>
<del> if (cfgStore != null && !cfg.isWriteThrough() && !cfg.isReadThrough()) {
<del> U.quietAndWarn(log,
<del> "Persistence store is configured, but both read-through and write-through are disabled. This " +
<del> "configuration makes sense if the store implements loadCache method only. If this is the " +
<del> "case, ignore this warning. Otherwise, fix the configuration for cache: " + cfg.getName(),
<del> "Persistence store is configured, but both read-through and write-through are disabled.");
<add> if (cfgStore != null) {
<add> if (!cfg.isWriteThrough() && !cfg.isReadThrough()) {
<add> U.quietAndWarn(log,
<add> "Persistence store is configured, but both read-through and write-through are disabled. This " +
<add> "configuration makes sense if the store implements loadCache method only. If this is the " +
<add> "case, ignore this warning. Otherwise, fix the configuration for the cache: " + cfg.getName(),
<add> "Persistence store is configured, but both read-through and write-through are disabled " +
<add> "for cache: " + cfg.getName());
<add> }
<add>
<add> if (!cfg.isWriteThrough() && cfg.isWriteBehindEnabled()) {
<add> U.quietAndWarn(log,
<add> "To enable write-behind mode for the cache store it's also required to set " +
<add> "CacheConfiguration.setWriteThrough(true) property, otherwise the persistence " +
<add> "store will be never updated. Consider fixing configuration for the cache: " + cfg.getName(),
<add> "Write-behind mode for the cache store also requires CacheConfiguration.setWriteThrough(true) " +
<add> "property. Fix configuration for the cache: " + cfg.getName());
<add> }
<ide> }
<ide>
<ide> sesLsnrs = CU.startStoreSessionListeners(cctx.kernalContext(), cfg.getCacheStoreSessionListenerFactories()); |
|
JavaScript | bsd-3-clause | 999cce246d7f29fd0358ebf43a8300d2a94b786b | 0 | sxyseo/openbiz,openbiz/openbiz-ui,sxyseo/openbiz,sxyseo/openbiz | "use strict";
define(['../objects/View'],function(view){
return view.extend({
_columnsConfig:null,
_filterConfig:null,
_paginatorConfig:null,
_actions:null,
metadata:null,
_recordActions:null,
_dataGridEL:'.data-grid',
collection:null,
elements:{},
initialize:function(){
this.template = _.template(this.template);
this.collection = new this.collection();
openbiz.View.prototype.initialize.apply(this);
return this;
},
_bindEvents:function(){
this.undelegateEvents();
var actions = this._getActions();
for (var i in actions){
var action = actions[i];
var key = action.event + " ." + action.className;
this.events[key] = action.function;
}
var recordActions = this._getRecordActions();
for (var i in recordActions){
var recordAction = recordActions[i];
if(typeof recordAction.function != 'undefined' && recordAction.function)
{
var selector = "rec-act-"+recordAction["name"].toLowerCase();
var key = recordAction.event + " ." + selector;
this.events[key] = recordAction.function;
}
}
this.delegateEvents();
return this;
},
_getLocale:function(){
this.locale.breadcrumbs = this.metadata.breadcrumbs;
this.locale.viewTitle = this.metadata.viewTitle;
this.locale.viewDescription = this.metadata.viewDescription;
},
beforeRender:function(){},
afterRender:function(){},
render:function(){
$(window).off('resize');
openbiz.ui.update($(this.el));
if(this._canDisplayView())
{
this.beforeRender();
this._getLocale();
$(this.el).html(this.template(this.locale));
this._renderDataGridConfig()._bindEvents();
this.afterRender();
}
else
{
this._renderNoPermissionView();
}
},
_renderDataGridConfig:function(){
var columns = [];
var columnConfigs = this._getColumnsConfig();
for (var i in columnConfigs){
var column = columnConfigs[i];
if(this._canDisplayColumn(column)){
var type = column['type'];
if(typeof type == 'undefined' || type == null){
type = 'text';
}
var field;
if(this.elements[type]){
field = this.elements[type].getConfig(this,column,this._getRecordActions());
}
else{
field = openbiz.elements.columns[type].getConfig(this,column,this._getRecordActions());
}
if(field != null){
columns.push(field);
}
}
}
if(this._getFilterConfig()){
var filter = new Backgrid.Extension.ServerSideFilter({
collection: this.collection,
name: "query",
placeholder: ""
});
$(this.el).find(this._dataGridEL).append(filter.render().el);
}
var grid = new Backgrid.Grid({
columns:columns,
collection: this.collection,
className: 'backgrid table table-striped table-bordered text-center',
emptyText: 'emptyText '
});
$(this.el).find(this._dataGridEL).append(grid.render().el);
if(this._getPaginatorConfig()){
var paginator = new Backgrid.Extension.Paginator({
windowSize: 10,
slideScale: 0.5,
goBackFirstOnSort: true,
collection: this.collection,
className:'pagination'
});
$(this.el).find(this._dataGridEL).append(paginator.render().el);
}
this.collection.fetch();
return this;
},
_renderNoPermissionView:function(){
//render 403 page
},
_canDisplayView:function(){
if(typeof this.metadata.permission == 'undefined' || this.metadata.permission == null){
return true;
}
return openbiz.session.me.hasPermission(this.metadata.permission);
},
_canDisplayColumn:function(column){
if(typeof column.permission != 'undefined' && column.permission)
return openbiz.session.me.hasPermission(column.permission);
return true;
},
_getRecordActions:function(){
if(! this._recordActions){
this._recordActions = this.metadata.recordActions;
}
return this._recordActions;
},
_getActions:function(){
if(! this._actions){
this._actions = this.metadata.actions;
}
return this._actions;
},
_getColumnsConfig:function(){
if(! this._columnsConfig){
this._columnsConfig = this.metadata.fields;
}
return this._columnsConfig;
},
_getFilterConfig:function(){
if(! this._filterConfig){
this._filterConfig = this.metadata.filter;
}
return this._filterConfig;
},
_getPaginatorConfig:function(){
if(! this._paginatorConfig){
this._paginatorConfig = this.metadata.paginator;
}
return this._paginatorConfig;
},
beforeDeleteRecord:function(){},
afterDeleteRecord:function(){},
deleteRecord:function(event){
event.preventDefault();
var self = this;
var recordId = $(event.currentTarget).attr('record-id');
var recordName = $(event.currentTarget).attr('record-name');
bootbox.confirm({
title: this.locale.deleteConfirmationTitle ? this.locale.deleteConfirmationTitle: this.app.locale.common.deleteConfirmationTitle,
message:_.template(this.locale.deleteConfirmationMessage ? this.locale.deleteConfirmationMessage: this.app.locale.common.deleteConfirmationMessage,{record:recordName}),
callback:function(result){
if(result){
self.beforeDeleteRecord();
self.collection.get(recordId).destroy({success:function(){
self.collection.fetch();
}});
self.afterDeleteRecord();
}
}
});
}
});
}); | ui/views/GridView.js | "use strict";
define(['../objects/View'],function(view){
return view.extend({
_columnsConfig:null,
_filterConfig:null,
_paginatorConfig:null,
_actions:null,
metadata:null,
_recordActions:null,
_dataGridEL:'.data-grid',
collection:null,
elements:{},
initialize:function(){
this.template = _.template(this.template);
this.collection = new this.collection();
openbiz.View.prototype.initialize.apply(this);
return this;
},
_bindEvents:function(){
this.undelegateEvents();
var actions = this._getActions();
for (var i in actions){
var action = actions[i];
var key = action.event + " ." + action.className;
this.events[key] = action.function;
}
var recordActions = this._getRecordActions();
for (var i in recordActions){
var recordAction = recordActions[i];
if(typeof recordAction.function != 'undefined' && recordAction.function)
{
var selector = "rec-act-"+recordAction["name"].toLowerCase();
var key = recordAction.event + " ." + selector;
this.events[key] = recordAction.function;
}
}
this.delegateEvents();
return this;
},
_getLocale:function(){
this.locale.breadcrumbs = this.metadata.breadcrumbs;
this.locale.viewTitle = this.metadata.viewTitle;
this.locale.viewDescription = this.metadata.viewDescription;
},
beforeRender:function(){},
afterRender:function(){},
render:function(){
$(window).off('resize');
openbiz.ui.update($(this.el));
if(this._canDisplayView())
{
this.beforeRender();
this._getLocale();
$(this.el).html(this.template(this.locale));
this._renderDataGridConfig()._bindEvents();
this.afterRender();
}
else
{
this._renderNoPermissionView();
}
},
_renderDataGridConfig:function(){
var columns = [];
var columnConfigs = this._getColumnsConfig();
for (var i in columnConfigs){
var column = columnConfigs[i];
if(this._canDisplayColumn(column)){
var type = column['type'];
if(typeof type == 'undefined' || type == null){
type = 'text';
}
var field = openbiz.elements.columns[type].getConfig(this,column,this._getRecordActions());
if(field != null){
columns.push(field);
}
}
}
if(this._getFilterConfig()){
var filter = new Backgrid.Extension.ServerSideFilter({
collection: this.collection,
name: "query",
placeholder: ""
});
$(this.el).find(this._dataGridEL).append(filter.render().el);
}
var grid = new Backgrid.Grid({
columns:columns,
collection: this.collection,
className: 'backgrid table table-striped table-bordered text-center',
emptyText: 'emptyText '
});
$(this.el).find(this._dataGridEL).append(grid.render().el);
if(this._getPaginatorConfig()){
var paginator = new Backgrid.Extension.Paginator({
windowSize: 10,
slideScale: 0.5,
goBackFirstOnSort: true,
collection: this.collection,
className:'pagination'
});
$(this.el).find(this._dataGridEL).append(paginator.render().el);
}
this.collection.fetch();
return this;
},
_renderNoPermissionView:function(){
//render 403 page
},
_canDisplayView:function(){
if(typeof this.metadata.permission == 'undefined' || this.metadata.permission == null){
return true;
}
return openbiz.session.me.hasPermission(this.metadata.permission);
},
_canDisplayColumn:function(column){
if(typeof column.permission != 'undefined' && column.permission)
return openbiz.session.me.hasPermission(column.permission);
return true;
},
_getRecordActions:function(){
if(! this._recordActions){
this._recordActions = this.metadata.recordActions;
}
return this._recordActions;
},
_getActions:function(){
if(! this._actions){
this._actions = this.metadata.actions;
}
return this._actions;
},
_getColumnsConfig:function(){
if(! this._columnsConfig){
this._columnsConfig = this.metadata.fields;
}
return this._columnsConfig;
},
_getFilterConfig:function(){
if(! this._filterConfig){
this._filterConfig = this.metadata.filter;
}
return this._filterConfig;
},
_getPaginatorConfig:function(){
if(! this._paginatorConfig){
this._paginatorConfig = this.metadata.paginator;
}
return this._paginatorConfig;
},
beforeDeleteRecord:function(){},
afterDeleteRecord:function(){},
deleteRecord:function(event){
event.preventDefault();
var self = this;
var recordId = $(event.currentTarget).attr('record-id');
var recordName = $(event.currentTarget).attr('record-name');
bootbox.confirm({
title: this.locale.deleteConfirmationTitle ? this.locale.deleteConfirmationTitle: this.app.locale.common.deleteConfirmationTitle,
message:_.template(this.locale.deleteConfirmationMessage ? this.locale.deleteConfirmationMessage: this.app.locale.common.deleteConfirmationMessage,{record:recordName}),
callback:function(result){
if(result){
self.beforeDeleteRecord();
self.collection.get(recordId).destroy({success:function(){
self.collection.fetch();
}});
self.afterDeleteRecord();
}
}
});
}
});
}); | add custom element into gridview
| ui/views/GridView.js | add custom element into gridview | <ide><path>i/views/GridView.js
<ide> if(typeof type == 'undefined' || type == null){
<ide> type = 'text';
<ide> }
<del> var field = openbiz.elements.columns[type].getConfig(this,column,this._getRecordActions());
<add> var field;
<add> if(this.elements[type]){
<add> field = this.elements[type].getConfig(this,column,this._getRecordActions());
<add> }
<add> else{
<add> field = openbiz.elements.columns[type].getConfig(this,column,this._getRecordActions());
<add> }
<ide> if(field != null){
<ide> columns.push(field);
<ide> } |
|
Java | apache-2.0 | bb41bd8edf8f80d83791324d8f30b3acbc4fd467 | 0 | tilioteo/hypothesis,tilioteo/hypothesis | /**
*
*/
package com.tilioteo.hypothesis.core;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import elemental.json.Json;
import elemental.json.JsonObject;
/**
* @author kamil
*
*/
@SuppressWarnings("serial")
public class Message implements Serializable {
private static final String MESSAGE_CLASS = "CLASS";
private static final String MESSAGE_UID = "UID";
private static final String MESSAGE_SENDER = "SENDER";
private static final String MESSAGE_RECEIVER = "RECEIVER";
private static final String MESSAGE_DEFINITIONS = "DEFS";
private static final String MESSAGE_DATA = "DATA";
private static final String MESSAGE_TIMESTAMP = "TIMESTAMP";
private JsonObject json;
private JsonObject defs;
private JsonObject data;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S", Locale.ENGLISH);
protected Message() {
}
public Message(String uid, Long senderId) {
json = Json.createObject();
json.put(MESSAGE_CLASS, this.getClass().getName());
json.put(MESSAGE_UID, uid);
if (senderId != null) {
json.put(MESSAGE_SENDER, senderId);
} else {
json.put(MESSAGE_SENDER, Json.createNull());
}
defs = Json.createObject();
json.put(MESSAGE_DEFINITIONS, defs);
data = Json.createObject();
json.put(MESSAGE_DATA, data);
}
protected void setPropertyDefinition(String name, Class<?> clazz) {
defs.put(name, clazz.getName());
}
public void setProperty(String name, Object value) {
if (defs.hasKey(name)) {
if (value != null) {
String className = defs.getString(name);
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
return;
}
if (!clazz.isAssignableFrom(value.getClass())) {
try {
value = clazz.cast(value);
} catch (ClassCastException e) {
return;
}
}
setData(name, clazz, value);
} else {
data.put(name, Json.createNull());
}
}
}
public void setProperty(String name, int value) {
setProperty(name, (Integer)value);
}
public void setProperty(String name, double value) {
setProperty(name, (Double)value);
}
public void setProperty(String name, boolean value) {
setProperty(name, (Boolean)value);
}
private void setData(String name, Class<?> clazz, Object value) {
if (Date.class.isAssignableFrom(clazz)) {
Date date = (Date)value;
data.put(name, dateToString(date));
} else if (Number.class.isAssignableFrom(clazz)) {
data.put(name, ((Number)value).doubleValue());
} else if (Boolean.class.isAssignableFrom(clazz)) {
data.put(name, (boolean)value);
} else if (String.class.isAssignableFrom(clazz)) {
data.put(name, (String)value);
}
}
public Object getProperty(String name) {
if (defs.hasKey(name)) {
String className = defs.getString(name);
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
return null;
}
try {
if (Date.class.isAssignableFrom(clazz)) {
return stringToDate(data.getString(name));
} else if (Double.class.isAssignableFrom(clazz)) {
return clazz.cast(data.getNumber(name));
} else if (Boolean.class.isAssignableFrom(clazz)) {
return data.getBoolean(name);
} else if (String.class.isAssignableFrom(clazz)) {
return data.getString(name);
}
} catch (Throwable e) {}
}
return null;
}
public String getUid() {
return json.getString(MESSAGE_UID);
}
public Long getSenderId() {
try {
return (long) json.getNumber(MESSAGE_SENDER);
} catch (Throwable e) {}
return null;
}
public Long getReceiverId() {
try {
Long id = (long) json.getNumber(MESSAGE_RECEIVER);
return id;
} catch (Throwable e) {}
return null;
}
public void setReceiverId(Long receiverId) {
if (receiverId != null) {
json.put(MESSAGE_RECEIVER, receiverId);
} else {
json.put(MESSAGE_RECEIVER, Json.createNull());
}
}
private Date stringToDate(String string) {
try {
Date date = dateFormat.parse(string);
return date;
} catch (ParseException e) {}
return null;
}
private String dateToString(Date date) {
if (date != null) {
return dateFormat.format(date);
}
return null;
}
public Date getTimestamp() {
try {
String str = json.getString(MESSAGE_TIMESTAMP);
return stringToDate(str);
} catch (Throwable e) {}
return null;
}
public void updateTimestamp() {
json.put(MESSAGE_TIMESTAMP, dateToString(new Date()));
}
@Override
public String toString() {
return json.toJson();
}
public static final Message fromJson(String string) {
JsonObject json = null;
try {
json = Json.parse(string);
String className = json.getString(MESSAGE_CLASS);
if (Message.class.getName().equals(className)) {
JsonObject defs = json.getObject(MESSAGE_DEFINITIONS);
JsonObject data = json.getObject(MESSAGE_DATA);
if (defs != null && data != null) {
Message message = new Message();
message.json = json;
message.defs = defs;
message.data = data;
return message;
}
}
} catch (Throwable e) {}
return null;
}
}
| src/com/tilioteo/hypothesis/core/Message.java | /**
*
*/
package com.tilioteo.hypothesis.core;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import elemental.json.Json;
import elemental.json.JsonObject;
/**
* @author kamil
*
*/
@SuppressWarnings("serial")
public class Message implements CoreObject {
private static final String MESSAGE_CLASS = "CLASS";
private static final String MESSAGE_UID = "UID";
private static final String MESSAGE_SENDER = "SENDER";
private static final String MESSAGE_RECEIVER = "RECEIVER";
private static final String MESSAGE_DEFINITIONS = "DEFS";
private static final String MESSAGE_DATA = "DATA";
private static final String MESSAGE_TIMESTAMP = "TIMESTAMP";
private JsonObject json;
private JsonObject defs;
private JsonObject data;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S", Locale.ENGLISH);
protected Message() {
}
public Message(String uid, Long senderId) {
json = Json.createObject();
json.put(MESSAGE_CLASS, this.getClass().getName());
json.put(MESSAGE_UID, uid);
if (senderId != null) {
json.put(MESSAGE_SENDER, senderId);
} else {
json.put(MESSAGE_SENDER, Json.createNull());
}
defs = Json.createObject();
json.put(MESSAGE_DEFINITIONS, defs);
data = Json.createObject();
json.put(MESSAGE_DATA, data);
}
protected void setPropertyDefinition(String name, Class<?> clazz) {
defs.put(name, clazz.getName());
}
public void setProperty(String name, Object value) {
if (defs.hasKey(name)) {
if (value != null) {
String className = defs.getString(name);
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
return;
}
if (!clazz.isAssignableFrom(value.getClass())) {
try {
value = clazz.cast(value);
} catch (ClassCastException e) {
return;
}
}
setData(name, clazz, value);
} else {
data.put(name, Json.createNull());
}
}
}
public void setProperty(String name, int value) {
setProperty(name, (Integer)value);
}
public void setProperty(String name, double value) {
setProperty(name, (Double)value);
}
public void setProperty(String name, boolean value) {
setProperty(name, (Boolean)value);
}
private void setData(String name, Class<?> clazz, Object value) {
if (Date.class.isAssignableFrom(clazz)) {
Date date = (Date)value;
data.put(name, dateToString(date));
} else if (Number.class.isAssignableFrom(clazz)) {
data.put(name, ((Number)value).doubleValue());
} else if (Boolean.class.isAssignableFrom(clazz)) {
data.put(name, (boolean)value);
} else if (String.class.isAssignableFrom(clazz)) {
data.put(name, (String)value);
}
}
public Object getProperty(String name) {
if (defs.hasKey(name)) {
String className = defs.getString(name);
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
return null;
}
try {
if (Date.class.isAssignableFrom(clazz)) {
return stringToDate(data.getString(name));
} else if (Double.class.isAssignableFrom(clazz)) {
return clazz.cast(data.getNumber(name));
} else if (Boolean.class.isAssignableFrom(clazz)) {
return data.getBoolean(name);
} else if (String.class.isAssignableFrom(clazz)) {
return data.getString(name);
}
} catch (Throwable e) {}
}
return null;
}
public String getUid() {
return json.getString(MESSAGE_UID);
}
public Long getSenderId() {
try {
return (long) json.getNumber(MESSAGE_SENDER);
} catch (Throwable e) {}
return null;
}
public Long getReceiverId() {
try {
Long id = (long) json.getNumber(MESSAGE_RECEIVER);
return id;
} catch (Throwable e) {}
return null;
}
public void setReceiverId(Long receiverId) {
if (receiverId != null) {
json.put(MESSAGE_RECEIVER, receiverId);
} else {
json.put(MESSAGE_RECEIVER, Json.createNull());
}
}
private Date stringToDate(String string) {
try {
Date date = dateFormat.parse(string);
return date;
} catch (ParseException e) {}
return null;
}
private String dateToString(Date date) {
if (date != null) {
return dateFormat.format(date);
}
return null;
}
public Date getTimestamp() {
try {
String str = json.getString(MESSAGE_TIMESTAMP);
return stringToDate(str);
} catch (Throwable e) {}
return null;
}
public void updateTimestamp() {
json.put(MESSAGE_TIMESTAMP, dateToString(new Date()));
}
@Override
public String toString() {
return json.toJson();
}
public static final Message fromJson(String string) {
JsonObject json = null;
try {
json = Json.parse(string);
String className = json.getString(MESSAGE_CLASS);
if (Message.class.getName().equals(className)) {
JsonObject defs = json.getObject(MESSAGE_DEFINITIONS);
JsonObject data = json.getObject(MESSAGE_DATA);
if (defs != null && data != null) {
Message message = new Message();
message.json = json;
message.defs = defs;
message.data = data;
return message;
}
}
} catch (Throwable e) {}
return null;
}
}
| changed interface implementation | src/com/tilioteo/hypothesis/core/Message.java | changed interface implementation | <ide><path>rc/com/tilioteo/hypothesis/core/Message.java
<ide> */
<ide> package com.tilioteo.hypothesis.core;
<ide>
<add>import java.io.Serializable;
<ide> import java.text.DateFormat;
<ide> import java.text.ParseException;
<ide> import java.text.SimpleDateFormat;
<ide> *
<ide> */
<ide> @SuppressWarnings("serial")
<del>public class Message implements CoreObject {
<add>public class Message implements Serializable {
<ide>
<ide> private static final String MESSAGE_CLASS = "CLASS";
<ide> private static final String MESSAGE_UID = "UID"; |
|
Java | apache-2.0 | 53eb8d8d4c489b1fdedd7c4352dc200c83a6461a | 0 | molindo/spring-social,Turbots/spring-social,Turbots/spring-social,molindo/spring-social,spring-projects/spring-social,codeconsole/spring-social,spring-projects/spring-social,codeconsole/spring-social | package org.springframework.social.config.support;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.core.GenericTypeResolver;
import org.springframework.social.config.xml.ApiHelper;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.support.ConnectionFactoryRegistry;
import org.springframework.social.security.provider.SocialAuthenticationService;
import org.springframework.util.ClassUtils;
public abstract class ProviderConfigurationSupport {
private final static Log logger = LogFactory.getLog(ProviderConfigurationSupport.class);
public ProviderConfigurationSupport(Class<? extends ConnectionFactory<?>> connectionFactoryClass, Class<? extends ApiHelper<?>> apiHelperClass) {
this.connectionFactoryClass = connectionFactoryClass;
this.apiHelperClass = apiHelperClass;
this.apiBindingType = GenericTypeResolver.resolveTypeArgument(connectionFactoryClass, ConnectionFactory.class);
if (isSocialSecurityAvailable()) {
this.authenticationServiceClass = getAuthenticationServiceClass();
}
}
protected Class<? extends SocialAuthenticationService<?>> getAuthenticationServiceClass() {
return null;
}
protected static boolean isSocialSecurityAvailable() {
try {
Class.forName("org.springframework.social.security.SocialAuthenticationServiceLocator");
return true;
} catch (ClassNotFoundException cnfe) {
return false;
}
}
/**
* Creates a BeanDefinition for a provider connection factory.
* Although most providers will not need to override this method, it does allow for overriding to address any provider-specific needs.
* @param appId The application's App ID
* @param appSecret The application's App Secret
* @param allAttributes All attributes available on the configuration element. Useful for provider-specific configuration.
* @return a BeanDefinition for the provider's connection factory bean.
*/
protected BeanDefinition getConnectionFactoryBeanDefinition(String appId, String appSecret, Map<String, Object> allAttributes) {
return BeanDefinitionBuilder.genericBeanDefinition(connectionFactoryClass).addConstructorArgValue(appId).addConstructorArgValue(appSecret).getBeanDefinition();
}
protected BeanDefinition getAuthenticationServiceBeanDefinition(String appId, String appSecret, Map<String, Object> allAttributes) {
return BeanDefinitionBuilder.genericBeanDefinition(authenticationServiceClass).addConstructorArgValue(appId).addConstructorArgValue(appSecret).getBeanDefinition();
}
protected BeanDefinition registerBeanDefinitions(BeanDefinitionRegistry registry, Map<String, Object> allAttributes) {
if (isSocialSecurityAvailable() && authenticationServiceClass != null) {
registerAuthenticationServiceBeanDefinitions(registry, allAttributes);
} else {
registerConnectionFactoryBeanDefinitions(registry, allAttributes);
}
return registerApiBindingBean(registry, apiHelperClass, apiBindingType,allAttributes);
}
protected abstract String getAppId(Map<String, Object> allAttributes);
protected abstract String getAppSecret(Map<String, Object> allAttributes);
private void registerConnectionFactoryBeanDefinitions(BeanDefinitionRegistry registry, Map<String, Object> allAttributes) {
BeanDefinition connectionFactoryBD = getConnectionFactoryBeanDefinition(getAppId(allAttributes), getAppSecret(allAttributes), allAttributes);
BeanDefinition connectionFactoryLocatorBD = registerConnectionFactoryLocatorBean(registry);
registerConnectionFactoryBean(connectionFactoryLocatorBD, connectionFactoryBD, connectionFactoryClass);
}
@SuppressWarnings("unchecked")
private void registerAuthenticationServiceBeanDefinitions(BeanDefinitionRegistry registry, Map<String, Object> allAttributes) {
Class<? extends org.springframework.social.security.provider.SocialAuthenticationService<?>> socialAuthenticationServiceClass = (Class<? extends org.springframework.social.security.provider.SocialAuthenticationService<?>>) this.authenticationServiceClass;
BeanDefinition authenticationServiceBD = getAuthenticationServiceBeanDefinition(getAppId(allAttributes), getAppSecret(allAttributes), allAttributes);
BeanDefinition connectionFactoryLocatorBD = registerConnectionFactoryLocatorBean(registry);
registerAuthenticationServiceBean(connectionFactoryLocatorBD, authenticationServiceBD, socialAuthenticationServiceClass);
}
private BeanDefinition registerConnectionFactoryLocatorBean(BeanDefinitionRegistry registry) {
Class<?> connectionFactoryRegistryClass = isSocialSecurityAvailable() ? org.springframework.social.security.SocialAuthenticationServiceRegistry.class : ConnectionFactoryRegistry.class;
if (!registry.containsBeanDefinition(CONNECTION_FACTORY_LOCATOR_ID)) {
if (logger.isDebugEnabled()) {
logger.debug("Registering ConnectionFactoryLocator bean (" + connectionFactoryRegistryClass.getName() + ")");
}
BeanDefinitionHolder connFactoryLocatorBeanDefHolder = new BeanDefinitionHolder(BeanDefinitionBuilder.genericBeanDefinition(connectionFactoryRegistryClass).getBeanDefinition(), CONNECTION_FACTORY_LOCATOR_ID);
BeanDefinitionHolder scopedProxy = ScopedProxyUtils.createScopedProxy(connFactoryLocatorBeanDefHolder, registry, false);
registry.registerBeanDefinition(scopedProxy.getBeanName(), scopedProxy.getBeanDefinition());
}
BeanDefinition connectionFactoryLocatorBD = registry.getBeanDefinition(ScopedProxyUtils.getTargetBeanName(CONNECTION_FACTORY_LOCATOR_ID));
return connectionFactoryLocatorBD;
}
private BeanDefinition registerConnectionFactoryBean(BeanDefinition connectionFactoryLocatorBD, BeanDefinition connectionFactoryBD, Class<? extends ConnectionFactory<?>> connectionFactoryClass) {
if (logger.isDebugEnabled()) {
logger.debug("Registering ConnectionFactory: " + connectionFactoryClass.getName());
}
PropertyValue connectionFactoriesPropertyValue = connectionFactoryLocatorBD.getPropertyValues().getPropertyValue(CONNECTION_FACTORIES);
@SuppressWarnings("unchecked")
List<BeanDefinition> connectionFactoriesList = connectionFactoriesPropertyValue != null ?
(List<BeanDefinition>) connectionFactoriesPropertyValue.getValue() : new ManagedList<BeanDefinition>();
connectionFactoriesList.add(connectionFactoryBD);
connectionFactoryLocatorBD.getPropertyValues().addPropertyValue(CONNECTION_FACTORIES, connectionFactoriesList);
return connectionFactoryBD;
}
private BeanDefinition registerAuthenticationServiceBean(BeanDefinition authenticationServiceLocatorBD, BeanDefinition authenticationServiceBD, Class<? extends org.springframework.social.security.provider.SocialAuthenticationService<?>> socialAuthenticationServiceClass) {
if (logger.isDebugEnabled()) {
logger.debug("Registering SocialAuthenticationService: " + socialAuthenticationServiceClass.getName());
}
PropertyValue authenticationServicesPropertyValue = authenticationServiceLocatorBD.getPropertyValues().getPropertyValue(AUTHENTICATION_SERVICES);
@SuppressWarnings("unchecked")
List<BeanDefinition> authenticationServicesList = authenticationServicesPropertyValue != null ?
(List<BeanDefinition>) authenticationServicesPropertyValue.getValue() : new ManagedList<BeanDefinition>();
authenticationServicesList.add(authenticationServiceBD);
authenticationServiceLocatorBD.getPropertyValues().addPropertyValue(AUTHENTICATION_SERVICES, authenticationServicesList);
return authenticationServiceBD;
}
private BeanDefinition registerApiBindingBean(BeanDefinitionRegistry registry, Class<? extends ApiHelper<?>> apiHelperClass, Class<?> apiBindingType,Map<String, Object> allAttributes) {
if (logger.isDebugEnabled()) {
logger.debug("Registering API Helper bean for " + ClassUtils.getShortName(apiBindingType));
}
String helperId = "__" + ClassUtils.getShortNameAsProperty(apiBindingType) + "ApiHelper";
// TODO: Make the bean IDs here configurable.
BeanDefinition helperBD = getApiHelperBeanDefinitionBuilder(allAttributes).getBeanDefinition();
registry.registerBeanDefinition(helperId, helperBD);
if (logger.isDebugEnabled()) {
logger.debug("Creating API Binding bean for " + ClassUtils.getShortName(apiBindingType));
}
BeanDefinition bindingBD = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
bindingBD.setFactoryBeanName(helperId);
bindingBD.setFactoryMethodName("getApi");
bindingBD.setScope("request");
BeanDefinitionHolder scopedProxyBDH = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(bindingBD, ClassUtils.getShortNameAsProperty(apiBindingType)), registry, false);
registry.registerBeanDefinition(scopedProxyBDH.getBeanName(), scopedProxyBDH.getBeanDefinition());
return scopedProxyBDH.getBeanDefinition();
}
/**
* Subclassing hook to allow api helper bean to be configured with attributes from annotation
*/
protected BeanDefinitionBuilder getApiHelperBeanDefinitionBuilder(Map<String, Object> allAttributes)
{
return BeanDefinitionBuilder.genericBeanDefinition(apiHelperClass).addConstructorArgReference("usersConnectionRepository").addConstructorArgReference("userIdSource");
}
protected final Class<? extends ConnectionFactory<?>> connectionFactoryClass;
protected final Class<? extends ApiHelper<?>> apiHelperClass;
protected final Class<?> apiBindingType;
protected Class<?> authenticationServiceClass;
private static final String CONNECTION_FACTORY_LOCATOR_ID = "connectionFactoryLocator";
private static final String CONNECTION_FACTORIES = "connectionFactories";
private static final String AUTHENTICATION_SERVICES = "authenticationServices";
}
| spring-social-config/src/main/java/org/springframework/social/config/support/ProviderConfigurationSupport.java | package org.springframework.social.config.support;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.core.GenericTypeResolver;
import org.springframework.social.config.xml.ApiHelper;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.support.ConnectionFactoryRegistry;
import org.springframework.social.security.provider.SocialAuthenticationService;
import org.springframework.util.ClassUtils;
public abstract class ProviderConfigurationSupport {
private final static Log logger = LogFactory.getLog(ProviderConfigurationSupport.class);
public ProviderConfigurationSupport(Class<? extends ConnectionFactory<?>> connectionFactoryClass, Class<? extends ApiHelper<?>> apiHelperClass) {
this.connectionFactoryClass = connectionFactoryClass;
this.apiHelperClass = apiHelperClass;
this.apiBindingType = GenericTypeResolver.resolveTypeArgument(connectionFactoryClass, ConnectionFactory.class);
if (isSocialSecurityAvailable()) {
this.authenticationServiceClass = getAuthenticationServiceClass();
}
}
protected Class<? extends SocialAuthenticationService<?>> getAuthenticationServiceClass() {
return null;
}
protected static boolean isSocialSecurityAvailable() {
try {
Class.forName("org.springframework.social.security.SocialAuthenticationServiceLocator");
return true;
} catch (ClassNotFoundException cnfe) {
return false;
}
}
/**
* Creates a BeanDefinition for a provider connection factory.
* Although most providers will not need to override this method, it does allow for overriding to address any provider-specific needs.
* @param appId The application's App ID
* @param appSecret The application's App Secret
* @param allAttributes All attributes available on the configuration element. Useful for provider-specific configuration.
* @return a BeanDefinition for the provider's connection factory bean.
*/
protected BeanDefinition getConnectionFactoryBeanDefinition(String appId, String appSecret, Map<String, Object> allAttributes) {
return BeanDefinitionBuilder.genericBeanDefinition(connectionFactoryClass).addConstructorArgValue(appId).addConstructorArgValue(appSecret).getBeanDefinition();
}
protected BeanDefinition getAuthenticationServiceBeanDefinition(String appId, String appSecret, Map<String, Object> allAttributes) {
return BeanDefinitionBuilder.genericBeanDefinition(authenticationServiceClass).addConstructorArgValue(appId).addConstructorArgValue(appSecret).getBeanDefinition();
}
protected BeanDefinition registerBeanDefinitions(BeanDefinitionRegistry registry, Map<String, Object> allAttributes) {
if (isSocialSecurityAvailable() && authenticationServiceClass != null) {
registerAuthenticationServiceBeanDefinitions(registry, allAttributes);
} else {
registerConnectionFactoryBeanDefinitions(registry, allAttributes);
}
return registerApiBindingBean(registry, apiHelperClass, apiBindingType);
}
protected abstract String getAppId(Map<String, Object> allAttributes);
protected abstract String getAppSecret(Map<String, Object> allAttributes);
private void registerConnectionFactoryBeanDefinitions(BeanDefinitionRegistry registry, Map<String, Object> allAttributes) {
BeanDefinition connectionFactoryBD = getConnectionFactoryBeanDefinition(getAppId(allAttributes), getAppSecret(allAttributes), allAttributes);
BeanDefinition connectionFactoryLocatorBD = registerConnectionFactoryLocatorBean(registry);
registerConnectionFactoryBean(connectionFactoryLocatorBD, connectionFactoryBD, connectionFactoryClass);
}
@SuppressWarnings("unchecked")
private void registerAuthenticationServiceBeanDefinitions(BeanDefinitionRegistry registry, Map<String, Object> allAttributes) {
Class<? extends org.springframework.social.security.provider.SocialAuthenticationService<?>> socialAuthenticationServiceClass = (Class<? extends org.springframework.social.security.provider.SocialAuthenticationService<?>>) this.authenticationServiceClass;
BeanDefinition authenticationServiceBD = getAuthenticationServiceBeanDefinition(getAppId(allAttributes), getAppSecret(allAttributes), allAttributes);
BeanDefinition connectionFactoryLocatorBD = registerConnectionFactoryLocatorBean(registry);
registerAuthenticationServiceBean(connectionFactoryLocatorBD, authenticationServiceBD, socialAuthenticationServiceClass);
}
private BeanDefinition registerConnectionFactoryLocatorBean(BeanDefinitionRegistry registry) {
Class<?> connectionFactoryRegistryClass = isSocialSecurityAvailable() ? org.springframework.social.security.SocialAuthenticationServiceRegistry.class : ConnectionFactoryRegistry.class;
if (!registry.containsBeanDefinition(CONNECTION_FACTORY_LOCATOR_ID)) {
if (logger.isDebugEnabled()) {
logger.debug("Registering ConnectionFactoryLocator bean (" + connectionFactoryRegistryClass.getName() + ")");
}
BeanDefinitionHolder connFactoryLocatorBeanDefHolder = new BeanDefinitionHolder(BeanDefinitionBuilder.genericBeanDefinition(connectionFactoryRegistryClass).getBeanDefinition(), CONNECTION_FACTORY_LOCATOR_ID);
BeanDefinitionHolder scopedProxy = ScopedProxyUtils.createScopedProxy(connFactoryLocatorBeanDefHolder, registry, false);
registry.registerBeanDefinition(scopedProxy.getBeanName(), scopedProxy.getBeanDefinition());
}
BeanDefinition connectionFactoryLocatorBD = registry.getBeanDefinition(ScopedProxyUtils.getTargetBeanName(CONNECTION_FACTORY_LOCATOR_ID));
return connectionFactoryLocatorBD;
}
private BeanDefinition registerConnectionFactoryBean(BeanDefinition connectionFactoryLocatorBD, BeanDefinition connectionFactoryBD, Class<? extends ConnectionFactory<?>> connectionFactoryClass) {
if (logger.isDebugEnabled()) {
logger.debug("Registering ConnectionFactory: " + connectionFactoryClass.getName());
}
PropertyValue connectionFactoriesPropertyValue = connectionFactoryLocatorBD.getPropertyValues().getPropertyValue(CONNECTION_FACTORIES);
@SuppressWarnings("unchecked")
List<BeanDefinition> connectionFactoriesList = connectionFactoriesPropertyValue != null ?
(List<BeanDefinition>) connectionFactoriesPropertyValue.getValue() : new ManagedList<BeanDefinition>();
connectionFactoriesList.add(connectionFactoryBD);
connectionFactoryLocatorBD.getPropertyValues().addPropertyValue(CONNECTION_FACTORIES, connectionFactoriesList);
return connectionFactoryBD;
}
private BeanDefinition registerAuthenticationServiceBean(BeanDefinition authenticationServiceLocatorBD, BeanDefinition authenticationServiceBD, Class<? extends org.springframework.social.security.provider.SocialAuthenticationService<?>> socialAuthenticationServiceClass) {
if (logger.isDebugEnabled()) {
logger.debug("Registering SocialAuthenticationService: " + socialAuthenticationServiceClass.getName());
}
PropertyValue authenticationServicesPropertyValue = authenticationServiceLocatorBD.getPropertyValues().getPropertyValue(AUTHENTICATION_SERVICES);
@SuppressWarnings("unchecked")
List<BeanDefinition> authenticationServicesList = authenticationServicesPropertyValue != null ?
(List<BeanDefinition>) authenticationServicesPropertyValue.getValue() : new ManagedList<BeanDefinition>();
authenticationServicesList.add(authenticationServiceBD);
authenticationServiceLocatorBD.getPropertyValues().addPropertyValue(AUTHENTICATION_SERVICES, authenticationServicesList);
return authenticationServiceBD;
}
private BeanDefinition registerApiBindingBean(BeanDefinitionRegistry registry, Class<? extends ApiHelper<?>> apiHelperClass, Class<?> apiBindingType) {
if (logger.isDebugEnabled()) {
logger.debug("Registering API Helper bean for " + ClassUtils.getShortName(apiBindingType));
}
String helperId = "__" + ClassUtils.getShortNameAsProperty(apiBindingType) + "ApiHelper";
// TODO: Make the bean IDs here configurable.
BeanDefinition helperBD = BeanDefinitionBuilder.genericBeanDefinition(apiHelperClass).addConstructorArgReference("usersConnectionRepository").addConstructorArgReference("userIdSource").getBeanDefinition();
registry.registerBeanDefinition(helperId, helperBD);
if (logger.isDebugEnabled()) {
logger.debug("Creating API Binding bean for " + ClassUtils.getShortName(apiBindingType));
}
BeanDefinition bindingBD = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
bindingBD.setFactoryBeanName(helperId);
bindingBD.setFactoryMethodName("getApi");
bindingBD.setScope("request");
BeanDefinitionHolder scopedProxyBDH = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(bindingBD, ClassUtils.getShortNameAsProperty(apiBindingType)), registry, false);
registry.registerBeanDefinition(scopedProxyBDH.getBeanName(), scopedProxyBDH.getBeanDefinition());
return scopedProxyBDH.getBeanDefinition();
}
protected final Class<? extends ConnectionFactory<?>> connectionFactoryClass;
protected final Class<? extends ApiHelper<?>> apiHelperClass;
protected final Class<?> apiBindingType;
protected Class<?> authenticationServiceClass;
private static final String CONNECTION_FACTORY_LOCATOR_ID = "connectionFactoryLocator";
private static final String CONNECTION_FACTORIES = "connectionFactories";
private static final String AUTHENTICATION_SERVICES = "authenticationServices";
}
| Add subclassing hook to ProviderConfigurationSupport to allow the constructor args of ApiHelper bean to be configurable
| spring-social-config/src/main/java/org/springframework/social/config/support/ProviderConfigurationSupport.java | Add subclassing hook to ProviderConfigurationSupport to allow the constructor args of ApiHelper bean to be configurable | <ide><path>pring-social-config/src/main/java/org/springframework/social/config/support/ProviderConfigurationSupport.java
<ide> registerConnectionFactoryBeanDefinitions(registry, allAttributes);
<ide> }
<ide>
<del> return registerApiBindingBean(registry, apiHelperClass, apiBindingType);
<add> return registerApiBindingBean(registry, apiHelperClass, apiBindingType,allAttributes);
<ide> }
<ide>
<ide> protected abstract String getAppId(Map<String, Object> allAttributes);
<ide> return authenticationServiceBD;
<ide> }
<ide>
<del> private BeanDefinition registerApiBindingBean(BeanDefinitionRegistry registry, Class<? extends ApiHelper<?>> apiHelperClass, Class<?> apiBindingType) {
<add> private BeanDefinition registerApiBindingBean(BeanDefinitionRegistry registry, Class<? extends ApiHelper<?>> apiHelperClass, Class<?> apiBindingType,Map<String, Object> allAttributes) {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Registering API Helper bean for " + ClassUtils.getShortName(apiBindingType));
<ide> }
<ide> String helperId = "__" + ClassUtils.getShortNameAsProperty(apiBindingType) + "ApiHelper";
<ide> // TODO: Make the bean IDs here configurable.
<del> BeanDefinition helperBD = BeanDefinitionBuilder.genericBeanDefinition(apiHelperClass).addConstructorArgReference("usersConnectionRepository").addConstructorArgReference("userIdSource").getBeanDefinition();
<add> BeanDefinition helperBD = getApiHelperBeanDefinitionBuilder(allAttributes).getBeanDefinition();
<ide> registry.registerBeanDefinition(helperId, helperBD);
<ide>
<ide> if (logger.isDebugEnabled()) {
<ide> BeanDefinitionHolder scopedProxyBDH = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(bindingBD, ClassUtils.getShortNameAsProperty(apiBindingType)), registry, false);
<ide> registry.registerBeanDefinition(scopedProxyBDH.getBeanName(), scopedProxyBDH.getBeanDefinition());
<ide> return scopedProxyBDH.getBeanDefinition();
<add> }
<add>
<add> /**
<add> * Subclassing hook to allow api helper bean to be configured with attributes from annotation
<add> */
<add> protected BeanDefinitionBuilder getApiHelperBeanDefinitionBuilder(Map<String, Object> allAttributes)
<add> {
<add> return BeanDefinitionBuilder.genericBeanDefinition(apiHelperClass).addConstructorArgReference("usersConnectionRepository").addConstructorArgReference("userIdSource");
<ide> }
<ide>
<ide> protected final Class<? extends ConnectionFactory<?>> connectionFactoryClass; |
|
Java | apache-2.0 | ba48632410a2d290e2bd8379bbb7350968903238 | 0 | webianks/PopupBubble | package com.webianks.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.PorterDuff;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/*
* PopupBubble library for Android
* Copyright (c) 2016 Ramankit Singh (http://github.com/webianks).
*
* 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.
*/
public class PopupBubble extends RelativeLayout {
private TextView textView;
private ImageView imageView;
private RecyclerView recyclerView;
private String TEXT = "New posts";
private String TEXT_COLOR = "#ffffff";
private String ICON_COLOR = "#ffffff";
private String BACKGROUND_COLOR = "#dd424242";
private boolean SHOW_ICON = true;
private Drawable ICON_DRAWABLE;
private PopupBubbleClickListener mListener;
private Context context;
private boolean animation = true;
//Java Inflation
public PopupBubble(Context context) {
super(context);
this.context = context;
textView = new TextView(context);
imageView = new ImageView(context);
init(context);
}
//XML Inflation
public PopupBubble(Context context, AttributeSet attrs) {
super(context, attrs);
textView = new TextView(context, attrs);
imageView = new ImageView(context);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PopupBubble, 0, 0);
try {
String text = typedArray.getString(R.styleable.PopupBubble_text);
String text_color = typedArray.getString(R.styleable.PopupBubble_textColor);
String icon_color = typedArray.getString(R.styleable.PopupBubble_iconColor);
String background_color = typedArray.getString(R.styleable.PopupBubble_backgroundColor);
Drawable icon_drawable = typedArray.getDrawable(R.styleable.PopupBubble_setIcon);
if (text!=null)
TEXT = text;
if (text_color!=null)
TEXT_COLOR = text_color;
if (icon_color!=null)
ICON_COLOR = icon_color;
if (background_color!=null)
BACKGROUND_COLOR = background_color;
if (icon_drawable!=null)
ICON_DRAWABLE = icon_drawable;
SHOW_ICON = typedArray.getBoolean(R.styleable.PopupBubble_showIcon, true);
init(context);
} finally {
typedArray.recycle();
}
}
//XMl Inflation
public PopupBubble(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
textView = new TextView(context, attrs, defStyleAttr);
imageView = new ImageView(context, attrs, defStyleAttr);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PopupBubble, 0, 0);
try {
String text = typedArray.getString(R.styleable.PopupBubble_text);
String text_color = typedArray.getString(R.styleable.PopupBubble_textColor);
String icon_color = typedArray.getString(R.styleable.PopupBubble_iconColor);
String background_color = typedArray.getString(R.styleable.PopupBubble_backgroundColor);
Drawable icon_drawable = typedArray.getDrawable(R.styleable.PopupBubble_setIcon);
if (text!=null)
TEXT = text;
if (text_color!=null)
TEXT_COLOR = text_color;
if (icon_color!=null)
ICON_COLOR = icon_color;
if (background_color!=null)
BACKGROUND_COLOR = background_color;
if (icon_drawable!=null)
ICON_DRAWABLE = icon_drawable;
SHOW_ICON = typedArray.getBoolean(R.styleable.PopupBubble_showIcon, true);
} finally {
typedArray.recycle();
}
init(context);
}
private void init(Context context) {
//prepare background of the bubble
setRoundedBackground(context);
//set the icon
if (SHOW_ICON)
addIcon();
//set the text
addText();
//move the whole layout in the center of the screen
moveToCenter();
//invalidate and redraw the views.
invalidate();
requestLayout();
}
private void moveToCenter() {
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, 0);
this.setLayoutParams(layoutParams);
}
private void addIcon() {
imageView.setId(R.id.image_view);
if (ICON_DRAWABLE != null)
imageView.setImageDrawable(ICON_DRAWABLE);
else
imageView.setImageResource(R.drawable.ic_arrow_upward_white_18dp);
imageView.setPadding(35, 20, 15, 25);
imageView.setColorFilter(Color.parseColor(ICON_COLOR), PorterDuff.Mode.SRC_ATOP);
this.addView(imageView);
}
private void addText() {
textView.setText(TEXT);
if (SHOW_ICON)
textView.setPadding(00, 20, 35, 25);
else
textView.setPadding(35, 20, 35, 25);
textView.setTextColor(Color.parseColor(TEXT_COLOR));
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.RIGHT_OF, imageView.getId());
this.addView(textView, layoutParams);
}
private void setRoundedBackground(Context context) {
RoundRectShape rect = new RoundRectShape(
new float[]{50, 50, 50, 50, 50, 50, 50, 50},
null,
null);
ShapeDrawable sd = new ShapeDrawable(rect);
sd.getPaint().setColor(Color.parseColor(BACKGROUND_COLOR));
this.setBackgroundDrawable(sd);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int maskedAction = event.getActionMasked();
if (maskedAction == MotionEvent.ACTION_DOWN) {
if (mListener != null) {
mListener.bubbleClicked(getContext());
if(animation){
if (recyclerView != null)
recyclerView.smoothScrollToPosition(0);
ShowHideAnimation showHideAnimation=new ShowHideAnimation();
showHideAnimation.animateOut(this);
}else{
this.removeAllViews();
if (recyclerView != null){
recyclerView.removeAllViews();
}
}
//deactivate();
}
}
invalidate();
return true;
}
public void setRecyclerView(android.support.v7.widget.RecyclerView recyclerView) {
this.recyclerView = recyclerView;
this.hide();
}
//onBubbleClick Setter and the interface
public void setPopupBubbleListener(PopupBubbleClickListener listener) {
mListener = listener;
}
public interface PopupBubbleClickListener {
void bubbleClicked(Context context);
}
//helper methods that can be accessed through the object
public void hide() {
this.setVisibility(View.INVISIBLE);
}
public void show() {
if(animation) {
ShowHideAnimation showHideAnimation = new ShowHideAnimation();
showHideAnimation.animateIn(this);
}else{
this.setVisibility(VISIBLE);
}
}
public void activate() {
this.show();
this.recyclerView.addOnScrollListener(new RecyclerViewListener(this));
}
//to detach the popub bubble when it has clicked or user manually scrolls to top
public void deactivate() {
this.removeAllViews();
this.recyclerView.removeOnScrollListener(null);
}
public void withAnimation(boolean animation){
this.animation = animation;
}
public void updateText(String text){
this.TEXT = text;
this.textView.setText(this.TEXT);
}
}
| popup-bubble/src/main/java/com/webianks/library/PopupBubble.java | package com.webianks.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.PorterDuff;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/*
* PopupBubble library for Android
* Copyright (c) 2016 Ramankit Singh (http://github.com/webianks).
*
* 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.
*/
public class PopupBubble extends RelativeLayout {
private TextView textView;
private ImageView imageView;
private RecyclerView recyclerView;
private String TEXT = "New posts";
private String TEXT_COLOR = "#ffffff";
private String ICON_COLOR = "#ffffff";
private String BACKGROUND_COLOR = "#dd424242";
private boolean SHOW_ICON = true;
private Drawable ICON_DRAWABLE;
private PopupBubbleClickListener mListener;
private Context context;
private boolean animation = true;
//Java Inflation
public PopupBubble(Context context) {
super(context);
this.context = context;
textView = new TextView(context);
imageView = new ImageView(context);
init(context);
}
//XML Inflation
public PopupBubble(Context context, AttributeSet attrs) {
super(context, attrs);
textView = new TextView(context, attrs);
imageView = new ImageView(context);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PopupBubble, 0, 0);
try {
String text = typedArray.getString(R.styleable.PopupBubble_text);
String text_color = typedArray.getString(R.styleable.PopupBubble_textColor);
String icon_color = typedArray.getString(R.styleable.PopupBubble_iconColor);
String background_color = typedArray.getString(R.styleable.PopupBubble_backgroundColor);
Drawable icon_drawable = typedArray.getDrawable(R.styleable.PopupBubble_setIcon);
if (text!=null)
TEXT = text;
if (text_color!=null)
TEXT_COLOR = text_color;
if (icon_color!=null)
ICON_COLOR = icon_color;
if (background_color!=null)
BACKGROUND_COLOR = background_color;
if (icon_drawable!=null)
ICON_DRAWABLE = icon_drawable;
SHOW_ICON = typedArray.getBoolean(R.styleable.PopupBubble_showIcon, true);
init(context);
} finally {
typedArray.recycle();
}
}
//XMl Inflation
public PopupBubble(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
textView = new TextView(context, attrs, defStyleAttr);
imageView = new ImageView(context, attrs, defStyleAttr);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PopupBubble, 0, 0);
try {
String text = typedArray.getString(R.styleable.PopupBubble_text);
String text_color = typedArray.getString(R.styleable.PopupBubble_textColor);
String icon_color = typedArray.getString(R.styleable.PopupBubble_iconColor);
String background_color = typedArray.getString(R.styleable.PopupBubble_backgroundColor);
Drawable icon_drawable = typedArray.getDrawable(R.styleable.PopupBubble_setIcon);
if (text!=null)
TEXT = text;
if (text_color!=null)
TEXT_COLOR = text_color;
if (icon_color!=null)
ICON_COLOR = icon_color;
if (background_color!=null)
BACKGROUND_COLOR = background_color;
if (icon_drawable!=null)
ICON_DRAWABLE = icon_drawable;
SHOW_ICON = typedArray.getBoolean(R.styleable.PopupBubble_showIcon, true);
} finally {
typedArray.recycle();
}
init(context);
}
private void init(Context context) {
//prepare background of the bubble
setRoundedBackground(context);
//set the icon
if (SHOW_ICON)
addIcon();
//set the text
addText();
//move the whole layout in the center of the screen
moveToCenter();
//invalidate and redraw the views.
invalidate();
requestLayout();
}
private void moveToCenter() {
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, 0);
this.setLayoutParams(layoutParams);
}
private void addIcon() {
imageView.setId(R.id.image_view);
if (ICON_DRAWABLE != null)
imageView.setImageDrawable(ICON_DRAWABLE);
else
imageView.setImageResource(R.drawable.ic_arrow_upward_white_18dp);
imageView.setPadding(35, 20, 15, 25);
imageView.setColorFilter(Color.parseColor(ICON_COLOR), PorterDuff.Mode.SRC_ATOP);
this.addView(imageView);
}
private void addText() {
textView.setText(TEXT);
if (SHOW_ICON)
textView.setPadding(00, 20, 35, 25);
else
textView.setPadding(35, 20, 35, 25);
textView.setTextColor(Color.parseColor(TEXT_COLOR));
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.RIGHT_OF, imageView.getId());
this.addView(textView, layoutParams);
}
private void setRoundedBackground(Context context) {
RoundRectShape rect = new RoundRectShape(
new float[]{50, 50, 50, 50, 50, 50, 50, 50},
null,
null);
ShapeDrawable sd = new ShapeDrawable(rect);
sd.getPaint().setColor(Color.parseColor(BACKGROUND_COLOR));
ShapeDrawable sds = new ShapeDrawable(rect);
sds.setShaderFactory(new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient lg = new LinearGradient(0, 0, 0, height,
new int[]{Color.parseColor("#dddddd"),
Color.parseColor("#dddddd"),
Color.parseColor("#dddddd"),
Color.parseColor("#dddddd")}, new float[]{0,
0.50f, 0.50f, 1}, Shader.TileMode.REPEAT);
return lg;
}
});
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{sds, sd});
layerDrawable.setLayerInset(0, 5, 5, 0, 0); // inset the shadow so it doesn't start right at the left/top
layerDrawable.setLayerInset(1, 0, 0, 5, 5); //
this.setBackgroundDrawable(layerDrawable);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int maskedAction = event.getActionMasked();
if (maskedAction == MotionEvent.ACTION_DOWN) {
if (mListener != null) {
mListener.bubbleClicked(getContext());
if(animation){
if (recyclerView != null)
recyclerView.smoothScrollToPosition(0);
ShowHideAnimation showHideAnimation=new ShowHideAnimation();
showHideAnimation.animateOut(this);
}else{
this.removeAllViews();
if (recyclerView != null){
recyclerView.removeAllViews();
}
}
//deactivate();
}
}
invalidate();
return true;
}
public void setRecyclerView(android.support.v7.widget.RecyclerView recyclerView) {
this.recyclerView = recyclerView;
this.hide();
}
//onBubbleClick Setter and the interface
public void setPopupBubbleListener(PopupBubbleClickListener listener) {
mListener = listener;
}
public interface PopupBubbleClickListener {
void bubbleClicked(Context context);
}
//helper methods that can be accessed through the object
public void hide() {
this.setVisibility(View.INVISIBLE);
}
public void show() {
if(animation) {
ShowHideAnimation showHideAnimation = new ShowHideAnimation();
showHideAnimation.animateIn(this);
}else{
this.setVisibility(VISIBLE);
}
}
public void activate() {
this.show();
this.recyclerView.addOnScrollListener(new RecyclerViewListener(this));
}
//to detach the popub bubble when it has clicked or user manually scrolls to top
public void deactivate() {
this.removeAllViews();
this.recyclerView.removeOnScrollListener(null);
}
public void withAnimation(boolean animation){
this.animation = animation;
}
public void updateText(String text){
this.TEXT = text;
this.textView.setText(this.TEXT);
}
}
| Remove trash useless shadow | popup-bubble/src/main/java/com/webianks/library/PopupBubble.java | Remove trash useless shadow | <ide><path>opup-bubble/src/main/java/com/webianks/library/PopupBubble.java
<ide> sd.getPaint().setColor(Color.parseColor(BACKGROUND_COLOR));
<ide>
<ide>
<del> ShapeDrawable sds = new ShapeDrawable(rect);
<del> sds.setShaderFactory(new ShapeDrawable.ShaderFactory() {
<del>
<del> @Override
<del> public Shader resize(int width, int height) {
<del> LinearGradient lg = new LinearGradient(0, 0, 0, height,
<del> new int[]{Color.parseColor("#dddddd"),
<del> Color.parseColor("#dddddd"),
<del> Color.parseColor("#dddddd"),
<del> Color.parseColor("#dddddd")}, new float[]{0,
<del> 0.50f, 0.50f, 1}, Shader.TileMode.REPEAT);
<del> return lg;
<del> }
<del> });
<del>
<del> LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{sds, sd});
<del> layerDrawable.setLayerInset(0, 5, 5, 0, 0); // inset the shadow so it doesn't start right at the left/top
<del> layerDrawable.setLayerInset(1, 0, 0, 5, 5); //
<del>
<del> this.setBackgroundDrawable(layerDrawable);
<add>
<add>
<add> this.setBackgroundDrawable(sd);
<ide>
<ide>
<ide> } |
|
Java | apache-2.0 | fdc7a79ac3ac0531b517a7ae0a8d48665a885136 | 0 | bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build.buildfarm.worker.shard;
import static build.buildfarm.worker.CASFileCache.getOrIOException;
import static com.google.common.util.concurrent.Futures.allAsList;
import build.buildfarm.common.ContentAddressableStorage;
import build.buildfarm.common.ContentAddressableStorage.Blob;
import build.buildfarm.common.DigestUtil;
import build.buildfarm.common.DigestUtil.ActionKey;
import build.buildfarm.common.DigestUtil.HashFunction;
import build.buildfarm.common.ShardBackplane;
import build.buildfarm.instance.Instance;
import build.buildfarm.instance.Instance.MatchListener;
import build.buildfarm.instance.memory.MemoryLRUContentAddressableStorage;
import build.buildfarm.instance.shard.RedisShardBackplane;
import build.buildfarm.instance.stub.ByteStreamUploader;
import build.buildfarm.instance.stub.Retrier;
import build.buildfarm.instance.stub.Retrier.Backoff;
import build.buildfarm.instance.stub.RetryException;
import build.buildfarm.instance.stub.StubInstance;
import build.buildfarm.server.InstanceNotFoundException;
import build.buildfarm.server.Instances;
import build.buildfarm.server.ContentAddressableStorageService;
import build.buildfarm.server.ByteStreamService;
import build.buildfarm.worker.CASFileCache;
import build.buildfarm.worker.Dirent;
import build.buildfarm.worker.ExecuteActionStage;
import build.buildfarm.worker.FuseCAS;
import build.buildfarm.worker.InputFetchStage;
import build.buildfarm.worker.InputStreamFactory;
import build.buildfarm.worker.MatchStage;
import build.buildfarm.worker.OutputDirectory;
import build.buildfarm.worker.OutputStreamFactory;
import build.buildfarm.worker.Pipeline;
import build.buildfarm.worker.PipelineStage;
import build.buildfarm.worker.Poller;
import build.buildfarm.worker.PutOperationStage;
import build.buildfarm.worker.ReportResultStage;
import build.buildfarm.worker.UploadManifest;
import build.buildfarm.worker.WorkerContext;
import build.buildfarm.v1test.CASInsertionPolicy;
import build.buildfarm.v1test.QueuedOperationMetadata;
import build.buildfarm.v1test.ShardWorkerConfig;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.remoteexecution.v1test.Action;
import com.google.devtools.remoteexecution.v1test.ActionResult;
import com.google.devtools.remoteexecution.v1test.Digest;
import com.google.devtools.remoteexecution.v1test.Directory;
import com.google.devtools.remoteexecution.v1test.DirectoryNode;
import com.google.devtools.remoteexecution.v1test.FileNode;
import com.google.devtools.remoteexecution.v1test.ExecuteOperationMetadata;
import com.google.devtools.remoteexecution.v1test.ExecuteOperationMetadata.Stage;
import com.google.devtools.remoteexecution.v1test.OutputFile;
import com.google.devtools.remoteexecution.v1test.Tree;
import com.google.longrunning.Operation;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.TextFormat;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.Status;
import io.grpc.Status.Code;
import io.grpc.StatusRuntimeException;
import io.grpc.netty.NegotiationType;
import io.grpc.netty.NettyChannelBuilder;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.ConfigurationException;
public class Worker implements Instances {
private static final Logger nettyLogger = Logger.getLogger("io.grpc.netty");
private final ShardWorkerConfig config;
private final ShardWorkerInstance instance;
private final Server server;
private final Path root;
private final DigestUtil digestUtil;
private final InputStreamFactory storageInputStreamFactory;
private final FuseCAS fuseCAS;
private final CASFileCache fileCache;
private final Pipeline pipeline;
private final ShardBackplane backplane;
private final Map<String, StubInstance> workerStubs;
private final Map<Path, Iterable<Path>> rootInputFiles = new ConcurrentHashMap<>();
private final Map<Path, Iterable<Digest>> rootInputDirectories = new ConcurrentHashMap<>();
private final ListeningScheduledExecutorService retryScheduler =
MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(1));
private final Set<String> activeOperations = new ConcurrentSkipListSet<>();
private static final int shutdownWaitTimeInMillis = 10000;
@Override
public Instance getFromBlob(String blobName) throws InstanceNotFoundException { return instance; }
@Override
public Instance getFromUploadBlob(String uploadBlobName) throws InstanceNotFoundException { return instance; }
@Override
public Instance getFromOperationsCollectionName(String operationsCollectionName) throws InstanceNotFoundException { return instance; }
@Override
public Instance getFromOperationName(String operationName) throws InstanceNotFoundException { return instance; }
@Override
public Instance getFromOperationStream(String operationStream) throws InstanceNotFoundException { return instance; }
@Override
public Instance get(String name) throws InstanceNotFoundException { return instance; }
public Worker(ShardWorkerConfig config) throws ConfigurationException {
this(ServerBuilder.forPort(config.getPort()), config);
}
private static Path getValidRoot(ShardWorkerConfig config) throws ConfigurationException {
String rootValue = config.getRoot();
if (Strings.isNullOrEmpty(rootValue)) {
throw new ConfigurationException("root value in config missing");
}
Path root = Paths.get(rootValue);
if (!Files.isDirectory(root)) {
throw new ConfigurationException("root [" + root.toString() + "] is not directory");
}
return root;
}
private static Path getValidCasCacheDirectory(ShardWorkerConfig config, Path root) throws ConfigurationException {
String casCacheValue = config.getCasCacheDirectory();
if (Strings.isNullOrEmpty(casCacheValue)) {
throw new ConfigurationException("Cas cache directory value in config missing");
}
return root.resolve(casCacheValue);
}
private static HashFunction getValidHashFunction(ShardWorkerConfig config) throws ConfigurationException {
try {
return HashFunction.get(config.getHashFunction());
} catch (IllegalArgumentException e) {
throw new ConfigurationException("hash_function value unrecognized");
}
}
private static ManagedChannel createChannel(String target) {
NettyChannelBuilder builder =
NettyChannelBuilder.forTarget(target)
.negotiationType(NegotiationType.PLAINTEXT);
return builder.build();
}
private static Retrier createStubRetrier() {
return new Retrier(
Backoff.exponential(
java.time.Duration.ofMillis(/*options.experimentalRemoteRetryStartDelayMillis=*/ 100),
java.time.Duration.ofMillis(/*options.experimentalRemoteRetryMaxDelayMillis=*/ 5000),
/*options.experimentalRemoteRetryMultiplier=*/ 2,
/*options.experimentalRemoteRetryJitter=*/ 0.1,
/*options.experimentalRemoteRetryMaxAttempts=*/ 5),
Retrier.DEFAULT_IS_RETRIABLE);
}
private ByteStreamUploader createStubUploader(Channel channel) {
return new ByteStreamUploader("", channel, null, 300, createStubRetrier(), retryScheduler);
}
private StubInstance workerStub(String worker) {
StubInstance instance = workerStubs.get(worker);
if (instance == null) {
ManagedChannel channel = createChannel(worker);
instance = new StubInstance(
"", digestUtil, channel,
10 /* FIXME CONFIG */, TimeUnit.SECONDS,
createStubRetrier(),
createStubUploader(channel));
workerStubs.put(worker, instance);
}
return instance;
}
/*
private void removeMalfunctioningWorkerClient(String worker) {
StubInstance instance = workerStubs.remove(worker);
if (instance != null) {
ManagedChannel channel = instance.getChannel();
channel.shutdownNow();
try {
channel.awaitTermination(0, TimeUnit.SECONDS);
} catch (InterruptedException intEx) {
// impossible, 0 timeout
Thread.currentThread().interrupt();
}
}
}
*/
private void fetchInputs(
Path execDir,
Digest directoryDigest,
Map<Digest, Directory> directoriesIndex,
OutputDirectory outputDirectory,
ImmutableList.Builder<Path> inputFiles,
ImmutableList.Builder<Digest> inputDirectories)
throws IOException, InterruptedException {
Directory directory = directoriesIndex.get(directoryDigest);
if (directory == null) {
throw new IOException("Directory " + DigestUtil.toString(directoryDigest) + " is not in directories index");
}
for (FileNode fileNode : directory.getFilesList()) {
Path execPath = execDir.resolve(fileNode.getName());
/*
System.out.println(String.format("Worker::fetchInputs(%s) linking %s (%s)",
DigestUtil.toString(directoryDigest),
fileNode.getIsExecutable() ? ("*" + fileNode.getName() + "*") : fileNode.getName(),
DigestUtil.toString(fileNode.getDigest())));
*/
Path fileCacheKey = fileCache.put(fileNode.getDigest(), fileNode.getIsExecutable(), /* containingDirectory=*/ null);
inputFiles.add(fileCacheKey);
/*
System.out.println(String.format("Worker::fetchInputs(%s) linking %s complete (%s)",
DigestUtil.toString(directoryDigest),
fileNode.getIsExecutable() ? ("*" + fileNode.getName() + "*") : fileNode.getName(),
DigestUtil.toString(fileNode.getDigest())));
*/
Files.createLink(execPath, fileCacheKey);
}
for (DirectoryNode directoryNode : directory.getDirectoriesList()) {
Digest digest = directoryNode.getDigest();
String name = directoryNode.getName();
OutputDirectory childOutputDirectory = outputDirectory != null
? outputDirectory.getChild(name) : null;
Path dirPath = execDir.resolve(name);
if (childOutputDirectory != null || !config.getLinkInputDirectories()) {
Files.createDirectories(dirPath);
/*
System.out.println(String.format("Worker::fetchInputs(%s) subdirectory %s (%s)",
DigestUtil.toString(directoryDigest),
name,
DigestUtil.toString(digest)));
*/
fetchInputs(dirPath, digest, directoriesIndex, childOutputDirectory, inputFiles, inputDirectories);
/*
System.out.println(String.format("Worker::fetchInputs(%s) subdirectory complete %s (%s)",
DigestUtil.toString(directoryDigest),
name,
DigestUtil.toString(digest)));
*/
} else {
/*
System.out.println(String.format("Worker::fetchInputs(%s) linkDirectory %s (%s)",
DigestUtil.toString(directoryDigest),
name,
DigestUtil.toString(digest)));
*/
linkDirectory(dirPath, digest, directoriesIndex);
inputDirectories.add(digest);
/*
System.out.println(String.format("Worker::fetchInputs(%s) linkDirectory complete %s (%s)",
DigestUtil.toString(directoryDigest),
name,
DigestUtil.toString(digest)));
*/
}
}
}
private void linkDirectory(
Path execPath,
Digest digest,
Map<Digest, Directory> directoriesIndex) throws IOException, InterruptedException {
Path cachePath = fileCache.putDirectory(digest, directoriesIndex);
Files.createSymbolicLink(execPath, cachePath);
}
private Operation stripOperation(Operation operation) {
return instance.stripOperation(operation);
}
private Operation stripQueuedOperation(Operation operation) {
return instance.stripQueuedOperation(operation);
}
private static int inlineOrDigest(
ByteString content,
CASInsertionPolicy policy,
ImmutableList.Builder<ByteString> contents,
int inlineContentBytes,
int inlineContentLimit,
Runnable setInline,
Consumer<ByteString> setDigest) {
boolean withinLimit = inlineContentBytes + content.size() <= inlineContentLimit;
if (withinLimit) {
setInline.run();
inlineContentBytes += content.size();
}
if (policy.equals(CASInsertionPolicy.ALWAYS_INSERT) ||
(!withinLimit && policy.equals(CASInsertionPolicy.INSERT_ABOVE_LIMIT))) {
contents.add(content);
setDigest.accept(content);
}
return inlineContentBytes;
}
public Worker(ServerBuilder<?> serverBuilder, ShardWorkerConfig config) throws ConfigurationException {
this.config = config;
workerStubs = new HashMap<>();
root = getValidRoot(config);
digestUtil = new DigestUtil(getValidHashFunction(config));
ShardWorkerConfig.BackplaneCase backplaneCase = config.getBackplaneCase();
switch (backplaneCase) {
default:
case BACKPLANE_NOT_SET:
throw new IllegalArgumentException("Shard Backplane not set in config");
case REDIS_SHARD_BACKPLANE_CONFIG:
backplane = new RedisShardBackplane(config.getRedisShardBackplaneConfig(), this::stripOperation, this::stripQueuedOperation, (o) -> false);
break;
}
InputStreamFactory remoteInputStreamFactory = new InputStreamFactory() {
private Random rand = new Random();
private InputStream fetchBlobFromRemoteWorker(Digest blobDigest, Deque<String> workers, long offset) throws IOException, InterruptedException {
String worker = workers.removeFirst();
try {
for (;;) {
Instance instance = workerStub(worker);
InputStream input = instance.newStreamInput(instance.getBlobName(blobDigest), offset);
// ensure that if the blob cannot be fetched, that we throw here
input.available();
if (Thread.interrupted()) {
throw new InterruptedException();
}
return input;
}
} catch (RetryException e) {
Status st = Status.fromThrowable(e);
if (st.getCode().equals(Code.UNAVAILABLE)) {
backplane.removeBlobLocation(blobDigest, worker);
// for now, leave this up to schedulers
// removeMalfunctioningWorker(worker, e, "getBlob(" + DigestUtil.toString(blobDigest) + ")");
} else if (st.getCode().equals(Code.NOT_FOUND)) {
// ignore this, the worker will update the backplane eventually
} else if (Retrier.DEFAULT_IS_RETRIABLE.test(st)) {
// why not, always
workers.addLast(worker);
} else {
throw e;
}
throw new NoSuchFileException(DigestUtil.toString(blobDigest));
}
}
private List<String> correctMissingBlob(Digest digest) throws IOException {
ImmutableList.Builder<String> foundWorkers = new ImmutableList.Builder<>();
Deque<String> workers;
try {
List<String> workersList = new ArrayList<>(
Sets.difference(backplane.getWorkerSet(), ImmutableSet.<String>of(config.getPublicName())));
Collections.shuffle(workersList, rand);
workers = new ArrayDeque(workersList);
} catch (IOException e) {
throw Status.fromThrowable(e).asRuntimeException();
}
for (String worker : workers) {
try {
Iterable<Digest> resultDigests = null;
while (resultDigests == null) {
try {
resultDigests = createStubRetrier().execute(() -> workerStub(worker).findMissingBlobs(ImmutableList.<Digest>of(digest)));
if (Iterables.size(resultDigests) == 0) {
System.out.println("Worker::RemoteInputStreamFactory::correctMissingBlob(" + DigestUtil.toString(digest) + "): Adding back to " + worker);
backplane.addBlobLocation(digest, worker);
foundWorkers.add(worker);
}
} catch (RetryException e) {
if (e.getCause() instanceof StatusRuntimeException) {
StatusRuntimeException sre = (StatusRuntimeException) e.getCause();
throw sre;
}
throw e;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Status.CANCELLED.asRuntimeException();
} catch (IOException e) {
throw Status.INTERNAL.withDescription(e.getMessage()).asRuntimeException();
} catch (StatusRuntimeException e) {
if (e.getStatus().getCode().equals(Status.UNAVAILABLE.getCode())) {
// removeMalfunctioningWorker(worker, e, "findMissingBlobs(...)");
} else {
e.printStackTrace();
}
}
}
return foundWorkers.build();
}
@Override
public InputStream newInput(Digest blobDigest, long offset) throws IOException, InterruptedException {
Set<String> workerSet = new HashSet<>(Sets.intersection(
backplane.getBlobLocationSet(blobDigest),
backplane.getWorkerSet()));
if (workerSet.remove(config.getPublicName())) {
backplane.removeBlobLocation(blobDigest, config.getPublicName());
}
List<String> workersList = new ArrayList<>(workerSet);
Collections.shuffle(workersList, rand);
Deque<String> workers = new ArrayDeque(workersList);
boolean printFinal = false;
boolean triedCheck = false;
for (;;) {
if (workers.isEmpty()) {
if (triedCheck) {
// maybe just return null here
throw new IOException("worker not found for blob " + DigestUtil.toString(blobDigest));
}
workersList.clear();
workersList.addAll(correctMissingBlob(blobDigest));
Collections.shuffle(workersList, rand);
workers = new ArrayDeque(workersList);
triedCheck = true;
} else {
int sizeBeforeFetch = workers.size();
InputStream input = fetchBlobFromRemoteWorker(blobDigest, workers, offset);
if (sizeBeforeFetch == workers.size()) {
printFinal = true;
System.out.println("Pushed worker to end of request list: " + workers.peekLast() + " for " + DigestUtil.toString(blobDigest));
}
if (printFinal) {
System.out.println("fetch with retried loop succeeded for " + DigestUtil.toString(blobDigest));
}
return input;
}
}
}
};
final ContentAddressableStorage storage;
final OutputStreamFactory outputStreamFactory;
if (config.getUseFuseCas()) {
fileCache = null;
storage = new MemoryLRUContentAddressableStorage(config.getCasMaxSizeBytes(), this::onStoragePut);
storageInputStreamFactory = (digest, offset) -> storage.get(digest).getData().substring((int) offset).newInput();
outputStreamFactory = (digest) -> { throw new UnsupportedOperationException(); };
InputStreamFactory localPopulatingInputStreamFactory = new InputStreamFactory() {
@Override
public InputStream newInput(Digest blobDigest, long offset) throws IOException, InterruptedException {
ByteString content = ByteString.readFrom(remoteInputStreamFactory.newInput(blobDigest, offset));
if (offset == 0) {
// extra computations
Blob blob = new Blob(content, digestUtil);
// here's hoping that our digest matches...
storage.put(blob);
}
return content.newInput();
}
};
fuseCAS = new FuseCAS(root, new EmptyInputStreamFactory(new FailoverInputStreamFactory(storageInputStreamFactory, localPopulatingInputStreamFactory)));
} else {
fuseCAS = null;
InputStreamFactory selfInputStreamChain = new InputStreamFactory() {
@Override
public InputStream newInput(Digest blobDigest, long offset) throws IOException, InterruptedException {
// oh the complication... using storage here requires us to be instantiated in this context
return new EmptyInputStreamFactory(new FailoverInputStreamFactory(storageInputStreamFactory, remoteInputStreamFactory))
.newInput(blobDigest, offset);
}
};
Path casCacheDirectory = getValidCasCacheDirectory(config, root);
fileCache = new CASFileCache(
selfInputStreamChain,
root.resolve(casCacheDirectory),
config.getCasCacheMaxSizeBytes(),
digestUtil,
this::onStoragePut,
this::onStorageExpire);
storage = fileCache;
storageInputStreamFactory = fileCache;
outputStreamFactory = fileCache;
}
instance = new ShardWorkerInstance(
config.getPublicName(),
digestUtil,
backplane,
storage,
storageInputStreamFactory,
outputStreamFactory,
config.getShardWorkerInstanceConfig());
server = serverBuilder
.addService(new ContentAddressableStorageService(this))
.addService(new ByteStreamService(this))
.build();
// FIXME factor into pipeline factory/constructor
WorkerContext context = new WorkerContext() {
@Override
public String getName() {
return config.getPublicName();
}
@Override
public Poller createPoller(String name, String operationName, Stage stage) {
return createPoller(name, operationName, stage, () -> {});
}
@Override
public Poller createPoller(String name, String operationName, Stage stage, Runnable onFailure) {
Poller poller = new Poller(
config.getOperationPollPeriod(),
() -> {
boolean success = false;
try {
success = backplane.pollOperation(operationName, stage, System.currentTimeMillis() + 30 * 1000);
} catch (IOException e) {
e.printStackTrace();
}
logInfo(name + ": poller: Completed Poll for " + operationName + ": " + (success ? "OK" : "Failed"));
if (!success) {
onFailure.run();
}
return success;
});
new Thread(poller).start();
return poller;
}
@Override
public DigestUtil getDigestUtil() {
return instance.getDigestUtil();
}
@Override
public void match(MatchListener listener) throws InterruptedException {
instance.match(config.getPlatform(), new MatchListener() {
@Override
public void onWaitStart() {
listener.onWaitStart();
}
@Override
public void onWaitEnd() {
listener.onWaitEnd();
}
@Override
public boolean onOperationName(String operationName) {
if (activeOperations.contains(operationName)) {
System.err.println("WorkerContext::match: WARNING matched duplicate operation " + operationName);
return listener.onOperation(null);
}
activeOperations.add(operationName);
boolean success = listener.onOperationName(operationName);
if (!success) {
try {
// fast path to requeue, implementation specific
backplane.pollOperation(operationName, ExecuteOperationMetadata.Stage.QUEUED, 0);
} catch (IOException e) {
System.err.println("Failure while trying to fast requeue " + operationName);
e.printStackTrace();
}
}
return success;
}
@Override
public boolean onOperation(Operation operation) {
// could not fetch
if (operation.getDone()) {
activeOperations.remove(operation.getName());
listener.onOperation(null);
try {
backplane.pollOperation(operation.getName(), ExecuteOperationMetadata.Stage.QUEUED, 0);
} catch (IOException e) {
System.err.println("Failure while trying to fast requeue " + operation.getName());
e.printStackTrace();
}
return false;
}
boolean success = listener.onOperation(operation);
if (!success) {
try {
requeue(operation);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
return success;
}
});
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
private ExecuteOperationMetadata expectExecuteOperationMetadata(Operation operation) {
Any metadata = operation.getMetadata();
if (metadata == null) {
return null;
}
if (metadata.is(QueuedOperationMetadata.class)) {
try {
return operation.getMetadata().unpack(QueuedOperationMetadata.class).getExecuteOperationMetadata();
} catch(InvalidProtocolBufferException e) {
e.printStackTrace();
return null;
}
}
if (metadata.is(ExecuteOperationMetadata.class)) {
try {
return operation.getMetadata().unpack(ExecuteOperationMetadata.class);
} catch(InvalidProtocolBufferException e) {
e.printStackTrace();
return null;
}
}
return null;
}
@Override
public void requeue(Operation operation) throws InterruptedException {
deactivate(operation);
try {
backplane.pollOperation(operation.getName(), ExecuteOperationMetadata.Stage.QUEUED, 0);
} catch (IOException e) {
// ignore, at least dispatcher will pick us up in 30s
e.printStackTrace();
}
}
@Override
public void deactivate(Operation operation) {
activeOperations.remove(operation.getName());
}
@Override
public void logInfo(String msg) {
System.out.println(msg);
}
@Override
public int getInlineContentLimit() {
return config.getInlineContentLimit();
}
@Override
public CASInsertionPolicy getFileCasPolicy() {
return CASInsertionPolicy.ALWAYS_INSERT;
}
@Override
public CASInsertionPolicy getStdoutCasPolicy() {
return CASInsertionPolicy.ALWAYS_INSERT;
}
@Override
public CASInsertionPolicy getStderrCasPolicy() {
return CASInsertionPolicy.ALWAYS_INSERT;
}
@Override
public int getExecuteStageWidth() {
return config.getExecuteStageWidth();
}
@Override
public int getTreePageSize() {
return 0;
}
@Override
public boolean hasDefaultActionTimeout() {
return false;
}
@Override
public boolean hasMaximumActionTimeout() {
return false;
}
@Override
public boolean getStreamStdout() {
return true;
}
@Override
public boolean getStreamStderr() {
return true;
}
@Override
public Duration getDefaultActionTimeout() {
return null;
}
@Override
public Duration getMaximumActionTimeout() {
return null;
}
private int updateActionResultStdOutputs(
ActionResult.Builder resultBuilder,
ImmutableList.Builder<ByteString> contents,
int inlineContentBytes) {
ByteString stdoutRaw = resultBuilder.getStdoutRaw();
if (stdoutRaw.size() > 0) {
// reset to allow policy to determine inlining
resultBuilder.setStdoutRaw(ByteString.EMPTY);
inlineContentBytes = inlineOrDigest(
stdoutRaw,
getStdoutCasPolicy(),
contents,
inlineContentBytes,
getInlineContentLimit(),
() -> resultBuilder.setStdoutRaw(stdoutRaw),
(content) -> resultBuilder.setStdoutDigest(getDigestUtil().compute(content)));
}
ByteString stderrRaw = resultBuilder.getStderrRaw();
if (stderrRaw.size() > 0) {
// reset to allow policy to determine inlining
resultBuilder.setStderrRaw(ByteString.EMPTY);
inlineContentBytes = inlineOrDigest(
stderrRaw,
getStderrCasPolicy(),
contents,
inlineContentBytes,
getInlineContentLimit(),
() -> resultBuilder.setStderrRaw(stdoutRaw),
(content) -> resultBuilder.setStderrDigest(getDigestUtil().compute(content)));
}
return inlineContentBytes;
}
@Override
public void uploadOutputs(
ActionResult.Builder resultBuilder,
Path actionRoot,
Iterable<String> outputFiles,
Iterable<String> outputDirs)
throws IOException, InterruptedException {
int inlineContentBytes = 0;
ImmutableList.Builder<ByteString> contents = new ImmutableList.Builder<>();
for (String outputFile : outputFiles) {
Path outputPath = actionRoot.resolve(outputFile);
if (!Files.exists(outputPath)) {
logInfo("ReportResultStage: " + outputPath + " does not exist...");
continue;
}
// FIXME put the output into the fileCache
// FIXME this needs to be streamed to the server, not read to completion, but
// this is a constraint of not knowing the hash, however, if we put the entry
// into the cache, we can likely do so, stream the output up, and be done
//
// will run into issues if we end up blocking on the cache insertion, might
// want to decrement input references *before* this to ensure that we cannot
// cause an internal deadlock
ByteString content;
try (InputStream inputStream = Files.newInputStream(outputPath)) {
content = ByteString.readFrom(inputStream);
} catch (IOException e) {
continue;
}
OutputFile.Builder outputFileBuilder = resultBuilder.addOutputFilesBuilder()
.setPath(outputFile)
.setIsExecutable(Files.isExecutable(outputPath));
inlineContentBytes = inlineOrDigest(
content,
getFileCasPolicy(),
contents,
inlineContentBytes,
getInlineContentLimit(),
() -> outputFileBuilder.setContent(content),
(fileContent) -> outputFileBuilder.setDigest(getDigestUtil().compute(fileContent)));
}
for (String outputDir : outputDirs) {
Path outputDirPath = actionRoot.resolve(outputDir);
if (!Files.exists(outputDirPath)) {
logInfo("ReportResultStage: " + outputDir + " does not exist...");
continue;
}
Tree.Builder treeBuilder = Tree.newBuilder();
Directory.Builder outputRoot = treeBuilder.getRootBuilder();
Files.walkFileTree(outputDirPath, new SimpleFileVisitor<Path>() {
Directory.Builder currentDirectory = null;
Stack<Directory.Builder> path = new Stack<>();
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
ByteString content;
try (InputStream inputStream = Files.newInputStream(file)) {
content = ByteString.readFrom(inputStream);
} catch (IOException e) {
e.printStackTrace();
return FileVisitResult.CONTINUE;
}
// should we cast to PosixFilePermissions and do gymnastics there for executable?
// TODO symlink per revision proposal
contents.add(content);
FileNode.Builder fileNodeBuilder = currentDirectory.addFilesBuilder()
.setName(file.getFileName().toString())
.setDigest(getDigestUtil().compute(content))
.setIsExecutable(Files.isExecutable(file));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
path.push(currentDirectory);
if (dir.equals(outputDirPath)) {
currentDirectory = outputRoot;
} else {
currentDirectory = treeBuilder.addChildrenBuilder();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Directory.Builder parentDirectory = path.pop();
if (parentDirectory != null) {
parentDirectory.addDirectoriesBuilder()
.setName(dir.getFileName().toString())
.setDigest(getDigestUtil().compute(currentDirectory.build()));
}
currentDirectory = parentDirectory;
return FileVisitResult.CONTINUE;
}
});
Tree tree = treeBuilder.build();
ByteString treeBlob = tree.toByteString();
contents.add(treeBlob);
Digest treeDigest = getDigestUtil().compute(treeBlob);
resultBuilder.addOutputDirectoriesBuilder()
.setPath(outputDir)
.setTreeDigest(treeDigest);
}
/* put together our outputs and update the result */
updateActionResultStdOutputs(resultBuilder, contents, inlineContentBytes);
List<ByteString> blobs = contents.build();
if (!blobs.isEmpty()) {
instance.putAllBlobs(blobs);
}
}
@Override
public boolean putOperation(Operation operation, Action action) throws IOException, InterruptedException {
boolean success = instance.putOperation(operation);
if (success && operation.getDone()) {
backplane.removeTree(action.getInputRootDigest());
}
return success;
}
@Override
public void createActionRoot(Path actionRoot, Map<Digest, Directory> directoriesIndex, Action action) throws IOException, InterruptedException {
if (config.getUseFuseCas()) {
String topdir = root.relativize(actionRoot).toString();
fuseCAS.createInputRoot(topdir, action.getInputRootDigest());
} else {
OutputDirectory outputDirectory = OutputDirectory.parse(
action.getOutputFilesList(),
action.getOutputDirectoriesList());
if (Files.exists(actionRoot)) {
getOrIOException(fileCache.removeDirectoryAsync(actionRoot));
}
Files.createDirectories(actionRoot);
ImmutableList.Builder<Path> inputFiles = new ImmutableList.Builder<>();
ImmutableList.Builder<Digest> inputDirectories = new ImmutableList.Builder<>();
System.out.println("WorkerContext::createActionRoot(" + DigestUtil.toString(action.getInputRootDigest()) + ") calling fetchInputs");
try {
fetchInputs(
actionRoot,
action.getInputRootDigest(),
directoriesIndex,
outputDirectory,
inputFiles,
inputDirectories);
} catch (IOException e) {
fileCache.decrementReferences(inputFiles.build(), inputDirectories.build());
throw e;
}
rootInputFiles.put(actionRoot, inputFiles.build());
rootInputDirectories.put(actionRoot, inputDirectories.build());
System.out.println("WorkerContext::createActionRoot(" + DigestUtil.toString(action.getInputRootDigest()) + ") stamping output directories");
try {
outputDirectory.stamp(actionRoot);
} catch (IOException e) {
destroyActionRoot(actionRoot);
throw e;
}
}
}
// might want to split for removeDirectory and decrement references to avoid removing for streamed output
@Override
public void destroyActionRoot(Path actionRoot) throws IOException, InterruptedException {
if (config.getUseFuseCas()) {
String topdir = root.relativize(actionRoot).toString();
fuseCAS.destroyInputRoot(topdir);
} else {
Iterable<Path> inputFiles = rootInputFiles.remove(actionRoot);
Iterable<Digest> inputDirectories = rootInputDirectories.remove(actionRoot);
if (inputFiles != null || inputDirectories != null) {
fileCache.decrementReferences(
inputFiles == null ? ImmutableList.<Path>of() : inputFiles,
inputDirectories == null ? ImmutableList.<Digest>of() : inputDirectories);
}
if (Files.exists(actionRoot)) {
getOrIOException(fileCache.removeDirectoryAsync(actionRoot));
}
}
}
public Path getRoot() {
return root;
}
@Override
public void putActionResult(ActionKey actionKey, ActionResult actionResult) {
instance.putActionResult(actionKey, actionResult);
}
@Override
public OutputStream getStreamOutput(String name) {
throw new UnsupportedOperationException();
}
};
PipelineStage completeStage = new PutOperationStage(context::deactivate);
PipelineStage errorStage = completeStage; /* new ErrorStage(); */
PipelineStage reportResultStage = new ReportResultStage(context, completeStage, errorStage);
PipelineStage executeActionStage = new ExecuteActionStage(context, reportResultStage, errorStage);
reportResultStage.setInput(executeActionStage);
PipelineStage inputFetchStage = new InputFetchStage(context, executeActionStage, new PutOperationStage(context::requeue));
executeActionStage.setInput(inputFetchStage);
PipelineStage matchStage = new MatchStage(context, inputFetchStage, errorStage);
inputFetchStage.setInput(matchStage);
pipeline = new Pipeline();
// pipeline.add(errorStage, 0);
pipeline.add(matchStage, 1);
pipeline.add(inputFetchStage, 2);
pipeline.add(executeActionStage, 3);
pipeline.add(reportResultStage, 4);
}
public void stop() {
System.err.println("Closing the pipeline");
try {
pipeline.close();
} catch (InterruptedException e) {
backplane.stop(); // the pool must be signaled...
Thread.currentThread().interrupt();
return;
}
if (config.getUseFuseCas()) {
System.err.println("Umounting Fuse");
fuseCAS.stop();
} else {
fileCache.stop();
}
if (server != null) {
System.err.println("Shutting down the server");
server.shutdown();
try {
server.awaitTermination(shutdownWaitTimeInMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
server.shutdownNow();
}
}
backplane.stop();
}
private void onStoragePut(Digest digest) {
try {
backplane.addBlobLocation(digest, config.getPublicName());
} catch (IOException e) {
throw Status.fromThrowable(e).asRuntimeException();
}
}
private void onStorageExpire(Iterable<Digest> digests) {
try {
backplane.removeBlobsLocation(digests, config.getPublicName());
} catch (IOException e) {
throw Status.fromThrowable(e).asRuntimeException();
}
}
private void blockUntilShutdown() throws InterruptedException {
// should really be waiting for both of these things...
/*
if (server != null) {
server.awaitTermination();
}
*/
pipeline.join();
if (server != null) {
server.shutdown();
try {
server.awaitTermination(shutdownWaitTimeInMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
server.shutdownNow();
}
}
if (config.getUseFuseCas()) {
fuseCAS.stop();
} else {
fileCache.stop();
}
backplane.stop();
}
private void removeWorker(String name) {
try {
backplane.removeWorker(name);
} catch (IOException e) {
Status status = Status.fromThrowable(e);
if (status.getCode() != Code.UNAVAILABLE && status.getCode() != Code.DEADLINE_EXCEEDED) {
throw status.asRuntimeException();
}
System.out.println("backplane was unavailable or overloaded, deferring removeWorker");
}
}
private void addBlobsLocation(List<Digest> digests, String name) {
for (;;) {
try {
backplane.addBlobsLocation(digests, name);
return;
} catch (IOException e) {
Status status = Status.fromThrowable(e);
if (status.getCode() != Code.UNAVAILABLE && status.getCode() != Code.DEADLINE_EXCEEDED) {
throw status.asRuntimeException();
}
}
}
}
private void addWorker(String name) {
for (;;) {
try {
backplane.addWorker(name);
return;
} catch (IOException e) {
Status status = Status.fromThrowable(e);
if (status.getCode() != Code.UNAVAILABLE && status.getCode() != Code.DEADLINE_EXCEEDED) {
throw status.asRuntimeException();
}
}
}
}
@Override
public void start() {
try {
backplane.start();
removeWorker(config.getPublicName());
if (!config.getUseFuseCas()) {
List<Dirent> dirents = null;
try {
dirents = UploadManifest.readdir(root, /* followSymlinks= */ false);
} catch (IOException e) {
e.printStackTrace();
}
ImmutableList.Builder<ListenableFuture<Void>> removeDirectoryFutures = new ImmutableList.Builder<>();
// only valid path under root is cache
for (Dirent dirent : dirents) {
String name = dirent.getName();
Path child = root.resolve(name);
if (!child.equals(fileCache.getRoot())) {
removeDirectoryFutures.add(fileCache.removeDirectoryAsync(root.resolve(name)));
}
}
ImmutableList.Builder<Digest> blobDigests = new ImmutableList.Builder<>();
fileCache.start(blobDigests::add);
addBlobsLocation(blobDigests.build(), config.getPublicName());
getOrIOException(allAsList(removeDirectoryFutures.build()));
}
server.start();
addWorker(config.getPublicName());
} catch (Exception e) {
stop();
e.printStackTrace();
return;
}
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("*** shutting down gRPC server since JVM is shutting down");
Worker.this.stop();
System.err.println("*** server shut down");
}
});
pipeline.start();
}
private static ShardWorkerConfig toShardWorkerConfig(Readable input, WorkerOptions options) throws IOException {
ShardWorkerConfig.Builder builder = ShardWorkerConfig.newBuilder();
TextFormat.merge(input, builder);
if (!Strings.isNullOrEmpty(options.root)) {
builder.setRoot(options.root);
}
if (!Strings.isNullOrEmpty(options.casCacheDirectory)) {
builder.setCasCacheDirectory(options.casCacheDirectory);
}
if (!Strings.isNullOrEmpty(options.publicName)) {
builder.setPublicName(options.publicName);
}
return builder.build();
}
private static void printUsage(OptionsParser parser) {
System.out.println("Usage: CONFIG_PATH");
System.out.println(parser.describeOptions(Collections.<String, String>emptyMap(),
OptionsParser.HelpVerbosity.LONG));
}
public static void main(String[] args) throws Exception {
// Only log severe log messages from Netty. Otherwise it logs warnings that look like this:
//
// 170714 08:16:28.552:WT 18 [io.grpc.netty.NettyServerHandler.onStreamError] Stream Error
// io.netty.handler.codec.http2.Http2Exception$StreamException: Received DATA frame for an
// unknown stream 11369
nettyLogger.setLevel(Level.SEVERE);
OptionsParser parser = OptionsParser.newOptionsParser(WorkerOptions.class);
parser.parseAndExitUponError(args);
List<String> residue = parser.getResidue();
if (residue.isEmpty()) {
printUsage(parser);
throw new IllegalArgumentException("Missing CONFIG_PATH");
}
Path configPath = Paths.get(residue.get(0));
Worker worker;
try (InputStream configInputStream = Files.newInputStream(configPath)) {
worker = new Worker(toShardWorkerConfig(new InputStreamReader(configInputStream), parser.getOptions(WorkerOptions.class)));
}
worker.start();
worker.blockUntilShutdown();
}
}
| src/main/java/build/buildfarm/worker/shard/Worker.java | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build.buildfarm.worker.shard;
import static build.buildfarm.worker.CASFileCache.getOrIOException;
import static com.google.common.util.concurrent.Futures.allAsList;
import build.buildfarm.common.ContentAddressableStorage;
import build.buildfarm.common.ContentAddressableStorage.Blob;
import build.buildfarm.common.DigestUtil;
import build.buildfarm.common.DigestUtil.ActionKey;
import build.buildfarm.common.DigestUtil.HashFunction;
import build.buildfarm.common.ShardBackplane;
import build.buildfarm.instance.Instance;
import build.buildfarm.instance.Instance.MatchListener;
import build.buildfarm.instance.memory.MemoryLRUContentAddressableStorage;
import build.buildfarm.instance.shard.RedisShardBackplane;
import build.buildfarm.instance.stub.ByteStreamUploader;
import build.buildfarm.instance.stub.Retrier;
import build.buildfarm.instance.stub.Retrier.Backoff;
import build.buildfarm.instance.stub.RetryException;
import build.buildfarm.instance.stub.StubInstance;
import build.buildfarm.server.InstanceNotFoundException;
import build.buildfarm.server.Instances;
import build.buildfarm.server.ContentAddressableStorageService;
import build.buildfarm.server.ByteStreamService;
import build.buildfarm.worker.CASFileCache;
import build.buildfarm.worker.Dirent;
import build.buildfarm.worker.ExecuteActionStage;
import build.buildfarm.worker.FuseCAS;
import build.buildfarm.worker.InputFetchStage;
import build.buildfarm.worker.InputStreamFactory;
import build.buildfarm.worker.MatchStage;
import build.buildfarm.worker.OutputDirectory;
import build.buildfarm.worker.OutputStreamFactory;
import build.buildfarm.worker.Pipeline;
import build.buildfarm.worker.PipelineStage;
import build.buildfarm.worker.Poller;
import build.buildfarm.worker.PutOperationStage;
import build.buildfarm.worker.ReportResultStage;
import build.buildfarm.worker.UploadManifest;
import build.buildfarm.worker.WorkerContext;
import build.buildfarm.v1test.CASInsertionPolicy;
import build.buildfarm.v1test.QueuedOperationMetadata;
import build.buildfarm.v1test.ShardWorkerConfig;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.remoteexecution.v1test.Action;
import com.google.devtools.remoteexecution.v1test.ActionResult;
import com.google.devtools.remoteexecution.v1test.Digest;
import com.google.devtools.remoteexecution.v1test.Directory;
import com.google.devtools.remoteexecution.v1test.DirectoryNode;
import com.google.devtools.remoteexecution.v1test.FileNode;
import com.google.devtools.remoteexecution.v1test.ExecuteOperationMetadata;
import com.google.devtools.remoteexecution.v1test.ExecuteOperationMetadata.Stage;
import com.google.devtools.remoteexecution.v1test.OutputFile;
import com.google.devtools.remoteexecution.v1test.Tree;
import com.google.longrunning.Operation;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.TextFormat;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.Status;
import io.grpc.Status.Code;
import io.grpc.StatusRuntimeException;
import io.grpc.netty.NegotiationType;
import io.grpc.netty.NettyChannelBuilder;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.ConfigurationException;
public class Worker implements Instances {
private static final Logger nettyLogger = Logger.getLogger("io.grpc.netty");
private final ShardWorkerConfig config;
private final ShardWorkerInstance instance;
private final Server server;
private final Path root;
private final DigestUtil digestUtil;
private final InputStreamFactory storageInputStreamFactory;
private final FuseCAS fuseCAS;
private final CASFileCache fileCache;
private final Pipeline pipeline;
private final ShardBackplane backplane;
private final Map<String, StubInstance> workerStubs;
private final Map<Path, Iterable<Path>> rootInputFiles = new ConcurrentHashMap<>();
private final Map<Path, Iterable<Digest>> rootInputDirectories = new ConcurrentHashMap<>();
private final ListeningScheduledExecutorService retryScheduler =
MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(1));
private final Set<String> activeOperations = new ConcurrentSkipListSet<>();
private static final int shutdownWaitTimeInMillis = 10000;
@Override
public Instance getFromBlob(String blobName) throws InstanceNotFoundException { return instance; }
@Override
public Instance getFromUploadBlob(String uploadBlobName) throws InstanceNotFoundException { return instance; }
@Override
public Instance getFromOperationsCollectionName(String operationsCollectionName) throws InstanceNotFoundException { return instance; }
@Override
public Instance getFromOperationName(String operationName) throws InstanceNotFoundException { return instance; }
@Override
public Instance getFromOperationStream(String operationStream) throws InstanceNotFoundException { return instance; }
@Override
public Instance get(String name) throws InstanceNotFoundException { return instance; }
public Worker(ShardWorkerConfig config) throws ConfigurationException {
this(ServerBuilder.forPort(config.getPort()), config);
}
private static Path getValidRoot(ShardWorkerConfig config) throws ConfigurationException {
String rootValue = config.getRoot();
if (Strings.isNullOrEmpty(rootValue)) {
throw new ConfigurationException("root value in config missing");
}
Path root = Paths.get(rootValue);
if (!Files.isDirectory(root)) {
throw new ConfigurationException("root [" + root.toString() + "] is not directory");
}
return root;
}
private static Path getValidCasCacheDirectory(ShardWorkerConfig config, Path root) throws ConfigurationException {
String casCacheValue = config.getCasCacheDirectory();
if (Strings.isNullOrEmpty(casCacheValue)) {
throw new ConfigurationException("Cas cache directory value in config missing");
}
return root.resolve(casCacheValue);
}
private static HashFunction getValidHashFunction(ShardWorkerConfig config) throws ConfigurationException {
try {
return HashFunction.get(config.getHashFunction());
} catch (IllegalArgumentException e) {
throw new ConfigurationException("hash_function value unrecognized");
}
}
private static ManagedChannel createChannel(String target) {
NettyChannelBuilder builder =
NettyChannelBuilder.forTarget(target)
.negotiationType(NegotiationType.PLAINTEXT);
return builder.build();
}
private static Retrier createStubRetrier() {
return new Retrier(
Backoff.exponential(
java.time.Duration.ofMillis(/*options.experimentalRemoteRetryStartDelayMillis=*/ 100),
java.time.Duration.ofMillis(/*options.experimentalRemoteRetryMaxDelayMillis=*/ 5000),
/*options.experimentalRemoteRetryMultiplier=*/ 2,
/*options.experimentalRemoteRetryJitter=*/ 0.1,
/*options.experimentalRemoteRetryMaxAttempts=*/ 5),
Retrier.DEFAULT_IS_RETRIABLE);
}
private ByteStreamUploader createStubUploader(Channel channel) {
return new ByteStreamUploader("", channel, null, 300, createStubRetrier(), retryScheduler);
}
private StubInstance workerStub(String worker) {
StubInstance instance = workerStubs.get(worker);
if (instance == null) {
ManagedChannel channel = createChannel(worker);
instance = new StubInstance(
"", digestUtil, channel,
10 /* FIXME CONFIG */, TimeUnit.SECONDS,
createStubRetrier(),
createStubUploader(channel));
workerStubs.put(worker, instance);
}
return instance;
}
/*
private void removeMalfunctioningWorkerClient(String worker) {
StubInstance instance = workerStubs.remove(worker);
if (instance != null) {
ManagedChannel channel = instance.getChannel();
channel.shutdownNow();
try {
channel.awaitTermination(0, TimeUnit.SECONDS);
} catch (InterruptedException intEx) {
// impossible, 0 timeout
Thread.currentThread().interrupt();
}
}
}
*/
private void fetchInputs(
Path execDir,
Digest directoryDigest,
Map<Digest, Directory> directoriesIndex,
OutputDirectory outputDirectory,
ImmutableList.Builder<Path> inputFiles,
ImmutableList.Builder<Digest> inputDirectories)
throws IOException, InterruptedException {
Directory directory = directoriesIndex.get(directoryDigest);
if (directory == null) {
throw new IOException("Directory " + DigestUtil.toString(directoryDigest) + " is not in directories index");
}
for (FileNode fileNode : directory.getFilesList()) {
Path execPath = execDir.resolve(fileNode.getName());
/*
System.out.println(String.format("Worker::fetchInputs(%s) linking %s (%s)",
DigestUtil.toString(directoryDigest),
fileNode.getIsExecutable() ? ("*" + fileNode.getName() + "*") : fileNode.getName(),
DigestUtil.toString(fileNode.getDigest())));
*/
Path fileCacheKey = fileCache.put(fileNode.getDigest(), fileNode.getIsExecutable(), /* containingDirectory=*/ null);
inputFiles.add(fileCacheKey);
/*
System.out.println(String.format("Worker::fetchInputs(%s) linking %s complete (%s)",
DigestUtil.toString(directoryDigest),
fileNode.getIsExecutable() ? ("*" + fileNode.getName() + "*") : fileNode.getName(),
DigestUtil.toString(fileNode.getDigest())));
*/
Files.createLink(execPath, fileCacheKey);
}
for (DirectoryNode directoryNode : directory.getDirectoriesList()) {
Digest digest = directoryNode.getDigest();
String name = directoryNode.getName();
OutputDirectory childOutputDirectory = outputDirectory != null
? outputDirectory.getChild(name) : null;
Path dirPath = execDir.resolve(name);
if (childOutputDirectory != null || !config.getLinkInputDirectories()) {
Files.createDirectories(dirPath);
/*
System.out.println(String.format("Worker::fetchInputs(%s) subdirectory %s (%s)",
DigestUtil.toString(directoryDigest),
name,
DigestUtil.toString(digest)));
*/
fetchInputs(dirPath, digest, directoriesIndex, childOutputDirectory, inputFiles, inputDirectories);
/*
System.out.println(String.format("Worker::fetchInputs(%s) subdirectory complete %s (%s)",
DigestUtil.toString(directoryDigest),
name,
DigestUtil.toString(digest)));
*/
} else {
/*
System.out.println(String.format("Worker::fetchInputs(%s) linkDirectory %s (%s)",
DigestUtil.toString(directoryDigest),
name,
DigestUtil.toString(digest)));
*/
linkDirectory(dirPath, digest, directoriesIndex);
inputDirectories.add(digest);
/*
System.out.println(String.format("Worker::fetchInputs(%s) linkDirectory complete %s (%s)",
DigestUtil.toString(directoryDigest),
name,
DigestUtil.toString(digest)));
*/
}
}
}
private void linkDirectory(
Path execPath,
Digest digest,
Map<Digest, Directory> directoriesIndex) throws IOException, InterruptedException {
Path cachePath = fileCache.putDirectory(digest, directoriesIndex);
Files.createSymbolicLink(execPath, cachePath);
}
private Operation stripOperation(Operation operation) {
return instance.stripOperation(operation);
}
private Operation stripQueuedOperation(Operation operation) {
return instance.stripQueuedOperation(operation);
}
private static int inlineOrDigest(
ByteString content,
CASInsertionPolicy policy,
ImmutableList.Builder<ByteString> contents,
int inlineContentBytes,
int inlineContentLimit,
Runnable setInline,
Consumer<ByteString> setDigest) {
boolean withinLimit = inlineContentBytes + content.size() <= inlineContentLimit;
if (withinLimit) {
setInline.run();
inlineContentBytes += content.size();
}
if (policy.equals(CASInsertionPolicy.ALWAYS_INSERT) ||
(!withinLimit && policy.equals(CASInsertionPolicy.INSERT_ABOVE_LIMIT))) {
contents.add(content);
setDigest.accept(content);
}
return inlineContentBytes;
}
public Worker(ServerBuilder<?> serverBuilder, ShardWorkerConfig config) throws ConfigurationException {
this.config = config;
workerStubs = new HashMap<>();
root = getValidRoot(config);
digestUtil = new DigestUtil(getValidHashFunction(config));
ShardWorkerConfig.BackplaneCase backplaneCase = config.getBackplaneCase();
switch (backplaneCase) {
default:
case BACKPLANE_NOT_SET:
throw new IllegalArgumentException("Shard Backplane not set in config");
case REDIS_SHARD_BACKPLANE_CONFIG:
backplane = new RedisShardBackplane(config.getRedisShardBackplaneConfig(), this::stripOperation, this::stripQueuedOperation, (o) -> false);
break;
}
InputStreamFactory remoteInputStreamFactory = new InputStreamFactory() {
private Random rand = new Random();
private InputStream fetchBlobFromRemoteWorker(Digest blobDigest, Deque<String> workers, long offset) throws IOException, InterruptedException {
String worker = workers.removeFirst();
try {
for (;;) {
Instance instance = workerStub(worker);
InputStream input = instance.newStreamInput(instance.getBlobName(blobDigest), offset);
// ensure that if the blob cannot be fetched, that we throw here
input.available();
if (Thread.interrupted()) {
throw new InterruptedException();
}
return input;
}
} catch (RetryException e) {
Status st = Status.fromThrowable(e);
if (st.getCode().equals(Code.UNAVAILABLE)) {
backplane.removeBlobLocation(blobDigest, worker);
// for now, leave this up to schedulers
// removeMalfunctioningWorker(worker, e, "getBlob(" + DigestUtil.toString(blobDigest) + ")");
} else if (st.getCode().equals(Code.NOT_FOUND)) {
// ignore this, the worker will update the backplane eventually
} else if (Retrier.DEFAULT_IS_RETRIABLE.test(st)) {
// why not, always
workers.addLast(worker);
} else {
throw e;
}
throw new NoSuchFileException(DigestUtil.toString(blobDigest));
}
}
private List<String> correctMissingBlob(Digest digest) throws IOException {
ImmutableList.Builder<String> foundWorkers = new ImmutableList.Builder<>();
Deque<String> workers;
try {
List<String> workersList = new ArrayList<>(
Sets.difference(backplane.getWorkerSet(), ImmutableSet.<String>of(config.getPublicName())));
Collections.shuffle(workersList, rand);
workers = new ArrayDeque(workersList);
} catch (IOException e) {
throw Status.fromThrowable(e).asRuntimeException();
}
for (String worker : workers) {
try {
Iterable<Digest> resultDigests = null;
while (resultDigests == null) {
try {
resultDigests = createStubRetrier().execute(() -> workerStub(worker).findMissingBlobs(ImmutableList.<Digest>of(digest)));
if (Iterables.size(resultDigests) == 0) {
System.out.println("Worker::RemoteInputStreamFactory::correctMissingBlob(" + DigestUtil.toString(digest) + "): Adding back to " + worker);
backplane.addBlobLocation(digest, worker);
foundWorkers.add(worker);
}
} catch (RetryException e) {
if (e.getCause() instanceof StatusRuntimeException) {
StatusRuntimeException sre = (StatusRuntimeException) e.getCause();
throw sre;
}
throw e;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Status.CANCELLED.asRuntimeException();
} catch (IOException e) {
throw Status.INTERNAL.withDescription(e.getMessage()).asRuntimeException();
} catch (StatusRuntimeException e) {
if (e.getStatus().getCode().equals(Status.UNAVAILABLE.getCode())) {
// removeMalfunctioningWorker(worker, e, "findMissingBlobs(...)");
} else {
e.printStackTrace();
}
}
}
return foundWorkers.build();
}
@Override
public InputStream newInput(Digest blobDigest, long offset) throws IOException, InterruptedException {
Set<String> workerSet = new HashSet<>(Sets.intersection(
backplane.getBlobLocationSet(blobDigest),
backplane.getWorkerSet()));
if (workerSet.remove(config.getPublicName())) {
backplane.removeBlobLocation(blobDigest, config.getPublicName());
}
List<String> workersList = new ArrayList<>(workerSet);
Collections.shuffle(workersList, rand);
Deque<String> workers = new ArrayDeque(workersList);
boolean printFinal = false;
boolean triedCheck = false;
for (;;) {
if (workers.isEmpty()) {
if (triedCheck) {
// maybe just return null here
throw new IOException("worker not found for blob " + DigestUtil.toString(blobDigest));
}
workersList.clear();
workersList.addAll(correctMissingBlob(blobDigest));
Collections.shuffle(workersList, rand);
workers = new ArrayDeque(workersList);
triedCheck = true;
} else {
int sizeBeforeFetch = workers.size();
InputStream input = fetchBlobFromRemoteWorker(blobDigest, workers, offset);
if (sizeBeforeFetch == workers.size()) {
printFinal = true;
System.out.println("Pushed worker to end of request list: " + workers.peekLast() + " for " + DigestUtil.toString(blobDigest));
}
if (printFinal) {
System.out.println("fetch with retried loop succeeded for " + DigestUtil.toString(blobDigest));
}
return input;
}
}
}
};
final ContentAddressableStorage storage;
final OutputStreamFactory outputStreamFactory;
if (config.getUseFuseCas()) {
fileCache = null;
storage = new MemoryLRUContentAddressableStorage(config.getCasMaxSizeBytes(), this::onStoragePut);
storageInputStreamFactory = (digest, offset) -> storage.get(digest).getData().substring((int) offset).newInput();
outputStreamFactory = (digest) -> { throw new UnsupportedOperationException(); };
InputStreamFactory localPopulatingInputStreamFactory = new InputStreamFactory() {
@Override
public InputStream newInput(Digest blobDigest, long offset) throws IOException, InterruptedException {
ByteString content = ByteString.readFrom(remoteInputStreamFactory.newInput(blobDigest, offset));
if (offset == 0) {
// extra computations
Blob blob = new Blob(content, digestUtil);
// here's hoping that our digest matches...
storage.put(blob);
}
return content.newInput();
}
};
fuseCAS = new FuseCAS(root, new EmptyInputStreamFactory(new FailoverInputStreamFactory(storageInputStreamFactory, localPopulatingInputStreamFactory)));
} else {
fuseCAS = null;
InputStreamFactory selfInputStreamChain = new InputStreamFactory() {
@Override
public InputStream newInput(Digest blobDigest, long offset) throws IOException, InterruptedException {
// oh the complication... using storage here requires us to be instantiated in this context
return new EmptyInputStreamFactory(new FailoverInputStreamFactory(storageInputStreamFactory, remoteInputStreamFactory))
.newInput(blobDigest, offset);
}
};
Path casCacheDirectory = getValidCasCacheDirectory(config, root);
fileCache = new CASFileCache(
selfInputStreamChain,
root.resolve(casCacheDirectory),
config.getCasCacheMaxSizeBytes(),
digestUtil,
this::onStoragePut,
this::onStorageExpire);
storage = fileCache;
storageInputStreamFactory = fileCache;
outputStreamFactory = fileCache;
}
instance = new ShardWorkerInstance(
config.getPublicName(),
digestUtil,
backplane,
storage,
storageInputStreamFactory,
outputStreamFactory,
config.getShardWorkerInstanceConfig());
server = serverBuilder
.addService(new ContentAddressableStorageService(this))
.addService(new ByteStreamService(this))
.build();
// FIXME factor into pipeline factory/constructor
WorkerContext context = new WorkerContext() {
@Override
public String getName() {
return config.getPublicName();
}
@Override
public Poller createPoller(String name, String operationName, Stage stage) {
return createPoller(name, operationName, stage, () -> {});
}
@Override
public Poller createPoller(String name, String operationName, Stage stage, Runnable onFailure) {
Poller poller = new Poller(
config.getOperationPollPeriod(),
() -> {
boolean success = false;
try {
success = backplane.pollOperation(operationName, stage, System.currentTimeMillis() + 30 * 1000);
} catch (IOException e) {
e.printStackTrace();
}
logInfo(name + ": poller: Completed Poll for " + operationName + ": " + (success ? "OK" : "Failed"));
if (!success) {
onFailure.run();
}
return success;
});
new Thread(poller).start();
return poller;
}
@Override
public DigestUtil getDigestUtil() {
return instance.getDigestUtil();
}
@Override
public void match(MatchListener listener) throws InterruptedException {
instance.match(config.getPlatform(), new MatchListener() {
@Override
public void onWaitStart() {
listener.onWaitStart();
}
@Override
public void onWaitEnd() {
listener.onWaitEnd();
}
@Override
public boolean onOperationName(String operationName) {
if (activeOperations.contains(operationName)) {
System.err.println("WorkerContext::match: WARNING matched duplicate operation " + operationName);
return listener.onOperation(null);
}
activeOperations.add(operationName);
boolean success = listener.onOperationName(operationName);
if (!success) {
try {
// fast path to requeue, implementation specific
backplane.pollOperation(operationName, ExecuteOperationMetadata.Stage.QUEUED, 0);
} catch (IOException e) {
System.err.println("Failure while trying to fast requeue " + operationName);
e.printStackTrace();
}
}
return success;
}
@Override
public boolean onOperation(Operation operation) {
// could not fetch
if (operation.getDone()) {
activeOperations.remove(operation.getName());
listener.onOperation(null);
try {
backplane.pollOperation(operation.getName(), ExecuteOperationMetadata.Stage.QUEUED, 0);
} catch (IOException e) {
System.err.println("Failure while trying to fast requeue " + operation.getName());
e.printStackTrace();
}
return false;
}
boolean success = listener.onOperation(operation);
if (!success) {
try {
requeue(operation);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
return success;
}
});
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
private ExecuteOperationMetadata expectExecuteOperationMetadata(Operation operation) {
Any metadata = operation.getMetadata();
if (metadata == null) {
return null;
}
if (metadata.is(QueuedOperationMetadata.class)) {
try {
return operation.getMetadata().unpack(QueuedOperationMetadata.class).getExecuteOperationMetadata();
} catch(InvalidProtocolBufferException e) {
e.printStackTrace();
return null;
}
}
if (metadata.is(ExecuteOperationMetadata.class)) {
try {
return operation.getMetadata().unpack(ExecuteOperationMetadata.class);
} catch(InvalidProtocolBufferException e) {
e.printStackTrace();
return null;
}
}
return null;
}
@Override
public void requeue(Operation operation) throws InterruptedException {
deactivate(operation);
try {
backplane.pollOperation(operation.getName(), ExecuteOperationMetadata.Stage.QUEUED, 0);
} catch (IOException e) {
// ignore, at least dispatcher will pick us up in 30s
e.printStackTrace();
}
}
@Override
public void deactivate(Operation operation) {
activeOperations.remove(operation.getName());
}
@Override
public void logInfo(String msg) {
System.out.println(msg);
}
@Override
public int getInlineContentLimit() {
return config.getInlineContentLimit();
}
@Override
public CASInsertionPolicy getFileCasPolicy() {
return CASInsertionPolicy.ALWAYS_INSERT;
}
@Override
public CASInsertionPolicy getStdoutCasPolicy() {
return CASInsertionPolicy.ALWAYS_INSERT;
}
@Override
public CASInsertionPolicy getStderrCasPolicy() {
return CASInsertionPolicy.ALWAYS_INSERT;
}
@Override
public int getExecuteStageWidth() {
return config.getExecuteStageWidth();
}
@Override
public int getTreePageSize() {
return 0;
}
@Override
public boolean hasDefaultActionTimeout() {
return false;
}
@Override
public boolean hasMaximumActionTimeout() {
return false;
}
@Override
public boolean getStreamStdout() {
return true;
}
@Override
public boolean getStreamStderr() {
return true;
}
@Override
public Duration getDefaultActionTimeout() {
return null;
}
@Override
public Duration getMaximumActionTimeout() {
return null;
}
private int updateActionResultStdOutputs(
ActionResult.Builder resultBuilder,
ImmutableList.Builder<ByteString> contents,
int inlineContentBytes) {
ByteString stdoutRaw = resultBuilder.getStdoutRaw();
if (stdoutRaw.size() > 0) {
// reset to allow policy to determine inlining
resultBuilder.setStdoutRaw(ByteString.EMPTY);
inlineContentBytes = inlineOrDigest(
stdoutRaw,
getStdoutCasPolicy(),
contents,
inlineContentBytes,
getInlineContentLimit(),
() -> resultBuilder.setStdoutRaw(stdoutRaw),
(content) -> resultBuilder.setStdoutDigest(getDigestUtil().compute(content)));
}
ByteString stderrRaw = resultBuilder.getStderrRaw();
if (stderrRaw.size() > 0) {
// reset to allow policy to determine inlining
resultBuilder.setStderrRaw(ByteString.EMPTY);
inlineContentBytes = inlineOrDigest(
stderrRaw,
getStderrCasPolicy(),
contents,
inlineContentBytes,
getInlineContentLimit(),
() -> resultBuilder.setStderrRaw(stdoutRaw),
(content) -> resultBuilder.setStderrDigest(getDigestUtil().compute(content)));
}
return inlineContentBytes;
}
@Override
public void uploadOutputs(
ActionResult.Builder resultBuilder,
Path actionRoot,
Iterable<String> outputFiles,
Iterable<String> outputDirs)
throws IOException, InterruptedException {
int inlineContentBytes = 0;
ImmutableList.Builder<ByteString> contents = new ImmutableList.Builder<>();
for (String outputFile : outputFiles) {
Path outputPath = actionRoot.resolve(outputFile);
if (!Files.exists(outputPath)) {
logInfo("ReportResultStage: " + outputPath + " does not exist...");
continue;
}
// FIXME put the output into the fileCache
// FIXME this needs to be streamed to the server, not read to completion, but
// this is a constraint of not knowing the hash, however, if we put the entry
// into the cache, we can likely do so, stream the output up, and be done
//
// will run into issues if we end up blocking on the cache insertion, might
// want to decrement input references *before* this to ensure that we cannot
// cause an internal deadlock
ByteString content;
try (InputStream inputStream = Files.newInputStream(outputPath)) {
content = ByteString.readFrom(inputStream);
} catch (IOException e) {
continue;
}
OutputFile.Builder outputFileBuilder = resultBuilder.addOutputFilesBuilder()
.setPath(outputFile)
.setIsExecutable(Files.isExecutable(outputPath));
inlineContentBytes = inlineOrDigest(
content,
getFileCasPolicy(),
contents,
inlineContentBytes,
getInlineContentLimit(),
() -> outputFileBuilder.setContent(content),
(fileContent) -> outputFileBuilder.setDigest(getDigestUtil().compute(fileContent)));
}
for (String outputDir : outputDirs) {
Path outputDirPath = actionRoot.resolve(outputDir);
if (!Files.exists(outputDirPath)) {
logInfo("ReportResultStage: " + outputDir + " does not exist...");
continue;
}
Tree.Builder treeBuilder = Tree.newBuilder();
Directory.Builder outputRoot = treeBuilder.getRootBuilder();
Files.walkFileTree(outputDirPath, new SimpleFileVisitor<Path>() {
Directory.Builder currentDirectory = null;
Stack<Directory.Builder> path = new Stack<>();
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
ByteString content;
try (InputStream inputStream = Files.newInputStream(file)) {
content = ByteString.readFrom(inputStream);
} catch (IOException e) {
e.printStackTrace();
return FileVisitResult.CONTINUE;
}
// should we cast to PosixFilePermissions and do gymnastics there for executable?
// TODO symlink per revision proposal
contents.add(content);
FileNode.Builder fileNodeBuilder = currentDirectory.addFilesBuilder()
.setName(file.getFileName().toString())
.setDigest(getDigestUtil().compute(content))
.setIsExecutable(Files.isExecutable(file));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
path.push(currentDirectory);
if (dir.equals(outputDirPath)) {
currentDirectory = outputRoot;
} else {
currentDirectory = treeBuilder.addChildrenBuilder();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Directory.Builder parentDirectory = path.pop();
if (parentDirectory != null) {
parentDirectory.addDirectoriesBuilder()
.setName(dir.getFileName().toString())
.setDigest(getDigestUtil().compute(currentDirectory.build()));
}
currentDirectory = parentDirectory;
return FileVisitResult.CONTINUE;
}
});
Tree tree = treeBuilder.build();
ByteString treeBlob = tree.toByteString();
contents.add(treeBlob);
Digest treeDigest = getDigestUtil().compute(treeBlob);
resultBuilder.addOutputDirectoriesBuilder()
.setPath(outputDir)
.setTreeDigest(treeDigest);
}
/* put together our outputs and update the result */
updateActionResultStdOutputs(resultBuilder, contents, inlineContentBytes);
List<ByteString> blobs = contents.build();
if (!blobs.isEmpty()) {
instance.putAllBlobs(blobs);
}
}
@Override
public boolean putOperation(Operation operation, Action action) throws IOException, InterruptedException {
boolean success = instance.putOperation(operation);
if (success && operation.getDone()) {
backplane.removeTree(action.getInputRootDigest());
}
return success;
}
@Override
public void createActionRoot(Path actionRoot, Map<Digest, Directory> directoriesIndex, Action action) throws IOException, InterruptedException {
if (config.getUseFuseCas()) {
String topdir = root.relativize(actionRoot).toString();
fuseCAS.createInputRoot(topdir, action.getInputRootDigest());
} else {
OutputDirectory outputDirectory = OutputDirectory.parse(
action.getOutputFilesList(),
action.getOutputDirectoriesList());
if (Files.exists(actionRoot)) {
getOrIOException(fileCache.removeDirectoryAsync(actionRoot));
}
Files.createDirectories(actionRoot);
ImmutableList.Builder<Path> inputFiles = new ImmutableList.Builder<>();
ImmutableList.Builder<Digest> inputDirectories = new ImmutableList.Builder<>();
System.out.println("WorkerContext::createActionRoot(" + DigestUtil.toString(action.getInputRootDigest()) + ") calling fetchInputs");
try {
fetchInputs(
actionRoot,
action.getInputRootDigest(),
directoriesIndex,
outputDirectory,
inputFiles,
inputDirectories);
} catch (IOException e) {
fileCache.decrementReferences(inputFiles.build(), inputDirectories.build());
throw e;
}
rootInputFiles.put(actionRoot, inputFiles.build());
rootInputDirectories.put(actionRoot, inputDirectories.build());
System.out.println("WorkerContext::createActionRoot(" + DigestUtil.toString(action.getInputRootDigest()) + ") stamping output directories");
try {
outputDirectory.stamp(actionRoot);
} catch (IOException e) {
destroyActionRoot(actionRoot);
throw e;
}
}
}
// might want to split for removeDirectory and decrement references to avoid removing for streamed output
@Override
public void destroyActionRoot(Path actionRoot) throws IOException, InterruptedException {
if (config.getUseFuseCas()) {
String topdir = root.relativize(actionRoot).toString();
fuseCAS.destroyInputRoot(topdir);
} else {
Iterable<Path> inputFiles = rootInputFiles.remove(actionRoot);
Iterable<Digest> inputDirectories = rootInputDirectories.remove(actionRoot);
if (inputFiles != null || inputDirectories != null) {
fileCache.decrementReferences(
inputFiles == null ? ImmutableList.<Path>of() : inputFiles,
inputDirectories == null ? ImmutableList.<Digest>of() : inputDirectories);
}
if (Files.exists(actionRoot)) {
getOrIOException(fileCache.removeDirectoryAsync(actionRoot));
}
}
}
public Path getRoot() {
return root;
}
@Override
public void putActionResult(ActionKey actionKey, ActionResult actionResult) {
instance.putActionResult(actionKey, actionResult);
}
@Override
public OutputStream getStreamOutput(String name) {
throw new UnsupportedOperationException();
}
};
PipelineStage completeStage = new PutOperationStage(context::deactivate);
PipelineStage errorStage = completeStage; /* new ErrorStage(); */
PipelineStage reportResultStage = new ReportResultStage(context, completeStage, errorStage);
PipelineStage executeActionStage = new ExecuteActionStage(context, reportResultStage, errorStage);
reportResultStage.setInput(executeActionStage);
PipelineStage inputFetchStage = new InputFetchStage(context, executeActionStage, new PutOperationStage(context::requeue));
executeActionStage.setInput(inputFetchStage);
PipelineStage matchStage = new MatchStage(context, inputFetchStage, errorStage);
inputFetchStage.setInput(matchStage);
pipeline = new Pipeline();
// pipeline.add(errorStage, 0);
pipeline.add(matchStage, 1);
pipeline.add(inputFetchStage, 2);
pipeline.add(executeActionStage, 3);
pipeline.add(reportResultStage, 4);
}
public void stop() {
System.err.println("Closing the pipeline");
try {
pipeline.close();
} catch (InterruptedException e) {
backplane.stop(); // the pool must be signaled...
Thread.currentThread().interrupt();
return;
}
if (config.getUseFuseCas()) {
System.err.println("Umounting Fuse");
fuseCAS.stop();
} else {
fileCache.stop();
}
if (server != null) {
System.err.println("Shutting down the server");
server.shutdown();
try {
server.awaitTermination(shutdownWaitTimeInMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
server.shutdownNow();
}
}
backplane.stop();
}
private void onStoragePut(Digest digest) {
try {
backplane.addBlobLocation(digest, config.getPublicName());
} catch (IOException e) {
throw Status.fromThrowable(e).asRuntimeException();
}
}
private void onStorageExpire(Iterable<Digest> digests) {
try {
backplane.removeBlobsLocation(digests, config.getPublicName());
} catch (IOException e) {
throw Status.fromThrowable(e).asRuntimeException();
}
}
private void blockUntilShutdown() throws InterruptedException {
// should really be waiting for both of these things...
/*
if (server != null) {
server.awaitTermination();
}
*/
pipeline.join();
if (server != null) {
server.shutdown();
try {
server.awaitTermination(shutdownWaitTimeInMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
server.shutdownNow();
}
}
backplane.stop();
}
private void removeWorker(String name) {
try {
backplane.removeWorker(name);
} catch (IOException e) {
Status status = Status.fromThrowable(e);
if (status.getCode() != Code.UNAVAILABLE && status.getCode() != Code.DEADLINE_EXCEEDED) {
throw status.asRuntimeException();
}
System.out.println("backplane was unavailable or overloaded, deferring removeWorker");
}
}
private void addBlobsLocation(List<Digest> digests, String name) {
for (;;) {
try {
backplane.addBlobsLocation(digests, name);
return;
} catch (IOException e) {
Status status = Status.fromThrowable(e);
if (status.getCode() != Code.UNAVAILABLE && status.getCode() != Code.DEADLINE_EXCEEDED) {
throw status.asRuntimeException();
}
}
}
}
private void addWorker(String name) {
for (;;) {
try {
backplane.addWorker(name);
return;
} catch (IOException e) {
Status status = Status.fromThrowable(e);
if (status.getCode() != Code.UNAVAILABLE && status.getCode() != Code.DEADLINE_EXCEEDED) {
throw status.asRuntimeException();
}
}
}
}
@Override
public void start() {
try {
backplane.start();
removeWorker(config.getPublicName());
if (!config.getUseFuseCas()) {
List<Dirent> dirents = null;
try {
dirents = UploadManifest.readdir(root, /* followSymlinks= */ false);
} catch (IOException e) {
e.printStackTrace();
}
ImmutableList.Builder<ListenableFuture<Void>> removeDirectoryFutures = new ImmutableList.Builder<>();
// only valid path under root is cache
for (Dirent dirent : dirents) {
String name = dirent.getName();
Path child = root.resolve(name);
if (!child.equals(fileCache.getRoot())) {
removeDirectoryFutures.add(fileCache.removeDirectoryAsync(root.resolve(name)));
}
}
ImmutableList.Builder<Digest> blobDigests = new ImmutableList.Builder<>();
fileCache.start(blobDigests::add);
addBlobsLocation(blobDigests.build(), config.getPublicName());
getOrIOException(allAsList(removeDirectoryFutures.build()));
}
server.start();
addWorker(config.getPublicName());
} catch (Exception e) {
stop();
e.printStackTrace();
return;
}
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("*** shutting down gRPC server since JVM is shutting down");
Worker.this.stop();
System.err.println("*** server shut down");
}
});
pipeline.start();
}
private static ShardWorkerConfig toShardWorkerConfig(Readable input, WorkerOptions options) throws IOException {
ShardWorkerConfig.Builder builder = ShardWorkerConfig.newBuilder();
TextFormat.merge(input, builder);
if (!Strings.isNullOrEmpty(options.root)) {
builder.setRoot(options.root);
}
if (!Strings.isNullOrEmpty(options.casCacheDirectory)) {
builder.setCasCacheDirectory(options.casCacheDirectory);
}
if (!Strings.isNullOrEmpty(options.publicName)) {
builder.setPublicName(options.publicName);
}
return builder.build();
}
private static void printUsage(OptionsParser parser) {
System.out.println("Usage: CONFIG_PATH");
System.out.println(parser.describeOptions(Collections.<String, String>emptyMap(),
OptionsParser.HelpVerbosity.LONG));
}
public static void main(String[] args) throws Exception {
// Only log severe log messages from Netty. Otherwise it logs warnings that look like this:
//
// 170714 08:16:28.552:WT 18 [io.grpc.netty.NettyServerHandler.onStreamError] Stream Error
// io.netty.handler.codec.http2.Http2Exception$StreamException: Received DATA frame for an
// unknown stream 11369
nettyLogger.setLevel(Level.SEVERE);
OptionsParser parser = OptionsParser.newOptionsParser(WorkerOptions.class);
parser.parseAndExitUponError(args);
List<String> residue = parser.getResidue();
if (residue.isEmpty()) {
printUsage(parser);
throw new IllegalArgumentException("Missing CONFIG_PATH");
}
Path configPath = Paths.get(residue.get(0));
Worker worker;
try (InputStream configInputStream = Files.newInputStream(configPath)) {
worker = new Worker(toShardWorkerConfig(new InputStreamReader(configInputStream), parser.getOptions(WorkerOptions.class)));
}
worker.start();
worker.blockUntilShutdown();
}
}
| Shut down fileCache or fuseCAS after pipeline join
| src/main/java/build/buildfarm/worker/shard/Worker.java | Shut down fileCache or fuseCAS after pipeline join | <ide><path>rc/main/java/build/buildfarm/worker/shard/Worker.java
<ide> server.shutdownNow();
<ide> }
<ide> }
<add> if (config.getUseFuseCas()) {
<add> fuseCAS.stop();
<add> } else {
<add> fileCache.stop();
<add> }
<ide> backplane.stop();
<ide> }
<ide> |
|
JavaScript | mit | b7559313505d7293bfefe143a2028aab3e555af2 | 0 | EnerG218/PServer | exports.BattleFormatsData = {
kyurem: {
inherit: true,
tier: "Ubers"
},
kyuremblack {
inherit: true,
tier: "Ubers"
| mods/projectxy/formats-data.js | exports.BattleFormatsData = {
luxray: {
inherit: true,
tier: "RU"
},
jynx: {
inherit: true,
tier: "NU"
},
gothitelle: {
inherit: true,
tier: "OU"
},
archeops: {
inherit: true,
tier: "OU"
},
weavile: {
inherit: true,
tier: "OU"
},
politoed: {
inherit: true,
tier: "UU"
},
ninetales: {
inherit: true,
tier: "UU"
},
darmanitan: {
inherit: true,
tier: "RU"
},
gligar: {
inherit: true,
tier: "RU"
},
roselia: {
inherit: true,
tier: "RU"
},
staraptor: {
inherit: true,
tier: "UU"
},
gliscor: {
inherit: true,
tier: "UU"
},
gastrodon: {
inherit: true,
tier: "UU"
}
};
| Fix Formats-Data.js | mods/projectxy/formats-data.js | Fix Formats-Data.js | <ide><path>ods/projectxy/formats-data.js
<ide> exports.BattleFormatsData = {
<del> luxray: {
<add> kyurem: {
<ide> inherit: true,
<del> tier: "RU"
<add> tier: "Ubers"
<ide> },
<del> jynx: {
<add> kyuremblack {
<ide> inherit: true,
<del> tier: "NU"
<del> },
<del> gothitelle: {
<del> inherit: true,
<del> tier: "OU"
<del> },
<del> archeops: {
<del> inherit: true,
<del> tier: "OU"
<del> },
<del> weavile: {
<del> inherit: true,
<del> tier: "OU"
<del> },
<del> politoed: {
<del> inherit: true,
<del> tier: "UU"
<del> },
<del> ninetales: {
<del> inherit: true,
<del> tier: "UU"
<del> },
<del> darmanitan: {
<del> inherit: true,
<del> tier: "RU"
<del> },
<del> gligar: {
<del> inherit: true,
<del> tier: "RU"
<del> },
<del> roselia: {
<del> inherit: true,
<del> tier: "RU"
<del> },
<del> staraptor: {
<del> inherit: true,
<del> tier: "UU"
<del> },
<del> gliscor: {
<del> inherit: true,
<del> tier: "UU"
<del> },
<del> gastrodon: {
<del> inherit: true,
<del> tier: "UU"
<del> }
<del>};
<add> tier: "Ubers" |
|
JavaScript | mit | 5061581f8e4d8e949a96d10e6f02e8231109a580 | 0 | DigitalRiver/react-atlas,Magneticmagnum/react-atlas | import React from "react";
import { mount, shallow, render } from "enzyme";
import { DropdownCore } from "../../../react-atlas-core/src/Dropdown/index";
function _findItem(n, text){
if(n.props().children){
if(n.props().children.props){
let str = n.props().children.props.value;
return (str == text);
}
}
return false;
}
describe("Test Dropdown component - Mouse tests", () => {
it("Test Dropdown component - Basic test", function(){
const component = mount(<DropdownCore onChange={ function(){} }>
<span>May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
expect(component.state().value).toEqual("");
expect(component.state().output).toEqual('May');
});
it("Test Dropdown component - Basic test (disabled)", function(){
const component = mount(<DropdownCore onChange={ function(){} } disabled={true}>
<span>May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
expect(component.state().value).toEqual("");
expect(component.state().output).toEqual('May');
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().active).toEqual(false);
component.find('Dropdown').simulate('click');
expect(component.state().output).toEqual('May');
expect(component.state().active).toEqual(false);
});
// it("Test Dropdown component - Basic test with errorCallback", function(){
// const component = mount(<DropdownCore onChange={ function(){} } errorCallback={ function(ev, val){return {valid: true, message: "Simple text"} } }>
// <span value="May">May</span>
// <span value="the">the</span>
// <span value="force">force</span>
// <span value="be">be</span>
// <span value="with">with</span>
// <span value="you">you</span>
// </DropdownCore>);
// expect(component.state().value).toEqual('May');
// expect(component.state().output).toEqual('May');
//
// component.find('Dropdown').simulate('focus');
// expect(component.state().output).toEqual('May');
// expect(component.state().focus).toEqual(true);
//
// component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
// });
it("Test Dropdown component - Select one item", function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Button').simulate('click');
expect(component.state().active).toEqual(true);
component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
expect(component.state().value).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
});
it("Test Dropdown component - Select one item - no onChange", function(){
const component = mount(<DropdownCore onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Button').simulate('click');
expect(component.state().active).toEqual(true);
component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
expect(component.state().value).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
});
it("Test Dropdown component - Select one item - no onClick", function(){
const component = mount(<DropdownCore onChange={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Button').simulate('click');
expect(component.state().active).toEqual(true);
component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
expect(component.state().value).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
});
it("Test Dropdown component - Select one item (twice)", function(){
const component = mount(<DropdownCore onChange={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Button').simulate('click');
expect(component.state().active).toEqual(true);
let item = component.findWhere(n => _findItem(n, 'you'));
item.simulate('mouseDown');
item.simulate('click');
expect(component.state().value).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
component.find('Button').simulate('click');
component.findWhere(n => _findItem(n, 'May')).simulate('mouseDown');
expect(component.state().value).toEqual('May');
expect(component.state().index).toEqual(0);
});
it("Test Dropdown component - Click with custon onClick Dropdown", function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} }>
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
component.find('Button').simulate('click');
component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
});
it("Test Dropdown component - Simple Click on Dropdown with onBeforeChange(false)", function(){
const component = mount(<DropdownCore onChange={ function(){} } onBeforeChange={ function(){return false} }>
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
component.find('Button').simulate('click');
let item = component.findWhere(n => _findItem(n, 'you'));
item.simulate('mouseDown');
item.simulate('click');
});
it("Test Dropdown component - Simple Click on Dropdown with onBeforeChange(true)", function(){
const component = mount(<DropdownCore onChange={ function(){} } onBeforeChange={ function(){return true} }>
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
component.find('Button').simulate('click');
let item = component.findWhere(n => _findItem(n, 'you'));
item.simulate('mouseDown');
item.simulate('click');
});
});
describe("Test Dropdown component - Keyboard tests", () => {
it("Test Dropdown component - Select one item (only ArrowDown used)",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('be');
expect(component.state().output).toEqual('be');
expect(component.state().index).toEqual(3);
});
it("Test Dropdown component - Select one item (ArrowDown & ArrowUp used)",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowUp"});
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('force');
expect(component.state().output).toEqual('force');
expect(component.state().index).toEqual(2);
});
it("Test Dropdown component - Select last item (only ArrowDown used)",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
for(let i=0; i<9; i++){
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
}
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('you');
expect(component.state().output).toEqual('you');
expect(component.state().index).toEqual(5);
});
it("Test Dropdown component - Select first item (going down & up with ArrowDown & Arrow up)",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
for(let i=0; i<9; i++){
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
}
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('you');
expect(component.state().output).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('you');
expect(component.state().active).toEqual(true);
for(let i=0; i<9; i++){
component.find('Dropdown').simulate('keyDown', {key: "ArrowUp"});
}
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('May');
expect(component.state().output).toEqual('May');
expect(component.state().index).toEqual(0);
});
it("Test Dropdown component - Press unhandled key",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Dropdown').simulate('keyDown', {key: "Ctrl"});
});
});
describe("Test Dropdown component - Window blur tests", () => {
it("Test Dropdown component - onBlur event test", function(){
const component = mount(<DropdownCore onChange={ function(){} }>
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
expect(component.state().value).toEqual('May');
expect(component.state().output).toEqual('May');
component.find('Dropdown').simulate('focus');
component.find('Dropdown').simulate('blur');
});
});
describe("Test Dropdown component - Dropdown Regression tests", () => {
it("Regression test for bug #249", function(){
expect( function(){ const component = mount(<DropdownCore></DropdownCore>); } ).toThrow(new Error("You must pass at least one child component to Dropdown"));
// expect.assertions(0);
});
});
describe("Test Dropdown component - Dropdown Regression tests", () => {
it("Regression test for bug #405", function(){
const component = mount(<DropdownCore isValid={false}><span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
expect(component.state().isValid).toEqual(false);
});
});
| packages/react-atlas-tests/dropdown/__tests__/dropdown.test.js | import React from "react";
import { mount, shallow, render } from "enzyme";
import { DropdownCore } from "../../../react-atlas-core/src/Dropdown/index";
function _findItem(n, text){
if(n.props().children){
if(n.props().children.props){
let str = n.props().children.props.value;
return (str == text);
}
}
return false;
}
describe("Test Dropdown component - Mouse tests", () => {
it("Test Dropdown component - Basic test", function(){
const component = mount(<DropdownCore onChange={ function(){} }>
<span>May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
expect(component.state().value).toEqual(undefined);
expect(component.state().output).toEqual('May');
});
it("Test Dropdown component - Basic test (disabled)", function(){
const component = mount(<DropdownCore onChange={ function(){} } disabled={true}>
<span>May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
expect(component.state().value).toEqual(undefined);
expect(component.state().output).toEqual('May');
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().active).toEqual(false);
component.find('Dropdown').simulate('click');
expect(component.state().output).toEqual('May');
expect(component.state().active).toEqual(false);
});
// it("Test Dropdown component - Basic test with errorCallback", function(){
// const component = mount(<DropdownCore onChange={ function(){} } errorCallback={ function(ev, val){return {valid: true, message: "Simple text"} } }>
// <span value="May">May</span>
// <span value="the">the</span>
// <span value="force">force</span>
// <span value="be">be</span>
// <span value="with">with</span>
// <span value="you">you</span>
// </DropdownCore>);
// expect(component.state().value).toEqual('May');
// expect(component.state().output).toEqual('May');
//
// component.find('Dropdown').simulate('focus');
// expect(component.state().output).toEqual('May');
// expect(component.state().focus).toEqual(true);
//
// component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
// });
it("Test Dropdown component - Select one item", function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Button').simulate('click');
expect(component.state().active).toEqual(true);
component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
expect(component.state().value).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
});
it("Test Dropdown component - Select one item - no onChange", function(){
const component = mount(<DropdownCore onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Button').simulate('click');
expect(component.state().active).toEqual(true);
component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
expect(component.state().value).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
});
it("Test Dropdown component - Select one item - no onClick", function(){
const component = mount(<DropdownCore onChange={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Button').simulate('click');
expect(component.state().active).toEqual(true);
component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
expect(component.state().value).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
});
it("Test Dropdown component - Select one item (twice)", function(){
const component = mount(<DropdownCore onChange={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Button').simulate('click');
expect(component.state().active).toEqual(true);
let item = component.findWhere(n => _findItem(n, 'you'));
item.simulate('mouseDown');
item.simulate('click');
expect(component.state().value).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
component.find('Button').simulate('click');
component.findWhere(n => _findItem(n, 'May')).simulate('mouseDown');
expect(component.state().value).toEqual('May');
expect(component.state().index).toEqual(0);
});
it("Test Dropdown component - Click with custon onClick Dropdown", function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} }>
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
component.find('Button').simulate('click');
component.findWhere(n => _findItem(n, 'you')).simulate('mouseDown');
});
it("Test Dropdown component - Simple Click on Dropdown with onBeforeChange(false)", function(){
const component = mount(<DropdownCore onChange={ function(){} } onBeforeChange={ function(){return false} }>
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
component.find('Button').simulate('click');
let item = component.findWhere(n => _findItem(n, 'you'));
item.simulate('mouseDown');
item.simulate('click');
});
it("Test Dropdown component - Simple Click on Dropdown with onBeforeChange(true)", function(){
const component = mount(<DropdownCore onChange={ function(){} } onBeforeChange={ function(){return true} }>
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
component.find('Button').simulate('click');
let item = component.findWhere(n => _findItem(n, 'you'));
item.simulate('mouseDown');
item.simulate('click');
});
});
describe("Test Dropdown component - Keyboard tests", () => {
it("Test Dropdown component - Select one item (only ArrowDown used)",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('be');
expect(component.state().output).toEqual('be');
expect(component.state().index).toEqual(3);
});
it("Test Dropdown component - Select one item (ArrowDown & ArrowUp used)",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
component.find('Dropdown').simulate('keyDown', {key: "ArrowUp"});
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('force');
expect(component.state().output).toEqual('force');
expect(component.state().index).toEqual(2);
});
it("Test Dropdown component - Select last item (only ArrowDown used)",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
for(let i=0; i<9; i++){
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
}
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('you');
expect(component.state().output).toEqual('you');
expect(component.state().index).toEqual(5);
});
it("Test Dropdown component - Select first item (going down & up with ArrowDown & Arrow up)",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
for(let i=0; i<9; i++){
component.find('Dropdown').simulate('keyDown', {key: "ArrowDown"});
}
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('you');
expect(component.state().output).toEqual('you');
expect(component.state().index).toEqual(5);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('you');
expect(component.state().active).toEqual(true);
for(let i=0; i<9; i++){
component.find('Dropdown').simulate('keyDown', {key: "ArrowUp"});
}
component.find('Dropdown').simulate('keyDown', {key: "Enter"});
expect(component.state().value).toEqual('May');
expect(component.state().output).toEqual('May');
expect(component.state().index).toEqual(0);
});
it("Test Dropdown component - Press unhandled key",function(){
const component = mount(<DropdownCore onChange={ function(){} } onClick={ function(){} } >
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
component.find('Dropdown').simulate('focus');
expect(component.state().output).toEqual('May');
expect(component.state().focus).toEqual(true);
component.find('Dropdown').simulate('keyDown', {key: "Ctrl"});
});
});
describe("Test Dropdown component - Window blur tests", () => {
it("Test Dropdown component - onBlur event test", function(){
const component = mount(<DropdownCore onChange={ function(){} }>
<span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
expect(component.state().value).toEqual('May');
expect(component.state().output).toEqual('May');
component.find('Dropdown').simulate('focus');
component.find('Dropdown').simulate('blur');
});
});
describe("Test Dropdown component - Dropdown Regression tests", () => {
it("Regression test for bug #249", function(){
expect( function(){ const component = mount(<DropdownCore></DropdownCore>); } ).toThrow(new Error("You must pass at least one child component to Dropdown"));
// expect.assertions(0);
});
});
describe("Test Dropdown component - Dropdown Regression tests", () => {
it("Regression test for bug #405", function(){
const component = mount(<DropdownCore isValid={false}><span value="May">May</span>
<span value="the">the</span>
<span value="force">force</span>
<span value="be">be</span>
<span value="with">with</span>
<span value="you">you</span>
</DropdownCore>);
expect(component.state().isValid).toEqual(false);
});
});
| Fix tests.
| packages/react-atlas-tests/dropdown/__tests__/dropdown.test.js | Fix tests. | <ide><path>ackages/react-atlas-tests/dropdown/__tests__/dropdown.test.js
<ide> <span value="you">you</span>
<ide> </DropdownCore>);
<ide>
<del> expect(component.state().value).toEqual(undefined);
<add> expect(component.state().value).toEqual("");
<ide> expect(component.state().output).toEqual('May');
<ide> });
<ide>
<ide> <span value="you">you</span>
<ide> </DropdownCore>);
<ide>
<del> expect(component.state().value).toEqual(undefined);
<add> expect(component.state().value).toEqual("");
<ide> expect(component.state().output).toEqual('May');
<ide>
<ide> component.find('Dropdown').simulate('focus'); |
|
Java | apache-2.0 | 0220af9867ea9768161977c3380f53ac67d2af24 | 0 | ahb0327/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,kool79/intellij-community,supersven/intellij-community,allotria/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,fnouama/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,izonder/intellij-community,holmes/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,caot/intellij-community,dslomov/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,adedayo/intellij-community,kool79/intellij-community,da1z/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,caot/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,jagguli/intellij-community,samthor/intellij-community,amith01994/intellij-community,vladmm/intellij-community,semonte/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,kdwink/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,da1z/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,supersven/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,tmpgit/intellij-community,caot/intellij-community,semonte/intellij-community,fnouama/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,izonder/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,kool79/intellij-community,apixandru/intellij-community,petteyg/intellij-community,petteyg/intellij-community,blademainer/intellij-community,kdwink/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,samthor/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,semonte/intellij-community,jagguli/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,kool79/intellij-community,kdwink/intellij-community,adedayo/intellij-community,caot/intellij-community,ibinti/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,samthor/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,caot/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,petteyg/intellij-community,suncycheng/intellij-community,semonte/intellij-community,signed/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,caot/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,samthor/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,da1z/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,da1z/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,blademainer/intellij-community,vladmm/intellij-community,da1z/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,supersven/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,hurricup/intellij-community,dslomov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,fnouama/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,adedayo/intellij-community,slisson/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,slisson/intellij-community,supersven/intellij-community,ryano144/intellij-community,retomerz/intellij-community,fitermay/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,izonder/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,fnouama/intellij-community,signed/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,semonte/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,diorcety/intellij-community,samthor/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,allotria/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,supersven/intellij-community,blademainer/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,FHannes/intellij-community,apixandru/intellij-community,dslomov/intellij-community,da1z/intellij-community,tmpgit/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,signed/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,asedunov/intellij-community,supersven/intellij-community,blademainer/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,diorcety/intellij-community,fitermay/intellij-community,kool79/intellij-community,slisson/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,dslomov/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,izonder/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,vladmm/intellij-community,allotria/intellij-community,youdonghai/intellij-community,semonte/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,signed/intellij-community,vladmm/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,fnouama/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,diorcety/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,signed/intellij-community,signed/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,retomerz/intellij-community,apixandru/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,allotria/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,jagguli/intellij-community,signed/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,caot/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ryano144/intellij-community,dslomov/intellij-community,signed/intellij-community,ahb0327/intellij-community,izonder/intellij-community,retomerz/intellij-community,semonte/intellij-community,tmpgit/intellij-community,signed/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,slisson/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ryano144/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,slisson/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,fitermay/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,semonte/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,xfournet/intellij-community,signed/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,ibinti/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,petteyg/intellij-community,ibinti/intellij-community,holmes/intellij-community,holmes/intellij-community,izonder/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,caot/intellij-community,jagguli/intellij-community,retomerz/intellij-community,robovm/robovm-studio,robovm/robovm-studio,amith01994/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,petteyg/intellij-community,diorcety/intellij-community,allotria/intellij-community,apixandru/intellij-community,da1z/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,samthor/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,robovm/robovm-studio,kool79/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ibinti/intellij-community,vladmm/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,signed/intellij-community,petteyg/intellij-community,dslomov/intellij-community,jagguli/intellij-community,holmes/intellij-community,blademainer/intellij-community,kdwink/intellij-community,adedayo/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,ibinti/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,adedayo/intellij-community,apixandru/intellij-community,nicolargo/intellij-community | package com.jetbrains.python.run;
import com.google.common.collect.Lists;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configuration.AbstractRunConfiguration;
import com.intellij.execution.configuration.EnvironmentVariablesComponent;
import com.intellij.execution.configurations.*;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.options.SettingsEditorGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizerUtil;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PlatformUtils;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PythonModuleTypeBase;
import com.intellij.util.PathMappingSettings;
import com.jetbrains.python.sdk.PythonEnvUtil;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Leonid Shalupov
*/
public abstract class AbstractPythonRunConfiguration<T extends AbstractRunConfiguration> extends AbstractRunConfiguration
implements LocatableConfiguration, AbstractPythonRunConfigurationParams, CommandLinePatcher {
private String myInterpreterOptions = "";
private String myWorkingDirectory = "";
private String mySdkHome = "";
private boolean myUseModuleSdk;
private boolean myAddContentRoots = true;
private boolean myAddSourceRoots = true;
protected PathMappingSettings myMappingSettings;
public AbstractPythonRunConfiguration(Project project, final ConfigurationFactory factory) {
super(project, factory);
getConfigurationModule().init();
}
public List<Module> getValidModules() {
return getValidModules(getProject());
}
public PathMappingSettings getMappingSettings() {
return myMappingSettings;
}
public void setMappingSettings(@Nullable PathMappingSettings mappingSettings) {
myMappingSettings = mappingSettings;
}
public static List<Module> getValidModules(Project project) {
final Module[] modules = ModuleManager.getInstance(project).getModules();
List<Module> result = Lists.newArrayList();
for (Module module : modules) {
if (PythonSdkType.findPythonSdk(module) != null) {
result.add(module);
}
}
return result;
}
public PyCommonOptionsFormData getCommonOptionsFormData() {
return new PyCommonOptionsFormData() {
@Override
public Project getProject() {
return AbstractPythonRunConfiguration.this.getProject();
}
@Override
public List<Module> getValidModules() {
return AbstractPythonRunConfiguration.this.getValidModules();
}
@Override
public boolean showConfigureInterpretersLink() {
return false;
}
};
}
@NotNull
@Override
public final SettingsEditor<T> getConfigurationEditor() {
final SettingsEditor<T> runConfigurationEditor = createConfigurationEditor();
final SettingsEditorGroup<T> group = new SettingsEditorGroup<T>();
// run configuration settings tab:
group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), runConfigurationEditor);
// tabs provided by extensions:
//noinspection unchecked
PythonRunConfigurationExtensionsManager.getInstance().appendEditors(this, (SettingsEditorGroup)group);
if (group.getEditors().size() > 0) {
return group;
}
return runConfigurationEditor;
}
protected abstract SettingsEditor<T> createConfigurationEditor();
@Override
public void checkConfiguration() throws RuntimeConfigurationException {
super.checkConfiguration();
checkSdk();
checkExtensions();
}
private void checkExtensions() throws RuntimeConfigurationException {
try {
PythonRunConfigurationExtensionsManager.getInstance().validateConfiguration(this, false);
}
catch (RuntimeConfigurationException e) {
throw e;
}
catch (Exception ee) {
throw new RuntimeConfigurationException(ee.getMessage());
}
}
private void checkSdk() throws RuntimeConfigurationError {
if (PlatformUtils.isPyCharm()) {
final String path = getInterpreterPath();
if (path == null) {
throw new RuntimeConfigurationError("Please select a valid Python interpreter");
}
}
else {
if (!myUseModuleSdk) {
if (StringUtil.isEmptyOrSpaces(getSdkHome())) {
final Sdk projectSdk = ProjectRootManager.getInstance(getProject()).getProjectSdk();
if (projectSdk == null || !(projectSdk.getSdkType() instanceof PythonSdkType)) {
throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_sdk"));
}
}
else if (!PythonSdkType.getInstance().isValidSdkHome(getSdkHome())) {
throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_valid_sdk"));
}
}
else {
Sdk sdk = PythonSdkType.findPythonSdk(getModule());
if (sdk == null) {
throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_module_sdk"));
}
}
}
}
public String getSdkHome() {
String sdkHome = mySdkHome;
if (StringUtil.isEmptyOrSpaces(mySdkHome)) {
final Sdk projectJdk = PythonSdkType.findPythonSdk(getModule());
if (projectJdk != null) {
sdkHome = projectJdk.getHomePath();
}
}
return sdkHome;
}
@Nullable
public String getInterpreterPath() {
String sdkHome;
if (myUseModuleSdk) {
Sdk sdk = PythonSdkType.findPythonSdk(getModule());
if (sdk == null) return null;
sdkHome = sdk.getHomePath();
}
else {
sdkHome = getSdkHome();
}
return sdkHome;
}
public Sdk getSdk() {
if (myUseModuleSdk) {
return PythonSdkType.findPythonSdk(getModule());
}
else {
return PythonSdkType.findSdkByPath(getSdkHome());
}
}
public void readExternal(Element element) throws InvalidDataException {
super.readExternal(element);
myInterpreterOptions = JDOMExternalizerUtil.readField(element, "INTERPRETER_OPTIONS");
readEnvs(element);
mySdkHome = JDOMExternalizerUtil.readField(element, "SDK_HOME");
myWorkingDirectory = JDOMExternalizerUtil.readField(element, "WORKING_DIRECTORY");
myUseModuleSdk = Boolean.parseBoolean(JDOMExternalizerUtil.readField(element, "IS_MODULE_SDK"));
final String addContentRoots = JDOMExternalizerUtil.readField(element, "ADD_CONTENT_ROOTS");
myAddContentRoots = addContentRoots == null || Boolean.parseBoolean(addContentRoots);
final String addSourceRoots = JDOMExternalizerUtil.readField(element, "ADD_SOURCE_ROOTS");
myAddSourceRoots = addSourceRoots == null|| Boolean.parseBoolean(addSourceRoots);
getConfigurationModule().readExternal(element);
setMappingSettings(PathMappingSettings.readExternal(element));
// extension settings:
PythonRunConfigurationExtensionsManager.getInstance().readExternal(this, element);
}
protected void readEnvs(Element element) {
final String parentEnvs = JDOMExternalizerUtil.readField(element, "PARENT_ENVS");
if (parentEnvs != null) {
setPassParentEnvs(Boolean.parseBoolean(parentEnvs));
}
EnvironmentVariablesComponent.readExternal(element, getEnvs());
}
public void writeExternal(Element element) throws WriteExternalException {
super.writeExternal(element);
JDOMExternalizerUtil.writeField(element, "INTERPRETER_OPTIONS", myInterpreterOptions);
writeEnvs(element);
JDOMExternalizerUtil.writeField(element, "SDK_HOME", mySdkHome);
JDOMExternalizerUtil.writeField(element, "WORKING_DIRECTORY", myWorkingDirectory);
JDOMExternalizerUtil.writeField(element, "IS_MODULE_SDK", Boolean.toString(myUseModuleSdk));
JDOMExternalizerUtil.writeField(element, "ADD_CONTENT_ROOTS", Boolean.toString(myAddContentRoots));
JDOMExternalizerUtil.writeField(element, "ADD_SOURCE_ROOTS", Boolean.toString(myAddSourceRoots));
getConfigurationModule().writeExternal(element);
// extension settings:
PythonRunConfigurationExtensionsManager.getInstance().writeExternal(this, element);
PathMappingSettings.writeExternal(element, getMappingSettings());
}
protected void writeEnvs(Element element) {
JDOMExternalizerUtil.writeField(element, "PARENT_ENVS", Boolean.toString(isPassParentEnvs()));
EnvironmentVariablesComponent.writeExternal(element, getEnvs());
}
public String getInterpreterOptions() {
return myInterpreterOptions;
}
public void setInterpreterOptions(String interpreterOptions) {
myInterpreterOptions = interpreterOptions;
}
public String getWorkingDirectory() {
return myWorkingDirectory;
}
public void setWorkingDirectory(String workingDirectory) {
myWorkingDirectory = workingDirectory;
}
public void setSdkHome(String sdkHome) {
mySdkHome = sdkHome;
}
public Module getModule() {
return getConfigurationModule().getModule();
}
public boolean isUseModuleSdk() {
return myUseModuleSdk;
}
public void setUseModuleSdk(boolean useModuleSdk) {
myUseModuleSdk = useModuleSdk;
}
@Override
public boolean addContentRoots() {
return myAddContentRoots;
}
@Override
public boolean addSourceRoots() {
return myAddSourceRoots;
}
@Override
public void addSourceRoots(boolean add) {
myAddSourceRoots = add;
}
@Override
public void addContentRoots(boolean add) {
myAddContentRoots = add;
}
public static void copyParams(AbstractPythonRunConfigurationParams source, AbstractPythonRunConfigurationParams target) {
target.setEnvs(new HashMap<String, String>(source.getEnvs()));
target.setInterpreterOptions(source.getInterpreterOptions());
target.setPassParentEnvs(source.isPassParentEnvs());
target.setSdkHome(source.getSdkHome());
target.setWorkingDirectory(source.getWorkingDirectory());
target.setModule(source.getModule());
target.setUseModuleSdk(source.isUseModuleSdk());
target.setMappingSettings(source.getMappingSettings());
target.addContentRoots(source.addContentRoots());
target.addSourceRoots(source.addSourceRoots());
}
/**
* Some setups (e.g. virtualenv) provide a script that alters environment variables before running a python interpreter or other tools.
* Such settings are not directly stored but applied right before running using this method.
*
* @param commandLine what to patch
*/
public void patchCommandLine(GeneralCommandLine commandLine) {
final String interpreterPath = getInterpreterPath();
Sdk sdk = getSdk();
if (sdk != null && interpreterPath != null) {
patchCommandLineFirst(commandLine, interpreterPath);
patchCommandLineForVirtualenv(commandLine, interpreterPath);
patchCommandLineForBuildout(commandLine, interpreterPath);
patchCommandLineLast(commandLine, interpreterPath);
}
}
/**
* Patches command line before virtualenv and buildout patchers.
* Default implementation does nothing.
*
* @param commandLine
* @param sdk_home
*/
protected void patchCommandLineFirst(GeneralCommandLine commandLine, String sdk_home) {
// override
}
/**
* Patches command line after virtualenv and buildout patchers.
* Default implementation does nothing.
*
* @param commandLine
* @param sdk_home
*/
protected void patchCommandLineLast(GeneralCommandLine commandLine, String sdk_home) {
// override
}
/**
* Gets called after {@link #patchCommandLineForVirtualenv(com.intellij.openapi.projectRoots.SdkType, com.intellij.openapi.projectRoots.SdkType)}
* Does nothing here, real implementations should use alter running script name or use engulfer.
*
* @param commandLine
* @param sdkHome
*/
protected void patchCommandLineForBuildout(GeneralCommandLine commandLine, String sdkHome) {
}
/**
* Alters PATH so that a virtualenv is activated, if present.
*
* @param commandLine
* @param sdkHome
*/
protected void patchCommandLineForVirtualenv(GeneralCommandLine commandLine, String sdkHome) {
PythonSdkType.patchCommandLineForVirtualenv(commandLine, sdkHome, isPassParentEnvs());
}
protected void setUnbufferedEnv() {
Map<String, String> envs = getEnvs();
// unbuffered I/O is easier for IDE to handle
PythonEnvUtil.setPythonUnbuffered(envs);
}
@Override
public boolean excludeCompileBeforeLaunchOption() {
final Module module = getModule();
return module != null ? ModuleType.get(module) instanceof PythonModuleTypeBase : true;
}
public boolean canRunWithCoverage() {
return true;
}
}
| python/src/com/jetbrains/python/run/AbstractPythonRunConfiguration.java | package com.jetbrains.python.run;
import com.google.common.collect.Lists;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configuration.AbstractRunConfiguration;
import com.intellij.execution.configuration.EnvironmentVariablesComponent;
import com.intellij.execution.configurations.*;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.options.SettingsEditorGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizerUtil;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PlatformUtils;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PythonModuleTypeBase;
import com.intellij.util.PathMappingSettings;
import com.jetbrains.python.sdk.PythonEnvUtil;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jdom.Element;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Leonid Shalupov
*/
public abstract class AbstractPythonRunConfiguration<T extends AbstractRunConfiguration> extends AbstractRunConfiguration
implements LocatableConfiguration, AbstractPythonRunConfigurationParams, CommandLinePatcher {
private String myInterpreterOptions = "";
private String myWorkingDirectory = "";
private String mySdkHome = "";
private boolean myUseModuleSdk;
private boolean myAddContentRoots = true;
private boolean myAddSourceRoots = true;
protected PathMappingSettings myMappingSettings;
public AbstractPythonRunConfiguration(Project project, final ConfigurationFactory factory) {
super(project, factory);
getConfigurationModule().init();
}
public List<Module> getValidModules() {
return getValidModules(getProject());
}
public PathMappingSettings getMappingSettings() {
return myMappingSettings;
}
public void setMappingSettings(@Nullable PathMappingSettings mappingSettings) {
myMappingSettings = mappingSettings;
}
public static List<Module> getValidModules(Project project) {
final Module[] modules = ModuleManager.getInstance(project).getModules();
List<Module> result = Lists.newArrayList();
for (Module module : modules) {
if (PythonSdkType.findPythonSdk(module) != null) {
result.add(module);
}
}
return result;
}
public PyCommonOptionsFormData getCommonOptionsFormData() {
return new PyCommonOptionsFormData() {
@Override
public Project getProject() {
return AbstractPythonRunConfiguration.this.getProject();
}
@Override
public List<Module> getValidModules() {
return AbstractPythonRunConfiguration.this.getValidModules();
}
@Override
public boolean showConfigureInterpretersLink() {
return false;
}
};
}
@Override
public final SettingsEditor<T> getConfigurationEditor() {
final SettingsEditor<T> runConfigurationEditor = createConfigurationEditor();
final SettingsEditorGroup<T> group = new SettingsEditorGroup<T>();
// run configuration settings tab:
group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), runConfigurationEditor);
// tabs provided by extensions:
//noinspection unchecked
PythonRunConfigurationExtensionsManager.getInstance().appendEditors(this, (SettingsEditorGroup)group);
if (group.getEditors().size() > 0) {
return group;
}
return runConfigurationEditor;
}
protected abstract SettingsEditor<T> createConfigurationEditor();
@Override
public void checkConfiguration() throws RuntimeConfigurationException {
super.checkConfiguration();
checkSdk();
checkExtensions();
}
private void checkExtensions() throws RuntimeConfigurationException {
try {
PythonRunConfigurationExtensionsManager.getInstance().validateConfiguration(this, false);
}
catch (RuntimeConfigurationException e) {
throw e;
}
catch (Exception ee) {
throw new RuntimeConfigurationException(ee.getMessage());
}
}
private void checkSdk() throws RuntimeConfigurationError {
if (PlatformUtils.isPyCharm()) {
final String path = getInterpreterPath();
if (path == null) {
throw new RuntimeConfigurationError("Please select a valid Python interpreter");
}
}
else {
if (!myUseModuleSdk) {
if (StringUtil.isEmptyOrSpaces(getSdkHome())) {
final Sdk projectSdk = ProjectRootManager.getInstance(getProject()).getProjectSdk();
if (projectSdk == null || !(projectSdk.getSdkType() instanceof PythonSdkType)) {
throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_sdk"));
}
}
else if (!PythonSdkType.getInstance().isValidSdkHome(getSdkHome())) {
throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_valid_sdk"));
}
}
else {
Sdk sdk = PythonSdkType.findPythonSdk(getModule());
if (sdk == null) {
throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_module_sdk"));
}
}
}
}
public String getSdkHome() {
String sdkHome = mySdkHome;
if (StringUtil.isEmptyOrSpaces(mySdkHome)) {
final Sdk projectJdk = PythonSdkType.findPythonSdk(getModule());
if (projectJdk != null) {
sdkHome = projectJdk.getHomePath();
}
}
return sdkHome;
}
@Nullable
public String getInterpreterPath() {
String sdkHome;
if (myUseModuleSdk) {
Sdk sdk = PythonSdkType.findPythonSdk(getModule());
if (sdk == null) return null;
sdkHome = sdk.getHomePath();
}
else {
sdkHome = getSdkHome();
}
return sdkHome;
}
public Sdk getSdk() {
if (myUseModuleSdk) {
return PythonSdkType.findPythonSdk(getModule());
}
else {
return PythonSdkType.findSdkByPath(getSdkHome());
}
}
public void readExternal(Element element) throws InvalidDataException {
super.readExternal(element);
myInterpreterOptions = JDOMExternalizerUtil.readField(element, "INTERPRETER_OPTIONS");
readEnvs(element);
mySdkHome = JDOMExternalizerUtil.readField(element, "SDK_HOME");
myWorkingDirectory = JDOMExternalizerUtil.readField(element, "WORKING_DIRECTORY");
myUseModuleSdk = Boolean.parseBoolean(JDOMExternalizerUtil.readField(element, "IS_MODULE_SDK"));
final String addContentRoots = JDOMExternalizerUtil.readField(element, "ADD_CONTENT_ROOTS");
myAddContentRoots = addContentRoots == null || Boolean.parseBoolean(addContentRoots);
final String addSourceRoots = JDOMExternalizerUtil.readField(element, "ADD_SOURCE_ROOTS");
myAddSourceRoots = addSourceRoots == null|| Boolean.parseBoolean(addSourceRoots);
getConfigurationModule().readExternal(element);
setMappingSettings(PathMappingSettings.readExternal(element));
// extension settings:
PythonRunConfigurationExtensionsManager.getInstance().readExternal(this, element);
}
protected void readEnvs(Element element) {
final String parentEnvs = JDOMExternalizerUtil.readField(element, "PARENT_ENVS");
if (parentEnvs != null) {
setPassParentEnvs(Boolean.parseBoolean(parentEnvs));
}
EnvironmentVariablesComponent.readExternal(element, getEnvs());
}
public void writeExternal(Element element) throws WriteExternalException {
super.writeExternal(element);
JDOMExternalizerUtil.writeField(element, "INTERPRETER_OPTIONS", myInterpreterOptions);
writeEnvs(element);
JDOMExternalizerUtil.writeField(element, "SDK_HOME", mySdkHome);
JDOMExternalizerUtil.writeField(element, "WORKING_DIRECTORY", myWorkingDirectory);
JDOMExternalizerUtil.writeField(element, "IS_MODULE_SDK", Boolean.toString(myUseModuleSdk));
JDOMExternalizerUtil.writeField(element, "ADD_CONTENT_ROOTS", Boolean.toString(myAddContentRoots));
JDOMExternalizerUtil.writeField(element, "ADD_SOURCE_ROOTS", Boolean.toString(myAddSourceRoots));
getConfigurationModule().writeExternal(element);
// extension settings:
PythonRunConfigurationExtensionsManager.getInstance().writeExternal(this, element);
PathMappingSettings.writeExternal(element, getMappingSettings());
}
protected void writeEnvs(Element element) {
JDOMExternalizerUtil.writeField(element, "PARENT_ENVS", Boolean.toString(isPassParentEnvs()));
EnvironmentVariablesComponent.writeExternal(element, getEnvs());
}
public String getInterpreterOptions() {
return myInterpreterOptions;
}
public void setInterpreterOptions(String interpreterOptions) {
myInterpreterOptions = interpreterOptions;
}
public String getWorkingDirectory() {
return myWorkingDirectory;
}
public void setWorkingDirectory(String workingDirectory) {
myWorkingDirectory = workingDirectory;
}
public void setSdkHome(String sdkHome) {
mySdkHome = sdkHome;
}
public Module getModule() {
return getConfigurationModule().getModule();
}
public boolean isUseModuleSdk() {
return myUseModuleSdk;
}
public void setUseModuleSdk(boolean useModuleSdk) {
myUseModuleSdk = useModuleSdk;
}
@Override
public boolean addContentRoots() {
return myAddContentRoots;
}
@Override
public boolean addSourceRoots() {
return myAddSourceRoots;
}
@Override
public void addSourceRoots(boolean add) {
myAddSourceRoots = add;
}
@Override
public void addContentRoots(boolean add) {
myAddContentRoots = add;
}
public static void copyParams(AbstractPythonRunConfigurationParams source, AbstractPythonRunConfigurationParams target) {
target.setEnvs(new HashMap<String, String>(source.getEnvs()));
target.setInterpreterOptions(source.getInterpreterOptions());
target.setPassParentEnvs(source.isPassParentEnvs());
target.setSdkHome(source.getSdkHome());
target.setWorkingDirectory(source.getWorkingDirectory());
target.setModule(source.getModule());
target.setUseModuleSdk(source.isUseModuleSdk());
target.setMappingSettings(source.getMappingSettings());
target.addContentRoots(source.addContentRoots());
target.addSourceRoots(source.addSourceRoots());
}
/**
* Some setups (e.g. virtualenv) provide a script that alters environment variables before running a python interpreter or other tools.
* Such settings are not directly stored but applied right before running using this method.
*
* @param commandLine what to patch
*/
public void patchCommandLine(GeneralCommandLine commandLine) {
final String interpreterPath = getInterpreterPath();
Sdk sdk = getSdk();
if (sdk != null && interpreterPath != null) {
patchCommandLineFirst(commandLine, interpreterPath);
patchCommandLineForVirtualenv(commandLine, interpreterPath);
patchCommandLineForBuildout(commandLine, interpreterPath);
patchCommandLineLast(commandLine, interpreterPath);
}
}
/**
* Patches command line before virtualenv and buildout patchers.
* Default implementation does nothing.
*
* @param commandLine
* @param sdk_home
*/
protected void patchCommandLineFirst(GeneralCommandLine commandLine, String sdk_home) {
// override
}
/**
* Patches command line after virtualenv and buildout patchers.
* Default implementation does nothing.
*
* @param commandLine
* @param sdk_home
*/
protected void patchCommandLineLast(GeneralCommandLine commandLine, String sdk_home) {
// override
}
/**
* Gets called after {@link #patchCommandLineForVirtualenv(com.intellij.openapi.projectRoots.SdkType, com.intellij.openapi.projectRoots.SdkType)}
* Does nothing here, real implementations should use alter running script name or use engulfer.
*
* @param commandLine
* @param sdkHome
*/
protected void patchCommandLineForBuildout(GeneralCommandLine commandLine, String sdkHome) {
}
/**
* Alters PATH so that a virtualenv is activated, if present.
*
* @param commandLine
* @param sdkHome
*/
protected void patchCommandLineForVirtualenv(GeneralCommandLine commandLine, String sdkHome) {
PythonSdkType.patchCommandLineForVirtualenv(commandLine, sdkHome, isPassParentEnvs());
}
protected void setUnbufferedEnv() {
Map<String, String> envs = getEnvs();
// unbuffered I/O is easier for IDE to handle
PythonEnvUtil.setPythonUnbuffered(envs);
}
@Override
public boolean excludeCompileBeforeLaunchOption() {
final Module module = getModule();
return module != null ? ModuleType.get(module) instanceof PythonModuleTypeBase : true;
}
public boolean canRunWithCoverage() {
return true;
}
}
| @NotNull RunConfiguration.getSettingsEditor()
| python/src/com/jetbrains/python/run/AbstractPythonRunConfiguration.java | @NotNull RunConfiguration.getSettingsEditor() | <ide><path>ython/src/com/jetbrains/python/run/AbstractPythonRunConfiguration.java
<ide> import com.jetbrains.python.sdk.PythonEnvUtil;
<ide> import com.jetbrains.python.sdk.PythonSdkType;
<ide> import org.jdom.Element;
<add>import org.jetbrains.annotations.NotNull;
<ide> import org.jetbrains.annotations.Nullable;
<ide>
<ide> import java.util.HashMap;
<ide> };
<ide> }
<ide>
<add> @NotNull
<ide> @Override
<ide> public final SettingsEditor<T> getConfigurationEditor() {
<ide> final SettingsEditor<T> runConfigurationEditor = createConfigurationEditor(); |
|
Java | mit | 8468cca20b84319c64bc307f8630d5c2be563a15 | 0 | CS2103JAN2017-F12-B2/main,CS2103JAN2017-F12-B2/main | package seedu.address.model.util;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.ReadOnlyToDoApp;
import seedu.address.model.ToDoApp;
import seedu.address.model.person.Deadline;
import seedu.address.model.person.Name;
import seedu.address.model.person.Start;
import seedu.address.model.person.Task;
import seedu.address.model.person.UniqueTaskList.DuplicateTaskException;
import seedu.address.model.tag.UniqueTagList;
public class SampleDataUtil {
public static Task[] getSampleTasks() {
try {
return new Task[] {
new Task(new Name("Buy printer"), new Start("today"), new Deadline("tomorrow"),
new UniqueTagList("shopping")),
new Task(new Name("Go to the gym"), new Start(""), new Deadline(""),
new UniqueTagList("exercise")),
};
} catch (IllegalValueException e) {
throw new AssertionError("sample data cannot be invalid", e);
}
}
public static ReadOnlyToDoApp getSampleToDoApp() {
try {
ToDoApp sampleTDA = new ToDoApp();
for (Task sampleTask : getSampleTasks()) {
sampleTDA.addTask(sampleTask);
}
return sampleTDA;
} catch (DuplicateTaskException e) {
throw new AssertionError("sample data cannot contain duplicate tasks", e);
}
}
}
| src/main/java/seedu/address/model/util/SampleDataUtil.java | package seedu.address.model.util;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.ReadOnlyToDoApp;
import seedu.address.model.ToDoApp;
import seedu.address.model.person.Deadline;
import seedu.address.model.person.Name;
import seedu.address.model.person.Task;
import seedu.address.model.person.UniqueTaskList.DuplicateTaskException;
import seedu.address.model.tag.UniqueTagList;
public class SampleDataUtil {
public static Task[] getSampleTasks() {
try {
return new Task[] {
new Task(new Name("Buy printer"), new Deadline(""),
new UniqueTagList("shopping")),
new Task(new Name("Go to the gym"), new Deadline(""),
new UniqueTagList("exercise")),
};
} catch (IllegalValueException e) {
throw new AssertionError("sample data cannot be invalid", e);
}
}
public static ReadOnlyToDoApp getSampleToDoApp() {
try {
ToDoApp sampleTDA = new ToDoApp();
for (Task sampleTask : getSampleTasks()) {
sampleTDA.addTask(sampleTask);
}
return sampleTDA;
} catch (DuplicateTaskException e) {
throw new AssertionError("sample data cannot contain duplicate tasks", e);
}
}
}
| Update SampleDataUtil with Start
| src/main/java/seedu/address/model/util/SampleDataUtil.java | Update SampleDataUtil with Start | <ide><path>rc/main/java/seedu/address/model/util/SampleDataUtil.java
<ide> import seedu.address.model.ToDoApp;
<ide> import seedu.address.model.person.Deadline;
<ide> import seedu.address.model.person.Name;
<add>import seedu.address.model.person.Start;
<ide> import seedu.address.model.person.Task;
<ide> import seedu.address.model.person.UniqueTaskList.DuplicateTaskException;
<ide> import seedu.address.model.tag.UniqueTagList;
<ide> public static Task[] getSampleTasks() {
<ide> try {
<ide> return new Task[] {
<del> new Task(new Name("Buy printer"), new Deadline(""),
<add> new Task(new Name("Buy printer"), new Start("today"), new Deadline("tomorrow"),
<ide> new UniqueTagList("shopping")),
<del> new Task(new Name("Go to the gym"), new Deadline(""),
<add> new Task(new Name("Go to the gym"), new Start(""), new Deadline(""),
<ide> new UniqueTagList("exercise")),
<ide> };
<ide> } catch (IllegalValueException e) { |
|
JavaScript | mit | 24cd93ee66f5fd4813f82f4efa08f82f6e4d269c | 0 | yieldbot/ferret,yieldbot/ferret,yieldbot/ferret,yieldbot/ferret | /*
* Ferret
* Copyright (c) 2016 Yieldbot, Inc.
* For the full copyright and license information, please view the LICENSE.txt file.
*/
/* jslint browser: true */
/* global document: false, $: false, Rx: false */
'use strict';
// Create the module
var app = function app() {
if(typeof $ != "function" || typeof Rx != "object") {
throw new Error("missing or invalid libraries (jQuery, Rx)");
}
// Init vars
var serverUrl = location.protocol + '//' + location.hostname + ':' + location.port;
serverUrl = (location.protocol == 'file:') ? 'http://localhost:3030' : serverUrl; // for debug
// init initializes the app
function init() {
// Get providers
getProviders().then(
function(data) {
if(data && data instanceof Array && data.length > 0) {
// Listen for search requests
listen(data);
} else {
critical("There is no any available provider to search");
}
},
function(err) {
var e = parseError(err);
critical("Could not get the available providers due to " + e.message + " (" + e.code + ")");
}
);
}
// listen listens search requests for the given providers
function listen(providers) {
// Create the observables
// Click button
var clickSource = Rx.Observable
.fromEvent($('#searchButton'), 'click')
.map(function() { return $('#searchInput').val(); });
// Input field
var inputSource = Rx.Observable
.fromEvent($('#searchInput'), 'keyup')
.filter(function(e) { return (e.keyCode == 13); })
.map(function(e) { return e.target.value; })
.filter(function(text) { return text.length > 2; })
.distinctUntilChanged()
.throttle(1000);
// Merge observables
var observable = Rx.Observable.merge(clickSource, inputSource);
// Check providers
if(providers instanceof Array && providers.length > 0) {
// Iterate providers
providers.forEach(function(provider) {
observable
.flatMapLatest(function(keyword) {
// Prepare UI
$("#logoMain").detach().appendTo($('#logoNavbarHolder')).addClass('logo-navbar');
$("#searchMain").detach().appendTo($("#searchNavbarHolder")).addClass('input-group-search-navbar');
$('#searchResults').empty();
// Exceptions
keyword = (provider.name == "github") ? keyword+'+extension:md' : keyword;
// Search
return search(provider.name, keyword);
})
.subscribe(
function(data) {
if(data && data instanceof Array) {
$('#searchResults').append($('<h3>').text((provider.title || '')));
$('#searchResults').append($.map(data, function (v) {
var content = '<a href="'+v.link+'" target="_blank">'+v.title+'</a>';
content += '<p>';
content += (v.description) ? encodeHtmlEntity(v.description)+'<br>' : '';
content += (v.date != "0001-01-01T00:00:00Z") ? '<span class="ts">'+(''+(new Date(v.date)).toISOString()).substr(0, 10)+'</span>' : '';
content += '</p>';
return $('<li class="search-results-li">').html(content);
}));
$('#searchResults').append($('<hr>'));
}
},
function(err) {
var e = parseError(err);
$('#searchResults').append($('<h3>').text((provider.title || '')));
$('#searchResults').append($('<div class="alert alert-danger" role="alert">').text(e.message));
}
);
});
}
$('#searchInput').focus();
}
// getProviders gets the provider list
function getProviders() {
return $.ajax({
url: serverUrl+'/providers',
dataType: 'jsonp',
method: 'GET',
}).promise();
}
// search makes a search by the given provider and keyword
function search(provider, keyword) {
return $.ajax({
url: serverUrl+'/search',
dataType: 'jsonp',
method: 'GET',
data: {
provider: (''+provider),
keyword: (''+keyword),
timeout: '5000ms',
limit: 10
}
}).promise();
}
// warning shows a warning message
function warning(message) {
$('#searchAlerts')
.html($('<div class="alert alert-warning search-alert" role="alert">')
.text(message));
}
// critical shows a critical message
function critical(message) {
$('#searchAlerts')
.html($('<div class="alert alert-danger search-alert" role="alert">')
.text(message));
}
// parseError parses the given error message and returns an object
function parseError(err) {
var code = 0,
message = 'unknown error';
if(err && typeof err == 'object') {
code = err.status || code;
message = err.statusText || err.message || message;
if(typeof err.responseJSON == 'object') {
message = err.responseJSON.message || err.responseJSON.error || message;
}
}
return {code: code, message: message};
}
// encodeHtmlEntity encodes HTML entity
function encodeHtmlEntity(str) {
return str.replace(/[\u00A0-\u9999\\<\>\&\'\"\\\/]/gim, function(c){
return '&#' + c.charCodeAt(0) + ';' ;
});
}
// Return
return {
init: init,
warning: warning,
critical: critical
};
};
$(document).ready(function() {
app().init();
}); | assets/public/js/app.js | /*
* Ferret
* Copyright (c) 2016 Yieldbot, Inc.
* For the full copyright and license information, please view the LICENSE.txt file.
*/
/* jslint browser: true */
/* global document: false, $: false, Rx: false */
'use strict';
// Create the module
var app = function app() {
if(typeof $ != "function" || typeof Rx != "object") {
throw new Error("missing or invalid libraries (jQuery, Rx)");
}
// Init vars
var serverUrl = location.protocol + '//' + location.hostname + ':' + location.port;
serverUrl = (location.protocol == 'file:') ? 'http://localhost:3030' : serverUrl; // for debug
// init initializes the app
function init() {
// Get providers
getProviders().then(
function(data) {
if(data && data instanceof Array && data.length > 0) {
// Listen for search requests
listen(data);
} else {
critical("There is no any available provider to search");
}
},
function(err) {
var e = parseError(err);
critical("Could not get the available providers due to " + e.message + " (" + e.code + ")");
}
);
}
// listen listens search requests for the given providers
function listen(providers) {
// Create the observables
// Click button
var clickSource = Rx.Observable
.fromEvent($('#searchButton'), 'click')
.map(function() { return $('#searchInput').val(); });
// Input field
var inputSource = Rx.Observable
.fromEvent($('#searchInput'), 'keyup')
.filter(function(e) { return (e.keyCode == 13); })
.map(function(e) { return e.target.value; })
.filter(function(text) { return text.length > 2; })
.distinctUntilChanged()
.throttle(1000);
// Merge observables
var observable = Rx.Observable.merge(clickSource, inputSource);
// Check providers
if(providers instanceof Array && providers.length > 0) {
// Iterate providers
providers.forEach(function(provider) {
observable
.flatMapLatest(function(keyword) {
// Prepare UI
$("#logoMain").detach().appendTo($('#logoNavbarHolder')).addClass('logo-navbar');
$("#searchMain").detach().appendTo($("#searchNavbarHolder")).addClass('input-group-search-navbar');
$('#searchResults').empty();
// Exceptions
keyword = (provider.name == "github") ? keyword+'+extension:md' : keyword;
// Search
return search(provider.name, keyword);
})
.subscribe(
function(data) {
if(data && data instanceof Array) {
$('#searchResults').append($('<h3>').text((provider.title || '')));
$('#searchResults').append($.map(data, function (v) {
var content = '<a href="'+v.Link+'" target="_blank">'+v.Title+'</a>';
content += '<p>';
content += (v.Description) ? encodeHtmlEntity(v.Description)+'<br>' : '';
content += (v.Date != "0001-01-01T00:00:00Z") ? '<span class="ts">'+(''+(new Date(v.Date)).toISOString()).substr(0, 10)+'</span>' : '';
content += '</p>';
return $('<li class="search-results-li">').html(content);
}));
$('#searchResults').append($('<hr>'));
}
},
function(err) {
var e = parseError(err);
$('#searchResults').append($('<h3>').text((provider.title || '')));
$('#searchResults').append($('<div class="alert alert-danger" role="alert">').text(e.message));
}
);
});
}
$('#searchInput').focus();
}
// getProviders gets the provider list
function getProviders() {
return $.ajax({
url: serverUrl+'/providers',
dataType: 'jsonp',
method: 'GET',
}).promise();
}
// search makes a search by the given provider and keyword
function search(provider, keyword) {
return $.ajax({
url: serverUrl+'/search',
dataType: 'jsonp',
method: 'GET',
data: {
provider: (''+provider),
keyword: (''+keyword),
timeout: '5000ms',
limit: 10
}
}).promise();
}
// warning shows a warning message
function warning(message) {
$('#searchAlerts')
.html($('<div class="alert alert-warning search-alert" role="alert">')
.text(message));
}
// critical shows a critical message
function critical(message) {
$('#searchAlerts')
.html($('<div class="alert alert-danger search-alert" role="alert">')
.text(message));
}
// parseError parses the given error message and returns an object
function parseError(err) {
var code = 0,
message = 'unknown error';
if(err && typeof err == 'object') {
code = err.status || code;
message = err.statusText || err.message || message;
if(typeof err.responseJSON == 'object') {
message = err.responseJSON.message || err.responseJSON.error || message;
}
}
return {code: code, message: message};
}
// encodeHtmlEntity encodes HTML entity
function encodeHtmlEntity(str) {
return str.replace(/[\u00A0-\u9999\\<\>\&\'\"\\\/]/gim, function(c){
return '&#' + c.charCodeAt(0) + ';' ;
});
}
// Return
return {
init: init,
warning: warning,
critical: critical
};
};
$(document).ready(function() {
app().init();
}); | Fix field names for search results
| assets/public/js/app.js | Fix field names for search results | <ide><path>ssets/public/js/app.js
<ide> if(data && data instanceof Array) {
<ide> $('#searchResults').append($('<h3>').text((provider.title || '')));
<ide> $('#searchResults').append($.map(data, function (v) {
<del> var content = '<a href="'+v.Link+'" target="_blank">'+v.Title+'</a>';
<add> var content = '<a href="'+v.link+'" target="_blank">'+v.title+'</a>';
<ide> content += '<p>';
<del> content += (v.Description) ? encodeHtmlEntity(v.Description)+'<br>' : '';
<del> content += (v.Date != "0001-01-01T00:00:00Z") ? '<span class="ts">'+(''+(new Date(v.Date)).toISOString()).substr(0, 10)+'</span>' : '';
<add> content += (v.description) ? encodeHtmlEntity(v.description)+'<br>' : '';
<add> content += (v.date != "0001-01-01T00:00:00Z") ? '<span class="ts">'+(''+(new Date(v.date)).toISOString()).substr(0, 10)+'</span>' : '';
<ide> content += '</p>';
<ide>
<ide> return $('<li class="search-results-li">').html(content); |
|
Java | apache-2.0 | f9bc38a95e7786331c67caca03b38dee1cb818a7 | 0 | corbel-platform/lib-ws,corbel-platform/lib-ws,bq/lib-ws | package io.corbel.lib.ws.dw.ioc;
import io.dropwizard.jetty.GzipFilterFactory;
import io.dropwizard.jetty.HttpConnectorFactory;
import io.dropwizard.logging.AppenderFactory;
import io.dropwizard.logging.ConsoleAppenderFactory;
import io.dropwizard.logging.FileAppenderFactory;
import io.dropwizard.logging.LoggingFactory;
import io.dropwizard.logging.SyslogAppenderFactory;
import io.dropwizard.server.DefaultServerFactory;
import io.dropwizard.util.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import ch.qos.logback.classic.Level;
import com.google.common.collect.ImmutableList;
/**
* @author Alexander De Leon
*/
@Configuration public class DropwizardIoc {
@Autowired private Environment env;
@Bean
public DefaultServerFactory getHttpConfiguration() {
DefaultServerFactory configuration = new DefaultServerFactory();
((HttpConnectorFactory) configuration.getApplicationConnectors().get(0)).setPort(env.getProperty("dw.http.port", Integer.class,
8080));
((HttpConnectorFactory) configuration.getApplicationConnectors().get(0)).setMaxRequestHeaderSize(Size.kilobytes(env.getProperty(
"dw.http.maxRequestHeaderSize", Long.class, 16l)));
((HttpConnectorFactory) configuration.getAdminConnectors().get(0)).setPort(env
.getProperty("dw.http.adminPort", Integer.class, 8081));
configuration.getRequestLogFactory().setAppenders(getLogConfiguration());
configuration.setGzipFilterFactory(getGzipConfiguration());
configuration.setRegisterDefaultExceptionMappers(false);
return configuration;
}
@Bean
public LoggingFactory getLoggingConfiguration() {
LoggingFactory configuration = new LoggingFactory();
configuration.setLevel(getLogLevel("dw.logging.level", "INFO"));
configuration.setAppenders(getLogConfiguration());
return configuration;
}
private ImmutableList<AppenderFactory> getLogConfiguration() {
ImmutableList.Builder<AppenderFactory> appenders = ImmutableList.builder();
getConsoleConfiguration(appenders);
getSyslogConfiguration(appenders);
getFileConfiguration(appenders);
return appenders.build();
}
private void getConsoleConfiguration(ImmutableList.Builder<AppenderFactory> appenders) {
if (env.getProperty("dw.logging.console.enabled", Boolean.class, true)) {
ConsoleAppenderFactory configuration = new ConsoleAppenderFactory();
configuration.setThreshold(getLogLevel("dw.logging.console.threshold", "ALL"));
appenders.add(configuration);
}
}
private void getSyslogConfiguration(ImmutableList.Builder<AppenderFactory> appenders) {
if (env.getProperty("dw.logging.syslog.enabled", Boolean.class, true)) {
SyslogAppenderFactory configuration = new SyslogAppenderFactory();
configuration.setThreshold(getLogLevel("dw.logging.syslog.threshold", "ALL"));
appenders.add(configuration);
}
}
private void getFileConfiguration(ImmutableList.Builder<AppenderFactory> appenders) {
if (env.getProperty("dw.logging.file.enabled", Boolean.class, false)) {
FileAppenderFactory configuration = new FileAppenderFactory();
configuration.setThreshold(getLogLevel("dw.logging.file.threshold", "ALL"));
configuration.setCurrentLogFilename(env.getProperty("dw.logging.file.currentLogFilename", "./logs/app.log"));
configuration.setArchivedLogFilenamePattern(env.getProperty("dw.logging.file.archivedLogFilenamePattern",
"./logs/app-%d.log.gz"));
appenders.add(configuration);
}
}
private GzipFilterFactory getGzipConfiguration() {
GzipFilterFactory gzipConfiguration = new GzipFilterFactory();
gzipConfiguration.setEnabled(false);
return gzipConfiguration;
}
private Level getLogLevel(String property, String def) {
String level = env.getProperty(property, def);
return Level.toLevel(level);
}
}
| src/main/java/io/corbel/lib/ws/dw/ioc/DropwizardIoc.java | package io.corbel.lib.ws.dw.ioc;
import io.dropwizard.jetty.GzipFilterFactory;
import io.dropwizard.jetty.HttpConnectorFactory;
import io.dropwizard.logging.AppenderFactory;
import io.dropwizard.logging.ConsoleAppenderFactory;
import io.dropwizard.logging.FileAppenderFactory;
import io.dropwizard.logging.LoggingFactory;
import io.dropwizard.logging.SyslogAppenderFactory;
import io.dropwizard.server.DefaultServerFactory;
import io.dropwizard.util.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import ch.qos.logback.classic.Level;
import com.google.common.collect.ImmutableList;
/**
* @author Alexander De Leon
*/
@Configuration public class DropwizardIoc {
@Autowired private Environment env;
@Bean
public DefaultServerFactory getHttpConfiguration() {
DefaultServerFactory configuration = new DefaultServerFactory();
((HttpConnectorFactory) configuration.getApplicationConnectors().get(0)).setPort(env.getProperty("dw.http.port", Integer.class,
8080));
((HttpConnectorFactory) configuration.getApplicationConnectors().get(0)).setMaxRequestHeaderSize(Size.kilobytes(env
.getProperty("dw.http.maxRequestHeaderSize", Integer.class, 16)));
((HttpConnectorFactory) configuration.getAdminConnectors().get(0)).setPort(env
.getProperty("dw.http.adminPort", Integer.class, 8081));
configuration.getRequestLogFactory().setAppenders(getLogConfiguration());
configuration.setGzipFilterFactory(getGzipConfiguration());
configuration.setRegisterDefaultExceptionMappers(false);
return configuration;
}
@Bean
public LoggingFactory getLoggingConfiguration() {
LoggingFactory configuration = new LoggingFactory();
configuration.setLevel(getLogLevel("dw.logging.level", "INFO"));
configuration.setAppenders(getLogConfiguration());
return configuration;
}
private ImmutableList<AppenderFactory> getLogConfiguration() {
ImmutableList.Builder<AppenderFactory> appenders = ImmutableList.builder();
getConsoleConfiguration(appenders);
getSyslogConfiguration(appenders);
getFileConfiguration(appenders);
return appenders.build();
}
private void getConsoleConfiguration(ImmutableList.Builder<AppenderFactory> appenders) {
if (env.getProperty("dw.logging.console.enabled", Boolean.class, true)) {
ConsoleAppenderFactory configuration = new ConsoleAppenderFactory();
configuration.setThreshold(getLogLevel("dw.logging.console.threshold", "ALL"));
appenders.add(configuration);
}
}
private void getSyslogConfiguration(ImmutableList.Builder<AppenderFactory> appenders) {
if (env.getProperty("dw.logging.syslog.enabled", Boolean.class, true)) {
SyslogAppenderFactory configuration = new SyslogAppenderFactory();
configuration.setThreshold(getLogLevel("dw.logging.syslog.threshold", "ALL"));
appenders.add(configuration);
}
}
private void getFileConfiguration(ImmutableList.Builder<AppenderFactory> appenders) {
if (env.getProperty("dw.logging.file.enabled", Boolean.class, false)) {
FileAppenderFactory configuration = new FileAppenderFactory();
configuration.setThreshold(getLogLevel("dw.logging.file.threshold", "ALL"));
configuration.setCurrentLogFilename(env.getProperty("dw.logging.file.currentLogFilename", "./logs/app.log"));
configuration.setArchivedLogFilenamePattern(env.getProperty("dw.logging.file.archivedLogFilenamePattern",
"./logs/app-%d.log.gz"));
appenders.add(configuration);
}
}
private GzipFilterFactory getGzipConfiguration() {
GzipFilterFactory gzipConfiguration = new GzipFilterFactory();
gzipConfiguration.setEnabled(false);
return gzipConfiguration;
}
private Level getLogLevel(String property, String def) {
String level = env.getProperty(property, def);
return Level.toLevel(level);
}
}
| fix casting bug
Change-Id: I6eac1ee7308f5f537e465fb66029dab4d32ec585
| src/main/java/io/corbel/lib/ws/dw/ioc/DropwizardIoc.java | fix casting bug | <ide><path>rc/main/java/io/corbel/lib/ws/dw/ioc/DropwizardIoc.java
<ide> import io.dropwizard.logging.LoggingFactory;
<ide> import io.dropwizard.logging.SyslogAppenderFactory;
<ide> import io.dropwizard.server.DefaultServerFactory;
<add>import io.dropwizard.util.Size;
<ide>
<del>import io.dropwizard.util.Size;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide> DefaultServerFactory configuration = new DefaultServerFactory();
<ide> ((HttpConnectorFactory) configuration.getApplicationConnectors().get(0)).setPort(env.getProperty("dw.http.port", Integer.class,
<ide> 8080));
<del> ((HttpConnectorFactory) configuration.getApplicationConnectors().get(0)).setMaxRequestHeaderSize(Size.kilobytes(env
<del> .getProperty("dw.http.maxRequestHeaderSize", Integer.class, 16)));
<add> ((HttpConnectorFactory) configuration.getApplicationConnectors().get(0)).setMaxRequestHeaderSize(Size.kilobytes(env.getProperty(
<add> "dw.http.maxRequestHeaderSize", Long.class, 16l)));
<ide> ((HttpConnectorFactory) configuration.getAdminConnectors().get(0)).setPort(env
<ide> .getProperty("dw.http.adminPort", Integer.class, 8081));
<ide> configuration.getRequestLogFactory().setAppenders(getLogConfiguration()); |
|
Java | mit | e0e08761248e92dce7a079d439317fa69e6b696a | 0 | to2mbn/JMCCC,Southern-InfinityStudio/JMCCC,Darkyoooooo/JMCCC | package org.to2mbn.jmccc.version.parsing;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import org.to2mbn.jmccc.internal.org.json.JSONArray;
import org.to2mbn.jmccc.internal.org.json.JSONException;
import org.to2mbn.jmccc.internal.org.json.JSONObject;
import org.to2mbn.jmccc.version.Asset;
import org.to2mbn.jmccc.version.AssetIndexInfo;
import org.to2mbn.jmccc.version.DownloadInfo;
import org.to2mbn.jmccc.version.Library;
import org.to2mbn.jmccc.version.LibraryInfo;
import org.to2mbn.jmccc.version.Native;
import org.to2mbn.jmccc.version.Version;
class VersionParserImpl implements VersionParser {
@Override
public DownloadInfo parseDownloadInfo(JSONObject json) throws JSONException {
if (json == null) return null;
String url = json.optString("url", null);
String checksum = json.optString("sha1", null);
long size = json.optLong("size", -1);
return new DownloadInfo(url, checksum, size);
}
@Override
public AssetIndexInfo parseAssetIndexInfo(JSONObject json) throws JSONException {
if (json == null) return null;
DownloadInfo base = parseDownloadInfo(json);
String id = json.getString("id");
long totalSize = json.optLong("totalSize", -1);
return new AssetIndexInfo(base.getUrl(), base.getChecksum(), base.getSize(), id, totalSize);
}
@Override
public LibraryInfo parseLibraryInfo(JSONObject json) throws JSONException {
if (json == null) return null;
DownloadInfo base = parseDownloadInfo(json);
String path = json.optString("path", null);
return new LibraryInfo(base.getUrl(), base.getChecksum(), base.getSize(), path);
}
@Override
public Library parseLibrary(JSONObject json, PlatformDescription platformDescription) throws JSONException {
if (json == null) return null;
if (!checkAllowed(json.optJSONArray("rules"), platformDescription)
|| !json.optBoolean("clientreq", true)) {
return null;
}
String[] splitedGav = json.getString("name").split(":", 3);
String groupId = splitedGav[0];
String artifactId = splitedGav[1];
String version = splitedGav[2];
String url = json.optString("url", null);
String[] checksums = parseChecksums(json.optJSONArray("checksums"));
JSONObject jsonNatives = json.optJSONObject("natives");
boolean isNative = jsonNatives != null;
String classifier = isNative ? parseNativeClassifier(json.getJSONObject("natives"), platformDescription) : null;
LibraryInfo libinfo = parseLibraryDownloads(json.optJSONObject("downloads"), classifier);
String type = "jar";
if (isNative) {
Set<String> excludes = parseExtractExcludes(json.optJSONObject("extract"));
return new Native(groupId, artifactId, version, classifier, type, libinfo, url, checksums, excludes);
} else {
return new Library(groupId, artifactId, version, classifier, type, libinfo, url, checksums);
}
}
@Override
public Set<Asset> parseAssetIndex(JSONObject json) throws JSONException {
if (json == null) return null;
JSONObject objects = json.getJSONObject("objects");
Set<Asset> assets = new TreeSet<>(new Comparator<Asset>() {
@Override
public int compare(Asset o1, Asset o2) {
return o1.getVirtualPath().compareTo(o2.getVirtualPath());
}
});
for (Object rawVirtualPath : objects.keySet()) {
String virtualPath = (String) rawVirtualPath;
JSONObject object = objects.getJSONObject(virtualPath);
String hash = object.getString("hash");
int size = object.getInt("size");
assets.add(new Asset(virtualPath, hash, size));
}
return Collections.unmodifiableSet(assets);
}
@Override
public Version parseVersion(Stack<JSONObject> hierarchy, PlatformDescription platformDescription) throws JSONException {
String version = hierarchy.get(0).getString("id");
String root = hierarchy.peek().getString("id");
String assets = "legacy";
String mainClass = null;
String launchArgs = null;
String type = null;
Map<String, Library> librariesMap = new TreeMap<>();
Map<String, DownloadInfo> downloads = new TreeMap<>();
AssetIndexInfo assetIndexInfo = null;
JSONObject json;
do {
json = hierarchy.pop();
assets = json.optString("assets", assets);
mainClass = json.optString("mainClass", mainClass);
launchArgs = parseMinecraftArgs(json);
type = json.optString("type", type);
Set<Library> currentLibraries = parseLibraries(json.optJSONArray("libraries"), platformDescription);
if (currentLibraries != null) {
for (Library library : currentLibraries) {
StringBuilder libId = new StringBuilder();
libId.append(library.getGroupId()).append(':')
.append(library.getArtifactId());
if (library.getClassifier() != null)
libId.append(':').append(library.getClassifier());
librariesMap.put(libId.toString(), library);
}
}
Map<String, DownloadInfo> currentDownloads = parseDownloads(json.optJSONObject("downloads"));
if (currentDownloads != null)
downloads.putAll(currentDownloads);
JSONObject jsonAssetIndexInfo = json.optJSONObject("assetIndex");
if (jsonAssetIndexInfo != null)
assetIndexInfo = parseAssetIndexInfo(jsonAssetIndexInfo);
} while (!hierarchy.isEmpty());
if (mainClass == null)
throw new JSONException("Missing mainClass");
if (launchArgs == null)
throw new JSONException("Missing minecraftArguments");
Set<Library> libraries = new LinkedHashSet<>(librariesMap.values());
return new Version(version,
type,
mainClass,
assets,
launchArgs,
root,
Collections.unmodifiableSet(libraries),
assets.equals("legacy"),
assetIndexInfo,
Collections.unmodifiableMap(downloads));
}
@Override
public boolean checkAllowed(JSONArray rules, PlatformDescription platformDescription) throws JSONException {
// by default it's allowed
if (rules == null || rules.length() == 0) {
return true;
}
// else it's disallow by default
boolean allow = false;
for (int i = 0; i < rules.length(); i++) {
JSONObject rule = rules.getJSONObject(i);
boolean action = rule.get("action").equals("allow");
// apply by default
boolean apply = true;
if (rule.has("os")) {
// don't apply by default if has os rule
apply = false;
JSONObject osRule = rule.getJSONObject("os");
String name = osRule.getString("name");
String version = osRule.has("version") ? osRule.getString("version") : null;
if (platformDescription.getPlatform().name().equalsIgnoreCase(name)) {
if (version == null || platformDescription.getVersion().matches(version)) {
apply = true;
}
}
}
if (apply) {
allow = action;
}
}
return allow;
}
private String[] parseChecksums(JSONArray json) throws JSONException {
if (json == null) return null;
String[] checksums = new String[json.length()];
for (int i = 0; i < json.length(); i++) {
checksums[i] = json.getString(i);
}
return checksums;
}
private String parseNativeClassifier(JSONObject natives, PlatformDescription platform) throws JSONException {
if (natives == null) return null;
String classifier = natives.optString(platform.getPlatform().name().toLowerCase(), null);
if (classifier != null) {
classifier = classifier.replaceAll("\\Q${arch}", platform.getArch());
}
return classifier;
}
private Set<String> parseExtractExcludes(JSONObject json) throws JSONException {
if (json == null) return null;
JSONArray elements = json.optJSONArray("exclude");
if (elements == null) return null;
Set<String> excludes = new LinkedHashSet<>();
for (Object element : elements) {
excludes.add((String) element);
}
return Collections.unmodifiableSet(excludes);
}
private LibraryInfo parseLibraryDownloads(JSONObject json, String classifier) throws JSONException {
if (json == null) return null;
JSONObject artifact;
if (classifier == null) {
artifact = json.optJSONObject("artifact");
} else {
JSONObject classifiers = json.optJSONObject("classifiers");
if (classifiers == null) return null;
artifact = classifiers.optJSONObject(classifier);
}
if (artifact == null) return null;
return parseLibraryInfo(artifact);
}
private Set<Library> parseLibraries(JSONArray json, PlatformDescription platform) throws JSONException {
if (json == null) return null;
Set<Library> libraries = new HashSet<>();
for (Object element : json) {
Library library = parseLibrary((JSONObject) element, platform);
if (library != null) {
libraries.add(library);
}
}
return libraries;
}
private Map<String, DownloadInfo> parseDownloads(JSONObject json) throws JSONException {
if (json == null) return null;
Map<String, DownloadInfo> downloads = new HashMap<>();
for (String key : json.keySet()) {
downloads.put(key, parseDownloadInfo(json.getJSONObject(key)));
}
return downloads;
}
private String parseMinecraftArgs(JSONObject json){
if(json.has("minecraftArguments"))
return json.getString("minecraftArguments");
JSONObject arguments = json.optJSONObject("arguments");
if(arguments != null && arguments.has("game")) {
JSONArray gameArgs = arguments.getJSONArray("game");
StringBuilder sb = new StringBuilder();
for(Object arg : gameArgs) {
if(arg instanceof String)
sb.append(arg).append(" ");
}
return sb.toString().trim();
}
return null;//No Minecraft Args found
}
}
| jmccc/src/main/java/org/to2mbn/jmccc/version/parsing/VersionParserImpl.java | package org.to2mbn.jmccc.version.parsing;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import org.to2mbn.jmccc.internal.org.json.JSONArray;
import org.to2mbn.jmccc.internal.org.json.JSONException;
import org.to2mbn.jmccc.internal.org.json.JSONObject;
import org.to2mbn.jmccc.version.Asset;
import org.to2mbn.jmccc.version.AssetIndexInfo;
import org.to2mbn.jmccc.version.DownloadInfo;
import org.to2mbn.jmccc.version.Library;
import org.to2mbn.jmccc.version.LibraryInfo;
import org.to2mbn.jmccc.version.Native;
import org.to2mbn.jmccc.version.Version;
class VersionParserImpl implements VersionParser {
@Override
public DownloadInfo parseDownloadInfo(JSONObject json) throws JSONException {
if (json == null) return null;
String url = json.optString("url", null);
String checksum = json.optString("sha1", null);
long size = json.optLong("size", -1);
return new DownloadInfo(url, checksum, size);
}
@Override
public AssetIndexInfo parseAssetIndexInfo(JSONObject json) throws JSONException {
if (json == null) return null;
DownloadInfo base = parseDownloadInfo(json);
String id = json.getString("id");
long totalSize = json.optLong("totalSize", -1);
return new AssetIndexInfo(base.getUrl(), base.getChecksum(), base.getSize(), id, totalSize);
}
@Override
public LibraryInfo parseLibraryInfo(JSONObject json) throws JSONException {
if (json == null) return null;
DownloadInfo base = parseDownloadInfo(json);
String path = json.optString("path", null);
return new LibraryInfo(base.getUrl(), base.getChecksum(), base.getSize(), path);
}
@Override
public Library parseLibrary(JSONObject json, PlatformDescription platformDescription) throws JSONException {
if (json == null) return null;
if (!checkAllowed(json.optJSONArray("rules"), platformDescription)
|| !json.optBoolean("clientreq", true)) {
return null;
}
String[] splitedGav = json.getString("name").split(":", 3);
String groupId = splitedGav[0];
String artifactId = splitedGav[1];
String version = splitedGav[2];
String url = json.optString("url", null);
String[] checksums = parseChecksums(json.optJSONArray("checksums"));
JSONObject jsonNatives = json.optJSONObject("natives");
boolean isNative = jsonNatives != null;
String classifier = isNative ? parseNativeClassifier(json.getJSONObject("natives"), platformDescription) : null;
LibraryInfo libinfo = parseLibraryDownloads(json.optJSONObject("downloads"), classifier);
String type = "jar";
if (isNative) {
Set<String> excludes = parseExtractExcludes(json.getJSONObject("extract"));
return new Native(groupId, artifactId, version, classifier, type, libinfo, url, checksums, excludes);
} else {
return new Library(groupId, artifactId, version, classifier, type, libinfo, url, checksums);
}
}
@Override
public Set<Asset> parseAssetIndex(JSONObject json) throws JSONException {
if (json == null) return null;
JSONObject objects = json.getJSONObject("objects");
Set<Asset> assets = new TreeSet<>(new Comparator<Asset>() {
@Override
public int compare(Asset o1, Asset o2) {
return o1.getVirtualPath().compareTo(o2.getVirtualPath());
}
});
for (Object rawVirtualPath : objects.keySet()) {
String virtualPath = (String) rawVirtualPath;
JSONObject object = objects.getJSONObject(virtualPath);
String hash = object.getString("hash");
int size = object.getInt("size");
assets.add(new Asset(virtualPath, hash, size));
}
return Collections.unmodifiableSet(assets);
}
@Override
public Version parseVersion(Stack<JSONObject> hierarchy, PlatformDescription platformDescription) throws JSONException {
String version = hierarchy.get(0).getString("id");
String root = hierarchy.peek().getString("id");
String assets = "legacy";
String mainClass = null;
String launchArgs = null;
String type = null;
Map<String, Library> librariesMap = new TreeMap<>();
Map<String, DownloadInfo> downloads = new TreeMap<>();
AssetIndexInfo assetIndexInfo = null;
JSONObject json;
do {
json = hierarchy.pop();
assets = json.optString("assets", assets);
mainClass = json.optString("mainClass", mainClass);
launchArgs = json.optString("minecraftArguments", launchArgs);
type = json.optString("type", type);
Set<Library> currentLibraries = parseLibraries(json.optJSONArray("libraries"), platformDescription);
if (currentLibraries != null) {
for (Library library : currentLibraries) {
StringBuilder libId = new StringBuilder();
libId.append(library.getGroupId()).append(':')
.append(library.getArtifactId());
if (library.getClassifier() != null)
libId.append(':').append(library.getClassifier());
librariesMap.put(libId.toString(), library);
}
}
Map<String, DownloadInfo> currentDownloads = parseDownloads(json.optJSONObject("downloads"));
if (currentDownloads != null)
downloads.putAll(currentDownloads);
JSONObject jsonAssetIndexInfo = json.optJSONObject("assetIndex");
if (jsonAssetIndexInfo != null)
assetIndexInfo = parseAssetIndexInfo(jsonAssetIndexInfo);
} while (!hierarchy.isEmpty());
if (mainClass == null)
throw new JSONException("Missing mainClass");
if (launchArgs == null)
throw new JSONException("Missing minecraftArguments");
Set<Library> libraries = new LinkedHashSet<>(librariesMap.values());
return new Version(version,
type,
mainClass,
assets,
launchArgs,
root,
Collections.unmodifiableSet(libraries),
assets.equals("legacy"),
assetIndexInfo,
Collections.unmodifiableMap(downloads));
}
@Override
public boolean checkAllowed(JSONArray rules, PlatformDescription platformDescription) throws JSONException {
// by default it's allowed
if (rules == null || rules.length() == 0) {
return true;
}
// else it's disallow by default
boolean allow = false;
for (int i = 0; i < rules.length(); i++) {
JSONObject rule = rules.getJSONObject(i);
boolean action = rule.get("action").equals("allow");
// apply by default
boolean apply = true;
if (rule.has("os")) {
// don't apply by default if has os rule
apply = false;
JSONObject osRule = rule.getJSONObject("os");
String name = osRule.getString("name");
String version = osRule.has("version") ? osRule.getString("version") : null;
if (platformDescription.getPlatform().name().equalsIgnoreCase(name)) {
if (version == null || platformDescription.getVersion().matches(version)) {
apply = true;
}
}
}
if (apply) {
allow = action;
}
}
return allow;
}
private String[] parseChecksums(JSONArray json) throws JSONException {
if (json == null) return null;
String[] checksums = new String[json.length()];
for (int i = 0; i < json.length(); i++) {
checksums[i] = json.getString(i);
}
return checksums;
}
private String parseNativeClassifier(JSONObject natives, PlatformDescription platform) throws JSONException {
if (natives == null) return null;
String classifier = natives.optString(platform.getPlatform().name().toLowerCase(), null);
if (classifier != null) {
classifier = classifier.replaceAll("\\Q${arch}", platform.getArch());
}
return classifier;
}
private Set<String> parseExtractExcludes(JSONObject json) throws JSONException {
if (json == null) return null;
JSONArray elements = json.optJSONArray("exclude");
if (elements == null) return null;
Set<String> excludes = new LinkedHashSet<>();
for (Object element : elements) {
excludes.add((String) element);
}
return Collections.unmodifiableSet(excludes);
}
private LibraryInfo parseLibraryDownloads(JSONObject json, String classifier) throws JSONException {
if (json == null) return null;
JSONObject artifact;
if (classifier == null) {
artifact = json.optJSONObject("artifact");
} else {
JSONObject classifiers = json.optJSONObject("classifiers");
if (classifiers == null) return null;
artifact = classifiers.optJSONObject(classifier);
}
if (artifact == null) return null;
return parseLibraryInfo(artifact);
}
private Set<Library> parseLibraries(JSONArray json, PlatformDescription platform) throws JSONException {
if (json == null) return null;
Set<Library> libraries = new HashSet<>();
for (Object element : json) {
Library library = parseLibrary((JSONObject) element, platform);
if (library != null) {
libraries.add(library);
}
}
return libraries;
}
private Map<String, DownloadInfo> parseDownloads(JSONObject json) throws JSONException {
if (json == null) return null;
Map<String, DownloadInfo> downloads = new HashMap<>();
for (String key : json.keySet()) {
downloads.put(key, parseDownloadInfo(json.getJSONObject(key)));
}
return downloads;
}
}
| Fix couldn't download 1.13
| jmccc/src/main/java/org/to2mbn/jmccc/version/parsing/VersionParserImpl.java | Fix couldn't download 1.13 | <ide><path>mccc/src/main/java/org/to2mbn/jmccc/version/parsing/VersionParserImpl.java
<ide> String type = "jar";
<ide>
<ide> if (isNative) {
<del> Set<String> excludes = parseExtractExcludes(json.getJSONObject("extract"));
<add> Set<String> excludes = parseExtractExcludes(json.optJSONObject("extract"));
<ide> return new Native(groupId, artifactId, version, classifier, type, libinfo, url, checksums, excludes);
<ide> } else {
<ide> return new Library(groupId, artifactId, version, classifier, type, libinfo, url, checksums);
<ide>
<ide> assets = json.optString("assets", assets);
<ide> mainClass = json.optString("mainClass", mainClass);
<del> launchArgs = json.optString("minecraftArguments", launchArgs);
<add> launchArgs = parseMinecraftArgs(json);
<ide> type = json.optString("type", type);
<ide>
<ide> Set<Library> currentLibraries = parseLibraries(json.optJSONArray("libraries"), platformDescription);
<ide> return downloads;
<ide> }
<ide>
<add> private String parseMinecraftArgs(JSONObject json){
<add> if(json.has("minecraftArguments"))
<add> return json.getString("minecraftArguments");
<add>
<add> JSONObject arguments = json.optJSONObject("arguments");
<add> if(arguments != null && arguments.has("game")) {
<add> JSONArray gameArgs = arguments.getJSONArray("game");
<add> StringBuilder sb = new StringBuilder();
<add> for(Object arg : gameArgs) {
<add> if(arg instanceof String)
<add> sb.append(arg).append(" ");
<add> }
<add> return sb.toString().trim();
<add> }
<add> return null;//No Minecraft Args found
<add> }
<ide> } |
|
JavaScript | mit | error: pathspec 'src/lib/stringParser.js' did not match any file(s) known to git
| 7dc3959f13c0a747d2194132330999a31841426f | 1 | CBIConsulting/Winterfell,mharnek/Winterfell,andrewhathaway/Winterfell,jwbrady/Winterfell | module.exports = (template, params) => {
template = template || '';
params = params || {};
/*
* Split up template in to array of characters
*/
var characters = template.split('');
var buffer = '';
var parsedTemplate = '';
var collecting = false;
for (var i = 0; i < characters.length; i++) {
var currentChar = characters[i];
/*
* If we're not collecting and we're not
* and opening or closing brace then
* append the charater to the
* parsedTemplate and move on
*/
if (!collecting
&& currentChar != '{'
&& currentChar != '}') {
parsedTemplate += currentChar;
continue;
}
/*
* If we're an opening brace,
* start collecting for the buffer
*/
if (currentChar == '{') {
collecting = true;
}
/*
* If we're here, we're collecting so if
* we're not a brace of any sort then add
* the character to the buffer
*/
if (currentChar != '{'
&& currentChar != '}') {
buffer += currentChar;
}
/*
* If we're a closing brace, then we
* attempt to get the value with the
* buffers name from the params object
* and add it to the parsedTemplate
*/
if (currentChar == '}') {
var value = '';
if (typeof params[buffer] !== 'undefined') {
value = params[buffer];
}
parsedTemplate += value;
/*
* Stop collecting and reset
* the buffer to nothing
*/
collecting = false;
buffer = '';
}
}
return parsedTemplate;
}; | src/lib/stringParser.js | Add stringParser library to parse strings with {} in them
| src/lib/stringParser.js | Add stringParser library to parse strings with {} in them | <ide><path>rc/lib/stringParser.js
<add>module.exports = (template, params) => {
<add> template = template || '';
<add> params = params || {};
<add>
<add> /*
<add> * Split up template in to array of characters
<add> */
<add> var characters = template.split('');
<add>
<add> var buffer = '';
<add> var parsedTemplate = '';
<add> var collecting = false;
<add>
<add> for (var i = 0; i < characters.length; i++) {
<add> var currentChar = characters[i];
<add>
<add> /*
<add> * If we're not collecting and we're not
<add> * and opening or closing brace then
<add> * append the charater to the
<add> * parsedTemplate and move on
<add> */
<add> if (!collecting
<add> && currentChar != '{'
<add> && currentChar != '}') {
<add> parsedTemplate += currentChar;
<add> continue;
<add> }
<add>
<add> /*
<add> * If we're an opening brace,
<add> * start collecting for the buffer
<add> */
<add> if (currentChar == '{') {
<add> collecting = true;
<add> }
<add>
<add> /*
<add> * If we're here, we're collecting so if
<add> * we're not a brace of any sort then add
<add> * the character to the buffer
<add> */
<add> if (currentChar != '{'
<add> && currentChar != '}') {
<add> buffer += currentChar;
<add> }
<add>
<add> /*
<add> * If we're a closing brace, then we
<add> * attempt to get the value with the
<add> * buffers name from the params object
<add> * and add it to the parsedTemplate
<add> */
<add> if (currentChar == '}') {
<add> var value = '';
<add> if (typeof params[buffer] !== 'undefined') {
<add> value = params[buffer];
<add> }
<add>
<add> parsedTemplate += value;
<add>
<add> /*
<add> * Stop collecting and reset
<add> * the buffer to nothing
<add> */
<add> collecting = false;
<add> buffer = '';
<add> }
<add> }
<add>
<add> return parsedTemplate;
<add>}; |
|
JavaScript | mit | 4b3e2ccca4e08ae41f23f9f7dd31305ffd7105de | 0 | PKRoma/atom,PKRoma/atom,stinsonga/atom,kevinrenaers/atom,ardeshirj/atom,Mokolea/atom,liuderchi/atom,t9md/atom,brettle/atom,FIT-CSE2410-A-Bombs/atom,Mokolea/atom,andrewleverette/atom,decaffeinate-examples/atom,t9md/atom,liuderchi/atom,stinsonga/atom,andrewleverette/atom,decaffeinate-examples/atom,xream/atom,ardeshirj/atom,Mokolea/atom,AlexxNica/atom,CraZySacX/atom,decaffeinate-examples/atom,Arcanemagus/atom,atom/atom,decaffeinate-examples/atom,xream/atom,stinsonga/atom,FIT-CSE2410-A-Bombs/atom,sotayamashita/atom,atom/atom,andrewleverette/atom,ardeshirj/atom,liuderchi/atom,Arcanemagus/atom,t9md/atom,sotayamashita/atom,Arcanemagus/atom,brettle/atom,stinsonga/atom,xream/atom,brettle/atom,CraZySacX/atom,sotayamashita/atom,FIT-CSE2410-A-Bombs/atom,AlexxNica/atom,atom/atom,kevinrenaers/atom,liuderchi/atom,CraZySacX/atom,PKRoma/atom,kevinrenaers/atom,AlexxNica/atom | 'use strict'
const _ = require('underscore-plus')
const url = require('url')
const path = require('path')
const {Emitter, Disposable, CompositeDisposable} = require('event-kit')
const fs = require('fs-plus')
const {Directory} = require('pathwatcher')
const DefaultDirectorySearcher = require('./default-directory-searcher')
const Model = require('./model')
const TextEditor = require('./text-editor')
const PaneContainer = require('./pane-container')
const Panel = require('./panel')
const PanelContainer = require('./panel-container')
const Task = require('./task')
// Essential: Represents the state of the user interface for the entire window.
// An instance of this class is available via the `atom.workspace` global.
//
// Interact with this object to open files, be notified of current and future
// editors, and manipulate panes. To add panels, use {Workspace::addTopPanel}
// and friends.
//
// * `editor` {TextEditor} the new editor
//
module.exports = class Workspace extends Model {
constructor (params) {
super(...arguments)
this.updateWindowTitle = this.updateWindowTitle.bind(this)
this.updateDocumentEdited = this.updateDocumentEdited.bind(this)
this.didDestroyPaneItem = this.didDestroyPaneItem.bind(this)
this.packageManager = params.packageManager
this.config = params.config
this.project = params.project
this.notificationManager = params.notificationManager
this.viewRegistry = params.viewRegistry
this.grammarRegistry = params.grammarRegistry
this.applicationDelegate = params.applicationDelegate
this.assert = params.assert
this.deserializerManager = params.deserializerManager
this.textEditorRegistry = params.textEditorRegistry
this.emitter = new Emitter()
this.openers = []
this.destroyedItemURIs = []
this.paneContainer = new PaneContainer({
config: this.config,
applicationDelegate: this.applicationDelegate,
notificationManager: this.notificationManager,
deserializerManager: this.deserializerManager
})
this.paneContainer.onDidDestroyPaneItem(this.didDestroyPaneItem)
this.defaultDirectorySearcher = new DefaultDirectorySearcher()
this.consumeServices(this.packageManager)
this.panelContainers = {
top: new PanelContainer({location: 'top'}),
left: new PanelContainer({location: 'left'}),
right: new PanelContainer({location: 'right'}),
bottom: new PanelContainer({location: 'bottom'}),
header: new PanelContainer({location: 'header'}),
footer: new PanelContainer({location: 'footer'}),
modal: new PanelContainer({location: 'modal'})
}
this.subscribeToEvents()
}
reset (packageManager) {
this.packageManager = packageManager
this.emitter.dispose()
this.emitter = new Emitter()
this.paneContainer.destroy()
_.values(this.panelContainers).forEach(panelContainer => { panelContainer.destroy() })
this.paneContainer = new PaneContainer({
config: this.config,
applicationDelegate: this.applicationDelegate,
notificationManager: this.notificationManager,
deserializerManager: this.deserializerManager
})
this.paneContainer.onDidDestroyPaneItem(this.didDestroyPaneItem)
this.panelContainers = {
top: new PanelContainer({location: 'top'}),
left: new PanelContainer({location: 'left'}),
right: new PanelContainer({location: 'right'}),
bottom: new PanelContainer({location: 'bottom'}),
header: new PanelContainer({location: 'header'}),
footer: new PanelContainer({location: 'footer'}),
modal: new PanelContainer({location: 'modal'})
}
this.originalFontSize = null
this.openers = []
this.destroyedItemURIs = []
this.consumeServices(this.packageManager)
}
subscribeToEvents () {
this.subscribeToActiveItem()
this.subscribeToFontSize()
this.subscribeToAddedItems()
}
consumeServices ({serviceHub}) {
this.directorySearchers = []
serviceHub.consume(
'atom.directory-searcher',
'^0.1.0',
provider => this.directorySearchers.unshift(provider)
)
}
// Called by the Serializable mixin during serialization.
serialize () {
return {
deserializer: 'Workspace',
paneContainer: this.paneContainer.serialize(),
packagesWithActiveGrammars: this.getPackageNamesWithActiveGrammars(),
destroyedItemURIs: this.destroyedItemURIs.slice()
}
}
deserialize (state, deserializerManager) {
const packagesWithActiveGrammars =
state.packagesWithActiveGrammars != null ? state.packagesWithActiveGrammars : []
for (let packageName of packagesWithActiveGrammars) {
const pkg = this.packageManager.getLoadedPackage(packageName)
if (pkg != null) {
pkg.loadGrammarsSync()
}
}
if (state.destroyedItemURIs != null) {
this.destroyedItemURIs = state.destroyedItemURIs
}
return this.paneContainer.deserialize(state.paneContainer, deserializerManager)
}
getPackageNamesWithActiveGrammars () {
const packageNames = []
const addGrammar = ({includedGrammarScopes, packageName} = {}) => {
if (!packageName) { return }
// Prevent cycles
if (packageNames.indexOf(packageName) !== -1) { return }
packageNames.push(packageName)
for (let scopeName of includedGrammarScopes != null ? includedGrammarScopes : []) {
addGrammar(this.grammarRegistry.grammarForScopeName(scopeName))
}
}
const editors = this.getTextEditors()
for (let editor of editors) { addGrammar(editor.getGrammar()) }
if (editors.length > 0) {
for (let grammar of this.grammarRegistry.getGrammars()) {
if (grammar.injectionSelector) {
addGrammar(grammar)
}
}
}
return _.uniq(packageNames)
}
subscribeToActiveItem () {
this.updateWindowTitle()
this.updateDocumentEdited()
this.project.onDidChangePaths(this.updateWindowTitle)
this.observeActivePaneItem(item => {
this.updateWindowTitle()
this.updateDocumentEdited()
if (this.activeItemSubscriptions != null) {
this.activeItemSubscriptions.dispose()
}
this.activeItemSubscriptions = new CompositeDisposable()
let modifiedSubscription, titleSubscription
if (item != null && typeof item.onDidChangeTitle === 'function') {
titleSubscription = item.onDidChangeTitle(this.updateWindowTitle)
} else if (item != null && typeof item.on === 'function') {
titleSubscription = item.on('title-changed', this.updateWindowTitle)
if (titleSubscription == null || typeof titleSubscription.dispose !== 'function') {
titleSubscription = new Disposable(() => {
item.off('title-changed', this.updateWindowTitle)
})
}
}
if (item != null && typeof item.onDidChangeModified === 'function') {
modifiedSubscription = item.onDidChangeModified(this.updateDocumentEdited)
} else if (item != null && typeof item.on === 'function') {
modifiedSubscription = item.on('modified-status-changed', this.updateDocumentEdited)
if (modifiedSubscription == null || typeof modifiedSubscription.dispose !== 'function') {
modifiedSubscription = new Disposable(() => {
item.off('modified-status-changed', this.updateDocumentEdited)
})
}
}
if (titleSubscription != null) { this.activeItemSubscriptions.add(titleSubscription) }
if (modifiedSubscription != null) { this.activeItemSubscriptions.add(modifiedSubscription) }
})
}
subscribeToAddedItems () {
this.onDidAddPaneItem(({item, pane, index}) => {
if (item instanceof TextEditor) {
const subscriptions = new CompositeDisposable(
this.textEditorRegistry.add(item),
this.textEditorRegistry.maintainGrammar(item),
this.textEditorRegistry.maintainConfig(item),
item.observeGrammar(this.handleGrammarUsed.bind(this))
)
item.onDidDestroy(() => { subscriptions.dispose() })
this.emitter.emit('did-add-text-editor', {textEditor: item, pane, index})
}
})
}
// Updates the application's title and proxy icon based on whichever file is
// open.
updateWindowTitle () {
let itemPath, itemTitle, projectPath, representedPath
const appName = 'Atom'
const left = this.project.getPaths()
const projectPaths = left != null ? left : []
const item = this.getActivePaneItem()
if (item) {
itemPath = typeof item.getPath === 'function' ? item.getPath() : undefined
const longTitle = typeof item.getLongTitle === 'function' ? item.getLongTitle() : undefined
itemTitle = longTitle == null
? (typeof item.getTitle === 'function' ? item.getTitle() : undefined)
: longTitle
projectPath = _.find(
projectPaths,
projectPath =>
(itemPath === projectPath) || (itemPath != null ? itemPath.startsWith(projectPath + path.sep) : undefined)
)
}
if (itemTitle == null) { itemTitle = 'untitled' }
if (projectPath == null) { projectPath = itemPath ? path.dirname(itemPath) : projectPaths[0] }
if (projectPath != null) {
projectPath = fs.tildify(projectPath)
}
const titleParts = []
if ((item != null) && (projectPath != null)) {
titleParts.push(itemTitle, projectPath)
representedPath = itemPath != null ? itemPath : projectPath
} else if (projectPath != null) {
titleParts.push(projectPath)
representedPath = projectPath
} else {
titleParts.push(itemTitle)
representedPath = ''
}
if (process.platform !== 'darwin') {
titleParts.push(appName)
}
document.title = titleParts.join(' \u2014 ')
this.applicationDelegate.setRepresentedFilename(representedPath)
}
// On macOS, fades the application window's proxy icon when the current file
// has been modified.
updateDocumentEdited () {
const activePaneItem = this.getActivePaneItem()
const modified = activePaneItem != null && typeof activePaneItem.isModified === 'function'
? activePaneItem.isModified() || false
: false
this.applicationDelegate.setWindowDocumentEdited(modified)
}
/*
Section: Event Subscription
*/
// Essential: Invoke the given callback with all current and future text
// editors in the workspace.
//
// * `callback` {Function} to be called with current and future text editors.
// * `editor` An {TextEditor} that is present in {::getTextEditors} at the time
// of subscription or that is added at some later time.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeTextEditors (callback) {
for (let textEditor of this.getTextEditors()) { callback(textEditor) }
return this.onDidAddTextEditor(({textEditor}) => callback(textEditor))
}
// Essential: Invoke the given callback with all current and future panes items
// in the workspace.
//
// * `callback` {Function} to be called with current and future pane items.
// * `item` An item that is present in {::getPaneItems} at the time of
// subscription or that is added at some later time.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observePaneItems (callback) { return this.paneContainer.observePaneItems(callback) }
// Essential: Invoke the given callback when the active pane item changes.
//
// Because observers are invoked synchronously, it's important not to perform
// any expensive operations via this method. Consider
// {::onDidStopChangingActivePaneItem} to delay operations until after changes
// stop occurring.
//
// * `callback` {Function} to be called when the active pane item changes.
// * `item` The active pane item.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeActivePaneItem (callback) {
return this.paneContainer.onDidChangeActivePaneItem(callback)
}
// Essential: Invoke the given callback when the active pane item stops
// changing.
//
// Observers are called asynchronously 100ms after the last active pane item
// change. Handling changes here rather than in the synchronous
// {::onDidChangeActivePaneItem} prevents unneeded work if the user is quickly
// changing or closing tabs and ensures critical UI feedback, like changing the
// highlighted tab, gets priority over work that can be done asynchronously.
//
// * `callback` {Function} to be called when the active pane item stopts
// changing.
// * `item` The active pane item.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidStopChangingActivePaneItem (callback) {
return this.paneContainer.onDidStopChangingActivePaneItem(callback)
}
// Essential: Invoke the given callback with the current active pane item and
// with all future active pane items in the workspace.
//
// * `callback` {Function} to be called when the active pane item changes.
// * `item` The current active pane item.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeActivePaneItem (callback) { return this.paneContainer.observeActivePaneItem(callback) }
// Essential: Invoke the given callback whenever an item is opened. Unlike
// {::onDidAddPaneItem}, observers will be notified for items that are already
// present in the workspace when they are reopened.
//
// * `callback` {Function} to be called whenever an item is opened.
// * `event` {Object} with the following keys:
// * `uri` {String} representing the opened URI. Could be `undefined`.
// * `item` The opened item.
// * `pane` The pane in which the item was opened.
// * `index` The index of the opened item on its pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidOpen (callback) {
return this.emitter.on('did-open', callback)
}
// Extended: Invoke the given callback when a pane is added to the workspace.
//
// * `callback` {Function} to be called panes are added.
// * `event` {Object} with the following keys:
// * `pane` The added pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddPane (callback) { return this.paneContainer.onDidAddPane(callback) }
// Extended: Invoke the given callback before a pane is destroyed in the
// workspace.
//
// * `callback` {Function} to be called before panes are destroyed.
// * `event` {Object} with the following keys:
// * `pane` The pane to be destroyed.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onWillDestroyPane (callback) { return this.paneContainer.onWillDestroyPane(callback) }
// Extended: Invoke the given callback when a pane is destroyed in the
// workspace.
//
// * `callback` {Function} to be called panes are destroyed.
// * `event` {Object} with the following keys:
// * `pane` The destroyed pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidDestroyPane (callback) { return this.paneContainer.onDidDestroyPane(callback) }
// Extended: Invoke the given callback with all current and future panes in the
// workspace.
//
// * `callback` {Function} to be called with current and future panes.
// * `pane` A {Pane} that is present in {::getPanes} at the time of
// subscription or that is added at some later time.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observePanes (callback) { return this.paneContainer.observePanes(callback) }
// Extended: Invoke the given callback when the active pane changes.
//
// * `callback` {Function} to be called when the active pane changes.
// * `pane` A {Pane} that is the current return value of {::getActivePane}.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeActivePane (callback) { return this.paneContainer.onDidChangeActivePane(callback) }
// Extended: Invoke the given callback with the current active pane and when
// the active pane changes.
//
// * `callback` {Function} to be called with the current and future active#
// panes.
// * `pane` A {Pane} that is the current return value of {::getActivePane}.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeActivePane (callback) { return this.paneContainer.observeActivePane(callback) }
// Extended: Invoke the given callback when a pane item is added to the
// workspace.
//
// * `callback` {Function} to be called when pane items are added.
// * `event` {Object} with the following keys:
// * `item` The added pane item.
// * `pane` {Pane} containing the added item.
// * `index` {Number} indicating the index of the added item in its pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddPaneItem (callback) { return this.paneContainer.onDidAddPaneItem(callback) }
// Extended: Invoke the given callback when a pane item is about to be
// destroyed, before the user is prompted to save it.
//
// * `callback` {Function} to be called before pane items are destroyed.
// * `event` {Object} with the following keys:
// * `item` The item to be destroyed.
// * `pane` {Pane} containing the item to be destroyed.
// * `index` {Number} indicating the index of the item to be destroyed in
// its pane.
//
// Returns a {Disposable} on which `.dispose` can be called to unsubscribe.
onWillDestroyPaneItem (callback) { return this.paneContainer.onWillDestroyPaneItem(callback) }
// Extended: Invoke the given callback when a pane item is destroyed.
//
// * `callback` {Function} to be called when pane items are destroyed.
// * `event` {Object} with the following keys:
// * `item` The destroyed item.
// * `pane` {Pane} containing the destroyed item.
// * `index` {Number} indicating the index of the destroyed item in its
// pane.
//
// Returns a {Disposable} on which `.dispose` can be called to unsubscribe.
onDidDestroyPaneItem (callback) { return this.paneContainer.onDidDestroyPaneItem(callback) }
// Extended: Invoke the given callback when a text editor is added to the
// workspace.
//
// * `callback` {Function} to be called panes are added.
// * `event` {Object} with the following keys:
// * `textEditor` {TextEditor} that was added.
// * `pane` {Pane} containing the added text editor.
// * `index` {Number} indicating the index of the added text editor in its
// pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddTextEditor (callback) {
return this.emitter.on('did-add-text-editor', callback)
}
/*
Section: Opening
*/
// Essential: Opens the given URI in Atom asynchronously.
// If the URI is already open, the existing item for that URI will be
// activated. If no URI is given, or no registered opener can open
// the URI, a new empty {TextEditor} will be created.
//
// * `uri` (optional) A {String} containing a URI.
// * `options` (optional) {Object}
// * `initialLine` A {Number} indicating which row to move the cursor to
// initially. Defaults to `0`.
// * `initialColumn` A {Number} indicating which column to move the cursor to
// initially. Defaults to `0`.
// * `split` Either 'left', 'right', 'up' or 'down'.
// If 'left', the item will be opened in leftmost pane of the current active pane's row.
// If 'right', the item will be opened in the rightmost pane of the current active pane's row. If only one pane exists in the row, a new pane will be created.
// If 'up', the item will be opened in topmost pane of the current active pane's column.
// If 'down', the item will be opened in the bottommost pane of the current active pane's column. If only one pane exists in the column, a new pane will be created.
// * `activatePane` A {Boolean} indicating whether to call {Pane::activate} on
// containing pane. Defaults to `true`.
// * `activateItem` A {Boolean} indicating whether to call {Pane::activateItem}
// on containing pane. Defaults to `true`.
// * `pending` A {Boolean} indicating whether or not the item should be opened
// in a pending state. Existing pending items in a pane are replaced with
// new pending items when they are opened.
// * `searchAllPanes` A {Boolean}. If `true`, the workspace will attempt to
// activate an existing item for the given URI on any pane.
// If `false`, only the active pane will be searched for
// an existing item for the same URI. Defaults to `false`.
//
// Returns a {Promise} that resolves to the {TextEditor} for the file URI.
open (uri_, options = {}) {
const { searchAllPanes } = options
const { split } = options
const uri = this.project.resolvePath(uri_)
if (!atom.config.get('core.allowPendingPaneItems')) {
options.pending = false
}
// Avoid adding URLs as recent documents to work-around this Spotlight crash:
// https://github.com/atom/atom/issues/10071
if ((uri != null) && ((url.parse(uri).protocol == null) || (process.platform === 'win32'))) {
this.applicationDelegate.addRecentDocument(uri)
}
let pane
if (searchAllPanes) { pane = this.paneContainer.paneForURI(uri) }
if (pane == null) {
switch (split) {
case 'left':
pane = this.getActivePane().findLeftmostSibling()
break
case 'right':
pane = this.getActivePane().findOrCreateRightmostSibling()
break
case 'up':
pane = this.getActivePane().findTopmostSibling()
break
case 'down':
pane = this.getActivePane().findOrCreateBottommostSibling()
break
default:
pane = this.getActivePane()
break
}
}
return this.openURIInPane(uri, pane, options)
}
// Open Atom's license in the active pane.
openLicense () {
return this.open(path.join(process.resourcesPath, 'LICENSE.md'))
}
// Synchronously open the given URI in the active pane. **Only use this method
// in specs. Calling this in production code will block the UI thread and
// everyone will be mad at you.**
//
// * `uri` A {String} containing a URI.
// * `options` An optional options {Object}
// * `initialLine` A {Number} indicating which row to move the cursor to
// initially. Defaults to `0`.
// * `initialColumn` A {Number} indicating which column to move the cursor to
// initially. Defaults to `0`.
// * `activatePane` A {Boolean} indicating whether to call {Pane::activate} on
// the containing pane. Defaults to `true`.
// * `activateItem` A {Boolean} indicating whether to call {Pane::activateItem}
// on containing pane. Defaults to `true`.
openSync (uri_ = '', options = {}) {
const {initialLine, initialColumn} = options
const activatePane = options.activatePane != null ? options.activatePane : true
const activateItem = options.activateItem != null ? options.activateItem : true
const uri = this.project.resolvePath(uri)
let item = this.getActivePane().itemForURI(uri)
if (uri && (item == null)) {
for (const opener of this.getOpeners()) {
item = opener(uri, options)
if (item) break
}
}
if (item == null) {
item = this.project.openSync(uri, {initialLine, initialColumn})
}
if (activateItem) {
this.getActivePane().activateItem(item)
}
this.itemOpened(item)
if (activatePane) {
this.getActivePane().activate()
}
return item
}
openURIInPane (uri, pane, options = {}) {
const activatePane = options.activatePane != null ? options.activatePane : true
const activateItem = options.activateItem != null ? options.activateItem : true
let item
if (uri != null) {
item = pane.itemForURI(uri)
if (item == null) {
for (let opener of this.getOpeners()) {
item = opener(uri, options)
if (item != null) break
}
} else if (!options.pending && (pane.getPendingItem() === item)) {
pane.clearPendingItem()
}
}
try {
if (item == null) {
item = this.openTextFile(uri, options)
}
} catch (error) {
switch (error.code) {
case 'CANCELLED':
return Promise.resolve()
case 'EACCES':
this.notificationManager.addWarning(`Permission denied '${error.path}'`)
return Promise.resolve()
case 'EPERM':
case 'EBUSY':
case 'ENXIO':
case 'EIO':
case 'ENOTCONN':
case 'UNKNOWN':
case 'ECONNRESET':
case 'EINVAL':
case 'EMFILE':
case 'ENOTDIR':
case 'EAGAIN':
this.notificationManager.addWarning(
`Unable to open '${error.path != null ? error.path : uri}'`,
{detail: error.message}
)
return Promise.resolve()
default:
throw error
}
}
return Promise.resolve(item)
.then(item => {
let initialColumn
if (pane.isDestroyed()) {
return item
}
this.itemOpened(item)
if (activateItem) {
pane.activateItem(item, {pending: options.pending})
}
if (activatePane) {
pane.activate()
}
let initialLine = initialColumn = 0
if (!Number.isNaN(options.initialLine)) {
initialLine = options.initialLine
}
if (!Number.isNaN(options.initialColumn)) {
initialColumn = options.initialColumn
}
if ((initialLine >= 0) || (initialColumn >= 0)) {
if (typeof item.setCursorBufferPosition === 'function') {
item.setCursorBufferPosition([initialLine, initialColumn])
}
}
const index = pane.getActiveItemIndex()
this.emitter.emit('did-open', {uri, pane, item, index})
return item
}
)
}
openTextFile (uri, options) {
const filePath = this.project.resolvePath(uri)
if (filePath != null) {
try {
fs.closeSync(fs.openSync(filePath, 'r'))
} catch (error) {
// allow ENOENT errors to create an editor for paths that dont exist
if (error.code !== 'ENOENT') {
throw error
}
}
}
const fileSize = fs.getSizeSync(filePath)
const largeFileMode = fileSize >= (2 * 1048576) // 2MB
if (fileSize >= (this.config.get('core.warnOnLargeFileLimit') * 1048576)) { // 20MB by default
const choice = this.applicationDelegate.confirm({
message: 'Atom will be unresponsive during the loading of very large files.',
detailedMessage: 'Do you still want to load this file?',
buttons: ['Proceed', 'Cancel']
})
if (choice === 1) {
const error = new Error()
error.code = 'CANCELLED'
throw error
}
}
return this.project.bufferForPath(filePath, options)
.then(buffer => {
return this.textEditorRegistry.build(Object.assign({buffer, largeFileMode, autoHeight: false}, options))
})
}
handleGrammarUsed (grammar) {
if (grammar == null) { return }
return this.packageManager.triggerActivationHook(`${grammar.packageName}:grammar-used`)
}
// Public: Returns a {Boolean} that is `true` if `object` is a `TextEditor`.
//
// * `object` An {Object} you want to perform the check against.
isTextEditor (object) {
return object instanceof TextEditor
}
// Extended: Create a new text editor.
//
// Returns a {TextEditor}.
buildTextEditor (params) {
const editor = this.textEditorRegistry.build(params)
const subscriptions = new CompositeDisposable(
this.textEditorRegistry.maintainGrammar(editor),
this.textEditorRegistry.maintainConfig(editor)
)
editor.onDidDestroy(() => { subscriptions.dispose() })
return editor
}
// Public: Asynchronously reopens the last-closed item's URI if it hasn't already been
// reopened.
//
// Returns a {Promise} that is resolved when the item is opened
reopenItem () {
const uri = this.destroyedItemURIs.pop()
if (uri) {
return this.open(uri)
} else {
return Promise.resolve()
}
}
// Public: Register an opener for a uri.
//
// When a URI is opened via {Workspace::open}, Atom loops through its registered
// opener functions until one returns a value for the given uri.
// Openers are expected to return an object that inherits from HTMLElement or
// a model which has an associated view in the {ViewRegistry}.
// A {TextEditor} will be used if no opener returns a value.
//
// ## Examples
//
// ```coffee
// atom.workspace.addOpener (uri) ->
// if path.extname(uri) is '.toml'
// return new TomlEditor(uri)
// ```
//
// * `opener` A {Function} to be called when a path is being opened.
//
// Returns a {Disposable} on which `.dispose()` can be called to remove the
// opener.
//
// Note that the opener will be called if and only if the URI is not already open
// in the current pane. The searchAllPanes flag expands the search from the
// current pane to all panes. If you wish to open a view of a different type for
// a file that is already open, consider changing the protocol of the URI. For
// example, perhaps you wish to preview a rendered version of the file `/foo/bar/baz.quux`
// that is already open in a text editor view. You could signal this by calling
// {Workspace::open} on the URI `quux-preview://foo/bar/baz.quux`. Then your opener
// can check the protocol for quux-preview and only handle those URIs that match.
addOpener (opener) {
this.openers.push(opener)
return new Disposable(() => { _.remove(this.openers, opener) })
}
getOpeners () {
return this.openers
}
/*
Section: Pane Items
*/
// Essential: Get all pane items in the workspace.
//
// Returns an {Array} of items.
getPaneItems () {
return this.paneContainer.getPaneItems()
}
// Essential: Get the active {Pane}'s active item.
//
// Returns an pane item {Object}.
getActivePaneItem () {
return this.paneContainer.getActivePaneItem()
}
// Essential: Get all text editors in the workspace.
//
// Returns an {Array} of {TextEditor}s.
getTextEditors () {
return this.getPaneItems().filter(item => item instanceof TextEditor)
}
// Essential: Get the active item if it is an {TextEditor}.
//
// Returns an {TextEditor} or `undefined` if the current active item is not an
// {TextEditor}.
getActiveTextEditor () {
const activeItem = this.getActivePaneItem()
if (activeItem instanceof TextEditor) { return activeItem }
}
// Save all pane items.
saveAll () {
return this.paneContainer.saveAll()
}
confirmClose (options) {
return this.paneContainer.confirmClose(options)
}
// Save the active pane item.
//
// If the active pane item currently has a URI according to the item's
// `.getURI` method, calls `.save` on the item. Otherwise
// {::saveActivePaneItemAs} # will be called instead. This method does nothing
// if the active item does not implement a `.save` method.
saveActivePaneItem () {
return this.getActivePane().saveActiveItem()
}
// Prompt the user for a path and save the active pane item to it.
//
// Opens a native dialog where the user selects a path on disk, then calls
// `.saveAs` on the item with the selected path. This method does nothing if
// the active item does not implement a `.saveAs` method.
saveActivePaneItemAs () {
return this.getActivePane().saveActiveItemAs()
}
// Destroy (close) the active pane item.
//
// Removes the active pane item and calls the `.destroy` method on it if one is
// defined.
destroyActivePaneItem () {
return this.getActivePane().destroyActiveItem()
}
/*
Section: Panes
*/
// Extended: Get all panes in the workspace.
//
// Returns an {Array} of {Pane}s.
getPanes () {
return this.paneContainer.getPanes()
}
// Extended: Get the active {Pane}.
//
// Returns a {Pane}.
getActivePane () {
return this.paneContainer.getActivePane()
}
// Extended: Make the next pane active.
activateNextPane () {
return this.paneContainer.activateNextPane()
}
// Extended: Make the previous pane active.
activatePreviousPane () {
return this.paneContainer.activatePreviousPane()
}
// Extended: Get the first {Pane} with an item for the given URI.
//
// * `uri` {String} uri
//
// Returns a {Pane} or `undefined` if no pane exists for the given URI.
paneForURI (uri) {
return this.paneContainer.paneForURI(uri)
}
// Extended: Get the {Pane} containing the given item.
//
// * `item` Item the returned pane contains.
//
// Returns a {Pane} or `undefined` if no pane exists for the given item.
paneForItem (item) {
return this.paneContainer.paneForItem(item)
}
// Destroy (close) the active pane.
destroyActivePane () {
const activePane = this.getActivePane()
if (activePane != null) {
activePane.destroy()
}
}
// Close the active pane item, or the active pane if it is empty,
// or the current window if there is only the empty root pane.
closeActivePaneItemOrEmptyPaneOrWindow () {
if (this.getActivePaneItem() != null) {
this.destroyActivePaneItem()
} else if (this.getPanes().length > 1) {
this.destroyActivePane()
} else if (this.config.get('core.closeEmptyWindows')) {
atom.close()
}
}
// Increase the editor font size by 1px.
increaseFontSize () {
this.config.set('editor.fontSize', this.config.get('editor.fontSize') + 1)
}
// Decrease the editor font size by 1px.
decreaseFontSize () {
const fontSize = this.config.get('editor.fontSize')
if (fontSize > 1) {
this.config.set('editor.fontSize', fontSize - 1)
}
}
// Restore to the window's original editor font size.
resetFontSize () {
if (this.originalFontSize) {
this.config.set('editor.fontSize', this.originalFontSize)
}
}
subscribeToFontSize () {
return this.config.onDidChange('editor.fontSize', ({oldValue}) => {
if (this.originalFontSize == null) {
this.originalFontSize = oldValue
}
})
}
// Removes the item's uri from the list of potential items to reopen.
itemOpened (item) {
let uri
if (typeof item.getURI === 'function') {
uri = item.getURI()
} else if (typeof item.getUri === 'function') {
uri = item.getUri()
}
if (uri != null) {
_.remove(this.destroyedItemURIs, uri)
}
}
// Adds the destroyed item's uri to the list of items to reopen.
didDestroyPaneItem ({item}) {
let uri
if (typeof item.getURI === 'function') {
uri = item.getURI()
} else if (typeof item.getUri === 'function') {
uri = item.getUri()
}
if (uri != null) {
this.destroyedItemURIs.push(uri)
}
}
// Called by Model superclass when destroyed
destroyed () {
this.paneContainer.destroy()
if (this.activeItemSubscriptions != null) {
this.activeItemSubscriptions.dispose()
}
}
/*
Section: Panels
Panels are used to display UI related to an editor window. They are placed at one of the four
edges of the window: left, right, top or bottom. If there are multiple panels on the same window
edge they are stacked in order of priority: higher priority is closer to the center, lower
priority towards the edge.
*Note:* If your panel changes its size throughout its lifetime, consider giving it a higher
priority, allowing fixed size panels to be closer to the edge. This allows control targets to
remain more static for easier targeting by users that employ mice or trackpads. (See
[atom/atom#4834](https://github.com/atom/atom/issues/4834) for discussion.)
*/
// Essential: Get an {Array} of all the panel items at the bottom of the editor window.
getBottomPanels () {
return this.getPanels('bottom')
}
// Essential: Adds a panel item to the bottom of the editor window.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addBottomPanel (options) {
return this.addPanel('bottom', options)
}
// Essential: Get an {Array} of all the panel items to the left of the editor window.
getLeftPanels () {
return this.getPanels('left')
}
// Essential: Adds a panel item to the left of the editor window.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addLeftPanel (options) {
return this.addPanel('left', options)
}
// Essential: Get an {Array} of all the panel items to the right of the editor window.
getRightPanels () {
return this.getPanels('right')
}
// Essential: Adds a panel item to the right of the editor window.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addRightPanel (options) {
return this.addPanel('right', options)
}
// Essential: Get an {Array} of all the panel items at the top of the editor window.
getTopPanels () {
return this.getPanels('top')
}
// Essential: Adds a panel item to the top of the editor window above the tabs.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addTopPanel (options) {
return this.addPanel('top', options)
}
// Essential: Get an {Array} of all the panel items in the header.
getHeaderPanels () {
return this.getPanels('header')
}
// Essential: Adds a panel item to the header.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addHeaderPanel (options) {
return this.addPanel('header', options)
}
// Essential: Get an {Array} of all the panel items in the footer.
getFooterPanels () {
return this.getPanels('footer')
}
// Essential: Adds a panel item to the footer.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addFooterPanel (options) {
return this.addPanel('footer', options)
}
// Essential: Get an {Array} of all the modal panel items
getModalPanels () {
return this.getPanels('modal')
}
// Essential: Adds a panel item as a modal dialog.
//
// * `options` {Object}
// * `item` Your panel content. It can be a DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// model option. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addModalPanel (options = {}) {
return this.addPanel('modal', options)
}
// Essential: Returns the {Panel} associated with the given item. Returns
// `null` when the item has no panel.
//
// * `item` Item the panel contains
panelForItem (item) {
for (let location in this.panelContainers) {
const container = this.panelContainers[location]
const panel = container.panelForItem(item)
if (panel != null) { return panel }
}
return null
}
getPanels (location) {
return this.panelContainers[location].getPanels()
}
addPanel (location, options) {
if (options == null) { options = {} }
return this.panelContainers[location].addPanel(new Panel(options))
}
/*
Section: Searching and Replacing
*/
// Public: Performs a search across all files in the workspace.
//
// * `regex` {RegExp} to search with.
// * `options` (optional) {Object}
// * `paths` An {Array} of glob patterns to search within.
// * `onPathsSearched` (optional) {Function} to be periodically called
// with number of paths searched.
// * `iterator` {Function} callback on each file found.
//
// Returns a {Promise} with a `cancel()` method that will cancel all
// of the underlying searches that were started as part of this scan.
scan (regex, options = {}, iterator) {
if (_.isFunction(options)) {
iterator = options
options = {}
}
// Find a searcher for every Directory in the project. Each searcher that is matched
// will be associated with an Array of Directory objects in the Map.
const directoriesForSearcher = new Map()
for (const directory of this.project.getDirectories()) {
let searcher = this.defaultDirectorySearcher
for (const directorySearcher of this.directorySearchers) {
if (directorySearcher.canSearchDirectory(directory)) {
searcher = directorySearcher
break
}
}
let directories = directoriesForSearcher.get(searcher)
if (!directories) {
directories = []
directoriesForSearcher.set(searcher, directories)
}
directories.push(directory)
}
// Define the onPathsSearched callback.
let onPathsSearched
if (_.isFunction(options.onPathsSearched)) {
// Maintain a map of directories to the number of search results. When notified of a new count,
// replace the entry in the map and update the total.
const onPathsSearchedOption = options.onPathsSearched
let totalNumberOfPathsSearched = 0
const numberOfPathsSearchedForSearcher = new Map()
onPathsSearched = function (searcher, numberOfPathsSearched) {
const oldValue = numberOfPathsSearchedForSearcher.get(searcher)
if (oldValue) {
totalNumberOfPathsSearched -= oldValue
}
numberOfPathsSearchedForSearcher.set(searcher, numberOfPathsSearched)
totalNumberOfPathsSearched += numberOfPathsSearched
return onPathsSearchedOption(totalNumberOfPathsSearched)
}
} else {
onPathsSearched = function () {}
}
// Kick off all of the searches and unify them into one Promise.
const allSearches = []
directoriesForSearcher.forEach((directories, searcher) => {
const searchOptions = {
inclusions: options.paths || [],
includeHidden: true,
excludeVcsIgnores: this.config.get('core.excludeVcsIgnoredPaths'),
exclusions: this.config.get('core.ignoredNames'),
follow: this.config.get('core.followSymlinks'),
didMatch: result => {
if (!this.project.isPathModified(result.filePath)) {
return iterator(result)
}
},
didError (error) {
return iterator(null, error)
},
didSearchPaths (count) {
return onPathsSearched(searcher, count)
}
}
const directorySearcher = searcher.search(directories, regex, searchOptions)
allSearches.push(directorySearcher)
})
const searchPromise = Promise.all(allSearches)
for (let buffer of this.project.getBuffers()) {
if (buffer.isModified()) {
const filePath = buffer.getPath()
if (!this.project.contains(filePath)) {
continue
}
var matches = []
buffer.scan(regex, match => matches.push(match))
if (matches.length > 0) {
iterator({filePath, matches})
}
}
}
// Make sure the Promise that is returned to the client is cancelable. To be consistent
// with the existing behavior, instead of cancel() rejecting the promise, it should
// resolve it with the special value 'cancelled'. At least the built-in find-and-replace
// package relies on this behavior.
let isCancelled = false
const cancellablePromise = new Promise((resolve, reject) => {
const onSuccess = function () {
if (isCancelled) {
resolve('cancelled')
} else {
resolve(null)
}
}
const onFailure = function () {
for (let promise of allSearches) { promise.cancel() }
reject()
}
searchPromise.then(onSuccess, onFailure)
})
cancellablePromise.cancel = () => {
isCancelled = true
// Note that cancelling all of the members of allSearches will cause all of the searches
// to resolve, which causes searchPromise to resolve, which is ultimately what causes
// cancellablePromise to resolve.
allSearches.map((promise) => promise.cancel())
}
// Although this method claims to return a `Promise`, the `ResultsPaneView.onSearch()`
// method in the find-and-replace package expects the object returned by this method to have a
// `done()` method. Include a done() method until find-and-replace can be updated.
cancellablePromise.done = onSuccessOrFailure => {
cancellablePromise.then(onSuccessOrFailure, onSuccessOrFailure)
}
return cancellablePromise
}
// Public: Performs a replace across all the specified files in the project.
//
// * `regex` A {RegExp} to search with.
// * `replacementText` {String} to replace all matches of regex with.
// * `filePaths` An {Array} of file path strings to run the replace on.
// * `iterator` A {Function} callback on each file with replacements:
// * `options` {Object} with keys `filePath` and `replacements`.
//
// Returns a {Promise}.
replace (regex, replacementText, filePaths, iterator) {
return new Promise((resolve, reject) => {
let buffer
const openPaths = this.project.getBuffers().map(buffer => buffer.getPath())
const outOfProcessPaths = _.difference(filePaths, openPaths)
let inProcessFinished = !openPaths.length
let outOfProcessFinished = !outOfProcessPaths.length
const checkFinished = () => {
if (outOfProcessFinished && inProcessFinished) {
resolve()
}
}
if (!outOfProcessFinished.length) {
let flags = 'g'
if (regex.ignoreCase) { flags += 'i' }
const task = Task.once(
require.resolve('./replace-handler'),
outOfProcessPaths,
regex.source,
flags,
replacementText,
() => {
outOfProcessFinished = true
checkFinished()
}
)
task.on('replace:path-replaced', iterator)
task.on('replace:file-error', error => { iterator(null, error) })
}
for (buffer of this.project.getBuffers()) {
if (!filePaths.includes(buffer.getPath())) { continue }
const replacements = buffer.replace(regex, replacementText, iterator)
if (replacements) {
iterator({filePath: buffer.getPath(), replacements})
}
}
inProcessFinished = true
checkFinished()
})
}
checkoutHeadRevision (editor) {
if (editor.getPath()) {
const checkoutHead = () => {
return this.project.repositoryForDirectory(new Directory(editor.getDirectoryPath()))
.then(repository => repository != null ? repository.checkoutHeadForEditor(editor) : undefined)
}
if (this.config.get('editor.confirmCheckoutHeadRevision')) {
this.applicationDelegate.confirm({
message: 'Confirm Checkout HEAD Revision',
detailedMessage: `Are you sure you want to discard all changes to "${editor.getFileName()}" since the last Git commit?`,
buttons: {
OK: checkoutHead,
Cancel: null
}
})
} else {
return checkoutHead()
}
} else {
return Promise.resolve(false)
}
}
}
| src/workspace.js | 'use strict'
const _ = require('underscore-plus')
const url = require('url')
const path = require('path')
const {Emitter, Disposable, CompositeDisposable} = require('event-kit')
const fs = require('fs-plus')
const {Directory} = require('pathwatcher')
const DefaultDirectorySearcher = require('./default-directory-searcher')
const Model = require('./model')
const TextEditor = require('./text-editor')
const PaneContainer = require('./pane-container')
const Panel = require('./panel')
const PanelContainer = require('./panel-container')
const Task = require('./task')
// Essential: Represents the state of the user interface for the entire window.
// An instance of this class is available via the `atom.workspace` global.
//
// Interact with this object to open files, be notified of current and future
// editors, and manipulate panes. To add panels, use {Workspace::addTopPanel}
// and friends.
//
// * `editor` {TextEditor} the new editor
//
module.exports = class Workspace extends Model {
constructor (params) {
super(...arguments)
this.updateWindowTitle = this.updateWindowTitle.bind(this)
this.updateDocumentEdited = this.updateDocumentEdited.bind(this)
this.didDestroyPaneItem = this.didDestroyPaneItem.bind(this)
this.packageManager = params.packageManager
this.config = params.config
this.project = params.project
this.notificationManager = params.notificationManager
this.viewRegistry = params.viewRegistry
this.grammarRegistry = params.grammarRegistry
this.applicationDelegate = params.applicationDelegate
this.assert = params.assert
this.deserializerManager = params.deserializerManager
this.textEditorRegistry = params.textEditorRegistry
this.emitter = new Emitter()
this.openers = []
this.destroyedItemURIs = []
this.paneContainer = new PaneContainer({
config: this.config,
applicationDelegate: this.applicationDelegate,
notificationManager: this.notificationManager,
deserializerManager: this.deserializerManager
})
this.paneContainer.onDidDestroyPaneItem(this.didDestroyPaneItem)
this.defaultDirectorySearcher = new DefaultDirectorySearcher()
this.consumeServices(this.packageManager)
// One cannot simply .bind here since it could be used as a component with
// Etch, in which case it'd be `new`d. And when it's `new`d, `this` is always
// the newly created object.
const realThis = this
this.buildTextEditor = (params) => Workspace.prototype.buildTextEditor.call(realThis, params)
this.panelContainers = {
top: new PanelContainer({location: 'top'}),
left: new PanelContainer({location: 'left'}),
right: new PanelContainer({location: 'right'}),
bottom: new PanelContainer({location: 'bottom'}),
header: new PanelContainer({location: 'header'}),
footer: new PanelContainer({location: 'footer'}),
modal: new PanelContainer({location: 'modal'})
}
this.subscribeToEvents()
}
reset (packageManager) {
this.packageManager = packageManager
this.emitter.dispose()
this.emitter = new Emitter()
this.paneContainer.destroy()
_.values(this.panelContainers).forEach(panelContainer => { panelContainer.destroy() })
this.paneContainer = new PaneContainer({
config: this.config,
applicationDelegate: this.applicationDelegate,
notificationManager: this.notificationManager,
deserializerManager: this.deserializerManager
})
this.paneContainer.onDidDestroyPaneItem(this.didDestroyPaneItem)
this.panelContainers = {
top: new PanelContainer({location: 'top'}),
left: new PanelContainer({location: 'left'}),
right: new PanelContainer({location: 'right'}),
bottom: new PanelContainer({location: 'bottom'}),
header: new PanelContainer({location: 'header'}),
footer: new PanelContainer({location: 'footer'}),
modal: new PanelContainer({location: 'modal'})
}
this.originalFontSize = null
this.openers = []
this.destroyedItemURIs = []
this.consumeServices(this.packageManager)
}
subscribeToEvents () {
this.subscribeToActiveItem()
this.subscribeToFontSize()
this.subscribeToAddedItems()
}
consumeServices ({serviceHub}) {
this.directorySearchers = []
serviceHub.consume(
'atom.directory-searcher',
'^0.1.0',
provider => this.directorySearchers.unshift(provider)
)
}
// Called by the Serializable mixin during serialization.
serialize () {
return {
deserializer: 'Workspace',
paneContainer: this.paneContainer.serialize(),
packagesWithActiveGrammars: this.getPackageNamesWithActiveGrammars(),
destroyedItemURIs: this.destroyedItemURIs.slice()
}
}
deserialize (state, deserializerManager) {
const packagesWithActiveGrammars =
state.packagesWithActiveGrammars != null ? state.packagesWithActiveGrammars : []
for (let packageName of packagesWithActiveGrammars) {
const pkg = this.packageManager.getLoadedPackage(packageName)
if (pkg != null) {
pkg.loadGrammarsSync()
}
}
if (state.destroyedItemURIs != null) {
this.destroyedItemURIs = state.destroyedItemURIs
}
return this.paneContainer.deserialize(state.paneContainer, deserializerManager)
}
getPackageNamesWithActiveGrammars () {
const packageNames = []
const addGrammar = ({includedGrammarScopes, packageName} = {}) => {
if (!packageName) { return }
// Prevent cycles
if (packageNames.indexOf(packageName) !== -1) { return }
packageNames.push(packageName)
for (let scopeName of includedGrammarScopes != null ? includedGrammarScopes : []) {
addGrammar(this.grammarRegistry.grammarForScopeName(scopeName))
}
}
const editors = this.getTextEditors()
for (let editor of editors) { addGrammar(editor.getGrammar()) }
if (editors.length > 0) {
for (let grammar of this.grammarRegistry.getGrammars()) {
if (grammar.injectionSelector) {
addGrammar(grammar)
}
}
}
return _.uniq(packageNames)
}
subscribeToActiveItem () {
this.updateWindowTitle()
this.updateDocumentEdited()
this.project.onDidChangePaths(this.updateWindowTitle)
this.observeActivePaneItem(item => {
this.updateWindowTitle()
this.updateDocumentEdited()
if (this.activeItemSubscriptions != null) {
this.activeItemSubscriptions.dispose()
}
this.activeItemSubscriptions = new CompositeDisposable()
let modifiedSubscription, titleSubscription
if (item != null && typeof item.onDidChangeTitle === 'function') {
titleSubscription = item.onDidChangeTitle(this.updateWindowTitle)
} else if (item != null && typeof item.on === 'function') {
titleSubscription = item.on('title-changed', this.updateWindowTitle)
if (titleSubscription == null || typeof titleSubscription.dispose !== 'function') {
titleSubscription = new Disposable(() => {
item.off('title-changed', this.updateWindowTitle)
})
}
}
if (item != null && typeof item.onDidChangeModified === 'function') {
modifiedSubscription = item.onDidChangeModified(this.updateDocumentEdited)
} else if (item != null && typeof item.on === 'function') {
modifiedSubscription = item.on('modified-status-changed', this.updateDocumentEdited)
if (modifiedSubscription == null || typeof modifiedSubscription.dispose !== 'function') {
modifiedSubscription = new Disposable(() => {
item.off('modified-status-changed', this.updateDocumentEdited)
})
}
}
if (titleSubscription != null) { this.activeItemSubscriptions.add(titleSubscription) }
if (modifiedSubscription != null) { this.activeItemSubscriptions.add(modifiedSubscription) }
})
}
subscribeToAddedItems () {
this.onDidAddPaneItem(({item, pane, index}) => {
if (item instanceof TextEditor) {
const subscriptions = new CompositeDisposable(
this.textEditorRegistry.add(item),
this.textEditorRegistry.maintainGrammar(item),
this.textEditorRegistry.maintainConfig(item),
item.observeGrammar(this.handleGrammarUsed.bind(this))
)
item.onDidDestroy(() => { subscriptions.dispose() })
this.emitter.emit('did-add-text-editor', {textEditor: item, pane, index})
}
})
}
// Updates the application's title and proxy icon based on whichever file is
// open.
updateWindowTitle () {
let itemPath, itemTitle, projectPath, representedPath
const appName = 'Atom'
const left = this.project.getPaths()
const projectPaths = left != null ? left : []
const item = this.getActivePaneItem()
if (item) {
itemPath = typeof item.getPath === 'function' ? item.getPath() : undefined
const longTitle = typeof item.getLongTitle === 'function' ? item.getLongTitle() : undefined
itemTitle = longTitle == null
? (typeof item.getTitle === 'function' ? item.getTitle() : undefined)
: longTitle
projectPath = _.find(
projectPaths,
projectPath =>
(itemPath === projectPath) || (itemPath != null ? itemPath.startsWith(projectPath + path.sep) : undefined)
)
}
if (itemTitle == null) { itemTitle = 'untitled' }
if (projectPath == null) { projectPath = itemPath ? path.dirname(itemPath) : projectPaths[0] }
if (projectPath != null) {
projectPath = fs.tildify(projectPath)
}
const titleParts = []
if ((item != null) && (projectPath != null)) {
titleParts.push(itemTitle, projectPath)
representedPath = itemPath != null ? itemPath : projectPath
} else if (projectPath != null) {
titleParts.push(projectPath)
representedPath = projectPath
} else {
titleParts.push(itemTitle)
representedPath = ''
}
if (process.platform !== 'darwin') {
titleParts.push(appName)
}
document.title = titleParts.join(' \u2014 ')
this.applicationDelegate.setRepresentedFilename(representedPath)
}
// On macOS, fades the application window's proxy icon when the current file
// has been modified.
updateDocumentEdited () {
const activePaneItem = this.getActivePaneItem()
const modified = activePaneItem != null && typeof activePaneItem.isModified === 'function'
? activePaneItem.isModified() || false
: false
this.applicationDelegate.setWindowDocumentEdited(modified)
}
/*
Section: Event Subscription
*/
// Essential: Invoke the given callback with all current and future text
// editors in the workspace.
//
// * `callback` {Function} to be called with current and future text editors.
// * `editor` An {TextEditor} that is present in {::getTextEditors} at the time
// of subscription or that is added at some later time.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeTextEditors (callback) {
for (let textEditor of this.getTextEditors()) { callback(textEditor) }
return this.onDidAddTextEditor(({textEditor}) => callback(textEditor))
}
// Essential: Invoke the given callback with all current and future panes items
// in the workspace.
//
// * `callback` {Function} to be called with current and future pane items.
// * `item` An item that is present in {::getPaneItems} at the time of
// subscription or that is added at some later time.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observePaneItems (callback) { return this.paneContainer.observePaneItems(callback) }
// Essential: Invoke the given callback when the active pane item changes.
//
// Because observers are invoked synchronously, it's important not to perform
// any expensive operations via this method. Consider
// {::onDidStopChangingActivePaneItem} to delay operations until after changes
// stop occurring.
//
// * `callback` {Function} to be called when the active pane item changes.
// * `item` The active pane item.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeActivePaneItem (callback) {
return this.paneContainer.onDidChangeActivePaneItem(callback)
}
// Essential: Invoke the given callback when the active pane item stops
// changing.
//
// Observers are called asynchronously 100ms after the last active pane item
// change. Handling changes here rather than in the synchronous
// {::onDidChangeActivePaneItem} prevents unneeded work if the user is quickly
// changing or closing tabs and ensures critical UI feedback, like changing the
// highlighted tab, gets priority over work that can be done asynchronously.
//
// * `callback` {Function} to be called when the active pane item stopts
// changing.
// * `item` The active pane item.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidStopChangingActivePaneItem (callback) {
return this.paneContainer.onDidStopChangingActivePaneItem(callback)
}
// Essential: Invoke the given callback with the current active pane item and
// with all future active pane items in the workspace.
//
// * `callback` {Function} to be called when the active pane item changes.
// * `item` The current active pane item.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeActivePaneItem (callback) { return this.paneContainer.observeActivePaneItem(callback) }
// Essential: Invoke the given callback whenever an item is opened. Unlike
// {::onDidAddPaneItem}, observers will be notified for items that are already
// present in the workspace when they are reopened.
//
// * `callback` {Function} to be called whenever an item is opened.
// * `event` {Object} with the following keys:
// * `uri` {String} representing the opened URI. Could be `undefined`.
// * `item` The opened item.
// * `pane` The pane in which the item was opened.
// * `index` The index of the opened item on its pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidOpen (callback) {
return this.emitter.on('did-open', callback)
}
// Extended: Invoke the given callback when a pane is added to the workspace.
//
// * `callback` {Function} to be called panes are added.
// * `event` {Object} with the following keys:
// * `pane` The added pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddPane (callback) { return this.paneContainer.onDidAddPane(callback) }
// Extended: Invoke the given callback before a pane is destroyed in the
// workspace.
//
// * `callback` {Function} to be called before panes are destroyed.
// * `event` {Object} with the following keys:
// * `pane` The pane to be destroyed.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onWillDestroyPane (callback) { return this.paneContainer.onWillDestroyPane(callback) }
// Extended: Invoke the given callback when a pane is destroyed in the
// workspace.
//
// * `callback` {Function} to be called panes are destroyed.
// * `event` {Object} with the following keys:
// * `pane` The destroyed pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidDestroyPane (callback) { return this.paneContainer.onDidDestroyPane(callback) }
// Extended: Invoke the given callback with all current and future panes in the
// workspace.
//
// * `callback` {Function} to be called with current and future panes.
// * `pane` A {Pane} that is present in {::getPanes} at the time of
// subscription or that is added at some later time.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observePanes (callback) { return this.paneContainer.observePanes(callback) }
// Extended: Invoke the given callback when the active pane changes.
//
// * `callback` {Function} to be called when the active pane changes.
// * `pane` A {Pane} that is the current return value of {::getActivePane}.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeActivePane (callback) { return this.paneContainer.onDidChangeActivePane(callback) }
// Extended: Invoke the given callback with the current active pane and when
// the active pane changes.
//
// * `callback` {Function} to be called with the current and future active#
// panes.
// * `pane` A {Pane} that is the current return value of {::getActivePane}.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeActivePane (callback) { return this.paneContainer.observeActivePane(callback) }
// Extended: Invoke the given callback when a pane item is added to the
// workspace.
//
// * `callback` {Function} to be called when pane items are added.
// * `event` {Object} with the following keys:
// * `item` The added pane item.
// * `pane` {Pane} containing the added item.
// * `index` {Number} indicating the index of the added item in its pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddPaneItem (callback) { return this.paneContainer.onDidAddPaneItem(callback) }
// Extended: Invoke the given callback when a pane item is about to be
// destroyed, before the user is prompted to save it.
//
// * `callback` {Function} to be called before pane items are destroyed.
// * `event` {Object} with the following keys:
// * `item` The item to be destroyed.
// * `pane` {Pane} containing the item to be destroyed.
// * `index` {Number} indicating the index of the item to be destroyed in
// its pane.
//
// Returns a {Disposable} on which `.dispose` can be called to unsubscribe.
onWillDestroyPaneItem (callback) { return this.paneContainer.onWillDestroyPaneItem(callback) }
// Extended: Invoke the given callback when a pane item is destroyed.
//
// * `callback` {Function} to be called when pane items are destroyed.
// * `event` {Object} with the following keys:
// * `item` The destroyed item.
// * `pane` {Pane} containing the destroyed item.
// * `index` {Number} indicating the index of the destroyed item in its
// pane.
//
// Returns a {Disposable} on which `.dispose` can be called to unsubscribe.
onDidDestroyPaneItem (callback) { return this.paneContainer.onDidDestroyPaneItem(callback) }
// Extended: Invoke the given callback when a text editor is added to the
// workspace.
//
// * `callback` {Function} to be called panes are added.
// * `event` {Object} with the following keys:
// * `textEditor` {TextEditor} that was added.
// * `pane` {Pane} containing the added text editor.
// * `index` {Number} indicating the index of the added text editor in its
// pane.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddTextEditor (callback) {
return this.emitter.on('did-add-text-editor', callback)
}
/*
Section: Opening
*/
// Essential: Opens the given URI in Atom asynchronously.
// If the URI is already open, the existing item for that URI will be
// activated. If no URI is given, or no registered opener can open
// the URI, a new empty {TextEditor} will be created.
//
// * `uri` (optional) A {String} containing a URI.
// * `options` (optional) {Object}
// * `initialLine` A {Number} indicating which row to move the cursor to
// initially. Defaults to `0`.
// * `initialColumn` A {Number} indicating which column to move the cursor to
// initially. Defaults to `0`.
// * `split` Either 'left', 'right', 'up' or 'down'.
// If 'left', the item will be opened in leftmost pane of the current active pane's row.
// If 'right', the item will be opened in the rightmost pane of the current active pane's row. If only one pane exists in the row, a new pane will be created.
// If 'up', the item will be opened in topmost pane of the current active pane's column.
// If 'down', the item will be opened in the bottommost pane of the current active pane's column. If only one pane exists in the column, a new pane will be created.
// * `activatePane` A {Boolean} indicating whether to call {Pane::activate} on
// containing pane. Defaults to `true`.
// * `activateItem` A {Boolean} indicating whether to call {Pane::activateItem}
// on containing pane. Defaults to `true`.
// * `pending` A {Boolean} indicating whether or not the item should be opened
// in a pending state. Existing pending items in a pane are replaced with
// new pending items when they are opened.
// * `searchAllPanes` A {Boolean}. If `true`, the workspace will attempt to
// activate an existing item for the given URI on any pane.
// If `false`, only the active pane will be searched for
// an existing item for the same URI. Defaults to `false`.
//
// Returns a {Promise} that resolves to the {TextEditor} for the file URI.
open (uri_, options = {}) {
const { searchAllPanes } = options
const { split } = options
const uri = this.project.resolvePath(uri_)
if (!atom.config.get('core.allowPendingPaneItems')) {
options.pending = false
}
// Avoid adding URLs as recent documents to work-around this Spotlight crash:
// https://github.com/atom/atom/issues/10071
if ((uri != null) && ((url.parse(uri).protocol == null) || (process.platform === 'win32'))) {
this.applicationDelegate.addRecentDocument(uri)
}
let pane
if (searchAllPanes) { pane = this.paneContainer.paneForURI(uri) }
if (pane == null) {
switch (split) {
case 'left':
pane = this.getActivePane().findLeftmostSibling()
break
case 'right':
pane = this.getActivePane().findOrCreateRightmostSibling()
break
case 'up':
pane = this.getActivePane().findTopmostSibling()
break
case 'down':
pane = this.getActivePane().findOrCreateBottommostSibling()
break
default:
pane = this.getActivePane()
break
}
}
return this.openURIInPane(uri, pane, options)
}
// Open Atom's license in the active pane.
openLicense () {
return this.open(path.join(process.resourcesPath, 'LICENSE.md'))
}
// Synchronously open the given URI in the active pane. **Only use this method
// in specs. Calling this in production code will block the UI thread and
// everyone will be mad at you.**
//
// * `uri` A {String} containing a URI.
// * `options` An optional options {Object}
// * `initialLine` A {Number} indicating which row to move the cursor to
// initially. Defaults to `0`.
// * `initialColumn` A {Number} indicating which column to move the cursor to
// initially. Defaults to `0`.
// * `activatePane` A {Boolean} indicating whether to call {Pane::activate} on
// the containing pane. Defaults to `true`.
// * `activateItem` A {Boolean} indicating whether to call {Pane::activateItem}
// on containing pane. Defaults to `true`.
openSync (uri_ = '', options = {}) {
const {initialLine, initialColumn} = options
const activatePane = options.activatePane != null ? options.activatePane : true
const activateItem = options.activateItem != null ? options.activateItem : true
const uri = this.project.resolvePath(uri)
let item = this.getActivePane().itemForURI(uri)
if (uri && (item == null)) {
for (const opener of this.getOpeners()) {
item = opener(uri, options)
if (item) break
}
}
if (item == null) {
item = this.project.openSync(uri, {initialLine, initialColumn})
}
if (activateItem) {
this.getActivePane().activateItem(item)
}
this.itemOpened(item)
if (activatePane) {
this.getActivePane().activate()
}
return item
}
openURIInPane (uri, pane, options = {}) {
const activatePane = options.activatePane != null ? options.activatePane : true
const activateItem = options.activateItem != null ? options.activateItem : true
let item
if (uri != null) {
item = pane.itemForURI(uri)
if (item == null) {
for (let opener of this.getOpeners()) {
item = opener(uri, options)
if (item != null) break
}
} else if (!options.pending && (pane.getPendingItem() === item)) {
pane.clearPendingItem()
}
}
try {
if (item == null) {
item = this.openTextFile(uri, options)
}
} catch (error) {
switch (error.code) {
case 'CANCELLED':
return Promise.resolve()
case 'EACCES':
this.notificationManager.addWarning(`Permission denied '${error.path}'`)
return Promise.resolve()
case 'EPERM':
case 'EBUSY':
case 'ENXIO':
case 'EIO':
case 'ENOTCONN':
case 'UNKNOWN':
case 'ECONNRESET':
case 'EINVAL':
case 'EMFILE':
case 'ENOTDIR':
case 'EAGAIN':
this.notificationManager.addWarning(
`Unable to open '${error.path != null ? error.path : uri}'`,
{detail: error.message}
)
return Promise.resolve()
default:
throw error
}
}
return Promise.resolve(item)
.then(item => {
let initialColumn
if (pane.isDestroyed()) {
return item
}
this.itemOpened(item)
if (activateItem) {
pane.activateItem(item, {pending: options.pending})
}
if (activatePane) {
pane.activate()
}
let initialLine = initialColumn = 0
if (!Number.isNaN(options.initialLine)) {
initialLine = options.initialLine
}
if (!Number.isNaN(options.initialColumn)) {
initialColumn = options.initialColumn
}
if ((initialLine >= 0) || (initialColumn >= 0)) {
if (typeof item.setCursorBufferPosition === 'function') {
item.setCursorBufferPosition([initialLine, initialColumn])
}
}
const index = pane.getActiveItemIndex()
this.emitter.emit('did-open', {uri, pane, item, index})
return item
}
)
}
openTextFile (uri, options) {
const filePath = this.project.resolvePath(uri)
if (filePath != null) {
try {
fs.closeSync(fs.openSync(filePath, 'r'))
} catch (error) {
// allow ENOENT errors to create an editor for paths that dont exist
if (error.code !== 'ENOENT') {
throw error
}
}
}
const fileSize = fs.getSizeSync(filePath)
const largeFileMode = fileSize >= (2 * 1048576) // 2MB
if (fileSize >= (this.config.get('core.warnOnLargeFileLimit') * 1048576)) { // 20MB by default
const choice = this.applicationDelegate.confirm({
message: 'Atom will be unresponsive during the loading of very large files.',
detailedMessage: 'Do you still want to load this file?',
buttons: ['Proceed', 'Cancel']
})
if (choice === 1) {
const error = new Error()
error.code = 'CANCELLED'
throw error
}
}
return this.project.bufferForPath(filePath, options)
.then(buffer => {
return this.textEditorRegistry.build(Object.assign({buffer, largeFileMode, autoHeight: false}, options))
})
}
handleGrammarUsed (grammar) {
if (grammar == null) { return }
return this.packageManager.triggerActivationHook(`${grammar.packageName}:grammar-used`)
}
// Public: Returns a {Boolean} that is `true` if `object` is a `TextEditor`.
//
// * `object` An {Object} you want to perform the check against.
isTextEditor (object) {
return object instanceof TextEditor
}
// Extended: Create a new text editor.
//
// Returns a {TextEditor}.
buildTextEditor (params) {
const editor = this.textEditorRegistry.build(params)
const subscriptions = new CompositeDisposable(
this.textEditorRegistry.maintainGrammar(editor),
this.textEditorRegistry.maintainConfig(editor)
)
editor.onDidDestroy(() => { subscriptions.dispose() })
return editor
}
// Public: Asynchronously reopens the last-closed item's URI if it hasn't already been
// reopened.
//
// Returns a {Promise} that is resolved when the item is opened
reopenItem () {
const uri = this.destroyedItemURIs.pop()
if (uri) {
return this.open(uri)
} else {
return Promise.resolve()
}
}
// Public: Register an opener for a uri.
//
// When a URI is opened via {Workspace::open}, Atom loops through its registered
// opener functions until one returns a value for the given uri.
// Openers are expected to return an object that inherits from HTMLElement or
// a model which has an associated view in the {ViewRegistry}.
// A {TextEditor} will be used if no opener returns a value.
//
// ## Examples
//
// ```coffee
// atom.workspace.addOpener (uri) ->
// if path.extname(uri) is '.toml'
// return new TomlEditor(uri)
// ```
//
// * `opener` A {Function} to be called when a path is being opened.
//
// Returns a {Disposable} on which `.dispose()` can be called to remove the
// opener.
//
// Note that the opener will be called if and only if the URI is not already open
// in the current pane. The searchAllPanes flag expands the search from the
// current pane to all panes. If you wish to open a view of a different type for
// a file that is already open, consider changing the protocol of the URI. For
// example, perhaps you wish to preview a rendered version of the file `/foo/bar/baz.quux`
// that is already open in a text editor view. You could signal this by calling
// {Workspace::open} on the URI `quux-preview://foo/bar/baz.quux`. Then your opener
// can check the protocol for quux-preview and only handle those URIs that match.
addOpener (opener) {
this.openers.push(opener)
return new Disposable(() => { _.remove(this.openers, opener) })
}
getOpeners () {
return this.openers
}
/*
Section: Pane Items
*/
// Essential: Get all pane items in the workspace.
//
// Returns an {Array} of items.
getPaneItems () {
return this.paneContainer.getPaneItems()
}
// Essential: Get the active {Pane}'s active item.
//
// Returns an pane item {Object}.
getActivePaneItem () {
return this.paneContainer.getActivePaneItem()
}
// Essential: Get all text editors in the workspace.
//
// Returns an {Array} of {TextEditor}s.
getTextEditors () {
return this.getPaneItems().filter(item => item instanceof TextEditor)
}
// Essential: Get the active item if it is an {TextEditor}.
//
// Returns an {TextEditor} or `undefined` if the current active item is not an
// {TextEditor}.
getActiveTextEditor () {
const activeItem = this.getActivePaneItem()
if (activeItem instanceof TextEditor) { return activeItem }
}
// Save all pane items.
saveAll () {
return this.paneContainer.saveAll()
}
confirmClose (options) {
return this.paneContainer.confirmClose(options)
}
// Save the active pane item.
//
// If the active pane item currently has a URI according to the item's
// `.getURI` method, calls `.save` on the item. Otherwise
// {::saveActivePaneItemAs} # will be called instead. This method does nothing
// if the active item does not implement a `.save` method.
saveActivePaneItem () {
return this.getActivePane().saveActiveItem()
}
// Prompt the user for a path and save the active pane item to it.
//
// Opens a native dialog where the user selects a path on disk, then calls
// `.saveAs` on the item with the selected path. This method does nothing if
// the active item does not implement a `.saveAs` method.
saveActivePaneItemAs () {
return this.getActivePane().saveActiveItemAs()
}
// Destroy (close) the active pane item.
//
// Removes the active pane item and calls the `.destroy` method on it if one is
// defined.
destroyActivePaneItem () {
return this.getActivePane().destroyActiveItem()
}
/*
Section: Panes
*/
// Extended: Get all panes in the workspace.
//
// Returns an {Array} of {Pane}s.
getPanes () {
return this.paneContainer.getPanes()
}
// Extended: Get the active {Pane}.
//
// Returns a {Pane}.
getActivePane () {
return this.paneContainer.getActivePane()
}
// Extended: Make the next pane active.
activateNextPane () {
return this.paneContainer.activateNextPane()
}
// Extended: Make the previous pane active.
activatePreviousPane () {
return this.paneContainer.activatePreviousPane()
}
// Extended: Get the first {Pane} with an item for the given URI.
//
// * `uri` {String} uri
//
// Returns a {Pane} or `undefined` if no pane exists for the given URI.
paneForURI (uri) {
return this.paneContainer.paneForURI(uri)
}
// Extended: Get the {Pane} containing the given item.
//
// * `item` Item the returned pane contains.
//
// Returns a {Pane} or `undefined` if no pane exists for the given item.
paneForItem (item) {
return this.paneContainer.paneForItem(item)
}
// Destroy (close) the active pane.
destroyActivePane () {
const activePane = this.getActivePane()
if (activePane != null) {
activePane.destroy()
}
}
// Close the active pane item, or the active pane if it is empty,
// or the current window if there is only the empty root pane.
closeActivePaneItemOrEmptyPaneOrWindow () {
if (this.getActivePaneItem() != null) {
this.destroyActivePaneItem()
} else if (this.getPanes().length > 1) {
this.destroyActivePane()
} else if (this.config.get('core.closeEmptyWindows')) {
atom.close()
}
}
// Increase the editor font size by 1px.
increaseFontSize () {
this.config.set('editor.fontSize', this.config.get('editor.fontSize') + 1)
}
// Decrease the editor font size by 1px.
decreaseFontSize () {
const fontSize = this.config.get('editor.fontSize')
if (fontSize > 1) {
this.config.set('editor.fontSize', fontSize - 1)
}
}
// Restore to the window's original editor font size.
resetFontSize () {
if (this.originalFontSize) {
this.config.set('editor.fontSize', this.originalFontSize)
}
}
subscribeToFontSize () {
return this.config.onDidChange('editor.fontSize', ({oldValue}) => {
if (this.originalFontSize == null) {
this.originalFontSize = oldValue
}
})
}
// Removes the item's uri from the list of potential items to reopen.
itemOpened (item) {
let uri
if (typeof item.getURI === 'function') {
uri = item.getURI()
} else if (typeof item.getUri === 'function') {
uri = item.getUri()
}
if (uri != null) {
_.remove(this.destroyedItemURIs, uri)
}
}
// Adds the destroyed item's uri to the list of items to reopen.
didDestroyPaneItem ({item}) {
let uri
if (typeof item.getURI === 'function') {
uri = item.getURI()
} else if (typeof item.getUri === 'function') {
uri = item.getUri()
}
if (uri != null) {
this.destroyedItemURIs.push(uri)
}
}
// Called by Model superclass when destroyed
destroyed () {
this.paneContainer.destroy()
if (this.activeItemSubscriptions != null) {
this.activeItemSubscriptions.dispose()
}
}
/*
Section: Panels
Panels are used to display UI related to an editor window. They are placed at one of the four
edges of the window: left, right, top or bottom. If there are multiple panels on the same window
edge they are stacked in order of priority: higher priority is closer to the center, lower
priority towards the edge.
*Note:* If your panel changes its size throughout its lifetime, consider giving it a higher
priority, allowing fixed size panels to be closer to the edge. This allows control targets to
remain more static for easier targeting by users that employ mice or trackpads. (See
[atom/atom#4834](https://github.com/atom/atom/issues/4834) for discussion.)
*/
// Essential: Get an {Array} of all the panel items at the bottom of the editor window.
getBottomPanels () {
return this.getPanels('bottom')
}
// Essential: Adds a panel item to the bottom of the editor window.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addBottomPanel (options) {
return this.addPanel('bottom', options)
}
// Essential: Get an {Array} of all the panel items to the left of the editor window.
getLeftPanels () {
return this.getPanels('left')
}
// Essential: Adds a panel item to the left of the editor window.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addLeftPanel (options) {
return this.addPanel('left', options)
}
// Essential: Get an {Array} of all the panel items to the right of the editor window.
getRightPanels () {
return this.getPanels('right')
}
// Essential: Adds a panel item to the right of the editor window.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addRightPanel (options) {
return this.addPanel('right', options)
}
// Essential: Get an {Array} of all the panel items at the top of the editor window.
getTopPanels () {
return this.getPanels('top')
}
// Essential: Adds a panel item to the top of the editor window above the tabs.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addTopPanel (options) {
return this.addPanel('top', options)
}
// Essential: Get an {Array} of all the panel items in the header.
getHeaderPanels () {
return this.getPanels('header')
}
// Essential: Adds a panel item to the header.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addHeaderPanel (options) {
return this.addPanel('header', options)
}
// Essential: Get an {Array} of all the panel items in the footer.
getFooterPanels () {
return this.getPanels('footer')
}
// Essential: Adds a panel item to the footer.
//
// * `options` {Object}
// * `item` Your panel content. It can be DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// latter. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addFooterPanel (options) {
return this.addPanel('footer', options)
}
// Essential: Get an {Array} of all the modal panel items
getModalPanels () {
return this.getPanels('modal')
}
// Essential: Adds a panel item as a modal dialog.
//
// * `options` {Object}
// * `item` Your panel content. It can be a DOM element, a jQuery element, or
// a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
// model option. See {ViewRegistry::addViewProvider} for more information.
// * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
// (default: true)
// * `priority` (optional) {Number} Determines stacking order. Lower priority items are
// forced closer to the edges of the window. (default: 100)
//
// Returns a {Panel}
addModalPanel (options = {}) {
return this.addPanel('modal', options)
}
// Essential: Returns the {Panel} associated with the given item. Returns
// `null` when the item has no panel.
//
// * `item` Item the panel contains
panelForItem (item) {
for (let location in this.panelContainers) {
const container = this.panelContainers[location]
const panel = container.panelForItem(item)
if (panel != null) { return panel }
}
return null
}
getPanels (location) {
return this.panelContainers[location].getPanels()
}
addPanel (location, options) {
if (options == null) { options = {} }
return this.panelContainers[location].addPanel(new Panel(options))
}
/*
Section: Searching and Replacing
*/
// Public: Performs a search across all files in the workspace.
//
// * `regex` {RegExp} to search with.
// * `options` (optional) {Object}
// * `paths` An {Array} of glob patterns to search within.
// * `onPathsSearched` (optional) {Function} to be periodically called
// with number of paths searched.
// * `iterator` {Function} callback on each file found.
//
// Returns a {Promise} with a `cancel()` method that will cancel all
// of the underlying searches that were started as part of this scan.
scan (regex, options = {}, iterator) {
if (_.isFunction(options)) {
iterator = options
options = {}
}
// Find a searcher for every Directory in the project. Each searcher that is matched
// will be associated with an Array of Directory objects in the Map.
const directoriesForSearcher = new Map()
for (const directory of this.project.getDirectories()) {
let searcher = this.defaultDirectorySearcher
for (const directorySearcher of this.directorySearchers) {
if (directorySearcher.canSearchDirectory(directory)) {
searcher = directorySearcher
break
}
}
let directories = directoriesForSearcher.get(searcher)
if (!directories) {
directories = []
directoriesForSearcher.set(searcher, directories)
}
directories.push(directory)
}
// Define the onPathsSearched callback.
let onPathsSearched
if (_.isFunction(options.onPathsSearched)) {
// Maintain a map of directories to the number of search results. When notified of a new count,
// replace the entry in the map and update the total.
const onPathsSearchedOption = options.onPathsSearched
let totalNumberOfPathsSearched = 0
const numberOfPathsSearchedForSearcher = new Map()
onPathsSearched = function (searcher, numberOfPathsSearched) {
const oldValue = numberOfPathsSearchedForSearcher.get(searcher)
if (oldValue) {
totalNumberOfPathsSearched -= oldValue
}
numberOfPathsSearchedForSearcher.set(searcher, numberOfPathsSearched)
totalNumberOfPathsSearched += numberOfPathsSearched
return onPathsSearchedOption(totalNumberOfPathsSearched)
}
} else {
onPathsSearched = function () {}
}
// Kick off all of the searches and unify them into one Promise.
const allSearches = []
directoriesForSearcher.forEach((directories, searcher) => {
const searchOptions = {
inclusions: options.paths || [],
includeHidden: true,
excludeVcsIgnores: this.config.get('core.excludeVcsIgnoredPaths'),
exclusions: this.config.get('core.ignoredNames'),
follow: this.config.get('core.followSymlinks'),
didMatch: result => {
if (!this.project.isPathModified(result.filePath)) {
return iterator(result)
}
},
didError (error) {
return iterator(null, error)
},
didSearchPaths (count) {
return onPathsSearched(searcher, count)
}
}
const directorySearcher = searcher.search(directories, regex, searchOptions)
allSearches.push(directorySearcher)
})
const searchPromise = Promise.all(allSearches)
for (let buffer of this.project.getBuffers()) {
if (buffer.isModified()) {
const filePath = buffer.getPath()
if (!this.project.contains(filePath)) {
continue
}
var matches = []
buffer.scan(regex, match => matches.push(match))
if (matches.length > 0) {
iterator({filePath, matches})
}
}
}
// Make sure the Promise that is returned to the client is cancelable. To be consistent
// with the existing behavior, instead of cancel() rejecting the promise, it should
// resolve it with the special value 'cancelled'. At least the built-in find-and-replace
// package relies on this behavior.
let isCancelled = false
const cancellablePromise = new Promise((resolve, reject) => {
const onSuccess = function () {
if (isCancelled) {
resolve('cancelled')
} else {
resolve(null)
}
}
const onFailure = function () {
for (let promise of allSearches) { promise.cancel() }
reject()
}
searchPromise.then(onSuccess, onFailure)
})
cancellablePromise.cancel = () => {
isCancelled = true
// Note that cancelling all of the members of allSearches will cause all of the searches
// to resolve, which causes searchPromise to resolve, which is ultimately what causes
// cancellablePromise to resolve.
allSearches.map((promise) => promise.cancel())
}
// Although this method claims to return a `Promise`, the `ResultsPaneView.onSearch()`
// method in the find-and-replace package expects the object returned by this method to have a
// `done()` method. Include a done() method until find-and-replace can be updated.
cancellablePromise.done = onSuccessOrFailure => {
cancellablePromise.then(onSuccessOrFailure, onSuccessOrFailure)
}
return cancellablePromise
}
// Public: Performs a replace across all the specified files in the project.
//
// * `regex` A {RegExp} to search with.
// * `replacementText` {String} to replace all matches of regex with.
// * `filePaths` An {Array} of file path strings to run the replace on.
// * `iterator` A {Function} callback on each file with replacements:
// * `options` {Object} with keys `filePath` and `replacements`.
//
// Returns a {Promise}.
replace (regex, replacementText, filePaths, iterator) {
return new Promise((resolve, reject) => {
let buffer
const openPaths = this.project.getBuffers().map(buffer => buffer.getPath())
const outOfProcessPaths = _.difference(filePaths, openPaths)
let inProcessFinished = !openPaths.length
let outOfProcessFinished = !outOfProcessPaths.length
const checkFinished = () => {
if (outOfProcessFinished && inProcessFinished) {
resolve()
}
}
if (!outOfProcessFinished.length) {
let flags = 'g'
if (regex.ignoreCase) { flags += 'i' }
const task = Task.once(
require.resolve('./replace-handler'),
outOfProcessPaths,
regex.source,
flags,
replacementText,
() => {
outOfProcessFinished = true
checkFinished()
}
)
task.on('replace:path-replaced', iterator)
task.on('replace:file-error', error => { iterator(null, error) })
}
for (buffer of this.project.getBuffers()) {
if (!filePaths.includes(buffer.getPath())) { continue }
const replacements = buffer.replace(regex, replacementText, iterator)
if (replacements) {
iterator({filePath: buffer.getPath(), replacements})
}
}
inProcessFinished = true
checkFinished()
})
}
checkoutHeadRevision (editor) {
if (editor.getPath()) {
const checkoutHead = () => {
return this.project.repositoryForDirectory(new Directory(editor.getDirectoryPath()))
.then(repository => repository != null ? repository.checkoutHeadForEditor(editor) : undefined)
}
if (this.config.get('editor.confirmCheckoutHeadRevision')) {
this.applicationDelegate.confirm({
message: 'Confirm Checkout HEAD Revision',
detailedMessage: `Are you sure you want to discard all changes to "${editor.getFileName()}" since the last Git commit?`,
buttons: {
OK: checkoutHead,
Cancel: null
}
})
} else {
return checkoutHead()
}
} else {
return Promise.resolve(false)
}
}
}
| Remove the buildTextEditor binding
The comment was actually no longer accurate since arrow functions
aren't newable. After doing an audit, @maxbrunsfeld determined that it
could just be removed.
| src/workspace.js | Remove the buildTextEditor binding | <ide><path>rc/workspace.js
<ide>
<ide> this.defaultDirectorySearcher = new DefaultDirectorySearcher()
<ide> this.consumeServices(this.packageManager)
<del>
<del> // One cannot simply .bind here since it could be used as a component with
<del> // Etch, in which case it'd be `new`d. And when it's `new`d, `this` is always
<del> // the newly created object.
<del> const realThis = this
<del> this.buildTextEditor = (params) => Workspace.prototype.buildTextEditor.call(realThis, params)
<ide>
<ide> this.panelContainers = {
<ide> top: new PanelContainer({location: 'top'}), |
|
Java | apache-2.0 | 41e10ffb799af602acf6862a2b9d75eae70b7849 | 0 | ukwa/blindex,ukwa/blindex,ukwa/blindex,ukwa/blindex,ukwa/blindex | package uk.bl.wa.blindex;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.hadoop.Solate;
import org.apache.solr.hadoop.SolrInputDocumentWritable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.com.bytecode.opencsv.CSVParser;
/**
*
* @author Andrew Jackson <[email protected]>
*
*/
public class IndexerJob {
private static final Logger LOG = LoggerFactory.getLogger(IndexerJob.class);
protected static String solrHomeZipName = "solrHome.zip";
/**
*
* This mapper parses the input table, downloads the relevant XML, parses
* the content into Solr documents, computes the target SolrCloud slice and
* passes them down to the reducer.
*
* @author Andrew Jackson <[email protected]>
*
*/
public static class Map extends MapReduceBase implements
Mapper<LongWritable, Text, IntWritable, SolrInputDocumentWritable> {
private CSVParser p = new CSVParser();
private Solate sp;
private String domidUrlPrefix;
/*
* (non-Javadoc)
*
* @see
* org.apache.hadoop.mapred.MapReduceBase#configure(org.apache.hadoop
* .mapred.JobConf)
*/
@Override
public void configure(JobConf job) {
super.configure(job);
//
String zkHost = "openstack2.ad.bl.uk:2181,openstack4.ad.bl.uk:2181,openstack5.ad.bl.uk:2181/solr";
String collection = "jisc2";
int numShards = 4;
sp = new Solate(zkHost, collection, numShards);
//
domidUrlPrefix = "http://194.66.239.142/did/";
}
public void map(LongWritable key, Text value,
OutputCollector<IntWritable, SolrInputDocumentWritable> output,
Reporter reporter)
throws IOException {
// String[] parts = value.toString().split("\\x01");
String[] parts = p.parseLine(value.toString());
// If this is the header line, return now:
if ("entityid".equals(parts[0]))
return;
// Otherwise, grab the content info:
String entityuid = parts[1];
String simpletitle = parts[3];
String originalname = parts[5];
String domid = parts[8];
// Construct URL:
URL xmlUrl = new URL(domidUrlPrefix + domid);
// Pass to the SAX-based parser to collect the outputs:
List<String> docs = null;
try {
docs = JISC2TextExtractor.extract(xmlUrl.openStream());
} catch (Exception e) {
e.printStackTrace();
return;
}
for (int i = 0; i < docs.size(); i++) {
// Skip empty records:
if (docs.get(i).length() == 0)
continue;
// Build up a Solr document:
String doc_id = entityuid + "/p" + i;
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id", doc_id);
doc.setField("simpletitle_s", simpletitle);
doc.setField("originalname_s", originalname);
doc.setField("domid_i", domid);
doc.setField("page_i", i);
doc.setField("content", docs.get(i));
output.collect(new IntWritable(sp.getPartition(doc_id, doc)),
new SolrInputDocumentWritable(doc));
}
}
}
/**
*
* This reducer collects the documents for each slice together and commits
* them to an embedded instance of the Solr server stored on HDFS
*
* @author Andrew Jackson <[email protected]>
*
*/
public static class Reduce extends MapReduceBase implements
Reducer<IntWritable, SolrInputDocumentWritable, Text, IntWritable> {
private FileSystem fs;
private Path solrHomeDir;
private Path outputDir;
private String shardPrefix = "shard";
/*
* (non-Javadoc)
*
* @see
* org.apache.hadoop.mapred.MapReduceBase#configure(org.apache.hadoop
* .mapred.JobConf)
*/
@Override
public void configure(JobConf job) {
super.configure(job);
try {
// Filesystem:
fs = FileSystem.get(job);
// Input:
solrHomeDir = findSolrConfig(job, solrHomeZipName);
} catch (IOException e) {
e.printStackTrace();
}
// Output:
outputDir = new Path("/user/admin/jisc2/solr/");
}
public void reduce(IntWritable key,
Iterator<SolrInputDocumentWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
int slice = key.get();
Path outputShardDir = new Path(outputDir, this.shardPrefix + slice);
EmbeddedSolrServer solrServer = JISC2TextExtractor
.createEmbeddedSolrServer(solrHomeDir, fs, outputShardDir);
while (values.hasNext()) {
SolrInputDocument doc = values.next().getSolrInputDocument();
try {
solrServer.add(doc);
} catch (SolrServerException e) {
e.printStackTrace();
}
}
output.collect(new Text("" + key), new IntWritable(1));
}
}
public static Path findSolrConfig(JobConf conf, String zipName)
throws IOException {
Path solrHome = null;
Path[] localArchives = DistributedCache.getLocalCacheArchives(conf);
if (localArchives.length == 0) {
throw new IOException(String.format("No local cache archives."));
}
for (Path unpackedDir : localArchives) {
if (unpackedDir.getName().equals(zipName)) {
LOG.info("Using this unpacked directory as solr home: {}", unpackedDir);
solrHome = unpackedDir;
break;
}
}
return solrHome;
}
/**
* c.f. SolrRecordWriter, SolrOutputFormat
*
* Cloudera Search defaults to: /solr/jisc2/core_node1 ...but note no
* replicas, which is why the shard-to-core mapping looks easy.
*
* Take /user/admin/jisc2-xmls/000000_0 Read line-by-line Split on 0x01.
*
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(IndexerJob.Map.class);
conf.setJobName("JISC2_Indexer");
conf.setMapOutputKeyClass(IntWritable.class);
conf.setMapOutputValueClass(SolrInputDocumentWritable.class);
conf.setMapperClass(Map.class);
conf.setNumMapTasks(4);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);
conf.setNumReduceTasks(4);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
// /user/admin/jisc2-xmls/table_sample.csv
FileInputFormat.setInputPaths(conf, new Path(
"/user/admin/jisc2-xmls/table_sample.csv"));
// /user/admin/jist2/solr
FileOutputFormat.setOutputPath(conf, new Path("/user/admin/jisc2/job"));
// File solrHomeZip = new
// File("src/main/resources/jisc2/solr_home.zip");
Path zipPath = new Path("/user/admin/jisc2-xmls/solr_home.zip");
FileSystem fs = FileSystem.get(conf);
// fs.copyFromLocalFile(new Path(solrHomeZip.toString()), zipPath);
final URI baseZipUrl = fs.getUri().resolve(
zipPath.toString() + '#' + solrHomeZipName);
DistributedCache.addCacheArchive(baseZipUrl, conf);
LOG.debug("Set Solr distributed cache: {}",
Arrays.asList(DistributedCache.getCacheArchives(conf)));
LOG.debug("Set zipPath: {}", zipPath);
JobClient.runJob(conf);
}
} | src/main/java/uk/bl/wa/blindex/IndexerJob.java | package uk.bl.wa.blindex;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.hadoop.Solate;
import org.apache.solr.hadoop.SolrInputDocumentWritable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.com.bytecode.opencsv.CSVParser;
/**
*
* @author Andrew Jackson <[email protected]>
*
*/
public class IndexerJob {
private static final Logger LOG = LoggerFactory.getLogger(IndexerJob.class);
protected static String solrHomeZipName = "solrHome.zip";
/**
*
* This mapper parses the input table, downloads the relevant XML, parses
* the content into Solr documents, computes the target SolrCloud slice and
* passes them down to the reducer.
*
* @author Andrew Jackson <[email protected]>
*
*/
public static class Map extends MapReduceBase implements
Mapper<LongWritable, Text, IntWritable, SolrInputDocumentWritable> {
private CSVParser p = new CSVParser();
private Solate sp;
private String domidUrlPrefix;
/*
* (non-Javadoc)
*
* @see
* org.apache.hadoop.mapred.MapReduceBase#configure(org.apache.hadoop
* .mapred.JobConf)
*/
@Override
public void configure(JobConf job) {
super.configure(job);
//
String zkHost = "openstack2.ad.bl.uk:2181,openstack4.ad.bl.uk:2181,openstack5.ad.bl.uk:2181/solr";
String collection = "jisc2";
int numShards = 4;
sp = new Solate(zkHost, collection, numShards);
//
domidUrlPrefix = "http://194.66.239.142/did/";
}
public void map(LongWritable key, Text value,
OutputCollector<IntWritable, SolrInputDocumentWritable> output,
Reporter reporter)
throws IOException {
// String[] parts = value.toString().split("\\x01");
String[] parts = p.parseLine(value.toString());
// If this is the header line, return now:
if ("entityid".equals(parts[0]))
return;
// Otherwise, grab the content info:
String entityuid = parts[1];
String simpletitle = parts[3];
String originalname = parts[5];
String domid = parts[8];
// Construct URL:
URL xmlUrl = new URL(domidUrlPrefix + domid);
// Pass to the SAX-based parser to collect the outputs:
List<String> docs = null;
try {
docs = JISC2TextExtractor.extract(xmlUrl.openStream());
} catch (Exception e) {
e.printStackTrace();
return;
}
for (int i = 0; i < docs.size(); i++) {
// Skip empty records:
if (docs.get(i).length() == 0)
continue;
// Build up a Solr document:
String doc_id = entityuid + "/p" + i;
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id", doc_id);
doc.setField("simpletitle_s", simpletitle);
doc.setField("originalname_s", originalname);
doc.setField("domid_i", domid);
doc.setField("page_i", i);
doc.setField("content", docs.get(i));
output.collect(new IntWritable(sp.getPartition(doc_id, doc)),
new SolrInputDocumentWritable(doc));
}
}
}
/**
*
* This reducer collects the documents for each slice together and commits
* them to an embedded instance of the Solr server stored on HDFS
*
* @author Andrew Jackson <[email protected]>
*
*/
public static class Reduce extends MapReduceBase implements
Reducer<IntWritable, SolrInputDocumentWritable, Text, IntWritable> {
private FileSystem fs;
private Path solrHomeDir;
private Path outputDir;
private String shardPrefix = "shard";
/*
* (non-Javadoc)
*
* @see
* org.apache.hadoop.mapred.MapReduceBase#configure(org.apache.hadoop
* .mapred.JobConf)
*/
@Override
public void configure(JobConf job) {
super.configure(job);
try {
// Filesystem:
fs = FileSystem.get(job);
// Input:
solrHomeDir = findSolrConfig(job, solrHomeZipName);
} catch (IOException e) {
e.printStackTrace();
}
// Output:
outputDir = new Path("/user/admin/jisc2/solr/");
}
public void reduce(IntWritable key,
Iterator<SolrInputDocumentWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
int slice = key.get();
Path outputShardDir = new Path(outputDir, this.shardPrefix + slice);
EmbeddedSolrServer solrServer = JISC2TextExtractor
.createEmbeddedSolrServer(solrHomeDir, fs, outputShardDir);
while (values.hasNext()) {
SolrInputDocument doc = values.next().getSolrInputDocument();
try {
solrServer.add(doc);
} catch (SolrServerException e) {
e.printStackTrace();
}
}
output.collect(new Text("" + key), new IntWritable(1));
}
}
public static Path findSolrConfig(JobConf conf, String zipName)
throws IOException {
Path solrHome = null;
Path[] localArchives = DistributedCache.getLocalCacheArchives(conf);
if (localArchives.length == 0) {
throw new IOException(String.format("No local cache archives."));
}
for (Path unpackedDir : localArchives) {
if (unpackedDir.getName().equals(zipName)) {
LOG.info("Using this unpacked directory as solr home: {}", unpackedDir);
solrHome = unpackedDir;
break;
}
}
return solrHome;
}
/**
* c.f. SolrRecordWriter, SolrOutputFormat
*
* Cloudera Search defaults to: /solr/jisc2/core_node1 ...but note no
* replicas, which is why the shard-to-core mapping looks easy.
*
* Take /user/admin/jisc2-xmls/000000_0 Read line-by-line Split on 0x01.
*
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(IndexerJob.Map.class);
conf.setJobName("JISC2_Indexer");
conf.setMapperClass(Map.class);
conf.setNumMapTasks(4);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);
conf.setNumReduceTasks(4);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
// /user/admin/jisc2-xmls/table_sample.csv
FileInputFormat.setInputPaths(conf, new Path(
"/user/admin/jisc2-xmls/table_sample.csv"));
// /user/admin/jist2/solr
FileOutputFormat.setOutputPath(conf, new Path("/user/admin/jisc2/job"));
// File solrHomeZip = new
// File("src/main/resources/jisc2/solr_home.zip");
Path zipPath = new Path("/user/admin/jisc2-xmls/solr_home.zip");
FileSystem fs = FileSystem.get(conf);
// fs.copyFromLocalFile(new Path(solrHomeZip.toString()), zipPath);
final URI baseZipUrl = fs.getUri().resolve(
zipPath.toString() + '#' + solrHomeZipName);
DistributedCache.addCacheArchive(baseZipUrl, conf);
LOG.debug("Set Solr distributed cache: {}",
Arrays.asList(DistributedCache.getCacheArchives(conf)));
LOG.debug("Set zipPath: {}", zipPath);
JobClient.runJob(conf);
}
} | Seems I have to repeat myself.
| src/main/java/uk/bl/wa/blindex/IndexerJob.java | Seems I have to repeat myself. | <ide><path>rc/main/java/uk/bl/wa/blindex/IndexerJob.java
<ide>
<ide> JobConf conf = new JobConf(IndexerJob.Map.class);
<ide> conf.setJobName("JISC2_Indexer");
<add> conf.setMapOutputKeyClass(IntWritable.class);
<add> conf.setMapOutputValueClass(SolrInputDocumentWritable.class);
<ide> conf.setMapperClass(Map.class);
<ide> conf.setNumMapTasks(4);
<ide> conf.setCombinerClass(Reduce.class); |
|
JavaScript | mit | efe73e2ce3ff794ada3ea879a02af9ffb8828372 | 0 | jupe/mongoose-tail | /* *******************
mongoose-tail
*******************
```
var motail = require('mongoose-tail');
var mt = new motail({});
mt.event('error', function(error){
})
mt.event('count', function(count){
})
mt.event('data', function(data)
{
});
```
*/
var EventEmitter = require('events').EventEmitter;
var util = require('util');
/* 3.rd modules*/
var _ = require('underscore');
var mongoose = module.parent.mongoose;
var cronJob = require('cron').CronJob;
/* Implementation */
var decSeconds = function(oDate, seconds)
{
var newDateObj = new Date();
newDateObj.setTime(oDate.getTime() - (seconds * 1000));
return newDateObj;
}
var incSeconds = function(oDate, seconds)
{
var newDateObj = new Date();
newDateObj.setTime(oDate.getTime() + (seconds * 1000));
return newDateObj;
}
/**
@param options json options for mongoose-tail
{
modelname: String Registered model name,
cron: int|String intervall in seconds/cron pattern for query intervall (optional, default: 10s interval)
start: Boolean if query should start immediately (optional, default: false)
count: Boolean result emit only count event instead of data (optional, default: false)
timefield: String Date-object field in mongoose model (optional, default: 'timestamp')
timeOffset: Int timeOffset in seconds (optional, default: 0 )
conditions: String|Object model find parameters (optional, default: {}),
limit: Object model limit parameters (optional, default: null),
sort: Object model sort parameters (optional, default: {timestamp: -1} )
select: String model select parameters (optional, default: null)
olderThan: Boolean if true, find documents with field $lt -operator otherwise $gt (optional, default: false)
}
*/
var Tail = function(options){
var self = this;
this.options = {}
this.model = false;
this.job = false;
this.triggeredList = [];
this.options = { //default values
mongoose: false,
cron: '*/10 * * * * *',
start: false,
timefield: 'timestamp',
timeOffset: 0,
individual: false,
conditions: {},
limit: 100,
select: '',
sort: {timestamp: -1},
olderThan: false,
count: false,
};
this.options = _.extend(this.options, options);
if( options ){
if( _.isNumber(options.cron) ) {
this.options.cron = "*/"+options.cron+" * * * *";
}
if( !_.isDate(options.timestamp) ){
this.options.timestamp = new Date();
}
if( !_.isArray(options.conditions) ){
this.options.conditions = {};
}
if( options.mongoose ) {
mongoose = options.mongoose;
}
}
if(mongoose.modelNames().indexOf(this.options.modelname) >= 0){
this.model = mongoose.model(this.options.modelname);
} else if(this.options.model instanceof mongoose.Model) {
this.model = this.options.model;
} else {
console.log('unregistered/unknown modelname');
console.log(this.options.modelNames());
return null;
}
this.setConditions = function(conditions)
{
this.options.conditions = conditions;
}
this.fetchData = function(conditions)
{
var search = self.model.find(conditions);
if( self.options.count===true ) {
search = search.count( function(error, count){
if(error){
console.log(error);
self.emit('error', error);
} else {
self.emit('count', count);
}
});
} else {
search = search
.limit(self.options.limit)
.sort(self.options.sort)
.select(self.options.select)
.execFind( function(error, docs){
if(error){
//emit error
self.emit('error', error);
} else {
if( docs.length>0) {
for(var i=0;i<docs.length;i++){
self.triggeredList.push(docs[i]._id);
}
//emit event for application
if( self.options.individual ) {
_.each(docs, function(doc){
self.emit('data', doc);
});
} else {
self.emit('data', docs);
}
//create new timestamp
if( self.options.olderThan ){
self.options.timestamp = incSeconds(new Date(), self.options.timeOffset);
} else {
self.options.timestamp = decSeconds(new Date(), self.options.timeOffset);
}
}
}
});
}
}
var generateConditions = function()
{
conditions = self.options.conditions;
if( self.options.timefield ) {
var condition = {}
condition[ self.options.timefield ] = {}
condition[ self.options.timefield ][self.options.olderThan?'$lt':'$gt'] = self.options.timestamp;
conditions = _.extend(conditions, condition);
}
if(self.triggeredList.length>0){
//if some docs are already triggered, skip those from next tick
var condition = {_id: {'$nin': self.triggeredList} }
conditions = _.extend(conditions, condition);
}
return conditions;
}
var tick = function()
{
//generate conditions
conditions = generateConditions();
//emit tick event to application
self.emit('tick', conditions);
//do search
self.fetchData(conditions);
}
this.start = function()
{
self.job.start();
}
this.stop = function()
{
self.job.stop();
}
this.job = new cronJob(this.options.cron, tick, null, options.start );
/* this might be usefull when optimized library..
this.on('newListener', function(event, listener) {
if(self.options.start )
self.start();
});*/
return this;
}
util.inherits(Tail, EventEmitter);
exports.Tail = Tail;
| lib/index.js | /* *******************
mongoose-tail
*******************
```
var motail = require('mongoose-tail');
var mt = new motail({});
mt.event('error', function(error){
})
mt.event('count', function(count){
})
mt.event('data', function(data)
{
});
```
*/
var EventEmitter = require('events').EventEmitter;
var util = require('util');
/* 3.rd modules*/
var _ = require('underscore');
var mongoose = require('mongoose');
var cronJob = require('cron').CronJob;
/* Implementation */
var decSeconds = function(oDate, seconds)
{
var newDateObj = new Date();
newDateObj.setTime(oDate.getTime() - (seconds * 1000));
return newDateObj;
}
var incSeconds = function(oDate, seconds)
{
var newDateObj = new Date();
newDateObj.setTime(oDate.getTime() + (seconds * 1000));
return newDateObj;
}
/**
@param options json options for mongoose-tail
{
modelname: String Registered model name,
cron: int|String intervall in seconds/cron pattern for query intervall (optional, default: 10s interval)
start: Boolean if query should start immediately (optional, default: false)
count: Boolean result emit only count event instead of data (optional, default: false)
timefield: String Date-object field in mongoose model (optional, default: 'timestamp')
timeOffset: Int timeOffset in seconds (optional, default: 0 )
conditions: String|Object model find parameters (optional, default: {}),
limit: Object model limit parameters (optional, default: null),
sort: Object model sort parameters (optional, default: {timestamp: -1} )
select: String model select parameters (optional, default: null)
olderThan: Boolean if true, find documents with field $lt -operator otherwise $gt (optional, default: false)
}
*/
var Tail = function(options){
var self = this;
this.options = {}
this.model = false;
this.job = false;
this.triggeredList = [];
this.options = { //default values
cron: '*/10 * * * * *',
start: false,
timefield: 'timestamp',
timeOffset: 0,
conditions: {},
limit: 100,
select: null,
sort: {timestamp: -1},
olderThan: false,
count: false,
};
this.options = _.extend(this.options, options);
if( options ){
if( _.isNumber(options.cron) ) {
this.options.cron = "*/"+options.cron+" * * * *";
}
if( !_.isDate(options.timestamp) ){
this.options.timestamp = new Date();
}
if( !_.isArray(options.conditions) ){
this.options.conditions = {};
}
}
if(mongoose.modelNames().indexOf(this.options.modelname) >= 0)
this.model = mongoose.model(this.options.modelname);
else {
console.log('unregistered/unknown modelname');
return null;
}
this.setConditions = function(conditions)
{
this.options.conditions = conditions;
}
this.fetchData = function(conditions)
{
var search = self.model.find(conditions);
if( self.options.count===true ) {
search = search.count( function(error, count){
if(error){
console.log(error);
self.emit('error', error);
} else {
self.emit('count', count);
}
});
} else {
search = search
.limit(self.options.limit)
.sort(self.options.sort)
.select(self.options.select)
.execFind( function(error, docs){
if(error){
//emit error
self.emit('error', error);
} else {
if( self.options.count ||
(!self.options.count && docs.length>0) ) {
for(var i=0;i<docs.length;i++){
self.triggeredList.push(docs[i]._id);
}
//emit event for application
self.emit('data', docs);
//create new timestamp
if( self.options.olderThan ){
self.options.timestamp = incSeconds(new Date(), self.options.timeOffset);
} else {
self.options.timestamp = decSeconds(new Date(), self.options.timeOffset);
}
}
}
});
}
}
var generateConditions = function()
{
conditions = self.options.conditions;
if( self.options.timefield ) {
var condition = {}
condition[ self.options.timefield ] = {}
condition[ self.options.timefield ][self.options.olderThan?'$lt':'$gt'] = self.options.timestamp;
conditions = _.extend(conditions, condition);
}
if(self.triggeredList.length>0){
//if some docs are already triggered, skip those from next tick
var condition = {_id: {'$nin': self.triggeredList} }
conditions = _.extend(conditions, condition);
}
return conditions;
}
var tick = function()
{
//emit tick event to application
self.emit('tick', self.options.conditions);
//generate conditions
conditions = generateConditions();
//do search
self.fetchData(conditions);
}
this.start = function()
{
self.job.start();
}
this.stop = function()
{
self.job.stop();
}
this.job = new cronJob(this.options.cron, tick, null, options.start );
/* this might be usefull when optimized library..
this.on('newListener', function(event, listener) {
if(self.options.start )
self.start();
});*/
return this;
}
util.inherits(Tail, EventEmitter);
exports.Tail = Tail;
| Update index.js | lib/index.js | Update index.js | <ide><path>ib/index.js
<ide>
<ide> /* 3.rd modules*/
<ide> var _ = require('underscore');
<del>var mongoose = require('mongoose');
<add>var mongoose = module.parent.mongoose;
<ide> var cronJob = require('cron').CronJob;
<ide>
<ide> /* Implementation */
<ide> this.job = false;
<ide> this.triggeredList = [];
<ide> this.options = { //default values
<add> mongoose: false,
<ide> cron: '*/10 * * * * *',
<ide> start: false,
<ide> timefield: 'timestamp',
<ide> timeOffset: 0,
<add> individual: false,
<ide> conditions: {},
<ide> limit: 100,
<del> select: null,
<add> select: '',
<ide> sort: {timestamp: -1},
<ide> olderThan: false,
<ide> count: false,
<ide> if( !_.isArray(options.conditions) ){
<ide> this.options.conditions = {};
<ide> }
<del>
<del> }
<del> if(mongoose.modelNames().indexOf(this.options.modelname) >= 0)
<add> if( options.mongoose ) {
<add> mongoose = options.mongoose;
<add> }
<add> }
<add> if(mongoose.modelNames().indexOf(this.options.modelname) >= 0){
<ide> this.model = mongoose.model(this.options.modelname);
<del> else {
<add> } else if(this.options.model instanceof mongoose.Model) {
<add> this.model = this.options.model;
<add> } else {
<ide> console.log('unregistered/unknown modelname');
<add> console.log(this.options.modelNames());
<ide> return null;
<ide> }
<add>
<ide> this.setConditions = function(conditions)
<ide> {
<ide> this.options.conditions = conditions;
<ide> //emit error
<ide> self.emit('error', error);
<ide> } else {
<del> if( self.options.count ||
<del> (!self.options.count && docs.length>0) ) {
<add> if( docs.length>0) {
<ide>
<ide> for(var i=0;i<docs.length;i++){
<ide> self.triggeredList.push(docs[i]._id);
<ide> }
<add>
<ide> //emit event for application
<del> self.emit('data', docs);
<add> if( self.options.individual ) {
<add> _.each(docs, function(doc){
<add> self.emit('data', doc);
<add> });
<add> } else {
<add> self.emit('data', docs);
<add> }
<ide>
<ide> //create new timestamp
<ide> if( self.options.olderThan ){
<ide> }
<ide> var tick = function()
<ide> {
<del> //emit tick event to application
<del> self.emit('tick', self.options.conditions);
<ide> //generate conditions
<ide> conditions = generateConditions();
<add>
<add> //emit tick event to application
<add> self.emit('tick', conditions);
<add>
<ide> //do search
<ide> self.fetchData(conditions);
<ide> } |
|
Java | mit | error: pathspec 'src/org/jmist/toolkit/Optics.java' did not match any file(s) known to git
| 37bb1e43547ebfe090045fecfc0e8e0317b4ec9d | 1 | bwkimmel/jmist | /**
*
*/
package org.jmist.toolkit;
import org.jmist.util.MathUtil;
import org.jmist.util.ReferenceArgument;
/**
* Provides utility methods for geometric optics.
* @author bkimmel
*/
public final class Optics {
/**
* Computes a reflected vector.
* @param in The vector to be reflected.
* @param normal The normal of the surface.
* @return The reflected vector.
*/
public static Vector3 reflect(Vector3 in, Vector3 normal) {
return in.minus(normal.times(2.0 * in.dot(normal)));
}
/**
* Computes the direction of a ray after being refracted
* at the interface between two media.
* @param in The direction of the incoming ray.
* @param n1 The refractive index of the medium on the side toward
* which the normal points.
* @param n2 The refractive index of the medium on the opposite
* side of the interface from which to the normal points.
* @param normal The direction normal to the interface between
* the two media.
* @return The direction of the refracted ray.
*/
public static Vector3 refract(Vector3 in, double n1, double n2, Vector3 normal) {
//
// Compute the refracted vector using Heckbert's method, see
//
// P.S. Heckbert, "Writing a Ray Tracer", in A.S. Glassner (Editor),
// "An Introduction to Ray Tracing", Morgan Kaufmann Publishers, Inc.,
// San Francisco, CA, 2002, Section 5.2, pp.291-293
//
// Note: The algorithm has been modified slightly from the one presented
// in the book so that refract(I, n1, n2, N) == refract(I, n2, n1, -N).
//
double c1 = -in.dot(normal);
if (c1 > 0.0) {
double eta = n1 / n2;
double det = 1.0 - eta * eta * (1.0 - c1 * c1);
if (det < 0.0) { // total internal reflection
return Optics.reflect(in, normal);
}
double c2 = Math.sqrt(det);
// return the unit vector in the direction of
// eta * I + (eta * c1 - c2) * N
return in.times(eta).plus(normal.times(eta * c1 - c2)).unit();
} else { // c1 <= 0.0
double eta = n2 / n1;
double det = 1.0 - eta * eta * (1.0 - c1 * c1);
if (det < 0.0) { // total internal reflection
return Optics.reflect(in, normal);
}
double c2 = Math.sqrt(det);
// return the unit vector in the direction of
// eta * I + (eta * c1 + c2) * N
return in.times(eta).plus(normal.times(eta * c1 + c2)).unit();
}
}
/**
* Computes the angle to the normal of a ray that has been
* refracted at the interface between two media.
* @param theta The angle between the normal and the incident ray.
* @param n1 The refractive index of the medium on the side of the
* interface to which to the normal points.
* @param n2 The refractive index of the medium
* @return The angle between the direction of the refracted ray and
* the anti-normal.
*/
public static double refract(double theta, double n1, double n2) {
double cost = Math.cos(theta);
if (cost < 0.0) {
double temp = n1;
n1 = n2;
n2 = temp;
cost = -cost;
}
double eta = n1 / n2;
double det = 1.0 - eta * eta * (1.0 - cost * cost);
if (det < 0.0) { // total internal reflection
return Math.PI - theta;
}
return Math.acos(Math.sqrt(det));
}
/**
* Computes the direction of a ray after being refracted
* at the interface between two media.
* @param in The direction of the incoming ray.
* @param n1 The refractive index of the medium on the side toward
* which the normal points.
* @param n2 The refractive index of the medium on the opposite
* side of the interface from which to the normal points.
* @param normal The direction normal to the interface between
* the two media.
* @return The direction of the refracted ray.
*/
public static Vector3 refract(Vector3 in, Complex n1, Complex n2, Vector3 normal) {
ReferenceArgument<Boolean> reftir = new ReferenceArgument<Boolean>();
ReferenceArgument<Double> refnp = new ReferenceArgument<Double>();
double ci = in.dot(normal);
double ct = Optics.getct(ci, n1, n2, refnp, reftir);
if (reftir.get()) { // total internal reflection.
return Optics.reflect(in, normal);
}
double np = refnp.get();
// return the refracted vector, recall that I + ci * N already has
// the length sin(theta_i), so we need only divide by np to resize
// to sin(theta'_t), see Born & Wolf, sec. 13.2, equation (9).
Vector3 out = in.divide(np).plus(normal.times(-ct + ci / np));
return out;
}
/**
* Computes the angle to the normal of a ray that has been
* refracted at the interface between two media.
* @param theta The angle between the normal and the incident ray.
* @param n1 The refractive index of the medium on the side of the
* interface to which to the normal points.
* @param n2 The refractive index of the medium
* @return The angle between the direction of the refracted ray and
* the anti-normal.
*/
public static double refract(double theta, Complex n1, Complex n2) {
ReferenceArgument<Boolean> reftir = new ReferenceArgument<Boolean>();
double ci = Math.cos(theta);
double ct = Optics.getct(ci, n1, n2, null, reftir);
if (reftir.get()) { // total internal reflection
return Math.PI - theta;
}
return Math.acos(ct);
}
/**
* Computes the reflectance components for polarized light incident
* on an interface between two media.
* @param in The incident direction.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @param normal The direction perpendicular to the interface between
* the two media.
* @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
* transverse electric (TE) and transverse magnetic (TM) modes
* of light incident on the interface from the specified direction.
*/
public static Vector2 polarizedReflectance(Vector3 in, double n1, double n2, Vector3 normal) {
double cost = -in.dot(normal);
double sin2t = 1.0 - cost * cost;
double n;
if (cost < 0.0) {
n = n1 / n2;
cost = -cost;
} else { // cost >= 0.0
n = n2 / n1;
}
double nSquared = n * n;
double A = Math.sqrt(nSquared - sin2t);
double TE = (cost - A) / (cost + A);
double TM = (nSquared * cost - A) / (nSquared * cost + A);
return new Vector2(MathUtil.threshold(TE * TE, 0.0, 1.0), MathUtil.threshold(TM * TM, 0.0, 1.0));
}
/**
* Computes the reflectance components for polarized light incident
* on an interface between two media.
* @param in The incident direction.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @param normal The direction perpendicular to the interface between
* the two media.
* @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
* transverse electric (TE) and transverse magnetic (TM) modes
* of light incident on the interface from the specified direction.
*/
public static Vector2 polarizedReflectance(Vector3 in, double n1, Complex n2, Vector3 normal) {
return polarizedReflectance(in, n1, n2, normal);
}
/**
* Computes the reflectance components for polarized light incident
* on an interface between two media.
* @param in The incident direction.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @param normal The direction perpendicular to the interface between
* the two media.
* @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
* transverse electric (TE) and transverse magnetic (TM) modes
* of light incident on the interface from the specified direction.
*/
public static Vector2 polarizedReflectance(Vector3 in, Complex n1, double n2, Vector3 normal) {
return polarizedReflectance(in, n1, n2, normal);
}
/**
* Computes the reflectance components for polarized light incident
* on an interface between two media.
* @param in The incident direction.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @param normal The direction perpendicular to the interface between
* the two media.
* @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
* transverse electric (TE) and transverse magnetic (TM) modes
* of light incident on the interface from the specified direction.
*/
public static Vector2 polarizedReflectance(Vector3 in, Complex n1, Complex n2, Vector3 normal) {
double cost = -in.dot(normal);
double sin2t = 1.0 - cost * cost;
Complex n;
if (cost < 0.0) {
n = n1.divide(n2);
cost = -cost;
} else { // cost >= 0.0
n = n2.divide(n1);
}
Complex nSquared = n.times(n);
Complex A = nSquared.minus(sin2t).sqrt();
// TE = (cost - A) / (cost + A)
// TM = (n^2 * cost - A) / (n^2 * cost + A)
double absTE = A.negative().plus(cost).divide(A.plus(cost)).abs();
double absTM = nSquared.times(cost).minus(A).divide(nSquared.times(cost).plus(A)).abs();
return new Vector2(MathUtil.threshold(absTE * absTE, 0.0, 1.0), MathUtil.threshold(absTM * absTM, 0.0, 1.0));
}
/**
* Computes the reflectance components for polarized light incident
* on an interface between two media.
* @param theta The angle between the incident direction and the normal.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
* transverse electric (TE) and transverse magnetic (TM) modes
* of light incident on the interface from the specified direction.
*/
public static Vector2 polarizedReflectance(double theta, double n1, double n2) {
double cost = Math.cos(theta);
double sin2t = 1.0 - cost * cost;
double n;
if (cost < 0.0) {
n = n1 / n2;
cost = -cost;
} else { // cost >= 0.0
n = n2 / n1;
}
double nSquared = n * n;
double A = Math.sqrt(nSquared - sin2t);
double TE = (cost - A) / (cost + A);
double TM = (nSquared * cost - A) / (nSquared * cost + A);
return new Vector2(MathUtil.threshold(TE * TE, 0.0, 1.0), MathUtil.threshold(TM * TM, 0.0, 1.0));
}
/**
* Computes the reflectance components for polarized light incident
* on an interface between two media.
* @param theta The angle between the incident direction and the normal.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
* transverse electric (TE) and transverse magnetic (TM) modes
* of light incident on the interface from the specified direction.
*/
public static Vector2 polarizedReflectance(double theta, double n1, Complex n2) {
return polarizedReflectance(theta, n1, n2);
}
/**
* Computes the reflectance components for polarized light incident
* on an interface between two media.
* @param theta The angle between the incident direction and the normal.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
* transverse electric (TE) and transverse magnetic (TM) modes
* of light incident on the interface from the specified direction.
*/
public static Vector2 polarizedReflectance(double theta, Complex n1, double n2) {
return polarizedReflectance(theta, n1, n2);
}
/**
* Computes the reflectance components for polarized light incident
* on an interface between two media.
* @param theta The angle between the incident direction and the normal.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
* transverse electric (TE) and transverse magnetic (TM) modes
* of light incident on the interface from the specified direction.
*/
public static Vector2 polarizedReflectance(double theta, Complex n1, Complex n2) {
double cost = Math.cos(theta);
double sin2t = 1.0 - cost * cost;
Complex n;
if (cost < 0.0) {
n = n1.divide(n2);
cost = -cost;
} else { // cost >= 0.0
n = n2.divide(n1);
}
Complex nSquared = n.times(n);
Complex A = nSquared.minus(sin2t).sqrt();
// TE = (cost - A) / (cost + A)
// TM = (n^2 * cost - A) / (n^2 * cost + A)
double absTE = A.negative().plus(cost).divide(A.plus(cost)).abs();
double absTM = nSquared.times(cost).minus(A).divide(nSquared.times(cost).plus(A)).abs();
return new Vector2(MathUtil.threshold(absTE * absTE, 0.0, 1.0), MathUtil.threshold(absTM * absTM, 0.0, 1.0));
}
/**
* Computes the reflectance components for unpolarized light incident
* on an interface between two media.
* @param in The incident direction.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @param normal The direction perpendicular to the interface between
* the two media.
* @return The reflectance of unpolarized light incident on the
* interface from the specified direction.
*/
public static double reflectance(Vector3 in, double n1, double n2, Vector3 normal) {
Vector2 R = polarizedReflectance(in, n1, n2, normal);
return 0.5 * (R.x() + R.y());
}
/**
* Computes the reflectance components for unpolarized light incident
* on an interface between two media.
* @param in The incident direction.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @param normal The direction perpendicular to the interface between
* the two media.
* @return The reflectance of unpolarized light incident on the
* interface from the specified direction.
*/
public static double reflectance(Vector3 in, double n1, Complex n2, Vector3 normal) {
Vector2 R = polarizedReflectance(in, n1, n2, normal);
return 0.5 * (R.x() + R.y());
}
/**
* Computes the reflectance components for unpolarized light incident
* on an interface between two media.
* @param in The incident direction.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @param normal The direction perpendicular to the interface between
* the two media.
* @return The reflectance of unpolarized light incident on the
* interface from the specified direction.
*/
public static double reflectance(Vector3 in, Complex n1, double n2, Vector3 normal) {
Vector2 R = polarizedReflectance(in, n1, n2, normal);
return 0.5 * (R.x() + R.y());
}
/**
* Computes the reflectance components for unpolarized light incident
* on an interface between two media.
* @param in The incident direction.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @param normal The direction perpendicular to the interface between
* the two media.
* @return The reflectance of unpolarized light incident on the
* interface from the specified direction.
*/
public static double reflectance(Vector3 in, Complex n1, Complex n2, Vector3 normal) {
Vector2 R = polarizedReflectance(in, n1, n2, normal);
return 0.5 * (R.x() + R.y());
}
/**
* Computes the reflectance components for unpolarized light incident
* on an interface between two media.
* @param theta The angle between the incident direction and the normal.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @return The reflectance of unpolarized light incident on the
* interface from the specified direction.
*/
public static double reflectance(double theta, double n1, double n2) {
Vector2 R = polarizedReflectance(theta, n1, n2);
return 0.5 * (R.x() + R.y());
}
/**
* Computes the reflectance components for unpolarized light incident
* on an interface between two media.
* @param theta The angle between the incident direction and the normal.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @return The reflectance of unpolarized light incident on the
* interface from the specified direction.
*/
public static double reflectance(double theta, double n1, Complex n2) {
Vector2 R = polarizedReflectance(theta, n1, n2);
return 0.5 * (R.x() + R.y());
}
/**
* Computes the reflectance components for unpolarized light incident
* on an interface between two media.
* @param theta The angle between the incident direction and the normal.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @return The reflectance of unpolarized light incident on the
* interface from the specified direction.
*/
public static double reflectance(double theta, Complex n1, double n2) {
Vector2 R = polarizedReflectance(theta, n1, n2);
return 0.5 * (R.x() + R.y());
}
/**
* Computes the reflectance components for unpolarized light incident
* on an interface between two media.
* @param theta The angle between the incident direction and the normal.
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the opposite side
* of the interface from which the normal points.
* @return The reflectance of unpolarized light incident on the
* interface from the specified direction.
*/
public static double reflectance(double theta, Complex n1, Complex n2) {
Vector2 R = polarizedReflectance(theta, n1, n2);
return 0.5 * (R.x() + R.y());
}
/**
* Computes the cosine of the refracted angle for an interface between
* two conductive media, the effective refractive index, and a value
* indicating whether total internal reflection has occurred.
* @param ci The cosine of the incident angle (the angle between the
* incident direction and the normal).
* @param n1 The refractive index of the medium on the side of the
* interface to which the normal points.
* @param n2 The refractive index of the medium on the side of the
* interface opposite from which the normal points.
* @param refnp [out] The effective real refractive index.
* @param reftir [out] A value indicating whether total internal
* reflection has occurred.
* @return The cosine of the angle between the refracted direction and
* the anti-normal.
*/
private static double getct(double ci, Complex n1, Complex n2, ReferenceArgument<Double> refnp, ReferenceArgument<Boolean> reftir) {
Complex eta;
if (ci > 0.0) {
eta = n2.divide(n1);
} else { // ci <= 0.0
//
// if the ray comes from the other side, rewrite the problem
// with the normal pointing toward the incident direction.
//
eta = n2.divide(n1);
ci = -ci;
}
double si2 = 1.0 - ci * ci;
// get components of the refractive index, eta = n + ik = n(1 + i*kappa)
double n = eta.re();
double k = eta.im();
double kappa = k / n;
// quantities that will appear later that we would rather not write out
// each time.
double A = n * n * (1.0 + kappa * kappa) * (1.0 + kappa * kappa);
double B = (1.0 - kappa * kappa) * si2;
double C = 2.0 * kappa * si2;
// components of cos(theta_t)^2 (the complex theta_t, Born & Wolf, sec 13.2 eq (3b))
double X = 1.0 - B / A;
double Y = C / A;
// compute q and gamma, where cos(theta_t) = qe^{i*gamma}
double q = Math.pow(X * X + Y * Y, 1.0 / 4.0);
double gamma = 0.5 * Math.atan2(A - B, C);
// will need cos and sin of gamma
double cg = Math.cos(gamma);
double sg = Math.sin(gamma);
// compute the modified refractive index
double K = n * q * (cg - kappa * sg);
double np = Math.sqrt(si2 + K * K);
// cosine of theta'_t, the real angle of refraction.
double ct = K / np;
ReferenceArgument.set(refnp, np);
ReferenceArgument.set(reftir, ct < 0.0);
return ct;
}
/**
* This class contains only static utility methods,
* and therefore should not be creatable.
*/
private Optics() {}
}
| src/org/jmist/toolkit/Optics.java | Added Optics class with static utility methods for geometric optics (reflection, refraction).
| src/org/jmist/toolkit/Optics.java | Added Optics class with static utility methods for geometric optics (reflection, refraction). | <ide><path>rc/org/jmist/toolkit/Optics.java
<add>/**
<add> *
<add> */
<add>package org.jmist.toolkit;
<add>
<add>import org.jmist.util.MathUtil;
<add>import org.jmist.util.ReferenceArgument;
<add>
<add>/**
<add> * Provides utility methods for geometric optics.
<add> * @author bkimmel
<add> */
<add>public final class Optics {
<add>
<add> /**
<add> * Computes a reflected vector.
<add> * @param in The vector to be reflected.
<add> * @param normal The normal of the surface.
<add> * @return The reflected vector.
<add> */
<add> public static Vector3 reflect(Vector3 in, Vector3 normal) {
<add> return in.minus(normal.times(2.0 * in.dot(normal)));
<add> }
<add>
<add> /**
<add> * Computes the direction of a ray after being refracted
<add> * at the interface between two media.
<add> * @param in The direction of the incoming ray.
<add> * @param n1 The refractive index of the medium on the side toward
<add> * which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite
<add> * side of the interface from which to the normal points.
<add> * @param normal The direction normal to the interface between
<add> * the two media.
<add> * @return The direction of the refracted ray.
<add> */
<add> public static Vector3 refract(Vector3 in, double n1, double n2, Vector3 normal) {
<add>
<add> //
<add> // Compute the refracted vector using Heckbert's method, see
<add> //
<add> // P.S. Heckbert, "Writing a Ray Tracer", in A.S. Glassner (Editor),
<add> // "An Introduction to Ray Tracing", Morgan Kaufmann Publishers, Inc.,
<add> // San Francisco, CA, 2002, Section 5.2, pp.291-293
<add> //
<add> // Note: The algorithm has been modified slightly from the one presented
<add> // in the book so that refract(I, n1, n2, N) == refract(I, n2, n1, -N).
<add> //
<add> double c1 = -in.dot(normal);
<add>
<add> if (c1 > 0.0) {
<add>
<add> double eta = n1 / n2;
<add> double det = 1.0 - eta * eta * (1.0 - c1 * c1);
<add>
<add> if (det < 0.0) { // total internal reflection
<add> return Optics.reflect(in, normal);
<add> }
<add>
<add> double c2 = Math.sqrt(det);
<add>
<add> // return the unit vector in the direction of
<add> // eta * I + (eta * c1 - c2) * N
<add> return in.times(eta).plus(normal.times(eta * c1 - c2)).unit();
<add>
<add> } else { // c1 <= 0.0
<add>
<add> double eta = n2 / n1;
<add> double det = 1.0 - eta * eta * (1.0 - c1 * c1);
<add>
<add> if (det < 0.0) { // total internal reflection
<add> return Optics.reflect(in, normal);
<add> }
<add>
<add> double c2 = Math.sqrt(det);
<add>
<add> // return the unit vector in the direction of
<add> // eta * I + (eta * c1 + c2) * N
<add> return in.times(eta).plus(normal.times(eta * c1 + c2)).unit();
<add>
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Computes the angle to the normal of a ray that has been
<add> * refracted at the interface between two media.
<add> * @param theta The angle between the normal and the incident ray.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which to the normal points.
<add> * @param n2 The refractive index of the medium
<add> * @return The angle between the direction of the refracted ray and
<add> * the anti-normal.
<add> */
<add> public static double refract(double theta, double n1, double n2) {
<add>
<add> double cost = Math.cos(theta);
<add>
<add> if (cost < 0.0) {
<add> double temp = n1;
<add> n1 = n2;
<add> n2 = temp;
<add> cost = -cost;
<add> }
<add>
<add> double eta = n1 / n2;
<add> double det = 1.0 - eta * eta * (1.0 - cost * cost);
<add>
<add> if (det < 0.0) { // total internal reflection
<add> return Math.PI - theta;
<add> }
<add>
<add> return Math.acos(Math.sqrt(det));
<add>
<add> }
<add>
<add>
<add> /**
<add> * Computes the direction of a ray after being refracted
<add> * at the interface between two media.
<add> * @param in The direction of the incoming ray.
<add> * @param n1 The refractive index of the medium on the side toward
<add> * which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite
<add> * side of the interface from which to the normal points.
<add> * @param normal The direction normal to the interface between
<add> * the two media.
<add> * @return The direction of the refracted ray.
<add> */
<add> public static Vector3 refract(Vector3 in, Complex n1, Complex n2, Vector3 normal) {
<add>
<add> ReferenceArgument<Boolean> reftir = new ReferenceArgument<Boolean>();
<add> ReferenceArgument<Double> refnp = new ReferenceArgument<Double>();
<add> double ci = in.dot(normal);
<add> double ct = Optics.getct(ci, n1, n2, refnp, reftir);
<add>
<add> if (reftir.get()) { // total internal reflection.
<add> return Optics.reflect(in, normal);
<add> }
<add>
<add> double np = refnp.get();
<add>
<add> // return the refracted vector, recall that I + ci * N already has
<add> // the length sin(theta_i), so we need only divide by np to resize
<add> // to sin(theta'_t), see Born & Wolf, sec. 13.2, equation (9).
<add> Vector3 out = in.divide(np).plus(normal.times(-ct + ci / np));
<add>
<add> return out;
<add>
<add> }
<add>
<add> /**
<add> * Computes the angle to the normal of a ray that has been
<add> * refracted at the interface between two media.
<add> * @param theta The angle between the normal and the incident ray.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which to the normal points.
<add> * @param n2 The refractive index of the medium
<add> * @return The angle between the direction of the refracted ray and
<add> * the anti-normal.
<add> */
<add> public static double refract(double theta, Complex n1, Complex n2) {
<add>
<add> ReferenceArgument<Boolean> reftir = new ReferenceArgument<Boolean>();
<add>
<add> double ci = Math.cos(theta);
<add> double ct = Optics.getct(ci, n1, n2, null, reftir);
<add>
<add> if (reftir.get()) { // total internal reflection
<add> return Math.PI - theta;
<add> }
<add>
<add> return Math.acos(ct);
<add>
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for polarized light incident
<add> * on an interface between two media.
<add> * @param in The incident direction.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @param normal The direction perpendicular to the interface between
<add> * the two media.
<add> * @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
<add> * transverse electric (TE) and transverse magnetic (TM) modes
<add> * of light incident on the interface from the specified direction.
<add> */
<add> public static Vector2 polarizedReflectance(Vector3 in, double n1, double n2, Vector3 normal) {
<add>
<add> double cost = -in.dot(normal);
<add> double sin2t = 1.0 - cost * cost;
<add> double n;
<add>
<add> if (cost < 0.0) {
<add> n = n1 / n2;
<add> cost = -cost;
<add> } else { // cost >= 0.0
<add> n = n2 / n1;
<add> }
<add>
<add> double nSquared = n * n;
<add>
<add> double A = Math.sqrt(nSquared - sin2t);
<add>
<add> double TE = (cost - A) / (cost + A);
<add> double TM = (nSquared * cost - A) / (nSquared * cost + A);
<add>
<add> return new Vector2(MathUtil.threshold(TE * TE, 0.0, 1.0), MathUtil.threshold(TM * TM, 0.0, 1.0));
<add>
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for polarized light incident
<add> * on an interface between two media.
<add> * @param in The incident direction.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @param normal The direction perpendicular to the interface between
<add> * the two media.
<add> * @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
<add> * transverse electric (TE) and transverse magnetic (TM) modes
<add> * of light incident on the interface from the specified direction.
<add> */
<add> public static Vector2 polarizedReflectance(Vector3 in, double n1, Complex n2, Vector3 normal) {
<add> return polarizedReflectance(in, n1, n2, normal);
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for polarized light incident
<add> * on an interface between two media.
<add> * @param in The incident direction.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @param normal The direction perpendicular to the interface between
<add> * the two media.
<add> * @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
<add> * transverse electric (TE) and transverse magnetic (TM) modes
<add> * of light incident on the interface from the specified direction.
<add> */
<add> public static Vector2 polarizedReflectance(Vector3 in, Complex n1, double n2, Vector3 normal) {
<add> return polarizedReflectance(in, n1, n2, normal);
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for polarized light incident
<add> * on an interface between two media.
<add> * @param in The incident direction.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @param normal The direction perpendicular to the interface between
<add> * the two media.
<add> * @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
<add> * transverse electric (TE) and transverse magnetic (TM) modes
<add> * of light incident on the interface from the specified direction.
<add> */
<add> public static Vector2 polarizedReflectance(Vector3 in, Complex n1, Complex n2, Vector3 normal) {
<add>
<add> double cost = -in.dot(normal);
<add> double sin2t = 1.0 - cost * cost;
<add> Complex n;
<add>
<add> if (cost < 0.0) {
<add> n = n1.divide(n2);
<add> cost = -cost;
<add> } else { // cost >= 0.0
<add> n = n2.divide(n1);
<add> }
<add>
<add> Complex nSquared = n.times(n);
<add>
<add> Complex A = nSquared.minus(sin2t).sqrt();
<add>
<add> // TE = (cost - A) / (cost + A)
<add> // TM = (n^2 * cost - A) / (n^2 * cost + A)
<add> double absTE = A.negative().plus(cost).divide(A.plus(cost)).abs();
<add> double absTM = nSquared.times(cost).minus(A).divide(nSquared.times(cost).plus(A)).abs();
<add>
<add> return new Vector2(MathUtil.threshold(absTE * absTE, 0.0, 1.0), MathUtil.threshold(absTM * absTM, 0.0, 1.0));
<add>
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for polarized light incident
<add> * on an interface between two media.
<add> * @param theta The angle between the incident direction and the normal.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
<add> * transverse electric (TE) and transverse magnetic (TM) modes
<add> * of light incident on the interface from the specified direction.
<add> */
<add> public static Vector2 polarizedReflectance(double theta, double n1, double n2) {
<add>
<add> double cost = Math.cos(theta);
<add> double sin2t = 1.0 - cost * cost;
<add> double n;
<add>
<add> if (cost < 0.0) {
<add> n = n1 / n2;
<add> cost = -cost;
<add> } else { // cost >= 0.0
<add> n = n2 / n1;
<add> }
<add>
<add> double nSquared = n * n;
<add>
<add> double A = Math.sqrt(nSquared - sin2t);
<add>
<add> double TE = (cost - A) / (cost + A);
<add> double TM = (nSquared * cost - A) / (nSquared * cost + A);
<add>
<add> return new Vector2(MathUtil.threshold(TE * TE, 0.0, 1.0), MathUtil.threshold(TM * TM, 0.0, 1.0));
<add>
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for polarized light incident
<add> * on an interface between two media.
<add> * @param theta The angle between the incident direction and the normal.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
<add> * transverse electric (TE) and transverse magnetic (TM) modes
<add> * of light incident on the interface from the specified direction.
<add> */
<add> public static Vector2 polarizedReflectance(double theta, double n1, Complex n2) {
<add> return polarizedReflectance(theta, n1, n2);
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for polarized light incident
<add> * on an interface between two media.
<add> * @param theta The angle between the incident direction and the normal.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
<add> * transverse electric (TE) and transverse magnetic (TM) modes
<add> * of light incident on the interface from the specified direction.
<add> */
<add> public static Vector2 polarizedReflectance(double theta, Complex n1, double n2) {
<add> return polarizedReflectance(theta, n1, n2);
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for polarized light incident
<add> * on an interface between two media.
<add> * @param theta The angle between the incident direction and the normal.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @return The vector (R_{TE}, R_{TM}), denoting the reflectance for
<add> * transverse electric (TE) and transverse magnetic (TM) modes
<add> * of light incident on the interface from the specified direction.
<add> */
<add> public static Vector2 polarizedReflectance(double theta, Complex n1, Complex n2) {
<add>
<add> double cost = Math.cos(theta);
<add> double sin2t = 1.0 - cost * cost;
<add> Complex n;
<add>
<add> if (cost < 0.0) {
<add> n = n1.divide(n2);
<add> cost = -cost;
<add> } else { // cost >= 0.0
<add> n = n2.divide(n1);
<add> }
<add>
<add> Complex nSquared = n.times(n);
<add>
<add> Complex A = nSquared.minus(sin2t).sqrt();
<add>
<add> // TE = (cost - A) / (cost + A)
<add> // TM = (n^2 * cost - A) / (n^2 * cost + A)
<add> double absTE = A.negative().plus(cost).divide(A.plus(cost)).abs();
<add> double absTM = nSquared.times(cost).minus(A).divide(nSquared.times(cost).plus(A)).abs();
<add>
<add> return new Vector2(MathUtil.threshold(absTE * absTE, 0.0, 1.0), MathUtil.threshold(absTM * absTM, 0.0, 1.0));
<add>
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for unpolarized light incident
<add> * on an interface between two media.
<add> * @param in The incident direction.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @param normal The direction perpendicular to the interface between
<add> * the two media.
<add> * @return The reflectance of unpolarized light incident on the
<add> * interface from the specified direction.
<add> */
<add> public static double reflectance(Vector3 in, double n1, double n2, Vector3 normal) {
<add> Vector2 R = polarizedReflectance(in, n1, n2, normal);
<add> return 0.5 * (R.x() + R.y());
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for unpolarized light incident
<add> * on an interface between two media.
<add> * @param in The incident direction.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @param normal The direction perpendicular to the interface between
<add> * the two media.
<add> * @return The reflectance of unpolarized light incident on the
<add> * interface from the specified direction.
<add> */
<add> public static double reflectance(Vector3 in, double n1, Complex n2, Vector3 normal) {
<add> Vector2 R = polarizedReflectance(in, n1, n2, normal);
<add> return 0.5 * (R.x() + R.y());
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for unpolarized light incident
<add> * on an interface between two media.
<add> * @param in The incident direction.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @param normal The direction perpendicular to the interface between
<add> * the two media.
<add> * @return The reflectance of unpolarized light incident on the
<add> * interface from the specified direction.
<add> */
<add> public static double reflectance(Vector3 in, Complex n1, double n2, Vector3 normal) {
<add> Vector2 R = polarizedReflectance(in, n1, n2, normal);
<add> return 0.5 * (R.x() + R.y());
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for unpolarized light incident
<add> * on an interface between two media.
<add> * @param in The incident direction.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @param normal The direction perpendicular to the interface between
<add> * the two media.
<add> * @return The reflectance of unpolarized light incident on the
<add> * interface from the specified direction.
<add> */
<add> public static double reflectance(Vector3 in, Complex n1, Complex n2, Vector3 normal) {
<add> Vector2 R = polarizedReflectance(in, n1, n2, normal);
<add> return 0.5 * (R.x() + R.y());
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for unpolarized light incident
<add> * on an interface between two media.
<add> * @param theta The angle between the incident direction and the normal.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @return The reflectance of unpolarized light incident on the
<add> * interface from the specified direction.
<add> */
<add> public static double reflectance(double theta, double n1, double n2) {
<add> Vector2 R = polarizedReflectance(theta, n1, n2);
<add> return 0.5 * (R.x() + R.y());
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for unpolarized light incident
<add> * on an interface between two media.
<add> * @param theta The angle between the incident direction and the normal.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @return The reflectance of unpolarized light incident on the
<add> * interface from the specified direction.
<add> */
<add> public static double reflectance(double theta, double n1, Complex n2) {
<add> Vector2 R = polarizedReflectance(theta, n1, n2);
<add> return 0.5 * (R.x() + R.y());
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for unpolarized light incident
<add> * on an interface between two media.
<add> * @param theta The angle between the incident direction and the normal.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @return The reflectance of unpolarized light incident on the
<add> * interface from the specified direction.
<add> */
<add> public static double reflectance(double theta, Complex n1, double n2) {
<add> Vector2 R = polarizedReflectance(theta, n1, n2);
<add> return 0.5 * (R.x() + R.y());
<add> }
<add>
<add> /**
<add> * Computes the reflectance components for unpolarized light incident
<add> * on an interface between two media.
<add> * @param theta The angle between the incident direction and the normal.
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the opposite side
<add> * of the interface from which the normal points.
<add> * @return The reflectance of unpolarized light incident on the
<add> * interface from the specified direction.
<add> */
<add> public static double reflectance(double theta, Complex n1, Complex n2) {
<add> Vector2 R = polarizedReflectance(theta, n1, n2);
<add> return 0.5 * (R.x() + R.y());
<add> }
<add>
<add> /**
<add> * Computes the cosine of the refracted angle for an interface between
<add> * two conductive media, the effective refractive index, and a value
<add> * indicating whether total internal reflection has occurred.
<add> * @param ci The cosine of the incident angle (the angle between the
<add> * incident direction and the normal).
<add> * @param n1 The refractive index of the medium on the side of the
<add> * interface to which the normal points.
<add> * @param n2 The refractive index of the medium on the side of the
<add> * interface opposite from which the normal points.
<add> * @param refnp [out] The effective real refractive index.
<add> * @param reftir [out] A value indicating whether total internal
<add> * reflection has occurred.
<add> * @return The cosine of the angle between the refracted direction and
<add> * the anti-normal.
<add> */
<add> private static double getct(double ci, Complex n1, Complex n2, ReferenceArgument<Double> refnp, ReferenceArgument<Boolean> reftir) {
<add>
<add> Complex eta;
<add>
<add> if (ci > 0.0) {
<add> eta = n2.divide(n1);
<add> } else { // ci <= 0.0
<add>
<add> //
<add> // if the ray comes from the other side, rewrite the problem
<add> // with the normal pointing toward the incident direction.
<add> //
<add> eta = n2.divide(n1);
<add> ci = -ci;
<add>
<add> }
<add>
<add> double si2 = 1.0 - ci * ci;
<add>
<add> // get components of the refractive index, eta = n + ik = n(1 + i*kappa)
<add> double n = eta.re();
<add> double k = eta.im();
<add> double kappa = k / n;
<add>
<add> // quantities that will appear later that we would rather not write out
<add> // each time.
<add> double A = n * n * (1.0 + kappa * kappa) * (1.0 + kappa * kappa);
<add> double B = (1.0 - kappa * kappa) * si2;
<add> double C = 2.0 * kappa * si2;
<add>
<add> // components of cos(theta_t)^2 (the complex theta_t, Born & Wolf, sec 13.2 eq (3b))
<add> double X = 1.0 - B / A;
<add> double Y = C / A;
<add>
<add> // compute q and gamma, where cos(theta_t) = qe^{i*gamma}
<add> double q = Math.pow(X * X + Y * Y, 1.0 / 4.0);
<add> double gamma = 0.5 * Math.atan2(A - B, C);
<add>
<add> // will need cos and sin of gamma
<add> double cg = Math.cos(gamma);
<add> double sg = Math.sin(gamma);
<add>
<add> // compute the modified refractive index
<add> double K = n * q * (cg - kappa * sg);
<add> double np = Math.sqrt(si2 + K * K);
<add>
<add> // cosine of theta'_t, the real angle of refraction.
<add> double ct = K / np;
<add>
<add> ReferenceArgument.set(refnp, np);
<add> ReferenceArgument.set(reftir, ct < 0.0);
<add>
<add> return ct;
<add>
<add> }
<add>
<add> /**
<add> * This class contains only static utility methods,
<add> * and therefore should not be creatable.
<add> */
<add> private Optics() {}
<add>
<add>} |
|
Java | mit | 9f89ea6518d9547e50e677991ad13376b54a515e | 0 | douggie/XChange | package org.knowm.xchange.bitmex.service;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.ws.rs.FormParam;
import org.knowm.xchange.service.BaseParamsDigest;
import si.mazi.rescu.RestInvocation;
public class BitmexDigest extends BaseParamsDigest {
private String apiKey;
/**
* Constructor
*
* @param secretKeyBase64
* @param apiKey @throws IllegalArgumentException if key is invalid (cannot be base-64-decoded or the decoded key is invalid).
*/
private BitmexDigest(byte[] secretKeyBase64) {
super(secretKeyBase64, HMAC_SHA_512);
}
public static BitmexDigest createInstance(String secretKeyBase64) {
if (secretKeyBase64 != null) {
return new BitmexDigest(Base64.getUrlDecoder().decode(secretKeyBase64.getBytes()));
}
return null;
}
@Override
public String digestParams(RestInvocation restInvocation) {
MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Illegal algorithm for post body digest. Check the implementation.");
}
sha256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
sha256.update(restInvocation.getRequestBody().getBytes());
Mac mac512 = getMac();
mac512.update(("/" + restInvocation.getPath()).getBytes());
mac512.update(sha256.digest());
return Base64.getUrlEncoder().encodeToString(mac512.doFinal()).trim();
}
private BitmexDigest(String secretKeyBase64, String apiKey) {
super(secretKeyBase64, HMAC_SHA_256);
this.apiKey = apiKey;
}
public static BitmexDigest createInstance(String secretKeyBase64, String apiKey) {
return secretKeyBase64 == null ? null : new BitmexDigest(secretKeyBase64, apiKey);
}
}
| xchange-bitmex/src/main/java/org/knowm/xchange/bitmex/service/BitmexDigest.java | package org.knowm.xchange.bitmex.service;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.ws.rs.FormParam;
import org.knowm.xchange.service.BaseParamsDigest;
import net.iharder.Base64;
import si.mazi.rescu.RestInvocation;
public class BitmexDigest extends BaseParamsDigest {
private String apiKey;
/**
* Constructor
*
* @param secretKeyBase64
* @param apiKey @throws IllegalArgumentException if key is invalid (cannot be base-64-decoded or the decoded key is invalid).
*/
private BitmexDigest(byte[] secretKeyBase64) {
super(secretKeyBase64, HMAC_SHA_512);
}
public static BitmexDigest createInstance(String secretKeyBase64) {
try {
if (secretKeyBase64 != null)
return new BitmexDigest(Base64.decode(secretKeyBase64.getBytes()));
} catch (IOException e) {
throw new IllegalArgumentException("Could not decode Base 64 string", e);
}
return null;
}
@Override
public String digestParams(RestInvocation restInvocation) {
MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Illegal algorithm for post body digest. Check the implementation.");
}
sha256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
sha256.update(restInvocation.getRequestBody().getBytes());
Mac mac512 = getMac();
mac512.update(("/" + restInvocation.getPath()).getBytes());
mac512.update(sha256.digest());
return Base64.encodeBytes(mac512.doFinal()).trim();
}
private BitmexDigest(String secretKeyBase64, String apiKey) {
super(secretKeyBase64, HMAC_SHA_256);
this.apiKey = apiKey;
}
public static BitmexDigest createInstance(String secretKeyBase64, String apiKey) {
return secretKeyBase64 == null ? null : new BitmexDigest(secretKeyBase64, apiKey);
}
}
| [bitmex] switch API keys to url-safe base64 encoding, which is the
scheme used by bitmex
| xchange-bitmex/src/main/java/org/knowm/xchange/bitmex/service/BitmexDigest.java | [bitmex] switch API keys to url-safe base64 encoding, which is the scheme used by bitmex | <ide><path>change-bitmex/src/main/java/org/knowm/xchange/bitmex/service/BitmexDigest.java
<ide> package org.knowm.xchange.bitmex.service;
<ide>
<del>import java.io.IOException;
<ide> import java.security.MessageDigest;
<ide> import java.security.NoSuchAlgorithmException;
<add>import java.util.Base64;
<ide>
<ide> import javax.crypto.Mac;
<ide> import javax.ws.rs.FormParam;
<ide>
<ide> import org.knowm.xchange.service.BaseParamsDigest;
<ide>
<del>import net.iharder.Base64;
<ide> import si.mazi.rescu.RestInvocation;
<ide>
<ide> public class BitmexDigest extends BaseParamsDigest {
<ide>
<ide> public static BitmexDigest createInstance(String secretKeyBase64) {
<ide>
<del> try {
<del> if (secretKeyBase64 != null)
<del> return new BitmexDigest(Base64.decode(secretKeyBase64.getBytes()));
<del> } catch (IOException e) {
<del> throw new IllegalArgumentException("Could not decode Base 64 string", e);
<add> if (secretKeyBase64 != null) {
<add> return new BitmexDigest(Base64.getUrlDecoder().decode(secretKeyBase64.getBytes()));
<ide> }
<ide> return null;
<ide> }
<ide> mac512.update(("/" + restInvocation.getPath()).getBytes());
<ide> mac512.update(sha256.digest());
<ide>
<del> return Base64.encodeBytes(mac512.doFinal()).trim();
<add> return Base64.getUrlEncoder().encodeToString(mac512.doFinal()).trim();
<ide>
<ide> }
<ide> |
|
JavaScript | mit | 1fba0f7d2e6c74fe03908aafd154a76381cbe2eb | 0 | Kilian/grafico,Kilian/grafico | var Ico = {
Base: {},
SparkLine: {},
SparkBar: {},
BaseGraph: {},
LineGraph: {},
BarGraph: {},
HorizontalBarGraph: {}
}
Ico.Base = Class.create({
/* Returns a suitable set of labels for given data points on the Y axis */
labelStep: function(data) {
var min = data.min(),
max = data.max(),
range = max - min,
step = 0;
if (range < 2) {
step = 0.1;
} else if (range < 3) {
step = 0.2;
} else if (range < 5) {
step = 0.5;
} else if (range < 11) {
step = 1;
} else if (range < 50) {
step = 5;
} else if (range < 100) {
step = 10;
} else {
step = Math.pow(20, (Math.log(range) / Math.LN10).round() - 1);
}
return step;
}
});
Ico.SparkLine = Class.create(Ico.Base, {
initialize: function(element, data, options) {
this.element = element;
this.data = data;
this.options = {
width: parseInt(element.getStyle('width')),
height: parseInt(element.getStyle('height')),
highlight: false,
background_colour: element.getStyle('backgroundColor'),
colour: '#036'
};
Object.extend(this.options, options || { });
this.step = this.calculateStep();
this.paper = Raphael(this.element, this.options['width'], this.options['height']);
if (this.options['acceptable_range']) {
this.background = this.paper.rect(0, this.options['height'] - this.normalise(this.options['acceptable_range'][1]),
this.options['width'], this.options['height'] - this.normalise(this.options['acceptable_range'][0]));
} else {
this.background = this.paper.rect(0, 0, this.options['width'], this.options['height']);
}
this.background.attr({fill: this.options['background_colour'], stroke: 'none' });
this.draw();
},
calculateStep: function() {
return this.options['width'] / (this.data.length - 1);
},
normalisedData: function() {
return $A(this.data).collect(function(value) {
return this.normalise(value);
}.bind(this))
},
normalise: function(value) {
return (this.options['height'] / this.data.max()) * value;
},
draw: function() {
var data = this.normalisedData();
this.drawLines('', this.options['colour'], data);
if (this.options['highlight']) {
this.showHighlight(data);
}
},
drawLines: function(label, colour, data) {
var line = this.paper.path({ stroke: colour }).moveTo(0, this.options['height'] - data.first());
var x = 0;
data.slice(1).each(function(value) {
x = x + this.step;
line.lineTo(x, this.options['height'] - value);
}.bind(this))
},
showHighlight: function(data) {
var size = 2,
x = this.options['width'] - size,
i = this.options['highlight']['index'] || data.length - 1,
y = data[i] + ((size / 2).round());
// Find the x position if it's not the last value
if (typeof(this.options['highlight']['index']) != 'undefined') {
x = this.step * this.options['highlight']['index'];
}
var circle = this.paper.circle(x, this.options['height'] - y, size);
circle.attr({ stroke: false, fill: this.options['highlight']['colour']})
}
});
Ico.SparkBar = Class.create(Ico.SparkLine, {
calculateStep: function() {
return this.options['width'] / this.data.length;
},
drawLines: function(label, colour, data) {
var width = this.step > 2 ? this.step - 1 : this.step;
var x = width;
var line = this.paper.path({ stroke: colour, 'stroke-width': width });
data.each(function(value) {
line.moveTo(x, this.options['height'] - value)
line.lineTo(x, this.options['height']);
x = x + this.step;
}.bind(this))
}
})
Ico.BaseGraph = Class.create(Ico.Base, {
initialize: function(element, data, options) {
this.element = element;
this.data_sets = Object.isArray(data) ? new Hash({ one: data }) : $H(data);
this.flat_data = this.data_sets.collect(function(data_set) { return data_set[1] }).flatten();
this.range = this.calculateRange();
this.data_size = this.longestDataSetLength();
this.start_value = this.calculateStartValue();
if (this.start_value == 0) {
this.range = this.max;
}
/* If one colour is specified, map it to a compatible set */
if (options && options['colour']) {
options['colours'] = {};
this.data_sets.keys().each(function(key) {
options['colours'][key] = options['colour'];
});
}
this.options = {
width: parseInt(element.getStyle('width')),
height: parseInt(element.getStyle('height')),
labels: $A($R(1, this.data_size)), // Label data
plot_padding: 10, // Padding for the graph line/bar plots
font_size: 10, // Label font size
show_horizontal_labels: true,
show_vertical_labels: true,
colours: this.makeRandomColours(), // Line colours
background_colour: element.getStyle('backgroundColor'),
label_colour: '#666', // Label text colour
markers: false, // false, circle
marker_size: 5,
meanline: false,
y_padding_top: 20,
stacked_fill: false, // fill the area in a stacked graph
draw_axis: true,
datalabels: '',
percentages: false, // opt for percentage in horizontal graph horizontal labels
start_at_zero: true,
horiz_bargraph_firstcolour: false, // different colour for first value in horizontal graph
hover_colour: "#333333" // hover color if there are datalabels
};
Object.extend(this.options, this.chartDefaults() || { });
Object.extend(this.options, options || { });
/* Padding around the graph area to make room for labels */
this.x_padding_left = 10 + this.paddingLeftOffset();
this.x_padding_right = 20;
this.x_padding = this.x_padding_left + this.x_padding_right;
this.y_padding_top = this.options['y_padding_top'];
this.y_padding_bottom = 20 + this.paddingBottomOffset();
this.y_padding = this.y_padding_top + this.y_padding_bottom;
this.graph_width = this.options['width'] - (this.x_padding);
this.graph_height = this.options['height'] - (this.y_padding);
this.step = this.calculateStep();
this.label_step = this.labelStep(this.flat_data);
/* Calculate how many labels are required */
this.y_label_count = (this.range / this.label_step).round();
this.value_labels = this.makeValueLabels(this.y_label_count);
this.top_value = this.value_labels.last();
if (this.start_value == 0) {
this.range = this.top_value;
}
/* Grid control options */
this.grid_start_offset = -1;
/* Drawing */
this.paper = Raphael(this.element, this.options['width'], this.options['height']);
this.background = this.paper.rect(this.x_padding_left, this.y_padding_top, this.graph_width, this.graph_height);
this.background.attr({fill: this.options['background_colour'], stroke: 'none' });
if (this.options['meanline'] === true) {
this.options['meanline'] = { 'stroke-width': '2px', stroke: '#BBBBBB' };
}
this.setChartSpecificOptions();
this.draw();
},
chartDefaults: function() {
/* Define in child class */
},
drawPlot: function(index, cursor, x, y, colour) {
/* Define in child class */
},
drawHorizontalLabels: function() {
/* Define in child class */
},
calculateStep: function() {
/* Define in child classes */
},
calculateStartValue: function() {
var min = this.flat_data.min();
return this.range < min || min < 0 ? min.round() : 0;
},
makeRandomColours: function(number) {
var colours = {};
this.data_sets.each(function(data) {
colours[data[0]] = Raphael.hsb2rgb(Math.random(), 1, .75).hex;
});
return colours;
},
longestDataSetLength: function() {
var length = 0;
this.data_sets.each(function(data_set) {
length = data_set[1].length > length ? data_set[1].length : length;
});
return length;
},
roundValue: function(value, length) {
var multiplier = Math.pow(10, length);
value *= multiplier;
value = Math.round(value) / multiplier;
return value;
},
roundValues: function(data, length) {
return $A(data).collect(function(value) { return this.roundValue(value, length) }.bind(this));
},
paddingLeftOffset: function() {
/* Find the longest label and multiply it by the font size */
var data = this.flat_data;
// Round values
data = this.roundValues(data, 2);
var longest_label_length = $A(data).sort(function(a, b) { return a.toString().length < b.toString().length }).first().toString().length;
longest_label_length = longest_label_length > 2 ? longest_label_length - 1 : longest_label_length;
return longest_label_length * this.options['font_size'];
},
paddingBottomOffset: function() {
/* Find the longest label and multiply it by the font size */
return this.options['font_size'];
},
/* Subtract the largest and smallest values from the data sets */
calculateRange: function() {
this.max = this.flat_data.max();
this.min = this.flat_data.min();
return this.max - this.min;
},
normaliseData: function(data) {
return $A(data).collect(function(value) {
return this.normalise(value);
}.bind(this))
},
normalise: function(value) {
var total = this.start_value == 0 ? this.top_value : this.range;
return ((value / total) * (this.graph_height));
},
draw: function() {
if (this.options['grid']) {
this.drawGrid();
}
if (this.options['meanline']) {
this.drawMeanLine(this.normaliseData(this.flat_data));
}
if(this.options['draw_axis']) {
this.drawAxis();
}
if (this.options['show_vertical_labels']) {
this.drawVerticalLabels();
}
if (this.options['show_horizontal_labels']) {
this.drawHorizontalLabels();
}
this.data_sets.each(function(data, index) {
this.drawLines(data[0], this.options['colours'][data[0]], this.normaliseData(data[1]), this.options['datalabels'][data[0]], this.element);
}.bind(this));
if (this.start_value != 0) {
this.drawFocusHint();
}
},
drawGrid: function() {
var path = this.paper.path({ stroke: '#CCC', 'stroke-width': '1px' });
if (this.options['show_vertical_labels'] && !this.options['horizontalbar_grid']) {
var y = this.graph_height + this.y_padding_top;
for (i = 0; i < this.y_label_count; i++) {
y = y - (this.graph_height / this.y_label_count);
path.moveTo(this.x_padding_left, y);
path.lineTo(this.x_padding_left + this.graph_width, y);
}
}
if (this.options['show_horizontal_labels']) {
var x = this.x_padding_left + this.options['plot_padding'] + this.grid_start_offset,
x_labels = this.options['labels'].length;
if(this.options["horizontalbar_grid"]) {
x_step = this.graph_width / this.y_label_count;
} else {
x_step = this.step;
}
for (i = 0; i < x_labels; i++) {
path.moveTo(x, this.y_padding_top);
path.lineTo(x, this.y_padding_top + this.graph_height);
x = x + x_step;
}
x = x - this.options['plot_padding'] - 1;
path.moveTo(x, this.y_padding_top);
path.lineTo(x, this.y_padding_top + this.graph_height);
}
},
drawLines: function(label, colour, data, datalabel, element) {
var coords = this.calculateCoords(data);
var y_offset = (this.graph_height + this.y_padding_top) + this.normalise(this.start_value);
if(this.options["start_at_zero"] == false) {
var odd_horizontal_offset=0;
$A(coords).each(function(coord, index) {
if(coord[1] == y_offset) {odd_horizontal_offset++;}
});
if(odd_horizontal_offset>1) {
coords.splice(0,odd_horizontal_offset);
}
}
if(this.options["stacked_fill"]) {
var cursor = this.paper.path({stroke: colour, fill: colour, 'stroke-width': '0'});
coords.unshift([coords[0][0],y_offset]);
coords.push([coords[coords.length-1][0],y_offset]);
} else {
var cursor = this.paper.path({stroke: colour, 'stroke-width': '5px'});
}
if(this.options["datalabels"]) {
var datalabelelem;
var colorattr = (this.options["stacked_fill"]) ? "fill" : "stroke";
var hover_colour = this.options["hover_colour"];
cursor.node.onmouseover = function (e) {
if(colorattr==="fill") { cursor.attr({fill: hover_colour});}
else { cursor.attr({stroke: hover_colour});}
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
datalabelelem = '<div id="datalabelelem-'+element.id+'" style="left:'+posx+'px;top:'+posy+'px" class="datalabelelem">'+datalabel+'</div>';
element.insert(datalabelelem);
cursor.node.onmousemove = function(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
$('datalabelelem-'+element.id).setStyle({left:posx+'px',top:posy+'px'});
};
};
cursor.node.onmouseout = function () {
if(colorattr==="fill") { cursor.attr({fill: colour});}
else { cursor.attr({stroke: colour});}
$('datalabelelem-'+element.id).remove();
}
}
$A(coords).each(function(coord, index) {
var x = coord[0],
y = coord[1];
this.drawPlot(index, cursor, x, y, colour, coords, datalabel, element);
}.bind(this))
},
calculateCoords: function(data) {
var x = this.x_padding_left + this.options['plot_padding'] - this.step;
var y_offset = (this.graph_height + this.y_padding_top) + this.normalise(this.start_value);
return $A(data).collect(function(value) {
var y = y_offset - value;
x = x + this.step;
return [x, y];
}.bind(this))
},
drawFocusHint: function() {
var length = 5,
x = this.x_padding_left + (length / 2) - 1,
y = this.options['height'] - this.y_padding_bottom;
var cursor = this.paper.path({stroke: this.options['label_colour'], 'stroke-width': 2});
cursor.moveTo(x, y);
cursor.lineTo(x - length, y - length);
cursor.moveTo(x, y - length);
cursor.lineTo(x - length, y - (length * 2));
},
drawMeanLine: function(data) {
var cursor = this.paper.path(this.options['meanline']);
var offset = $A(data).inject(0, function(value, sum) { return sum + value }) / data.length;
cursor.moveTo(this.x_padding_left - 1, this.options['height'] - this.y_padding_bottom - offset);
cursor.lineTo(this.graph_width + this.x_padding_left, this.options['height'] - this.y_padding_bottom - offset);
},
drawAxis: function() {
var cursor = this.paper.path({stroke: this.options['label_colour']});
cursor.moveTo(this.x_padding_left - 1, this.options['height'] - this.y_padding_bottom);
cursor.lineTo(this.graph_width + this.x_padding_left, this.options['height'] - this.y_padding_bottom);
cursor.moveTo(this.x_padding_left - 1, this.options['height'] - this.y_padding_bottom);
cursor.lineTo(this.x_padding_left - 1, this.y_padding_top);
},
makeValueLabels: function(steps) {
var step = this.label_step,
label = this.start_value,
labels = [];
for (var i = 0; i < steps; i++) {
label = this.roundValue((label + step), 2);
labels.push(label);
}
return labels;
},
/* Axis label markers */
drawMarkers: function(labels, direction, step, start_offset, font_offsets, extra_font_options) {
function x_offset(value) {
return value * direction[0];
}
function y_offset(value) {
return value * direction[1];
}
/* Start at the origin */
var x = this.x_padding_left - 1 + x_offset(start_offset),
y = this.options['height'] - this.y_padding_bottom + y_offset(start_offset);
var cursor = this.paper.path({stroke: this.options['label_colour']});
font_options = {"font": this.options['font_size'] + 'px "Arial"', stroke: "none", fill: "#000"};
Object.extend(font_options, extra_font_options || {});
labels.each(function(label) {
cursor.moveTo(x, y);
cursor.lineTo(x + y_offset(5), y + x_offset(5));
this.paper.text(x + font_offsets[0], y - font_offsets[1], label).attr(font_options).toFront();
x = x + x_offset(step);
y = y + y_offset(step);
}.bind(this));
},
drawVerticalLabels: function() {
var y_step = this.graph_height / this.y_label_count;
this.drawMarkers(this.value_labels, [0, -1], y_step, y_step, [-8, -2], { "text-anchor": 'end' });
},
drawHorizontalLabels: function() {
this.drawMarkers(this.options['labels'], [1, 0], this.step, this.options['plot_padding'], [0, (this.options['font_size'] + 7) * -1]);
}
});
Ico.LineGraph = Class.create(Ico.BaseGraph, {
chartDefaults: function() {
return { plot_padding: 10 };
},
setChartSpecificOptions: function() {
if (typeof(this.options['curve_amount']) == 'undefined') {
this.options['curve_amount'] = 10
}
},
calculateStep: function() {
return (this.graph_width - (this.options['plot_padding'] * 2)) / (this.data_size - 1);
},
startPlot: function(cursor, x, y, colour) {
cursor.moveTo(x, y);
},
drawPlot: function(index, cursor, x, y, colour, coords, datalabel, element) {
if (this.options['markers'] == 'circle') {
var circle = this.paper.circle(x, y, this.options['marker_size']);
circle.attr({ 'stroke-width': '1px', stroke: this.options['background_colour'], fill: colour });
if(this.options["datalabels"]) {
var datalabelelem;
var old_marker_size = this.options["marker_size"];
circle.node.onmouseover = function (e) {
new_marker_size = parseInt(1.7*old_marker_size);
circle.attr({r:new_marker_size});
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
datalabelelem = '<div id="datalabelelem-'+element.id+'" style="left:'+posx+'px;top:'+posy+'px" class="datalabelelem">'+datalabel+'</div>';
element.insert(datalabelelem);
cursor.node.onmousemove = function(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
$('datalabelelem-'+element.id).setStyle({left:posx+'px',top:posy+'px'});
};
};
circle.node.onmouseout = function () {
circle.attr({r:old_marker_size});
$('datalabelelem-'+element.id).remove();
}
}
}
if (index == 0) {
return this.startPlot(cursor, x, y, colour);
}
if (this.options['curve_amount']) {
cursor.cplineTo(x, y, this.options['curve_amount']);
} else {
cursor.lineTo(x, y);
}
}
});
Ico.StackGraph = Class.create(Ico.BaseGraph, {
chartDefaults: function() {
return { plot_padding: 10 };
},
setChartSpecificOptions: function() {
if (typeof(this.options['curve_amount']) == 'undefined') {
this.options['curve_amount'] = 10
}
},
calculateStep: function() {
return (this.graph_width - (this.options['plot_padding'] * 2)) / (this.data_size - 1);
},
startPlot: function(cursor, x, y, colour) {
cursor.moveTo(x, y);
},
drawPlot: function(index, cursor, x, y, colour, coords) {
if (index == 0) {
return this.startPlot(cursor, x, y, colour);
}
if (this.options['curve_amount'] && index > 1) {
if(index < coords.length-1) {
cursor.cplineTo(x, y, this.options['curve_amount']);
} else {
cursor.lineTo(x, y);
}
} else {
cursor.lineTo(x, y);
}
}
});
/* This is based on the line graph, I can probably inherit from a shared class here */
Ico.BarGraph = Class.create(Ico.BaseGraph, {
chartDefaults: function() {
return { plot_padding: 0 };
},
setChartSpecificOptions: function() {
this.bar_padding = 5;
this.bar_width = this.calculateBarWidth();
this.options['plot_padding'] = (this.bar_width / 2);
this.step = this.calculateStep();
this.grid_start_offset = this.bar_padding - 1;
},
calculateBarWidth: function() {
return (this.graph_width / this.data_size) - this.bar_padding;
},
calculateStep: function() {
return (this.graph_width - (this.options['plot_padding'] * 2) - (this.bar_padding * 2)) / (this.data_size - 1);
},
drawPlot: function(index, cursor, x, y, colour) {
var start_y = this.options['height'] - this.y_padding_bottom;
x = x + this.bar_padding;
cursor.moveTo(x, start_y);
cursor.attr({stroke: colour, 'stroke-width': this.bar_width + 'px'});
cursor.lineTo(x, y);
x = x + this.step;
cursor.moveTo(x, start_y);
},
/* Change the standard options to correctly offset against the bars */
drawHorizontalLabels: function() {
var x_start = this.bar_padding + this.options['plot_padding'];
this.drawMarkers(this.options['labels'], [1, 0], this.step, x_start, [0, (this.options['font_size'] + 7) * -1]);
}
});
/* This is based on the line graph, I can probably inherit from a shared class here */
Ico.HorizontalBarGraph = Class.create(Ico.BarGraph, {
setChartSpecificOptions: function() {
// Approximate the width required by the labels
this.x_padding_left = 12 + this.longestLabel() * (this.options['font_size'] / 2);
this.bar_padding = 5;
this.bar_width = this.calculateBarHeight();
this.options['plot_padding'] = 0;
this.step = this.calculateStep();
this.options["horizontalbar_grid"] = true;
},
normalise: function(value) {
var offset = this.x_padding_left;
return ((value / this.range) * (this.graph_width - offset));
},
longestLabel: function() {
return $A(this.options['labels']).sort(function(a, b) { return a.toString().length < b.toString().length }).first().toString().length;
},
/* Height */
calculateBarHeight: function() {
return (this.graph_height / this.data_size) - this.bar_padding;
},
calculateStep: function() {
return (this.graph_height - (this.options['plot_padding'] * 2)) / (this.data_size);
},
drawLines: function(label, colour, data, datalabel, element) {
var x = this.x_padding_left + this.options['plot_padding'];
var y = this.options['height'] - this.y_padding_bottom - (this.step / 2);
var firstcolor = this.options['horiz_bargraph_firstcolour'];
$A(data).each(function(value, number) {
var colour2;
if(firstcolor && value == $A(data).first()){
colour2 = firstcolor;
} else {
colour2 = colour;
}
var cursor = this.paper.path({stroke: colour2, 'stroke-width': this.bar_width + 'px'}).moveTo(x, y);
cursor.lineTo(x + value - this.normalise(this.start_value), y);
y = y - this.step;
if(this.options["datalabels"]) {
var hover_colour = this.options["hover_colour"];
cursor.node.onmouseover = function (e) {
cursor.attr({stroke: hover_colour});
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
var datalabelelem = '<div id="datalabelelem-'+element.id+'" style="left:'+posx+'px;top:'+posy+'px" class="datalabelelem">'+datalabel[number]+'</div>';
element.insert(datalabelelem);
cursor.node.onmousemove = function(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
$('datalabelelem-'+element.id).setStyle({left:posx+'px',top:posy+'px'});
};
};
cursor.node.onmouseout = function (e) {
cursor.attr({stroke: colour2});
$('datalabelelem-'+element.id).remove();
};
}
}.bind(this))
},
/* Horizontal version */
drawFocusHint: function() {
var length = 5,
x = this.x_padding_left + (this.step * 2),
y = this.options['height'] - this.y_padding_bottom;
var cursor = this.paper.path({stroke: this.options['label_colour'], 'stroke-width': 2});
cursor.moveTo(x, y);
cursor.lineTo(x - length, y + length);
cursor.moveTo(x - length, y);
cursor.lineTo(x - (length * 2), y + length);
},
drawVerticalLabels: function() {
var y_start = (this.step / 2) - this.options['plot_padding'];
this.drawMarkers(this.options['labels'], [0, -1], this.step, y_start, [-8, -(this.options['font_size'] / 5)], { "text-anchor": 'end' });
},
drawHorizontalLabels: function() {
var x_step = this.graph_width / this.y_label_count,
x_labels = this.makeValueLabels(this.y_label_count);
if(this.options["percentages"]) {
for(var i=0;i<x_labels.length;i++) {
x_labels[i] += "%";
}
}
this.drawMarkers(x_labels, [1, 0], x_step, x_step, [0, (this.options['font_size'] + 7) * -1]);
}
});
| ico.js | var Ico = {
Base: {},
SparkLine: {},
SparkBar: {},
BaseGraph: {},
LineGraph: {},
BarGraph: {},
HorizontalBarGraph: {}
}
Ico.Base = Class.create({
/* Returns a suitable set of labels for given data points on the Y axis */
labelStep: function(data) {
var min = data.min(),
max = data.max(),
range = max - min,
step = 0;
if (range < 2) {
step = 0.1;
} else if (range < 3) {
step = 0.2;
} else if (range < 5) {
step = 0.5;
} else if (range < 11) {
step = 1;
} else if (range < 50) {
step = 5;
} else if (range < 100) {
step = 10;
} else {
step = Math.pow(20, (Math.log(range) / Math.LN10).round() - 1);
}
return step;
}
});
Ico.SparkLine = Class.create(Ico.Base, {
initialize: function(element, data, options) {
this.element = element;
this.data = data;
this.options = {
width: parseInt(element.getStyle('width')),
height: parseInt(element.getStyle('height')),
highlight: false,
background_colour: element.getStyle('backgroundColor'),
colour: '#036'
};
Object.extend(this.options, options || { });
this.step = this.calculateStep();
this.paper = Raphael(this.element, this.options['width'], this.options['height']);
if (this.options['acceptable_range']) {
this.background = this.paper.rect(0, this.options['height'] - this.normalise(this.options['acceptable_range'][1]),
this.options['width'], this.options['height'] - this.normalise(this.options['acceptable_range'][0]));
} else {
this.background = this.paper.rect(0, 0, this.options['width'], this.options['height']);
}
this.background.attr({fill: this.options['background_colour'], stroke: 'none' });
this.draw();
},
calculateStep: function() {
return this.options['width'] / (this.data.length - 1);
},
normalisedData: function() {
return $A(this.data).collect(function(value) {
return this.normalise(value);
}.bind(this))
},
normalise: function(value) {
return (this.options['height'] / this.data.max()) * value;
},
draw: function() {
var data = this.normalisedData();
this.drawLines('', this.options['colour'], data);
if (this.options['highlight']) {
this.showHighlight(data);
}
},
drawLines: function(label, colour, data) {
var line = this.paper.path({ stroke: colour }).moveTo(0, this.options['height'] - data.first());
var x = 0;
data.slice(1).each(function(value) {
x = x + this.step;
line.lineTo(x, this.options['height'] - value);
}.bind(this))
},
showHighlight: function(data) {
var size = 2,
x = this.options['width'] - size,
i = this.options['highlight']['index'] || data.length - 1,
y = data[i] + ((size / 2).round());
// Find the x position if it's not the last value
if (typeof(this.options['highlight']['index']) != 'undefined') {
x = this.step * this.options['highlight']['index'];
}
var circle = this.paper.circle(x, this.options['height'] - y, size);
circle.attr({ stroke: false, fill: this.options['highlight']['colour']})
}
});
Ico.SparkBar = Class.create(Ico.SparkLine, {
calculateStep: function() {
return this.options['width'] / this.data.length;
},
drawLines: function(label, colour, data) {
var width = this.step > 2 ? this.step - 1 : this.step;
var x = width;
var line = this.paper.path({ stroke: colour, 'stroke-width': width });
data.each(function(value) {
line.moveTo(x, this.options['height'] - value)
line.lineTo(x, this.options['height']);
x = x + this.step;
}.bind(this))
}
})
Ico.BaseGraph = Class.create(Ico.Base, {
initialize: function(element, data, options) {
this.element = element;
this.data_sets = Object.isArray(data) ? new Hash({ one: data }) : $H(data);
this.flat_data = this.data_sets.collect(function(data_set) { return data_set[1] }).flatten();
this.range = this.calculateRange();
this.data_size = this.longestDataSetLength();
this.start_value = this.calculateStartValue();
if (this.start_value == 0) {
this.range = this.max;
}
/* If one colour is specified, map it to a compatible set */
if (options && options['colour']) {
options['colours'] = {};
this.data_sets.keys().each(function(key) {
options['colours'][key] = options['colour'];
});
}
this.options = {
width: parseInt(element.getStyle('width')),
height: parseInt(element.getStyle('height')),
labels: $A($R(1, this.data_size)), // Label data
plot_padding: 10, // Padding for the graph line/bar plots
font_size: 10, // Label font size
show_horizontal_labels: true,
show_vertical_labels: true,
colours: this.makeRandomColours(), // Line colours
background_colour: element.getStyle('backgroundColor'),
label_colour: '#666', // Label text colour
markers: false, // false, circle
marker_size: 5,
meanline: false,
y_padding_top: 20,
stacked_fill: false, // fill the area in a stacked graph
draw_axis: true,
datalabels: '',
percentages: false, // opt for percentage in horizontal graph horizontal labels
start_at_zero: true,
horiz_bargraph_firstcolour: false // different colour for first value in horizontal graph
};
Object.extend(this.options, this.chartDefaults() || { });
Object.extend(this.options, options || { });
/* Padding around the graph area to make room for labels */
this.x_padding_left = 10 + this.paddingLeftOffset();
this.x_padding_right = 20;
this.x_padding = this.x_padding_left + this.x_padding_right;
this.y_padding_top = this.options['y_padding_top'];
this.y_padding_bottom = 20 + this.paddingBottomOffset();
this.y_padding = this.y_padding_top + this.y_padding_bottom;
this.graph_width = this.options['width'] - (this.x_padding);
this.graph_height = this.options['height'] - (this.y_padding);
this.step = this.calculateStep();
this.label_step = this.labelStep(this.flat_data);
/* Calculate how many labels are required */
this.y_label_count = (this.range / this.label_step).round();
this.value_labels = this.makeValueLabels(this.y_label_count);
this.top_value = this.value_labels.last();
if (this.start_value == 0) {
this.range = this.top_value;
}
/* Grid control options */
this.grid_start_offset = -1;
/* Drawing */
this.paper = Raphael(this.element, this.options['width'], this.options['height']);
this.background = this.paper.rect(this.x_padding_left, this.y_padding_top, this.graph_width, this.graph_height);
this.background.attr({fill: this.options['background_colour'], stroke: 'none' });
if (this.options['meanline'] === true) {
this.options['meanline'] = { 'stroke-width': '2px', stroke: '#BBBBBB' };
}
this.setChartSpecificOptions();
this.draw();
},
chartDefaults: function() {
/* Define in child class */
},
drawPlot: function(index, cursor, x, y, colour) {
/* Define in child class */
},
drawHorizontalLabels: function() {
/* Define in child class */
},
calculateStep: function() {
/* Define in child classes */
},
calculateStartValue: function() {
var min = this.flat_data.min();
return this.range < min || min < 0 ? min.round() : 0;
},
makeRandomColours: function(number) {
var colours = {};
this.data_sets.each(function(data) {
colours[data[0]] = Raphael.hsb2rgb(Math.random(), 1, .75).hex;
});
return colours;
},
longestDataSetLength: function() {
var length = 0;
this.data_sets.each(function(data_set) {
length = data_set[1].length > length ? data_set[1].length : length;
});
return length;
},
roundValue: function(value, length) {
var multiplier = Math.pow(10, length);
value *= multiplier;
value = Math.round(value) / multiplier;
return value;
},
roundValues: function(data, length) {
return $A(data).collect(function(value) { return this.roundValue(value, length) }.bind(this));
},
paddingLeftOffset: function() {
/* Find the longest label and multiply it by the font size */
var data = this.flat_data;
// Round values
data = this.roundValues(data, 2);
var longest_label_length = $A(data).sort(function(a, b) { return a.toString().length < b.toString().length }).first().toString().length;
longest_label_length = longest_label_length > 2 ? longest_label_length - 1 : longest_label_length;
return longest_label_length * this.options['font_size'];
},
paddingBottomOffset: function() {
/* Find the longest label and multiply it by the font size */
return this.options['font_size'];
},
/* Subtract the largest and smallest values from the data sets */
calculateRange: function() {
this.max = this.flat_data.max();
this.min = this.flat_data.min();
return this.max - this.min;
},
normaliseData: function(data) {
return $A(data).collect(function(value) {
return this.normalise(value);
}.bind(this))
},
normalise: function(value) {
var total = this.start_value == 0 ? this.top_value : this.range;
return ((value / total) * (this.graph_height));
},
draw: function() {
if (this.options['grid']) {
this.drawGrid();
}
if (this.options['meanline']) {
this.drawMeanLine(this.normaliseData(this.flat_data));
}
if(this.options['draw_axis']) {
this.drawAxis();
}
if (this.options['show_vertical_labels']) {
this.drawVerticalLabels();
}
if (this.options['show_horizontal_labels']) {
this.drawHorizontalLabels();
}
this.data_sets.each(function(data, index) {
this.drawLines(data[0], this.options['colours'][data[0]], this.normaliseData(data[1]), this.options['datalabels'][data[0]], this.element);
}.bind(this));
if (this.start_value != 0) {
this.drawFocusHint();
}
},
drawGrid: function() {
var path = this.paper.path({ stroke: '#CCC', 'stroke-width': '1px' });
if (this.options['show_vertical_labels'] && !this.options['horizontalbar_grid']) {
var y = this.graph_height + this.y_padding_top;
for (i = 0; i < this.y_label_count; i++) {
y = y - (this.graph_height / this.y_label_count);
path.moveTo(this.x_padding_left, y);
path.lineTo(this.x_padding_left + this.graph_width, y);
}
}
if (this.options['show_horizontal_labels']) {
var x = this.x_padding_left + this.options['plot_padding'] + this.grid_start_offset,
x_labels = this.options['labels'].length;
if(this.options["horizontalbar_grid"]) {
x_step = this.graph_width / this.y_label_count;
} else {
x_step = this.step;
}
for (i = 0; i < x_labels; i++) {
path.moveTo(x, this.y_padding_top);
path.lineTo(x, this.y_padding_top + this.graph_height);
x = x + x_step;
}
x = x - this.options['plot_padding'] - 1;
path.moveTo(x, this.y_padding_top);
path.lineTo(x, this.y_padding_top + this.graph_height);
}
},
drawLines: function(label, colour, data, datalabel, element) {
var coords = this.calculateCoords(data);
var y_offset = (this.graph_height + this.y_padding_top) + this.normalise(this.start_value);
if(this.options["start_at_zero"] == false) {
var odd_horizontal_offset=0;
$A(coords).each(function(coord, index) {
if(coord[1] == y_offset) {odd_horizontal_offset++;}
});
if(odd_horizontal_offset>1) {
coords.splice(0,odd_horizontal_offset);
}
}
if(this.options["stacked_fill"]) {
var cursor = this.paper.path({stroke: colour, fill: colour, 'stroke-width': '0'});
coords.unshift([coords[0][0],y_offset]);
coords.push([coords[coords.length-1][0],y_offset]);
} else {
var cursor = this.paper.path({stroke: colour, 'stroke-width': '5px'});
}
if(this.options["datalabels"]) {
var datalabelelem;
var colorattr = (this.options["stacked_fill"]) ? "fill" : "stroke";
cursor.node.onmouseover = function (e) {
if(colorattr==="fill") { cursor.attr({fill: "#333333"});}
else { cursor.attr({stroke: "#333333"});}
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
datalabelelem = '<div id="datalabelelem-'+element.id+'" style="left:'+posx+'px;top:'+posy+'px" class="datalabelelem">'+datalabel+'</div>';
element.insert(datalabelelem);
cursor.node.onmousemove = function(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
$('datalabelelem-'+element.id).setStyle({left:posx+'px',top:posy+'px'});
};
};
cursor.node.onmouseout = function () {
if(colorattr==="fill") { cursor.attr({fill: colour});}
else { cursor.attr({stroke: colour});}
$('datalabelelem-'+element.id).remove();
}
}
$A(coords).each(function(coord, index) {
var x = coord[0],
y = coord[1];
this.drawPlot(index, cursor, x, y, colour, coords, datalabel, element);
}.bind(this))
},
calculateCoords: function(data) {
var x = this.x_padding_left + this.options['plot_padding'] - this.step;
var y_offset = (this.graph_height + this.y_padding_top) + this.normalise(this.start_value);
return $A(data).collect(function(value) {
var y = y_offset - value;
x = x + this.step;
return [x, y];
}.bind(this))
},
drawFocusHint: function() {
var length = 5,
x = this.x_padding_left + (length / 2) - 1,
y = this.options['height'] - this.y_padding_bottom;
var cursor = this.paper.path({stroke: this.options['label_colour'], 'stroke-width': 2});
cursor.moveTo(x, y);
cursor.lineTo(x - length, y - length);
cursor.moveTo(x, y - length);
cursor.lineTo(x - length, y - (length * 2));
},
drawMeanLine: function(data) {
var cursor = this.paper.path(this.options['meanline']);
var offset = $A(data).inject(0, function(value, sum) { return sum + value }) / data.length;
cursor.moveTo(this.x_padding_left - 1, this.options['height'] - this.y_padding_bottom - offset);
cursor.lineTo(this.graph_width + this.x_padding_left, this.options['height'] - this.y_padding_bottom - offset);
},
drawAxis: function() {
var cursor = this.paper.path({stroke: this.options['label_colour']});
cursor.moveTo(this.x_padding_left - 1, this.options['height'] - this.y_padding_bottom);
cursor.lineTo(this.graph_width + this.x_padding_left, this.options['height'] - this.y_padding_bottom);
cursor.moveTo(this.x_padding_left - 1, this.options['height'] - this.y_padding_bottom);
cursor.lineTo(this.x_padding_left - 1, this.y_padding_top);
},
makeValueLabels: function(steps) {
var step = this.label_step,
label = this.start_value,
labels = [];
for (var i = 0; i < steps; i++) {
label = this.roundValue((label + step), 2);
labels.push(label);
}
return labels;
},
/* Axis label markers */
drawMarkers: function(labels, direction, step, start_offset, font_offsets, extra_font_options) {
function x_offset(value) {
return value * direction[0];
}
function y_offset(value) {
return value * direction[1];
}
/* Start at the origin */
var x = this.x_padding_left - 1 + x_offset(start_offset),
y = this.options['height'] - this.y_padding_bottom + y_offset(start_offset);
var cursor = this.paper.path({stroke: this.options['label_colour']});
font_options = {"font": this.options['font_size'] + 'px "Arial"', stroke: "none", fill: "#000"};
Object.extend(font_options, extra_font_options || {});
labels.each(function(label) {
cursor.moveTo(x, y);
cursor.lineTo(x + y_offset(5), y + x_offset(5));
this.paper.text(x + font_offsets[0], y - font_offsets[1], label).attr(font_options).toFront();
x = x + x_offset(step);
y = y + y_offset(step);
}.bind(this));
},
drawVerticalLabels: function() {
var y_step = this.graph_height / this.y_label_count;
this.drawMarkers(this.value_labels, [0, -1], y_step, y_step, [-8, -2], { "text-anchor": 'end' });
},
drawHorizontalLabels: function() {
this.drawMarkers(this.options['labels'], [1, 0], this.step, this.options['plot_padding'], [0, (this.options['font_size'] + 7) * -1]);
}
});
Ico.LineGraph = Class.create(Ico.BaseGraph, {
chartDefaults: function() {
return { plot_padding: 10 };
},
setChartSpecificOptions: function() {
if (typeof(this.options['curve_amount']) == 'undefined') {
this.options['curve_amount'] = 10
}
},
calculateStep: function() {
return (this.graph_width - (this.options['plot_padding'] * 2)) / (this.data_size - 1);
},
startPlot: function(cursor, x, y, colour) {
cursor.moveTo(x, y);
},
drawPlot: function(index, cursor, x, y, colour, coords, datalabel, element) {
if (this.options['markers'] == 'circle') {
var circle = this.paper.circle(x, y, this.options['marker_size']);
circle.attr({ 'stroke-width': '1px', stroke: this.options['background_colour'], fill: colour });
if(this.options["datalabels"]) {
var datalabelelem;
var old_marker_size = this.options["marker_size"];
circle.node.onmouseover = function (e) {
new_marker_size = parseInt(1.7*old_marker_size);
circle.attr({r:new_marker_size});
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
datalabelelem = '<div id="datalabelelem-'+element.id+'" style="left:'+posx+'px;top:'+posy+'px" class="datalabelelem">'+datalabel+'</div>';
element.insert(datalabelelem);
cursor.node.onmousemove = function(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
$('datalabelelem-'+element.id).setStyle({left:posx+'px',top:posy+'px'});
};
};
circle.node.onmouseout = function () {
circle.attr({r:old_marker_size});
$('datalabelelem-'+element.id).remove();
}
}
}
if (index == 0) {
return this.startPlot(cursor, x, y, colour);
}
if (this.options['curve_amount']) {
cursor.cplineTo(x, y, this.options['curve_amount']);
} else {
cursor.lineTo(x, y);
}
}
});
Ico.StackGraph = Class.create(Ico.BaseGraph, {
chartDefaults: function() {
return { plot_padding: 10 };
},
setChartSpecificOptions: function() {
if (typeof(this.options['curve_amount']) == 'undefined') {
this.options['curve_amount'] = 10
}
},
calculateStep: function() {
return (this.graph_width - (this.options['plot_padding'] * 2)) / (this.data_size - 1);
},
startPlot: function(cursor, x, y, colour) {
cursor.moveTo(x, y);
},
drawPlot: function(index, cursor, x, y, colour, coords) {
if (index == 0) {
return this.startPlot(cursor, x, y, colour);
}
if (this.options['curve_amount'] && index > 1) {
if(index < coords.length-1) {
cursor.cplineTo(x, y, this.options['curve_amount']);
} else {
cursor.lineTo(x, y);
}
} else {
cursor.lineTo(x, y);
}
}
});
/* This is based on the line graph, I can probably inherit from a shared class here */
Ico.BarGraph = Class.create(Ico.BaseGraph, {
chartDefaults: function() {
return { plot_padding: 0 };
},
setChartSpecificOptions: function() {
this.bar_padding = 5;
this.bar_width = this.calculateBarWidth();
this.options['plot_padding'] = (this.bar_width / 2);
this.step = this.calculateStep();
this.grid_start_offset = this.bar_padding - 1;
},
calculateBarWidth: function() {
return (this.graph_width / this.data_size) - this.bar_padding;
},
calculateStep: function() {
return (this.graph_width - (this.options['plot_padding'] * 2) - (this.bar_padding * 2)) / (this.data_size - 1);
},
drawPlot: function(index, cursor, x, y, colour) {
var start_y = this.options['height'] - this.y_padding_bottom;
x = x + this.bar_padding;
cursor.moveTo(x, start_y);
cursor.attr({stroke: colour, 'stroke-width': this.bar_width + 'px'});
cursor.lineTo(x, y);
x = x + this.step;
cursor.moveTo(x, start_y);
},
/* Change the standard options to correctly offset against the bars */
drawHorizontalLabels: function() {
var x_start = this.bar_padding + this.options['plot_padding'];
this.drawMarkers(this.options['labels'], [1, 0], this.step, x_start, [0, (this.options['font_size'] + 7) * -1]);
}
});
/* This is based on the line graph, I can probably inherit from a shared class here */
Ico.HorizontalBarGraph = Class.create(Ico.BarGraph, {
setChartSpecificOptions: function() {
// Approximate the width required by the labels
this.x_padding_left = 12 + this.longestLabel() * (this.options['font_size'] / 2);
this.bar_padding = 5;
this.bar_width = this.calculateBarHeight();
this.options['plot_padding'] = 0;
this.step = this.calculateStep();
this.options["horizontalbar_grid"] = true;
},
normalise: function(value) {
var offset = this.x_padding_left;
return ((value / this.range) * (this.graph_width - offset));
},
longestLabel: function() {
return $A(this.options['labels']).sort(function(a, b) { return a.toString().length < b.toString().length }).first().toString().length;
},
/* Height */
calculateBarHeight: function() {
return (this.graph_height / this.data_size) - this.bar_padding;
},
calculateStep: function() {
return (this.graph_height - (this.options['plot_padding'] * 2)) / (this.data_size);
},
drawLines: function(label, colour, data, datalabel, element) {
var x = this.x_padding_left + this.options['plot_padding'];
var y = this.options['height'] - this.y_padding_bottom - (this.step / 2);
var firstcolor = this.options['horiz_bargraph_firstcolour'];
$A(data).each(function(value, number) {
var colour2;
if(firstcolor && value == $A(data).first()){
colour2 = firstcolor;
} else {
colour2 = colour;
}
var cursor = this.paper.path({stroke: colour2, 'stroke-width': this.bar_width + 'px'}).moveTo(x, y);
cursor.lineTo(x + value - this.normalise(this.start_value), y);
y = y - this.step;
if(this.options["datalabels"]) {
cursor.node.onmouseover = function (e) {
cursor.attr({stroke: "#333333"});
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
var datalabelelem = '<div id="datalabelelem-'+element.id+'" style="left:'+posx+'px;top:'+posy+'px" class="datalabelelem">'+datalabel[number]+'</div>';
element.insert(datalabelelem);
cursor.node.onmousemove = function(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
$('datalabelelem-'+element.id).setStyle({left:posx+'px',top:posy+'px'});
};
};
cursor.node.onmouseout = function (e) {
cursor.attr({stroke: colour2});
$('datalabelelem-'+element.id).remove();
};
}
}.bind(this))
},
/* Horizontal version */
drawFocusHint: function() {
var length = 5,
x = this.x_padding_left + (this.step * 2),
y = this.options['height'] - this.y_padding_bottom;
var cursor = this.paper.path({stroke: this.options['label_colour'], 'stroke-width': 2});
cursor.moveTo(x, y);
cursor.lineTo(x - length, y + length);
cursor.moveTo(x - length, y);
cursor.lineTo(x - (length * 2), y + length);
},
drawVerticalLabels: function() {
var y_start = (this.step / 2) - this.options['plot_padding'];
this.drawMarkers(this.options['labels'], [0, -1], this.step, y_start, [-8, -(this.options['font_size'] / 5)], { "text-anchor": 'end' });
},
drawHorizontalLabels: function() {
var x_step = this.graph_width / this.y_label_count,
x_labels = this.makeValueLabels(this.y_label_count);
if(this.options["percentages"]) {
for(var i=0;i<x_labels.length;i++) {
x_labels[i] += "%";
}
}
this.drawMarkers(x_labels, [1, 0], x_step, x_step, [0, (this.options['font_size'] + 7) * -1]);
}
});
| add hover colour to api
| ico.js | add hover colour to api | <ide><path>co.js
<ide> datalabels: '',
<ide> percentages: false, // opt for percentage in horizontal graph horizontal labels
<ide> start_at_zero: true,
<del> horiz_bargraph_firstcolour: false // different colour for first value in horizontal graph
<add> horiz_bargraph_firstcolour: false, // different colour for first value in horizontal graph
<add> hover_colour: "#333333" // hover color if there are datalabels
<ide> };
<ide> Object.extend(this.options, this.chartDefaults() || { });
<ide> Object.extend(this.options, options || { });
<ide> if(this.options["datalabels"]) {
<ide> var datalabelelem;
<ide> var colorattr = (this.options["stacked_fill"]) ? "fill" : "stroke";
<del>
<add> var hover_colour = this.options["hover_colour"];
<ide> cursor.node.onmouseover = function (e) {
<del> if(colorattr==="fill") { cursor.attr({fill: "#333333"});}
<del> else { cursor.attr({stroke: "#333333"});}
<add> if(colorattr==="fill") { cursor.attr({fill: hover_colour});}
<add> else { cursor.attr({stroke: hover_colour});}
<ide>
<ide> var posx = 0;
<ide> var posy = 0;
<ide> cursor.lineTo(x + value - this.normalise(this.start_value), y);
<ide> y = y - this.step;
<ide>
<add>
<ide> if(this.options["datalabels"]) {
<add> var hover_colour = this.options["hover_colour"];
<ide> cursor.node.onmouseover = function (e) {
<del> cursor.attr({stroke: "#333333"});
<add> cursor.attr({stroke: hover_colour});
<ide>
<ide> var posx = 0;
<ide> var posy = 0; |
|
Java | apache-2.0 | bde251dc0bb81d486128a53abfb5dd163f1f46be | 0 | strapdata/elassandra,vroyer/elasticassandra,vroyer/elassandra,strapdata/elassandra,vroyer/elasticassandra,vroyer/elassandra,strapdata/elassandra,vroyer/elassandra,vroyer/elasticassandra,strapdata/elassandra,strapdata/elassandra | /*
* 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.test;
import org.elasticsearch.Version;
import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.collect.Tuple;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
public class VersionUtilsTests extends ESTestCase {
public void testAllVersionsSorted() {
List<Version> allVersions = VersionUtils.allReleasedVersions();
for (int i = 0, j = 1; j < allVersions.size(); ++i, ++j) {
assertTrue(allVersions.get(i).before(allVersions.get(j)));
}
}
public void testRandomVersionBetween() {
// full range
Version got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), Version.CURRENT);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
got = VersionUtils.randomVersionBetween(random(), null, Version.CURRENT);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), null);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
// sub range
got = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0,
Version.V_6_0_0_beta1);
assertTrue(got.onOrAfter(Version.V_5_0_0));
assertTrue(got.onOrBefore(Version.V_6_0_0_beta1));
// unbounded lower
got = VersionUtils.randomVersionBetween(random(), null, Version.V_6_0_0_beta1);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.V_6_0_0_beta1));
got = VersionUtils.randomVersionBetween(random(), null, VersionUtils.allReleasedVersions().get(0));
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(VersionUtils.allReleasedVersions().get(0)));
// unbounded upper
got = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0, null);
assertTrue(got.onOrAfter(Version.V_5_0_0));
assertTrue(got.onOrBefore(Version.CURRENT));
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getPreviousVersion(), null);
assertTrue(got.onOrAfter(VersionUtils.getPreviousVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
// range of one
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), VersionUtils.getFirstVersion());
assertEquals(got, VersionUtils.getFirstVersion());
got = VersionUtils.randomVersionBetween(random(), Version.CURRENT, Version.CURRENT);
assertEquals(got, Version.CURRENT);
got = VersionUtils.randomVersionBetween(random(), Version.V_6_0_0_beta1,
Version.V_6_0_0_beta1);
assertEquals(got, Version.V_6_0_0_beta1);
// implicit range of one
got = VersionUtils.randomVersionBetween(random(), null, VersionUtils.getFirstVersion());
assertEquals(got, VersionUtils.getFirstVersion());
got = VersionUtils.randomVersionBetween(random(), Version.CURRENT, null);
assertEquals(got, Version.CURRENT);
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
// max or min can be an unreleased version
final Version unreleased = randomFrom(VersionUtils.allUnreleasedVersions());
assertThat(VersionUtils.randomVersionBetween(random(), null, unreleased), lessThanOrEqualTo(unreleased));
assertThat(VersionUtils.randomVersionBetween(random(), unreleased, null), greaterThanOrEqualTo(unreleased));
assertEquals(unreleased, VersionUtils.randomVersionBetween(random(), unreleased, unreleased));
}
}
public static class TestReleaseBranch {
public static final Version V_5_3_0 = Version.fromString("5.3.0");
public static final Version V_5_3_1 = Version.fromString("5.3.1");
public static final Version V_5_3_2 = Version.fromString("5.3.2");
public static final Version V_5_4_0 = Version.fromString("5.4.0");
public static final Version V_5_4_1 = Version.fromString("5.4.1");
public static final Version CURRENT = V_5_4_1;
}
public void testResolveReleasedVersionsForReleaseBranch() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestReleaseBranch.CURRENT, TestReleaseBranch.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestReleaseBranch.V_5_3_0,
TestReleaseBranch.V_5_3_1,
TestReleaseBranch.V_5_3_2,
TestReleaseBranch.V_5_4_0);
expectedUnreleased = Collections.singletonList(TestReleaseBranch.V_5_4_1);
} else {
expectedReleased = Arrays.asList(
TestReleaseBranch.V_5_3_0,
TestReleaseBranch.V_5_3_1,
TestReleaseBranch.V_5_3_2,
TestReleaseBranch.V_5_4_0,
TestReleaseBranch.V_5_4_1);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestStableBranch {
public static final Version V_5_3_0 = Version.fromString("5.3.0");
public static final Version V_5_3_1 = Version.fromString("5.3.1");
public static final Version V_5_3_2 = Version.fromString("5.3.2");
public static final Version V_5_4_0 = Version.fromString("5.4.0");
public static final Version CURRENT = V_5_4_0;
}
public void testResolveReleasedVersionsForUnreleasedStableBranch() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestStableBranch.CURRENT,
TestStableBranch.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(TestStableBranch.V_5_3_0, TestStableBranch.V_5_3_1);
expectedUnreleased = Arrays.asList(TestStableBranch.V_5_3_2, TestStableBranch.V_5_4_0);
} else {
expectedReleased =
Arrays.asList(TestStableBranch.V_5_3_0, TestStableBranch.V_5_3_1, TestStableBranch.V_5_3_2, TestStableBranch.V_5_4_0);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestStableBranchBehindStableBranch {
public static final Version V_5_3_0 = Version.fromString("5.3.0");
public static final Version V_5_3_1 = Version.fromString("5.3.1");
public static final Version V_5_3_2 = Version.fromString("5.3.2");
public static final Version V_5_4_0 = Version.fromString("5.4.0");
public static final Version V_5_5_0 = Version.fromString("5.5.0");
public static final Version CURRENT = V_5_5_0;
}
public void testResolveReleasedVersionsForStableBranchBehindStableBranch() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestStableBranchBehindStableBranch.CURRENT,
TestStableBranchBehindStableBranch.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(TestStableBranchBehindStableBranch.V_5_3_0, TestStableBranchBehindStableBranch.V_5_3_1);
expectedUnreleased = Arrays.asList(
TestStableBranchBehindStableBranch.V_5_3_2,
TestStableBranchBehindStableBranch.V_5_4_0,
TestStableBranchBehindStableBranch.V_5_5_0);
} else {
expectedReleased = Arrays.asList(
TestStableBranchBehindStableBranch.V_5_3_0,
TestStableBranchBehindStableBranch.V_5_3_1,
TestStableBranchBehindStableBranch.V_5_3_2,
TestStableBranchBehindStableBranch.V_5_4_0,
TestStableBranchBehindStableBranch.V_5_5_0);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestUnstableBranch {
public static final Version V_5_3_0 = Version.fromString("5.3.0");
public static final Version V_5_3_1 = Version.fromString("5.3.1");
public static final Version V_5_3_2 = Version.fromString("5.3.2");
public static final Version V_5_4_0 = Version.fromString("5.4.0");
public static final Version V_6_0_0_alpha1 = Version.fromString("6.0.0-alpha1");
public static final Version V_6_0_0_alpha2 = Version.fromString("6.0.0-alpha2");
public static final Version V_6_0_0_beta1 = Version.fromString("6.0.0-beta1");
public static final Version CURRENT = V_6_0_0_beta1;
}
public void testResolveReleasedVersionsForUnstableBranch() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestUnstableBranch.CURRENT,
TestUnstableBranch.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestUnstableBranch.V_5_3_0,
TestUnstableBranch.V_5_3_1,
TestUnstableBranch.V_6_0_0_alpha1,
TestUnstableBranch.V_6_0_0_alpha2);
expectedUnreleased = Arrays.asList(TestUnstableBranch.V_5_3_2, TestUnstableBranch.V_5_4_0, TestUnstableBranch.V_6_0_0_beta1);
} else {
expectedReleased = Arrays.asList(
TestUnstableBranch.V_5_3_0,
TestUnstableBranch.V_5_3_1,
TestUnstableBranch.V_5_3_2,
TestUnstableBranch.V_5_4_0,
TestUnstableBranch.V_6_0_0_alpha1,
TestUnstableBranch.V_6_0_0_alpha2,
TestUnstableBranch.V_6_0_0_beta1);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestNewMajorRelease {
public static final Version V_5_6_0 = Version.fromString("5.6.0");
public static final Version V_5_6_1 = Version.fromString("5.6.1");
public static final Version V_5_6_2 = Version.fromString("5.6.2");
public static final Version V_6_0_0_alpha1 = Version.fromString("6.0.0-alpha1");
public static final Version V_6_0_0_alpha2 = Version.fromString("6.0.0-alpha2");
public static final Version V_6_0_0_beta1 = Version.fromString("6.0.0-beta1");
public static final Version V_6_0_0_beta2 = Version.fromString("6.0.0-beta2");
public static final Version V_6_0_0 = Version.fromString("6.0.0");
public static final Version V_6_0_1 = Version.fromString("6.0.1");
public static final Version CURRENT = V_6_0_1;
}
public void testResolveReleasedVersionsAtNewMajorRelease() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestNewMajorRelease.CURRENT,
TestNewMajorRelease.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestNewMajorRelease.V_5_6_0,
TestNewMajorRelease.V_5_6_1,
TestNewMajorRelease.V_6_0_0_alpha1,
TestNewMajorRelease.V_6_0_0_alpha2,
TestNewMajorRelease.V_6_0_0_beta1,
TestNewMajorRelease.V_6_0_0_beta2,
TestNewMajorRelease.V_6_0_0);
expectedUnreleased = Arrays.asList(TestNewMajorRelease.V_5_6_2, TestNewMajorRelease.V_6_0_1);
} else {
expectedReleased = Arrays.asList(
TestNewMajorRelease.V_5_6_0,
TestNewMajorRelease.V_5_6_1,
TestNewMajorRelease.V_5_6_2,
TestNewMajorRelease.V_6_0_0_alpha1,
TestNewMajorRelease.V_6_0_0_alpha2,
TestNewMajorRelease.V_6_0_0_beta1,
TestNewMajorRelease.V_6_0_0_beta2,
TestNewMajorRelease.V_6_0_0,
TestNewMajorRelease.V_6_0_1);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestVersionBumpIn6x {
public static final Version V_5_6_0 = Version.fromString("5.6.0");
public static final Version V_5_6_1 = Version.fromString("5.6.1");
public static final Version V_5_6_2 = Version.fromString("5.6.2");
public static final Version V_6_0_0_alpha1 = Version.fromString("6.0.0-alpha1");
public static final Version V_6_0_0_alpha2 = Version.fromString("6.0.0-alpha2");
public static final Version V_6_0_0_beta1 = Version.fromString("6.0.0-beta1");
public static final Version V_6_0_0_beta2 = Version.fromString("6.0.0-beta2");
public static final Version V_6_0_0 = Version.fromString("6.0.0");
public static final Version V_6_0_1 = Version.fromString("6.0.1");
public static final Version V_6_1_0 = Version.fromString("6.1.0");
public static final Version CURRENT = V_6_1_0;
}
public void testResolveReleasedVersionsAtVersionBumpIn6x() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestVersionBumpIn6x.CURRENT,
TestVersionBumpIn6x.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestVersionBumpIn6x.V_5_6_0,
TestVersionBumpIn6x.V_5_6_1,
TestVersionBumpIn6x.V_6_0_0_alpha1,
TestVersionBumpIn6x.V_6_0_0_alpha2,
TestVersionBumpIn6x.V_6_0_0_beta1,
TestVersionBumpIn6x.V_6_0_0_beta2,
TestVersionBumpIn6x.V_6_0_0);
expectedUnreleased = Arrays.asList(TestVersionBumpIn6x.V_5_6_2, TestVersionBumpIn6x.V_6_0_1, TestVersionBumpIn6x.V_6_1_0);
} else {
expectedReleased = Arrays.asList(
TestVersionBumpIn6x.V_5_6_0,
TestVersionBumpIn6x.V_5_6_1,
TestVersionBumpIn6x.V_5_6_2,
TestVersionBumpIn6x.V_6_0_0_alpha1,
TestVersionBumpIn6x.V_6_0_0_alpha2,
TestVersionBumpIn6x.V_6_0_0_beta1,
TestVersionBumpIn6x.V_6_0_0_beta2,
TestVersionBumpIn6x.V_6_0_0,
TestVersionBumpIn6x.V_6_0_1,
TestVersionBumpIn6x.V_6_1_0);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestNewMinorBranchIn6x {
public static final Version V_5_6_0 = Version.fromString("5.6.0");
public static final Version V_5_6_1 = Version.fromString("5.6.1");
public static final Version V_5_6_2 = Version.fromString("5.6.2");
public static final Version V_6_0_0_alpha1 = Version.fromString("6.0.0-alpha1");
public static final Version V_6_0_0_alpha2 = Version.fromString("6.0.0-alpha2");
public static final Version V_6_0_0_beta1 = Version.fromString("6.0.0-beta1");
public static final Version V_6_0_0_beta2 = Version.fromString("6.0.0-beta2");
public static final Version V_6_0_0 = Version.fromString("6.0.0");
public static final Version V_6_0_1 = Version.fromString("6.0.1");
public static final Version V_6_1_0 = Version.fromString("6.1.0");
public static final Version V_6_1_1 = Version.fromString("6.1.1");
public static final Version V_6_1_2 = Version.fromString("6.1.2");
public static final Version V_6_2_0 = Version.fromString("6.2.0");
public static final Version CURRENT = V_6_2_0;
}
public void testResolveReleasedVersionsAtNewMinorBranchIn6x() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestNewMinorBranchIn6x.CURRENT,
TestNewMinorBranchIn6x.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestNewMinorBranchIn6x.V_5_6_0,
TestNewMinorBranchIn6x.V_5_6_1,
TestNewMinorBranchIn6x.V_6_0_0_alpha1,
TestNewMinorBranchIn6x.V_6_0_0_alpha2,
TestNewMinorBranchIn6x.V_6_0_0_beta1,
TestNewMinorBranchIn6x.V_6_0_0_beta2,
TestNewMinorBranchIn6x.V_6_0_0,
TestNewMinorBranchIn6x.V_6_1_0,
TestNewMinorBranchIn6x.V_6_1_1);
expectedUnreleased = Arrays.asList(
TestNewMinorBranchIn6x.V_5_6_2,
TestNewMinorBranchIn6x.V_6_0_1,
TestNewMinorBranchIn6x.V_6_1_2,
TestNewMinorBranchIn6x.V_6_2_0);
} else {
expectedReleased = Arrays.asList(
TestNewMinorBranchIn6x.V_5_6_0,
TestNewMinorBranchIn6x.V_5_6_1,
TestNewMinorBranchIn6x.V_5_6_2,
TestNewMinorBranchIn6x.V_6_0_0_alpha1,
TestNewMinorBranchIn6x.V_6_0_0_alpha2,
TestNewMinorBranchIn6x.V_6_0_0_beta1,
TestNewMinorBranchIn6x.V_6_0_0_beta2,
TestNewMinorBranchIn6x.V_6_0_0,
TestNewMinorBranchIn6x.V_6_0_1,
TestNewMinorBranchIn6x.V_6_1_0,
TestNewMinorBranchIn6x.V_6_1_1,
TestNewMinorBranchIn6x.V_6_1_2,
TestNewMinorBranchIn6x.V_6_2_0);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
/**
* Tests that {@link Version#minimumCompatibilityVersion()} and {@link VersionUtils#allReleasedVersions()}
* agree with the list of wire and index compatible versions we build in gradle.
*/
public void testGradleVersionsMatchVersionUtils() {
// First check the index compatible versions
VersionsFromProperty indexCompatible = new VersionsFromProperty("tests.gradle_index_compat_versions");
List<Version> released = VersionUtils.allReleasedVersions().stream()
/* We skip alphas, betas, and the like in gradle because they don't have
* backwards compatibility guarantees even though they are technically
* released. */
.filter(Version::isRelease)
.collect(toList());
List<String> releasedIndexCompatible = released.stream()
.filter(v -> !Version.CURRENT.equals(v))
.map(Object::toString)
.collect(toList());
assertEquals(releasedIndexCompatible, indexCompatible.released);
List<String> unreleasedIndexCompatible = VersionUtils.allUnreleasedVersions().stream()
/* Gradle skips the current version because being backwards compatible
* with yourself is implied. Java lists the version because it is useful. */
.filter(v -> !Version.CURRENT.equals(v))
.map(Object::toString)
.collect(toList());
assertEquals(unreleasedIndexCompatible, indexCompatible.unreleased);
// Now the wire compatible versions
VersionsFromProperty wireCompatible = new VersionsFromProperty("tests.gradle_wire_compat_versions");
Version minimumCompatibleVersion = Version.CURRENT.minimumCompatibilityVersion();
List<String> releasedWireCompatible = released.stream()
.filter(v -> !Version.CURRENT.equals(v))
.filter(v -> v.onOrAfter(minimumCompatibleVersion))
.map(Object::toString)
.collect(toList());
assertEquals(releasedWireCompatible, wireCompatible.released);
List<String> unreleasedWireCompatible = VersionUtils.allUnreleasedVersions().stream()
/* Gradle skips the current version because being backwards compatible
* with yourself is implied. Java lists the version because it is useful. */
.filter(v -> !Version.CURRENT.equals(v))
.filter(v -> v.onOrAfter(minimumCompatibleVersion))
.map(Object::toString)
.collect(toList());
assertEquals(unreleasedWireCompatible, wireCompatible.unreleased);
}
/**
* Read a versions system property as set by gradle into a tuple of {@code (releasedVersion, unreleasedVersion)}.
*/
private class VersionsFromProperty {
private final List<String> released = new ArrayList<>();
private final List<String> unreleased = new ArrayList<>();
private VersionsFromProperty(String property) {
String versions = System.getProperty(property);
assertNotNull("Couldn't find [" + property + "]. Gradle should set these before running the tests.", versions);
logger.info("Looked up versions [{}={}]", property, versions);
for (String version : versions.split(",")) {
if (version.endsWith("-SNAPSHOT")) {
unreleased.add(version.replace("-SNAPSHOT", ""));
} else {
released.add(version);
}
}
}
}
}
| test/framework/src/test/java/org/elasticsearch/test/VersionUtilsTests.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.test;
import org.elasticsearch.Version;
import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.collect.Tuple;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
public class VersionUtilsTests extends ESTestCase {
public void testAllVersionsSorted() {
List<Version> allVersions = VersionUtils.allReleasedVersions();
for (int i = 0, j = 1; j < allVersions.size(); ++i, ++j) {
assertTrue(allVersions.get(i).before(allVersions.get(j)));
}
}
public void testRandomVersionBetween() {
// full range
Version got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), Version.CURRENT);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
got = VersionUtils.randomVersionBetween(random(), null, Version.CURRENT);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), null);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
// sub range
got = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0,
Version.V_6_0_0_beta1);
assertTrue(got.onOrAfter(Version.V_5_0_0));
assertTrue(got.onOrBefore(Version.V_6_0_0_beta1));
// unbounded lower
got = VersionUtils.randomVersionBetween(random(), null, Version.V_6_0_0_beta1);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.V_6_0_0_beta1));
got = VersionUtils.randomVersionBetween(random(), null, VersionUtils.allReleasedVersions().get(0));
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(VersionUtils.allReleasedVersions().get(0)));
// unbounded upper
got = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0, null);
assertTrue(got.onOrAfter(Version.V_5_0_0));
assertTrue(got.onOrBefore(Version.CURRENT));
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getPreviousVersion(), null);
assertTrue(got.onOrAfter(VersionUtils.getPreviousVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
// range of one
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), VersionUtils.getFirstVersion());
assertEquals(got, VersionUtils.getFirstVersion());
got = VersionUtils.randomVersionBetween(random(), Version.CURRENT, Version.CURRENT);
assertEquals(got, Version.CURRENT);
got = VersionUtils.randomVersionBetween(random(), Version.V_6_0_0_beta1,
Version.V_6_0_0_beta1);
assertEquals(got, Version.V_6_0_0_beta1);
// implicit range of one
got = VersionUtils.randomVersionBetween(random(), null, VersionUtils.getFirstVersion());
assertEquals(got, VersionUtils.getFirstVersion());
got = VersionUtils.randomVersionBetween(random(), Version.CURRENT, null);
assertEquals(got, Version.CURRENT);
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
// max or min can be an unreleased version
final Version unreleased = randomFrom(VersionUtils.allUnreleasedVersions());
assertThat(VersionUtils.randomVersionBetween(random(), null, unreleased), lessThanOrEqualTo(unreleased));
assertThat(VersionUtils.randomVersionBetween(random(), unreleased, null), greaterThanOrEqualTo(unreleased));
assertEquals(unreleased, VersionUtils.randomVersionBetween(random(), unreleased, unreleased));
}
}
public static class TestReleaseBranch {
public static final Version V_5_3_0 = Version.fromString("5.3.0");
public static final Version V_5_3_1 = Version.fromString("5.3.1");
public static final Version V_5_3_2 = Version.fromString("5.3.2");
public static final Version V_5_4_0 = Version.fromString("5.4.0");
public static final Version V_5_4_1 = Version.fromString("5.4.1");
public static final Version CURRENT = V_5_4_1;
}
public void testResolveReleasedVersionsForReleaseBranch() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestReleaseBranch.CURRENT, TestReleaseBranch.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestReleaseBranch.V_5_3_0,
TestReleaseBranch.V_5_3_1,
TestReleaseBranch.V_5_3_2,
TestReleaseBranch.V_5_4_0);
expectedUnreleased = Collections.singletonList(TestReleaseBranch.V_5_4_1);
} else {
expectedReleased = Arrays.asList(
TestReleaseBranch.V_5_3_0,
TestReleaseBranch.V_5_3_1,
TestReleaseBranch.V_5_3_2,
TestReleaseBranch.V_5_4_0,
TestReleaseBranch.V_5_4_1);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestStableBranch {
public static final Version V_5_3_0 = Version.fromString("5.3.0");
public static final Version V_5_3_1 = Version.fromString("5.3.1");
public static final Version V_5_3_2 = Version.fromString("5.3.2");
public static final Version V_5_4_0 = Version.fromString("5.4.0");
public static final Version CURRENT = V_5_4_0;
}
public void testResolveReleasedVersionsForUnreleasedStableBranch() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestStableBranch.CURRENT,
TestStableBranch.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(TestStableBranch.V_5_3_0, TestStableBranch.V_5_3_1);
expectedUnreleased = Arrays.asList(TestStableBranch.V_5_3_2, TestStableBranch.V_5_4_0);
} else {
expectedReleased =
Arrays.asList(TestStableBranch.V_5_3_0, TestStableBranch.V_5_3_1, TestStableBranch.V_5_3_2, TestStableBranch.V_5_4_0);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestStableBranchBehindStableBranch {
public static final Version V_5_3_0 = Version.fromString("5.3.0");
public static final Version V_5_3_1 = Version.fromString("5.3.1");
public static final Version V_5_3_2 = Version.fromString("5.3.2");
public static final Version V_5_4_0 = Version.fromString("5.4.0");
public static final Version V_5_5_0 = Version.fromString("5.5.0");
public static final Version CURRENT = V_5_5_0;
}
public void testResolveReleasedVersionsForStableBranchBehindStableBranch() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestStableBranchBehindStableBranch.CURRENT,
TestStableBranchBehindStableBranch.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(TestStableBranchBehindStableBranch.V_5_3_0, TestStableBranchBehindStableBranch.V_5_3_1);
expectedUnreleased = Arrays.asList(
TestStableBranchBehindStableBranch.V_5_3_2,
TestStableBranchBehindStableBranch.V_5_4_0,
TestStableBranchBehindStableBranch.V_5_5_0);
} else {
expectedReleased = Arrays.asList(
TestStableBranchBehindStableBranch.V_5_3_0,
TestStableBranchBehindStableBranch.V_5_3_1,
TestStableBranchBehindStableBranch.V_5_3_2,
TestStableBranchBehindStableBranch.V_5_4_0,
TestStableBranchBehindStableBranch.V_5_5_0);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestUnstableBranch {
public static final Version V_5_3_0 = Version.fromString("5.3.0");
public static final Version V_5_3_1 = Version.fromString("5.3.1");
public static final Version V_5_3_2 = Version.fromString("5.3.2");
public static final Version V_5_4_0 = Version.fromString("5.4.0");
public static final Version V_6_0_0_alpha1 = Version.fromString("6.0.0-alpha1");
public static final Version V_6_0_0_alpha2 = Version.fromString("6.0.0-alpha2");
public static final Version V_6_0_0_beta1 = Version.fromString("6.0.0-beta1");
public static final Version CURRENT = V_6_0_0_beta1;
}
public void testResolveReleasedVersionsForUnstableBranch() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestUnstableBranch.CURRENT,
TestUnstableBranch.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestUnstableBranch.V_5_3_0,
TestUnstableBranch.V_5_3_1,
TestUnstableBranch.V_6_0_0_alpha1,
TestUnstableBranch.V_6_0_0_alpha2);
expectedUnreleased = Arrays.asList(TestUnstableBranch.V_5_3_2, TestUnstableBranch.V_5_4_0, TestUnstableBranch.V_6_0_0_beta1);
} else {
expectedReleased = Arrays.asList(
TestUnstableBranch.V_5_3_0,
TestUnstableBranch.V_5_3_1,
TestUnstableBranch.V_5_3_2,
TestUnstableBranch.V_5_4_0,
TestUnstableBranch.V_6_0_0_alpha1,
TestUnstableBranch.V_6_0_0_alpha2,
TestUnstableBranch.V_6_0_0_beta1);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestNewMajorRelease {
public static final Version V_5_6_0 = Version.fromString("5.6.0");
public static final Version V_5_6_1 = Version.fromString("5.6.1");
public static final Version V_5_6_2 = Version.fromString("5.6.2");
public static final Version V_6_0_0_alpha1 = Version.fromString("6.0.0-alpha1");
public static final Version V_6_0_0_alpha2 = Version.fromString("6.0.0-alpha2");
public static final Version V_6_0_0_beta1 = Version.fromString("6.0.0-beta1");
public static final Version V_6_0_0_beta2 = Version.fromString("6.0.0-beta2");
public static final Version V_6_0_0 = Version.fromString("6.0.0");
public static final Version V_6_0_1 = Version.fromString("6.0.1");
public static final Version CURRENT = V_6_0_1;
}
public void testResolveReleasedVersionsAtNewMajorRelease() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestNewMajorRelease.CURRENT,
TestNewMajorRelease.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestNewMajorRelease.V_5_6_0,
TestNewMajorRelease.V_5_6_1,
TestNewMajorRelease.V_6_0_0_alpha1,
TestNewMajorRelease.V_6_0_0_alpha2,
TestNewMajorRelease.V_6_0_0_beta1,
TestNewMajorRelease.V_6_0_0_beta2,
TestNewMajorRelease.V_6_0_0);
expectedUnreleased = Arrays.asList(TestNewMajorRelease.V_5_6_2, TestNewMajorRelease.V_6_0_1);
} else {
expectedReleased = Arrays.asList(
TestNewMajorRelease.V_5_6_0,
TestNewMajorRelease.V_5_6_1,
TestNewMajorRelease.V_5_6_2,
TestNewMajorRelease.V_6_0_0_alpha1,
TestNewMajorRelease.V_6_0_0_alpha2,
TestNewMajorRelease.V_6_0_0_beta1,
TestNewMajorRelease.V_6_0_0_beta2,
TestNewMajorRelease.V_6_0_0,
TestNewMajorRelease.V_6_0_1);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestVersionBumpIn6x {
public static final Version V_5_6_0 = Version.fromString("5.6.0");
public static final Version V_5_6_1 = Version.fromString("5.6.1");
public static final Version V_5_6_2 = Version.fromString("5.6.2");
public static final Version V_6_0_0_alpha1 = Version.fromString("6.0.0-alpha1");
public static final Version V_6_0_0_alpha2 = Version.fromString("6.0.0-alpha2");
public static final Version V_6_0_0_beta1 = Version.fromString("6.0.0-beta1");
public static final Version V_6_0_0_beta2 = Version.fromString("6.0.0-beta2");
public static final Version V_6_0_0 = Version.fromString("6.0.0");
public static final Version V_6_0_1 = Version.fromString("6.0.1");
public static final Version V_6_1_0 = Version.fromString("6.1.0");
public static final Version CURRENT = V_6_1_0;
}
public void testResolveReleasedVersionsAtVersionBumpIn6x() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestVersionBumpIn6x.CURRENT,
TestVersionBumpIn6x.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestVersionBumpIn6x.V_5_6_0,
TestVersionBumpIn6x.V_5_6_1,
TestVersionBumpIn6x.V_6_0_0_alpha1,
TestVersionBumpIn6x.V_6_0_0_alpha2,
TestVersionBumpIn6x.V_6_0_0_beta1,
TestVersionBumpIn6x.V_6_0_0_beta2,
TestVersionBumpIn6x.V_6_0_0);
expectedUnreleased = Arrays.asList(TestVersionBumpIn6x.V_5_6_2, TestVersionBumpIn6x.V_6_0_1, TestVersionBumpIn6x.V_6_1_0);
} else {
expectedReleased = Arrays.asList(
TestVersionBumpIn6x.V_5_6_0,
TestVersionBumpIn6x.V_5_6_1,
TestVersionBumpIn6x.V_5_6_2,
TestVersionBumpIn6x.V_6_0_0_alpha1,
TestVersionBumpIn6x.V_6_0_0_alpha2,
TestVersionBumpIn6x.V_6_0_0_beta1,
TestVersionBumpIn6x.V_6_0_0_beta2,
TestVersionBumpIn6x.V_6_0_0,
TestVersionBumpIn6x.V_6_0_1,
TestVersionBumpIn6x.V_6_1_0);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
public static class TestNewMinorBranchIn6x {
public static final Version V_5_6_0 = Version.fromString("5.6.0");
public static final Version V_5_6_1 = Version.fromString("5.6.1");
public static final Version V_5_6_2 = Version.fromString("5.6.2");
public static final Version V_6_0_0_alpha1 = Version.fromString("6.0.0-alpha1");
public static final Version V_6_0_0_alpha2 = Version.fromString("6.0.0-alpha2");
public static final Version V_6_0_0_beta1 = Version.fromString("6.0.0-beta1");
public static final Version V_6_0_0_beta2 = Version.fromString("6.0.0-beta2");
public static final Version V_6_0_0 = Version.fromString("6.0.0");
public static final Version V_6_0_1 = Version.fromString("6.0.1");
public static final Version V_6_1_0 = Version.fromString("6.1.0");
public static final Version V_6_1_1 = Version.fromString("6.1.1");
public static final Version V_6_1_2 = Version.fromString("6.1.2");
public static final Version V_6_2_0 = Version.fromString("6.2.0");
public static final Version CURRENT = V_6_2_0;
}
public void testResolveReleasedVersionsAtNewMinorBranchIn6x() {
Tuple<List<Version>, List<Version>> t = VersionUtils.resolveReleasedVersions(TestNewMinorBranchIn6x.CURRENT,
TestNewMinorBranchIn6x.class);
List<Version> released = t.v1();
List<Version> unreleased = t.v2();
final List<Version> expectedReleased;
final List<Version> expectedUnreleased;
if (Booleans.parseBoolean(System.getProperty("build.snapshot", "true"))) {
expectedReleased = Arrays.asList(
TestNewMinorBranchIn6x.V_5_6_0,
TestNewMinorBranchIn6x.V_5_6_1,
TestNewMinorBranchIn6x.V_6_0_0_alpha1,
TestNewMinorBranchIn6x.V_6_0_0_alpha2,
TestNewMinorBranchIn6x.V_6_0_0_beta1,
TestNewMinorBranchIn6x.V_6_0_0_beta2,
TestNewMinorBranchIn6x.V_6_0_0,
TestNewMinorBranchIn6x.V_6_1_0,
TestNewMinorBranchIn6x.V_6_1_1);
expectedUnreleased = Arrays.asList(
TestNewMinorBranchIn6x.V_5_6_2,
TestNewMinorBranchIn6x.V_6_0_1,
TestNewMinorBranchIn6x.V_6_1_2,
TestNewMinorBranchIn6x.V_6_2_0);
} else {
expectedReleased = Arrays.asList(
TestNewMinorBranchIn6x.V_5_6_0,
TestNewMinorBranchIn6x.V_5_6_1,
TestNewMinorBranchIn6x.V_5_6_2,
TestNewMinorBranchIn6x.V_6_0_0_alpha1,
TestNewMinorBranchIn6x.V_6_0_0_alpha2,
TestNewMinorBranchIn6x.V_6_0_0_beta1,
TestNewMinorBranchIn6x.V_6_0_0_beta2,
TestNewMinorBranchIn6x.V_6_0_0,
TestNewMinorBranchIn6x.V_6_0_1,
TestNewMinorBranchIn6x.V_6_1_0,
TestNewMinorBranchIn6x.V_6_1_1,
TestNewMinorBranchIn6x.V_6_1_2,
TestNewMinorBranchIn6x.V_6_2_0);
expectedUnreleased = Collections.emptyList();
}
assertThat(released, equalTo(expectedReleased));
assertThat(unreleased, equalTo(expectedUnreleased));
}
/**
* Tests that {@link Version#minimumCompatibilityVersion()} and {@link VersionUtils#allReleasedVersions()}
* agree with the list of wire and index compatible versions we build in gradle.
*/
public void testGradleVersionsMatchVersionUtils() {
// First check the index compatible versions
VersionsFromProperty indexCompatible = new VersionsFromProperty("tests.gradle_index_compat_versions");
List<Version> released = VersionUtils.allReleasedVersions().stream()
/* We skip alphas, betas, and the like in gradle because they don't have
* backwards compatibility guarantees even though they are technically
* released. */
.filter(Version::isRelease)
.collect(toList());
List<String> releasedIndexCompatible = released.stream()
.map(Object::toString)
.collect(toList());
assertEquals(releasedIndexCompatible, indexCompatible.released);
List<String> unreleasedIndexCompatible = VersionUtils.allUnreleasedVersions().stream()
/* Gradle skips the current version because being backwards compatible
* with yourself is implied. Java lists the version because it is useful. */
.filter(v -> v != Version.CURRENT)
.map(Object::toString)
.collect(toList());
assertEquals(unreleasedIndexCompatible, indexCompatible.unreleased);
// Now the wire compatible versions
VersionsFromProperty wireCompatible = new VersionsFromProperty("tests.gradle_wire_compat_versions");
Version minimumCompatibleVersion = Version.CURRENT.minimumCompatibilityVersion();
List<String> releasedWireCompatible = released.stream()
.filter(v -> v.onOrAfter(minimumCompatibleVersion))
.map(Object::toString)
.collect(toList());
assertEquals(releasedWireCompatible, wireCompatible.released);
List<String> unreleasedWireCompatible = VersionUtils.allUnreleasedVersions().stream()
/* Gradle skips the current version because being backwards compatible
* with yourself is implied. Java lists the version because it is useful. */
.filter(v -> v != Version.CURRENT)
.filter(v -> v.onOrAfter(minimumCompatibleVersion))
.map(Object::toString)
.collect(toList());
assertEquals(unreleasedWireCompatible, wireCompatible.unreleased);
}
/**
* Read a versions system property as set by gradle into a tuple of {@code (releasedVersion, unreleasedVersion)}.
*/
private class VersionsFromProperty {
private final List<String> released = new ArrayList<>();
private final List<String> unreleased = new ArrayList<>();
private VersionsFromProperty(String property) {
String versions = System.getProperty(property);
assertNotNull("Couldn't find [" + property + "]. Gradle should set these before running the tests.", versions);
logger.info("Looked up versions [{}={}]", property, versions);
for (String version : versions.split(",")) {
if (version.endsWith("-SNAPSHOT")) {
unreleased.add(version.replace("-SNAPSHOT", ""));
} else {
released.add(version);
}
}
}
}
}
| Filter current version from compatible versions
We need to filter the current version from the list of compatible
versions to match how we calculate the list of compatible versions in
Gradle.
| test/framework/src/test/java/org/elasticsearch/test/VersionUtilsTests.java | Filter current version from compatible versions | <ide><path>est/framework/src/test/java/org/elasticsearch/test/VersionUtilsTests.java
<ide> .filter(Version::isRelease)
<ide> .collect(toList());
<ide> List<String> releasedIndexCompatible = released.stream()
<add> .filter(v -> !Version.CURRENT.equals(v))
<ide> .map(Object::toString)
<ide> .collect(toList());
<ide> assertEquals(releasedIndexCompatible, indexCompatible.released);
<ide> List<String> unreleasedIndexCompatible = VersionUtils.allUnreleasedVersions().stream()
<ide> /* Gradle skips the current version because being backwards compatible
<ide> * with yourself is implied. Java lists the version because it is useful. */
<del> .filter(v -> v != Version.CURRENT)
<add> .filter(v -> !Version.CURRENT.equals(v))
<ide> .map(Object::toString)
<ide> .collect(toList());
<ide> assertEquals(unreleasedIndexCompatible, indexCompatible.unreleased);
<ide> VersionsFromProperty wireCompatible = new VersionsFromProperty("tests.gradle_wire_compat_versions");
<ide> Version minimumCompatibleVersion = Version.CURRENT.minimumCompatibilityVersion();
<ide> List<String> releasedWireCompatible = released.stream()
<add> .filter(v -> !Version.CURRENT.equals(v))
<ide> .filter(v -> v.onOrAfter(minimumCompatibleVersion))
<ide> .map(Object::toString)
<ide> .collect(toList());
<ide> List<String> unreleasedWireCompatible = VersionUtils.allUnreleasedVersions().stream()
<ide> /* Gradle skips the current version because being backwards compatible
<ide> * with yourself is implied. Java lists the version because it is useful. */
<del> .filter(v -> v != Version.CURRENT)
<add> .filter(v -> !Version.CURRENT.equals(v))
<ide> .filter(v -> v.onOrAfter(minimumCompatibleVersion))
<ide> .map(Object::toString)
<ide> .collect(toList()); |
|
Java | lgpl-2.1 | d681511077d56443175d3d9d6e2686403999b4c3 | 0 | hal/core,hal/core,hal/core,hal/core,hal/core | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.mbui.gui.reification.strategy;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.mbui.model.structure.Container;
import org.jboss.mbui.model.structure.InteractionUnit;
import org.jboss.mbui.gui.reification.Context;
import org.jboss.as.console.client.widgets.tabs.DefaultTabLayoutPanel;
import static org.jboss.mbui.model.structure.TemporalOperator.Choice;
/**
* Strategy for a container with temporal operator == Choice.
*
* @author Harald Pehl
* @author Heiko Braun
* @date 11/01/2012
*/
public class ChoiceStrategy implements ReificationStrategy<ReificationWidget>
{
@Override
public ReificationWidget reify(final InteractionUnit interactionUnit, final Context context)
{
TabPanelAdapter adapter = null;
if (interactionUnit != null)
{
adapter = new TabPanelAdapter(interactionUnit);
}
return adapter;
}
@Override
public boolean appliesTo(final InteractionUnit interactionUnit)
{
return (interactionUnit instanceof Container) && (((Container) interactionUnit)
.getTemporalOperator() == Choice);
}
class TabPanelAdapter implements ReificationWidget
{
final WidgetStrategy delegate;
final InteractionUnit interactionUnit;
TabPanelAdapter(final InteractionUnit interactionUnit)
{
this.interactionUnit = interactionUnit;
if(interactionUnit.hasParent()) // nested tab panel
{
final TabPanel tabPanel = new TabPanel();
tabPanel.setStyleName("default-tabpanel");
tabPanel.addAttachHandler(new AttachEvent.Handler() {
@Override
public void onAttachOrDetach(AttachEvent attachEvent) {
if(tabPanel.getWidgetCount()>0)
tabPanel.selectTab(0);
}
});
this.delegate = new WidgetStrategy() {
@Override
public void add(InteractionUnit unit, Widget widget) {
tabPanel.add(widget, unit.getName());
}
@Override
public Widget as() {
return tabPanel;
}
};
}
else // top level tab panel
{
final DefaultTabLayoutPanel tabLayoutpanel = new DefaultTabLayoutPanel(40, Style.Unit.PX);
tabLayoutpanel.addStyleName("default-tabpanel");
this.delegate = new WidgetStrategy() {
@Override
public void add(InteractionUnit unit, Widget widget) {
final VerticalPanel vpanel = new VerticalPanel();
vpanel.setStyleName("rhs-content-panel");
vpanel.add(widget);
ScrollPanel scroll = new ScrollPanel(vpanel);
tabLayoutpanel.add(scroll, unit.getName());
}
@Override
public Widget as() {
return tabLayoutpanel;
}
};
}
}
@Override
public InteractionUnit getInteractionUnit() {
return interactionUnit;
}
@Override
public void add(final ReificationWidget widget)
{
if (widget != null)
{
//System.out.println("Add "+widget.getInteractionUnit() +" to " + getInteractionUnit());
delegate.add(widget.getInteractionUnit(), widget.asWidget());
}
}
@Override
public Widget asWidget()
{
return delegate.as();
}
}
}
| gui/src/main/java/org/jboss/mbui/gui/reification/strategy/ChoiceStrategy.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.mbui.gui.reification.strategy;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.mbui.model.structure.Container;
import org.jboss.mbui.model.structure.InteractionUnit;
import org.jboss.mbui.gui.reification.Context;
import org.jboss.as.console.client.widgets.tabs.DefaultTabLayoutPanel;
import static org.jboss.mbui.model.structure.TemporalOperator.Choice;
/**
* Strategy for a container with temporal operator == Choice.
*
* @author Harald Pehl
* @author Heiko Braun
* @date 11/01/2012
*/
public class ChoiceStrategy implements ReificationStrategy<ReificationWidget>
{
@Override
public ReificationWidget reify(final InteractionUnit interactionUnit, final Context context)
{
TabPanelAdapter adapter = null;
if (interactionUnit != null)
{
adapter = new TabPanelAdapter(interactionUnit);
}
return adapter;
}
@Override
public boolean appliesTo(final InteractionUnit interactionUnit)
{
return (interactionUnit instanceof Container) && (((Container) interactionUnit)
.getTemporalOperator() == Choice);
}
class TabPanelAdapter implements ReificationWidget
{
final WidgetStrategy delegate;
final InteractionUnit interactionUnit;
TabPanelAdapter(final InteractionUnit interactionUnit)
{
this.interactionUnit = interactionUnit;
if(interactionUnit.hasParent()) // nested tab panel
{
final TabPanel tabPanel = new TabPanel();
tabPanel.setStyleName("default-tabpanel");
tabPanel.addAttachHandler(new AttachEvent.Handler() {
@Override
public void onAttachOrDetach(AttachEvent attachEvent) {
if(tabPanel.getWidgetCount()>0)
tabPanel.selectTab(0);
}
});
this.delegate = new WidgetStrategy() {
@Override
public void add(InteractionUnit unit, Widget widget) {
tabPanel.add(widget, unit.getName());
}
@Override
public Widget as() {
return tabPanel;
}
};
}
else // top level tab panel
{
final DefaultTabLayoutPanel tabLayoutpanel = new DefaultTabLayoutPanel(40, Style.Unit.PX);
tabLayoutpanel.addStyleName("default-tabpanel");
this.delegate = new WidgetStrategy() {
@Override
public void add(InteractionUnit unit, Widget widget) {
final VerticalPanel vpanel = new VerticalPanel();
vpanel.setStyleName("rhs-content-panel");
vpanel.add(widget);
tabLayoutpanel.add(vpanel, unit.getName());
}
@Override
public Widget as() {
return tabLayoutpanel;
}
};
}
}
@Override
public InteractionUnit getInteractionUnit() {
return interactionUnit;
}
@Override
public void add(final ReificationWidget widget)
{
if (widget != null)
{
//System.out.println("Add "+widget.getInteractionUnit() +" to " + getInteractionUnit());
delegate.add(widget.getInteractionUnit(), widget.asWidget());
}
}
@Override
public Widget asWidget()
{
return delegate.as();
}
}
}
| Top level Container.CHOICE uses scroll panel for nested elements | gui/src/main/java/org/jboss/mbui/gui/reification/strategy/ChoiceStrategy.java | Top level Container.CHOICE uses scroll panel for nested elements | <ide><path>ui/src/main/java/org/jboss/mbui/gui/reification/strategy/ChoiceStrategy.java
<ide>
<ide> import com.google.gwt.dom.client.Style;
<ide> import com.google.gwt.event.logical.shared.AttachEvent;
<add>import com.google.gwt.user.client.ui.ScrollPanel;
<ide> import com.google.gwt.user.client.ui.TabPanel;
<ide> import com.google.gwt.user.client.ui.VerticalPanel;
<ide> import com.google.gwt.user.client.ui.Widget;
<ide> final VerticalPanel vpanel = new VerticalPanel();
<ide> vpanel.setStyleName("rhs-content-panel");
<ide> vpanel.add(widget);
<del> tabLayoutpanel.add(vpanel, unit.getName());
<add>
<add> ScrollPanel scroll = new ScrollPanel(vpanel);
<add> tabLayoutpanel.add(scroll, unit.getName());
<ide> }
<ide>
<ide> @Override |
|
Java | mit | c8ad0401fce1564f5fe7f49df8091499dfa53818 | 0 | kobasemi/PacketCAM,kobasemi/PacketCAM | package jp.ac.kansai_u.kutc.firefly.packetcam.opengl;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.opengl.GLSurfaceView;
import android.util.Log;
import jp.ac.kansai_u.kutc.firefly.packetcam.readpcap.PacketAnalyser;
import jp.ac.kansai_u.kutc.firefly.packetcam.readpcap.PcapManager;
import jp.ac.kansai_u.kutc.firefly.packetcam.utils.Enum;
import jp.ac.kansai_u.kutc.firefly.packetcam.utils.Switch;
import org.jnetstream.capture.file.pcap.PcapPacket;
import org.jnetstream.protocol.tcpip.Tcp;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Queue;
/**
* OpenGLの描画を行う
* @author akasaka kousaka
*/
public class EffectRenderer implements GLSurfaceView.Renderer
{
private static final String TAG = EffectRenderer.class.getSimpleName();
// オブジェクトを格納するリスト
ArrayList<Draw2D> Draw2DList = new ArrayList<Draw2D>();
int mWidth = 0, mHeight = 0;
private Switch mSwitch = Switch.getInstance();
private DrawCamera mDrawCamera;
PcapPacket packet = null;
int colorFlg = 0;
boolean alphaFlg = false;
/**
* スレッドセーフなキュー,インスタンスはPcapManagerから取得する
* @see jp.ac.kansai_u.kutc.firefly.packetcam.readpcap.ConcurrentPacketsQueue
*/
Queue<PcapPacket> packetsQueue;
/**
* パケット解析インスタンス
* @see jp.ac.kansai_u.kutc.firefly.packetcam.readpcap.PacketAnalyser
*/
PacketAnalyser pa = new PacketAnalyser();
/**
* GLSurfaceViewのRendererが生成された際に呼ばれる
*
* @param gl
* @param config
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
Log.i(TAG, "onSurfaceCreated()");
mDrawCamera = new DrawCamera();
mDrawCamera.generatedTexture(gl);
newGraphic();
// キューの取得
packetsQueue = PcapManager.getInstance().getConcurrentPacketsQueue();
}
/**
* 画面が変更された時に呼び出されるメソッド
* 1:画面が生成された時(onSurfaceCreatedの後)
* 2:画面サイズが変わった時(縦と横で端末が切り替わった時)
*
* @param gl
* @param width
* @param height
*/
public void onSurfaceChanged(GL10 gl, int width, int height)
{
Log.i(TAG, "onSurfaceChanged()");
mWidth = width;
mHeight = height;
// ビューモードの設定
// GL上で扱うスクリーンをどこにどれくらいの大きさで表示するのかを設定する
// 左上が0,0
// 以下のコードで全画面になる
gl.glViewport(0, 0, width, height);
mDrawCamera.setUpCamera();
}
/**
* 描画処理のループ
*
* @param gl
*/
public void onDrawFrame(GL10 gl)
{
// キューの先頭パケットを取得.到着していない場合でもぬるぽを出さない
// パケットは1秒ごとに装填される
packet = packetsQueue.poll();
if(packet != null){
// パケットが到着した場合,描画オブジェクトを追加する
// 解析機にパケットをセットする
pa.setPacket(packet);
// TODO ここでパケット情報を用いてエフェクトを追加していく
// 解析機からヘッダを取り出す場合
// 先にヘッダがあるかを確認してほしい
if(pa.hasTcp()){
Tcp tcp = pa.getTcp();
short dport = tcp.destination();
Log.i(TAG, "dport = " + dport);
short sport = tcp.source();
Log.i(TAG, "sport = " + sport);
// データにマイナス?が混じっている場合があるので,取り除く
dport = minusReducer(dport);
sport = minusReducer(sport);
Log.i(TAG, "noMinusdport = " + dport);
Log.i(TAG, "noMinussport = " + sport);
// 描画位置:TCPヘッダのdport
short[] dportPoint = calcPort(dport);
// 描画サイズ:TCPヘッダのsport
short[] sportPoint = calcPort(sport);
Log.i(TAG, "dportPoint[0] = " + dportPoint[0]);
Log.i(TAG, "dportPoint[1] = " + dportPoint[1]);
Log.i(TAG, "sportPoint[0] = " + sportPoint[0]);
Log.i(TAG, "sportPoint[1] = " + sportPoint[1]);
Enum.COLOR color = null;
if (colorFlg == 0) color = Enum.COLOR.RED;
if (colorFlg == 1) color = Enum.COLOR.GREEN;
if (colorFlg == 2) color = Enum.COLOR.BLUE;
if (colorFlg == 3) color = Enum.COLOR.CYAN;
if (colorFlg == 4) color = Enum.COLOR.MAGENTA;
if (colorFlg == 5) color = Enum.COLOR.YELLOW;
if (colorFlg == 6) color = Enum.COLOR.WHITE;
if (colorFlg == 7) color = Enum.COLOR.BLACK;
Draw2DList.add(new Draw2D(dportPoint[0], dportPoint[1], sportPoint[0], sportPoint[1], color));
colorFlg++;
if (colorFlg == 8) colorFlg = 0;
}
// カラー:ICMPのchecksumとか,あるいはsequenceとか
// Draw2DList.add(new Draw2D(dportPoint[0], dportPoint[1], sportPoint[0], sportPoint[1], Enum.COLOR.BLACK));
// Draw2DList.add(new Draw2D(0, 0, 50, 20, Enum.COLOR.BLACK));
packet = null;
}
if (mSwitch.getDrawstate() == Enum.DRAWSTATE.PREPARATION)
{
return;
}
mDrawCamera.draw(gl);
// カメラプレビュー描画後に,ブレンドを有効化する
gl.glEnable(GL10.GL_BLEND);
// ブレンドモードを指定
// src, dst
gl.glBlendFunc(GL10.GL_ONE_MINUS_DST_COLOR, GL10.GL_ONE_MINUS_SRC_ALPHA);
// GLViewクラスのvisibility変数をいじることで、描画のON・OFFが可能
//SwitchクラスのswitchVisibilityメソッドをcallして描画のON・OFFを行う
if (mSwitch.getVisibility() == Enum.VISIBILITY.VISIBLE)
{
for (int i = 0; i < this.Draw2DList.size(); i++)
{
Draw2DList.get(i).draw(gl);
}
}
// OpenGLで描画したフレームバッファからbitmapを生成する
if (mSwitch.getShutter() == true)
{
Log.d(TAG, "callCreateBitmap");
createOpenGLBitmap(gl);
mSwitch.switchShutter();
}
gl.glDisable(GL10.GL_BLEND);
}
private short minusReducer(short num)
{
if (num >= 0) return num;
char[] oldNumCharArray = String.valueOf(num).toCharArray();
char[] newNumCharArray = new char[oldNumCharArray.length - 1];
for (int i = 1; i < oldNumCharArray.length; i++)
{
newNumCharArray[i - 1] = oldNumCharArray[i];
}
short newNum = Short.valueOf(String.valueOf(newNumCharArray));
return newNum;
}
/**
* ポート番号から,オブジェクト生成用の座標を求める
* @param port
* @return
*/
private short[] calcPort(short port)
{
// ポート番号をchar配列に
char[] portChar = String.valueOf(port).toCharArray();
if ((portChar.length % 2) != 0)
{
// 桁数が奇数の場合の処理
// だいたい真ん中を求める
int aboutCenter = portChar.length / 2;
char[] firstChar = new char[aboutCenter + 1];
int j = 0;
for (int i = 0; i < aboutCenter + 1; i++)
{
firstChar[i] = portChar[i];
j++;
}
char[] secondChar = new char[aboutCenter];
for (int i = 0; i < aboutCenter; i++)
{
secondChar[i] = portChar[j];
j++;
}
// firstの方が桁数が多くなるはず
short first = Short.valueOf(String.valueOf(firstChar));
short second = Short.valueOf(String.valueOf(secondChar));
// PORT番号の幅は,0~65535
// firstが3桁以上の場合,ひたすら2で割って2桁に抑える
first = digitReducer(first);
second = digitReducer(second);
short[] data = new short[2];
data[0] = first;
data[1] = second;
return data;
}
else
{
// 桁数が偶数の場合
// 4桁か,2桁
int center = portChar.length / 2;
char[] firstChar = new char[center];
int j = 0;
for (int i = 0; i < center; i++)
{
firstChar[i] = portChar[i];
j++;
}
char[] secondChar = new char[center];
for (int i = 0; i < center; i++)
{
secondChar[i] = portChar[j];
j++;
}
short first = Short.valueOf(String.valueOf(firstChar));
short second = Short.valueOf(String.valueOf(secondChar));
first = digitReducer(first);
second = digitReducer(second);
short[] data = new short[2];
data[0] = first;
data[1] = second;
return data;
}
}
// 3桁以上の値を10で割って2桁に抑える
private short digitReducer(short source)
{
if (String.valueOf(source).length() > 2)
{
source = (short)(source / 10);
digitReducer(source);
}
return source;
}
/**
* 新たな描画オブジェクトを生成する
* Draw2Dに渡す引数は,xy座標及びwidth, height, 色情報
* なお,x, y, width, heightに関しては,
* 描画したい位置や描画図形の大きさをスクリーンのパーセンテージで指定する
* インスタンス化は次の2通りの方法がある
* - int型で0〜100[%]で渡す方法.
* ~ new Draw2D(0, 0, 100, 100, color);
* - float型で0.f〜1.fで渡す方法
* ~ new Draw2D(0.f, 0.f, 1.f, 1.f ,color);
* 2つの例はどちらも,左上から右下までを描画するもの
* 分かりやすい方法を使ったら良い
*
* @see jp.ac.kansai_u.kutc.firefly.packetcam.opengl.Draw2D
*/
public void newGraphic()
{
Log.d(TAG, "newGraphic()");
Draw2D drawBlue = new Draw2D(0.f, 0.f, .25f, .25f, Enum.COLOR.BLUE);
Draw2DList.add(drawBlue);
Draw2D drawGreen = new Draw2D(.25f, .25f, .75f, .75f, Enum.COLOR.GREEN);
Draw2DList.add(drawGreen);
Draw2D drawRed = new Draw2D(.75f, .75f, .25f, .25f, Enum.COLOR.RED);
Draw2DList.add(drawRed);
}
/**
* 指定したオブジェクトを破棄する
*
* @param num 何番目のオブジェクトを破棄するか
*/
public void removeGraphic(int num)
{
Log.d(TAG, "removeGraphic()");
Draw2DList.remove(num);
}
/**
* OpenGLのフレームバッファからBitmapを作る
* http://stackoverflow.com/questions/3310990/taking-screenshot-of-android-opengl
*
* @param gl
*/
private void createOpenGLBitmap(GL10 gl)
{
Log.d(TAG, "createOpenglBitmap()");
// Bitmap作ったあとに、透明化の処理を施す?
if (mWidth == 0 || mHeight == 0)
{
Log.d(TAG, "Error1");
return;
}
int size = mWidth * mHeight;
//region createBitmapFromFrameBuffer
ByteBuffer bb = ByteBuffer.allocateDirect(size * 4);
// OpenGLのフレームバッファからピクセル情報を読み込む
gl.glReadPixels(0, 0, mWidth, mHeight, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, bb);
Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(bb);
//endregion
// 生成されたBitmap画像は上下が反転しているため,修正する
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap correctBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
SaveSDCard.save(correctBitmap);
}
} | PacketCAM/src/jp/ac/kansai_u/kutc/firefly/packetcam/opengl/EffectRenderer.java | package jp.ac.kansai_u.kutc.firefly.packetcam.opengl;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.opengl.GLSurfaceView;
import android.util.Log;
import jp.ac.kansai_u.kutc.firefly.packetcam.readpcap.PacketAnalyser;
import jp.ac.kansai_u.kutc.firefly.packetcam.readpcap.PcapManager;
import jp.ac.kansai_u.kutc.firefly.packetcam.utils.Enum;
import jp.ac.kansai_u.kutc.firefly.packetcam.utils.Switch;
import org.jnetstream.capture.file.pcap.PcapPacket;
import org.jnetstream.protocol.tcpip.Tcp;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Queue;
/**
* OpenGLの描画を行う
* @author akasaka kousaka
*/
public class EffectRenderer implements GLSurfaceView.Renderer
{
private static final String TAG = EffectRenderer.class.getSimpleName();
// オブジェクトを格納するリスト
ArrayList<Draw2D> Draw2DList = new ArrayList<Draw2D>();
int mWidth = 0, mHeight = 0;
private Switch mSwitch = Switch.getInstance();
private DrawCamera mDrawCamera;
PcapPacket packet = null;
/**
* スレッドセーフなキュー,インスタンスはPcapManagerから取得する
* @see jp.ac.kansai_u.kutc.firefly.packetcam.readpcap.ConcurrentPacketsQueue
*/
Queue<PcapPacket> packetsQueue;
/**
* パケット解析インスタンス
* @see jp.ac.kansai_u.kutc.firefly.packetcam.readpcap.PacketAnalyser
*/
PacketAnalyser pa = new PacketAnalyser();
/**
* GLSurfaceViewのRendererが生成された際に呼ばれる
*
* @param gl
* @param config
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
Log.i(TAG, "onSurfaceCreated()");
mDrawCamera = new DrawCamera();
mDrawCamera.generatedTexture(gl);
newGraphic();
// キューの取得
packetsQueue = PcapManager.getInstance().getConcurrentPacketsQueue();
}
/**
* 画面が変更された時に呼び出されるメソッド
* 1:画面が生成された時(onSurfaceCreatedの後)
* 2:画面サイズが変わった時(縦と横で端末が切り替わった時)
*
* @param gl
* @param width
* @param height
*/
public void onSurfaceChanged(GL10 gl, int width, int height)
{
Log.i(TAG, "onSurfaceChanged()");
mWidth = width;
mHeight = height;
// ビューモードの設定
// GL上で扱うスクリーンをどこにどれくらいの大きさで表示するのかを設定する
// 左上が0,0
// 以下のコードで全画面になる
gl.glViewport(0, 0, width, height);
mDrawCamera.setUpCamera();
}
/**
* 描画処理のループ
*
* @param gl
*/
public void onDrawFrame(GL10 gl)
{
Log.i(TAG, "onDrawFrame");
// キューの先頭パケットを取得.到着していない場合でもぬるぽを出さない
packet = packetsQueue.poll();
if(packet != null){
// パケットが到着した場合,描画オブジェクトを追加する
// 解析機にパケットをセットする
pa.setPacket(packet);
// TODO ここでパケット情報を用いてエフェクトを追加していく
// 解析機からヘッダを取り出す場合
// 先にヘッダがあるかを確認してほしい
if(pa.hasTcp()){
Tcp tcp = pa.getTcp();
short dport = tcp.destination();
short sport = tcp.source();
// 描画位置:TCPヘッダのdport
short[] dportPoint = calcPort(dport);
// 描画サイズ:TCPヘッダのsport
short[] sportPoint = calcPort(sport);
}
// カラー:ICMPのchecksumとか,あるいはsequenceとか
// Draw2DList.add(new Draw2D(dportPoint[0], dportPoint[1], sportPoint[0], sportPoint[1], Enum.COLOR.BLACK));
Draw2DList.add(new Draw2D(0, 0, 50, 20, Enum.COLOR.BLACK));
packet = null;
}
if (mSwitch.getDrawstate() == Enum.DRAWSTATE.PREPARATION)
{
return;
}
mDrawCamera.draw(gl);
// カメラプレビュー描画後に,ブレンドを有効化する
gl.glEnable(GL10.GL_BLEND);
// ブレンドモードを指定
gl.glBlendFunc(GL10.GL_ONE_MINUS_DST_COLOR, GL10.GL_ONE_MINUS_SRC_ALPHA);
// GLViewクラスのvisibility変数をいじることで、描画のON・OFFが可能
//SwitchクラスのswitchVisibilityメソッドをcallして描画のON・OFFを行う
if (mSwitch.getVisibility() == Enum.VISIBILITY.VISIBLE)
{
for (int i = 0; i < this.Draw2DList.size(); i++)
{
Draw2DList.get(i).draw(gl);
}
}
// OpenGLで描画したフレームバッファからbitmapを生成する
if (mSwitch.getShutter() == true)
{
Log.d(TAG, "callCreateBitmap");
createOpenGLBitmap(gl);
mSwitch.switchShutter();
}
gl.glDisable(GL10.GL_BLEND);
}
/**
* ポート番号から,オブジェクト生成用の座標を求める
* @param port
* @return
*/
private short[] calcPort(short port)
{
// ポート番号をchar配列に
char[] portChar = String.valueOf(port).toCharArray();
if ((portChar.length % 2) != 0)
{
// 桁数が奇数の場合の処理
// だいたい真ん中を求める
int aboutCenter = portChar.length / 2;
char[] firstChar = new char[aboutCenter + 1];
int j = 0;
for (int i = 0; i < aboutCenter + 1; i++)
{
firstChar[i] = portChar[i];
j++;
}
char[] secondChar = new char[aboutCenter];
j++;
for (int i = 0; i < aboutCenter; i++)
{
secondChar[i] = portChar[j];
j++;
}
// firstの方が桁数が多くなるはず
short first = Short.valueOf(firstChar.toString());
short second = Short.valueOf(secondChar.toString());
// PORT番号の幅は,0~65535
// firstが3桁以上の場合,ひたすら2で割って2桁に抑える
first = digitReducer(first);
second = digitReducer(second);
short[] data = new short[2];
data[0] = first;
data[1] = second;
return data;
}
else
{
// 桁数が偶数の場合
// 4桁か,2桁
int center = portChar.length / 2;
char[] firstChar = new char[center];
int j = 0;
for (int i = 0; i < center; i++)
{
firstChar[i] = portChar[i];
j++;
}
char[] secondChar = new char[center];
j++;
for (int i = 0; i < center; i++)
{
secondChar[i] = portChar[j];
j++;
}
short first = Short.valueOf(firstChar.toString());
short second = Short.valueOf(secondChar.toString());
first = digitReducer(first);
second = digitReducer(second);
short[] data = new short[2];
data[0] = first;
data[1] = second;
return data;
}
}
// 3桁以上の値を10で割って2桁に抑える
private short digitReducer(short source)
{
if (String.valueOf(source).length() > 2)
{
source = (short)(source / 10);
digitReducer(source);
}
return source;
}
/**
* 新たな描画オブジェクトを生成する
* Draw2Dに渡す引数は,xy座標及びwidth, height, 色情報
* なお,x, y, width, heightに関しては,
* 描画したい位置や描画図形の大きさをスクリーンのパーセンテージで指定する
* インスタンス化は次の2通りの方法がある
* - int型で0〜100[%]で渡す方法.
* ~ new Draw2D(0, 0, 100, 100, color);
* - float型で0.f〜1.fで渡す方法
* ~ new Draw2D(0.f, 0.f, 1.f, 1.f ,color);
* 2つの例はどちらも,左上から右下までを描画するもの
* 分かりやすい方法を使ったら良い
*
* @see jp.ac.kansai_u.kutc.firefly.packetcam.opengl.Draw2D
*/
public void newGraphic()
{
Log.d(TAG, "newGraphic()");
Draw2D drawBlue = new Draw2D(0.f, 0.f, .25f, .25f, Enum.COLOR.BLUE);
Draw2DList.add(drawBlue);
Draw2D drawGreen = new Draw2D(.25f, .25f, .75f, .75f, Enum.COLOR.GREEN);
Draw2DList.add(drawGreen);
Draw2D drawRed = new Draw2D(.75f, .75f, .25f, .25f, Enum.COLOR.RED);
Draw2DList.add(drawRed);
}
/**
* 指定したオブジェクトを破棄する
*
* @param num 何番目のオブジェクトを破棄するか
*/
public void removeGraphic(int num)
{
Log.d(TAG, "removeGraphic()");
Draw2DList.remove(num);
}
/**
* OpenGLのフレームバッファからBitmapを作る
* http://stackoverflow.com/questions/3310990/taking-screenshot-of-android-opengl
*
* @param gl
*/
private void createOpenGLBitmap(GL10 gl)
{
Log.d(TAG, "createOpenglBitmap()");
// Bitmap作ったあとに、透明化の処理を施す?
if (mWidth == 0 || mHeight == 0)
{
Log.d(TAG, "Error1");
return;
}
int size = mWidth * mHeight;
//region createBitmapFromFrameBuffer
ByteBuffer bb = ByteBuffer.allocateDirect(size * 4);
// OpenGLのフレームバッファからピクセル情報を読み込む
gl.glReadPixels(0, 0, mWidth, mHeight, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, bb);
Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(bb);
//endregion
// 生成されたBitmap画像は上下が反転しているため,修正する
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap correctBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
SaveSDCard.save(correctBitmap);
}
} | 位置とサイズをパケット情報を利用して表示できるように実装
| PacketCAM/src/jp/ac/kansai_u/kutc/firefly/packetcam/opengl/EffectRenderer.java | 位置とサイズをパケット情報を利用して表示できるように実装 | <ide><path>acketCAM/src/jp/ac/kansai_u/kutc/firefly/packetcam/opengl/EffectRenderer.java
<ide>
<ide> PcapPacket packet = null;
<ide>
<add> int colorFlg = 0;
<add> boolean alphaFlg = false;
<add>
<ide> /**
<ide> * スレッドセーフなキュー,インスタンスはPcapManagerから取得する
<ide> * @see jp.ac.kansai_u.kutc.firefly.packetcam.readpcap.ConcurrentPacketsQueue
<ide> */
<ide> public void onDrawFrame(GL10 gl)
<ide> {
<del> Log.i(TAG, "onDrawFrame");
<del>
<ide> // キューの先頭パケットを取得.到着していない場合でもぬるぽを出さない
<add> // パケットは1秒ごとに装填される
<ide> packet = packetsQueue.poll();
<ide> if(packet != null){
<ide> // パケットが到着した場合,描画オブジェクトを追加する
<ide> Tcp tcp = pa.getTcp();
<ide>
<ide> short dport = tcp.destination();
<add> Log.i(TAG, "dport = " + dport);
<ide> short sport = tcp.source();
<add> Log.i(TAG, "sport = " + sport);
<add>
<add> // データにマイナス?が混じっている場合があるので,取り除く
<add> dport = minusReducer(dport);
<add> sport = minusReducer(sport);
<add>
<add> Log.i(TAG, "noMinusdport = " + dport);
<add> Log.i(TAG, "noMinussport = " + sport);
<ide>
<ide> // 描画位置:TCPヘッダのdport
<ide> short[] dportPoint = calcPort(dport);
<ide>
<ide> // 描画サイズ:TCPヘッダのsport
<ide> short[] sportPoint = calcPort(sport);
<del> }
<add>
<add> Log.i(TAG, "dportPoint[0] = " + dportPoint[0]);
<add> Log.i(TAG, "dportPoint[1] = " + dportPoint[1]);
<add>
<add> Log.i(TAG, "sportPoint[0] = " + sportPoint[0]);
<add> Log.i(TAG, "sportPoint[1] = " + sportPoint[1]);
<add>
<add> Enum.COLOR color = null;
<add> if (colorFlg == 0) color = Enum.COLOR.RED;
<add> if (colorFlg == 1) color = Enum.COLOR.GREEN;
<add> if (colorFlg == 2) color = Enum.COLOR.BLUE;
<add> if (colorFlg == 3) color = Enum.COLOR.CYAN;
<add> if (colorFlg == 4) color = Enum.COLOR.MAGENTA;
<add> if (colorFlg == 5) color = Enum.COLOR.YELLOW;
<add> if (colorFlg == 6) color = Enum.COLOR.WHITE;
<add> if (colorFlg == 7) color = Enum.COLOR.BLACK;
<add>
<add>
<add> Draw2DList.add(new Draw2D(dportPoint[0], dportPoint[1], sportPoint[0], sportPoint[1], color));
<add>
<add> colorFlg++;
<add> if (colorFlg == 8) colorFlg = 0;
<add> }
<ide>
<ide> // カラー:ICMPのchecksumとか,あるいはsequenceとか
<ide>
<del> // Draw2DList.add(new Draw2D(dportPoint[0], dportPoint[1], sportPoint[0], sportPoint[1], Enum.COLOR.BLACK));
<del>
<del> Draw2DList.add(new Draw2D(0, 0, 50, 20, Enum.COLOR.BLACK));
<add>// Draw2DList.add(new Draw2D(dportPoint[0], dportPoint[1], sportPoint[0], sportPoint[1], Enum.COLOR.BLACK));
<add>
<add>// Draw2DList.add(new Draw2D(0, 0, 50, 20, Enum.COLOR.BLACK));
<ide> packet = null;
<ide> }
<ide>
<ide> gl.glEnable(GL10.GL_BLEND);
<ide>
<ide> // ブレンドモードを指定
<add> // src, dst
<ide> gl.glBlendFunc(GL10.GL_ONE_MINUS_DST_COLOR, GL10.GL_ONE_MINUS_SRC_ALPHA);
<ide>
<ide> // GLViewクラスのvisibility変数をいじることで、描画のON・OFFが可能
<ide> }
<ide> gl.glDisable(GL10.GL_BLEND);
<ide> }
<add>
<add>
<add> private short minusReducer(short num)
<add> {
<add> if (num >= 0) return num;
<add>
<add> char[] oldNumCharArray = String.valueOf(num).toCharArray();
<add> char[] newNumCharArray = new char[oldNumCharArray.length - 1];
<add>
<add> for (int i = 1; i < oldNumCharArray.length; i++)
<add> {
<add> newNumCharArray[i - 1] = oldNumCharArray[i];
<add> }
<add>
<add> short newNum = Short.valueOf(String.valueOf(newNumCharArray));
<add> return newNum;
<add> }
<ide>
<ide>
<ide> /**
<ide>
<ide> char[] secondChar = new char[aboutCenter];
<ide>
<del> j++;
<ide> for (int i = 0; i < aboutCenter; i++)
<ide> {
<ide> secondChar[i] = portChar[j];
<ide> }
<ide>
<ide> // firstの方が桁数が多くなるはず
<del> short first = Short.valueOf(firstChar.toString());
<del> short second = Short.valueOf(secondChar.toString());
<add> short first = Short.valueOf(String.valueOf(firstChar));
<add> short second = Short.valueOf(String.valueOf(secondChar));
<ide>
<ide> // PORT番号の幅は,0~65535
<ide> // firstが3桁以上の場合,ひたすら2で割って2桁に抑える
<ide>
<ide> char[] secondChar = new char[center];
<ide>
<del> j++;
<ide> for (int i = 0; i < center; i++)
<ide> {
<ide> secondChar[i] = portChar[j];
<ide> j++;
<ide> }
<ide>
<del> short first = Short.valueOf(firstChar.toString());
<del> short second = Short.valueOf(secondChar.toString());
<add> short first = Short.valueOf(String.valueOf(firstChar));
<add> short second = Short.valueOf(String.valueOf(secondChar));
<ide>
<ide> first = digitReducer(first);
<ide> second = digitReducer(second); |
|
Java | mit | 92ec2f8513ba6ccb2e91e7ff4edc55f5febe2f67 | 0 | AmadouSallah/Programming-Interview-Questions,AmadouSallah/Programming-Interview-Questions | /*
Problem 91. Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
*/
public class NumberOfDecodings {
// O(n) runtime and O(n) space complexities
public static int numDecodings(String s) {
if (s == null || s.length() == 0) return 0;
int n = s.length();
int[] dp = new int[n+1];
dp[0] = 1; // there is only 1 way to decode empty string, which is the empty string: "" -> ""
if (s.charAt(0) != '0') // There is only 1 way to decode a nonempty string of length 1:
dp[1] = 1; // Example s = "3" -> "C", so only 1 way to decode "3"
// i represents the index of dp, and i-1 will be the corresponding index of input s
for (int i = 2; i <= n; i++) {
if (s.charAt(i-1) != '0') {
dp[i] += dp[i-1];
}
int twoDigits = Integer.parseInt(s.substring(i-2, i));
if (twoDigits >= 10 && twoDigits <= 26) {
dp[i] += dp[i-2];
}
}
return dp[n];
}
// O(n) runtime and O(1) space complexities
public static int numDecodings2(String s) {
if (s == null || s.length() == 0) return 0;
int n = s.length();
int p1 = 1, p2 = 0, temp;
if (s.charAt(0) != '0') // There is only 1 way to decode a nonempty string of length 1:
p2 = 1; // Example s = "3" -> "C", so only 1 way to decode "3"
for (int i = 2; i <= n; i++) {
temp = 0;
if (s.charAt(i-1) != '0') {
temp += p2;
}
int twoDigits = Integer.parseInt(s.substring(i-2, i));
if (twoDigits >= 10 && twoDigits <= 26) {
temp += p1;
}
p1 = p2;
p2 = temp;
}
return p2;
}
public static void main(String[] args) {
System.out.println("Using solution1: O(n) runtime and O(n) space complexities");
System.out.println("numDecodings(\"\") = " + numDecodings("")); // -> ""
System.out.println("numDecodings(\"1\") = " + numDecodings("1")); // -> "A"
System.out.println("numDecodings(\"12\") = " + numDecodings("12")); // -> "AB", or "L"
System.out.println("numDecodings(\"123\") = " + numDecodings("123")); // -> "ABC", or "LX", or "LC"
System.out.println("\nUsing solution2: O(n) runtime and O(1) space complexities");
System.out.println("numDecodings2(\"\") = " + numDecodings2("")); // -> ""
System.out.println("numDecodings2(\"1\") = " + numDecodings2("1")); // -> "A"
System.out.println("numDecodings2(\"12\") = " + numDecodings2("12")); // -> "AB", or "L"
System.out.println("numDecodings2(\"123\") = " + numDecodings2("123")); // -> "ABC", or "LX", or "LC"
}
}
| leetcode/java/prob91DecodeWays/NumberOfDecodings.java | /*
Problem 91. Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
*/
public class NumberOfDecodings {
public static int numDecodings(String s) {
if (s == null || s.length() == 0) return 0;
int n = s.length();
int[] dp = new int[n+1];
dp[0] = 1; // there is only 1 way to decode empty string, which is the empty string: "" -> ""
if (s.charAt(0) != '0') // There is only 1 way to decode a nonempty string of length 1:
dp[1] = 1; // Example s = "3" -> "C", so only 1 way to decode "3"
// i represents the index of dp, and i-1 will be the corresponding index of input s
for (int i = 2; i <= n; i++) {
if (s.charAt(i-1) != '0') {
dp[i] += dp[i-1];
}
int twoDigits = Integer.parseInt(s.substring(i-2, i));
if (twoDigits >= 10 && twoDigits <= 26) {
dp[i] += dp[i-2];
}
}
return dp[n];
}
public static void main(String[] args) {
System.out.println("numDecodings(\"\") = " + numDecodings("")); // -> ""
System.out.println("numDecodings(\"1\") = " + numDecodings("1")); // -> "A"
System.out.println("numDecodings(\"12\") = " + numDecodings("12")); // -> "AB", or "L"
System.out.println("numDecodings(\"123\") = " + numDecodings("123")); // -> "ABC", or "LX", or "LC"
}
}
| Added Solution2 for NumberOfDecodings.java: O(n) runtime and O(1) space complexities
| leetcode/java/prob91DecodeWays/NumberOfDecodings.java | Added Solution2 for NumberOfDecodings.java: O(n) runtime and O(1) space complexities | <ide><path>eetcode/java/prob91DecodeWays/NumberOfDecodings.java
<ide> */
<ide>
<ide> public class NumberOfDecodings {
<add>
<add> // O(n) runtime and O(n) space complexities
<ide> public static int numDecodings(String s) {
<ide> if (s == null || s.length() == 0) return 0;
<ide> int n = s.length();
<ide> return dp[n];
<ide> }
<ide>
<add> // O(n) runtime and O(1) space complexities
<add> public static int numDecodings2(String s) {
<add> if (s == null || s.length() == 0) return 0;
<add> int n = s.length();
<add> int p1 = 1, p2 = 0, temp;
<add>
<add> if (s.charAt(0) != '0') // There is only 1 way to decode a nonempty string of length 1:
<add> p2 = 1; // Example s = "3" -> "C", so only 1 way to decode "3"
<add>
<add> for (int i = 2; i <= n; i++) {
<add> temp = 0;
<add> if (s.charAt(i-1) != '0') {
<add> temp += p2;
<add> }
<add>
<add> int twoDigits = Integer.parseInt(s.substring(i-2, i));
<add> if (twoDigits >= 10 && twoDigits <= 26) {
<add> temp += p1;
<add> }
<add>
<add> p1 = p2;
<add> p2 = temp;
<add> }
<add> return p2;
<add> }
<add>
<ide> public static void main(String[] args) {
<add> System.out.println("Using solution1: O(n) runtime and O(n) space complexities");
<ide> System.out.println("numDecodings(\"\") = " + numDecodings("")); // -> ""
<ide> System.out.println("numDecodings(\"1\") = " + numDecodings("1")); // -> "A"
<ide> System.out.println("numDecodings(\"12\") = " + numDecodings("12")); // -> "AB", or "L"
<ide> System.out.println("numDecodings(\"123\") = " + numDecodings("123")); // -> "ABC", or "LX", or "LC"
<add>
<add> System.out.println("\nUsing solution2: O(n) runtime and O(1) space complexities");
<add> System.out.println("numDecodings2(\"\") = " + numDecodings2("")); // -> ""
<add> System.out.println("numDecodings2(\"1\") = " + numDecodings2("1")); // -> "A"
<add> System.out.println("numDecodings2(\"12\") = " + numDecodings2("12")); // -> "AB", or "L"
<add> System.out.println("numDecodings2(\"123\") = " + numDecodings2("123")); // -> "ABC", or "LX", or "LC"
<ide> }
<ide> } |
|
Java | apache-2.0 | 205f8823dac554e685073e9a0ea8769f8f528e70 | 0 | apereo/cas,rkorn86/cas,apereo/cas,rkorn86/cas,Jasig/cas,apereo/cas,apereo/cas,rkorn86/cas,fogbeam/cas_mirror,apereo/cas,fogbeam/cas_mirror,rkorn86/cas,Jasig/cas,apereo/cas,fogbeam/cas_mirror,fogbeam/cas_mirror,fogbeam/cas_mirror,Jasig/cas,apereo/cas,Jasig/cas,fogbeam/cas_mirror | package org.apereo.cas.configuration.model.support.jpa;
import org.apereo.cas.configuration.model.support.ConnectionPoolingProperties;
import org.apereo.cas.configuration.support.DurationCapable;
import org.apereo.cas.configuration.support.ExpressionLanguageCapable;
import org.apereo.cas.configuration.support.RequiredProperty;
import org.apereo.cas.configuration.support.RequiresModule;
import com.fasterxml.jackson.annotation.JsonFilter;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Common properties for all jpa configs.
*
* @author Dmitriy Kopylenko
* @since 5.0.0
*/
@Getter
@Setter
@RequiresModule(name = "cas-server-support-jdbc-drivers")
@Accessors(chain = true)
@JsonFilter("AbstractJpaProperties")
@SuppressWarnings("UnescapedEntity")
public abstract class AbstractJpaProperties implements Serializable {
private static final long serialVersionUID = 761486823496930920L;
/**
* The database dialect is a configuration setting for platform independent software (JPA, Hibernate, etc)
* which allows such software to translate its generic SQL statements into vendor specific DDL, DML.
*/
private String dialect = "org.hibernate.dialect.HSQLDialect";
/**
* Hibernate feature to automatically validate and exports DDL to the schema.
* By default, creates and drops the schema automatically when a session is starts and ends.
* Setting the value to {@code validate} or {@code none} may be more desirable for production,
* but any of the following options can be used:
* <ul>
* <li>{@code validate}: Validate the schema, but make no changes to the database.</li>
* <li>{@code update}: Update the schema.</li>
* <li>{@code create}: Create the schema, destroying previous data.</li>
* <li>{@code create-drop}: Drop the schema at the end of the session.</li>
* <li>{@code none}: Do nothing.</li>
* </ul>
* <p>
* Note that during a version migration where any schema has changed {@code create-drop} will result
* in the loss of all data as soon as CAS is started. For transient data like tickets this is probably
* not an issue, but in cases like the audit table important data could be lost. Using `update`, while safe
* for data, is confirmed to result in invalid database state. {@code validate} or {@code none} settings
* are likely the only safe options for production use.
* </p>
* For more info, <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api">see this</a>.
*/
private String ddlAuto = "update";
/**
* The JDBC driver used to connect to the database.
*/
@RequiredProperty
private String driverClass = "org.hsqldb.jdbcDriver";
/**
* The database connection URL.
*/
@RequiredProperty
@ExpressionLanguageCapable
private String url = "jdbc:hsqldb:mem:cas-hsql-database";
/**
* The database user.
* <p>
* The database user must have sufficient permissions to be able to handle
* schema changes and updates, when needed.
*/
@RequiredProperty
private String user = "sa";
/**
* The database connection password.
*/
@RequiredProperty
private String password = StringUtils.EMPTY;
/**
* Qualifies unqualified table names with the given catalog in generated SQL.
*/
private String defaultCatalog;
/**
* Qualify unqualified table names with the given schema/tablespace in generated SQL.
*/
private String defaultSchema;
/**
* The SQL query to be executed to test the validity of connections.
*/
private String healthQuery = StringUtils.EMPTY;
/**
* Controls the maximum amount of time that a connection is allowed to sit idle in the pool.
*/
@DurationCapable
private String idleTimeout = "PT10M";
/**
* Attempts to do a JNDI data source look up for the data source name specified.
* Will attempt to locate the data source object as is.
*/
private String dataSourceName;
/**
* Additional settings provided by Hibernate in form of key-value pairs.
*/
private Map<String, String> properties = new HashMap<>(0);
/**
* Database connection pooling settings.
*/
@NestedConfigurationProperty
private ConnectionPoolingProperties pool = new ConnectionPoolingProperties();
/**
* Controls the amount of time that a connection can be out of the pool before a message
* is logged indicating a possible connection leak.
*/
private int leakThreshold = 3_000;
/**
* Allow hibernate to generate query statistics.
*/
private boolean generateStatistics;
/**
* A non-zero value enables use of JDBC2 batch updates by Hibernate. e.g. recommended values between 5 and 30.
*/
private int batchSize = 100;
/**
* Used to specify number of rows to be fetched in a select query.
*/
private int fetchSize = 100;
/**
* Set the pool initialization failure timeout.
* <ul>
* <li>Any value greater than zero will be treated as a timeout for pool initialization.
* The calling thread will be blocked from continuing until a successful connection
* to the database, or until the timeout is reached. If the timeout is reached, then
* a {@code PoolInitializationException} will be thrown. </li>
* <li>A value of zero will <i>not</i> prevent the pool from starting in the
* case that a connection cannot be obtained. However, upon start the pool will
* attempt to obtain a connection and validate that the {@code connectionTestQuery}
* and {@code connectionInitSql} are valid. If those validations fail, an exception
* will be thrown. If a connection cannot be obtained, the validation is skipped
* and the the pool will start and continue to try to obtain connections in the
* background. This can mean that callers to {@code DataSource#getConnection()} may
* encounter exceptions. </li>
* <li>A value less than zero will <i>not</i> bypass any connection attempt and
* validation during startup, and therefore the pool will start immediately. The
* pool will continue to try to obtain connections in the background. This can mean
* that callers to {@code DataSource#getConnection()} may encounter exceptions. </li>
* </ul>
* Note that if this timeout value is greater than or equal to zero (0), and therefore an
* initial connection validation is performed, this timeout does not override the
* {@code connectionTimeout} or {@code validationTimeout}; they will be honored before this
* timeout is applied. The default value is one millisecond.
*/
private long failFastTimeout = 1;
/**
* This property determines whether data source isolates internal pool queries, such as the connection alive test,
* in their own transaction.
* <p>
* Since these are typically read-only queries, it is rarely necessary to encapsulate them in their own transaction.
* This property only applies if {@link #autocommit} is disabled.
*/
private boolean isolateInternalQueries;
/**
* The default auto-commit behavior of connections in the pool.
* Determined whether queries such as update/insert should be immediately executed
* without waiting for an underlying transaction.
*/
private boolean autocommit;
/**
* Fully-qualified name of the class that can control the physical naming strategy of hibernate.
*/
private String physicalNamingStrategyClassName = "org.apereo.cas.hibernate.CasHibernatePhysicalNamingStrategy";
/**
* Defines the isolation level for transactions.
*
* @see org.springframework.transaction.TransactionDefinition
*/
private String isolationLevelName = "ISOLATION_READ_COMMITTED";
/**
* Defines the propagation behavior for transactions.
*
* @see org.springframework.transaction.TransactionDefinition
*/
private String propagationBehaviorName = "PROPAGATION_REQUIRED";
}
| api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/jpa/AbstractJpaProperties.java | package org.apereo.cas.configuration.model.support.jpa;
import org.apereo.cas.configuration.model.support.ConnectionPoolingProperties;
import org.apereo.cas.configuration.support.DurationCapable;
import org.apereo.cas.configuration.support.ExpressionLanguageCapable;
import org.apereo.cas.configuration.support.RequiredProperty;
import org.apereo.cas.configuration.support.RequiresModule;
import com.fasterxml.jackson.annotation.JsonFilter;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Common properties for all jpa configs.
*
* @author Dmitriy Kopylenko
* @since 5.0.0
*/
@Getter
@Setter
@RequiresModule(name = "cas-server-support-jdbc-drivers")
@Accessors(chain = true)
@JsonFilter("AbstractJpaProperties")
@SuppressWarnings("UnescapedEntity")
public abstract class AbstractJpaProperties implements Serializable {
private static final long serialVersionUID = 761486823496930920L;
/**
* The database dialect is a configuration setting for platform independent software (JPA, Hibernate, etc)
* which allows such software to translate its generic SQL statements into vendor specific DDL, DML.
*/
private String dialect = "org.hibernate.dialect.HSQLDialect";
/**
* Hibernate feature to automatically validate and exports DDL to the schema.
* By default, creates and drops the schema automatically when a session is starts and ends.
* Setting the value to {@code validate} or {@code none} may be more desirable for production,
* but any of the following options can be used:
* <ul>
* <li>{@code validate}: Validate the schema, but make no changes to the database.</li>
* <li>{@code update}: Update the schema.</li>
* <li>{@code create}: Create the schema, destroying previous data.</li>
* <li>{@code create-drop}: Drop the schema at the end of the session.</li>
* <li>{@code none}: Do nothing.</li>
* </ul>
* <p>
* Note that during a version migration where any schema has changed {@code create-drop} will result
* in the loss of all data as soon as CAS is started. For transient data like tickets this is probably
* not an issue, but in cases like the audit table important data could be lost. Using `update`, while safe
* for data, is confirmed to result in invalid database state. {@code validate} or {@code none} settings
* are likely the only safe options for production use.
* </p>
* For more info, <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api">see this</a>.
*/
private String ddlAuto = "update";
/**
* The JDBC driver used to connect to the database.
*/
@RequiredProperty
private String driverClass = "org.hsqldb.jdbcDriver";
/**
* The database connection URL.
*/
@RequiredProperty
@ExpressionLanguageCapable
private String url = "jdbc:hsqldb:mem:cas-hsql-database";
/**
* The database user.
* <p>
* The database user must have sufficient permissions to be able to handle
* schema changes and updates, when needed.
*/
@RequiredProperty
private String user = "sa";
/**
* The database connection password.
*/
@RequiredProperty
private String password = StringUtils.EMPTY;
/**
* Qualifies unqualified table names with the given catalog in generated SQL.
*/
private String defaultCatalog;
/**
* Qualify unqualified table names with the given schema/tablespace in generated SQL.
*/
private String defaultSchema;
/**
* The SQL query to be executed to test the validity of connections.
*/
private String healthQuery = StringUtils.EMPTY;
/**
* Controls the maximum amount of time that a connection is allowed to sit idle in the pool.
*/
@DurationCapable
private String idleTimeout = "PT10M";
/**
* Attempts to do a JNDI data source look up for the data source name specified.
* Will attempt to locate the data source object as is, or will try to return a proxy
* instance of it, in the event that {@link #dataSourceProxy} is used.
*/
private String dataSourceName;
/**
* Additional settings provided by Hibernate in form of key-value pairs.
*/
private Map<String, String> properties = new HashMap<>(0);
/**
* Database connection pooling settings.
*/
@NestedConfigurationProperty
private ConnectionPoolingProperties pool = new ConnectionPoolingProperties();
/**
* Controls the amount of time that a connection can be out of the pool before a message
* is logged indicating a possible connection leak.
*/
private int leakThreshold = 3_000;
/**
* Allow hibernate to generate query statistics.
*/
private boolean generateStatistics;
/**
* A non-zero value enables use of JDBC2 batch updates by Hibernate. e.g. recommended values between 5 and 30.
*/
private int batchSize = 100;
/**
* Used to specify number of rows to be fetched in a select query.
*/
private int fetchSize = 100;
/**
* Set the pool initialization failure timeout.
* <ul>
* <li>Any value greater than zero will be treated as a timeout for pool initialization.
* The calling thread will be blocked from continuing until a successful connection
* to the database, or until the timeout is reached. If the timeout is reached, then
* a {@code PoolInitializationException} will be thrown. </li>
* <li>A value of zero will <i>not</i> prevent the pool from starting in the
* case that a connection cannot be obtained. However, upon start the pool will
* attempt to obtain a connection and validate that the {@code connectionTestQuery}
* and {@code connectionInitSql} are valid. If those validations fail, an exception
* will be thrown. If a connection cannot be obtained, the validation is skipped
* and the the pool will start and continue to try to obtain connections in the
* background. This can mean that callers to {@code DataSource#getConnection()} may
* encounter exceptions. </li>
* <li>A value less than zero will <i>not</i> bypass any connection attempt and
* validation during startup, and therefore the pool will start immediately. The
* pool will continue to try to obtain connections in the background. This can mean
* that callers to {@code DataSource#getConnection()} may encounter exceptions. </li>
* </ul>
* Note that if this timeout value is greater than or equal to zero (0), and therefore an
* initial connection validation is performed, this timeout does not override the
* {@code connectionTimeout} or {@code validationTimeout}; they will be honored before this
* timeout is applied. The default value is one millisecond.
*/
private long failFastTimeout = 1;
/**
* This property determines whether data source isolates internal pool queries, such as the connection alive test,
* in their own transaction.
* <p>
* Since these are typically read-only queries, it is rarely necessary to encapsulate them in their own transaction.
* This property only applies if {@link #autocommit} is disabled.
*/
private boolean isolateInternalQueries;
/**
* The default auto-commit behavior of connections in the pool.
* Determined whether queries such as update/insert should be immediately executed
* without waiting for an underlying transaction.
*/
private boolean autocommit;
/**
* Fully-qualified name of the class that can control the physical naming strategy of hibernate.
*/
private String physicalNamingStrategyClassName = "org.apereo.cas.hibernate.CasHibernatePhysicalNamingStrategy";
/**
* Defines the isolation level for transactions.
*
* @see org.springframework.transaction.TransactionDefinition
*/
private String isolationLevelName = "ISOLATION_READ_COMMITTED";
/**
* Defines the propagation behavior for transactions.
*
* @see org.springframework.transaction.TransactionDefinition
*/
private String propagationBehaviorName = "PROPAGATION_REQUIRED";
}
| fix tests; update rel notes
| api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/jpa/AbstractJpaProperties.java | fix tests; update rel notes | <ide><path>pi/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/jpa/AbstractJpaProperties.java
<ide>
<ide> /**
<ide> * Attempts to do a JNDI data source look up for the data source name specified.
<del> * Will attempt to locate the data source object as is, or will try to return a proxy
<del> * instance of it, in the event that {@link #dataSourceProxy} is used.
<add> * Will attempt to locate the data source object as is.
<ide> */
<ide> private String dataSourceName;
<ide> |
|
Java | lgpl-2.1 | 25ee92544ce08d635794be7aa19301ad7dd6807c | 0 | exedio/copernica,exedio/copernica,exedio/copernica | /*
* Copyright (C) 2004-2005 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.exedio.cope.search.Condition;
import com.exedio.cope.util.Day;
import com.exedio.dsmf.Driver;
import com.exedio.dsmf.SQLRuntimeException;
import com.exedio.dsmf.Schema;
abstract class Database
{
private final List tables = new ArrayList();
private final HashMap uniqueConstraintsByID = new HashMap();
private final HashMap itemColumnsByIntegrityConstraintName = new HashMap();
private boolean buildStage = true;
final Driver driver;
private final boolean useDefineColumnTypes;
private final boolean log;
private final boolean butterflyPkSource;
final ConnectionPool connectionPool;
private final java.util.Properties forcedNames;
private List expectedCalls = null;
protected Database(final Driver driver, final Properties properties)
{
this.driver = driver;
this.useDefineColumnTypes = this instanceof DatabaseColumnTypesDefinable;
this.log = properties.getDatabaseLog();
this.butterflyPkSource = properties.getPkSourceButterfly();
this.connectionPool = new ConnectionPool(properties);
this.forcedNames = properties.getDatabaseForcedNames();
//System.out.println("using database "+getClass());
}
final void addTable(final Table table)
{
if(!buildStage)
throw new RuntimeException();
tables.add(table);
}
final void addUniqueConstraint(final String constraintID, final UniqueConstraint constraint)
{
if(!buildStage)
throw new RuntimeException();
final Object collision = uniqueConstraintsByID.put(constraintID, constraint);
if(collision!=null)
throw new RuntimeException("ambiguous unique constraint "+constraint+" trimmed to >"+constraintID+"< colliding with "+collision);
}
final void addIntegrityConstraint(final ItemColumn column)
{
if(!buildStage)
throw new RuntimeException();
if(itemColumnsByIntegrityConstraintName.put(column.integrityConstraintName, column)!=null)
throw new RuntimeException("there is more than one integrity constraint with name "+column.integrityConstraintName);
}
protected final Statement createStatement()
{
return new Statement(useDefineColumnTypes);
}
void createDatabase()
{
buildStage = false;
makeSchema().create();
}
//private static int checkTableTime = 0;
void checkDatabase(final Connection connection)
{
buildStage = false;
//final long time = System.currentTimeMillis();
final Statement bf = createStatement();
bf.append("select count(*) from ").defineColumnInteger();
boolean first = true;
for(Iterator i = tables.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Table table = (Table)i.next();
bf.append(table.protectedID);
}
final Long testDate = new Long(System.currentTimeMillis());
final Integer testDay = new Integer(DayColumn.getTransientNumber(new Day(2005, 9, 26)));
bf.append(" where ");
first = true;
for(Iterator i = tables.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(" and ");
final Table table = (Table)i.next();
final Column primaryKey = table.getPrimaryKey();
bf.append(table.protectedID).
append('.').
append(primaryKey.protectedID).
append('=').
append(Type.NOT_A_PK);
for(Iterator j = table.getColumns().iterator(); j.hasNext(); )
{
final Column column = (Column)j.next();
bf.append(" and ").
append(table.protectedID).
append('.').
append(column.protectedID).
append('=');
if(column instanceof IntegerColumn)
bf.appendValue(column, ((IntegerColumn)column).longInsteadOfInt ? (Number)new Long(1) : new Integer(1));
else if(column instanceof DoubleColumn)
bf.appendValue(column, new Double(2.2));
else if(column instanceof StringColumn)
bf.appendValue(column, "z");
else if(column instanceof TimestampColumn)
bf.appendValue(column, testDate);
else if(column instanceof DayColumn)
bf.appendValue(column, testDay);
else
throw new RuntimeException(column.toString());
}
}
executeSQLQuery(connection, bf,
new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
}
},
false
);
}
void dropDatabase()
{
buildStage = false;
makeSchema().drop();
}
void tearDownDatabase()
{
buildStage = false;
makeSchema().tearDown();
}
void checkEmptyDatabase(final Connection connection)
{
buildStage = false;
//final long time = System.currentTimeMillis();
for(Iterator i = tables.iterator(); i.hasNext(); )
{
final Table table = (Table)i.next();
final int count = countTable(connection, table);
if(count>0)
throw new RuntimeException("there are "+count+" items left for table "+table.id);
}
//final long amount = (System.currentTimeMillis()-time);
//checkEmptyTableTime += amount;
//System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime);
}
private final boolean appendLimitClauseInSearch(final Statement bf, final int start, final int count)
{
if(start>0 || count!=Query.UNLIMITED_COUNT)
return appendLimitClause(bf, start, count);
else
return false;
}
final ArrayList search(final Connection connection, final Query query, final boolean doCountOnly)
{
if ( expectedCalls!=null )
{
nextExpectedCall().checkSearch( connection, query );
}
buildStage = false;
final int limitStart = query.limitStart;
final int limitCount = query.limitCount;
final boolean limitClauseInSelect = doCountOnly ? false : isLimitClauseInSelect();
boolean limitByDatabaseTemp = false;
final Statement bf = createStatement();
bf.setJoinsToAliases(query);
bf.append("select");
if(!doCountOnly && limitClauseInSelect)
limitByDatabaseTemp = appendLimitClauseInSearch(bf, limitStart, limitCount);
bf.append(' ');
final Selectable[] selectables = query.selectables;
final Column[] selectColumns = new Column[selectables.length];
final Type[] selectTypes = new Type[selectables.length];
if(doCountOnly)
{
bf.append("count(*)");
}
else
{
for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++)
{
final Selectable selectable = selectables[selectableIndex];
final Column selectColumn;
final Type selectType;
final Table selectTable;
final Column selectPrimaryKey;
if(selectable instanceof Function)
{
final Function selectAttribute = (Function)selectable;
selectType = selectAttribute.getType();
if(selectableIndex>0)
bf.append(',');
if(selectable instanceof ObjectAttribute)
{
selectColumn = ((ObjectAttribute)selectAttribute).getColumn();
selectTable = selectColumn.table;
selectPrimaryKey = selectTable.getPrimaryKey();
bf.append(selectColumn.table.protectedID).
append('.').
append(selectColumn.protectedID).defineColumn(selectColumn);
}
else
{
selectColumn = null;
final ComputedFunction computedFunction = (ComputedFunction)selectable;
bf.append(computedFunction, (Join)null).defineColumn(computedFunction);
}
}
else
{
selectType = (Type)selectable;
selectTable = selectType.getTable();
selectPrimaryKey = selectTable.getPrimaryKey();
selectColumn = selectPrimaryKey;
if(selectableIndex>0)
bf.append(',');
bf.append(selectColumn.table.protectedID).
append('.').
append(selectColumn.protectedID).defineColumn(selectColumn);
if(selectColumn.primaryKey)
{
final StringColumn selectTypeColumn = selectColumn.getTypeColumn();
if(selectTypeColumn!=null)
{
bf.append(',').
append(selectTable.protectedID).
append('.').
append(selectTypeColumn.protectedID).defineColumn(selectTypeColumn);
}
else
selectTypes[selectableIndex] = selectType;
}
else
selectTypes[selectableIndex] = selectType;
}
selectColumns[selectableIndex] = selectColumn;
}
}
bf.append(" from ").
append(query.type.getTable().protectedID);
final String fromAlias = bf.getAlias(null);
if(fromAlias!=null)
{
bf.append(' ').
append(fromAlias);
}
final ArrayList queryJoins = query.joins;
if(queryJoins!=null)
{
for(Iterator i = queryJoins.iterator(); i.hasNext(); )
{
final Join join = (Join)i.next();
bf.append(' ').
append(join.getKindString()).
append(" join ").
append(join.type.getTable().protectedID);
final String joinAlias = bf.getAlias(join);
if(joinAlias!=null)
{
bf.append(' ').
append(joinAlias);
}
final Condition joinCondition = join.condition;
if(joinCondition!=null)
{
bf.append(" on ");
joinCondition.appendStatement(bf);
}
}
}
if(query.condition!=null)
{
bf.append(" where ");
query.condition.appendStatement(bf);
}
if(!doCountOnly)
{
boolean firstOrderBy = true;
if(query.orderBy!=null || query.deterministicOrder)
bf.append(" order by ");
if(query.orderBy!=null)
{
firstOrderBy = false;
bf.append(query.orderBy, (Join)null);
if(!query.orderAscending)
bf.append(" desc");
}
if(query.deterministicOrder) // TODO skip this, if orderBy already orders by some unique condition
{
if(!firstOrderBy)
bf.append(',');
query.type.getPkSource().appendDeterministicOrderByExpression(bf, query.type.getTable());
}
if(!limitClauseInSelect)
limitByDatabaseTemp = appendLimitClauseInSearch(bf, limitStart, limitCount);
}
final boolean limitByDatabase = limitByDatabaseTemp; // must be final for usage in ResultSetHandler
final Type[] types = selectTypes;
final Model model = query.model;
final ArrayList result = new ArrayList();
if(limitStart<0)
throw new RuntimeException();
if(selectables.length!=selectColumns.length)
throw new RuntimeException();
if(selectables.length!=types.length)
throw new RuntimeException();
query.addStatementInfo(executeSQLQuery(connection, bf, new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
if(doCountOnly)
{
resultSet.next();
result.add(new Integer(resultSet.getInt(1)));
if(resultSet.next())
throw new RuntimeException();
return;
}
if(!limitByDatabase && limitStart>0)
{
// TODO: ResultSet.relative
// Would like to use
// resultSet.relative(limitStart+1);
// but this throws a java.sql.SQLException:
// Invalid operation for forward only resultset : relative
for(int i = limitStart; i>0; i--)
resultSet.next();
}
int i = ((limitCount==Query.UNLIMITED_COUNT||limitByDatabase) ? Integer.MAX_VALUE : limitCount );
if(i<=0)
throw new RuntimeException(String.valueOf(limitCount));
while(resultSet.next() && (--i)>=0)
{
int columnIndex = 1;
final Object[] resultRow = (selectables.length > 1) ? new Object[selectables.length] : null;
for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++)
{
final Selectable selectable = selectables[selectableIndex];
final Object resultCell;
if(selectable instanceof ObjectAttribute)
{
final Object selectValue = selectColumns[selectableIndex].load(resultSet, columnIndex++);
final ObjectAttribute selectAttribute = (ObjectAttribute)selectable;
resultCell = selectAttribute.cacheToSurface(selectValue);
}
else if(selectable instanceof ComputedFunction)
{
final ComputedFunction selectFunction = (ComputedFunction)selectable;
resultCell = selectFunction.load(resultSet, columnIndex++);
}
else
{
final Number pk = (Number)resultSet.getObject(columnIndex++);
//System.out.println("pk:"+pk);
if(pk==null)
{
// can happen when using right outer joins
resultCell = null;
}
else
{
final Type type = types[selectableIndex];
final Type currentType;
if(type==null)
{
final String typeID = resultSet.getString(columnIndex++);
currentType = model.findTypeByID(typeID);
if(currentType==null)
throw new RuntimeException("no type with type id "+typeID);
}
else
currentType = type;
resultCell = currentType.getItemObject(pk.intValue());
}
}
if(resultRow!=null)
resultRow[selectableIndex] = resultCell;
else
result.add(resultCell);
}
if(resultRow!=null)
result.add(Collections.unmodifiableList(Arrays.asList(resultRow)));
}
}
}, query.makeStatementInfo));
return result;
}
private void log(final long start, final String sqlText)
{
final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS");
final long end = System.currentTimeMillis();
System.out.println(df.format(new Date(start)) + " " + sqlText + " " +(end-start) + "ms.");
}
private List getExpectedCalls()
{
if ( expectedCalls==null )
{
expectedCalls = new LinkedList();
}
return expectedCalls;
}
void expectNoCall()
{
if ( expectedCalls!=null ) throw new RuntimeException( expectedCalls.toString() );
expectedCalls = Collections.EMPTY_LIST;
}
void expectLoad( Transaction tx, Item item )
{
getExpectedCalls().add( new LoadCall(tx, item) );
}
void expectSearch( Transaction tx, Type type )
{
getExpectedCalls().add( new SearchCall(tx, type) );
}
void verifyExpectations()
{
if ( expectedCalls==null ) throw new RuntimeException("no expectations set");
if ( !expectedCalls.isEmpty() )
{
throw new RuntimeException( "missing calls: "+expectedCalls );
}
expectedCalls = null;
}
Call nextExpectedCall()
{
if ( expectedCalls.isEmpty() )
{
throw new RuntimeException( "no more calls expected" );
}
return (Call)expectedCalls.remove(0);
}
/**
* return true if the database was in expectation checking mode
*/
boolean clearExpectedCalls()
{
boolean result = expectedCalls!=null;
expectedCalls = null;
return result;
}
void load(final Connection connection, final PersistentState state)
{
if ( expectedCalls!=null )
{
nextExpectedCall().checkLoad( connection, state );
}
buildStage = false;
final Statement bf = createStatement();
bf.append("select ");
boolean first = true;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
final Table table = type.getTable();
final List columns = table.getColumns();
for(Iterator i = columns.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Column column = (Column)i.next();
bf.append(table.protectedID).
append('.').
append(column.protectedID).defineColumn(column);
}
}
if(first)
{
// no columns in type
bf.append(state.type.getTable().getPrimaryKey().protectedID);
}
bf.append(" from ");
first = true;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
if(first)
first = false;
else
bf.append(',');
bf.append(type.getTable().protectedID);
}
bf.append(" where ");
first = true;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
if(first)
first = false;
else
bf.append(" and ");
final Table table = type.getTable();
bf.append(table.protectedID).
append('.').
append(table.getPrimaryKey().protectedID).
append('=').
append(state.pk);
}
// TODO: let PersistentState be its own ResultSetHandler
executeSQLQuery(connection, bf, new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new NoSuchItemException( state.item );
else
{
int columnIndex = 1;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
for(Iterator i = type.getTable().getColumns().iterator(); i.hasNext(); )
((Column)i.next()).load(resultSet, columnIndex++, state);
}
}
}
}, false);
}
void store(final Connection connection, final State state, final boolean present)
throws UniqueViolationException
{
store(connection, state, state.type, present);
}
private void store(final Connection connection, final State state, final Type type, final boolean present)
throws UniqueViolationException
{
buildStage = false;
final Type supertype = type.getSupertype();
if(supertype!=null)
store(connection, state, supertype, present);
final Table table = type.getTable();
final List columns = table.getColumns();
final Statement bf = createStatement();
if(present)
{
bf.append("update ").
append(table.protectedID).
append(" set ");
boolean first = true;
for(Iterator i = columns.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Column column = (Column)i.next();
bf.append(column.protectedID).
append('=');
final Object value = state.store(column);
bf.append(column.cacheToDatabase(value));
}
bf.append(" where ").
append(table.getPrimaryKey().protectedID).
append('=').
append(state.pk);
}
else
{
bf.append("insert into ").
append(table.protectedID).
append("(").
append(table.getPrimaryKey().protectedID);
final StringColumn typeColumn = table.getTypeColumn();
if(typeColumn!=null)
{
bf.append(',').
append(typeColumn.protectedID);
}
for(Iterator i = columns.iterator(); i.hasNext(); )
{
bf.append(',');
final Column column = (Column)i.next();
bf.append(column.protectedID);
}
bf.append(")values(").
append(state.pk);
if(typeColumn!=null)
{
bf.append(",'").
append(state.type.getID()).
append('\'');
}
for(Iterator i = columns.iterator(); i.hasNext(); )
{
bf.append(',');
final Column column = (Column)i.next();
final Object value = state.store(column);
bf.append(column.cacheToDatabase(value));
}
bf.append(')');
}
//System.out.println("storing "+bf.toString());
final UniqueConstraint[] uqs = type.uniqueConstraints;
executeSQLUpdate(connection, bf, 1, uqs.length==1?uqs[0]:null);
}
void delete(final Connection connection, final Item item)
{
buildStage = false;
final Type type = item.type;
final int pk = item.pk;
for(Type currentType = type; currentType!=null; currentType = currentType.getSupertype())
{
final Table currentTable = currentType.getTable();
final Statement bf = createStatement();
bf.append("delete from ").
append(currentTable.protectedID).
append(" where ").
append(currentTable.getPrimaryKey().protectedID).
append('=').
append(pk);
//System.out.println("deleting "+bf.toString());
try
{
executeSQLUpdate(connection, bf, 1);
}
catch(UniqueViolationException e)
{
throw new NestingRuntimeException(e);
}
}
}
static interface ResultSetHandler
{
public void run(ResultSet resultSet) throws SQLException;
}
private final static int convertSQLResult(final Object sqlInteger)
{
// IMPLEMENTATION NOTE
// Whether the returned object is an Integer, a Long or a BigDecimal,
// depends on the database used and for oracle on whether
// OracleStatement.defineColumnType is used or not, so we support all
// here.
return ((Number)sqlInteger).intValue();
}
//private static int timeExecuteQuery = 0;
private final StatementInfo executeSQLQuery(
final Connection connection,
final Statement statement,
final ResultSetHandler resultSetHandler,
final boolean makeStatementInfo)
{
java.sql.Statement sqlStatement = null;
ResultSet resultSet = null;
try
{
final String sqlText = statement.getText();
final long logStart = log ? System.currentTimeMillis() : 0;
// TODO: use prepared statements and reuse the statement.
sqlStatement = connection.createStatement();
if(useDefineColumnTypes)
((DatabaseColumnTypesDefinable)this).defineColumnTypes(statement.columnTypes, sqlStatement);
resultSet = sqlStatement.executeQuery(sqlText);
resultSetHandler.run(resultSet);
if(resultSet!=null)
{
resultSet.close();
resultSet = null;
}
if(sqlStatement!=null)
{
sqlStatement.close();
sqlStatement = null;
}
if(log)
log(logStart, sqlText);
if(makeStatementInfo)
return makeStatementInfo(statement, connection);
else
return null;
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, statement.toString());
}
finally
{
if(resultSet!=null)
{
try
{
resultSet.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
private final void executeSQLUpdate(final Connection connection, final Statement statement, final int expectedRows)
throws UniqueViolationException
{
executeSQLUpdate(connection, statement, expectedRows, null);
}
private final void executeSQLUpdate(
final Connection connection,
final Statement statement, final int expectedRows,
final UniqueConstraint onlyThreatenedUniqueConstraint)
throws UniqueViolationException
{
java.sql.Statement sqlStatement = null;
try
{
// TODO: use prepared statements and reuse the statement.
final String sqlText = statement.getText();
final long logStart = log ? System.currentTimeMillis() : 0;
sqlStatement = connection.createStatement();
final int rows = sqlStatement.executeUpdate(sqlText);
if(log)
log(logStart, sqlText);
//System.out.println("("+rows+"): "+statement.getText());
if(rows!=expectedRows)
throw new RuntimeException("expected "+expectedRows+" rows, but got "+rows+" on statement "+sqlText);
}
catch(SQLException e)
{
final UniqueViolationException wrappedException = wrapException(e, onlyThreatenedUniqueConstraint);
if(wrappedException!=null)
throw wrappedException;
else
throw new SQLRuntimeException(e, statement.toString());
}
finally
{
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
protected StatementInfo makeStatementInfo(final Statement statement, final Connection connection)
{
return new StatementInfo(statement.getText());
}
protected abstract String extractUniqueConstraintName(SQLException e);
protected final static String ANY_CONSTRAINT = "--ANY--";
private final UniqueViolationException wrapException(
final SQLException e,
final UniqueConstraint onlyThreatenedUniqueConstraint)
{
final String uniqueConstraintID = extractUniqueConstraintName(e);
if(uniqueConstraintID!=null)
{
final UniqueConstraint constraint;
if(ANY_CONSTRAINT.equals(uniqueConstraintID))
constraint = onlyThreatenedUniqueConstraint;
else
{
constraint = (UniqueConstraint)uniqueConstraintsByID.get(uniqueConstraintID);
if(constraint==null)
throw new SQLRuntimeException(e, "no unique constraint found for >"+uniqueConstraintID
+"<, has only "+uniqueConstraintsByID.keySet());
}
return new UniqueViolationException(e, null, constraint);
}
return null;
}
/**
* Trims a name to length for being a suitable qualifier for database entities,
* such as tables, columns, indexes, constraints, partitions etc.
*/
protected static final String trimString(final String longString, final int maxLength)
{
if(maxLength<=0)
throw new RuntimeException("maxLength must be greater zero");
if(longString.length()==0)
throw new RuntimeException("longString must not be empty");
if(longString.length()<=maxLength)
return longString;
int longStringLength = longString.length();
final int[] trimPotential = new int[maxLength];
final ArrayList words = new ArrayList();
{
final StringBuffer buf = new StringBuffer();
for(int i=0; i<longString.length(); i++)
{
final char c = longString.charAt(i);
if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
if(buf.length()<maxLength)
buf.append(c);
else
longStringLength--;
}
if(buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
}
final int expectedTrimPotential = longStringLength - maxLength;
//System.out.println("expected trim potential = "+expectedTrimPotential);
int wordLength;
int remainder = 0;
for(wordLength = trimPotential.length-1; wordLength>=0; wordLength--)
{
//System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]);
remainder = trimPotential[wordLength] - expectedTrimPotential;
if(remainder>=0)
break;
}
final StringBuffer result = new StringBuffer(longStringLength);
for(Iterator i = words.iterator(); i.hasNext(); )
{
final String word = (String)i.next();
//System.out.println("word "+word+" remainder:"+remainder);
if((word.length()>wordLength) && remainder>0)
{
result.append(word.substring(0, wordLength+1));
remainder--;
}
else if(word.length()>wordLength)
result.append(word.substring(0, wordLength));
else
result.append(word);
}
//System.out.println("---- trimName("+longString+","+maxLength+") == "+result+" --- "+words);
if(result.length()!=maxLength)
throw new RuntimeException(result.toString()+maxLength);
return result.toString();
}
String makeName(final String longName)
{
return makeName(null, longName);
}
String makeName(final String prefix, final String longName)
{
final String query = prefix==null ? longName : prefix+'.'+longName;
final String forcedName = (String)forcedNames.get(query);
//System.out.println("---------"+query+"--"+forcedName);
if(forcedName!=null)
return forcedName;
return trimString(longName, 25);
}
protected boolean supportsCheckConstraints()
{
return true;
}
protected boolean supportsEmptyStrings()
{
return true;
}
protected boolean supportsRightOuterJoins()
{
return true;
}
abstract String getIntegerType(int precision);
abstract String getDoubleType(int precision);
abstract String getStringType(int maxLength);
abstract String getDayType();
boolean isLimitClauseInSelect()
{
return false;
}
/**
* Appends a clause to the statement causing the database limiting the query result.
* This method is never called for <code>start==0 && count=={@link Query#UNLIMITED_COUNT}</code>.
* NOTE: Don't forget the space before the keyword 'limit'!
* @param start the number of rows to be skipped
* or zero, if no rows to be skipped.
* Is never negative.
* @param count the number of rows to be returned
* or {@link Query#UNLIMITED_COUNT} if all rows to be returned.
* @return whether the database does support limiting with the given parameters.
* if returns false, the statement must be left unmodified.
*/
abstract boolean appendLimitClause(Statement bf, int start, int count);
private int countTable(final Connection connection, final Table table)
{
final Statement bf = createStatement();
bf.append("select count(*) from ").defineColumnInteger().
append(table.protectedID);
final CountResultSetHandler handler = new CountResultSetHandler();
executeSQLQuery(connection, bf, handler, false);
return handler.result;
}
private static class CountResultSetHandler implements ResultSetHandler
{
int result;
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
result = convertSQLResult(resultSet.getObject(1));
}
}
final PkSource makePkSource(final Table table)
{
return butterflyPkSource ? (PkSource)new ButterflyPkSource(table) : new SequentialPkSource(table);
}
final int[] getMinMaxPK(final Connection connection, final Table table)
{
buildStage = false;
final Statement bf = createStatement();
final String primaryKeyProtectedID = table.getPrimaryKey().protectedID;
bf.append("select min(").
append(primaryKeyProtectedID).defineColumnInteger().
append("),max(").
append(primaryKeyProtectedID).defineColumnInteger().
append(") from ").
append(table.protectedID);
final NextPKResultSetHandler handler = new NextPKResultSetHandler();
executeSQLQuery(connection, bf, handler, false);
return handler.result;
}
private static class NextPKResultSetHandler implements ResultSetHandler
{
int[] result;
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
final Object oLo = resultSet.getObject(1);
if(oLo!=null)
{
result = new int[2];
result[0] = convertSQLResult(oLo);
final Object oHi = resultSet.getObject(2);
result[1] = convertSQLResult(oHi);
}
}
}
final Schema makeSchema()
{
final Schema result = new Schema(driver, connectionPool);
for(Iterator i = tables.iterator(); i.hasNext(); )
((Table)i.next()).makeSchema(result);
completeSchema(result);
return result;
}
protected void completeSchema(final Schema schema)
{
}
final Schema makeVerifiedSchema()
{
final Schema result = makeSchema();
result.verify();
return result;
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
protected static final void printMeta(final ResultSet resultSet) throws SQLException
{
final ResultSetMetaData metaData = resultSet.getMetaData();;
final int columnCount = metaData.getColumnCount();
for(int i = 1; i<=columnCount; i++)
System.out.println("------"+i+":"+metaData.getColumnName(i)+":"+metaData.getColumnType(i));
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
protected static final void printRow(final ResultSet resultSet) throws SQLException
{
final ResultSetMetaData metaData = resultSet.getMetaData();;
final int columnCount = metaData.getColumnCount();
for(int i = 1; i<=columnCount; i++)
System.out.println("----------"+i+":"+resultSet.getObject(i));
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
static final ResultSetHandler logHandler = new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
final int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("columnCount:"+columnCount);
final ResultSetMetaData meta = resultSet.getMetaData();
for(int i = 1; i<=columnCount; i++)
{
System.out.println(meta.getColumnName(i)+"|");
}
while(resultSet.next())
{
for(int i = 1; i<=columnCount; i++)
{
System.out.println(resultSet.getObject(i)+"|");
}
}
}
};
static abstract class Call
{
final Transaction tx;
Call( Transaction tx )
{
this.tx = tx;
}
void checkLoad( Connection connection, PersistentState state )
{
throw new RuntimeException( "load in "+toString() );
}
void checkSearch( Connection connection, Query query )
{
throw new RuntimeException( "search in "+toString() );
}
void checkConnection( Connection connection )
{
if ( ! tx.getConnection().equals(connection) )
{
throw new RuntimeException( "connection mismatch in "+toString() );
}
}
}
static class LoadCall extends Call
{
final Item item;
LoadCall( Transaction tx, Item item )
{
super( tx );
this.item = item;
}
void checkLoad( Connection connection, PersistentState state )
{
checkConnection( connection );
if ( !item.equals(state.item) )
{
throw new RuntimeException( "item mismatch in "+toString()+" (got "+state.item.getCopeID()+")" );
}
}
public String toString()
{
return "Load("+tx.getName()+"/"+item.getCopeID()+")";
}
}
static class SearchCall extends Call
{
final Type type;
SearchCall( Transaction tx, Type type )
{
super( tx );
this.type = type;
}
void checkSearch( Connection connection, Query query )
{
checkConnection( connection );
if ( !type.equals(query.getType()) )
{
throw new RuntimeException( "search type mismatch in "+toString()+" (got "+query.getType()+")" );
}
}
public String toString()
{
return "Search("+tx.getName()+"/"+type+")";
}
}
}
| lib/src/com/exedio/cope/Database.java | /*
* Copyright (C) 2004-2005 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.exedio.cope.search.Condition;
import com.exedio.cope.util.Day;
import com.exedio.dsmf.Driver;
import com.exedio.dsmf.SQLRuntimeException;
import com.exedio.dsmf.Schema;
abstract class Database
{
private final List tables = new ArrayList();
private final HashMap uniqueConstraintsByID = new HashMap();
private final HashMap itemColumnsByIntegrityConstraintName = new HashMap();
private boolean buildStage = true;
final Driver driver;
private final boolean useDefineColumnTypes;
private final boolean log;
private final boolean butterflyPkSource;
final ConnectionPool connectionPool;
private final java.util.Properties forcedNames;
private List expectedCalls = null;
protected Database(final Driver driver, final Properties properties)
{
this.driver = driver;
this.useDefineColumnTypes = this instanceof DatabaseColumnTypesDefinable;
this.log = properties.getDatabaseLog();
this.butterflyPkSource = properties.getPkSourceButterfly();
this.connectionPool = new ConnectionPool(properties);
this.forcedNames = properties.getDatabaseForcedNames();
//System.out.println("using database "+getClass());
}
final void addTable(final Table table)
{
if(!buildStage)
throw new RuntimeException();
tables.add(table);
}
final void addUniqueConstraint(final String constraintID, final UniqueConstraint constraint)
{
if(!buildStage)
throw new RuntimeException();
final Object collision = uniqueConstraintsByID.put(constraintID, constraint);
if(collision!=null)
throw new RuntimeException("ambiguous unique constraint "+constraint+" trimmed to >"+constraintID+"< colliding with "+collision);
}
final void addIntegrityConstraint(final ItemColumn column)
{
if(!buildStage)
throw new RuntimeException();
if(itemColumnsByIntegrityConstraintName.put(column.integrityConstraintName, column)!=null)
throw new RuntimeException("there is more than one integrity constraint with name "+column.integrityConstraintName);
}
protected final Statement createStatement()
{
return new Statement(useDefineColumnTypes);
}
void createDatabase()
{
buildStage = false;
makeSchema().create();
}
//private static int checkTableTime = 0;
void checkDatabase(final Connection connection)
{
buildStage = false;
//final long time = System.currentTimeMillis();
final Statement bf = createStatement();
bf.append("select count(*) from ").defineColumnInteger();
boolean first = true;
for(Iterator i = tables.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Table table = (Table)i.next();
bf.append(table.protectedID);
}
final Long testDate = new Long(System.currentTimeMillis());
final Integer testDay = new Integer(DayColumn.getTransientNumber(new Day(2005, 9, 26)));
bf.append(" where ");
first = true;
for(Iterator i = tables.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(" and ");
final Table table = (Table)i.next();
final Column primaryKey = table.getPrimaryKey();
bf.append(table.protectedID).
append('.').
append(primaryKey.protectedID).
append('=').
append(Type.NOT_A_PK);
for(Iterator j = table.getColumns().iterator(); j.hasNext(); )
{
final Column column = (Column)j.next();
bf.append(" and ").
append(table.protectedID).
append('.').
append(column.protectedID).
append('=');
if(column instanceof IntegerColumn)
bf.appendValue(column, ((IntegerColumn)column).longInsteadOfInt ? (Number)new Long(1) : new Integer(1));
else if(column instanceof DoubleColumn)
bf.appendValue(column, new Double(2.2));
else if(column instanceof StringColumn)
bf.appendValue(column, "z");
else if(column instanceof TimestampColumn)
bf.appendValue(column, testDate);
else if(column instanceof DayColumn)
bf.appendValue(column, testDay);
else
throw new RuntimeException(column.toString());
}
}
final long logStart = log ? System.currentTimeMillis() : 0;
executeSQLQuery(connection, bf,
new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
}
},
false
);
if(log)
log(logStart, bf);
}
void dropDatabase()
{
buildStage = false;
makeSchema().drop();
}
void tearDownDatabase()
{
buildStage = false;
makeSchema().tearDown();
}
void checkEmptyDatabase(final Connection connection)
{
buildStage = false;
//final long time = System.currentTimeMillis();
for(Iterator i = tables.iterator(); i.hasNext(); )
{
final Table table = (Table)i.next();
final int count = countTable(connection, table);
if(count>0)
throw new RuntimeException("there are "+count+" items left for table "+table.id);
}
//final long amount = (System.currentTimeMillis()-time);
//checkEmptyTableTime += amount;
//System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime);
}
private final boolean appendLimitClauseInSearch(final Statement bf, final int start, final int count)
{
if(start>0 || count!=Query.UNLIMITED_COUNT)
return appendLimitClause(bf, start, count);
else
return false;
}
final ArrayList search(final Connection connection, final Query query, final boolean doCountOnly)
{
if ( expectedCalls!=null )
{
nextExpectedCall().checkSearch( connection, query );
}
buildStage = false;
final int limitStart = query.limitStart;
final int limitCount = query.limitCount;
final boolean limitClauseInSelect = doCountOnly ? false : isLimitClauseInSelect();
boolean limitByDatabaseTemp = false;
final Statement bf = createStatement();
bf.setJoinsToAliases(query);
bf.append("select");
if(!doCountOnly && limitClauseInSelect)
limitByDatabaseTemp = appendLimitClauseInSearch(bf, limitStart, limitCount);
bf.append(' ');
final Selectable[] selectables = query.selectables;
final Column[] selectColumns = new Column[selectables.length];
final Type[] selectTypes = new Type[selectables.length];
if(doCountOnly)
{
bf.append("count(*)");
}
else
{
for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++)
{
final Selectable selectable = selectables[selectableIndex];
final Column selectColumn;
final Type selectType;
final Table selectTable;
final Column selectPrimaryKey;
if(selectable instanceof Function)
{
final Function selectAttribute = (Function)selectable;
selectType = selectAttribute.getType();
if(selectableIndex>0)
bf.append(',');
if(selectable instanceof ObjectAttribute)
{
selectColumn = ((ObjectAttribute)selectAttribute).getColumn();
selectTable = selectColumn.table;
selectPrimaryKey = selectTable.getPrimaryKey();
bf.append(selectColumn.table.protectedID).
append('.').
append(selectColumn.protectedID).defineColumn(selectColumn);
}
else
{
selectColumn = null;
final ComputedFunction computedFunction = (ComputedFunction)selectable;
bf.append(computedFunction, (Join)null).defineColumn(computedFunction);
}
}
else
{
selectType = (Type)selectable;
selectTable = selectType.getTable();
selectPrimaryKey = selectTable.getPrimaryKey();
selectColumn = selectPrimaryKey;
if(selectableIndex>0)
bf.append(',');
bf.append(selectColumn.table.protectedID).
append('.').
append(selectColumn.protectedID).defineColumn(selectColumn);
if(selectColumn.primaryKey)
{
final StringColumn selectTypeColumn = selectColumn.getTypeColumn();
if(selectTypeColumn!=null)
{
bf.append(',').
append(selectTable.protectedID).
append('.').
append(selectTypeColumn.protectedID).defineColumn(selectTypeColumn);
}
else
selectTypes[selectableIndex] = selectType;
}
else
selectTypes[selectableIndex] = selectType;
}
selectColumns[selectableIndex] = selectColumn;
}
}
bf.append(" from ").
append(query.type.getTable().protectedID);
final String fromAlias = bf.getAlias(null);
if(fromAlias!=null)
{
bf.append(' ').
append(fromAlias);
}
final ArrayList queryJoins = query.joins;
if(queryJoins!=null)
{
for(Iterator i = queryJoins.iterator(); i.hasNext(); )
{
final Join join = (Join)i.next();
bf.append(' ').
append(join.getKindString()).
append(" join ").
append(join.type.getTable().protectedID);
final String joinAlias = bf.getAlias(join);
if(joinAlias!=null)
{
bf.append(' ').
append(joinAlias);
}
final Condition joinCondition = join.condition;
if(joinCondition!=null)
{
bf.append(" on ");
joinCondition.appendStatement(bf);
}
}
}
if(query.condition!=null)
{
bf.append(" where ");
query.condition.appendStatement(bf);
}
if(!doCountOnly)
{
boolean firstOrderBy = true;
if(query.orderBy!=null || query.deterministicOrder)
bf.append(" order by ");
if(query.orderBy!=null)
{
firstOrderBy = false;
bf.append(query.orderBy, (Join)null);
if(!query.orderAscending)
bf.append(" desc");
}
if(query.deterministicOrder) // TODO skip this, if orderBy already orders by some unique condition
{
if(!firstOrderBy)
bf.append(',');
query.type.getPkSource().appendDeterministicOrderByExpression(bf, query.type.getTable());
}
if(!limitClauseInSelect)
limitByDatabaseTemp = appendLimitClauseInSearch(bf, limitStart, limitCount);
}
final boolean limitByDatabase = limitByDatabaseTemp; // must be final for usage in ResultSetHandler
final Type[] types = selectTypes;
final Model model = query.model;
final ArrayList result = new ArrayList();
if(limitStart<0)
throw new RuntimeException();
if(selectables.length!=selectColumns.length)
throw new RuntimeException();
if(selectables.length!=types.length)
throw new RuntimeException();
final long logStart = log ? System.currentTimeMillis() : 0;
query.addStatementInfo(executeSQLQuery(connection, bf, new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
if(doCountOnly)
{
resultSet.next();
result.add(new Integer(resultSet.getInt(1)));
if(resultSet.next())
throw new RuntimeException();
return;
}
if(!limitByDatabase && limitStart>0)
{
// TODO: ResultSet.relative
// Would like to use
// resultSet.relative(limitStart+1);
// but this throws a java.sql.SQLException:
// Invalid operation for forward only resultset : relative
for(int i = limitStart; i>0; i--)
resultSet.next();
}
int i = ((limitCount==Query.UNLIMITED_COUNT||limitByDatabase) ? Integer.MAX_VALUE : limitCount );
if(i<=0)
throw new RuntimeException(String.valueOf(limitCount));
while(resultSet.next() && (--i)>=0)
{
int columnIndex = 1;
final Object[] resultRow = (selectables.length > 1) ? new Object[selectables.length] : null;
for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++)
{
final Selectable selectable = selectables[selectableIndex];
final Object resultCell;
if(selectable instanceof ObjectAttribute)
{
final Object selectValue = selectColumns[selectableIndex].load(resultSet, columnIndex++);
final ObjectAttribute selectAttribute = (ObjectAttribute)selectable;
resultCell = selectAttribute.cacheToSurface(selectValue);
}
else if(selectable instanceof ComputedFunction)
{
final ComputedFunction selectFunction = (ComputedFunction)selectable;
resultCell = selectFunction.load(resultSet, columnIndex++);
}
else
{
final Number pk = (Number)resultSet.getObject(columnIndex++);
//System.out.println("pk:"+pk);
if(pk==null)
{
// can happen when using right outer joins
resultCell = null;
}
else
{
final Type type = types[selectableIndex];
final Type currentType;
if(type==null)
{
final String typeID = resultSet.getString(columnIndex++);
currentType = model.findTypeByID(typeID);
if(currentType==null)
throw new RuntimeException("no type with type id "+typeID);
}
else
currentType = type;
resultCell = currentType.getItemObject(pk.intValue());
}
}
if(resultRow!=null)
resultRow[selectableIndex] = resultCell;
else
result.add(resultCell);
}
if(resultRow!=null)
result.add(Collections.unmodifiableList(Arrays.asList(resultRow)));
}
}
}, query.makeStatementInfo));
if(log)
log(logStart, bf);
return result;
}
private void log(final long start, final Statement bf)
{
final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS");
final long end = System.currentTimeMillis();
System.out.println(df.format(new Date(start)) + " " + bf.getText() + " " +(end-start) + "ms.");
}
private List getExpectedCalls()
{
if ( expectedCalls==null )
{
expectedCalls = new LinkedList();
}
return expectedCalls;
}
void expectNoCall()
{
if ( expectedCalls!=null ) throw new RuntimeException( expectedCalls.toString() );
expectedCalls = Collections.EMPTY_LIST;
}
void expectLoad( Transaction tx, Item item )
{
getExpectedCalls().add( new LoadCall(tx, item) );
}
void expectSearch( Transaction tx, Type type )
{
getExpectedCalls().add( new SearchCall(tx, type) );
}
void verifyExpectations()
{
if ( expectedCalls==null ) throw new RuntimeException("no expectations set");
if ( !expectedCalls.isEmpty() )
{
throw new RuntimeException( "missing calls: "+expectedCalls );
}
expectedCalls = null;
}
Call nextExpectedCall()
{
if ( expectedCalls.isEmpty() )
{
throw new RuntimeException( "no more calls expected" );
}
return (Call)expectedCalls.remove(0);
}
/**
* return true if the database was in expectation checking mode
*/
boolean clearExpectedCalls()
{
boolean result = expectedCalls!=null;
expectedCalls = null;
return result;
}
void load(final Connection connection, final PersistentState state)
{
if ( expectedCalls!=null )
{
nextExpectedCall().checkLoad( connection, state );
}
buildStage = false;
final Statement bf = createStatement();
bf.append("select ");
boolean first = true;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
final Table table = type.getTable();
final List columns = table.getColumns();
for(Iterator i = columns.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Column column = (Column)i.next();
bf.append(table.protectedID).
append('.').
append(column.protectedID).defineColumn(column);
}
}
if(first)
{
// no columns in type
bf.append(state.type.getTable().getPrimaryKey().protectedID);
}
bf.append(" from ");
first = true;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
if(first)
first = false;
else
bf.append(',');
bf.append(type.getTable().protectedID);
}
bf.append(" where ");
first = true;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
if(first)
first = false;
else
bf.append(" and ");
final Table table = type.getTable();
bf.append(table.protectedID).
append('.').
append(table.getPrimaryKey().protectedID).
append('=').
append(state.pk);
}
final long logStart = log ? System.currentTimeMillis() : 0;
// TODO: let PersistentState be its own ResultSetHandler
executeSQLQuery(connection, bf, new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new NoSuchItemException( state.item );
else
{
int columnIndex = 1;
for(Type type = state.type; type!=null; type = type.getSupertype())
{
for(Iterator i = type.getTable().getColumns().iterator(); i.hasNext(); )
((Column)i.next()).load(resultSet, columnIndex++, state);
}
}
}
}, false);
if(log)
log(logStart, bf);
}
void store(final Connection connection, final State state, final boolean present)
throws UniqueViolationException
{
store(connection, state, state.type, present);
}
private void store(final Connection connection, final State state, final Type type, final boolean present)
throws UniqueViolationException
{
buildStage = false;
final Type supertype = type.getSupertype();
if(supertype!=null)
store(connection, state, supertype, present);
final Table table = type.getTable();
final List columns = table.getColumns();
final Statement bf = createStatement();
if(present)
{
bf.append("update ").
append(table.protectedID).
append(" set ");
boolean first = true;
for(Iterator i = columns.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Column column = (Column)i.next();
bf.append(column.protectedID).
append('=');
final Object value = state.store(column);
bf.append(column.cacheToDatabase(value));
}
bf.append(" where ").
append(table.getPrimaryKey().protectedID).
append('=').
append(state.pk);
}
else
{
bf.append("insert into ").
append(table.protectedID).
append("(").
append(table.getPrimaryKey().protectedID);
final StringColumn typeColumn = table.getTypeColumn();
if(typeColumn!=null)
{
bf.append(',').
append(typeColumn.protectedID);
}
for(Iterator i = columns.iterator(); i.hasNext(); )
{
bf.append(',');
final Column column = (Column)i.next();
bf.append(column.protectedID);
}
bf.append(")values(").
append(state.pk);
if(typeColumn!=null)
{
bf.append(",'").
append(state.type.getID()).
append('\'');
}
for(Iterator i = columns.iterator(); i.hasNext(); )
{
bf.append(',');
final Column column = (Column)i.next();
final Object value = state.store(column);
bf.append(column.cacheToDatabase(value));
}
bf.append(')');
}
//System.out.println("storing "+bf.toString());
final UniqueConstraint[] uqs = type.uniqueConstraints;
final long logStart = log ? System.currentTimeMillis() : 0;
executeSQLUpdate(connection, bf, 1, uqs.length==1?uqs[0]:null);
if(log)
log(logStart, bf);
}
void delete(final Connection connection, final Item item)
{
buildStage = false;
final Type type = item.type;
final int pk = item.pk;
for(Type currentType = type; currentType!=null; currentType = currentType.getSupertype())
{
final Table currentTable = currentType.getTable();
final Statement bf = createStatement();
bf.append("delete from ").
append(currentTable.protectedID).
append(" where ").
append(currentTable.getPrimaryKey().protectedID).
append('=').
append(pk);
//System.out.println("deleting "+bf.toString());
try
{
final long logStart = log ? System.currentTimeMillis() : 0;
executeSQLUpdate(connection, bf, 1);
if(log)
log(logStart, bf);
}
catch(UniqueViolationException e)
{
throw new NestingRuntimeException(e);
}
}
}
static interface ResultSetHandler
{
public void run(ResultSet resultSet) throws SQLException;
}
private final static int convertSQLResult(final Object sqlInteger)
{
// IMPLEMENTATION NOTE
// Whether the returned object is an Integer, a Long or a BigDecimal,
// depends on the database used and for oracle on whether
// OracleStatement.defineColumnType is used or not, so we support all
// here.
return ((Number)sqlInteger).intValue();
}
//private static int timeExecuteQuery = 0;
private final StatementInfo executeSQLQuery(
final Connection connection,
final Statement statement,
final ResultSetHandler resultSetHandler,
final boolean makeStatementInfo)
{
java.sql.Statement sqlStatement = null;
ResultSet resultSet = null;
try
{
final String sqlText = statement.getText();
// TODO: use prepared statements and reuse the statement.
sqlStatement = connection.createStatement();
if(useDefineColumnTypes)
((DatabaseColumnTypesDefinable)this).defineColumnTypes(statement.columnTypes, sqlStatement);
//System.out.println(Transaction.get().toString()+": "+sqlText);
//long time = System.currentTimeMillis();
resultSet = sqlStatement.executeQuery(sqlText);
//long interval = System.currentTimeMillis() - time;
//timeExecuteQuery += interval;
//System.out.println("executeQuery: "+interval+"ms sum "+timeExecuteQuery+"ms");
resultSetHandler.run(resultSet);
if(resultSet!=null)
{
resultSet.close();
resultSet = null;
}
if(sqlStatement!=null)
{
sqlStatement.close();
sqlStatement = null;
}
if(makeStatementInfo)
return makeStatementInfo(statement, connection);
else
return null;
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, statement.toString());
}
finally
{
if(resultSet!=null)
{
try
{
resultSet.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
private final void executeSQLUpdate(final Connection connection, final Statement statement, final int expectedRows)
throws UniqueViolationException
{
executeSQLUpdate(connection, statement, expectedRows, null);
}
private final void executeSQLUpdate(
final Connection connection,
final Statement statement, final int expectedRows,
final UniqueConstraint onlyThreatenedUniqueConstraint)
throws UniqueViolationException
{
java.sql.Statement sqlStatement = null;
try
{
// TODO: use prepared statements and reuse the statement.
final String sqlText = statement.getText();
//System.err.println(Transaction.get().toString()+": "+statement.getText());
sqlStatement = connection.createStatement();
final int rows = sqlStatement.executeUpdate(sqlText);
//System.out.println("("+rows+"): "+statement.getText());
if(rows!=expectedRows)
throw new RuntimeException("expected "+expectedRows+" rows, but got "+rows+" on statement "+sqlText);
}
catch(SQLException e)
{
final UniqueViolationException wrappedException = wrapException(e, onlyThreatenedUniqueConstraint);
if(wrappedException!=null)
throw wrappedException;
else
throw new SQLRuntimeException(e, statement.toString());
}
finally
{
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
protected StatementInfo makeStatementInfo(final Statement statement, final Connection connection)
{
return new StatementInfo(statement.getText());
}
protected abstract String extractUniqueConstraintName(SQLException e);
protected final static String ANY_CONSTRAINT = "--ANY--";
private final UniqueViolationException wrapException(
final SQLException e,
final UniqueConstraint onlyThreatenedUniqueConstraint)
{
final String uniqueConstraintID = extractUniqueConstraintName(e);
if(uniqueConstraintID!=null)
{
final UniqueConstraint constraint;
if(ANY_CONSTRAINT.equals(uniqueConstraintID))
constraint = onlyThreatenedUniqueConstraint;
else
{
constraint = (UniqueConstraint)uniqueConstraintsByID.get(uniqueConstraintID);
if(constraint==null)
throw new SQLRuntimeException(e, "no unique constraint found for >"+uniqueConstraintID
+"<, has only "+uniqueConstraintsByID.keySet());
}
return new UniqueViolationException(e, null, constraint);
}
return null;
}
/**
* Trims a name to length for being a suitable qualifier for database entities,
* such as tables, columns, indexes, constraints, partitions etc.
*/
protected static final String trimString(final String longString, final int maxLength)
{
if(maxLength<=0)
throw new RuntimeException("maxLength must be greater zero");
if(longString.length()==0)
throw new RuntimeException("longString must not be empty");
if(longString.length()<=maxLength)
return longString;
int longStringLength = longString.length();
final int[] trimPotential = new int[maxLength];
final ArrayList words = new ArrayList();
{
final StringBuffer buf = new StringBuffer();
for(int i=0; i<longString.length(); i++)
{
final char c = longString.charAt(i);
if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
if(buf.length()<maxLength)
buf.append(c);
else
longStringLength--;
}
if(buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
}
final int expectedTrimPotential = longStringLength - maxLength;
//System.out.println("expected trim potential = "+expectedTrimPotential);
int wordLength;
int remainder = 0;
for(wordLength = trimPotential.length-1; wordLength>=0; wordLength--)
{
//System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]);
remainder = trimPotential[wordLength] - expectedTrimPotential;
if(remainder>=0)
break;
}
final StringBuffer result = new StringBuffer(longStringLength);
for(Iterator i = words.iterator(); i.hasNext(); )
{
final String word = (String)i.next();
//System.out.println("word "+word+" remainder:"+remainder);
if((word.length()>wordLength) && remainder>0)
{
result.append(word.substring(0, wordLength+1));
remainder--;
}
else if(word.length()>wordLength)
result.append(word.substring(0, wordLength));
else
result.append(word);
}
//System.out.println("---- trimName("+longString+","+maxLength+") == "+result+" --- "+words);
if(result.length()!=maxLength)
throw new RuntimeException(result.toString()+maxLength);
return result.toString();
}
String makeName(final String longName)
{
return makeName(null, longName);
}
String makeName(final String prefix, final String longName)
{
final String query = prefix==null ? longName : prefix+'.'+longName;
final String forcedName = (String)forcedNames.get(query);
//System.out.println("---------"+query+"--"+forcedName);
if(forcedName!=null)
return forcedName;
return trimString(longName, 25);
}
protected boolean supportsCheckConstraints()
{
return true;
}
protected boolean supportsEmptyStrings()
{
return true;
}
protected boolean supportsRightOuterJoins()
{
return true;
}
abstract String getIntegerType(int precision);
abstract String getDoubleType(int precision);
abstract String getStringType(int maxLength);
abstract String getDayType();
boolean isLimitClauseInSelect()
{
return false;
}
/**
* Appends a clause to the statement causing the database limiting the query result.
* This method is never called for <code>start==0 && count=={@link Query#UNLIMITED_COUNT}</code>.
* NOTE: Don't forget the space before the keyword 'limit'!
* @param start the number of rows to be skipped
* or zero, if no rows to be skipped.
* Is never negative.
* @param count the number of rows to be returned
* or {@link Query#UNLIMITED_COUNT} if all rows to be returned.
* @return whether the database does support limiting with the given parameters.
* if returns false, the statement must be left unmodified.
*/
abstract boolean appendLimitClause(Statement bf, int start, int count);
private int countTable(final Connection connection, final Table table)
{
final Statement bf = createStatement();
bf.append("select count(*) from ").defineColumnInteger().
append(table.protectedID);
final CountResultSetHandler handler = new CountResultSetHandler();
final long logStart = log ? System.currentTimeMillis() : 0;
executeSQLQuery(connection, bf, handler, false);
if(log)
log(logStart, bf);
return handler.result;
}
private static class CountResultSetHandler implements ResultSetHandler
{
int result;
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
result = convertSQLResult(resultSet.getObject(1));
}
}
final PkSource makePkSource(final Table table)
{
return butterflyPkSource ? (PkSource)new ButterflyPkSource(table) : new SequentialPkSource(table);
}
final int[] getMinMaxPK(final Connection connection, final Table table)
{
buildStage = false;
final Statement bf = createStatement();
final String primaryKeyProtectedID = table.getPrimaryKey().protectedID;
bf.append("select min(").
append(primaryKeyProtectedID).defineColumnInteger().
append("),max(").
append(primaryKeyProtectedID).defineColumnInteger().
append(") from ").
append(table.protectedID);
final NextPKResultSetHandler handler = new NextPKResultSetHandler();
final long logStart = log ? System.currentTimeMillis() : 0;
executeSQLQuery(connection, bf, handler, false);
if(log)
log(logStart, bf);
return handler.result;
}
private static class NextPKResultSetHandler implements ResultSetHandler
{
int[] result;
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
final Object oLo = resultSet.getObject(1);
if(oLo!=null)
{
result = new int[2];
result[0] = convertSQLResult(oLo);
final Object oHi = resultSet.getObject(2);
result[1] = convertSQLResult(oHi);
}
}
}
final Schema makeSchema()
{
final Schema result = new Schema(driver, connectionPool);
for(Iterator i = tables.iterator(); i.hasNext(); )
((Table)i.next()).makeSchema(result);
completeSchema(result);
return result;
}
protected void completeSchema(final Schema schema)
{
}
final Schema makeVerifiedSchema()
{
final Schema result = makeSchema();
result.verify();
return result;
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
protected static final void printMeta(final ResultSet resultSet) throws SQLException
{
final ResultSetMetaData metaData = resultSet.getMetaData();;
final int columnCount = metaData.getColumnCount();
for(int i = 1; i<=columnCount; i++)
System.out.println("------"+i+":"+metaData.getColumnName(i)+":"+metaData.getColumnType(i));
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
protected static final void printRow(final ResultSet resultSet) throws SQLException
{
final ResultSetMetaData metaData = resultSet.getMetaData();;
final int columnCount = metaData.getColumnCount();
for(int i = 1; i<=columnCount; i++)
System.out.println("----------"+i+":"+resultSet.getObject(i));
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
static final ResultSetHandler logHandler = new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
final int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("columnCount:"+columnCount);
final ResultSetMetaData meta = resultSet.getMetaData();
for(int i = 1; i<=columnCount; i++)
{
System.out.println(meta.getColumnName(i)+"|");
}
while(resultSet.next())
{
for(int i = 1; i<=columnCount; i++)
{
System.out.println(resultSet.getObject(i)+"|");
}
}
}
};
static abstract class Call
{
final Transaction tx;
Call( Transaction tx )
{
this.tx = tx;
}
void checkLoad( Connection connection, PersistentState state )
{
throw new RuntimeException( "load in "+toString() );
}
void checkSearch( Connection connection, Query query )
{
throw new RuntimeException( "search in "+toString() );
}
void checkConnection( Connection connection )
{
if ( ! tx.getConnection().equals(connection) )
{
throw new RuntimeException( "connection mismatch in "+toString() );
}
}
}
static class LoadCall extends Call
{
final Item item;
LoadCall( Transaction tx, Item item )
{
super( tx );
this.item = item;
}
void checkLoad( Connection connection, PersistentState state )
{
checkConnection( connection );
if ( !item.equals(state.item) )
{
throw new RuntimeException( "item mismatch in "+toString()+" (got "+state.item.getCopeID()+")" );
}
}
public String toString()
{
return "Load("+tx.getName()+"/"+item.getCopeID()+")";
}
}
static class SearchCall extends Call
{
final Type type;
SearchCall( Transaction tx, Type type )
{
super( tx );
this.type = type;
}
void checkSearch( Connection connection, Query query )
{
checkConnection( connection );
if ( !type.equals(query.getType()) )
{
throw new RuntimeException( "search type mismatch in "+toString()+" (got "+query.getType()+")" );
}
}
public String toString()
{
return "Search("+tx.getName()+"/"+type+")";
}
}
}
| put logging into executeSQL
git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@3630 e7d4fc99-c606-0410-b9bf-843393a9eab7
| lib/src/com/exedio/cope/Database.java | put logging into executeSQL | <ide><path>ib/src/com/exedio/cope/Database.java
<ide> }
<ide> }
<ide>
<del> final long logStart = log ? System.currentTimeMillis() : 0;
<del>
<ide> executeSQLQuery(connection, bf,
<ide> new ResultSetHandler()
<ide> {
<ide> },
<ide> false
<ide> );
<del>
<del> if(log)
<del> log(logStart, bf);
<ide> }
<ide>
<ide> void dropDatabase()
<ide> if(selectables.length!=types.length)
<ide> throw new RuntimeException();
<ide>
<del> final long logStart = log ? System.currentTimeMillis() : 0;
<del>
<ide> query.addStatementInfo(executeSQLQuery(connection, bf, new ResultSetHandler()
<ide> {
<ide> public void run(final ResultSet resultSet) throws SQLException
<ide> }
<ide> }, query.makeStatementInfo));
<ide>
<del> if(log)
<del> log(logStart, bf);
<del>
<ide> return result;
<ide> }
<ide>
<del> private void log(final long start, final Statement bf)
<add> private void log(final long start, final String sqlText)
<ide> {
<ide> final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS");
<ide> final long end = System.currentTimeMillis();
<del> System.out.println(df.format(new Date(start)) + " " + bf.getText() + " " +(end-start) + "ms.");
<add> System.out.println(df.format(new Date(start)) + " " + sqlText + " " +(end-start) + "ms.");
<ide> }
<ide>
<ide> private List getExpectedCalls()
<ide> append('=').
<ide> append(state.pk);
<ide> }
<del>
<del> final long logStart = log ? System.currentTimeMillis() : 0;
<ide>
<ide> // TODO: let PersistentState be its own ResultSetHandler
<ide> executeSQLQuery(connection, bf, new ResultSetHandler()
<ide> }
<ide> }
<ide> }, false);
<del>
<del> if(log)
<del> log(logStart, bf);
<ide> }
<ide>
<ide> void store(final Connection connection, final State state, final boolean present)
<ide>
<ide> //System.out.println("storing "+bf.toString());
<ide> final UniqueConstraint[] uqs = type.uniqueConstraints;
<del> final long logStart = log ? System.currentTimeMillis() : 0;
<ide> executeSQLUpdate(connection, bf, 1, uqs.length==1?uqs[0]:null);
<del> if(log)
<del> log(logStart, bf);
<ide> }
<ide>
<ide> void delete(final Connection connection, final Item item)
<ide>
<ide> try
<ide> {
<del> final long logStart = log ? System.currentTimeMillis() : 0;
<ide> executeSQLUpdate(connection, bf, 1);
<del> if(log)
<del> log(logStart, bf);
<ide> }
<ide> catch(UniqueViolationException e)
<ide> {
<ide> try
<ide> {
<ide> final String sqlText = statement.getText();
<add> final long logStart = log ? System.currentTimeMillis() : 0;
<add>
<ide> // TODO: use prepared statements and reuse the statement.
<ide> sqlStatement = connection.createStatement();
<ide>
<ide> if(useDefineColumnTypes)
<ide> ((DatabaseColumnTypesDefinable)this).defineColumnTypes(statement.columnTypes, sqlStatement);
<ide>
<del> //System.out.println(Transaction.get().toString()+": "+sqlText);
<del> //long time = System.currentTimeMillis();
<ide> resultSet = sqlStatement.executeQuery(sqlText);
<del> //long interval = System.currentTimeMillis() - time;
<del> //timeExecuteQuery += interval;
<del> //System.out.println("executeQuery: "+interval+"ms sum "+timeExecuteQuery+"ms");
<ide>
<ide> resultSetHandler.run(resultSet);
<ide>
<ide> sqlStatement.close();
<ide> sqlStatement = null;
<ide> }
<add> if(log)
<add> log(logStart, sqlText);
<ide>
<ide> if(makeStatementInfo)
<ide> return makeStatementInfo(statement, connection);
<ide> {
<ide> // TODO: use prepared statements and reuse the statement.
<ide> final String sqlText = statement.getText();
<del> //System.err.println(Transaction.get().toString()+": "+statement.getText());
<add> final long logStart = log ? System.currentTimeMillis() : 0;
<ide> sqlStatement = connection.createStatement();
<ide> final int rows = sqlStatement.executeUpdate(sqlText);
<add> if(log)
<add> log(logStart, sqlText);
<ide>
<ide> //System.out.println("("+rows+"): "+statement.getText());
<ide> if(rows!=expectedRows)
<ide> append(table.protectedID);
<ide>
<ide> final CountResultSetHandler handler = new CountResultSetHandler();
<del> final long logStart = log ? System.currentTimeMillis() : 0;
<ide> executeSQLQuery(connection, bf, handler, false);
<del> if(log)
<del> log(logStart, bf);
<ide> return handler.result;
<ide> }
<ide>
<ide> append(table.protectedID);
<ide>
<ide> final NextPKResultSetHandler handler = new NextPKResultSetHandler();
<del> final long logStart = log ? System.currentTimeMillis() : 0;
<ide> executeSQLQuery(connection, bf, handler, false);
<del> if(log)
<del> log(logStart, bf);
<ide> return handler.result;
<ide> }
<ide> |
|
Java | apache-2.0 | f29b9e84f2993cbd40001418ac5bc3eed1534dab | 0 | Shabirmean/carbon-device-mgt,madawas/carbon-device-mgt,milanperera/carbon-device-mgt,sameeragunarathne/carbon-device-mgt,madhawap/carbon-device-mgt,prithvi66/carbon-device-mgt,wso2/carbon-device-mgt,DimalChandrasiri/carbon-device-mgt,pasindujw/carbon-device-mgt,GDLMadushanka/carbon-device-mgt,pasindujw/carbon-device-mgt,GDLMadushanka/carbon-device-mgt,chathurace/carbon-device-mgt,Jasintha/carbon-device-mgt,Megala21/carbon-device-mgt,madhawap/carbon-device-mgt,menakaj/carbon-device-mgt,prithvi66/carbon-device-mgt,dilee/carbon-device-mgt,Jasintha/carbon-device-mgt,madawas/carbon-device-mgt,sinthuja/carbon-device-mgt,milanperera/carbon-device-mgt,sinthuja/carbon-device-mgt,geethkokila/carbon-device-mgt,prithvi66/carbon-device-mgt,hasuniea/carbon-device-mgt,Supun94/carbon-device-mgt,Supun94/carbon-device-mgt,Kamidu/carbon-device-mgt,chathurace/carbon-device-mgt,DimalChandrasiri/carbon-device-mgt,dilee/carbon-device-mgt,hasuniea/carbon-device-mgt,pasindujw/carbon-device-mgt,GDLMadushanka/carbon-device-mgt,madawas/carbon-device-mgt,chathurace/carbon-device-mgt,hasuniea/carbon-device-mgt,rasika90/carbon-device-mgt,charithag/carbon-device-mgt,charithag/carbon-device-mgt,wso2/carbon-device-mgt,rasika/carbon-device-mgt,rasika90/carbon-device-mgt,geethkokila/carbon-device-mgt,geethkokila/carbon-device-mgt,harshanL/carbon-device-mgt,sinthuja/carbon-device-mgt,harshanL/carbon-device-mgt,menakaj/carbon-device-mgt,charithag/carbon-device-mgt,rasika/carbon-device-mgt,sameeragunarathne/carbon-device-mgt,Supun94/carbon-device-mgt,milanperera/carbon-device-mgt,wso2/carbon-device-mgt,ruwany/carbon-device-mgt,rasika90/carbon-device-mgt,sameeragunarathne/carbon-device-mgt,Megala21/carbon-device-mgt,Kamidu/carbon-device-mgt,Megala21/carbon-device-mgt,Kamidu/carbon-device-mgt,rasika/carbon-device-mgt,Shabirmean/carbon-device-mgt,DimalChandrasiri/carbon-device-mgt,harshanL/carbon-device-mgt,Shabirmean/carbon-device-mgt,madhawap/carbon-device-mgt,menakaj/carbon-device-mgt,Jasintha/carbon-device-mgt,ruwany/carbon-device-mgt,dilee/carbon-device-mgt,ruwany/carbon-device-mgt | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.ActivityList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.ActivityInfoProviderService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.validation.constraints.Size;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Path("/activities")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ActivityProviderServiceImpl implements ActivityInfoProviderService {
private static final Log log = LogFactory.getLog(ActivityProviderServiceImpl.class);
@GET
@Override
@Path("/{id}")
public Response getActivity(@PathParam("id")
@Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
Activity activity;
DeviceManagementProviderService dmService;
try {
RequestValidationUtil.validateActivityId(id);
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activity = dmService.getOperationByActivityId(id);
if (activity == null) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " +
"found upon the provided activity id '" + id + "'").build()).build();
}
return Response.status(Response.Status.OK).entity(activity).build();
} catch (OperationManagementException e) {
String msg = "ErrorResponse occurred while fetching the activity for the supplied id.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@GET
@Override
public Response getActivities(@QueryParam("since") String since, @QueryParam("offset") int offset,
@QueryParam("limit") int limit,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
long ifModifiedSinceTimestamp;
long sinceTimestamp;
long timestamp = 0;
boolean isIfModifiedSinceSet = false;
boolean isSinceSet = false;
RequestValidationUtil.validatePaginationParameters(offset, limit);
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
Date ifSinceDate;
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
try {
ifSinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"Invalid date string is provided in 'If-Modified-Since' header").build()).build();
}
ifModifiedSinceTimestamp = ifSinceDate.getTime();
isIfModifiedSinceSet = true;
timestamp = ifModifiedSinceTimestamp / 1000;
} else if (since != null && !since.isEmpty()) {
Date sinceDate;
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"Invalid date string is provided in 'since' filter").build()).build();
}
sinceTimestamp = sinceDate.getTime();
isSinceSet = true;
timestamp = sinceTimestamp / 1000;
}
List<Activity> activities;
ActivityList activityList = new ActivityList();
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activities = dmService.getActivitiesUpdatedAfter(timestamp, limit, offset);
activityList.setList(activities);
int count = dmService.getActivityCountUpdatedAfter(timestamp);
activityList.setCount(count);
if (activities == null || activities.size() == 0) {
if (isIfModifiedSinceSet) {
return Response.notModified().build();
}
}
return Response.ok().entity(activityList).build();
} catch (OperationManagementException e) {
String msg
= "ErrorResponse occurred while fetching the activities updated after given time stamp.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
}
| components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.ActivityList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.ActivityInfoProviderService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.validation.constraints.Size;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Path("/activities")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ActivityProviderServiceImpl implements ActivityInfoProviderService {
private static final Log log = LogFactory.getLog(ActivityProviderServiceImpl.class);
@GET
@Override
@Path("/{id}")
public Response getActivity(@PathParam("id")
@Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
Activity activity;
DeviceManagementProviderService dmService;
try {
RequestValidationUtil.validateActivityId(id);
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activity = dmService.getOperationByActivityId(id);
if (activity == null) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " +
"found upon the provided activity id '" + id + "'").build()).build();
}
return Response.status(Response.Status.OK).entity(activity).build();
} catch (OperationManagementException e) {
String msg = "ErrorResponse occurred while fetching the activity for the supplied id.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@GET
@Override
public Response getActivities(@QueryParam("since") String since, @QueryParam("offset") int offset,
@QueryParam("limit") int limit,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
long ifModifiedSinceTimestamp;
long sinceTimestamp;
long timestamp = 0;
boolean isIfModifiedSinceSet = false;
boolean isSinceSet = false;
RequestValidationUtil.validatePaginationParameters(offset, limit);
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
Date ifSinceDate;
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
try {
ifSinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"Invalid date string is provided in 'If-Modified-Since' header").build()).build();
}
ifModifiedSinceTimestamp = ifSinceDate.getTime();
isIfModifiedSinceSet = true;
timestamp = ifModifiedSinceTimestamp / 1000;
} else if (since != null && !since.isEmpty()) {
Date sinceDate;
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"Invalid date string is provided in 'since' filter").build()).build();
}
sinceTimestamp = sinceDate.getTime();
isSinceSet = true;
timestamp = sinceTimestamp / 1000;
}
List<Activity> activities;
ActivityList activityList = new ActivityList();
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activities = dmService.getActivitiesUpdatedAfter(timestamp, limit, offset);
activityList.setList(activities);
int count = dmService.getActivityCountUpdatedAfter(timestamp);
activityList.setCount(count);
if (activities == null || activities.size() == 0) {
if (isIfModifiedSinceSet || isSinceSet) {
return Response.notModified().build();
}
}
return Response.ok().entity(activityList).build();
} catch (OperationManagementException e) {
String msg
= "ErrorResponse occurred while fetching the activities updated after given time stamp.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
}
| Fixed 200 returns when activities are empty and since is a future date
| components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java | Fixed 200 returns when activities are empty and since is a future date | <ide><path>omponents/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java
<ide> int count = dmService.getActivityCountUpdatedAfter(timestamp);
<ide> activityList.setCount(count);
<ide> if (activities == null || activities.size() == 0) {
<del> if (isIfModifiedSinceSet || isSinceSet) {
<add> if (isIfModifiedSinceSet) {
<ide> return Response.notModified().build();
<ide> }
<ide> } |
|
Java | mit | d79c969bc9a7c8318d384c5b6a92c09bf419f5a0 | 0 | roccobarbi/predatorieprede02 | package predatorieprede02;
public class LinkedPredatore extends LinkedOrganism {
// Private fields
private Predatore self; // Overloaded
// Accessors
/**
* @return the self
*/
public Predatore getSelf() {
return self;
}
/**
* @param self the self to set
*/
private void setSelf(Predatore self) {
if(self instanceof Predatore) // To avoid that a null value overwrites a legitimate one
this.self = self;
}
// Constructors
public LinkedPredatore() {
this(null, -1, -1, null); // Negative positions imply that the organism hasn't been placed on the field
}
public LinkedPredatore(Predatore predatore, int posX, int posY, PlayingField field){
this(predatore, posX, posY, field, null);
}
public LinkedPredatore(Predatore predatore, int posX, int posY, PlayingField field, LinkedOrganisms list) {
super(predatore, posX, posY, field, list);
setSelf(predatore);
}
// Public methods
/**
* Chooses a move, changes the position accordingly and updates the field.
* After the move, if this is appropriate, it spawns a new Predatore.
* If the Predatore dies of starvation, it removes the LinkedPredatore from the field and from the list.
* @throws Exception Invalid move. This is a critical error and it should cause the program to stop.
*/
public void act() throws Exception{
Organismo [] grid;
int posX = getPosX(), posY = getPosY();
int dest, newX = posX, newY = posY;
Predatore pup;
LinkedPredatore lPup;
PlayingField field = getField();
// Move
grid = field.lookAround(posX, posY);
dest = self.chooseMove(grid);
//for(int i = 0; i < grid.length; i++) System.out.println(grid[i]); // DEBUG: remove after debugging
if(dest > -1){
//System.out.println(dest + " : " + grid[dest]); // DEBUG: remove after debugging
switch(dest){
case 1:
newY--;
break;
case 3:
newX++;
break;
case 5:
newY++;
break;
case 7:
newX--;
break;
default:
throw new Exception("Invalid move: " + dest + "! Should have been 1, 3, 5 or 7.");
}
if(field.getOccupant(newX, newY) == null){
field.move(posX, posY, newX, newY);
setPosX(newX);
setPosY(newY);
} else if(field.getOccupant(newX, newY).reveal() instanceof Preda){
field.getOccupant(newX, newY).kill();
field.move(posX, posY, newX, newY);
setPosX(newX);
setPosY(newY);
} else {
throw new Exception("Invalid move: " + dest + " is not an instance of Preda!");
}
}
if (!self.getIsAlive()) { // If the beast is dead, it kills the beast
kill();
}
// Spawn
grid = field.lookAround(posX, posY);
dest = self.chooseSpawn(grid);
if(dest > -1){
switch(dest){
case 1:
newY--;
break;
case 3:
newX++;
break;
case 5:
newY++;
break;
case 7:
newX--;
break;
default:
throw new Exception("Invalid spawn: " + dest + "! Should have been 1, 3, 5 or 7.");
}
pup = self.copy();
lPup = new LinkedPredatore(pup, newX, newY, field);
getList().add(lPup);
field.spawn(newX, newY, lPup);
}
}
/**
* Outputs a safe copy of the occupant.
* @return a Predatore that is an exact copy of the occupant
*/
public Predatore reveal(){ // Overloaded to be sure that the type is right
return self.copy();
}
}
| src/predatorieprede02/LinkedPredatore.java | package predatorieprede02;
public class LinkedPredatore extends LinkedOrganism {
// Private fields
private Predatore self; // Overloaded
// Accessors
/**
* @return the self
*/
public Predatore getSelf() {
return self;
}
/**
* @param self the self to set
*/
private void setSelf(Predatore self) {
if(self instanceof Predatore) // To avoid that a null value overwrites a legitimate one
this.self = self;
}
// Constructors
public LinkedPredatore() {
this(null, -1, -1, null); // Negative positions imply that the organism hasn't been placed on the field
}
public LinkedPredatore(Predatore predatore, int posX, int posY, PlayingField field){
this(predatore, posX, posY, field, null);
}
public LinkedPredatore(Predatore predatore, int posX, int posY, PlayingField field, LinkedOrganisms list) {
super(predatore, posX, posY, field, list);
setSelf(predatore);
}
// Public methods
/**
* Chooses a move, changes the position accordingly and updates the field.
* After the move, if this is appropriate, it spawns a new Predatore.
* If the Predatore dies of starvation, it removes the LinkedPredatore from the field and from the list.
* @throws Exception Invalid move. This is a critical error and it should cause the program to stop.
*/
public void act() throws Exception{
Organismo [] grid;
int posX = getPosX(), posY = getPosY();
int dest, newX = posX, newY = posY;
Predatore pup;
LinkedPredatore lPup;
PlayingField field = getField();
// Move
grid = field.lookAround(posX, posY);
dest = self.chooseMove(grid);
if(dest > -1){
System.out.println(dest + " : " + grid[dest]); // DEBUG: remove after debugging
switch(dest){
case 1:
newY--;
break;
case 3:
newX++;
break;
case 5:
newY++;
break;
case 7:
newX--;
break;
default:
throw new Exception("Invalid move: " + dest + "! Should have been 1, 3, 5 or 7.");
}
if(field.getOccupant(newX, newY) == null){
field.move(posX, posY, newX, newY);
setPosX(newX);
setPosY(newY);
} else if(field.getOccupant(newX, newY).reveal() instanceof Preda){
field.getOccupant(newX, newY).kill();
field.move(posX, posY, newX, newY);
setPosX(newX);
setPosY(newY);
} else {
throw new Exception("Invalid move: " + dest + " is not an instance of Preda!");
}
}
if (!self.getIsAlive()) { // If the beast is dead, it kills the beast
kill();
}
// Spawn
grid = field.lookAround(posX, posY);
dest = self.chooseSpawn(grid);
if(dest > -1){
switch(dest){
case 1:
newY--;
break;
case 3:
newX++;
break;
case 5:
newY++;
break;
case 7:
newX--;
break;
default:
throw new Exception("Invalid spawn: " + dest + "! Should have been 1, 3, 5 or 7.");
}
pup = self.copy();
lPup = new LinkedPredatore(pup, newX, newY, field);
getList().add(lPup);
field.spawn(newX, newY, lPup);
}
}
/**
* Outputs a safe copy of the occupant.
* @return a Predatore that is an exact copy of the occupant
*/
public Predatore reveal(){ // Overloaded to be sure that the type is right
return self.copy();
}
}
| minor debugging
| src/predatorieprede02/LinkedPredatore.java | minor debugging | <ide><path>rc/predatorieprede02/LinkedPredatore.java
<ide> // Move
<ide> grid = field.lookAround(posX, posY);
<ide> dest = self.chooseMove(grid);
<add> //for(int i = 0; i < grid.length; i++) System.out.println(grid[i]); // DEBUG: remove after debugging
<ide> if(dest > -1){
<del> System.out.println(dest + " : " + grid[dest]); // DEBUG: remove after debugging
<add> //System.out.println(dest + " : " + grid[dest]); // DEBUG: remove after debugging
<ide> switch(dest){
<ide> case 1:
<ide> newY--; |
|
Java | apache-2.0 | 4c90af4050d6c852d80331579b5340d78641af1a | 0 | squirrelala/Rainfall-core,cljohnso/Rainfall-core,squirrelala/Rainfall-core,cschanck/Rainfall-core,cschanck/Rainfall-core,aurbroszniowski/Rainfall-core,cljohnso/Rainfall-core,aurbroszniowski/Rainfall-core | /*
* Copyright 2014 Aurélien Broszniowski
*
* 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.rainfall.reporting;
import io.rainfall.Reporter;
import io.rainfall.statistics.StatisticsHolder;
import io.rainfall.statistics.StatisticsPeek;
import io.rainfall.statistics.StatisticsPeekHolder;
import jsr166e.DoubleAdder;
import org.HdrHistogram.Histogram;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Writer;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.Set;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* @author Aurelien Broszniowski
*/
public class HtmlReporter<E extends Enum<E>> extends Reporter<E> {
private String basedir;
private String averageLatencyFile = "averageLatency.csv";
private String tpsFile = "tps.csv";
private String percentilesFile = "total-percentiles.csv";
private String reportFile;
private final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
private final static String CRLF = System.getProperty("line.separator");
private Calendar calendar = GregorianCalendar.getInstance(TimeZone.getDefault());
private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
public HtmlReporter() {
this("target/rainfall-report");
}
public HtmlReporter(String outputPath) {
try {
this.basedir = new File(outputPath).getAbsoluteFile().getAbsolutePath();
this.reportFile = this.basedir + File.separatorChar + "report.html";
deleteDirectory(new File(this.basedir));
if (jarFile.isFile()) { // Run with JAR file
extractFromJar("/report", this.basedir);
} else {
extractFromPath(new File(HtmlReporter.class.getClass().getResource("/report").toURI()), new File(this.basedir));
}
} catch (URISyntaxException e) {
throw new RuntimeException("Can not read report template");
} catch (IOException e) {
throw new RuntimeException("Can not copy report template");
}
}
private void extractFromPath(final File src, final File dst) throws IOException {
if (src.isDirectory()) {
dst.mkdirs();
String files[] = src.list();
for (String file : files) {
File srcFile = new File(src, file);
File destFile = new File(dst, file);
extractFromPath(srcFile, destFile);
}
} else {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
@Override
public void report(final StatisticsPeekHolder<E> statisticsPeekHolder) {
try {
if (!new File(reportFile).exists()) {
copyReportTemplate(statisticsPeekHolder);
}
StatisticsPeek<E> totalStatisticsPeeks = statisticsPeekHolder.getTotalStatisticsPeeks();
Set<String> keys = statisticsPeekHolder.getStatisticsPeeksNames();
for (String key : keys) {
StatisticsPeek<E> statisticsPeeks = statisticsPeekHolder.getStatisticsPeeks(key);
logPeriodicStats(key, statisticsPeeks, statisticsPeekHolder.getResultsReported());
}
if (totalStatisticsPeeks != null)
logPeriodicStats("total", totalStatisticsPeeks, statisticsPeekHolder.getResultsReported());
} catch (IOException e) {
throw new RuntimeException("Can not write report data");
} catch (URISyntaxException e) {
throw new RuntimeException("Can not write report data");
}
}
@Override
public void summarize(final StatisticsHolder<E> statisticsHolder) {
StringBuilder sb = new StringBuilder();
Enum<E>[] results = statisticsHolder.getResultsReported();
try {
for (Enum<E> result : results) {
Histogram histogram = statisticsHolder.getHistogram(result);
String percentilesFilename = this.basedir + File.separatorChar + getPercentilesFilename(result.name());
PrintStream stream = new PrintStream(new File(percentilesFilename));
try {
histogram.outputPercentileDistribution(stream, 5, 1000000d, true);
} catch (Exception e) {
e.printStackTrace();
}
stream.close();
String mean = "NaN";
try {
mean = "" + histogram.getMean();
} catch (Exception e) {
e.printStackTrace();
}
String maxValue = "NaN";
try {
maxValue = "" + histogram.getMaxValue();
} catch (Exception e) {
e.printStackTrace();
}
sb.append("reportPercentiles('")
.append(getPercentilesFilename(result.name()).substring(0, getPercentilesFilename(result.name()).length() - 4))
.append("', 'Reponse Time percentiles for ").append(result.name())
.append("', '" + mean + "', '" + maxValue)
.append("');").append(CRLF);
}
substituteInFile(new FileInputStream(new File(reportFile)), reportFile, "//!summary!", sb);
} catch (Exception e) {
throw new RuntimeException("Can not report to Html", e);
}
//TODO : put onglets
}
private void logPeriodicStats(String name, StatisticsPeek<E> statisticsPeek, final Enum<E>[] resultsReported) throws IOException {
String avgFilename = this.basedir + File.separatorChar + getAverageLatencyFilename(name);
String tpsFilename = this.basedir + File.separatorChar + getTpsFilename(name);
Writer averageLatencyOutput;
Writer tpsOutput;
averageLatencyOutput = new BufferedWriter(new FileWriter(avgFilename, true));
if (new File(avgFilename).length() == 0)
addHeader(averageLatencyOutput, resultsReported);
tpsOutput = new BufferedWriter(new FileWriter(tpsFilename, true));
if (new File(tpsFilename).length() == 0)
addHeader(tpsOutput, resultsReported);
String timestamp = formatTimestampInNano(statisticsPeek.getTimestamp());
StringBuilder averageLatencySb = new StringBuilder(timestamp);
StringBuilder tpsSb = new StringBuilder(timestamp);
for (Enum<E> result : resultsReported) {
averageLatencySb.append(",")
.append(String.format("%.3f", (statisticsPeek.getPeriodicAverageLatencyInMs(result))));
tpsSb.append(",").append(statisticsPeek.getPeriodicTps(result));
}
averageLatencyOutput.append(averageLatencySb.toString()).append("\n");
tpsOutput.append(tpsSb.toString()).append("\n");
averageLatencyOutput.close();
tpsOutput.close();
}
/**
* extract the subdirectory from a jar on the classpath to {@code writeDirectory}
*
* @param sourceDirectory directory (in a jar on the classpath) to extract
* @param writeDirectory the location to extract to
* @throws IOException if an IO exception occurs
*/
public void extractFromJar(String sourceDirectory, String writeDirectory) throws IOException {
final URL dirURL = getClass().getResource(sourceDirectory);
final String path = sourceDirectory.substring(1);
if ((dirURL != null) && dirURL.getProtocol().equals("jar")) {
final JarURLConnection jarConnection = (JarURLConnection)dirURL.openConnection();
System.out.println("jarConnection is " + jarConnection);
final ZipFile jar = jarConnection.getJarFile();
final Enumeration<? extends ZipEntry> entries = jar.entries(); // gives ALL entries in jar
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
final String name = entry.getName();
// System.out.println( name );
if (!name.startsWith(path)) {
// entry in wrong subdir -- don't copy
continue;
}
final String entryTail = name.substring(path.length());
final File f = new File(writeDirectory + File.separator + entryTail);
if (entry.isDirectory()) {
// if its a directory, create it
final boolean bMade = f.mkdir();
System.out.println((bMade ? " creating " : " unable to create ") + name);
} else {
System.out.println(" writing " + name);
final InputStream is = jar.getInputStream(entry);
final OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
final byte buffer[] = new byte[4096];
int readCount;
// write contents of 'is' to 'os'
while ((readCount = is.read(buffer)) > 0) {
os.write(buffer, 0, readCount);
}
os.close();
is.close();
}
}
} else if (dirURL == null) {
throw new IllegalStateException("can't find " + sourceDirectory + " on the classpath");
} else {
// not a "jar" protocol URL
throw new IllegalStateException("don't know how to handle extracting from " + dirURL);
}
}
private String getTpsFilename(String key) {
return cleanFilename(key) + "-" + this.tpsFile;
}
private String getAverageLatencyFilename(String key) {
return cleanFilename(key) + "-" + this.averageLatencyFile;
}
private String getPercentilesFilename(String result) {
return cleanFilename(result) + "-" + this.percentilesFile;
}
private final static int[] illegalChars = { 34, 60, 62, 124, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 58, 42, 63, 92, 47, '@', '.', '\'', '"', '!', '#', '$',
'%', '^', '&', '*', '(', ')', '\\' };
public String cleanFilename(String filename) {
Arrays.sort(illegalChars);
StringBuilder cleanName = new StringBuilder();
for (int i = 0; i < filename.length(); i++) {
int c = (int)filename.charAt(i);
if (Arrays.binarySearch(illegalChars, c) < 0) {
cleanName.append((char)c);
}
}
return cleanName.toString();
}
private void copyReportTemplate(final StatisticsPeekHolder<E> peek) throws IOException, URISyntaxException {
StringBuilder sb = new StringBuilder();
Set<String> names = peek.getStatisticsPeeksNames();
// Periodic
for (String name : names) {
String tpsFilename = getTpsFilename(name);
sb.append("reportTps('").append(tpsFilename.substring(0, tpsFilename.length() - 4))
.append("', 'Periodic TPS - ").append(name)
.append("');").append(CRLF);
}
sb.append("reportTps('total-tps', 'Periodic Total TPS');").append(CRLF);
for (String key : names) {
String averageLatencyFilename = getAverageLatencyFilename(key);
sb.append("reportResponseTime('")
.append(averageLatencyFilename.substring(0, averageLatencyFilename.length() - 4))
.append("', 'Periodic Reponse Time - ").append(key)
.append("');").append(CRLF);
}
sb.append("reportResponseTime('total-averageLatency', 'Periodic Average Response Time of all entities');")
.append(CRLF);
InputStream in = HtmlReporter.class.getClass().getResourceAsStream("/template/Tps-template.html");
substituteInFile(in, reportFile, "//!report!", sb);
}
/**
* take a StringBuilder and replace a marker inside a file by the content of that StringBuilder.
*
* @param in InputStream of the source file
* @param outputFile the destination file
* @param marker marker String in file to be replace
* @param sb StringBuilder that has the content to put instead of the marker
* @throws IOException
*/
private void substituteInFile(final InputStream in, final String outputFile, final String marker, final StringBuilder sb) throws IOException {
Scanner scanner = new Scanner(in);
StringBuilder fileContents = new StringBuilder();
try {
while (scanner.hasNextLine()) {
fileContents.append(scanner.nextLine()).append(CRLF);
}
} finally {
scanner.close();
}
in.close();
// create template
byte[] replace = fileContents.toString().replace(marker, sb.toString()).getBytes();
OutputStream out = new FileOutputStream(outputFile);
out.write(replace, 0, replace.length);
out.close();
}
private String formatTimestampInNano(final long timestamp) {
calendar.setTime(new Date(timestamp));
return sdf.format(calendar.getTime());
}
private void addHeader(Writer output, Enum[] keys) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("timestamp");
for (Enum key : keys) {
sb.append(",").append(key.name());
}
output.append(sb.toString()).append("\n");
}
private void deleteDirectory(File path) {
if (path == null)
return;
if (path.exists()) {
for (File f : path.listFiles()) {
if (f.isDirectory()) {
deleteDirectory(f);
f.delete();
} else {
f.delete();
}
}
path.delete();
}
}
}
| src/main/java/io/rainfall/reporting/HtmlReporter.java | /*
* Copyright 2014 Aurélien Broszniowski
*
* 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.rainfall.reporting;
import io.rainfall.Reporter;
import io.rainfall.statistics.StatisticsHolder;
import io.rainfall.statistics.StatisticsPeek;
import io.rainfall.statistics.StatisticsPeekHolder;
import jsr166e.DoubleAdder;
import org.HdrHistogram.Histogram;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Writer;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.Set;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* @author Aurelien Broszniowski
*/
public class HtmlReporter<E extends Enum<E>> extends Reporter<E> {
private String basedir;
private String averageLatencyFile = "averageLatency.csv";
private String tpsFile = "tps.csv";
private String percentilesFile = "total-percentiles.csv";
private String reportFile;
private final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
private final static String CRLF = System.getProperty("line.separator");
private Calendar calendar = GregorianCalendar.getInstance(TimeZone.getDefault());
private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
public HtmlReporter() {
this("target/rainfall-report");
}
public HtmlReporter(String outputPath) {
try {
this.basedir = new File(outputPath).getAbsoluteFile().getAbsolutePath();
this.reportFile = this.basedir + File.separatorChar + "report.html";
deleteDirectory(new File(this.basedir));
if (jarFile.isFile()) { // Run with JAR file
extractFromJar("/report", this.basedir);
} else {
extractFromPath(new File(HtmlReporter.class.getClass().getResource("/report").toURI()), new File(this.basedir));
}
} catch (URISyntaxException e) {
throw new RuntimeException("Can not read report template");
} catch (IOException e) {
throw new RuntimeException("Can not copy report template");
}
}
private void extractFromPath(final File src, final File dst) throws IOException {
if (src.isDirectory()) {
dst.mkdirs();
String files[] = src.list();
for (String file : files) {
File srcFile = new File(src, file);
File destFile = new File(dst, file);
extractFromPath(srcFile, destFile);
}
} else {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
@Override
public void report(final StatisticsPeekHolder<E> statisticsPeekHolder) {
try {
if (!new File(reportFile).exists()) {
copyReportTemplate(statisticsPeekHolder);
}
StatisticsPeek<E> totalStatisticsPeeks = statisticsPeekHolder.getTotalStatisticsPeeks();
Set<String> keys = statisticsPeekHolder.getStatisticsPeeksNames();
for (String key : keys) {
StatisticsPeek<E> statisticsPeeks = statisticsPeekHolder.getStatisticsPeeks(key);
logPeriodicStats(key, statisticsPeeks, statisticsPeekHolder.getResultsReported());
}
if (totalStatisticsPeeks != null)
logPeriodicStats("total", totalStatisticsPeeks, statisticsPeekHolder.getResultsReported());
} catch (IOException e) {
throw new RuntimeException("Can not write report data");
} catch (URISyntaxException e) {
throw new RuntimeException("Can not write report data");
}
}
@Override
public void summarize(final StatisticsHolder<E> statisticsHolder) {
StringBuilder sb = new StringBuilder();
Enum<E>[] results = statisticsHolder.getResultsReported();
try {
for (Enum<E> result : results) {
Histogram histogram = statisticsHolder.getHistogram(result);
String percentilesFilename = this.basedir + File.separatorChar + getPercentilesFilename(result.name());
PrintStream stream = new PrintStream(new File(percentilesFilename));
try {
histogram.outputPercentileDistribution(stream, 5, 1000000d, true);
} catch (Exception e) {
e.printStackTrace();
}
stream.close();
String mean = "NaN";
try {
mean = "" + histogram.getMean();
} catch (Exception e) {
e.printStackTrace();
}
String maxValue = "NaN";
try {
maxValue = "" + histogram.getMaxValue();
} catch (Exception e) {
e.printStackTrace();
}
sb.append("reportPercentiles('")
.append(getPercentilesFilename(result.name()).substring(0, getPercentilesFilename(result.name()).length() - 4))
.append("', 'Reponse Time percentiles for ").append(result.name())
.append("', '" + mean + "', '" + maxValue)
.append("');").append(CRLF);
}
substituteInFile(new FileInputStream(new File(reportFile)), reportFile, "//!summary!", sb);
} catch (Exception e) {
throw new RuntimeException("Can not report to Html", e);
}
//TODO : put onglets
}
private void logPeriodicStats(String name, StatisticsPeek<E> statisticsPeek, final Enum<E>[] resultsReported) throws IOException {
String avgFilename = this.basedir + File.separatorChar + getAverageLatencyFilename(name);
String tpsFilename = this.basedir + File.separatorChar + getTpsFilename(name);
Writer averageLatencyOutput;
Writer tpsOutput;
averageLatencyOutput = new BufferedWriter(new FileWriter(avgFilename, true));
if (new File(avgFilename).length() == 0)
addHeader(averageLatencyOutput, resultsReported);
tpsOutput = new BufferedWriter(new FileWriter(tpsFilename, true));
if (new File(tpsFilename).length() == 0)
addHeader(tpsOutput, resultsReported);
String timestamp = formatTimestampInNano(statisticsPeek.getTimestamp());
StringBuilder averageLatencySb = new StringBuilder(timestamp);
StringBuilder tpsSb = new StringBuilder(timestamp);
for (Enum<E> result : resultsReported) {
averageLatencySb.append(",")
.append(String.format("%.2f", (statisticsPeek.getPeriodicAverageLatencyInMs(result))));
tpsSb.append(",").append(statisticsPeek.getPeriodicTps(result));
}
averageLatencyOutput.append(averageLatencySb.toString()).append("\n");
tpsOutput.append(tpsSb.toString()).append("\n");
averageLatencyOutput.close();
tpsOutput.close();
}
/**
* extract the subdirectory from a jar on the classpath to {@code writeDirectory}
*
* @param sourceDirectory directory (in a jar on the classpath) to extract
* @param writeDirectory the location to extract to
* @throws IOException if an IO exception occurs
*/
public void extractFromJar(String sourceDirectory, String writeDirectory) throws IOException {
final URL dirURL = getClass().getResource(sourceDirectory);
final String path = sourceDirectory.substring(1);
if ((dirURL != null) && dirURL.getProtocol().equals("jar")) {
final JarURLConnection jarConnection = (JarURLConnection)dirURL.openConnection();
System.out.println("jarConnection is " + jarConnection);
final ZipFile jar = jarConnection.getJarFile();
final Enumeration<? extends ZipEntry> entries = jar.entries(); // gives ALL entries in jar
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
final String name = entry.getName();
// System.out.println( name );
if (!name.startsWith(path)) {
// entry in wrong subdir -- don't copy
continue;
}
final String entryTail = name.substring(path.length());
final File f = new File(writeDirectory + File.separator + entryTail);
if (entry.isDirectory()) {
// if its a directory, create it
final boolean bMade = f.mkdir();
System.out.println((bMade ? " creating " : " unable to create ") + name);
} else {
System.out.println(" writing " + name);
final InputStream is = jar.getInputStream(entry);
final OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
final byte buffer[] = new byte[4096];
int readCount;
// write contents of 'is' to 'os'
while ((readCount = is.read(buffer)) > 0) {
os.write(buffer, 0, readCount);
}
os.close();
is.close();
}
}
} else if (dirURL == null) {
throw new IllegalStateException("can't find " + sourceDirectory + " on the classpath");
} else {
// not a "jar" protocol URL
throw new IllegalStateException("don't know how to handle extracting from " + dirURL);
}
}
private String getTpsFilename(String key) {
return cleanFilename(key) + "-" + this.tpsFile;
}
private String getAverageLatencyFilename(String key) {
return cleanFilename(key) + "-" + this.averageLatencyFile;
}
private String getPercentilesFilename(String result) {
return cleanFilename(result) + "-" + this.percentilesFile;
}
private final static int[] illegalChars = { 34, 60, 62, 124, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 58, 42, 63, 92, 47, '@', '.', '\'', '"', '!', '#', '$',
'%', '^', '&', '*', '(', ')', '\\' };
public String cleanFilename(String filename) {
Arrays.sort(illegalChars);
StringBuilder cleanName = new StringBuilder();
for (int i = 0; i < filename.length(); i++) {
int c = (int)filename.charAt(i);
if (Arrays.binarySearch(illegalChars, c) < 0) {
cleanName.append((char)c);
}
}
return cleanName.toString();
}
private void copyReportTemplate(final StatisticsPeekHolder<E> peek) throws IOException, URISyntaxException {
StringBuilder sb = new StringBuilder();
Set<String> names = peek.getStatisticsPeeksNames();
// Periodic
for (String name : names) {
String tpsFilename = getTpsFilename(name);
sb.append("reportTps('").append(tpsFilename.substring(0, tpsFilename.length() - 4))
.append("', 'Periodic TPS - ").append(name)
.append("');").append(CRLF);
}
sb.append("reportTps('total-tps', 'Periodic Total TPS');").append(CRLF);
for (String key : names) {
String averageLatencyFilename = getAverageLatencyFilename(key);
sb.append("reportResponseTime('")
.append(averageLatencyFilename.substring(0, averageLatencyFilename.length() - 4))
.append("', 'Periodic Reponse Time - ").append(key)
.append("');").append(CRLF);
}
sb.append("reportResponseTime('total-averageLatency', 'Periodic Average Response Time of all entities');")
.append(CRLF);
InputStream in = HtmlReporter.class.getClass().getResourceAsStream("/template/Tps-template.html");
substituteInFile(in, reportFile, "//!report!", sb);
}
/**
* take a StringBuilder and replace a marker inside a file by the content of that StringBuilder.
*
* @param in InputStream of the source file
* @param outputFile the destination file
* @param marker marker String in file to be replace
* @param sb StringBuilder that has the content to put instead of the marker
* @throws IOException
*/
private void substituteInFile(final InputStream in, final String outputFile, final String marker, final StringBuilder sb) throws IOException {
Scanner scanner = new Scanner(in);
StringBuilder fileContents = new StringBuilder();
try {
while (scanner.hasNextLine()) {
fileContents.append(scanner.nextLine()).append(CRLF);
}
} finally {
scanner.close();
}
in.close();
// create template
byte[] replace = fileContents.toString().replace(marker, sb.toString()).getBytes();
OutputStream out = new FileOutputStream(outputFile);
out.write(replace, 0, replace.length);
out.close();
}
private String formatTimestampInNano(final long timestamp) {
calendar.setTime(new Date(timestamp));
return sdf.format(calendar.getTime());
}
private void addHeader(Writer output, Enum[] keys) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("timestamp");
for (Enum key : keys) {
sb.append(",").append(key.name());
}
output.append(sb.toString()).append("\n");
}
private void deleteDirectory(File path) {
if (path == null)
return;
if (path.exists()) {
for (File f : path.listFiles()) {
if (f.isDirectory()) {
deleteDirectory(f);
f.delete();
} else {
f.delete();
}
}
path.delete();
}
}
}
| added 3rd digit to latencies reporting
| src/main/java/io/rainfall/reporting/HtmlReporter.java | added 3rd digit to latencies reporting | <ide><path>rc/main/java/io/rainfall/reporting/HtmlReporter.java
<ide>
<ide> for (Enum<E> result : resultsReported) {
<ide> averageLatencySb.append(",")
<del> .append(String.format("%.2f", (statisticsPeek.getPeriodicAverageLatencyInMs(result))));
<add> .append(String.format("%.3f", (statisticsPeek.getPeriodicAverageLatencyInMs(result))));
<ide> tpsSb.append(",").append(statisticsPeek.getPeriodicTps(result));
<ide> }
<ide> averageLatencyOutput.append(averageLatencySb.toString()).append("\n"); |
|
Java | apache-2.0 | a3f5561caaf8bc51b1d1b4ef9369f7bc9d5f5717 | 0 | ceruleanotter/feb_5_Sunshine | /*
* Copyright (C) 2014 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 com.example.android.sunshine.app;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.android.sunshine.app.data.WeatherContract;
/**
* Encapsulates fetching the forecast and displaying it as a {@link ListView} layout.
*/
public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int FORECAST_LOADER = 0;
private ForecastAdapter mForecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// The CursorAdapter will take data from our cursor and populate the ListView.
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(FORECAST_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
private void updateWeather() {
FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String location = prefs.getString(getString(R.string.pref_location_key),
getString(R.string.pref_location_default));
weatherTask.execute(location);
}
@Override
public void onStart() {
super.onStart();
updateWeather();
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String locationSetting = prefs.getString(getString(R.string.pref_location_key),
getString(R.string.pref_location_default));
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
locationSetting, System.currentTimeMillis());
return new CursorLoader(getActivity(),
weatherForLocationUri,
null,
null,
null,
sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mForecastAdapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mForecastAdapter.swapCursor(null);
}
}
| app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java | /*
* Copyright (C) 2014 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 com.example.android.sunshine.app;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.android.sunshine.app.data.WeatherContract;
/**
* Encapsulates fetching the forecast and displaying it as a {@link ListView} layout.
*/
public class ForecastFragment extends Fragment {
private ForecastAdapter mForecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String locationSetting = prefs.getString(getString(R.string.pref_location_key),
getString(R.string.pref_location_default));
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
locationSetting, System.currentTimeMillis());
Cursor cur = getActivity().getContentResolver().query(weatherForLocationUri,
null, null, null, sortOrder);
// The CursorAdapter will take data from our cursor and populate the ListView.
// Note that we are using the deprecated FLAG_AUTO_REQUERY. We'll fix this when we
// switch to using Loaders.
mForecastAdapter = new ForecastAdapter(getActivity(), cur, android.support.v4.widget.CursorAdapter.FLAG_AUTO_REQUERY);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
private void updateWeather() {
FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String location = prefs.getString(getString(R.string.pref_location_key),
getString(R.string.pref_location_default));
weatherTask.execute(location);
}
@Override
public void onStart() {
super.onStart();
updateWeather();
}
}
| Updated forecast fragment to use loaders.
| app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java | Updated forecast fragment to use loaders. | <ide><path>pp/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
<ide> import android.os.Bundle;
<ide> import android.preference.PreferenceManager;
<ide> import android.support.v4.app.Fragment;
<add>import android.support.v4.app.LoaderManager;
<add>import android.support.v4.content.CursorLoader;
<add>import android.support.v4.content.Loader;
<ide> import android.view.LayoutInflater;
<ide> import android.view.Menu;
<ide> import android.view.MenuInflater;
<ide> /**
<ide> * Encapsulates fetching the forecast and displaying it as a {@link ListView} layout.
<ide> */
<del>public class ForecastFragment extends Fragment {
<add>public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
<ide>
<add> private static final int FORECAST_LOADER = 0;
<ide> private ForecastAdapter mForecastAdapter;
<ide>
<ide> public ForecastFragment() {
<ide> @Override
<ide> public View onCreateView(LayoutInflater inflater, ViewGroup container,
<ide> Bundle savedInstanceState) {
<del> SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
<del> String locationSetting = prefs.getString(getString(R.string.pref_location_key),
<del> getString(R.string.pref_location_default));
<del>
<del> // Sort order: Ascending, by date.
<del> String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
<del> Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
<del> locationSetting, System.currentTimeMillis());
<del>
<del> Cursor cur = getActivity().getContentResolver().query(weatherForLocationUri,
<del> null, null, null, sortOrder);
<del>
<ide> // The CursorAdapter will take data from our cursor and populate the ListView.
<del> // Note that we are using the deprecated FLAG_AUTO_REQUERY. We'll fix this when we
<del> // switch to using Loaders.
<del> mForecastAdapter = new ForecastAdapter(getActivity(), cur, android.support.v4.widget.CursorAdapter.FLAG_AUTO_REQUERY);
<add> mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
<ide>
<ide> View rootView = inflater.inflate(R.layout.fragment_main, container, false);
<ide>
<ide> listView.setAdapter(mForecastAdapter);
<ide>
<ide> return rootView;
<add> }
<add>
<add> @Override
<add> public void onActivityCreated(Bundle savedInstanceState) {
<add> getLoaderManager().initLoader(FORECAST_LOADER, null, this);
<add> super.onActivityCreated(savedInstanceState);
<ide> }
<ide>
<ide> private void updateWeather() {
<ide> super.onStart();
<ide> updateWeather();
<ide> }
<add>
<add> @Override
<add> public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
<add> SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
<add> String locationSetting = prefs.getString(getString(R.string.pref_location_key),
<add> getString(R.string.pref_location_default));
<add>
<add> // Sort order: Ascending, by date.
<add> String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
<add> Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
<add> locationSetting, System.currentTimeMillis());
<add>
<add> return new CursorLoader(getActivity(),
<add> weatherForLocationUri,
<add> null,
<add> null,
<add> null,
<add> sortOrder);
<add> }
<add>
<add> @Override
<add> public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
<add> mForecastAdapter.swapCursor(cursor);
<add> }
<add>
<add> @Override
<add> public void onLoaderReset(Loader<Cursor> cursorLoader) {
<add> mForecastAdapter.swapCursor(null);
<add> }
<ide> } |
|
Java | bsd-3-clause | b9c49b5aea03710a4a9cb32ad8cf04ef8650e59c | 0 | NCIP/c3pr,NCIP/c3pr,NCIP/c3pr | package edu.duke.cabig.c3pr.domain.factory;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import edu.duke.cabig.c3pr.constants.ContactMechanismType;
import edu.duke.cabig.c3pr.constants.CoordinatingCenterStudyStatus;
import edu.duke.cabig.c3pr.constants.OrganizationIdentifierTypeEnum;
import edu.duke.cabig.c3pr.constants.SiteStudyStatus;
import edu.duke.cabig.c3pr.dao.HealthcareSiteDao;
import edu.duke.cabig.c3pr.dao.ICD9DiseaseSiteDao;
import edu.duke.cabig.c3pr.dao.ParticipantDao;
import edu.duke.cabig.c3pr.dao.StudySubjectDao;
import edu.duke.cabig.c3pr.domain.Arm;
import edu.duke.cabig.c3pr.domain.Consent;
import edu.duke.cabig.c3pr.domain.ContactMechanism;
import edu.duke.cabig.c3pr.domain.Epoch;
import edu.duke.cabig.c3pr.domain.HealthcareSite;
import edu.duke.cabig.c3pr.domain.ICD9DiseaseSite;
import edu.duke.cabig.c3pr.domain.LocalContactMechanism;
import edu.duke.cabig.c3pr.domain.OrganizationAssignedIdentifier;
import edu.duke.cabig.c3pr.domain.Participant;
import edu.duke.cabig.c3pr.domain.ScheduledEpoch;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.StudyDisease;
import edu.duke.cabig.c3pr.domain.StudyInvestigator;
import edu.duke.cabig.c3pr.domain.StudySite;
import edu.duke.cabig.c3pr.domain.StudySubject;
import edu.duke.cabig.c3pr.domain.StudySubjectConsentVersion;
import edu.duke.cabig.c3pr.domain.repository.StudyRepository;
import edu.duke.cabig.c3pr.exception.C3PRCodedException;
import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper;
import edu.duke.cabig.c3pr.service.ParticipantService;
public class StudySubjectFactory {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(StudySubjectFactory.class);
private C3PRExceptionHelper exceptionHelper;
private MessageSource c3prErrorMessages;
private final String prtIdentifierTypeValueStr = "MRN";
private ParticipantService participantService;
private StudyRepository studyRepository;
private StudySubjectDao studySubjectDao;
private ParticipantDao participantDao;
private ICD9DiseaseSiteDao icd9DiseaseSiteDao;
private HealthcareSiteDao healthcareSiteDao;
public void setHealthcareSiteDao(HealthcareSiteDao healthcareSiteDao) {
this.healthcareSiteDao = healthcareSiteDao;
}
public ICD9DiseaseSiteDao getIcd9DiseaseSiteDao() {
return icd9DiseaseSiteDao;
}
public void setIcd9DiseaseSiteDao(ICD9DiseaseSiteDao icd9DiseaseSiteDao) {
this.icd9DiseaseSiteDao = icd9DiseaseSiteDao;
}
public void setParticipantDao(ParticipantDao participantDao) {
this.participantDao = participantDao;
}
public void setStudySubjectDao(StudySubjectDao studySubjectDao) {
this.studySubjectDao = studySubjectDao;
}
public StudySubject buildStudySubject(StudySubject deserializedStudySubject)
throws C3PRCodedException {
StudySubject built = new StudySubject();
StudySite studySite = buildStudySite(deserializedStudySubject.getStudySite(),
buildStudy(deserializedStudySubject.getStudySite().getStudy()));
Participant participant = buildParticipant(deserializedStudySubject.getParticipant());
if (participant.getId() != null) {
StudySubject exampleSS = new StudySubject(true);
exampleSS.setParticipant(participant);
exampleSS.setStudySite(studySite);
List<StudySubject> registrations = studySubjectDao
.searchBySubjectAndStudySite(exampleSS);
if (registrations.size() > 0) {
throw this.exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSUBJECTS_ALREADY_EXISTS.CODE"));
}
}
else {
if (participant.validateParticipant()){ }//participantDao.save(participant);
else {
throw this.exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.SUBJECTS_INVALID_DETAILS.CODE"));
}
}
buildAndAddStudySubjectConsentVersions(built, studySite);
built.setStudySite(studySite);
built.setParticipant(participant);
Epoch epoch = buildEpoch(studySite.getStudy().getEpochs(), deserializedStudySubject
.getScheduledEpoch());
ScheduledEpoch scheduledEpoch = buildScheduledEpoch(deserializedStudySubject
.getScheduledEpoch(), epoch);
built.getScheduledEpochs().add(0, scheduledEpoch);
fillStudySubjectDetails(built, deserializedStudySubject);
return built;
}
public void buildAndAddStudySubjectConsentVersions(StudySubject built,StudySite studySite){
for (Consent consent :studySite.getStudy().getStudyVersion().getConsents()){
StudySubjectConsentVersion studySubjectConsentVersion = new StudySubjectConsentVersion();
studySubjectConsentVersion.setConsent(consent);
built.getStudySubjectStudyVersion().addStudySubjectConsentVersion(studySubjectConsentVersion);
built.getStudySubjectStudyVersion().setStudySiteStudyVersion(studySite.getStudySiteStudyVersion());
studySite.getStudySiteStudyVersion().addStudySubjectStudyVersion(built.getStudySubjectStudyVersion());
}
}
public StudySubject buildReferencedStudySubject(StudySubject deserializedStudySubject)
throws C3PRCodedException {
StudySubject built = new StudySubject();
StudySite studySite = buildStudySite(deserializedStudySubject.getStudySite(),
buildStudy(deserializedStudySubject.getStudySite().getStudy()));
Participant participant = buildParticipant(deserializedStudySubject.getParticipant());
built.setStudySite(studySite);
built.setParticipant(participant);
Epoch epoch = buildEpoch(studySite.getStudy().getEpochs(), deserializedStudySubject
.getScheduledEpoch());
ScheduledEpoch scheduledEpoch = buildScheduledEpoch(deserializedStudySubject
.getScheduledEpoch(), epoch);
built.getScheduledEpochs().add(0, scheduledEpoch);
fillStudySubjectDetails(built, deserializedStudySubject);
return built;
}
public Participant buildParticipant(Participant participant) throws C3PRCodedException {
if (participant.getIdentifiers() == null || participant.getIdentifiers().size() == 0) {
throw exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.MISSING.SUBJECT_IDENTIFIER.CODE"));
}
for (OrganizationAssignedIdentifier organizationAssignedIdentifier : participant
.getOrganizationAssignedIdentifiers()) {
if (organizationAssignedIdentifier.getType().getName().equals(this.prtIdentifierTypeValueStr)) {
List<Participant> paList = participantService
.searchByMRN(organizationAssignedIdentifier);
if (paList.size() > 1) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE.SUBJECTS_SAME_MRN.CODE"),
new String[] { organizationAssignedIdentifier
.getValue() });
}
else if (paList.size() == 1) {
if (logger.isDebugEnabled()) {
logger
.debug("buildParticipant(Participant) - Participant with the same MRN found in the database");
}
Participant temp = paList.get(0);
if (temp.getFirstName().equals(participant.getFirstName())
&& temp.getLastName().equals(participant.getLastName())
&& temp.getBirthDate().getTime() == participant.getBirthDate()
.getTime()) {
return temp;
}
else {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.INVALID.ANOTHER_SUBJECT_SAME_MRN.CODE"),
new String[] { organizationAssignedIdentifier
.getValue() });
}
}
}
}
for (OrganizationAssignedIdentifier organizationAssignedIdentifier : participant
.getOrganizationAssignedIdentifiers()) {
HealthcareSite healthcareSite= healthcareSiteDao.getByPrimaryIdentifier(organizationAssignedIdentifier.getHealthcareSite().getPrimaryIdentifier());
organizationAssignedIdentifier.setHealthcareSite(healthcareSite);
}
// addContactsToParticipant(participant);
return participant;
}
public Study buildStudy(Study study) throws C3PRCodedException {
if (study.getIdentifiers() == null || study.getIdentifiers().size() == 0) {
throw exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.MISSING.STUDY_IDENTIFIER.CODE"));
}
List<Study> studies = null;
OrganizationAssignedIdentifier identifier = null;
for (OrganizationAssignedIdentifier organizationAssignedIdentifier : study
.getOrganizationAssignedIdentifiers()) {
if (organizationAssignedIdentifier.getType().equals(OrganizationIdentifierTypeEnum.COORDINATING_CENTER_IDENTIFIER)) {
identifier = organizationAssignedIdentifier;
studies = studyRepository
.searchByCoOrdinatingCenterId(organizationAssignedIdentifier);
break;
}
}
if (identifier == null) {
throw exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.MISSING.STUDY_COORDINATING_IDENTIFIER.CODE"));
}
if (studies == null) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.STUDY_WITH_IDENTIFIER.CODE"),
new String[] {
identifier.getValue(),
OrganizationIdentifierTypeEnum.COORDINATING_CENTER_IDENTIFIER.getCode() });
}
if (studies.size() == 0) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.STUDY_WITH_IDENTIFIER.CODE"),
new String[] {
identifier.getValue(),
OrganizationIdentifierTypeEnum.COORDINATING_CENTER_IDENTIFIER.getCode() });
}
if (studies.size() > 1) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE.STUDY_SAME_CO_IDENTIFIER.CODE"),
new String[] {
identifier.getValue(),
OrganizationIdentifierTypeEnum.COORDINATING_CENTER_IDENTIFIER.getCode() });
}
if (studies.get(0).getCoordinatingCenterStudyStatus() != CoordinatingCenterStudyStatus.OPEN) {
throw exceptionHelper.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.STUDY_NOT_ACTIVE"), new String[] {
identifier.getHealthcareSite().getPrimaryIdentifier(),
identifier.getValue() });
}
return studies.get(0);
}
public StudySite buildStudySite(StudySite studySite, Study study) throws C3PRCodedException {
for (StudySite temp : study.getStudySites()) {
if (temp.getHealthcareSite().getPrimaryIdentifier().equals(
studySite.getHealthcareSite().getPrimaryIdentifier())) {
if (temp.getSiteStudyStatus() != SiteStudyStatus.ACTIVE) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSITE_NOT_ACTIVE"),
new String[] { temp.getHealthcareSite()
.getPrimaryIdentifier() });
}
return temp;
}
}
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.STUDYSITE_WITH_NCICODE.CODE"),
new String[] { studySite.getHealthcareSite()
.getPrimaryIdentifier() });
}
private Epoch buildEpoch(List<Epoch> epochs, ScheduledEpoch scheduledEpoch)
throws C3PRCodedException {
for (Epoch epochCurr : epochs) {
if (epochCurr.getName().equalsIgnoreCase(scheduledEpoch.getEpoch().getName())) {
return epochCurr;
}
}
throw exceptionHelper.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.EPOCH_NAME.CODE"),
new String[] { scheduledEpoch.getEpoch().getName() });
}
private ScheduledEpoch buildScheduledEpoch(ScheduledEpoch source, Epoch epoch)
throws C3PRCodedException {
ScheduledEpoch scheduledEpoch = null;
ScheduledEpoch scheduledEpochSource = source;
scheduledEpoch = new ScheduledEpoch();
ScheduledEpoch scheduledTreatmentEpoch = scheduledEpoch;
scheduledTreatmentEpoch.setEligibilityIndicator(true);
if (scheduledEpochSource.getScheduledArm() != null
&& scheduledEpochSource.getScheduledArm().getArm() != null
&& scheduledEpochSource.getScheduledArm().getArm()
.getName() != null) {
Arm arm = null;
for (Arm a : (epoch).getArms()) {
if (a.getName().equals(
scheduledEpochSource.getScheduledArm().getArm()
.getName())) {
arm = a;
}
}
if (arm == null) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.ARM_NAME.CODE"),
new String[] {
scheduledEpochSource
.getScheduledArm()
.getArm().getName(),
scheduledEpochSource
.getEpoch()
.getName() });
}
scheduledTreatmentEpoch.getScheduledArms().get(0).setArm(arm);
}
scheduledEpoch.setEpoch(epoch);
scheduledEpoch.setScEpochWorkflowStatus(source.getScEpochWorkflowStatus());
scheduledEpoch.setStratumGroupNumber(source.getStratumGroupNumber());
return scheduledEpoch;
}
private void fillStudySubjectDetails(StudySubject studySubject, StudySubject source){
studySubject.getStudySubjectStudyVersion()
.getStudySubjectConsentVersions().get(0).setInformedConsentSignedDate(source.getStudySubjectStudyVersion()
.getStudySubjectConsentVersions().get(0).getInformedConsentSignedDate());
studySubject.setStartDate(source.getStartDate());
studySubject.setPaymentMethod(source.getPaymentMethod());
studySubject.getIdentifiers().addAll(source.getIdentifiers());
for (OrganizationAssignedIdentifier organizationAssignedIdentifier : studySubject
.getOrganizationAssignedIdentifiers()) {
HealthcareSite healthcareSite= healthcareSiteDao.getByPrimaryIdentifier(organizationAssignedIdentifier.getHealthcareSite().getPrimaryIdentifier());
organizationAssignedIdentifier.setHealthcareSite(healthcareSite);
}
if(source.getTreatingPhysician()!=null){
for(StudyInvestigator studyInvestigator:studySubject.getStudySite().getStudyInvestigators()){
if(studyInvestigator.getHealthcareSiteInvestigator().getInvestigator().getNciIdentifier().equals(source.getTreatingPhysician().getHealthcareSiteInvestigator().getInvestigator().getNciIdentifier())){
studySubject.setTreatingPhysician(studyInvestigator);
break;
}
}
}
if(source.getDiseaseHistory()!=null){
if(source.getDiseaseHistory().getStudyDisease()!=null){
for(StudyDisease studyDisease: studySubject.getStudySite().getStudy().getStudyDiseases()){
if(studyDisease.getDiseaseTerm().getCtepTerm().equals(source.getDiseaseHistory().getStudyDisease().getDiseaseTerm().getCtepTerm())){
studySubject.getDiseaseHistory().setStudyDisease(studyDisease);
break;
}
}
}
if(source.getDiseaseHistory().getIcd9DiseaseSite()!=null){
ICD9DiseaseSite icd9DiseaseSite= icd9DiseaseSiteDao.getByCode(source.getDiseaseHistory().getIcd9DiseaseSite().getCode());
if(icd9DiseaseSite == null){
studySubject.getDiseaseHistory().setOtherPrimaryDiseaseSiteCode(source.getDiseaseHistory().getIcd9DiseaseSite().getName());
studySubject.getDiseaseHistory().setIcd9DiseaseSite(null);
}else{
studySubject.getDiseaseHistory().setIcd9DiseaseSite(icd9DiseaseSite);
}
}
}
/*studySubject.setCctsWorkflowStatus(source.getCctsWorkflowStatus());
studySubject.setMultisiteWorkflowStatus(source.getMultisiteWorkflowStatus());*/
}
// private Participant addContactsToParticipant(Participant participant) {
//
// ContactMechanism contactMechanismEmail = new LocalContactMechanism();
// ContactMechanism contactMechanismPhone = new LocalContactMechanism();
// ContactMechanism contactMechanismFax = new LocalContactMechanism();
// contactMechanismEmail.setType(ContactMechanismType.EMAIL);
// contactMechanismPhone.setType(ContactMechanismType.PHONE);
// contactMechanismFax.setType(ContactMechanismType.Fax);
// participant.addContactMechanism(contactMechanismEmail);
// participant.addContactMechanism(contactMechanismPhone);
// participant.addContactMechanism(contactMechanismFax);
// return participant;
// }
private int getCode(String errortypeString) {
return Integer.parseInt(this.c3prErrorMessages.getMessage(errortypeString, null, null));
}
public void setExceptionHelper(C3PRExceptionHelper exceptionHelper) {
this.exceptionHelper = exceptionHelper;
}
public void setC3prErrorMessages(MessageSource errorMessages) {
c3prErrorMessages = errorMessages;
}
public void setParticipantService(ParticipantService participantService) {
this.participantService = participantService;
}
public void setStudyRepository(StudyRepository studyRepository) {
this.studyRepository = studyRepository;
}
}
| codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/factory/StudySubjectFactory.java | package edu.duke.cabig.c3pr.domain.factory;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import edu.duke.cabig.c3pr.constants.ContactMechanismType;
import edu.duke.cabig.c3pr.constants.CoordinatingCenterStudyStatus;
import edu.duke.cabig.c3pr.constants.OrganizationIdentifierTypeEnum;
import edu.duke.cabig.c3pr.constants.SiteStudyStatus;
import edu.duke.cabig.c3pr.dao.HealthcareSiteDao;
import edu.duke.cabig.c3pr.dao.ICD9DiseaseSiteDao;
import edu.duke.cabig.c3pr.dao.ParticipantDao;
import edu.duke.cabig.c3pr.dao.StudySubjectDao;
import edu.duke.cabig.c3pr.domain.Arm;
import edu.duke.cabig.c3pr.domain.Consent;
import edu.duke.cabig.c3pr.domain.ContactMechanism;
import edu.duke.cabig.c3pr.domain.Epoch;
import edu.duke.cabig.c3pr.domain.HealthcareSite;
import edu.duke.cabig.c3pr.domain.ICD9DiseaseSite;
import edu.duke.cabig.c3pr.domain.LocalContactMechanism;
import edu.duke.cabig.c3pr.domain.OrganizationAssignedIdentifier;
import edu.duke.cabig.c3pr.domain.Participant;
import edu.duke.cabig.c3pr.domain.ScheduledEpoch;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.StudyDisease;
import edu.duke.cabig.c3pr.domain.StudyInvestigator;
import edu.duke.cabig.c3pr.domain.StudySite;
import edu.duke.cabig.c3pr.domain.StudySubject;
import edu.duke.cabig.c3pr.domain.StudySubjectConsentVersion;
import edu.duke.cabig.c3pr.domain.repository.StudyRepository;
import edu.duke.cabig.c3pr.exception.C3PRCodedException;
import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper;
import edu.duke.cabig.c3pr.service.ParticipantService;
public class StudySubjectFactory {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(StudySubjectFactory.class);
private C3PRExceptionHelper exceptionHelper;
private MessageSource c3prErrorMessages;
private final String prtIdentifierTypeValueStr = "MRN";
private ParticipantService participantService;
private StudyRepository studyRepository;
private StudySubjectDao studySubjectDao;
private ParticipantDao participantDao;
private ICD9DiseaseSiteDao icd9DiseaseSiteDao;
private HealthcareSiteDao healthcareSiteDao;
public void setHealthcareSiteDao(HealthcareSiteDao healthcareSiteDao) {
this.healthcareSiteDao = healthcareSiteDao;
}
public void setAnatomicSiteDao(ICD9DiseaseSiteDao icd9DiseaseSiteDao) {
this.icd9DiseaseSiteDao = icd9DiseaseSiteDao;
}
public void setParticipantDao(ParticipantDao participantDao) {
this.participantDao = participantDao;
}
public void setStudySubjectDao(StudySubjectDao studySubjectDao) {
this.studySubjectDao = studySubjectDao;
}
public StudySubject buildStudySubject(StudySubject deserializedStudySubject)
throws C3PRCodedException {
StudySubject built = new StudySubject();
StudySite studySite = buildStudySite(deserializedStudySubject.getStudySite(),
buildStudy(deserializedStudySubject.getStudySite().getStudy()));
Participant participant = buildParticipant(deserializedStudySubject.getParticipant());
if (participant.getId() != null) {
StudySubject exampleSS = new StudySubject(true);
exampleSS.setParticipant(participant);
exampleSS.setStudySite(studySite);
List<StudySubject> registrations = studySubjectDao
.searchBySubjectAndStudySite(exampleSS);
if (registrations.size() > 0) {
throw this.exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSUBJECTS_ALREADY_EXISTS.CODE"));
}
}
else {
if (participant.validateParticipant()){ }//participantDao.save(participant);
else {
throw this.exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.SUBJECTS_INVALID_DETAILS.CODE"));
}
}
buildAndAddStudySubjectConsentVersions(built, studySite);
built.setStudySite(studySite);
built.setParticipant(participant);
Epoch epoch = buildEpoch(studySite.getStudy().getEpochs(), deserializedStudySubject
.getScheduledEpoch());
ScheduledEpoch scheduledEpoch = buildScheduledEpoch(deserializedStudySubject
.getScheduledEpoch(), epoch);
built.getScheduledEpochs().add(0, scheduledEpoch);
fillStudySubjectDetails(built, deserializedStudySubject);
return built;
}
public void buildAndAddStudySubjectConsentVersions(StudySubject built,StudySite studySite){
for (Consent consent :studySite.getStudy().getStudyVersion().getConsents()){
StudySubjectConsentVersion studySubjectConsentVersion = new StudySubjectConsentVersion();
studySubjectConsentVersion.setConsent(consent);
built.getStudySubjectStudyVersion().addStudySubjectConsentVersion(studySubjectConsentVersion);
built.getStudySubjectStudyVersion().setStudySiteStudyVersion(studySite.getStudySiteStudyVersion());
studySite.getStudySiteStudyVersion().addStudySubjectStudyVersion(built.getStudySubjectStudyVersion());
}
}
public StudySubject buildReferencedStudySubject(StudySubject deserializedStudySubject)
throws C3PRCodedException {
StudySubject built = new StudySubject();
StudySite studySite = buildStudySite(deserializedStudySubject.getStudySite(),
buildStudy(deserializedStudySubject.getStudySite().getStudy()));
Participant participant = buildParticipant(deserializedStudySubject.getParticipant());
built.setStudySite(studySite);
built.setParticipant(participant);
Epoch epoch = buildEpoch(studySite.getStudy().getEpochs(), deserializedStudySubject
.getScheduledEpoch());
ScheduledEpoch scheduledEpoch = buildScheduledEpoch(deserializedStudySubject
.getScheduledEpoch(), epoch);
built.getScheduledEpochs().add(0, scheduledEpoch);
fillStudySubjectDetails(built, deserializedStudySubject);
return built;
}
public Participant buildParticipant(Participant participant) throws C3PRCodedException {
if (participant.getIdentifiers() == null || participant.getIdentifiers().size() == 0) {
throw exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.MISSING.SUBJECT_IDENTIFIER.CODE"));
}
for (OrganizationAssignedIdentifier organizationAssignedIdentifier : participant
.getOrganizationAssignedIdentifiers()) {
if (organizationAssignedIdentifier.getType().getName().equals(this.prtIdentifierTypeValueStr)) {
List<Participant> paList = participantService
.searchByMRN(organizationAssignedIdentifier);
if (paList.size() > 1) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE.SUBJECTS_SAME_MRN.CODE"),
new String[] { organizationAssignedIdentifier
.getValue() });
}
else if (paList.size() == 1) {
if (logger.isDebugEnabled()) {
logger
.debug("buildParticipant(Participant) - Participant with the same MRN found in the database");
}
Participant temp = paList.get(0);
if (temp.getFirstName().equals(participant.getFirstName())
&& temp.getLastName().equals(participant.getLastName())
&& temp.getBirthDate().getTime() == participant.getBirthDate()
.getTime()) {
return temp;
}
else {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.INVALID.ANOTHER_SUBJECT_SAME_MRN.CODE"),
new String[] { organizationAssignedIdentifier
.getValue() });
}
}
}
}
for (OrganizationAssignedIdentifier organizationAssignedIdentifier : participant
.getOrganizationAssignedIdentifiers()) {
HealthcareSite healthcareSite= healthcareSiteDao.getByPrimaryIdentifier(organizationAssignedIdentifier.getHealthcareSite().getPrimaryIdentifier());
organizationAssignedIdentifier.setHealthcareSite(healthcareSite);
}
// addContactsToParticipant(participant);
return participant;
}
public Study buildStudy(Study study) throws C3PRCodedException {
if (study.getIdentifiers() == null || study.getIdentifiers().size() == 0) {
throw exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.MISSING.STUDY_IDENTIFIER.CODE"));
}
List<Study> studies = null;
OrganizationAssignedIdentifier identifier = null;
for (OrganizationAssignedIdentifier organizationAssignedIdentifier : study
.getOrganizationAssignedIdentifiers()) {
if (organizationAssignedIdentifier.getType().equals(OrganizationIdentifierTypeEnum.COORDINATING_CENTER_IDENTIFIER)) {
identifier = organizationAssignedIdentifier;
studies = studyRepository
.searchByCoOrdinatingCenterId(organizationAssignedIdentifier);
break;
}
}
if (identifier == null) {
throw exceptionHelper
.getException(getCode("C3PR.EXCEPTION.REGISTRATION.MISSING.STUDY_COORDINATING_IDENTIFIER.CODE"));
}
if (studies == null) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.STUDY_WITH_IDENTIFIER.CODE"),
new String[] {
identifier.getValue(),
OrganizationIdentifierTypeEnum.COORDINATING_CENTER_IDENTIFIER.getCode() });
}
if (studies.size() == 0) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.STUDY_WITH_IDENTIFIER.CODE"),
new String[] {
identifier.getValue(),
OrganizationIdentifierTypeEnum.COORDINATING_CENTER_IDENTIFIER.getCode() });
}
if (studies.size() > 1) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE.STUDY_SAME_CO_IDENTIFIER.CODE"),
new String[] {
identifier.getValue(),
OrganizationIdentifierTypeEnum.COORDINATING_CENTER_IDENTIFIER.getCode() });
}
if (studies.get(0).getCoordinatingCenterStudyStatus() != CoordinatingCenterStudyStatus.OPEN) {
throw exceptionHelper.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.STUDY_NOT_ACTIVE"), new String[] {
identifier.getHealthcareSite().getPrimaryIdentifier(),
identifier.getValue() });
}
return studies.get(0);
}
public StudySite buildStudySite(StudySite studySite, Study study) throws C3PRCodedException {
for (StudySite temp : study.getStudySites()) {
if (temp.getHealthcareSite().getPrimaryIdentifier().equals(
studySite.getHealthcareSite().getPrimaryIdentifier())) {
if (temp.getSiteStudyStatus() != SiteStudyStatus.ACTIVE) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSITE_NOT_ACTIVE"),
new String[] { temp.getHealthcareSite()
.getPrimaryIdentifier() });
}
return temp;
}
}
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.STUDYSITE_WITH_NCICODE.CODE"),
new String[] { studySite.getHealthcareSite()
.getPrimaryIdentifier() });
}
private Epoch buildEpoch(List<Epoch> epochs, ScheduledEpoch scheduledEpoch)
throws C3PRCodedException {
for (Epoch epochCurr : epochs) {
if (epochCurr.getName().equalsIgnoreCase(scheduledEpoch.getEpoch().getName())) {
return epochCurr;
}
}
throw exceptionHelper.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.EPOCH_NAME.CODE"),
new String[] { scheduledEpoch.getEpoch().getName() });
}
private ScheduledEpoch buildScheduledEpoch(ScheduledEpoch source, Epoch epoch)
throws C3PRCodedException {
ScheduledEpoch scheduledEpoch = null;
ScheduledEpoch scheduledEpochSource = source;
scheduledEpoch = new ScheduledEpoch();
ScheduledEpoch scheduledTreatmentEpoch = scheduledEpoch;
scheduledTreatmentEpoch.setEligibilityIndicator(true);
if (scheduledEpochSource.getScheduledArm() != null
&& scheduledEpochSource.getScheduledArm().getArm() != null
&& scheduledEpochSource.getScheduledArm().getArm()
.getName() != null) {
Arm arm = null;
for (Arm a : (epoch).getArms()) {
if (a.getName().equals(
scheduledEpochSource.getScheduledArm().getArm()
.getName())) {
arm = a;
}
}
if (arm == null) {
throw exceptionHelper
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.ARM_NAME.CODE"),
new String[] {
scheduledEpochSource
.getScheduledArm()
.getArm().getName(),
scheduledEpochSource
.getEpoch()
.getName() });
}
scheduledTreatmentEpoch.getScheduledArms().get(0).setArm(arm);
}
scheduledEpoch.setEpoch(epoch);
scheduledEpoch.setScEpochWorkflowStatus(source.getScEpochWorkflowStatus());
scheduledEpoch.setStratumGroupNumber(source.getStratumGroupNumber());
return scheduledEpoch;
}
private void fillStudySubjectDetails(StudySubject studySubject, StudySubject source){
studySubject.getStudySubjectStudyVersion()
.getStudySubjectConsentVersions().get(0).setInformedConsentSignedDate(source.getStudySubjectStudyVersion()
.getStudySubjectConsentVersions().get(0).getInformedConsentSignedDate());
studySubject.setStartDate(source.getStartDate());
studySubject.setPaymentMethod(source.getPaymentMethod());
studySubject.getIdentifiers().addAll(source.getIdentifiers());
for (OrganizationAssignedIdentifier organizationAssignedIdentifier : studySubject
.getOrganizationAssignedIdentifiers()) {
HealthcareSite healthcareSite= healthcareSiteDao.getByPrimaryIdentifier(organizationAssignedIdentifier.getHealthcareSite().getPrimaryIdentifier());
organizationAssignedIdentifier.setHealthcareSite(healthcareSite);
}
if(source.getTreatingPhysician()!=null){
for(StudyInvestigator studyInvestigator:studySubject.getStudySite().getStudyInvestigators()){
if(studyInvestigator.getHealthcareSiteInvestigator().getInvestigator().getNciIdentifier().equals(source.getTreatingPhysician().getHealthcareSiteInvestigator().getInvestigator().getNciIdentifier())){
studySubject.setTreatingPhysician(studyInvestigator);
break;
}
}
}
if(source.getDiseaseHistory()!=null){
if(source.getDiseaseHistory().getStudyDisease()!=null){
for(StudyDisease studyDisease: studySubject.getStudySite().getStudy().getStudyDiseases()){
if(studyDisease.getDiseaseTerm().getCtepTerm().equals(source.getDiseaseHistory().getStudyDisease().getDiseaseTerm().getCtepTerm())){
studySubject.getDiseaseHistory().setStudyDisease(studyDisease);
break;
}
}
}
if(source.getDiseaseHistory().getIcd9DiseaseSite()!=null){
ICD9DiseaseSite icd9DiseaseSite= icd9DiseaseSiteDao.getByCode(source.getDiseaseHistory().getIcd9DiseaseSite().getCode());
if(icd9DiseaseSite == null){
studySubject.getDiseaseHistory().setOtherPrimaryDiseaseSiteCode(source.getDiseaseHistory().getIcd9DiseaseSite().getName());
studySubject.getDiseaseHistory().setIcd9DiseaseSite(null);
}else{
studySubject.getDiseaseHistory().setIcd9DiseaseSite(icd9DiseaseSite);
}
}
}
/*studySubject.setCctsWorkflowStatus(source.getCctsWorkflowStatus());
studySubject.setMultisiteWorkflowStatus(source.getMultisiteWorkflowStatus());*/
}
// private Participant addContactsToParticipant(Participant participant) {
//
// ContactMechanism contactMechanismEmail = new LocalContactMechanism();
// ContactMechanism contactMechanismPhone = new LocalContactMechanism();
// ContactMechanism contactMechanismFax = new LocalContactMechanism();
// contactMechanismEmail.setType(ContactMechanismType.EMAIL);
// contactMechanismPhone.setType(ContactMechanismType.PHONE);
// contactMechanismFax.setType(ContactMechanismType.Fax);
// participant.addContactMechanism(contactMechanismEmail);
// participant.addContactMechanism(contactMechanismPhone);
// participant.addContactMechanism(contactMechanismFax);
// return participant;
// }
private int getCode(String errortypeString) {
return Integer.parseInt(this.c3prErrorMessages.getMessage(errortypeString, null, null));
}
public void setExceptionHelper(C3PRExceptionHelper exceptionHelper) {
this.exceptionHelper = exceptionHelper;
}
public void setC3prErrorMessages(MessageSource errorMessages) {
c3prErrorMessages = errorMessages;
}
public void setParticipantService(ParticipantService participantService) {
this.participantService = participantService;
}
public void setStudyRepository(StudyRepository studyRepository) {
this.studyRepository = studyRepository;
}
}
| CPR-1478 : added a setter method for icd9DiseaseSiteDao
| codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/factory/StudySubjectFactory.java | CPR-1478 : added a setter method for icd9DiseaseSiteDao | <ide><path>odebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/factory/StudySubjectFactory.java
<ide> this.healthcareSiteDao = healthcareSiteDao;
<ide> }
<ide>
<del> public void setAnatomicSiteDao(ICD9DiseaseSiteDao icd9DiseaseSiteDao) {
<add> public ICD9DiseaseSiteDao getIcd9DiseaseSiteDao() {
<add> return icd9DiseaseSiteDao;
<add> }
<add>
<add> public void setIcd9DiseaseSiteDao(ICD9DiseaseSiteDao icd9DiseaseSiteDao) {
<ide> this.icd9DiseaseSiteDao = icd9DiseaseSiteDao;
<ide> }
<ide> |
|
JavaScript | mpl-2.0 | ed31c81945e5bdc4295e999a95479f25932df51e | 0 | matthewjwein/webextensions-examples,mdn/webextensions-examples,evolighting/webextensions-examples,matthewjwein/webextensions-examples,matthewjwein/webextensions-examples,mdn/webextensions-examples,evolighting/webextensions-examples,evolighting/webextensions-examples,mdn/webextensions-examples | function saveOptions(e) {
browser.storage.local.set({
colour: document.querySelector("#colour").value
});
e.preventDefault();
}
function restoreOptions() {
var gettingItem = browser.storage.local.get('colour');
gettingItem.then((res) => {
document.querySelector("#colour").value = res.colour || 'Firefox red';
});
}
document.addEventListener('DOMContentLoaded', restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);
| favourite-colour/options.js | function saveOptions(e) {
browser.storage.local.set({
colour: document.querySelector("#colour").value
});
}
function restoreOptions() {
var gettingItem = browser.storage.local.get('colour');
gettingItem.then((res) => {
document.querySelector("#colour").value = res.colour || 'Firefox red';
});
}
document.addEventListener('DOMContentLoaded', restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);
| add in prevent default (#173)
| favourite-colour/options.js | add in prevent default (#173) | <ide><path>avourite-colour/options.js
<ide> browser.storage.local.set({
<ide> colour: document.querySelector("#colour").value
<ide> });
<add> e.preventDefault();
<ide> }
<ide>
<ide> function restoreOptions() { |
|
Java | mit | error: pathspec 'src/ctci/_25SPNSchedulingNonPreEmptive.java' did not match any file(s) known to git
| 3f97b244a5a646f4bb2d323cb62e27a44e3b5dba | 1 | darshanhs90/Java-InterviewPrep,darshanhs90/Java-Coding | package ctci;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
/*Implementation of LFU Page Replacement Algorithm*/
public class _25SPNSchedulingNonPreEmptive{
public static void main(String[] args) {
Scanner scanner=new Scanner(new InputStreamReader(System.in));
Integer noOfProcesses=Integer.parseInt(scanner.nextLine());
int arrivalTimeArray[]=new int[noOfProcesses];
int serviceTimeArray[]=new int[noOfProcesses];
String arrivalTimeStringArray[]={"0","2","4","6","8"};//scanner.nextLine().split(",");
String serviceTimeStringArray[]={"3","6","4","5","2"};//scanner.nextLine().split(",");
scanner.close();
for (int i = 0; i < noOfProcesses; i++) {
arrivalTimeArray[i]=Integer.parseInt(arrivalTimeStringArray[i]);
serviceTimeArray[i]=Integer.parseInt(serviceTimeStringArray[i]);
}
float[] outputList=spnScheduler(arrivalTimeArray,serviceTimeArray);
System.out.println(Arrays.toString(outputList));
}
private static float[] spnScheduler(int[] arrivalTimeArray,
int[] serviceTimeArray) {
boolean visited[]=new boolean[arrivalTimeArray.length];
int remainingTimeArray[]=new int[arrivalTimeArray.length];
int finishTimeArray[]=new int[arrivalTimeArray.length];
int turnAroundTimeArray[]=new int[arrivalTimeArray.length];
Arrays.fill(remainingTimeArray,0);
Arrays.fill(visited,false);
int totalServiceTime=0;
for (int i = 0; i < serviceTimeArray.length; i++) {
totalServiceTime+=serviceTimeArray[i];
}
int count=0;
int index=0;
for (int i = 0; i < totalServiceTime; i++) {
if(arrivalTimeArray[count]==i)
{
remainingTimeArray[count]=serviceTimeArray[count];
count=(count==arrivalTimeArray.length-1)?count:(count+1);
}
remainingTimeArray[index]--;
if(remainingTimeArray[index]==0)
{
finishTimeArray[index]=i+1;
turnAroundTimeArray[index]=finishTimeArray[index]-arrivalTimeArray[index];
index=findNextIndex(remainingTimeArray);
}
}
float[] outputArray=new float[arrivalTimeArray.length];
for (int i = 0; i < turnAroundTimeArray.length; i++) {
turnAroundTimeArray[i]=finishTimeArray[i]-arrivalTimeArray[i];
outputArray[i]=(float)turnAroundTimeArray[i]/serviceTimeArray[i];
}
return outputArray;
}
private static int findNextIndex(int[] remainingTimeArray) {
int index=0,min=Integer.MAX_VALUE;
for (int i = 0; i < remainingTimeArray.length; i++) {
if(remainingTimeArray[i]!=0 && remainingTimeArray[i]<min)
{
min=remainingTimeArray[i];
index=i;
}
}
return index;
}
} | src/ctci/_25SPNSchedulingNonPreEmptive.java | Shortest Path Next schdeuler completed | src/ctci/_25SPNSchedulingNonPreEmptive.java | Shortest Path Next schdeuler completed | <ide><path>rc/ctci/_25SPNSchedulingNonPreEmptive.java
<add>package ctci;
<add>
<add>import java.io.InputStreamReader;
<add>import java.util.Arrays;
<add>import java.util.Scanner;
<add>
<add>
<add>/*Implementation of LFU Page Replacement Algorithm*/
<add>public class _25SPNSchedulingNonPreEmptive{
<add>
<add> public static void main(String[] args) {
<add> Scanner scanner=new Scanner(new InputStreamReader(System.in));
<add> Integer noOfProcesses=Integer.parseInt(scanner.nextLine());
<add> int arrivalTimeArray[]=new int[noOfProcesses];
<add> int serviceTimeArray[]=new int[noOfProcesses];
<add> String arrivalTimeStringArray[]={"0","2","4","6","8"};//scanner.nextLine().split(",");
<add> String serviceTimeStringArray[]={"3","6","4","5","2"};//scanner.nextLine().split(",");
<add> scanner.close();
<add> for (int i = 0; i < noOfProcesses; i++) {
<add> arrivalTimeArray[i]=Integer.parseInt(arrivalTimeStringArray[i]);
<add> serviceTimeArray[i]=Integer.parseInt(serviceTimeStringArray[i]);
<add> }
<add> float[] outputList=spnScheduler(arrivalTimeArray,serviceTimeArray);
<add> System.out.println(Arrays.toString(outputList));
<add> }
<add>
<add> private static float[] spnScheduler(int[] arrivalTimeArray,
<add> int[] serviceTimeArray) {
<add> boolean visited[]=new boolean[arrivalTimeArray.length];
<add> int remainingTimeArray[]=new int[arrivalTimeArray.length];
<add> int finishTimeArray[]=new int[arrivalTimeArray.length];
<add> int turnAroundTimeArray[]=new int[arrivalTimeArray.length];
<add>
<add> Arrays.fill(remainingTimeArray,0);
<add> Arrays.fill(visited,false);
<add> int totalServiceTime=0;
<add> for (int i = 0; i < serviceTimeArray.length; i++) {
<add> totalServiceTime+=serviceTimeArray[i];
<add> }
<add> int count=0;
<add> int index=0;
<add> for (int i = 0; i < totalServiceTime; i++) {
<add> if(arrivalTimeArray[count]==i)
<add> {
<add> remainingTimeArray[count]=serviceTimeArray[count];
<add> count=(count==arrivalTimeArray.length-1)?count:(count+1);
<add> }
<add> remainingTimeArray[index]--;
<add> if(remainingTimeArray[index]==0)
<add> {
<add> finishTimeArray[index]=i+1;
<add> turnAroundTimeArray[index]=finishTimeArray[index]-arrivalTimeArray[index];
<add> index=findNextIndex(remainingTimeArray);
<add> }
<add> }
<add> float[] outputArray=new float[arrivalTimeArray.length];
<add> for (int i = 0; i < turnAroundTimeArray.length; i++) {
<add> turnAroundTimeArray[i]=finishTimeArray[i]-arrivalTimeArray[i];
<add> outputArray[i]=(float)turnAroundTimeArray[i]/serviceTimeArray[i];
<add> }
<add> return outputArray;
<add> }
<add>
<add> private static int findNextIndex(int[] remainingTimeArray) {
<add> int index=0,min=Integer.MAX_VALUE;
<add> for (int i = 0; i < remainingTimeArray.length; i++) {
<add> if(remainingTimeArray[i]!=0 && remainingTimeArray[i]<min)
<add> {
<add> min=remainingTimeArray[i];
<add> index=i;
<add> }
<add> }
<add> return index;
<add> }
<add>} |
|
Java | epl-1.0 | 947549b6c26311fecf8e05180e14aebe0d66aa8e | 0 | abstratt/textuml,abstratt/textuml,abstratt/textuml | /*******************************************************************************
* Copyright (c) 2006, 2010 Abstratt Technologies
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Rafael Chaves (Abstratt Technologies) - initial API and implementation
*******************************************************************************/
package com.abstratt.mdd.internal.frontend.textuml;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.runtime.Assert;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.uml2.uml.Action;
import org.eclipse.uml2.uml.Activity;
import org.eclipse.uml2.uml.ActivityNode;
import org.eclipse.uml2.uml.AddStructuralFeatureValueAction;
import org.eclipse.uml2.uml.AddVariableValueAction;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.BehavioralFeature;
import org.eclipse.uml2.uml.BehavioredClassifier;
import org.eclipse.uml2.uml.CallOperationAction;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Clause;
import org.eclipse.uml2.uml.ConditionalNode;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.CreateObjectAction;
import org.eclipse.uml2.uml.DataType;
import org.eclipse.uml2.uml.DestroyObjectAction;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.eclipse.uml2.uml.ExceptionHandler;
import org.eclipse.uml2.uml.InputPin;
import org.eclipse.uml2.uml.InstanceValue;
import org.eclipse.uml2.uml.LinkEndData;
import org.eclipse.uml2.uml.LiteralUnlimitedNatural;
import org.eclipse.uml2.uml.LoopNode;
import org.eclipse.uml2.uml.MultiplicityElement;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.ObjectFlow;
import org.eclipse.uml2.uml.ObjectNode;
import org.eclipse.uml2.uml.Operation;
import org.eclipse.uml2.uml.OutputPin;
import org.eclipse.uml2.uml.Parameter;
import org.eclipse.uml2.uml.ParameterDirectionKind;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.RaiseExceptionAction;
import org.eclipse.uml2.uml.ReadExtentAction;
import org.eclipse.uml2.uml.ReadIsClassifiedObjectAction;
import org.eclipse.uml2.uml.ReadLinkAction;
import org.eclipse.uml2.uml.ReadSelfAction;
import org.eclipse.uml2.uml.ReadStructuralFeatureAction;
import org.eclipse.uml2.uml.ReadVariableAction;
import org.eclipse.uml2.uml.SendSignalAction;
import org.eclipse.uml2.uml.Signal;
import org.eclipse.uml2.uml.StateMachine;
import org.eclipse.uml2.uml.StructuredActivityNode;
import org.eclipse.uml2.uml.TemplateableElement;
import org.eclipse.uml2.uml.TestIdentityAction;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.TypedElement;
import org.eclipse.uml2.uml.UMLPackage;
import org.eclipse.uml2.uml.UMLPackage.Literals;
import org.eclipse.uml2.uml.ValueSpecification;
import org.eclipse.uml2.uml.ValueSpecificationAction;
import org.eclipse.uml2.uml.Variable;
import org.eclipse.uml2.uml.Vertex;
import org.eclipse.uml2.uml.WriteLinkAction;
import com.abstratt.mdd.core.IProblem.Severity;
import com.abstratt.mdd.core.IRepository;
import com.abstratt.mdd.core.Step;
import com.abstratt.mdd.core.UnclassifiedProblem;
import com.abstratt.mdd.core.util.ActivityUtils;
import com.abstratt.mdd.core.util.BasicTypeUtils;
import com.abstratt.mdd.core.util.ClassifierUtils;
import com.abstratt.mdd.core.util.DataTypeUtils;
import com.abstratt.mdd.core.util.FeatureUtils;
import com.abstratt.mdd.core.util.MDDExtensionUtils;
import com.abstratt.mdd.core.util.MDDUtil;
import com.abstratt.mdd.core.util.PackageUtils;
import com.abstratt.mdd.core.util.StateMachineUtils;
import com.abstratt.mdd.core.util.TypeUtils;
import com.abstratt.mdd.frontend.core.CannotModifyADerivedAttribute;
import com.abstratt.mdd.frontend.core.FrontEnd;
import com.abstratt.mdd.frontend.core.InternalProblem;
import com.abstratt.mdd.frontend.core.MissingRequiredArgument;
import com.abstratt.mdd.frontend.core.NotAConcreteClassifier;
import com.abstratt.mdd.frontend.core.NotInAssociation;
import com.abstratt.mdd.frontend.core.OptionalValueExpected;
import com.abstratt.mdd.frontend.core.QueryOperationsMustBeSideEffectFree;
import com.abstratt.mdd.frontend.core.ReadSelfFromStaticContext;
import com.abstratt.mdd.frontend.core.RequiredValueExpected;
import com.abstratt.mdd.frontend.core.ReturnStatementRequired;
import com.abstratt.mdd.frontend.core.ReturnValueNotExpected;
import com.abstratt.mdd.frontend.core.ReturnValueRequired;
import com.abstratt.mdd.frontend.core.TypeMismatch;
import com.abstratt.mdd.frontend.core.UnknownAttribute;
import com.abstratt.mdd.frontend.core.UnknownOperation;
import com.abstratt.mdd.frontend.core.UnknownRole;
import com.abstratt.mdd.frontend.core.UnknownType;
import com.abstratt.mdd.frontend.core.spi.AbortedCompilationException;
import com.abstratt.mdd.frontend.core.spi.AbortedScopeCompilationException;
import com.abstratt.mdd.frontend.core.spi.AbortedStatementCompilationException;
import com.abstratt.mdd.frontend.core.spi.IActivityBuilder;
import com.abstratt.mdd.frontend.textuml.core.TextUMLCore;
import com.abstratt.mdd.frontend.textuml.grammar.analysis.DepthFirstAdapter;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP1;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP2;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP3;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP4;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP5;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltExpressionP0;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP1;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP2;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP3;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP4;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP5;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltUnaryExpressionP0;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAttributeIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ABlockKernel;
import com.abstratt.mdd.frontend.textuml.grammar.node.ABooleanLiteral;
import com.abstratt.mdd.frontend.textuml.grammar.node.ABroadcastSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ACast;
import com.abstratt.mdd.frontend.textuml.grammar.node.ACatchSection;
import com.abstratt.mdd.frontend.textuml.grammar.node.AClassAttributeIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AClassOperationIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AClosure;
import com.abstratt.mdd.frontend.textuml.grammar.node.AClosureOperand;
import com.abstratt.mdd.frontend.textuml.grammar.node.ADestroySpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AElseRestIf;
import com.abstratt.mdd.frontend.textuml.grammar.node.AEmptyExpressionList;
import com.abstratt.mdd.frontend.textuml.grammar.node.AEmptyReturnSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AEmptySet;
import com.abstratt.mdd.frontend.textuml.grammar.node.AEqualsComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.AExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AExpressionListElement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AExpressionSimpleBlockResolved;
import com.abstratt.mdd.frontend.textuml.grammar.node.AExtentIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AFunctionIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AGreaterOrEqualsComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.AGreaterThanComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.AIfClause;
import com.abstratt.mdd.frontend.textuml.grammar.node.AIfStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AIsClassExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALinkIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALinkRole;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALinkSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALiteralOperand;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALoopSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALoopTest;
import com.abstratt.mdd.frontend.textuml.grammar.node.AMinimalTypeIdentifier;
import com.abstratt.mdd.frontend.textuml.grammar.node.ANamedArgument;
import com.abstratt.mdd.frontend.textuml.grammar.node.ANewIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ANotEqualsComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.ANotSameComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.AOperationIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AParenthesisOperand;
import com.abstratt.mdd.frontend.textuml.grammar.node.AQualifiedAssociationTraversal;
import com.abstratt.mdd.frontend.textuml.grammar.node.ARaiseSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ARepeatLoopBody;
import com.abstratt.mdd.frontend.textuml.grammar.node.ARequiredTargetObjectDot;
import com.abstratt.mdd.frontend.textuml.grammar.node.ARootExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASameComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASelfIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASendSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASimpleAssociationTraversal;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASimpleExpressionBlock;
import com.abstratt.mdd.frontend.textuml.grammar.node.AStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATarget;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATernaryExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATrueBoolean;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATryStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATupleComponentValue;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATupleConstructor;
import com.abstratt.mdd.frontend.textuml.grammar.node.AUnlinkSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AValuedReturnSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AVarDecl;
import com.abstratt.mdd.frontend.textuml.grammar.node.AVariableAccess;
import com.abstratt.mdd.frontend.textuml.grammar.node.AWhileLoopBody;
import com.abstratt.mdd.frontend.textuml.grammar.node.AWriteAttributeSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AWriteClassAttributeSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AWriteVariableSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.Node;
import com.abstratt.mdd.frontend.textuml.grammar.node.PAssociationTraversal;
import com.abstratt.mdd.frontend.textuml.grammar.node.PExpressionList;
import com.abstratt.mdd.frontend.textuml.grammar.node.POperand;
import com.abstratt.mdd.frontend.textuml.grammar.node.PTarget;
import com.abstratt.mdd.frontend.textuml.grammar.node.PTypeIdentifier;
import com.abstratt.mdd.frontend.textuml.grammar.node.TAnd;
import com.abstratt.mdd.frontend.textuml.grammar.node.TBangs;
import com.abstratt.mdd.frontend.textuml.grammar.node.TDiv;
import com.abstratt.mdd.frontend.textuml.grammar.node.TElvis;
import com.abstratt.mdd.frontend.textuml.grammar.node.TIs;
import com.abstratt.mdd.frontend.textuml.grammar.node.TLab;
import com.abstratt.mdd.frontend.textuml.grammar.node.TLabEquals;
import com.abstratt.mdd.frontend.textuml.grammar.node.TMinus;
import com.abstratt.mdd.frontend.textuml.grammar.node.TMult;
import com.abstratt.mdd.frontend.textuml.grammar.node.TNot;
import com.abstratt.mdd.frontend.textuml.grammar.node.TOr;
import com.abstratt.mdd.frontend.textuml.grammar.node.TPlus;
import com.abstratt.mdd.frontend.textuml.grammar.node.TQuestion;
import com.abstratt.mdd.frontend.textuml.grammar.node.TTrue;
import com.abstratt.pluginutils.LogUtils;
/**
* This tree visitor will generate the behavioral model for a given input.
*/
public class BehaviorGenerator extends AbstractGenerator {
class DeferredActivity {
private Activity activity;
private Node block;
public DeferredActivity(Activity activity, Node block) {
this.activity = activity;
this.block = block;
}
public Activity getActivity() {
return activity;
}
public Node getBlock() {
return block;
}
}
class OperationInfo {
String operationName;
// operand (target)[, operand (argument)], result (return)
Classifier[] types;
public OperationInfo(int numberOfTypes) {
types = new Classifier[numberOfTypes];
}
}
private IActivityBuilder builder;
private List<DeferredActivity> deferredActivities;
public BehaviorGenerator(SourceCompilationContext<Node> sourceContext) {
super(sourceContext);
deferredActivities = new LinkedList<DeferredActivity>();
builder = FrontEnd.newActivityBuilder(getRepository());
}
/**
* Creates an anonymous activity and returns a reference.
*/
private Activity buildClosure(BehavioredClassifier parent, StructuredActivityNode context, AClosure node) {
Activity newClosure = MDDExtensionUtils.createClosure(parent, context);
// create activity parameters
node.getSimpleSignature().apply(newSignatureProcessor(newClosure));
deferBlockCreation(node.getBlock(), newClosure);
return newClosure;
}
private ValueSpecificationAction buildValueSpecificationAction(ValueSpecification valueSpec, Node node) {
ValueSpecificationAction action = (ValueSpecificationAction) builder.createAction(IRepository.PACKAGE
.getValueSpecificationAction());
try {
action.setValue(valueSpec);
builder.registerOutput(action.createResult(null, valueSpec.getType()));
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
return action;
}
@Override
public void caseAAttributeIdentifierExpression(AAttributeIdentifierExpression node) {
ReadStructuralFeatureAction action = (ReadStructuralFeatureAction) builder.createAction(IRepository.PACKAGE
.getReadStructuralFeatureAction());
final String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
try {
builder.registerInput(action.createObject(null, null));
super.caseAAttributeIdentifierExpression(node);
builder.registerOutput(action.createResult(null, null));
final ObjectNode targetSource = ActivityUtils.getSource(action.getObject());
Classifier targetClassifier = (Classifier) TypeUtils.getTargetType(getRepository(), targetSource, true);
if (targetClassifier == null) {
problemBuilder.addError("Object type not determined for '"
+ ((ATarget) node.getTarget()).getOperand().toString().trim() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
Property attribute = FeatureUtils.findAttribute(targetClassifier, attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addProblem(new UnknownAttribute(targetClassifier.getName(), attributeIdentifier, false),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (attribute.isStatic()) {
problemBuilder.addError("Non-static attribute expected: '" + attributeIdentifier + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setStructuralFeature(attribute);
action.getObject().setType(targetSource.getType());
TypeUtils.copyType(attribute, action.getResult(), targetClassifier);
checkIfTargetIsRequired(node.getTarget(), targetSource);
if (!TypeUtils.isRequiredPin(targetSource) && !TypeUtils.isMultivalued(targetSource))
// it is a tentative access, result must be optional
action.getResult().setLower(0);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
@Override
public void caseAIsClassExpression(AIsClassExpression expressionNode) {
handleBinaryExpression(expressionNode.getOperand1(), expressionNode.getOperator(), expressionNode.getOperand2());
}
@Override
public void caseAAltUnaryExpressionP0(AAltUnaryExpressionP0 node) {
handleUnaryExpression(node.getOperator(), node.getOperand());
}
@Override
public void caseAAltBinaryExpressionP1(AAltBinaryExpressionP1 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
@Override
public void caseAAltBinaryExpressionP2(AAltBinaryExpressionP2 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
@Override
public void caseAAltBinaryExpressionP3(AAltBinaryExpressionP3 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
@Override
public void caseAAltBinaryExpressionP4(AAltBinaryExpressionP4 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
@Override
public void caseAAltBinaryExpressionP5(AAltBinaryExpressionP5 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
private void handleUnaryExpression(Node operator, Node operand) {
final String[] operationName = { null };
boolean[] specialHandling = { false };
operator.apply(new DepthFirstAdapter() {
@Override
public void caseTMinus(TMinus node) {
operationName[0] = "subtract";
}
@Override
public void caseTNot(TNot node) {
operationName[0] = "not";
}
@Override
public void caseTQuestion(TQuestion node) {
operationName[0] = "notNull";
}
public void caseTBangs(TBangs node) {
specialHandling[0] = true;
handleRequiredUnaryOperator(operand);
}
});
if (!specialHandling[0]) {
ensure(operationName[0] != null, operator, () -> new UnclassifiedProblem("Unknown unary operator: " + operator.toString()));
handleUnaryExpressionAsOperation(operator, operand, operationName[0]);
}
}
private void handleBinaryExpression(Node left, Node operator, Node right) {
String[] operationName = { null };
boolean[] specialHandling = { false };
operator.apply(new DepthFirstAdapter() {
@Override
public void caseANotEqualsComparisonOperator(ANotEqualsComparisonOperator node) {
operationName[0] = "notEquals";
}
@Override
public void caseASameComparisonOperator(ASameComparisonOperator node) {
handleSameBinaryOperator(left, right);
specialHandling[0] = true;
}
@Override
public void caseANotSameComparisonOperator(ANotSameComparisonOperator node) {
handleUnaryExpressionAsOperation(node, "not", () -> {
handleSameBinaryOperator(left, right);
return node;
});
specialHandling[0] = true;
}
@Override
public void caseAEqualsComparisonOperator(AEqualsComparisonOperator node) {
operationName[0] = "equals";
}
@Override
public void caseAGreaterOrEqualsComparisonOperator(AGreaterOrEqualsComparisonOperator node) {
operationName[0] = "greaterOrEquals";
}
@Override
public void caseAGreaterThanComparisonOperator(AGreaterThanComparisonOperator node) {
operationName[0] = "greaterThan";
}
@Override
public void caseTIs(TIs node) {
handleIsClassifiedOperator(left, right);
specialHandling[0] = true;
}
@Override
public void caseTElvis(TElvis node) {
handleElvisOperator(left, right);
specialHandling[0] = true;
}
@Override
public void caseTLab(TLab node) {
operationName[0] = "lowerThan";
}
@Override
public void caseTLabEquals(TLabEquals node) {
operationName[0] = "lowerOrEquals";
}
@Override
public void caseTAnd(TAnd node) {
operationName[0] = "and";
}
@Override
public void caseTDiv(TDiv node) {
operationName[0] = "divide";
}
@Override
public void caseTMinus(TMinus node) {
operationName[0] = "subtract";
}
@Override
public void caseTMult(TMult node) {
operationName[0] = "multiply";
}
@Override
public void caseTOr(TOr node) {
operationName[0] = "or";
}
@Override
public void caseTPlus(TPlus node) {
operationName[0] = "add";
}
});
if (!specialHandling[0]) {
ensure(operationName[0] != null, operator, () -> new UnclassifiedProblem("Unknown binary operator: " + operator.toString()));
handleBinaryExpressionAsOperation(left, operator, right, operationName[0]);
}
}
public void handleBinaryExpressionAsOperation(Node operand1, Node operator, Node operand2, String operationName) {
handleBinaryExpressionAsOperation(operator, () -> {
operand1.apply(this);
return operand1;
}, () -> {
operand2.apply(this);
return operand2;
}, operationName);
}
public void handleBinaryExpressionAsOperation(Node contextNode, Supplier<Node> operand1, Supplier<Node> operand2, String operationName) {
CallOperationAction action = (CallOperationAction) builder.createAction(IRepository.PACKAGE
.getCallOperationAction());
try {
// register the target input pin
builder.registerInput(action.createTarget(null, null));
// register the argument input pins
builder.registerInput(action.createArgument(null, null));
// process the target and argument expressions - this will connect
// their output pins to the input pins we just created
Node targetNode = operand1.get();
Node argumentNode = operand2.get();
InputPin target = action.getTarget();
InputPin argument = action.getArguments().get(0);
Type targetType = ActivityUtils.getSource(target).getType();
Type argumentType = ActivityUtils.getSource(argument).getType();
ensure(targetType != null, targetNode, () -> new UnclassifiedProblem("No type information for " + operand1));
ensure(argumentType != null, argumentNode, () -> new UnclassifiedProblem("No type information for " + operand2));
TypeUtils.copyType(ActivityUtils.getSource(target), target);
TypeUtils.copyType(ActivityUtils.getSource(argument), argument);
List<TypedElement> argumentList = Collections.singletonList((TypedElement) argument);
Operation operation = FeatureUtils.findOperation(getRepository(), (Classifier) targetType, operationName,
argumentList, false, true);
if (operation == null)
missingOperation(true, contextNode, (Classifier) targetType, operationName,
argumentList, false);
if (operation.isStatic())
missingOperation(true, contextNode, (Classifier) targetType, operationName, argumentList,
false);
ensure(TypeUtils.isRequired(target) || FeatureUtils.isBasicOperation(operation), contextNode, () ->
new RequiredValueExpected());
List<Parameter> parameters = operation.getOwnedParameters();
if (parameters.size() != 2 && parameters.get(0).getDirection() != ParameterDirectionKind.IN_LITERAL
&& parameters.get(1).getDirection() != ParameterDirectionKind.RETURN_LITERAL) {
problemBuilder.addError("Unexpected signature: '" + operationName + "' in '"
+ target.getType().getQualifiedName() + "'", contextNode);
throw new AbortedStatementCompilationException();
}
// register the result output pin
OutputPin result = action.createResult(null, operation.getType());
builder.registerOutput(result);
result.setLower(Math.min(target.getLower(), operation.getReturnResult().getLower()));
action.setOperation(operation);
fillDebugInfo(action, contextNode.parent());
} finally {
builder.closeAction();
}
checkIncomings(action, contextNode, getBoundElement());
}
private ConditionalNode buildConditionalExpression(Node trueResultNode, Node falseResultNode, Runnable conditionExpressionBuilder) {
return createBlock(IRepository.PACKAGE.getConditionalNode(), true, (ConditionalNode action) -> {
Clause testClause = action.createClause();
createClauseTest(testClause, conditionExpressionBuilder);
createClauseBody(testClause, () -> trueResultNode.apply(this));
Clause elseClause = action.createClause();
createClauseTest(elseClause, () -> buildValueSpecificationAction(MDDUtil.createLiteralBoolean(namespaceTracker.currentPackage(), true), falseResultNode));
createClauseBody(elseClause, () -> falseResultNode.apply(this));
// ensure the test expression is boolean
if (testClause.getDecider().getType() != elseClause.getDecider().getType()) {
reportIncompatibleTypes(trueResultNode.parent(), elseClause.getDecider(), testClause.getDecider());
throw new AbortedStatementCompilationException();
}
OutputPin result = action.createResult(null, null);
OutputPin optionalValueOutput = testClause.getBodyOutputs().get(0);
OutputPin defaultValueOutput = elseClause.getBodyOutputs().get(0);
if (!TypeUtils.isCompatible(getRepository(), defaultValueOutput.getType(), optionalValueOutput.getType(), null)
|| !TypeUtils.isMultiplicityCompatible(optionalValueOutput, defaultValueOutput, false, true)) {
reportIncompatibleTypes(falseResultNode, defaultValueOutput, optionalValueOutput);
throw new AbortedStatementCompilationException();
}
TypeUtils.copyType(optionalValueOutput, result);
result.setLower(Math.max(optionalValueOutput.getLower(), defaultValueOutput.getLower()));
builder.registerOutput(result);
fillDebugInfo(action, trueResultNode.parent());
});
}
private void handleElvisOperator(Node left, Node right) {
ConditionalNode conditional = buildConditionalExpression(left, right, () -> handleUnaryExpressionAsOperation(left, left, "notNull"));
OutputPin mainOutput = conditional.getClauses().get(0).getBodyOutputs().get(0);
ensure(
!TypeUtils.isRequiredPin(mainOutput),
left,
() -> new OptionalValueExpected()
);
MDDExtensionUtils.makeDefaultValueExpression(conditional);
}
@Override
public void caseATernaryExpression(ATernaryExpression node) {
buildConditionalExpression(node.getTrueExpression(), node.getFalseExpression(), () -> node.getCondition().apply(this));
}
private void handleSameBinaryOperator(Node left, Node right) {
TestIdentityAction action = (TestIdentityAction) builder.createAction(IRepository.PACKAGE
.getTestIdentityAction());
try {
builder.registerInput(action.createFirst(null, null));
builder.registerInput(action.createSecond(null, null));
left.apply(this);
right.apply(this);
TypeUtils.copyType(ActivityUtils.getSource(action.getFirst()), action.getFirst());
TypeUtils.copyType(ActivityUtils.getSource(action.getSecond()), action.getSecond());
Classifier expressionType = BasicTypeUtils.findBuiltInType("Boolean");
builder.registerOutput(action.createResult(null, expressionType));
fillDebugInfo(action, left.parent());
} finally {
builder.closeAction();
}
checkIncomings(action, left.parent(), getBoundElement());
}
private void handleRequiredUnaryOperator(Node operand) {
// cast input as required (preserving type information
buildCast(operand, action -> {
InputPin input = action.getStructuredNodeInputs().get(0);
OutputPin output = action.getStructuredNodeOutputs().get(0);
ensure(!TypeUtils.isRequired(input), operand, () -> new OptionalValueExpected());
TypeUtils.copyType(input, output);
output.setLower(1);
});
}
private void handleIsClassifiedOperator(Node left, Node right) {
ReadIsClassifiedObjectAction action = (ReadIsClassifiedObjectAction) builder.createAction(IRepository.PACKAGE
.getReadIsClassifiedObjectAction());
Node parent = left.parent();
try {
if (!(right instanceof AMinimalTypeIdentifier)) {
problemBuilder.addError("A qualified identifier is expected",
right);
throw new AbortedStatementCompilationException();
}
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(right);
Classifier classifier = (Classifier) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
ensure(classifier != null, right, () -> new UnknownType(qualifiedIdentifier));
builder.registerInput(action.createObject(null, null));
left.apply(this);
Classifier expressionType = BasicTypeUtils.findBuiltInType("Boolean");
builder.registerOutput(action.createResult(null, expressionType));
action.setClassifier(classifier);
fillDebugInfo(action, parent);
} finally {
builder.closeAction();
}
checkIncomings(action, parent, getBoundElement());
}
/**
* Blocks can be simple (curly brackets) or wordy (begin...end). Regardless
* the delimiters, the kernel of the block is processed here.
*/
@Override
public void caseABlockKernel(ABlockKernel node) {
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, block -> {
CommentUtils.applyComment(node.getModelComment(), block);
fillDebugInfo(builder.getCurrentBlock(), node);
BehaviorGenerator.super.caseABlockKernel(node);
// isolation determines whether the block should be treated as a
// transaction
Activity currentActivity = builder.getCurrentActivity();
if (!MDDExtensionUtils.isClosure(currentActivity))
if (ActivityUtils.shouldIsolate(builder.getCurrentBlock())) {
builder.getCurrentBlock().setMustIsolate(true);
// if blocks themselves are isolated, the main body does not
// need isolation
ActivityUtils.getBodyNode(currentActivity).setMustIsolate(false);
}
});
}
@Override
public void caseAExpressionSimpleBlockResolved(AExpressionSimpleBlockResolved node) {
createBlock(false, () ->
buildReturnStatement(node.getSimpleExpressionBlock())
);
}
@Override
public void caseAClassAttributeIdentifierExpression(AClassAttributeIdentifierExpression node) {
String typeIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
Classifier targetClassifier = (Classifier) getRepository().findNamedElement(typeIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentNamespace(null));
if (targetClassifier == null) {
problemBuilder.addError("Class reference expected: '" + typeIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute = FeatureUtils.findAttribute(targetClassifier, attributeIdentifier, false, true);
if (attribute != null) {
buildReadStaticStructuralFeature(targetClassifier, attribute, node);
return;
}
if (targetClassifier instanceof Enumeration) {
EnumerationLiteral enumerationValue = ((Enumeration) targetClassifier).getOwnedLiteral(attributeIdentifier);
if (enumerationValue != null) {
InstanceValue valueSpec = (InstanceValue) namespaceTracker.currentPackage().createPackagedElement(null,
IRepository.PACKAGE.getInstanceValue());
valueSpec.setInstance(enumerationValue);
valueSpec.setType(targetClassifier);
buildValueSpecificationAction(valueSpec, node);
return;
}
}
if (targetClassifier instanceof StateMachine) {
Vertex state = StateMachineUtils.getState((StateMachine) targetClassifier, attributeIdentifier);
if (state != null) {
ValueSpecification stateReference = MDDExtensionUtils.buildVertexLiteral(
namespaceTracker.currentPackage(), state);
buildValueSpecificationAction(stateReference, node);
return;
}
}
problemBuilder.addProblem(new UnknownAttribute(targetClassifier.getName(), attributeIdentifier, true),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
private void buildReadStaticStructuralFeature(Classifier targetClassifier, Property attribute,
AClassAttributeIdentifierExpression node) {
ReadStructuralFeatureAction action = (ReadStructuralFeatureAction) builder.createAction(IRepository.PACKAGE
.getReadStructuralFeatureAction());
try {
// // according to UML 2.1 §11.1, "(...) The semantics for static
// features is undefined. (...)"
// // our intepretation is that they are allowed and the input is a
// null value spec
// builder.registerInput(action.createObject(null, null));
// LiteralNull literalNull = (LiteralNull)
// currentPackage().createPackagedElement(null,
// IRepository.PACKAGE.getLiteralNull());
// buildValueSpecificationAction(literalNull, node);
builder.registerOutput(action.createResult(null, targetClassifier));
if (!attribute.isStatic()) {
problemBuilder.addError("Static attribute expected: '" + attribute.getName() + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setStructuralFeature(attribute);
// action.getObject().setType(targetClassifier);
TypeUtils.copyType(attribute, action.getResult(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
@Override
public void caseAClassOperationIdentifierExpression(final AClassOperationIdentifierExpression node) {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(
node.getMinimalTypeIdentifier());
Class targetClassifier = (Class) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClass_(), namespaceTracker.currentPackage());
if (targetClassifier == null) {
problemBuilder.addError("Class reference expected: '" + qualifiedIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
CallOperationAction action = (CallOperationAction) builder.createAction(IRepository.PACKAGE
.getCallOperationAction());
try {
int argumentCount = countElements(node.getExpressionList());
for (int i = 0; i < argumentCount; i++)
builder.registerInput(action.createArgument(null, null));
super.caseAClassOperationIdentifierExpression(node);
// collect sources so we can match the right operation (in
// case of overloading)
List<ObjectNode> sources = new ArrayList<ObjectNode>();
for (InputPin argument : action.getArguments())
sources.add(ActivityUtils.getSource(argument));
String operationName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Operation operation = findOperation(node.getIdentifier(), targetClassifier, operationName,
new ArrayList<TypedElement>(sources), true, true);
if (!operation.isQuery() && !PackageUtils.isModelLibrary(operation.getNearestPackage()))
ensureNotQuery(node);
if (operation.getReturnResult() == null)
ensureTerminal(node.getIdentifier());
action.setOperation(operation);
List<Parameter> inputParameters = FeatureUtils.getInputParameters(operation.getOwnedParameters());
Map<Type, Type> wildcardSubstitutions = FeatureUtils.buildWildcardSubstitutions(new HashMap<Type, Type>(),
inputParameters, sources);
int argumentPos = 0;
for (Parameter current : operation.getOwnedParameters()) {
switch (current.getDirection().getValue()) {
case ParameterDirectionKind.IN:
if (argumentPos == argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
throw new AbortedStatementCompilationException();
}
InputPin argument = action.getArguments().get(argumentPos++);
argument.setName(current.getName());
TypeUtils.copyType(current, argument, targetClassifier);
break;
case ParameterDirectionKind.RETURN:
// there should be only one of these
Assert.isTrue(action.getResults().isEmpty());
OutputPin result = builder.registerOutput(action.createResult(null, null));
TypeUtils.copyType(current, result, targetClassifier);
resolveWildcardTypes(wildcardSubstitutions, current, result);
break;
case ParameterDirectionKind.OUT:
case ParameterDirectionKind.INOUT:
Assert.isTrue(false);
}
}
if (argumentPos != argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
return;
}
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
/**
* In the context of an operation call, copies types from source to target
* for every target that still has a wildcard type.
*
* In the case of a target that is a signature,
*
* @param wildcardSubstitutions
* @param source
* @param target
*/
private void resolveWildcardTypes(Map<Type, Type> wildcardSubstitutions, TypedElement source, TypedElement target) {
if (wildcardSubstitutions.isEmpty())
return;
if (MDDExtensionUtils.isWildcardType(target.getType())) {
Type subbedType = wildcardSubstitutions.get(source.getType());
if (subbedType != null)
target.setType(subbedType);
} else if (MDDExtensionUtils.isSignature(target.getType())) {
List<Parameter> originalSignatureParameters = MDDExtensionUtils.getSignatureParameters(target.getType());
boolean signatureUsesWildcardTypes = false;
for (Parameter parameter : originalSignatureParameters) {
if (MDDExtensionUtils.isWildcardType(parameter.getType())) {
signatureUsesWildcardTypes = true;
break;
}
}
if (signatureUsesWildcardTypes) {
Activity closure = (Activity) ActivityUtils.resolveBehaviorReference((Action) ((OutputPin) source)
.getOwner());
Type resolvedSignature = MDDExtensionUtils.createSignature(namespaceTracker.currentNamespace(null));
for (Parameter closureParameter : closure.getOwnedParameters()) {
Parameter resolvedParameter = MDDExtensionUtils.createSignatureParameter(resolvedSignature,
closureParameter.getName(), closureParameter.getType());
resolvedParameter.setDirection(closureParameter.getDirection());
resolvedParameter.setUpper(closureParameter.getUpper());
}
target.setType(resolvedSignature);
}
}
}
@Override
public void caseAClosureOperand(AClosureOperand node) {
BehavioredClassifier parent = builder.getCurrentActivity();
StructuredActivityNode closureContext = builder.getCurrentBlock();
Activity closure = buildClosure(parent, closureContext, (AClosure) node.getClosure());
buildValueSpecificationAction(
ActivityUtils.buildBehaviorReference(namespaceTracker.currentPackage(), closure, null), node);
}
@Override
public void caseADestroySpecificStatement(ADestroySpecificStatement node) {
final DestroyObjectAction action = (DestroyObjectAction) builder.createAction(IRepository.PACKAGE
.getDestroyObjectAction());
final InputPin object;
try {
object = action.createTarget(null, null);
builder.registerInput(object);
super.caseADestroySpecificStatement(node);
final Type expressionType = ActivityUtils.getSource(object).getType();
object.setType(expressionType);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
@Override
public void caseAElseRestIf(AElseRestIf node) {
// all this gymnastic is to create the always-true test action
ValueSpecificationAction action = buildValueSpecificationAction(MDDUtil.createLiteralBoolean(namespaceTracker.currentPackage(), true), node);
Clause newClause = createClause();
newClause.getTests().add(action);
newClause.setDecider(action.getResult());
createClauseBody(newClause, () -> node.getClauseBody().apply(this));
checkIncomings(action, node.getElse(), getBoundElement());
}
@Override
public void caseAExtentIdentifierExpression(AExtentIdentifierExpression node) {
String classifierName = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
final Classifier classifier = (Classifier) getRepository().findNamedElement(classifierName,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder.addError("Unknown classifier '" + classifierName + "'", node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
ReadExtentAction action = (ReadExtentAction) builder.createAction(IRepository.PACKAGE.getReadExtentAction());
try {
action.setClassifier(classifier);
final OutputPin result = action.createResult(null, classifier);
result.setUpperValue(MDDUtil.createLiteralUnlimitedNatural(namespaceTracker.currentPackage(),
LiteralUnlimitedNatural.UNLIMITED));
result.setIsUnique(true);
builder.registerOutput(result);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
}
// TODO function call temporarily disabled
// /**
// * Processes a function invocation expression. We restrict function
// * invocations to be variable based.
// */
// @Override
// public void
// caseAFunctionIdentifierExpression(AFunctionIdentifierExpression node) {
// DynamicCallBehaviorAction action =
// (DynamicCallBehaviorAction) builder.createAction(MetaPackage.eINSTANCE
// .getDynamicCallBehaviorAction());
// try {
// // register the behavior input pin
// builder.registerInput(action.createBehavior(null, null));
// // register the argument input pins
// int argumentCount = countElements(node.getExpressionList());
// for (int i = 0; i < argumentCount; i++)
// builder.registerInput(action.createArgument(null, null));
// // process the variable and argument expressions - this will connect
// // their output pins to the input pins we just created
// super.caseAFunctionIdentifierExpression(node);
// // match the list of arguments with the behavior parameters
// final Type functionType =
// ActivityUtils.getSource(action.getBehavior()).getType();
// if (!(functionType instanceof Signature)) {
// problemBuilder.addProblem( new TypeMismatch("function type",
// functionType.getName()), node
// .getVariableAccess());
// throw new AbortedStatementCompilationException();
// }
// Signature signature = (Signature) functionType;
// Assert.isNotNull(signature, "Function not found");
// // collect argument types so we can match the right operation (in
// // case of overloading)
// List<ObjectNode> argumentSources = new ArrayList<ObjectNode>();
// for (InputPin argument : action.getArguments())
// argumentSources.add(ActivityUtils.getSource(argument));
// final List<Parameter> inputParameters =
// FeatureUtils.filterParameters(signature.getOwnedParameters(),
// ParameterDirectionKind.IN_LITERAL);
// if (!TypeUtils.isCompatible(getRepository(), argumentSources,
// inputParameters, null)) {
// problemBuilder.addProblem( new UnresolvedSymbol("Unknown function"),
// node.getVariableAccess());
// throw new AbortedStatementCompilationException();
// }
// int argumentPos = 0;
// for (Parameter current : signature.getOwnedParameters()) {
// OutputPin result;
// InputPin argument;
// switch (current.getDirection().getValue()) {
// case ParameterDirectionKind.IN:
// if (argumentPos == argumentCount) {
// problemBuilder.addError("Wrong number of arguments", node.getLParen());
// throw new AbortedStatementCompilationException();
// }
// argument = action.getArguments().get(argumentPos++);
// argument.setName(current.getName());
// TypeUtils.copyType(current, argument);
// break;
// case ParameterDirectionKind.RETURN:
// // there should be only one of these
// result = builder.registerOutput(action.createResult(null, null));
// TypeUtils.copyType(current, result);
// break;
// case ParameterDirectionKind.OUT:
// case ParameterDirectionKind.INOUT:
// Assert.isTrue(false);
// }
// }
// if (argumentPos != argumentCount) {
// problemBuilder.addError("Wrong number of arguments", node.getLParen());
// return;
// }
// // action.getBehavior().setType(targetClassifier);
// fillDebugInfo(action, node);
// } finally {
// builder.closeAction();
// }
// checkIncomings(action, node.getVariableAccess());
// }
@Override
public void caseAIfClause(AIfClause node) {
Clause newClause = createClause();
createClauseTest(newClause, () -> node.getTest().apply(this));
createClauseBody(newClause, () -> node.getClauseBody().apply(this));
}
@Override
public void caseAIfStatement(AIfStatement node) {
createBlock(IRepository.PACKAGE.getConditionalNode(), false, () ->
super.caseAIfStatement(node)
);
}
@Override
public void caseALinkIdentifierExpression(ALinkIdentifierExpression node) {
ReadLinkAction action = (ReadLinkAction) builder.createAction(IRepository.PACKAGE.getReadLinkAction());
try {
InputPin linkEndValue = builder.registerInput(action.createInputValue(null, null));
node.getIdentifierExpression().apply(this);
ObjectNode source = ActivityUtils.getSource(linkEndValue);
Classifier targetClassifier = (Classifier) TypeUtils.getTargetType(getRepository(), source, true);
Property openEnd = parseRole(targetClassifier, node.getAssociationTraversal());
Association association = openEnd.getAssociation();
linkEndValue.setType(targetClassifier);
int openEndIndex = association.getMemberEnds().indexOf(openEnd);
Property fedEnd = association.getMemberEnds().get(1 - openEndIndex);
LinkEndData endData = action.createEndData();
endData.setEnd(fedEnd);
endData.setValue(linkEndValue);
builder.registerOutput(action.createResult(null, openEnd.getType()));
TypeUtils.copyType(openEnd, action.getResult());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getAssociationTraversal(), getBoundElement());
}
private Property parseRole(Classifier sourceType, PAssociationTraversal node) {
return (node instanceof ASimpleAssociationTraversal) ? parseSimpleTraversal(sourceType,
(ASimpleAssociationTraversal) node) : parseQualifiedTraversal(sourceType,
(AQualifiedAssociationTraversal) node);
}
private Property parseSimpleTraversal(Classifier sourceType, ASimpleAssociationTraversal node) {
final String openEndName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property openEnd = sourceType.getAttribute(openEndName, null);
Association association;
if (openEnd == null) {
EList<Association> associations = sourceType.getAssociations();
for (Association current : associations)
if ((openEnd = current.getMemberEnd(openEndName, null)) != null)
break;
if (openEnd == null) {
problemBuilder.addProblem(new UnknownRole(sourceType.getQualifiedName() + NamedElement.SEPARATOR
+ openEndName), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
}
association = openEnd.getAssociation();
if (association == null) {
problemBuilder.addError(openEndName + " is not an association member end", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
return openEnd;
}
private Property parseQualifiedTraversal(Classifier sourceType, AQualifiedAssociationTraversal node) {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(
node.getMinimalTypeIdentifier());
final Association association = (Association) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getAssociation(), namespaceTracker.currentPackage());
if (association == null) {
problemBuilder.addError("Unknown association '" + qualifiedIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
Classifier associated = ClassifierUtils.findUpHierarchy(getRepository(), sourceType, it -> it.getRelationships(IRepository.PACKAGE.getAssociation()).contains(association) ? it : null);
if (associated == null) {
problemBuilder.addProblem(
new NotInAssociation(sourceType.getQualifiedName(), association.getQualifiedName()),
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
final String openEndName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
// XXX implementation limitation: only binary associations are
// supported
Property openEnd = association.getMemberEnd(openEndName, null);
if (openEnd == null) {
problemBuilder.addProblem(new UnknownRole(association.getQualifiedName(), openEndName),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
return openEnd;
}
@Override
public void caseALinkSpecificStatement(ALinkSpecificStatement node) {
buildWriteLinkAction(node, node.getMinimalTypeIdentifier(), IRepository.PACKAGE.getCreateLinkAction());
}
private void buildWriteLinkAction(Node linkStatementNode, Node associationIdentifierNode, EClass linkActionClass) {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(associationIdentifierNode);
final Association association = (Association) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getAssociation(), namespaceTracker.currentPackage());
if (association == null) {
problemBuilder.addError("Unknown association '" + qualifiedIdentifier + "'", associationIdentifierNode);
throw new AbortedStatementCompilationException();
}
final WriteLinkAction action = (WriteLinkAction) builder.createAction(linkActionClass);
try {
linkStatementNode.apply(new DepthFirstAdapter() {
@Override
public void caseALinkRole(ALinkRole node) {
String roleName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property end = association.getMemberEnd(roleName, null);
if (end == null) {
problemBuilder.addProblem(new UnknownRole(association.getQualifiedName(), roleName),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
LinkEndData endData = action.createEndData();
endData.setEnd(end);
InputPin input = action.createInputValue(null, end.getType());
input.setLower(end.getLower());
input.setUpper(end.getUpper());
endData.setValue(input);
builder.registerInput(input);
node.getRootExpression().apply(BehaviorGenerator.this);
}
});
// TODO need to validate that all ends declared have input values,
// no repetitions, etc
fillDebugInfo(action, linkStatementNode);
} finally {
builder.closeAction();
}
checkIncomings(action, linkStatementNode, getBoundElement());
}
@Override
public void caseAFunctionIdentifierExpression(AFunctionIdentifierExpression node) {
String functionName = sourceMiner.getIdentifier(node.getVariableAccess());
problemBuilder.addProblem(new UnclassifiedProblem("Function call not supported yet: " + functionName),
node.getVariableAccess());
throw new AbortedStatementCompilationException();
}
@Override
public void caseALiteralOperand(ALiteralOperand node) {
ValueSpecification value = LiteralValueParser.parseLiteralValue(node.getLiteral(),
namespaceTracker.currentPackage(), problemBuilder);
buildValueSpecificationAction(value, node);
}
@Override
public void caseAEmptySet(AEmptySet node) {
final ValueSpecificationAction action = (ValueSpecificationAction) builder.createAction(IRepository.PACKAGE
.getValueSpecificationAction());
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(
node.getMinimalTypeIdentifier());
Classifier classifier = (Classifier) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder.addProblem(new UnknownType(qualifiedIdentifier), node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
try {
ValueSpecification emptySetValue = MDDExtensionUtils.buildEmptySet(namespaceTracker.currentPackage(), classifier);
action.setValue(emptySetValue);
OutputPin result = action.createResult(null, classifier);
result.setUpperValue(MDDUtil.createLiteralUnlimitedNatural(namespaceTracker.currentPackage(),
LiteralUnlimitedNatural.UNLIMITED));
builder.registerOutput(result);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
@Override
public void caseALoopSpecificStatement(ALoopSpecificStatement node) {
LoopNode loop = (LoopNode) createBlock(IRepository.PACKAGE.getLoopNode(), false, () ->
super.caseALoopSpecificStatement(node)
);
loop.setIsTestedFirst(true);
}
@Override
public void caseALoopTest(ALoopTest node) {
LoopNode currentLoop = (LoopNode) builder.getCurrentBlock();
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, () -> {
super.caseALoopTest(node);
currentLoop.getTests().add(builder.getCurrentBlock());
final OutputPin decider = ActivityUtils.getActionOutputs(builder.getLastRootAction()).get(0);
currentLoop.setDecider(decider);
});
}
@Override
public void caseANewIdentifierExpression(final ANewIdentifierExpression node) {
ensureNotQuery(node);
final CreateObjectAction action = (CreateObjectAction) builder.createAction(IRepository.PACKAGE
.getCreateObjectAction());
try {
super.caseANewIdentifierExpression(node);
final OutputPin output = builder.registerOutput(action.createResult(null, null));
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(
node.getMinimalTypeIdentifier());
Classifier classifier = (Classifier) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder.addError("Unknown classifier '" + qualifiedIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
if (classifier.isAbstract()) {
problemBuilder.addProblem(new NotAConcreteClassifier(qualifiedIdentifier),
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
output.setType(classifier);
action.setClassifier(classifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getNew(), getBoundElement());
}
private void ensureNotQuery(Node node) {
boolean isReadOnly = builder.getCurrentActivity().isReadOnly();
QueryOperationsMustBeSideEffectFree.ensure(!isReadOnly, problemBuilder, node);
}
@Override
public void caseASendSpecificStatement(ASendSpecificStatement node) {
ensureNotQuery(node);
final SendSignalAction action = (SendSignalAction) builder.createAction(IRepository.PACKAGE
.getSendSignalAction());
try {
final String signalIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getSignal());
final Signal signal = this.context.getRepository().findNamedElement(signalIdentifier,
UMLPackage.Literals.SIGNAL, namespaceTracker.currentNamespace(null));
if (signal == null) {
problemBuilder.addError("Unknown signal '" + signalIdentifier + "'", node.getSignal());
throw new AbortedStatementCompilationException();
}
builder.registerInput(action.createTarget(null, null));
node.getTarget().apply(this);
if (node.getNamedArgumentList() != null)
node.getNamedArgumentList().apply(new DepthFirstAdapter() {
@Override
public void caseANamedArgument(ANamedArgument node) {
String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute = FeatureUtils.findAttribute(signal, attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addProblem(
new UnknownAttribute(signal.getName(), attributeIdentifier, false),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
InputPin signalArgument = action.createArgument(attribute.getName(), null);
TypeUtils.copyType(attribute, signalArgument);
builder.registerInput(signalArgument);
node.getExpression().apply(BehaviorGenerator.this);
}
});
for (Property signalAttribute : signal.getAllAttributes())
if (signalAttribute.getLower() == 1 && signalAttribute.getDefaultValue() == null
&& action.getArgument(signalAttribute.getName(), signalAttribute.getType()) == null) {
problemBuilder.addProblem(new MissingRequiredArgument(signalAttribute.getName()), node);
throw new AbortedStatementCompilationException();
}
action.setSignal(signal);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getSignal(), getBoundElement());
}
@Override
public void caseABroadcastSpecificStatement(ABroadcastSpecificStatement node) {
SendSignalAction action = (SendSignalAction) builder.createAction(IRepository.PACKAGE.getSendSignalAction());
try {
super.caseABroadcastSpecificStatement(node);
final String signalIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getSignal());
Signal signal = this.context.getRepository().findNamedElement(signalIdentifier, UMLPackage.Literals.SIGNAL,
namespaceTracker.currentNamespace(null));
if (signal == null) {
problemBuilder.addError("Unknown signal '" + signalIdentifier + "'", node.getSignal());
throw new AbortedStatementCompilationException();
}
action.setSignal(signal);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getSignal(), getBoundElement());
}
// FIXME a lot of duplication between this and
// caseAClassOperationIdentifierExpression
@Override
public void caseAOperationIdentifierExpression(AOperationIdentifierExpression node) {
Classifier targetClassifier = null;
String operationName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
CallOperationAction action = (CallOperationAction) builder.createAction(IRepository.PACKAGE
.getCallOperationAction());
try {
// register the target input pin
builder.registerInput(action.createTarget(null, null));
// register the argument input pins
int argumentCount = countElements(node.getExpressionList());
for (int i = 0; i < argumentCount; i++)
builder.registerInput(action.createArgument(null, null));
// process the target and argument expressions - this will connect
// their output pins to the input pins we just created
super.caseAOperationIdentifierExpression(node);
final ObjectNode targetSource = ActivityUtils.getSource(action.getTarget());
checkIfTargetIsRequired(node.getTarget(), targetSource);
targetClassifier = (Classifier) TypeUtils.getTargetType(getRepository(), targetSource, true);
if (targetClassifier == null) {
problemBuilder.addProblem(new UnclassifiedProblem(Severity.ERROR,
"Could not determine the type of the target"), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
// collect sources so we can match the right operation (in
// case of overloading)
List<TypedElement> sources = new ArrayList<TypedElement>();
for (InputPin argument : action.getArguments()) {
ObjectNode argumentSource = ActivityUtils.getSource(argument);
if (argumentSource == null) {
problemBuilder.addProblem(new UnclassifiedProblem(Severity.ERROR,
"One of the arguments does not produce a result value"), node.getExpressionList());
throw new AbortedStatementCompilationException();
}
sources.add(argumentSource);
}
Operation operation = findOperation(node.getIdentifier(), targetClassifier, operationName, sources, false,
true);
if (!operation.isQuery() && !PackageUtils.isModelLibrary(operation.getNearestPackage()))
ensureNotQuery(node);
if (operation.getReturnResult() == null)
ensureTerminal(node.getIdentifier());
action.setOperation(operation);
List<Parameter> inputParameters = FeatureUtils.getInputParameters(operation.getOwnedParameters());
Map<Type, Type> wildcardSubstitutions = FeatureUtils.buildWildcardSubstitutions(new HashMap<Type, Type>(),
inputParameters, sources);
int argumentPos = 0;
for (Parameter current : operation.getOwnedParameters()) {
OutputPin result;
InputPin argument;
switch (current.getDirection().getValue()) {
case ParameterDirectionKind.IN:
case ParameterDirectionKind.INOUT:
if (argumentPos == argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
throw new AbortedStatementCompilationException();
}
argument = action.getArguments().get(argumentPos++);
argument.setName(current.getName());
TypeUtils.copyType(current, argument, targetClassifier);
break;
case ParameterDirectionKind.RETURN:
// there should be only one of these
Assert.isTrue(action.getResults().isEmpty());
result = builder.registerOutput(action.createResult(null, null));
TypeUtils.copyType(current, result, targetClassifier);
resolveWildcardTypes(wildcardSubstitutions, current, result);
if (!TypeUtils.isRequiredPin(targetSource) && !TypeUtils.isMultivalued(targetSource))
// it is a tentative call, result must be optional
result.setLower(0);
break;
case ParameterDirectionKind.OUT:
Assert.isTrue(false);
}
}
if (argumentPos != argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
return;
}
// set the type of the target input pin using copy type so we
// understand collections
TypeUtils.copyType(targetSource, action.getTarget(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), targetClassifier);
}
private void checkIfTargetIsRequired(PTarget targetNode, final ObjectNode targetSource) {
boolean requiredTargetExpected = sourceMiner.findChild(targetNode, ARequiredTargetObjectDot.class, true) != null;
if (requiredTargetExpected)
ensure(TypeUtils.isRequiredPin(targetSource) || TypeUtils.isMultivalued(targetSource), targetNode, () -> new RequiredValueExpected());
else
ensure(!TypeUtils.isRequiredPin(targetSource) || TypeUtils.isMultivalued(targetSource), targetNode, () -> new OptionalValueExpected());
}
private void ensureTerminal(Node identifierNode) {
if (!builder.isCurrentActionTerminal()) {
String operationName = TextUMLCore.getSourceMiner().getIdentifier(identifierNode);
problemBuilder.addProblem(
new UnclassifiedProblem("Operation " + operationName + " does not have a result"), identifierNode);
throw new AbortedStatementCompilationException();
}
}
@Override
public void caseARaiseSpecificStatement(ARaiseSpecificStatement node) {
final RaiseExceptionAction action = (RaiseExceptionAction) builder.createAction(IRepository.PACKAGE
.getRaiseExceptionAction());
final InputPin exception;
try {
exception = action.createException(null, null);
builder.registerInput(exception);
super.caseARaiseSpecificStatement(node);
final Type exceptionType = ActivityUtils.getSource(exception).getType();
exception.setType(exceptionType);
if (ActivityUtils.findHandler(action, (Classifier) exceptionType, true) == null)
if (!builder.getCurrentActivity().getSpecification().getRaisedExceptions().contains(exceptionType))
problemBuilder.addWarning("Exception '" + exceptionType.getQualifiedName()
+ "' is not declared by operation", node.getRootExpression());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getRaise(), getBoundElement());
// a raise exception action is a final action
ActivityUtils.makeFinal(builder.getCurrentBlock(), action);
}
@Override
public void caseARepeatLoopBody(ARepeatLoopBody node) {
LoopNode currentLoop = (LoopNode) builder.getCurrentBlock();
currentLoop.setIsTestedFirst(false);
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, () -> {
super.caseARepeatLoopBody(node);
currentLoop.getBodyParts().add(builder.getCurrentBlock());
});
}
@Override
public void caseATryStatement(ATryStatement node) {
if (node.getCatchSection() == null && node.getFinallySection() == null) {
problemBuilder.addError("One or both catch and finally sections are required", node.getTry());
throw new AbortedStatementCompilationException();
}
createBlock(false, () -> {
if (node.getCatchSection() != null)
node.getCatchSection().apply(this);
node.getProtectedBlock().apply(this);
});
}
@Override
public void caseACatchSection(ACatchSection node) {
StructuredActivityNode protectedBlock = builder.getCurrentBlock();
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, (handlerBlock) -> {
// declare exception variable
node.getVarDecl().apply(this);
node.getHandlerBlock().apply(this);
Variable exceptionVar = handlerBlock.getVariables().get(0);
ExceptionHandler exceptionHandler = protectedBlock.createHandler();
exceptionHandler.getExceptionTypes().add((Classifier) exceptionVar.getType());
InputPin exceptionInputPin = (InputPin) handlerBlock.createNode(exceptionVar.getName(),
UMLPackage.Literals.INPUT_PIN);
exceptionInputPin.setType(exceptionVar.getType());
exceptionHandler.setExceptionInput(exceptionInputPin);
exceptionHandler.setHandlerBody(handlerBlock);
});
}
@Override
public void caseASelfIdentifierExpression(ASelfIdentifierExpression node) {
ReadSelfAction action = (ReadSelfAction) builder.createAction(IRepository.PACKAGE.getReadSelfAction());
try {
super.caseASelfIdentifierExpression(node);
Activity currentActivity = builder.getCurrentActivity();
while (MDDExtensionUtils.isClosure(currentActivity)) {
// TODO refactor to use ActivityUtils
ActivityNode rootNode = MDDExtensionUtils.getClosureContext(currentActivity);
currentActivity = ActivityUtils.getActionActivity(rootNode);
}
final BehavioralFeature operation = currentActivity.getSpecification();
boolean staticContext = false;
if (operation != null) {
staticContext = operation.isStatic();
} else if (MDDExtensionUtils.isConstraintBehavior(currentActivity)) {
Constraint constraint = MDDExtensionUtils.getBehaviorConstraint(currentActivity);
staticContext = MDDExtensionUtils.isStaticConstraint(constraint);
}
if (staticContext) {
problemBuilder.addProblem(new ReadSelfFromStaticContext(), node);
throw new AbortedStatementCompilationException();
}
Classifier currentClassifier = ActivityUtils.getContext(currentActivity);
if (currentClassifier == null) {
problemBuilder.addProblem(new InternalProblem("Could not determine context"), node);
throw new AbortedStatementCompilationException();
}
OutputPin result = action.createResult(null, currentClassifier);
result.setLower(1);
result.setUpper(1);
builder.registerOutput(result);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getSelf(), getBoundElement());
}
// TODO temporarily disabled during refactor to remove metamodel extensions
// @Override
// public void
// caseASetLiteralIdentifierExpression(ASetLiteralIdentifierExpression node)
// {
// String qualifiedIdentifier =
// Util.parseQualifiedIdentifier(node.getMinimalTypeIdentifier());
// final Classifier classifier =
// (Classifier) getRepository().findNamedElement(qualifiedIdentifier,
// IRepository.PACKAGE.getClassifier(), currentPackage());
// if (classifier == null) {
// problemBuilder.addError("Unknown classifier '" + qualifiedIdentifier +
// "'", node
// .getMinimalTypeIdentifier());
// throw new AbortedStatementCompilationException();
// }
//
// final CollectionLiteral valueSpec =
// (CollectionLiteral) currentPackage().createPackagedElement(null,
// MetaPackage.eINSTANCE.getCollectionLiteral());
// valueSpec.setType(classifier);
// node.apply(new DepthFirstAdapter() {
// @Override
// public void caseASetValue(ASetValue node) {
// // TODO create a value specification and add it to
// ValueSpecification value =
// MDDUtil.createUnlimitedNatural(classifier.getNearestPackage(),
// valueSpec.getValues()
// .size());
// valueSpec.getValues().add(value);
// super.caseASetValue(node);
// }
// });
// ValueSpecificationAction valueSpecAction =
// buildValueSpecificationAction(valueSpec, node);
// final OutputPin outputPin = valueSpecAction.getOutputs().get(0);
// outputPin.setLowerValue(MDDUtil.createUnlimitedNatural(classifier.getNearestPackage(),
// 0));
// outputPin.setUpperValue(MDDUtil.createUnlimitedNatural(classifier.getNearestPackage(),
// null));
// }
@Override
public void caseAStatement(AStatement node) {
try {
super.caseAStatement(node);
processAnnotations(node.getAnnotations(), this.builder.getLastRootAction());
} catch (AbortedStatementCompilationException e) {
// aborted statement compilation...
if (builder.isDebug())
LogUtils.logWarning(TextUMLCore.PLUGIN_ID, null, e);
} catch (AbortedCompilationException e) {
// we don't handle those here
throw e;
} catch (AssertionError e) {
LogUtils.logError(TextUMLCore.PLUGIN_ID, "Assertion failed", e);
problemBuilder.addError("Exception: " + e.toString(), node);
} catch (RuntimeException e) {
LogUtils.logError(TextUMLCore.PLUGIN_ID, "Unexpected exception", e);
problemBuilder.addError("Exception: " + e.toString(), node);
}
}
@Override
public void caseAParenthesisOperand(AParenthesisOperand node) {
ACast cast = (ACast) node.getCast();
if (cast == null) {
// no casting, just process inner expression
node.getExpression().apply(this);
return;
}
PTypeIdentifier typeIdentifier = cast.getTypeIdentifier();
buildCast(node.getExpression(), action ->
new TypeSetter(
sourceContext,
namespaceTracker.currentNamespace(null),
action.getStructuredNodeOutputs().get(0)
).process(typeIdentifier)
);
}
private void buildCast(Node expression, Consumer<StructuredActivityNode> doIt) {
StructuredActivityNode action = (StructuredActivityNode) builder
.createAction(Literals.STRUCTURED_ACTIVITY_NODE);
MDDExtensionUtils.makeCast(action);
try {
// register the target input pin (type is null)
InputPin inputPin = (InputPin) action.createStructuredNodeInput(null, null);
builder.registerInput(inputPin);
// process the target expression - this will connect its output pin
// to the input pin we just created
expression.apply(this);
// copy whatever multiplicity coming into the source to the source
// but leave type as undefined as this action is supposed to accept any type of input
ObjectNode inputSource = ActivityUtils.getSource(inputPin);
TypeUtils.copyMultiplicity((MultiplicityElement) inputSource, inputPin);
// register the result output pin
OutputPin outputPin = (OutputPin) action.createStructuredNodeOutput(null, null);
doIt.accept(action);
builder.registerOutput(outputPin);
fillDebugInfo(action, expression);
} finally {
builder.closeAction();
}
checkIncomings(action, expression, getBoundElement());
}
public Action handleUnaryExpressionAsOperation(Node operator, Node operand, String operationName) {
return handleUnaryExpressionAsOperation(operator, operationName, () -> {
operand.apply(BehaviorGenerator.this);
return operand;
});
}
public Action handleUnaryExpressionAsOperation(Node contextNode, String operationName, Supplier<Node> childProcessor) {
CallOperationAction action = (CallOperationAction) builder.createAction(IRepository.PACKAGE
.getCallOperationAction());
try {
// register the target input pin
builder.registerInput(action.createTarget(null, null));
// process the target expression - this will connect its output pin
// to the input pin we just created
Node childNode = childProcessor.get();
InputPin target = action.getTarget();
ObjectNode targetSource = ActivityUtils.getSource(target);
Type targetType = targetSource.getType();
ensure(targetType != null, childNode, () -> new UnclassifiedProblem("No type information for " + childNode));
Operation operation = FeatureUtils.findOperation(getRepository(), (Classifier) targetType, operationName, Arrays.asList(), false, true);
TypeUtils.copyType(targetSource, target);
if (operation == null) {
missingOperation(true, contextNode, (Classifier) targetType, operationName,
Arrays.asList(), false);
}
ensure(TypeUtils.isRequired(target) || FeatureUtils.isBasicOperation(operation), childNode, () ->
new RequiredValueExpected());
// register the result output pin
OutputPin result = action.createResult(null, operation.getType());
builder.registerOutput(result);
result.setLower(Math.min(target.getLower(), operation.getReturnResult().getLower()));
action.setOperation(operation);
fillDebugInfo(action, contextNode.parent());
} finally {
builder.closeAction();
}
checkIncomings(action, contextNode, getBoundElement());
return action;
}
@Override
public void caseAUnlinkSpecificStatement(AUnlinkSpecificStatement node) {
buildWriteLinkAction(node, node.getMinimalTypeIdentifier(), IRepository.PACKAGE.getDestroyLinkAction());
}
@Override
public void caseAEmptyReturnSpecificStatement(AEmptyReturnSpecificStatement node) {
Variable variable = builder.getReturnValueVariable();
if (variable != null) {
problemBuilder.addProblem(new ReturnValueRequired(), node.getReturn());
throw new AbortedScopeCompilationException();
}
Action previousStatement = builder.getLastRootAction();
if (previousStatement != null)
ActivityUtils.makeFinal(builder.getCurrentBlock(), previousStatement);
}
@Override
public void caseAValuedReturnSpecificStatement(AValuedReturnSpecificStatement node) {
buildReturnStatement(node.getRootExpression());
}
protected void buildReturnStatement(Node node) {
TemplateableElement bound = (Class) MDDUtil.getNearest(builder.getCurrentActivity(),
IRepository.PACKAGE.getClass_());
AddVariableValueAction action = (AddVariableValueAction) builder.createAction(IRepository.PACKAGE
.getAddVariableValueAction());
try {
Variable variable = builder.getReturnValueVariable();
if (variable == null) {
problemBuilder.addProblem(new ReturnValueNotExpected(), node);
throw new AbortedScopeCompilationException();
}
final InputPin value = builder.registerInput(action.createValue(null, null));
node.apply(this);
action.setVariable(variable);
TypeUtils.copyType(variable, value, bound);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
ActivityUtils.makeFinal(builder.getCurrentBlock(), action);
}
@Override
public void caseAVarDecl(final AVarDecl node) {
super.caseAVarDecl(node);
String varIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
final Variable var = builder.getCurrentBlock().createVariable(varIdentifier, null);
if (node.getOptionalType() != null)
// type is optional for local vars
new TypeSetter(sourceContext, namespaceTracker.currentNamespace(null), var).process(node.getOptionalType());
else {
// ensure a type is eventually inferred
defer(Step.BEHAVIOR, r -> {
ensure(var.getType() != null, node.getIdentifier(), Severity.ERROR, () -> "Could not infer a type for variable '" + var.getName() + "'");
});
}
}
@Override
public void caseAVariableAccess(AVariableAccess node) {
ReadVariableAction action = (ReadVariableAction) builder.createAction(IRepository.PACKAGE
.getReadVariableAction());
try {
super.caseAVariableAccess(node);
final OutputPin result = action.createResult(null, null);
builder.registerOutput(result);
String variableName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Variable variable = builder.getVariable(variableName);
ensure(variable != null, node.getIdentifier(), Severity.ERROR, () -> "Unknown local variable '" + variableName + "'");
action.setVariable(variable);
TypeUtils.copyType(variable, result, getBoundElement());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
private Class getBoundElement() {
return (Class) MDDUtil.getNearest(builder.getCurrentActivity().getOwner(), IRepository.PACKAGE.getClass_());
}
@Override
public void caseAWhileLoopBody(AWhileLoopBody node) {
LoopNode currentLoop = (LoopNode) builder.getCurrentBlock();
currentLoop.setIsTestedFirst(true);
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, () -> {
super.caseAWhileLoopBody(node);
currentLoop.getBodyParts().add(builder.getCurrentBlock());
});
}
@Override
public void caseAWriteAttributeSpecificStatement(AWriteAttributeSpecificStatement node) {
AddStructuralFeatureValueAction action = (AddStructuralFeatureValueAction) builder
.createAction(IRepository.PACKAGE.getAddStructuralFeatureValueAction());
final String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
action.setIsReplaceAll(true);
try {
builder.registerInput(action.createObject(null, null));
builder.registerInput(action.createValue(null, null));
super.caseAWriteAttributeSpecificStatement(node);
ObjectNode targetSource = ActivityUtils.getSource(action.getObject());
Classifier targetClassifier = (Classifier) targetSource.getType();
if (targetClassifier == null) {
problemBuilder.addError("Object type not determined for '"
+ ((ATarget) node.getTarget()).getOperand().toString().trim() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
Property attribute = FeatureUtils.findAttribute(targetClassifier, attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addError(
"Unknown attribute '" + attributeIdentifier + "' in '" + targetClassifier.getName() + "'",
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (attribute.isDerived()) {
problemBuilder.addProblem(new CannotModifyADerivedAttribute(), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
checkIfTargetIsRequired(node.getTarget(), targetSource);
ensureNotQuery(node);
action.setStructuralFeature(attribute);
action.getObject().setType(targetClassifier);
TypeUtils.copyType(attribute, action.getValue(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
@Override
public void caseAWriteClassAttributeSpecificStatement(AWriteClassAttributeSpecificStatement node) {
ensureNotQuery(node);
TemplateableElement bound = null;
AddStructuralFeatureValueAction action = (AddStructuralFeatureValueAction) builder
.createAction(IRepository.PACKAGE.getAddStructuralFeatureValueAction());
action.setIsReplaceAll(true);
try {
String typeIdentifier = TextUMLCore.getSourceMiner()
.getQualifiedIdentifier(node.getMinimalTypeIdentifier());
Classifier targetClassifier = (Classifier) getRepository().findNamedElement(typeIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (targetClassifier == null) {
problemBuilder.addError("Class reference expected: '" + typeIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
bound = targetClassifier;
final String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute = FeatureUtils.findAttribute(targetClassifier, attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addError(
"Unknown attribute '" + attributeIdentifier + "' in '" + targetClassifier.getName() + "'",
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (attribute.isDerived()) {
problemBuilder.addProblem(new CannotModifyADerivedAttribute(), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (!attribute.isStatic()) {
problemBuilder.addError("Static attribute expected: '" + attributeIdentifier + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
builder.registerInput(action.createValue(null, null));
// builds expression
node.getRootExpression().apply(this);
action.setStructuralFeature(attribute);
TypeUtils.copyType(attribute, action.getValue(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), bound);
}
@Override
public void caseAWriteVariableSpecificStatement(AWriteVariableSpecificStatement node) {
AddVariableValueAction action = (AddVariableValueAction) builder.createAction(IRepository.PACKAGE
.getAddVariableValueAction());
action.setIsReplaceAll(true);
try {
final InputPin value = builder.registerInput(action.createValue(null, null));
super.caseAWriteVariableSpecificStatement(node);
String variableName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Variable variable = builder.getVariable(variableName);
if (variable == null) {
problemBuilder.addError("Unknown local variable '" + variableName + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setVariable(variable);
if (variable.getType() == null)
// infer variable type if omitted
TypeUtils.copyType(ActivityUtils.getSource(value), variable, getBoundElement());
TypeUtils.copyType(variable, value, getBoundElement());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
private void checkIncomings(final Action action, final Node node, TemplateableElement bound) {
ObjectFlow incompatible = TypeUtils.checkCompatibility(getRepository(), action, bound);
if (incompatible == null)
return;
final ObjectNode target = ((ObjectNode) incompatible.getTarget());
final ObjectNode source = ((ObjectNode) incompatible.getSource());
final Type anyType = findBuiltInType(TypeUtils.ANY_TYPE, node);
if (target.getType() != null && target.getType() != anyType
&& (source.getType() == null || source.getType() == anyType))
source.setType(target.getType());
else
reportIncompatibleTypes(node, target, source);
checkAllInputsHaveFlows(action, node);
}
private void checkAllInputsHaveFlows(Action action, Node node) {
boolean alreadyReportedErrors = !problemBuilder.hasErrors();
if (!alreadyReportedErrors)
ActivityUtils.getActionInputs(action).stream().forEach(input -> {
if (input.getIncomings().isEmpty())
problemBuilder.addProblem(new UnclassifiedProblem("Missing incoming flow for input pin " + StringUtils.trimToEmpty(input.getName())), node);
});
}
private void reportIncompatibleTypes(final Node context, final ObjectNode expected, final ObjectNode actual) {
problemBuilder.addProblem(buildTypeMismatchProblem(expected, actual),
context);
}
private TypeMismatch buildTypeMismatchProblem(final ObjectNode expected, final ObjectNode actual) {
return new TypeMismatch(MDDUtil.getDisplayName(expected), MDDUtil.getDisplayName(actual));
}
private int countElements(PExpressionList list) {
if (list instanceof AEmptyExpressionList)
return 0;
final int[] counter = { 0 };
list.apply(new DepthFirstAdapter() {
@Override
public void caseAExpressionListElement(AExpressionListElement node) {
counter[0]++;
}
});
return counter[0];
}
/**
* Fills in the given activity with behavior parsed from the given node.
*/
public void createBody(Node bodyNode, Activity activity) {
namespaceTracker.enterNamespace(activity);
try {
builder.createRootBlock(activity);
try {
bodyNode.apply(this);
} finally {
builder.closeRootBlock();
}
} finally {
namespaceTracker.leaveNamespace();
}
defer(Step.BEHAVIOR, r -> validateReturnStatement(bodyNode, activity));
// process any deferred activities
while (!deferredActivities.isEmpty()) {
DeferredActivity next = deferredActivities.remove(0);
createBody(next.getBlock(), next.getActivity());
}
}
public void validateReturnStatement(Node bodyNode, Activity activity) {
boolean hasReturnWithValue = ActivityUtils.getFinalAction(ActivityUtils.getBodyNode(activity)) == null;
if (!problemBuilder.hasErrors() && hasReturnWithValue) {
boolean returnValueRequired = FeatureUtils.findReturnParameter(activity.getOwnedParameters()) != null;
ensure(!returnValueRequired, bodyNode, () -> new ReturnStatementRequired());
}
}
private Clause createClause() {
ConditionalNode currentConditional = (ConditionalNode) builder.getCurrentBlock();
boolean hasClauses = !currentConditional.getClauses().isEmpty();
Clause newClause = currentConditional.createClause();
if (hasClauses) {
Clause previousClause = currentConditional.getClauses().get(currentConditional.getClauses().size() - 1);
previousClause.getSuccessorClauses().add(newClause);
}
return newClause;
}
private <T extends StructuredActivityNode> T createBlock(boolean dataFlows, Runnable builderBehavior) {
return createBlock(IRepository.PACKAGE.getStructuredActivityNode(), dataFlows, builderBehavior);
}
private <T extends StructuredActivityNode> T createBlock(EClass activityNode, boolean dataFlows, Runnable builderBehavior) {
return createBlock(activityNode, dataFlows, it -> builderBehavior.run());
}
private <T extends StructuredActivityNode> T createBlock(EClass activityNode, boolean dataFlows, Consumer<T> builderBehavior) {
T block = (T) builder.createBlock(activityNode, dataFlows);
try {
builderBehavior.accept(block);
} catch (AbortedScopeCompilationException e) {
if (!ActivityUtils.isBodyNode(block)) {
// keep throwing exception
throw e;
}
// aborted activity block compilation...
if (builder.isDebug())
LogUtils.logWarning(TextUMLCore.PLUGIN_ID, null, e);
} finally {
builder.closeBlock();
}
return block;
}
private void createClauseBody(Clause clause, Runnable builderBlock) {
createBlock(false, () -> {
builderBlock.run();
clause.getBodies().add(builder.getCurrentBlock());
Action lastRootAction = builder.getLastRootAction();
if (lastRootAction != null) {
List<OutputPin> bodyOutput = ActivityUtils.getActionOutputs(lastRootAction);
clause.getBodyOutputs().addAll(bodyOutput);
}
});
}
private void createClauseTest(Clause clause, Runnable builderBlock) {
createBlock(false, () -> {
builderBlock.run();
clause.getTests().add(builder.getCurrentBlock());
Action lastRootAction = builder.getLastRootAction();
OutputPin decider = ActivityUtils.getActionOutputs(lastRootAction).get(0);
clause.setDecider(decider);
});
}
private void deferBlockCreation(Node block, Activity activity) {
deferredActivities.add(new DeferredActivity(activity, block));
}
private Operation findOperation(Node node, Classifier classifier, String operationName,
List<TypedElement> arguments, boolean isStatic, boolean required) {
Operation found = FeatureUtils
.findOperation(getRepository(), classifier, operationName, arguments, false, true);
if (found != null) {
if (found.isStatic() != isStatic) {
problemBuilder.addError((isStatic ? "Static" : "Non-static") + " operation expected: '" + operationName
+ "' in '" + found.getType().getQualifiedName() + "'", node);
throw new AbortedStatementCompilationException();
}
return found;
}
return missingOperation(required, node, classifier, operationName, arguments, isStatic);
}
protected Operation missingOperation(boolean required, Node node, Classifier classifier, String operationName,
List<TypedElement> arguments, boolean isStatic) {
if (!required)
return null;
Operation alternative = FeatureUtils.findOperation(getRepository(), classifier, operationName, null, false,
true);
problemBuilder.addProblem(
new UnknownOperation(classifier.getQualifiedName(), operationName, MDDUtil
.getArgumentListString(arguments), isStatic, alternative), node);
throw new AbortedStatementCompilationException();
}
// OperationInfo parseOperationInfo(Node operatorNode, int infoCount) {
// final OperationInfo info = new OperationInfo(infoCount);
// operatorNode.apply(new DepthFirstAdapter() {
//
// @Override
// public void caseAArithmeticBinaryOperatorP1(AArithmeticBinaryOperatorP1 node) {
// super.caseAArithmeticBinaryOperatorP1(node);
// handleArithmeticOperator(info);
// }
//
// @Override
// public void caseAArithmeticBinaryOperatorP2(AArithmeticBinaryOperatorP2 node) {
// super.caseAArithmeticBinaryOperatorP2(node);
// handleArithmeticOperator(info);
// }
//
// private void handleArithmeticOperator(final OperationInfo info) {
// info.types[0] = info.types[1] = info.types[2] = (Classifier) getRepository().findNamedElement(
// "base::Integer", IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseAComparisonBinaryOperatorP2(AComparisonBinaryOperatorP2 node) {
// super.caseAComparisonBinaryOperatorP2(node);
// handleComparisonOperator(info);
// }
//
// private void handleComparisonOperator(final OperationInfo info) {
// info.types[0] = info.types[1] = (Classifier) getRepository().findNamedElement("base::Comparable",
// IRepository.PACKAGE.getType(), null);
// info.types[2] = (Classifier) getRepository().findNamedElement("base::Boolean",
// IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseAEqualsComparisonBinaryOperatorP2(AEqualsComparisonBinaryOperatorP2 node) {
// info.operationName = "equals";
// }
//
// @Override
// public void caseANotEqualsComparisonBinaryOperatorP2(ANotEqualsComparisonBinaryOperatorP2 node) {
// info.operationName = "not";
// }
//
// @Override
// public void caseAGreaterOrEqualsComparisonBinaryOperatorP2(AGreaterOrEqualsComparisonBinaryOperatorP2 node) {
// info.operationName = "greaterOrEquals";
// }
//
// @Override
// public void caseAGreaterThanComparisonBinaryOperatorP2(AGreaterThanComparisonBinaryOperatorP2 node) {
// info.operationName = "greater";
// }
//
// @Override
// public void caseAIdentityComparisonBinaryOperatorP2(AIdentityComparisonBinaryOperatorP2 node) {
// super.caseAIdentityComparisonBinaryOperatorP2(node);
// info.operationName = "same";
// info.types[0] = info.types[1] = (Classifier) getRepository().findNamedElement("base::Any",
// IRepository.PACKAGE.getClass_(), null);
// info.types[2] = (Classifier) getRepository().findNamedElement("base::Boolean",
// IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseALogicalBinaryOperatorP2(ALogicalBinaryOperatorP2 node) {
// super.caseALogicalBinaryOperatorP2(node);
// handleLogicalBinaryOperator();
// }
//
// @Override
// public void caseALogicalBinaryOperatorP1(ALogicalBinaryOperatorP1 node) {
// super.caseALogicalBinaryOperatorP1(node);
// handleLogicalBinaryOperator();
// }
//
// private void handleLogicalBinaryOperator() {
// info.types[0] = info.types[1] = info.types[2] = (Classifier) getRepository().findNamedElement(
// "base::Boolean", IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseALowerOrEqualsComparisonBinaryOperatorP2(ALowerOrEqualsComparisonBinaryOperatorP2 node) {
// info.operationName = "lowerOrEquals";
// }
//
// @Override
// public void caseALowerThanComparisonBinaryOperatorP2(ALowerThanComparisonBinaryOperatorP2 node) {
// info.operationName = "lowerThan";
// }
//
// @Override
// public void caseAMinusUnaryOperator(AMinusUnaryOperator node) {
// super.caseAMinusUnaryOperator(node);
// info.types[0] = info.types[1] = (Classifier) getRepository().findNamedElement("base::Integer",
// IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseANotUnaryOperator(ANotUnaryOperator node) {
// super.caseANotUnaryOperator(node);
// info.types[0] = info.types[1] = (Classifier) getRepository().findNamedElement("base::Boolean",
// IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseANotNullUnaryOperator(ANotNullUnaryOperator node) {
// super.caseANotNullUnaryOperator(node);
// info.types[0] = (Classifier) getRepository().findNamedElement("base::Basic",
// IRepository.PACKAGE.getType(), null);
// info.types[1] = (Classifier) getRepository().findNamedElement("base::Boolean",
// IRepository.PACKAGE.getType(), null);
// }
//
// public void caseTAnd(TAnd node) {
// info.operationName = "and";
// }
//
// public void caseTDiv(TDiv node) {
// info.operationName = "divide";
// }
//
// public void caseTMinus(TMinus node) {
// info.operationName = "subtract";
// }
//
// public void caseTMult(TMult node) {
// info.operationName = "multiply";
// }
//
// @Override
// public void caseTNot(TNot node) {
// info.operationName = "not";
// }
//
// public void caseTNotNull(TNotNull node) {
// info.operationName = "notNull";
// }
//
// public void caseTOr(TOr node) {
// info.operationName = "or";
// }
//
// public void caseTPlus(TPlus node) {
// info.operationName = "add";
// }
// });
// return info;
// }
@Override
public void caseATupleConstructor(ATupleConstructor node) {
final StructuredActivityNode action = (StructuredActivityNode) builder.createAction(IRepository.PACKAGE
.getStructuredActivityNode());
MDDExtensionUtils.makeObjectInitialization(action);
try {
node.apply(new DepthFirstAdapter() {
@Override
public void caseATupleComponentValue(ATupleComponentValue node) {
String slotName = sourceMiner.getIdentifier(node.getIdentifier());
builder.registerInput(action.createStructuredNodeInput(slotName, null));
node.getExpression().apply(BehaviorGenerator.this);
}
});
builder.registerOutput(action.createStructuredNodeOutput(null, null));
// now we determine the types of the incoming flows and build a
// corresponding data type on the fly
List<String> slotNames = new ArrayList<>();
List<Type> slotTypes = new ArrayList<>();
action.getStructuredNodeInputs().forEach((input) -> {
slotNames.add(input.getName());
slotTypes.add(input.getType());
});
DataType dataType = DataTypeUtils.findOrCreateDataType(namespaceTracker.currentPackage(), slotNames,
slotTypes);
action.getStructuredNodeOutputs().get(0).setType(dataType);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
public void createBodyLater(final Node bodyNode, final Activity body) {
defer(Step.BEHAVIOR, r -> createBody(bodyNode, body));
}
public void createConstraintBehaviorLater(final BehavioredClassifier parent, final Constraint constraint,
final Node constraintBlock, final List<Parameter> parameters) {
defer(Step.BEHAVIOR, repository -> createConstraintBehavior(parent, constraint, constraintBlock, parameters));
}
public Activity createConstraintBehavior(BehavioredClassifier parent, Constraint constraint, Node constraintBlock,
List<Parameter> parameters) {
Activity activity = MDDExtensionUtils.createConstraintBehavior(parent, constraint);
for (Parameter parameter : parameters)
activity.getOwnedParameters().add(parameter);
Classifier constraintType = BasicTypeUtils.findBuiltInType("Boolean");
activity.createOwnedParameter(null, constraintType).setDirection(ParameterDirectionKind.RETURN_LITERAL);
if (constraintBlock == null) {
constraintBlock = new AExpressionSimpleBlockResolved(
new ASimpleExpressionBlock(
null,
buildOperandExpression(new ALiteralOperand(
new ABooleanLiteral(
new ATrueBoolean(new TTrue())
)
)),
null
)
);
}
createBody(constraintBlock, activity);
ValueSpecification reference = ActivityUtils.buildBehaviorReference(constraint.getNearestPackage(), activity,
constraintType);
constraint.setSpecification(reference);
return activity;
}
private ARootExpression buildOperandExpression(POperand operand) {
return buildExpression(new AAltNestedExpressionP1(new AAltExpressionP0(operand)));
}
private ARootExpression buildExpression(AAltNestedExpressionP1 expressionP1) {
return buildExpression(new AAltNestedExpressionP2(expressionP1));
}
private ARootExpression buildExpression(AAltNestedExpressionP2 expressionP2) {
return buildExpression(new AAltNestedExpressionP3(expressionP2));
}
private ARootExpression buildExpression(AAltNestedExpressionP3 expressionP3) {
return buildExpression(new AAltNestedExpressionP4(expressionP3));
}
private ARootExpression buildExpression(AAltNestedExpressionP4 expression4) {
return buildExpression(new AAltNestedExpressionP5(expression4));
}
private ARootExpression buildExpression(AAltNestedExpressionP5 expressionP5) {
return new ARootExpression(new AExpression(expressionP5));
}
} | plugins/com.abstratt.mdd.frontend.textuml.core/src/com/abstratt/mdd/internal/frontend/textuml/BehaviorGenerator.java | /*******************************************************************************
* Copyright (c) 2006, 2010 Abstratt Technologies
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Rafael Chaves (Abstratt Technologies) - initial API and implementation
*******************************************************************************/
package com.abstratt.mdd.internal.frontend.textuml;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.runtime.Assert;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.uml2.uml.Action;
import org.eclipse.uml2.uml.Activity;
import org.eclipse.uml2.uml.ActivityNode;
import org.eclipse.uml2.uml.AddStructuralFeatureValueAction;
import org.eclipse.uml2.uml.AddVariableValueAction;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.BehavioralFeature;
import org.eclipse.uml2.uml.BehavioredClassifier;
import org.eclipse.uml2.uml.CallOperationAction;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Clause;
import org.eclipse.uml2.uml.ConditionalNode;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.CreateObjectAction;
import org.eclipse.uml2.uml.DataType;
import org.eclipse.uml2.uml.DestroyObjectAction;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.eclipse.uml2.uml.ExceptionHandler;
import org.eclipse.uml2.uml.InputPin;
import org.eclipse.uml2.uml.InstanceValue;
import org.eclipse.uml2.uml.LinkEndData;
import org.eclipse.uml2.uml.LiteralUnlimitedNatural;
import org.eclipse.uml2.uml.LoopNode;
import org.eclipse.uml2.uml.MultiplicityElement;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.ObjectFlow;
import org.eclipse.uml2.uml.ObjectNode;
import org.eclipse.uml2.uml.Operation;
import org.eclipse.uml2.uml.OutputPin;
import org.eclipse.uml2.uml.Parameter;
import org.eclipse.uml2.uml.ParameterDirectionKind;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.RaiseExceptionAction;
import org.eclipse.uml2.uml.ReadExtentAction;
import org.eclipse.uml2.uml.ReadIsClassifiedObjectAction;
import org.eclipse.uml2.uml.ReadLinkAction;
import org.eclipse.uml2.uml.ReadSelfAction;
import org.eclipse.uml2.uml.ReadStructuralFeatureAction;
import org.eclipse.uml2.uml.ReadVariableAction;
import org.eclipse.uml2.uml.SendSignalAction;
import org.eclipse.uml2.uml.Signal;
import org.eclipse.uml2.uml.StateMachine;
import org.eclipse.uml2.uml.StructuredActivityNode;
import org.eclipse.uml2.uml.TemplateableElement;
import org.eclipse.uml2.uml.TestIdentityAction;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.TypedElement;
import org.eclipse.uml2.uml.UMLPackage;
import org.eclipse.uml2.uml.UMLPackage.Literals;
import org.eclipse.uml2.uml.ValueSpecification;
import org.eclipse.uml2.uml.ValueSpecificationAction;
import org.eclipse.uml2.uml.Variable;
import org.eclipse.uml2.uml.Vertex;
import org.eclipse.uml2.uml.WriteLinkAction;
import com.abstratt.mdd.core.IProblem.Severity;
import com.abstratt.mdd.core.IRepository;
import com.abstratt.mdd.core.Step;
import com.abstratt.mdd.core.UnclassifiedProblem;
import com.abstratt.mdd.core.util.ActivityUtils;
import com.abstratt.mdd.core.util.BasicTypeUtils;
import com.abstratt.mdd.core.util.ClassifierUtils;
import com.abstratt.mdd.core.util.DataTypeUtils;
import com.abstratt.mdd.core.util.FeatureUtils;
import com.abstratt.mdd.core.util.MDDExtensionUtils;
import com.abstratt.mdd.core.util.MDDUtil;
import com.abstratt.mdd.core.util.PackageUtils;
import com.abstratt.mdd.core.util.StateMachineUtils;
import com.abstratt.mdd.core.util.TypeUtils;
import com.abstratt.mdd.frontend.core.CannotModifyADerivedAttribute;
import com.abstratt.mdd.frontend.core.FrontEnd;
import com.abstratt.mdd.frontend.core.InternalProblem;
import com.abstratt.mdd.frontend.core.MissingRequiredArgument;
import com.abstratt.mdd.frontend.core.NotAConcreteClassifier;
import com.abstratt.mdd.frontend.core.NotInAssociation;
import com.abstratt.mdd.frontend.core.OptionalValueExpected;
import com.abstratt.mdd.frontend.core.QueryOperationsMustBeSideEffectFree;
import com.abstratt.mdd.frontend.core.ReadSelfFromStaticContext;
import com.abstratt.mdd.frontend.core.RequiredValueExpected;
import com.abstratt.mdd.frontend.core.ReturnStatementRequired;
import com.abstratt.mdd.frontend.core.ReturnValueNotExpected;
import com.abstratt.mdd.frontend.core.ReturnValueRequired;
import com.abstratt.mdd.frontend.core.TypeMismatch;
import com.abstratt.mdd.frontend.core.UnknownAttribute;
import com.abstratt.mdd.frontend.core.UnknownOperation;
import com.abstratt.mdd.frontend.core.UnknownRole;
import com.abstratt.mdd.frontend.core.UnknownType;
import com.abstratt.mdd.frontend.core.spi.AbortedCompilationException;
import com.abstratt.mdd.frontend.core.spi.AbortedScopeCompilationException;
import com.abstratt.mdd.frontend.core.spi.AbortedStatementCompilationException;
import com.abstratt.mdd.frontend.core.spi.IActivityBuilder;
import com.abstratt.mdd.frontend.textuml.core.TextUMLCore;
import com.abstratt.mdd.frontend.textuml.grammar.analysis.DepthFirstAdapter;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP1;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP2;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP3;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP4;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltBinaryExpressionP5;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltExpressionP0;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP1;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP2;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP3;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP4;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltNestedExpressionP5;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAltUnaryExpressionP0;
import com.abstratt.mdd.frontend.textuml.grammar.node.AAttributeIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ABlockKernel;
import com.abstratt.mdd.frontend.textuml.grammar.node.ABooleanLiteral;
import com.abstratt.mdd.frontend.textuml.grammar.node.ABroadcastSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ACast;
import com.abstratt.mdd.frontend.textuml.grammar.node.ACatchSection;
import com.abstratt.mdd.frontend.textuml.grammar.node.AClassAttributeIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AClassOperationIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AClosure;
import com.abstratt.mdd.frontend.textuml.grammar.node.AClosureOperand;
import com.abstratt.mdd.frontend.textuml.grammar.node.ADestroySpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AElseRestIf;
import com.abstratt.mdd.frontend.textuml.grammar.node.AEmptyExpressionList;
import com.abstratt.mdd.frontend.textuml.grammar.node.AEmptyReturnSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AEmptySet;
import com.abstratt.mdd.frontend.textuml.grammar.node.AEqualsComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.AExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AExpressionListElement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AExpressionSimpleBlockResolved;
import com.abstratt.mdd.frontend.textuml.grammar.node.AExtentIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AFunctionIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AGreaterOrEqualsComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.AGreaterThanComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.AIfClause;
import com.abstratt.mdd.frontend.textuml.grammar.node.AIfStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AIsClassExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALinkIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALinkRole;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALinkSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALiteralOperand;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALoopSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ALoopTest;
import com.abstratt.mdd.frontend.textuml.grammar.node.AMinimalTypeIdentifier;
import com.abstratt.mdd.frontend.textuml.grammar.node.ANamedArgument;
import com.abstratt.mdd.frontend.textuml.grammar.node.ANewIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ANotEqualsComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.ANotSameComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.AOperationIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.AParenthesisOperand;
import com.abstratt.mdd.frontend.textuml.grammar.node.AQualifiedAssociationTraversal;
import com.abstratt.mdd.frontend.textuml.grammar.node.ARaiseSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ARepeatLoopBody;
import com.abstratt.mdd.frontend.textuml.grammar.node.ARequiredTargetObjectDot;
import com.abstratt.mdd.frontend.textuml.grammar.node.ARootExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASameComparisonOperator;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASelfIdentifierExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASendSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASimpleAssociationTraversal;
import com.abstratt.mdd.frontend.textuml.grammar.node.ASimpleExpressionBlock;
import com.abstratt.mdd.frontend.textuml.grammar.node.AStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATarget;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATernaryExpression;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATrueBoolean;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATryStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATupleComponentValue;
import com.abstratt.mdd.frontend.textuml.grammar.node.ATupleConstructor;
import com.abstratt.mdd.frontend.textuml.grammar.node.AUnlinkSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AValuedReturnSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AVarDecl;
import com.abstratt.mdd.frontend.textuml.grammar.node.AVariableAccess;
import com.abstratt.mdd.frontend.textuml.grammar.node.AWhileLoopBody;
import com.abstratt.mdd.frontend.textuml.grammar.node.AWriteAttributeSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AWriteClassAttributeSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.AWriteVariableSpecificStatement;
import com.abstratt.mdd.frontend.textuml.grammar.node.Node;
import com.abstratt.mdd.frontend.textuml.grammar.node.PAssociationTraversal;
import com.abstratt.mdd.frontend.textuml.grammar.node.PExpressionList;
import com.abstratt.mdd.frontend.textuml.grammar.node.POperand;
import com.abstratt.mdd.frontend.textuml.grammar.node.PTarget;
import com.abstratt.mdd.frontend.textuml.grammar.node.PTypeIdentifier;
import com.abstratt.mdd.frontend.textuml.grammar.node.TAnd;
import com.abstratt.mdd.frontend.textuml.grammar.node.TBangs;
import com.abstratt.mdd.frontend.textuml.grammar.node.TDiv;
import com.abstratt.mdd.frontend.textuml.grammar.node.TElvis;
import com.abstratt.mdd.frontend.textuml.grammar.node.TIs;
import com.abstratt.mdd.frontend.textuml.grammar.node.TLab;
import com.abstratt.mdd.frontend.textuml.grammar.node.TLabEquals;
import com.abstratt.mdd.frontend.textuml.grammar.node.TMinus;
import com.abstratt.mdd.frontend.textuml.grammar.node.TMult;
import com.abstratt.mdd.frontend.textuml.grammar.node.TNot;
import com.abstratt.mdd.frontend.textuml.grammar.node.TOr;
import com.abstratt.mdd.frontend.textuml.grammar.node.TPlus;
import com.abstratt.mdd.frontend.textuml.grammar.node.TQuestion;
import com.abstratt.mdd.frontend.textuml.grammar.node.TTrue;
import com.abstratt.pluginutils.LogUtils;
/**
* This tree visitor will generate the behavioral model for a given input.
*/
public class BehaviorGenerator extends AbstractGenerator {
class DeferredActivity {
private Activity activity;
private Node block;
public DeferredActivity(Activity activity, Node block) {
this.activity = activity;
this.block = block;
}
public Activity getActivity() {
return activity;
}
public Node getBlock() {
return block;
}
}
class OperationInfo {
String operationName;
// operand (target)[, operand (argument)], result (return)
Classifier[] types;
public OperationInfo(int numberOfTypes) {
types = new Classifier[numberOfTypes];
}
}
private IActivityBuilder builder;
private List<DeferredActivity> deferredActivities;
public BehaviorGenerator(SourceCompilationContext<Node> sourceContext) {
super(sourceContext);
deferredActivities = new LinkedList<DeferredActivity>();
builder = FrontEnd.newActivityBuilder(getRepository());
}
/**
* Creates an anonymous activity and returns a reference.
*/
private Activity buildClosure(BehavioredClassifier parent, StructuredActivityNode context, AClosure node) {
Activity newClosure = MDDExtensionUtils.createClosure(parent, context);
// create activity parameters
node.getSimpleSignature().apply(newSignatureProcessor(newClosure));
deferBlockCreation(node.getBlock(), newClosure);
return newClosure;
}
private ValueSpecificationAction buildValueSpecificationAction(ValueSpecification valueSpec, Node node) {
ValueSpecificationAction action = (ValueSpecificationAction) builder.createAction(IRepository.PACKAGE
.getValueSpecificationAction());
try {
action.setValue(valueSpec);
builder.registerOutput(action.createResult(null, valueSpec.getType()));
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
return action;
}
@Override
public void caseAAttributeIdentifierExpression(AAttributeIdentifierExpression node) {
ReadStructuralFeatureAction action = (ReadStructuralFeatureAction) builder.createAction(IRepository.PACKAGE
.getReadStructuralFeatureAction());
final String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
try {
builder.registerInput(action.createObject(null, null));
super.caseAAttributeIdentifierExpression(node);
builder.registerOutput(action.createResult(null, null));
final ObjectNode targetSource = ActivityUtils.getSource(action.getObject());
Classifier targetClassifier = (Classifier) TypeUtils.getTargetType(getRepository(), targetSource, true);
if (targetClassifier == null) {
problemBuilder.addError("Object type not determined for '"
+ ((ATarget) node.getTarget()).getOperand().toString().trim() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
Property attribute = FeatureUtils.findAttribute(targetClassifier, attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addProblem(new UnknownAttribute(targetClassifier.getName(), attributeIdentifier, false),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (attribute.isStatic()) {
problemBuilder.addError("Non-static attribute expected: '" + attributeIdentifier + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setStructuralFeature(attribute);
action.getObject().setType(targetSource.getType());
TypeUtils.copyType(attribute, action.getResult(), targetClassifier);
checkIfTargetIsRequired(node.getTarget(), targetSource);
if (!TypeUtils.isRequiredPin(targetSource) && !TypeUtils.isMultivalued(targetSource))
// it is a tentative access, result must be optional
action.getResult().setLower(0);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
@Override
public void caseAIsClassExpression(AIsClassExpression expressionNode) {
handleBinaryExpression(expressionNode.getOperand1(), expressionNode.getOperator(), expressionNode.getOperand2());
}
@Override
public void caseAAltUnaryExpressionP0(AAltUnaryExpressionP0 node) {
handleUnaryExpression(node.getOperator(), node.getOperand());
}
@Override
public void caseAAltBinaryExpressionP1(AAltBinaryExpressionP1 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
@Override
public void caseAAltBinaryExpressionP2(AAltBinaryExpressionP2 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
@Override
public void caseAAltBinaryExpressionP3(AAltBinaryExpressionP3 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
@Override
public void caseAAltBinaryExpressionP4(AAltBinaryExpressionP4 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
@Override
public void caseAAltBinaryExpressionP5(AAltBinaryExpressionP5 node) {
handleBinaryExpression(node.getOperand1(), node.getOperator(), node.getOperand2());
}
private void handleUnaryExpression(Node operator, Node operand) {
final String[] operationName = { null };
boolean[] specialHandling = { false };
operator.apply(new DepthFirstAdapter() {
@Override
public void caseTMinus(TMinus node) {
operationName[0] = "subtract";
}
@Override
public void caseTNot(TNot node) {
operationName[0] = "not";
}
@Override
public void caseTQuestion(TQuestion node) {
operationName[0] = "notNull";
}
public void caseTBangs(TBangs node) {
specialHandling[0] = true;
handleRequiredUnaryOperator(operand);
}
});
if (!specialHandling[0]) {
ensure(operationName[0] != null, operator, () -> new UnclassifiedProblem("Unknown unary operator: " + operator.toString()));
handleUnaryExpressionAsOperation(operator, operand, operationName[0]);
}
}
private void handleBinaryExpression(Node left, Node operator, Node right) {
String[] operationName = { null };
boolean[] specialHandling = { false };
operator.apply(new DepthFirstAdapter() {
@Override
public void caseANotEqualsComparisonOperator(ANotEqualsComparisonOperator node) {
operationName[0] = "notEquals";
}
@Override
public void caseASameComparisonOperator(ASameComparisonOperator node) {
handleSameBinaryOperator(left, right);
specialHandling[0] = true;
}
@Override
public void caseANotSameComparisonOperator(ANotSameComparisonOperator node) {
handleUnaryExpressionAsOperation(node, "not", () -> {
handleSameBinaryOperator(left, right);
return node;
});
specialHandling[0] = true;
}
@Override
public void caseAEqualsComparisonOperator(AEqualsComparisonOperator node) {
operationName[0] = "equals";
}
@Override
public void caseAGreaterOrEqualsComparisonOperator(AGreaterOrEqualsComparisonOperator node) {
operationName[0] = "greaterOrEquals";
}
@Override
public void caseAGreaterThanComparisonOperator(AGreaterThanComparisonOperator node) {
operationName[0] = "greaterThan";
}
@Override
public void caseTIs(TIs node) {
handleIsClassifiedOperator(left, right);
specialHandling[0] = true;
}
@Override
public void caseTElvis(TElvis node) {
handleElvisOperator(left, right);
specialHandling[0] = true;
}
@Override
public void caseTLab(TLab node) {
operationName[0] = "lowerThan";
}
@Override
public void caseTLabEquals(TLabEquals node) {
operationName[0] = "lowerOrEquals";
}
@Override
public void caseTAnd(TAnd node) {
operationName[0] = "and";
}
@Override
public void caseTDiv(TDiv node) {
operationName[0] = "divide";
}
@Override
public void caseTMinus(TMinus node) {
operationName[0] = "subtract";
}
@Override
public void caseTMult(TMult node) {
operationName[0] = "multiply";
}
@Override
public void caseTOr(TOr node) {
operationName[0] = "or";
}
@Override
public void caseTPlus(TPlus node) {
operationName[0] = "add";
}
});
if (!specialHandling[0]) {
ensure(operationName[0] != null, operator, () -> new UnclassifiedProblem("Unknown binary operator: " + operator.toString()));
handleBinaryExpressionAsOperation(left, operator, right, operationName[0]);
}
}
public void handleBinaryExpressionAsOperation(Node operand1, Node operator, Node operand2, String operationName) {
handleBinaryExpressionAsOperation(operator, () -> {
operand1.apply(this);
return operand1;
}, () -> {
operand2.apply(this);
return operand2;
}, operationName);
}
public void handleBinaryExpressionAsOperation(Node contextNode, Supplier<Node> operand1, Supplier<Node> operand2, String operationName) {
CallOperationAction action = (CallOperationAction) builder.createAction(IRepository.PACKAGE
.getCallOperationAction());
try {
// register the target input pin
builder.registerInput(action.createTarget(null, null));
// register the argument input pins
builder.registerInput(action.createArgument(null, null));
// process the target and argument expressions - this will connect
// their output pins to the input pins we just created
Node targetNode = operand1.get();
Node argumentNode = operand2.get();
InputPin target = action.getTarget();
InputPin argument = action.getArguments().get(0);
Type targetType = ActivityUtils.getSource(target).getType();
Type argumentType = ActivityUtils.getSource(argument).getType();
ensure(targetType != null, targetNode, () -> new UnclassifiedProblem("No type information for " + operand1));
ensure(argumentType != null, argumentNode, () -> new UnclassifiedProblem("No type information for " + operand2));
TypeUtils.copyType(ActivityUtils.getSource(target), target);
TypeUtils.copyType(ActivityUtils.getSource(argument), argument);
List<TypedElement> argumentList = Collections.singletonList((TypedElement) argument);
Operation operation = FeatureUtils.findOperation(getRepository(), (Classifier) targetType, operationName,
argumentList, false, true);
if (operation == null)
missingOperation(true, contextNode, (Classifier) targetType, operationName,
argumentList, false);
if (operation.isStatic())
missingOperation(true, contextNode, (Classifier) targetType, operationName, argumentList,
false);
ensure(TypeUtils.isRequired(target) || FeatureUtils.isBasicOperation(operation), contextNode, () ->
new RequiredValueExpected());
List<Parameter> parameters = operation.getOwnedParameters();
if (parameters.size() != 2 && parameters.get(0).getDirection() != ParameterDirectionKind.IN_LITERAL
&& parameters.get(1).getDirection() != ParameterDirectionKind.RETURN_LITERAL) {
problemBuilder.addError("Unexpected signature: '" + operationName + "' in '"
+ target.getType().getQualifiedName() + "'", contextNode);
throw new AbortedStatementCompilationException();
}
// register the result output pin
OutputPin result = action.createResult(null, operation.getType());
builder.registerOutput(result);
result.setLower(Math.min(target.getLower(), operation.getReturnResult().getLower()));
action.setOperation(operation);
fillDebugInfo(action, contextNode.parent());
} finally {
builder.closeAction();
}
checkIncomings(action, contextNode, getBoundElement());
}
private ConditionalNode buildConditionalExpression(Node trueResultNode, Node falseResultNode, Runnable conditionExpressionBuilder) {
return createBlock(IRepository.PACKAGE.getConditionalNode(), true, (ConditionalNode action) -> {
Clause testClause = action.createClause();
createClauseTest(testClause, conditionExpressionBuilder);
createClauseBody(testClause, () -> trueResultNode.apply(this));
Clause elseClause = action.createClause();
createClauseTest(elseClause, () -> buildValueSpecificationAction(MDDUtil.createLiteralBoolean(namespaceTracker.currentPackage(), true), falseResultNode));
createClauseBody(elseClause, () -> falseResultNode.apply(this));
// ensure the test expression is boolean
if (testClause.getDecider().getType() != elseClause.getDecider().getType()) {
reportIncompatibleTypes(trueResultNode.parent(), elseClause.getDecider(), testClause.getDecider());
throw new AbortedStatementCompilationException();
}
OutputPin result = action.createResult(null, null);
OutputPin optionalValueOutput = testClause.getBodyOutputs().get(0);
OutputPin defaultValueOutput = elseClause.getBodyOutputs().get(0);
if (!TypeUtils.isCompatible(getRepository(), defaultValueOutput.getType(), optionalValueOutput.getType(), null)
|| !TypeUtils.isMultiplicityCompatible(optionalValueOutput, defaultValueOutput, false, true)) {
reportIncompatibleTypes(falseResultNode, defaultValueOutput, optionalValueOutput);
throw new AbortedStatementCompilationException();
}
TypeUtils.copyType(optionalValueOutput, result);
result.setLower(Math.max(optionalValueOutput.getLower(), defaultValueOutput.getLower()));
builder.registerOutput(result);
fillDebugInfo(action, trueResultNode.parent());
});
}
private void handleElvisOperator(Node left, Node right) {
ConditionalNode conditional = buildConditionalExpression(left, right, () -> handleUnaryExpressionAsOperation(left, left, "notNull"));
OutputPin mainOutput = conditional.getClauses().get(0).getBodyOutputs().get(0);
ensure(
!TypeUtils.isRequiredPin(mainOutput),
left,
() -> new UnclassifiedProblem("Expression must be optional")
);
MDDExtensionUtils.makeDefaultValueExpression(conditional);
}
@Override
public void caseATernaryExpression(ATernaryExpression node) {
buildConditionalExpression(node.getTrueExpression(), node.getFalseExpression(), () -> node.getCondition().apply(this));
}
private void handleSameBinaryOperator(Node left, Node right) {
TestIdentityAction action = (TestIdentityAction) builder.createAction(IRepository.PACKAGE
.getTestIdentityAction());
try {
builder.registerInput(action.createFirst(null, null));
builder.registerInput(action.createSecond(null, null));
left.apply(this);
right.apply(this);
TypeUtils.copyType(ActivityUtils.getSource(action.getFirst()), action.getFirst());
TypeUtils.copyType(ActivityUtils.getSource(action.getSecond()), action.getSecond());
Classifier expressionType = BasicTypeUtils.findBuiltInType("Boolean");
builder.registerOutput(action.createResult(null, expressionType));
fillDebugInfo(action, left.parent());
} finally {
builder.closeAction();
}
checkIncomings(action, left.parent(), getBoundElement());
}
private void handleRequiredUnaryOperator(Node operand) {
// cast input as required (preserving type information
buildCast(operand, action -> {
InputPin input = action.getStructuredNodeInputs().get(0);
OutputPin output = action.getStructuredNodeOutputs().get(0);
ensure(!TypeUtils.isRequired(input), operand, () -> buildTypeMismatchProblem(output, input));
TypeUtils.copyType(input, output);
output.setLower(1);
});
}
private void handleIsClassifiedOperator(Node left, Node right) {
ReadIsClassifiedObjectAction action = (ReadIsClassifiedObjectAction) builder.createAction(IRepository.PACKAGE
.getReadIsClassifiedObjectAction());
Node parent = left.parent();
try {
if (!(right instanceof AMinimalTypeIdentifier)) {
problemBuilder.addError("A qualified identifier is expected",
right);
throw new AbortedStatementCompilationException();
}
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(right);
Classifier classifier = (Classifier) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
ensure(classifier != null, right, () -> new UnknownType(qualifiedIdentifier));
builder.registerInput(action.createObject(null, null));
left.apply(this);
Classifier expressionType = BasicTypeUtils.findBuiltInType("Boolean");
builder.registerOutput(action.createResult(null, expressionType));
action.setClassifier(classifier);
fillDebugInfo(action, parent);
} finally {
builder.closeAction();
}
checkIncomings(action, parent, getBoundElement());
}
/**
* Blocks can be simple (curly brackets) or wordy (begin...end). Regardless
* the delimiters, the kernel of the block is processed here.
*/
@Override
public void caseABlockKernel(ABlockKernel node) {
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, block -> {
CommentUtils.applyComment(node.getModelComment(), block);
fillDebugInfo(builder.getCurrentBlock(), node);
BehaviorGenerator.super.caseABlockKernel(node);
// isolation determines whether the block should be treated as a
// transaction
Activity currentActivity = builder.getCurrentActivity();
if (!MDDExtensionUtils.isClosure(currentActivity))
if (ActivityUtils.shouldIsolate(builder.getCurrentBlock())) {
builder.getCurrentBlock().setMustIsolate(true);
// if blocks themselves are isolated, the main body does not
// need isolation
ActivityUtils.getBodyNode(currentActivity).setMustIsolate(false);
}
});
}
@Override
public void caseAExpressionSimpleBlockResolved(AExpressionSimpleBlockResolved node) {
createBlock(false, () ->
buildReturnStatement(node.getSimpleExpressionBlock())
);
}
@Override
public void caseAClassAttributeIdentifierExpression(AClassAttributeIdentifierExpression node) {
String typeIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
Classifier targetClassifier = (Classifier) getRepository().findNamedElement(typeIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentNamespace(null));
if (targetClassifier == null) {
problemBuilder.addError("Class reference expected: '" + typeIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute = FeatureUtils.findAttribute(targetClassifier, attributeIdentifier, false, true);
if (attribute != null) {
buildReadStaticStructuralFeature(targetClassifier, attribute, node);
return;
}
if (targetClassifier instanceof Enumeration) {
EnumerationLiteral enumerationValue = ((Enumeration) targetClassifier).getOwnedLiteral(attributeIdentifier);
if (enumerationValue != null) {
InstanceValue valueSpec = (InstanceValue) namespaceTracker.currentPackage().createPackagedElement(null,
IRepository.PACKAGE.getInstanceValue());
valueSpec.setInstance(enumerationValue);
valueSpec.setType(targetClassifier);
buildValueSpecificationAction(valueSpec, node);
return;
}
}
if (targetClassifier instanceof StateMachine) {
Vertex state = StateMachineUtils.getState((StateMachine) targetClassifier, attributeIdentifier);
if (state != null) {
ValueSpecification stateReference = MDDExtensionUtils.buildVertexLiteral(
namespaceTracker.currentPackage(), state);
buildValueSpecificationAction(stateReference, node);
return;
}
}
problemBuilder.addProblem(new UnknownAttribute(targetClassifier.getName(), attributeIdentifier, true),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
private void buildReadStaticStructuralFeature(Classifier targetClassifier, Property attribute,
AClassAttributeIdentifierExpression node) {
ReadStructuralFeatureAction action = (ReadStructuralFeatureAction) builder.createAction(IRepository.PACKAGE
.getReadStructuralFeatureAction());
try {
// // according to UML 2.1 §11.1, "(...) The semantics for static
// features is undefined. (...)"
// // our intepretation is that they are allowed and the input is a
// null value spec
// builder.registerInput(action.createObject(null, null));
// LiteralNull literalNull = (LiteralNull)
// currentPackage().createPackagedElement(null,
// IRepository.PACKAGE.getLiteralNull());
// buildValueSpecificationAction(literalNull, node);
builder.registerOutput(action.createResult(null, targetClassifier));
if (!attribute.isStatic()) {
problemBuilder.addError("Static attribute expected: '" + attribute.getName() + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setStructuralFeature(attribute);
// action.getObject().setType(targetClassifier);
TypeUtils.copyType(attribute, action.getResult(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
@Override
public void caseAClassOperationIdentifierExpression(final AClassOperationIdentifierExpression node) {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(
node.getMinimalTypeIdentifier());
Class targetClassifier = (Class) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClass_(), namespaceTracker.currentPackage());
if (targetClassifier == null) {
problemBuilder.addError("Class reference expected: '" + qualifiedIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
CallOperationAction action = (CallOperationAction) builder.createAction(IRepository.PACKAGE
.getCallOperationAction());
try {
int argumentCount = countElements(node.getExpressionList());
for (int i = 0; i < argumentCount; i++)
builder.registerInput(action.createArgument(null, null));
super.caseAClassOperationIdentifierExpression(node);
// collect sources so we can match the right operation (in
// case of overloading)
List<ObjectNode> sources = new ArrayList<ObjectNode>();
for (InputPin argument : action.getArguments())
sources.add(ActivityUtils.getSource(argument));
String operationName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Operation operation = findOperation(node.getIdentifier(), targetClassifier, operationName,
new ArrayList<TypedElement>(sources), true, true);
if (!operation.isQuery() && !PackageUtils.isModelLibrary(operation.getNearestPackage()))
ensureNotQuery(node);
if (operation.getReturnResult() == null)
ensureTerminal(node.getIdentifier());
action.setOperation(operation);
List<Parameter> inputParameters = FeatureUtils.getInputParameters(operation.getOwnedParameters());
Map<Type, Type> wildcardSubstitutions = FeatureUtils.buildWildcardSubstitutions(new HashMap<Type, Type>(),
inputParameters, sources);
int argumentPos = 0;
for (Parameter current : operation.getOwnedParameters()) {
switch (current.getDirection().getValue()) {
case ParameterDirectionKind.IN:
if (argumentPos == argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
throw new AbortedStatementCompilationException();
}
InputPin argument = action.getArguments().get(argumentPos++);
argument.setName(current.getName());
TypeUtils.copyType(current, argument, targetClassifier);
break;
case ParameterDirectionKind.RETURN:
// there should be only one of these
Assert.isTrue(action.getResults().isEmpty());
OutputPin result = builder.registerOutput(action.createResult(null, null));
TypeUtils.copyType(current, result, targetClassifier);
resolveWildcardTypes(wildcardSubstitutions, current, result);
break;
case ParameterDirectionKind.OUT:
case ParameterDirectionKind.INOUT:
Assert.isTrue(false);
}
}
if (argumentPos != argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
return;
}
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
/**
* In the context of an operation call, copies types from source to target
* for every target that still has a wildcard type.
*
* In the case of a target that is a signature,
*
* @param wildcardSubstitutions
* @param source
* @param target
*/
private void resolveWildcardTypes(Map<Type, Type> wildcardSubstitutions, TypedElement source, TypedElement target) {
if (wildcardSubstitutions.isEmpty())
return;
if (MDDExtensionUtils.isWildcardType(target.getType())) {
Type subbedType = wildcardSubstitutions.get(source.getType());
if (subbedType != null)
target.setType(subbedType);
} else if (MDDExtensionUtils.isSignature(target.getType())) {
List<Parameter> originalSignatureParameters = MDDExtensionUtils.getSignatureParameters(target.getType());
boolean signatureUsesWildcardTypes = false;
for (Parameter parameter : originalSignatureParameters) {
if (MDDExtensionUtils.isWildcardType(parameter.getType())) {
signatureUsesWildcardTypes = true;
break;
}
}
if (signatureUsesWildcardTypes) {
Activity closure = (Activity) ActivityUtils.resolveBehaviorReference((Action) ((OutputPin) source)
.getOwner());
Type resolvedSignature = MDDExtensionUtils.createSignature(namespaceTracker.currentNamespace(null));
for (Parameter closureParameter : closure.getOwnedParameters()) {
Parameter resolvedParameter = MDDExtensionUtils.createSignatureParameter(resolvedSignature,
closureParameter.getName(), closureParameter.getType());
resolvedParameter.setDirection(closureParameter.getDirection());
resolvedParameter.setUpper(closureParameter.getUpper());
}
target.setType(resolvedSignature);
}
}
}
@Override
public void caseAClosureOperand(AClosureOperand node) {
BehavioredClassifier parent = builder.getCurrentActivity();
StructuredActivityNode closureContext = builder.getCurrentBlock();
Activity closure = buildClosure(parent, closureContext, (AClosure) node.getClosure());
buildValueSpecificationAction(
ActivityUtils.buildBehaviorReference(namespaceTracker.currentPackage(), closure, null), node);
}
@Override
public void caseADestroySpecificStatement(ADestroySpecificStatement node) {
final DestroyObjectAction action = (DestroyObjectAction) builder.createAction(IRepository.PACKAGE
.getDestroyObjectAction());
final InputPin object;
try {
object = action.createTarget(null, null);
builder.registerInput(object);
super.caseADestroySpecificStatement(node);
final Type expressionType = ActivityUtils.getSource(object).getType();
object.setType(expressionType);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
@Override
public void caseAElseRestIf(AElseRestIf node) {
// all this gymnastic is to create the always-true test action
ValueSpecificationAction action = buildValueSpecificationAction(MDDUtil.createLiteralBoolean(namespaceTracker.currentPackage(), true), node);
Clause newClause = createClause();
newClause.getTests().add(action);
newClause.setDecider(action.getResult());
createClauseBody(newClause, () -> node.getClauseBody().apply(this));
checkIncomings(action, node.getElse(), getBoundElement());
}
@Override
public void caseAExtentIdentifierExpression(AExtentIdentifierExpression node) {
String classifierName = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
final Classifier classifier = (Classifier) getRepository().findNamedElement(classifierName,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder.addError("Unknown classifier '" + classifierName + "'", node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
ReadExtentAction action = (ReadExtentAction) builder.createAction(IRepository.PACKAGE.getReadExtentAction());
try {
action.setClassifier(classifier);
final OutputPin result = action.createResult(null, classifier);
result.setUpperValue(MDDUtil.createLiteralUnlimitedNatural(namespaceTracker.currentPackage(),
LiteralUnlimitedNatural.UNLIMITED));
result.setIsUnique(true);
builder.registerOutput(result);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
}
// TODO function call temporarily disabled
// /**
// * Processes a function invocation expression. We restrict function
// * invocations to be variable based.
// */
// @Override
// public void
// caseAFunctionIdentifierExpression(AFunctionIdentifierExpression node) {
// DynamicCallBehaviorAction action =
// (DynamicCallBehaviorAction) builder.createAction(MetaPackage.eINSTANCE
// .getDynamicCallBehaviorAction());
// try {
// // register the behavior input pin
// builder.registerInput(action.createBehavior(null, null));
// // register the argument input pins
// int argumentCount = countElements(node.getExpressionList());
// for (int i = 0; i < argumentCount; i++)
// builder.registerInput(action.createArgument(null, null));
// // process the variable and argument expressions - this will connect
// // their output pins to the input pins we just created
// super.caseAFunctionIdentifierExpression(node);
// // match the list of arguments with the behavior parameters
// final Type functionType =
// ActivityUtils.getSource(action.getBehavior()).getType();
// if (!(functionType instanceof Signature)) {
// problemBuilder.addProblem( new TypeMismatch("function type",
// functionType.getName()), node
// .getVariableAccess());
// throw new AbortedStatementCompilationException();
// }
// Signature signature = (Signature) functionType;
// Assert.isNotNull(signature, "Function not found");
// // collect argument types so we can match the right operation (in
// // case of overloading)
// List<ObjectNode> argumentSources = new ArrayList<ObjectNode>();
// for (InputPin argument : action.getArguments())
// argumentSources.add(ActivityUtils.getSource(argument));
// final List<Parameter> inputParameters =
// FeatureUtils.filterParameters(signature.getOwnedParameters(),
// ParameterDirectionKind.IN_LITERAL);
// if (!TypeUtils.isCompatible(getRepository(), argumentSources,
// inputParameters, null)) {
// problemBuilder.addProblem( new UnresolvedSymbol("Unknown function"),
// node.getVariableAccess());
// throw new AbortedStatementCompilationException();
// }
// int argumentPos = 0;
// for (Parameter current : signature.getOwnedParameters()) {
// OutputPin result;
// InputPin argument;
// switch (current.getDirection().getValue()) {
// case ParameterDirectionKind.IN:
// if (argumentPos == argumentCount) {
// problemBuilder.addError("Wrong number of arguments", node.getLParen());
// throw new AbortedStatementCompilationException();
// }
// argument = action.getArguments().get(argumentPos++);
// argument.setName(current.getName());
// TypeUtils.copyType(current, argument);
// break;
// case ParameterDirectionKind.RETURN:
// // there should be only one of these
// result = builder.registerOutput(action.createResult(null, null));
// TypeUtils.copyType(current, result);
// break;
// case ParameterDirectionKind.OUT:
// case ParameterDirectionKind.INOUT:
// Assert.isTrue(false);
// }
// }
// if (argumentPos != argumentCount) {
// problemBuilder.addError("Wrong number of arguments", node.getLParen());
// return;
// }
// // action.getBehavior().setType(targetClassifier);
// fillDebugInfo(action, node);
// } finally {
// builder.closeAction();
// }
// checkIncomings(action, node.getVariableAccess());
// }
@Override
public void caseAIfClause(AIfClause node) {
Clause newClause = createClause();
createClauseTest(newClause, () -> node.getTest().apply(this));
createClauseBody(newClause, () -> node.getClauseBody().apply(this));
}
@Override
public void caseAIfStatement(AIfStatement node) {
createBlock(IRepository.PACKAGE.getConditionalNode(), false, () ->
super.caseAIfStatement(node)
);
}
@Override
public void caseALinkIdentifierExpression(ALinkIdentifierExpression node) {
ReadLinkAction action = (ReadLinkAction) builder.createAction(IRepository.PACKAGE.getReadLinkAction());
try {
InputPin linkEndValue = builder.registerInput(action.createInputValue(null, null));
node.getIdentifierExpression().apply(this);
ObjectNode source = ActivityUtils.getSource(linkEndValue);
Classifier targetClassifier = (Classifier) TypeUtils.getTargetType(getRepository(), source, true);
Property openEnd = parseRole(targetClassifier, node.getAssociationTraversal());
Association association = openEnd.getAssociation();
linkEndValue.setType(targetClassifier);
int openEndIndex = association.getMemberEnds().indexOf(openEnd);
Property fedEnd = association.getMemberEnds().get(1 - openEndIndex);
LinkEndData endData = action.createEndData();
endData.setEnd(fedEnd);
endData.setValue(linkEndValue);
builder.registerOutput(action.createResult(null, openEnd.getType()));
TypeUtils.copyType(openEnd, action.getResult());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getAssociationTraversal(), getBoundElement());
}
private Property parseRole(Classifier sourceType, PAssociationTraversal node) {
return (node instanceof ASimpleAssociationTraversal) ? parseSimpleTraversal(sourceType,
(ASimpleAssociationTraversal) node) : parseQualifiedTraversal(sourceType,
(AQualifiedAssociationTraversal) node);
}
private Property parseSimpleTraversal(Classifier sourceType, ASimpleAssociationTraversal node) {
final String openEndName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property openEnd = sourceType.getAttribute(openEndName, null);
Association association;
if (openEnd == null) {
EList<Association> associations = sourceType.getAssociations();
for (Association current : associations)
if ((openEnd = current.getMemberEnd(openEndName, null)) != null)
break;
if (openEnd == null) {
problemBuilder.addProblem(new UnknownRole(sourceType.getQualifiedName() + NamedElement.SEPARATOR
+ openEndName), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
}
association = openEnd.getAssociation();
if (association == null) {
problemBuilder.addError(openEndName + " is not an association member end", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
return openEnd;
}
private Property parseQualifiedTraversal(Classifier sourceType, AQualifiedAssociationTraversal node) {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(
node.getMinimalTypeIdentifier());
final Association association = (Association) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getAssociation(), namespaceTracker.currentPackage());
if (association == null) {
problemBuilder.addError("Unknown association '" + qualifiedIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
Classifier associated = ClassifierUtils.findUpHierarchy(getRepository(), sourceType, it -> it.getRelationships(IRepository.PACKAGE.getAssociation()).contains(association) ? it : null);
if (associated == null) {
problemBuilder.addProblem(
new NotInAssociation(sourceType.getQualifiedName(), association.getQualifiedName()),
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
final String openEndName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
// XXX implementation limitation: only binary associations are
// supported
Property openEnd = association.getMemberEnd(openEndName, null);
if (openEnd == null) {
problemBuilder.addProblem(new UnknownRole(association.getQualifiedName(), openEndName),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
return openEnd;
}
@Override
public void caseALinkSpecificStatement(ALinkSpecificStatement node) {
buildWriteLinkAction(node, node.getMinimalTypeIdentifier(), IRepository.PACKAGE.getCreateLinkAction());
}
private void buildWriteLinkAction(Node linkStatementNode, Node associationIdentifierNode, EClass linkActionClass) {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(associationIdentifierNode);
final Association association = (Association) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getAssociation(), namespaceTracker.currentPackage());
if (association == null) {
problemBuilder.addError("Unknown association '" + qualifiedIdentifier + "'", associationIdentifierNode);
throw new AbortedStatementCompilationException();
}
final WriteLinkAction action = (WriteLinkAction) builder.createAction(linkActionClass);
try {
linkStatementNode.apply(new DepthFirstAdapter() {
@Override
public void caseALinkRole(ALinkRole node) {
String roleName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property end = association.getMemberEnd(roleName, null);
if (end == null) {
problemBuilder.addProblem(new UnknownRole(association.getQualifiedName(), roleName),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
LinkEndData endData = action.createEndData();
endData.setEnd(end);
InputPin input = action.createInputValue(null, end.getType());
input.setLower(end.getLower());
input.setUpper(end.getUpper());
endData.setValue(input);
builder.registerInput(input);
node.getRootExpression().apply(BehaviorGenerator.this);
}
});
// TODO need to validate that all ends declared have input values,
// no repetitions, etc
fillDebugInfo(action, linkStatementNode);
} finally {
builder.closeAction();
}
checkIncomings(action, linkStatementNode, getBoundElement());
}
@Override
public void caseAFunctionIdentifierExpression(AFunctionIdentifierExpression node) {
String functionName = sourceMiner.getIdentifier(node.getVariableAccess());
problemBuilder.addProblem(new UnclassifiedProblem("Function call not supported yet: " + functionName),
node.getVariableAccess());
throw new AbortedStatementCompilationException();
}
@Override
public void caseALiteralOperand(ALiteralOperand node) {
ValueSpecification value = LiteralValueParser.parseLiteralValue(node.getLiteral(),
namespaceTracker.currentPackage(), problemBuilder);
buildValueSpecificationAction(value, node);
}
@Override
public void caseAEmptySet(AEmptySet node) {
final ValueSpecificationAction action = (ValueSpecificationAction) builder.createAction(IRepository.PACKAGE
.getValueSpecificationAction());
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(
node.getMinimalTypeIdentifier());
Classifier classifier = (Classifier) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder.addProblem(new UnknownType(qualifiedIdentifier), node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
try {
ValueSpecification emptySetValue = MDDExtensionUtils.buildEmptySet(namespaceTracker.currentPackage(), classifier);
action.setValue(emptySetValue);
OutputPin result = action.createResult(null, classifier);
result.setUpperValue(MDDUtil.createLiteralUnlimitedNatural(namespaceTracker.currentPackage(),
LiteralUnlimitedNatural.UNLIMITED));
builder.registerOutput(result);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
@Override
public void caseALoopSpecificStatement(ALoopSpecificStatement node) {
LoopNode loop = (LoopNode) createBlock(IRepository.PACKAGE.getLoopNode(), false, () ->
super.caseALoopSpecificStatement(node)
);
loop.setIsTestedFirst(true);
}
@Override
public void caseALoopTest(ALoopTest node) {
LoopNode currentLoop = (LoopNode) builder.getCurrentBlock();
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, () -> {
super.caseALoopTest(node);
currentLoop.getTests().add(builder.getCurrentBlock());
final OutputPin decider = ActivityUtils.getActionOutputs(builder.getLastRootAction()).get(0);
currentLoop.setDecider(decider);
});
}
@Override
public void caseANewIdentifierExpression(final ANewIdentifierExpression node) {
ensureNotQuery(node);
final CreateObjectAction action = (CreateObjectAction) builder.createAction(IRepository.PACKAGE
.getCreateObjectAction());
try {
super.caseANewIdentifierExpression(node);
final OutputPin output = builder.registerOutput(action.createResult(null, null));
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(
node.getMinimalTypeIdentifier());
Classifier classifier = (Classifier) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder.addError("Unknown classifier '" + qualifiedIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
if (classifier.isAbstract()) {
problemBuilder.addProblem(new NotAConcreteClassifier(qualifiedIdentifier),
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
output.setType(classifier);
action.setClassifier(classifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getNew(), getBoundElement());
}
private void ensureNotQuery(Node node) {
boolean isReadOnly = builder.getCurrentActivity().isReadOnly();
QueryOperationsMustBeSideEffectFree.ensure(!isReadOnly, problemBuilder, node);
}
@Override
public void caseASendSpecificStatement(ASendSpecificStatement node) {
ensureNotQuery(node);
final SendSignalAction action = (SendSignalAction) builder.createAction(IRepository.PACKAGE
.getSendSignalAction());
try {
final String signalIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getSignal());
final Signal signal = this.context.getRepository().findNamedElement(signalIdentifier,
UMLPackage.Literals.SIGNAL, namespaceTracker.currentNamespace(null));
if (signal == null) {
problemBuilder.addError("Unknown signal '" + signalIdentifier + "'", node.getSignal());
throw new AbortedStatementCompilationException();
}
builder.registerInput(action.createTarget(null, null));
node.getTarget().apply(this);
if (node.getNamedArgumentList() != null)
node.getNamedArgumentList().apply(new DepthFirstAdapter() {
@Override
public void caseANamedArgument(ANamedArgument node) {
String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute = FeatureUtils.findAttribute(signal, attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addProblem(
new UnknownAttribute(signal.getName(), attributeIdentifier, false),
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
InputPin signalArgument = action.createArgument(attribute.getName(), null);
TypeUtils.copyType(attribute, signalArgument);
builder.registerInput(signalArgument);
node.getExpression().apply(BehaviorGenerator.this);
}
});
for (Property signalAttribute : signal.getAllAttributes())
if (signalAttribute.getLower() == 1 && signalAttribute.getDefaultValue() == null
&& action.getArgument(signalAttribute.getName(), signalAttribute.getType()) == null) {
problemBuilder.addProblem(new MissingRequiredArgument(signalAttribute.getName()), node);
throw new AbortedStatementCompilationException();
}
action.setSignal(signal);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getSignal(), getBoundElement());
}
@Override
public void caseABroadcastSpecificStatement(ABroadcastSpecificStatement node) {
SendSignalAction action = (SendSignalAction) builder.createAction(IRepository.PACKAGE.getSendSignalAction());
try {
super.caseABroadcastSpecificStatement(node);
final String signalIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getSignal());
Signal signal = this.context.getRepository().findNamedElement(signalIdentifier, UMLPackage.Literals.SIGNAL,
namespaceTracker.currentNamespace(null));
if (signal == null) {
problemBuilder.addError("Unknown signal '" + signalIdentifier + "'", node.getSignal());
throw new AbortedStatementCompilationException();
}
action.setSignal(signal);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getSignal(), getBoundElement());
}
// FIXME a lot of duplication between this and
// caseAClassOperationIdentifierExpression
@Override
public void caseAOperationIdentifierExpression(AOperationIdentifierExpression node) {
Classifier targetClassifier = null;
String operationName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
CallOperationAction action = (CallOperationAction) builder.createAction(IRepository.PACKAGE
.getCallOperationAction());
try {
// register the target input pin
builder.registerInput(action.createTarget(null, null));
// register the argument input pins
int argumentCount = countElements(node.getExpressionList());
for (int i = 0; i < argumentCount; i++)
builder.registerInput(action.createArgument(null, null));
// process the target and argument expressions - this will connect
// their output pins to the input pins we just created
super.caseAOperationIdentifierExpression(node);
final ObjectNode targetSource = ActivityUtils.getSource(action.getTarget());
checkIfTargetIsRequired(node.getTarget(), targetSource);
targetClassifier = (Classifier) TypeUtils.getTargetType(getRepository(), targetSource, true);
if (targetClassifier == null) {
problemBuilder.addProblem(new UnclassifiedProblem(Severity.ERROR,
"Could not determine the type of the target"), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
// collect sources so we can match the right operation (in
// case of overloading)
List<TypedElement> sources = new ArrayList<TypedElement>();
for (InputPin argument : action.getArguments()) {
ObjectNode argumentSource = ActivityUtils.getSource(argument);
if (argumentSource == null) {
problemBuilder.addProblem(new UnclassifiedProblem(Severity.ERROR,
"One of the arguments does not produce a result value"), node.getExpressionList());
throw new AbortedStatementCompilationException();
}
sources.add(argumentSource);
}
Operation operation = findOperation(node.getIdentifier(), targetClassifier, operationName, sources, false,
true);
if (!operation.isQuery() && !PackageUtils.isModelLibrary(operation.getNearestPackage()))
ensureNotQuery(node);
if (operation.getReturnResult() == null)
ensureTerminal(node.getIdentifier());
action.setOperation(operation);
List<Parameter> inputParameters = FeatureUtils.getInputParameters(operation.getOwnedParameters());
Map<Type, Type> wildcardSubstitutions = FeatureUtils.buildWildcardSubstitutions(new HashMap<Type, Type>(),
inputParameters, sources);
int argumentPos = 0;
for (Parameter current : operation.getOwnedParameters()) {
OutputPin result;
InputPin argument;
switch (current.getDirection().getValue()) {
case ParameterDirectionKind.IN:
case ParameterDirectionKind.INOUT:
if (argumentPos == argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
throw new AbortedStatementCompilationException();
}
argument = action.getArguments().get(argumentPos++);
argument.setName(current.getName());
TypeUtils.copyType(current, argument, targetClassifier);
break;
case ParameterDirectionKind.RETURN:
// there should be only one of these
Assert.isTrue(action.getResults().isEmpty());
result = builder.registerOutput(action.createResult(null, null));
TypeUtils.copyType(current, result, targetClassifier);
resolveWildcardTypes(wildcardSubstitutions, current, result);
if (!TypeUtils.isRequiredPin(targetSource) && !TypeUtils.isMultivalued(targetSource))
// it is a tentative call, result must be optional
result.setLower(0);
break;
case ParameterDirectionKind.OUT:
Assert.isTrue(false);
}
}
if (argumentPos != argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
return;
}
// set the type of the target input pin using copy type so we
// understand collections
TypeUtils.copyType(targetSource, action.getTarget(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), targetClassifier);
}
private void checkIfTargetIsRequired(PTarget targetNode, final ObjectNode targetSource) {
boolean requiredTargetExpected = sourceMiner.findChild(targetNode, ARequiredTargetObjectDot.class, true) != null;
if (requiredTargetExpected)
ensure(TypeUtils.isRequiredPin(targetSource) || TypeUtils.isMultivalued(targetSource), targetNode, () -> new RequiredValueExpected());
else
ensure(!TypeUtils.isRequiredPin(targetSource) || TypeUtils.isMultivalued(targetSource), targetNode, () -> new OptionalValueExpected());
}
private void ensureTerminal(Node identifierNode) {
if (!builder.isCurrentActionTerminal()) {
String operationName = TextUMLCore.getSourceMiner().getIdentifier(identifierNode);
problemBuilder.addProblem(
new UnclassifiedProblem("Operation " + operationName + " does not have a result"), identifierNode);
throw new AbortedStatementCompilationException();
}
}
@Override
public void caseARaiseSpecificStatement(ARaiseSpecificStatement node) {
final RaiseExceptionAction action = (RaiseExceptionAction) builder.createAction(IRepository.PACKAGE
.getRaiseExceptionAction());
final InputPin exception;
try {
exception = action.createException(null, null);
builder.registerInput(exception);
super.caseARaiseSpecificStatement(node);
final Type exceptionType = ActivityUtils.getSource(exception).getType();
exception.setType(exceptionType);
if (ActivityUtils.findHandler(action, (Classifier) exceptionType, true) == null)
if (!builder.getCurrentActivity().getSpecification().getRaisedExceptions().contains(exceptionType))
problemBuilder.addWarning("Exception '" + exceptionType.getQualifiedName()
+ "' is not declared by operation", node.getRootExpression());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getRaise(), getBoundElement());
// a raise exception action is a final action
ActivityUtils.makeFinal(builder.getCurrentBlock(), action);
}
@Override
public void caseARepeatLoopBody(ARepeatLoopBody node) {
LoopNode currentLoop = (LoopNode) builder.getCurrentBlock();
currentLoop.setIsTestedFirst(false);
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, () -> {
super.caseARepeatLoopBody(node);
currentLoop.getBodyParts().add(builder.getCurrentBlock());
});
}
@Override
public void caseATryStatement(ATryStatement node) {
if (node.getCatchSection() == null && node.getFinallySection() == null) {
problemBuilder.addError("One or both catch and finally sections are required", node.getTry());
throw new AbortedStatementCompilationException();
}
createBlock(false, () -> {
if (node.getCatchSection() != null)
node.getCatchSection().apply(this);
node.getProtectedBlock().apply(this);
});
}
@Override
public void caseACatchSection(ACatchSection node) {
StructuredActivityNode protectedBlock = builder.getCurrentBlock();
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, (handlerBlock) -> {
// declare exception variable
node.getVarDecl().apply(this);
node.getHandlerBlock().apply(this);
Variable exceptionVar = handlerBlock.getVariables().get(0);
ExceptionHandler exceptionHandler = protectedBlock.createHandler();
exceptionHandler.getExceptionTypes().add((Classifier) exceptionVar.getType());
InputPin exceptionInputPin = (InputPin) handlerBlock.createNode(exceptionVar.getName(),
UMLPackage.Literals.INPUT_PIN);
exceptionInputPin.setType(exceptionVar.getType());
exceptionHandler.setExceptionInput(exceptionInputPin);
exceptionHandler.setHandlerBody(handlerBlock);
});
}
@Override
public void caseASelfIdentifierExpression(ASelfIdentifierExpression node) {
ReadSelfAction action = (ReadSelfAction) builder.createAction(IRepository.PACKAGE.getReadSelfAction());
try {
super.caseASelfIdentifierExpression(node);
Activity currentActivity = builder.getCurrentActivity();
while (MDDExtensionUtils.isClosure(currentActivity)) {
// TODO refactor to use ActivityUtils
ActivityNode rootNode = MDDExtensionUtils.getClosureContext(currentActivity);
currentActivity = ActivityUtils.getActionActivity(rootNode);
}
final BehavioralFeature operation = currentActivity.getSpecification();
boolean staticContext = false;
if (operation != null) {
staticContext = operation.isStatic();
} else if (MDDExtensionUtils.isConstraintBehavior(currentActivity)) {
Constraint constraint = MDDExtensionUtils.getBehaviorConstraint(currentActivity);
staticContext = MDDExtensionUtils.isStaticConstraint(constraint);
}
if (staticContext) {
problemBuilder.addProblem(new ReadSelfFromStaticContext(), node);
throw new AbortedStatementCompilationException();
}
Classifier currentClassifier = ActivityUtils.getContext(currentActivity);
if (currentClassifier == null) {
problemBuilder.addProblem(new InternalProblem("Could not determine context"), node);
throw new AbortedStatementCompilationException();
}
OutputPin result = action.createResult(null, currentClassifier);
result.setLower(1);
result.setUpper(1);
builder.registerOutput(result);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getSelf(), getBoundElement());
}
// TODO temporarily disabled during refactor to remove metamodel extensions
// @Override
// public void
// caseASetLiteralIdentifierExpression(ASetLiteralIdentifierExpression node)
// {
// String qualifiedIdentifier =
// Util.parseQualifiedIdentifier(node.getMinimalTypeIdentifier());
// final Classifier classifier =
// (Classifier) getRepository().findNamedElement(qualifiedIdentifier,
// IRepository.PACKAGE.getClassifier(), currentPackage());
// if (classifier == null) {
// problemBuilder.addError("Unknown classifier '" + qualifiedIdentifier +
// "'", node
// .getMinimalTypeIdentifier());
// throw new AbortedStatementCompilationException();
// }
//
// final CollectionLiteral valueSpec =
// (CollectionLiteral) currentPackage().createPackagedElement(null,
// MetaPackage.eINSTANCE.getCollectionLiteral());
// valueSpec.setType(classifier);
// node.apply(new DepthFirstAdapter() {
// @Override
// public void caseASetValue(ASetValue node) {
// // TODO create a value specification and add it to
// ValueSpecification value =
// MDDUtil.createUnlimitedNatural(classifier.getNearestPackage(),
// valueSpec.getValues()
// .size());
// valueSpec.getValues().add(value);
// super.caseASetValue(node);
// }
// });
// ValueSpecificationAction valueSpecAction =
// buildValueSpecificationAction(valueSpec, node);
// final OutputPin outputPin = valueSpecAction.getOutputs().get(0);
// outputPin.setLowerValue(MDDUtil.createUnlimitedNatural(classifier.getNearestPackage(),
// 0));
// outputPin.setUpperValue(MDDUtil.createUnlimitedNatural(classifier.getNearestPackage(),
// null));
// }
@Override
public void caseAStatement(AStatement node) {
try {
super.caseAStatement(node);
processAnnotations(node.getAnnotations(), this.builder.getLastRootAction());
} catch (AbortedStatementCompilationException e) {
// aborted statement compilation...
if (builder.isDebug())
LogUtils.logWarning(TextUMLCore.PLUGIN_ID, null, e);
} catch (AbortedCompilationException e) {
// we don't handle those here
throw e;
} catch (AssertionError e) {
LogUtils.logError(TextUMLCore.PLUGIN_ID, "Assertion failed", e);
problemBuilder.addError("Exception: " + e.toString(), node);
} catch (RuntimeException e) {
LogUtils.logError(TextUMLCore.PLUGIN_ID, "Unexpected exception", e);
problemBuilder.addError("Exception: " + e.toString(), node);
}
}
@Override
public void caseAParenthesisOperand(AParenthesisOperand node) {
ACast cast = (ACast) node.getCast();
if (cast == null) {
// no casting, just process inner expression
node.getExpression().apply(this);
return;
}
PTypeIdentifier typeIdentifier = cast.getTypeIdentifier();
buildCast(node.getExpression(), action ->
new TypeSetter(
sourceContext,
namespaceTracker.currentNamespace(null),
action.getStructuredNodeOutputs().get(0)
).process(typeIdentifier)
);
}
private void buildCast(Node expression, Consumer<StructuredActivityNode> doIt) {
StructuredActivityNode action = (StructuredActivityNode) builder
.createAction(Literals.STRUCTURED_ACTIVITY_NODE);
MDDExtensionUtils.makeCast(action);
try {
// register the target input pin (type is null)
InputPin inputPin = (InputPin) action.createStructuredNodeInput(null, null);
builder.registerInput(inputPin);
// process the target expression - this will connect its output pin
// to the input pin we just created
expression.apply(this);
// copy whatever multiplicity coming into the source to the source
// but leave type as undefined as this action is supposed to accept any type of input
ObjectNode inputSource = ActivityUtils.getSource(inputPin);
TypeUtils.copyMultiplicity((MultiplicityElement) inputSource, inputPin);
// register the result output pin
OutputPin outputPin = (OutputPin) action.createStructuredNodeOutput(null, null);
doIt.accept(action);
builder.registerOutput(outputPin);
fillDebugInfo(action, expression);
} finally {
builder.closeAction();
}
checkIncomings(action, expression, getBoundElement());
}
public Action handleUnaryExpressionAsOperation(Node operator, Node operand, String operationName) {
return handleUnaryExpressionAsOperation(operator, operationName, () -> {
operand.apply(BehaviorGenerator.this);
return operand;
});
}
public Action handleUnaryExpressionAsOperation(Node contextNode, String operationName, Supplier<Node> childProcessor) {
CallOperationAction action = (CallOperationAction) builder.createAction(IRepository.PACKAGE
.getCallOperationAction());
try {
// register the target input pin
builder.registerInput(action.createTarget(null, null));
// process the target expression - this will connect its output pin
// to the input pin we just created
Node childNode = childProcessor.get();
InputPin target = action.getTarget();
ObjectNode targetSource = ActivityUtils.getSource(target);
Type targetType = targetSource.getType();
ensure(targetType != null, childNode, () -> new UnclassifiedProblem("No type information for " + childNode));
Operation operation = FeatureUtils.findOperation(getRepository(), (Classifier) targetType, operationName, Arrays.asList(), false, true);
TypeUtils.copyType(targetSource, target);
if (operation == null) {
missingOperation(true, contextNode, (Classifier) targetType, operationName,
Arrays.asList(), false);
}
ensure(TypeUtils.isRequired(target) || FeatureUtils.isBasicOperation(operation), childNode, () ->
new RequiredValueExpected());
// register the result output pin
OutputPin result = action.createResult(null, operation.getType());
builder.registerOutput(result);
result.setLower(Math.min(target.getLower(), operation.getReturnResult().getLower()));
action.setOperation(operation);
fillDebugInfo(action, contextNode.parent());
} finally {
builder.closeAction();
}
checkIncomings(action, contextNode, getBoundElement());
return action;
}
@Override
public void caseAUnlinkSpecificStatement(AUnlinkSpecificStatement node) {
buildWriteLinkAction(node, node.getMinimalTypeIdentifier(), IRepository.PACKAGE.getDestroyLinkAction());
}
@Override
public void caseAEmptyReturnSpecificStatement(AEmptyReturnSpecificStatement node) {
Variable variable = builder.getReturnValueVariable();
if (variable != null) {
problemBuilder.addProblem(new ReturnValueRequired(), node.getReturn());
throw new AbortedScopeCompilationException();
}
Action previousStatement = builder.getLastRootAction();
if (previousStatement != null)
ActivityUtils.makeFinal(builder.getCurrentBlock(), previousStatement);
}
@Override
public void caseAValuedReturnSpecificStatement(AValuedReturnSpecificStatement node) {
buildReturnStatement(node.getRootExpression());
}
protected void buildReturnStatement(Node node) {
TemplateableElement bound = (Class) MDDUtil.getNearest(builder.getCurrentActivity(),
IRepository.PACKAGE.getClass_());
AddVariableValueAction action = (AddVariableValueAction) builder.createAction(IRepository.PACKAGE
.getAddVariableValueAction());
try {
Variable variable = builder.getReturnValueVariable();
if (variable == null) {
problemBuilder.addProblem(new ReturnValueNotExpected(), node);
throw new AbortedScopeCompilationException();
}
final InputPin value = builder.registerInput(action.createValue(null, null));
node.apply(this);
action.setVariable(variable);
TypeUtils.copyType(variable, value, bound);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
ActivityUtils.makeFinal(builder.getCurrentBlock(), action);
}
@Override
public void caseAVarDecl(final AVarDecl node) {
super.caseAVarDecl(node);
String varIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
final Variable var = builder.getCurrentBlock().createVariable(varIdentifier, null);
if (node.getOptionalType() != null)
// type is optional for local vars
new TypeSetter(sourceContext, namespaceTracker.currentNamespace(null), var).process(node.getOptionalType());
else {
// ensure a type is eventually inferred
defer(Step.BEHAVIOR, r -> {
ensure(var.getType() != null, node.getIdentifier(), Severity.ERROR, () -> "Could not infer a type for variable '" + var.getName() + "'");
});
}
}
@Override
public void caseAVariableAccess(AVariableAccess node) {
ReadVariableAction action = (ReadVariableAction) builder.createAction(IRepository.PACKAGE
.getReadVariableAction());
try {
super.caseAVariableAccess(node);
final OutputPin result = action.createResult(null, null);
builder.registerOutput(result);
String variableName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Variable variable = builder.getVariable(variableName);
ensure(variable != null, node.getIdentifier(), Severity.ERROR, () -> "Unknown local variable '" + variableName + "'");
action.setVariable(variable);
TypeUtils.copyType(variable, result, getBoundElement());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
private Class getBoundElement() {
return (Class) MDDUtil.getNearest(builder.getCurrentActivity().getOwner(), IRepository.PACKAGE.getClass_());
}
@Override
public void caseAWhileLoopBody(AWhileLoopBody node) {
LoopNode currentLoop = (LoopNode) builder.getCurrentBlock();
currentLoop.setIsTestedFirst(true);
createBlock(IRepository.PACKAGE.getStructuredActivityNode(), false, () -> {
super.caseAWhileLoopBody(node);
currentLoop.getBodyParts().add(builder.getCurrentBlock());
});
}
@Override
public void caseAWriteAttributeSpecificStatement(AWriteAttributeSpecificStatement node) {
AddStructuralFeatureValueAction action = (AddStructuralFeatureValueAction) builder
.createAction(IRepository.PACKAGE.getAddStructuralFeatureValueAction());
final String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
action.setIsReplaceAll(true);
try {
builder.registerInput(action.createObject(null, null));
builder.registerInput(action.createValue(null, null));
super.caseAWriteAttributeSpecificStatement(node);
ObjectNode targetSource = ActivityUtils.getSource(action.getObject());
Classifier targetClassifier = (Classifier) targetSource.getType();
if (targetClassifier == null) {
problemBuilder.addError("Object type not determined for '"
+ ((ATarget) node.getTarget()).getOperand().toString().trim() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
Property attribute = FeatureUtils.findAttribute(targetClassifier, attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addError(
"Unknown attribute '" + attributeIdentifier + "' in '" + targetClassifier.getName() + "'",
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (attribute.isDerived()) {
problemBuilder.addProblem(new CannotModifyADerivedAttribute(), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
checkIfTargetIsRequired(node.getTarget(), targetSource);
ensureNotQuery(node);
action.setStructuralFeature(attribute);
action.getObject().setType(targetClassifier);
TypeUtils.copyType(attribute, action.getValue(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
@Override
public void caseAWriteClassAttributeSpecificStatement(AWriteClassAttributeSpecificStatement node) {
ensureNotQuery(node);
TemplateableElement bound = null;
AddStructuralFeatureValueAction action = (AddStructuralFeatureValueAction) builder
.createAction(IRepository.PACKAGE.getAddStructuralFeatureValueAction());
action.setIsReplaceAll(true);
try {
String typeIdentifier = TextUMLCore.getSourceMiner()
.getQualifiedIdentifier(node.getMinimalTypeIdentifier());
Classifier targetClassifier = (Classifier) getRepository().findNamedElement(typeIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (targetClassifier == null) {
problemBuilder.addError("Class reference expected: '" + typeIdentifier + "'",
node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
bound = targetClassifier;
final String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute = FeatureUtils.findAttribute(targetClassifier, attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addError(
"Unknown attribute '" + attributeIdentifier + "' in '" + targetClassifier.getName() + "'",
node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (attribute.isDerived()) {
problemBuilder.addProblem(new CannotModifyADerivedAttribute(), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (!attribute.isStatic()) {
problemBuilder.addError("Static attribute expected: '" + attributeIdentifier + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
builder.registerInput(action.createValue(null, null));
// builds expression
node.getRootExpression().apply(this);
action.setStructuralFeature(attribute);
TypeUtils.copyType(attribute, action.getValue(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), bound);
}
@Override
public void caseAWriteVariableSpecificStatement(AWriteVariableSpecificStatement node) {
AddVariableValueAction action = (AddVariableValueAction) builder.createAction(IRepository.PACKAGE
.getAddVariableValueAction());
action.setIsReplaceAll(true);
try {
final InputPin value = builder.registerInput(action.createValue(null, null));
super.caseAWriteVariableSpecificStatement(node);
String variableName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Variable variable = builder.getVariable(variableName);
if (variable == null) {
problemBuilder.addError("Unknown local variable '" + variableName + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setVariable(variable);
if (variable.getType() == null)
// infer variable type if omitted
TypeUtils.copyType(ActivityUtils.getSource(value), variable, getBoundElement());
TypeUtils.copyType(variable, value, getBoundElement());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
private void checkIncomings(final Action action, final Node node, TemplateableElement bound) {
ObjectFlow incompatible = TypeUtils.checkCompatibility(getRepository(), action, bound);
if (incompatible == null)
return;
final ObjectNode target = ((ObjectNode) incompatible.getTarget());
final ObjectNode source = ((ObjectNode) incompatible.getSource());
final Type anyType = findBuiltInType(TypeUtils.ANY_TYPE, node);
if (target.getType() != null && target.getType() != anyType
&& (source.getType() == null || source.getType() == anyType))
source.setType(target.getType());
else
reportIncompatibleTypes(node, target, source);
checkAllInputsHaveFlows(action, node);
}
private void checkAllInputsHaveFlows(Action action, Node node) {
boolean alreadyReportedErrors = !problemBuilder.hasErrors();
if (!alreadyReportedErrors)
ActivityUtils.getActionInputs(action).stream().forEach(input -> {
if (input.getIncomings().isEmpty())
problemBuilder.addProblem(new UnclassifiedProblem("Missing incoming flow for input pin " + StringUtils.trimToEmpty(input.getName())), node);
});
}
private void reportIncompatibleTypes(final Node context, final ObjectNode expected, final ObjectNode actual) {
problemBuilder.addProblem(buildTypeMismatchProblem(expected, actual),
context);
}
private TypeMismatch buildTypeMismatchProblem(final ObjectNode expected, final ObjectNode actual) {
return new TypeMismatch(MDDUtil.getDisplayName(expected), MDDUtil.getDisplayName(actual));
}
private int countElements(PExpressionList list) {
if (list instanceof AEmptyExpressionList)
return 0;
final int[] counter = { 0 };
list.apply(new DepthFirstAdapter() {
@Override
public void caseAExpressionListElement(AExpressionListElement node) {
counter[0]++;
}
});
return counter[0];
}
/**
* Fills in the given activity with behavior parsed from the given node.
*/
public void createBody(Node bodyNode, Activity activity) {
namespaceTracker.enterNamespace(activity);
try {
builder.createRootBlock(activity);
try {
bodyNode.apply(this);
} finally {
builder.closeRootBlock();
}
} finally {
namespaceTracker.leaveNamespace();
}
defer(Step.BEHAVIOR, r -> validateReturnStatement(bodyNode, activity));
// process any deferred activities
while (!deferredActivities.isEmpty()) {
DeferredActivity next = deferredActivities.remove(0);
createBody(next.getBlock(), next.getActivity());
}
}
public void validateReturnStatement(Node bodyNode, Activity activity) {
boolean hasReturnWithValue = ActivityUtils.getFinalAction(ActivityUtils.getBodyNode(activity)) == null;
if (!problemBuilder.hasErrors() && hasReturnWithValue) {
boolean returnValueRequired = FeatureUtils.findReturnParameter(activity.getOwnedParameters()) != null;
ensure(!returnValueRequired, bodyNode, () -> new ReturnStatementRequired());
}
}
private Clause createClause() {
ConditionalNode currentConditional = (ConditionalNode) builder.getCurrentBlock();
boolean hasClauses = !currentConditional.getClauses().isEmpty();
Clause newClause = currentConditional.createClause();
if (hasClauses) {
Clause previousClause = currentConditional.getClauses().get(currentConditional.getClauses().size() - 1);
previousClause.getSuccessorClauses().add(newClause);
}
return newClause;
}
private <T extends StructuredActivityNode> T createBlock(boolean dataFlows, Runnable builderBehavior) {
return createBlock(IRepository.PACKAGE.getStructuredActivityNode(), dataFlows, builderBehavior);
}
private <T extends StructuredActivityNode> T createBlock(EClass activityNode, boolean dataFlows, Runnable builderBehavior) {
return createBlock(activityNode, dataFlows, it -> builderBehavior.run());
}
private <T extends StructuredActivityNode> T createBlock(EClass activityNode, boolean dataFlows, Consumer<T> builderBehavior) {
T block = (T) builder.createBlock(activityNode, dataFlows);
try {
builderBehavior.accept(block);
} catch (AbortedScopeCompilationException e) {
if (!ActivityUtils.isBodyNode(block)) {
// keep throwing exception
throw e;
}
// aborted activity block compilation...
if (builder.isDebug())
LogUtils.logWarning(TextUMLCore.PLUGIN_ID, null, e);
} finally {
builder.closeBlock();
}
return block;
}
private void createClauseBody(Clause clause, Runnable builderBlock) {
createBlock(false, () -> {
builderBlock.run();
clause.getBodies().add(builder.getCurrentBlock());
Action lastRootAction = builder.getLastRootAction();
if (lastRootAction != null) {
List<OutputPin> bodyOutput = ActivityUtils.getActionOutputs(lastRootAction);
clause.getBodyOutputs().addAll(bodyOutput);
}
});
}
private void createClauseTest(Clause clause, Runnable builderBlock) {
createBlock(false, () -> {
builderBlock.run();
clause.getTests().add(builder.getCurrentBlock());
Action lastRootAction = builder.getLastRootAction();
OutputPin decider = ActivityUtils.getActionOutputs(lastRootAction).get(0);
clause.setDecider(decider);
});
}
private void deferBlockCreation(Node block, Activity activity) {
deferredActivities.add(new DeferredActivity(activity, block));
}
private Operation findOperation(Node node, Classifier classifier, String operationName,
List<TypedElement> arguments, boolean isStatic, boolean required) {
Operation found = FeatureUtils
.findOperation(getRepository(), classifier, operationName, arguments, false, true);
if (found != null) {
if (found.isStatic() != isStatic) {
problemBuilder.addError((isStatic ? "Static" : "Non-static") + " operation expected: '" + operationName
+ "' in '" + found.getType().getQualifiedName() + "'", node);
throw new AbortedStatementCompilationException();
}
return found;
}
return missingOperation(required, node, classifier, operationName, arguments, isStatic);
}
protected Operation missingOperation(boolean required, Node node, Classifier classifier, String operationName,
List<TypedElement> arguments, boolean isStatic) {
if (!required)
return null;
Operation alternative = FeatureUtils.findOperation(getRepository(), classifier, operationName, null, false,
true);
problemBuilder.addProblem(
new UnknownOperation(classifier.getQualifiedName(), operationName, MDDUtil
.getArgumentListString(arguments), isStatic, alternative), node);
throw new AbortedStatementCompilationException();
}
// OperationInfo parseOperationInfo(Node operatorNode, int infoCount) {
// final OperationInfo info = new OperationInfo(infoCount);
// operatorNode.apply(new DepthFirstAdapter() {
//
// @Override
// public void caseAArithmeticBinaryOperatorP1(AArithmeticBinaryOperatorP1 node) {
// super.caseAArithmeticBinaryOperatorP1(node);
// handleArithmeticOperator(info);
// }
//
// @Override
// public void caseAArithmeticBinaryOperatorP2(AArithmeticBinaryOperatorP2 node) {
// super.caseAArithmeticBinaryOperatorP2(node);
// handleArithmeticOperator(info);
// }
//
// private void handleArithmeticOperator(final OperationInfo info) {
// info.types[0] = info.types[1] = info.types[2] = (Classifier) getRepository().findNamedElement(
// "base::Integer", IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseAComparisonBinaryOperatorP2(AComparisonBinaryOperatorP2 node) {
// super.caseAComparisonBinaryOperatorP2(node);
// handleComparisonOperator(info);
// }
//
// private void handleComparisonOperator(final OperationInfo info) {
// info.types[0] = info.types[1] = (Classifier) getRepository().findNamedElement("base::Comparable",
// IRepository.PACKAGE.getType(), null);
// info.types[2] = (Classifier) getRepository().findNamedElement("base::Boolean",
// IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseAEqualsComparisonBinaryOperatorP2(AEqualsComparisonBinaryOperatorP2 node) {
// info.operationName = "equals";
// }
//
// @Override
// public void caseANotEqualsComparisonBinaryOperatorP2(ANotEqualsComparisonBinaryOperatorP2 node) {
// info.operationName = "not";
// }
//
// @Override
// public void caseAGreaterOrEqualsComparisonBinaryOperatorP2(AGreaterOrEqualsComparisonBinaryOperatorP2 node) {
// info.operationName = "greaterOrEquals";
// }
//
// @Override
// public void caseAGreaterThanComparisonBinaryOperatorP2(AGreaterThanComparisonBinaryOperatorP2 node) {
// info.operationName = "greater";
// }
//
// @Override
// public void caseAIdentityComparisonBinaryOperatorP2(AIdentityComparisonBinaryOperatorP2 node) {
// super.caseAIdentityComparisonBinaryOperatorP2(node);
// info.operationName = "same";
// info.types[0] = info.types[1] = (Classifier) getRepository().findNamedElement("base::Any",
// IRepository.PACKAGE.getClass_(), null);
// info.types[2] = (Classifier) getRepository().findNamedElement("base::Boolean",
// IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseALogicalBinaryOperatorP2(ALogicalBinaryOperatorP2 node) {
// super.caseALogicalBinaryOperatorP2(node);
// handleLogicalBinaryOperator();
// }
//
// @Override
// public void caseALogicalBinaryOperatorP1(ALogicalBinaryOperatorP1 node) {
// super.caseALogicalBinaryOperatorP1(node);
// handleLogicalBinaryOperator();
// }
//
// private void handleLogicalBinaryOperator() {
// info.types[0] = info.types[1] = info.types[2] = (Classifier) getRepository().findNamedElement(
// "base::Boolean", IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseALowerOrEqualsComparisonBinaryOperatorP2(ALowerOrEqualsComparisonBinaryOperatorP2 node) {
// info.operationName = "lowerOrEquals";
// }
//
// @Override
// public void caseALowerThanComparisonBinaryOperatorP2(ALowerThanComparisonBinaryOperatorP2 node) {
// info.operationName = "lowerThan";
// }
//
// @Override
// public void caseAMinusUnaryOperator(AMinusUnaryOperator node) {
// super.caseAMinusUnaryOperator(node);
// info.types[0] = info.types[1] = (Classifier) getRepository().findNamedElement("base::Integer",
// IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseANotUnaryOperator(ANotUnaryOperator node) {
// super.caseANotUnaryOperator(node);
// info.types[0] = info.types[1] = (Classifier) getRepository().findNamedElement("base::Boolean",
// IRepository.PACKAGE.getType(), null);
// }
//
// @Override
// public void caseANotNullUnaryOperator(ANotNullUnaryOperator node) {
// super.caseANotNullUnaryOperator(node);
// info.types[0] = (Classifier) getRepository().findNamedElement("base::Basic",
// IRepository.PACKAGE.getType(), null);
// info.types[1] = (Classifier) getRepository().findNamedElement("base::Boolean",
// IRepository.PACKAGE.getType(), null);
// }
//
// public void caseTAnd(TAnd node) {
// info.operationName = "and";
// }
//
// public void caseTDiv(TDiv node) {
// info.operationName = "divide";
// }
//
// public void caseTMinus(TMinus node) {
// info.operationName = "subtract";
// }
//
// public void caseTMult(TMult node) {
// info.operationName = "multiply";
// }
//
// @Override
// public void caseTNot(TNot node) {
// info.operationName = "not";
// }
//
// public void caseTNotNull(TNotNull node) {
// info.operationName = "notNull";
// }
//
// public void caseTOr(TOr node) {
// info.operationName = "or";
// }
//
// public void caseTPlus(TPlus node) {
// info.operationName = "add";
// }
// });
// return info;
// }
@Override
public void caseATupleConstructor(ATupleConstructor node) {
final StructuredActivityNode action = (StructuredActivityNode) builder.createAction(IRepository.PACKAGE
.getStructuredActivityNode());
MDDExtensionUtils.makeObjectInitialization(action);
try {
node.apply(new DepthFirstAdapter() {
@Override
public void caseATupleComponentValue(ATupleComponentValue node) {
String slotName = sourceMiner.getIdentifier(node.getIdentifier());
builder.registerInput(action.createStructuredNodeInput(slotName, null));
node.getExpression().apply(BehaviorGenerator.this);
}
});
builder.registerOutput(action.createStructuredNodeOutput(null, null));
// now we determine the types of the incoming flows and build a
// corresponding data type on the fly
List<String> slotNames = new ArrayList<>();
List<Type> slotTypes = new ArrayList<>();
action.getStructuredNodeInputs().forEach((input) -> {
slotNames.add(input.getName());
slotTypes.add(input.getType());
});
DataType dataType = DataTypeUtils.findOrCreateDataType(namespaceTracker.currentPackage(), slotNames,
slotTypes);
action.getStructuredNodeOutputs().get(0).setType(dataType);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
public void createBodyLater(final Node bodyNode, final Activity body) {
defer(Step.BEHAVIOR, r -> createBody(bodyNode, body));
}
public void createConstraintBehaviorLater(final BehavioredClassifier parent, final Constraint constraint,
final Node constraintBlock, final List<Parameter> parameters) {
defer(Step.BEHAVIOR, repository -> createConstraintBehavior(parent, constraint, constraintBlock, parameters));
}
public Activity createConstraintBehavior(BehavioredClassifier parent, Constraint constraint, Node constraintBlock,
List<Parameter> parameters) {
Activity activity = MDDExtensionUtils.createConstraintBehavior(parent, constraint);
for (Parameter parameter : parameters)
activity.getOwnedParameters().add(parameter);
Classifier constraintType = BasicTypeUtils.findBuiltInType("Boolean");
activity.createOwnedParameter(null, constraintType).setDirection(ParameterDirectionKind.RETURN_LITERAL);
if (constraintBlock == null) {
constraintBlock = new AExpressionSimpleBlockResolved(
new ASimpleExpressionBlock(
null,
buildOperandExpression(new ALiteralOperand(
new ABooleanLiteral(
new ATrueBoolean(new TTrue())
)
)),
null
)
);
}
createBody(constraintBlock, activity);
ValueSpecification reference = ActivityUtils.buildBehaviorReference(constraint.getNearestPackage(), activity,
constraintType);
constraint.setSpecification(reference);
return activity;
}
private ARootExpression buildOperandExpression(POperand operand) {
return buildExpression(new AAltNestedExpressionP1(new AAltExpressionP0(operand)));
}
private ARootExpression buildExpression(AAltNestedExpressionP1 expressionP1) {
return buildExpression(new AAltNestedExpressionP2(expressionP1));
}
private ARootExpression buildExpression(AAltNestedExpressionP2 expressionP2) {
return buildExpression(new AAltNestedExpressionP3(expressionP2));
}
private ARootExpression buildExpression(AAltNestedExpressionP3 expressionP3) {
return buildExpression(new AAltNestedExpressionP4(expressionP3));
}
private ARootExpression buildExpression(AAltNestedExpressionP4 expression4) {
return buildExpression(new AAltNestedExpressionP5(expression4));
}
private ARootExpression buildExpression(AAltNestedExpressionP5 expressionP5) {
return new ARootExpression(new AExpression(expressionP5));
}
} | tweaking error reporting in case of required expression provided when an optional one was expected
| plugins/com.abstratt.mdd.frontend.textuml.core/src/com/abstratt/mdd/internal/frontend/textuml/BehaviorGenerator.java | tweaking error reporting in case of required expression provided when an optional one was expected | <ide><path>lugins/com.abstratt.mdd.frontend.textuml.core/src/com/abstratt/mdd/internal/frontend/textuml/BehaviorGenerator.java
<ide> ensure(
<ide> !TypeUtils.isRequiredPin(mainOutput),
<ide> left,
<del> () -> new UnclassifiedProblem("Expression must be optional")
<add> () -> new OptionalValueExpected()
<ide> );
<ide> MDDExtensionUtils.makeDefaultValueExpression(conditional);
<ide> }
<ide> buildCast(operand, action -> {
<ide> InputPin input = action.getStructuredNodeInputs().get(0);
<ide> OutputPin output = action.getStructuredNodeOutputs().get(0);
<del> ensure(!TypeUtils.isRequired(input), operand, () -> buildTypeMismatchProblem(output, input));
<add> ensure(!TypeUtils.isRequired(input), operand, () -> new OptionalValueExpected());
<ide> TypeUtils.copyType(input, output);
<ide> output.setLower(1);
<ide> }); |
|
Java | apache-2.0 | 285111b5e81aead1bec6cfc6b7adc5fbf3070e8c | 0 | cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x | /*
* The Spring Framework is published under the terms
* of the Apache Software License.
*/
package org.springframework.transaction.interceptor;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.easymock.MockControl;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.aop.target.HotSwappableTargetSource;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.transaction.CountingTxManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
/**
* Test cases for AOP transaction management.
* @author Rod Johnson
* @since 23-Apr-2003
* @version $Id: BeanFactoryTransactionTests.java,v 1.13 2003-12-02 16:30:33 johnsonr Exp $
*/
public class BeanFactoryTransactionTests extends TestCase {
private BeanFactory factory;
public void setUp() {
InputStream is = getClass().getResourceAsStream("transactionalBeanFactory.xml");
this.factory = new XmlBeanFactory(is, null);
ITestBean testBean = (ITestBean) factory.getBean("target");
testBean.setAge(666);
}
public void testGetsAreNotTransactionalWithProxyFactory1() throws NoSuchMethodException {
ITestBean testBean = (ITestBean) factory.getBean("proxyFactory1");
assertTrue("testBean is a dynamic proxy", Proxy.isProxyClass(testBean.getClass()));
executeGetsAreNotTransactional(testBean);
}
public void testGetsAreNotTransactionalWithProxyFactory2() throws NoSuchMethodException {
ITestBean testBean = (ITestBean) factory.getBean("proxyFactory2");
assertTrue("testBean is a dynamic proxy", Proxy.isProxyClass(testBean.getClass()));
executeGetsAreNotTransactional(testBean);
}
public void testGetsAreNotTransactionalWithProxyFactory3() throws NoSuchMethodException {
ITestBean testBean = (ITestBean) factory.getBean("proxyFactory3");
assertTrue("testBean is a full proxy", testBean instanceof DerivedTestBean);
InvocationCounterPointcut txnCounter = (InvocationCounterPointcut) factory.getBean("txnInvocationCounterPointcut");
InvocationCounterInterceptor preCounter = (InvocationCounterInterceptor) factory.getBean("preInvocationCounterInterceptor");
InvocationCounterInterceptor postCounter = (InvocationCounterInterceptor) factory.getBean("postInvocationCounterInterceptor");
txnCounter.counter = 0;
preCounter.counter = 0;
postCounter.counter = 0;
executeGetsAreNotTransactional(testBean);
// Can't assert it's equal to 4 as the pointcut may be optimized and only invoked once
assertTrue(0 < txnCounter.counter && txnCounter.counter <= 4);
assertEquals(4, preCounter.counter);
assertEquals(4, postCounter.counter);
}
public void executeGetsAreNotTransactional(ITestBean testBean) throws NoSuchMethodException {
// Install facade
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Expect no methods
ptmControl.replay();
PlatformTransactionManagerFacade.delegate = ptm;
assertTrue("Age should not be " + testBean.getAge(), testBean.getAge() == 666);
// Check no calls
ptmControl.verify();
// Install facade expecting a call
ptmControl = MockControl.createControl(PlatformTransactionManager.class);
ptm = (PlatformTransactionManager) ptmControl.getMock();
TransactionStatus txStatus = new TransactionStatus(null, true);
TransactionInterceptor txInterceptor = (TransactionInterceptor) factory.getBean("txInterceptor");
MethodMapTransactionAttributeSource txAttSrc = (MethodMapTransactionAttributeSource) txInterceptor.getTransactionAttributeSource();
ptm.getTransaction((TransactionDefinition) txAttSrc.methodMap.values().iterator().next());
//ptm.getTransaction(null);
ptmControl.setReturnValue(txStatus);
ptm.commit(txStatus);
ptmControl.setVoidCallable();
ptmControl.replay();
PlatformTransactionManagerFacade.delegate = ptm;
// TODO same as old age to avoid ordering effect for now
int age = 666;
testBean.setAge(age);
assertTrue(testBean.getAge() == age);
ptmControl.verify();
}
/**
* Check that we fail gracefully if the user doesn't
* set any transaction attributes.
*/
public void testNoTransactionAttributeSource() {
InputStream is = getClass().getResourceAsStream("noTransactionAttributeSource.xml");
try {
XmlBeanFactory bf = new XmlBeanFactory(is, null);
ITestBean testBean = (ITestBean) bf.getBean("noTransactionAttributeSource");
fail("Should require TransactionAttributeSource to be set");
}
catch (FatalBeanException ex) {
// Ok
}
}
/**
* Test that we can set the target to a dynamic TargetSource
* @throws NoSuchMethodException
*/
public void testDynamicTargetSource() throws NoSuchMethodException {
// Install facade
CountingTxManager txMan = new CountingTxManager();
PlatformTransactionManagerFacade.delegate = txMan;
TestBean tb = (TestBean) factory.getBean("hotSwapped");
assertEquals(666, tb.getAge());
int newAge = 557;
tb.setAge(newAge);
assertEquals(newAge, tb.getAge());
TestBean target2 = new TestBean();
target2.setAge(65);
HotSwappableTargetSource ts = (HotSwappableTargetSource) factory.getBean("swapper");
ts.swap(target2);
assertEquals(target2.getAge(), tb.getAge());
tb.setAge(newAge);
assertEquals(newAge, target2.getAge());
assertEquals(0, txMan.inflight);
assertEquals(2, txMan.commits);
assertEquals(0, txMan.rollbacks);
}
public static class InvocationCounterPointcut extends StaticMethodMatcherPointcut {
int counter = 0;
public boolean matches(Method method, Class clazz) {
counter++;
return true;
}
}
public static class InvocationCounterInterceptor implements MethodInterceptor {
int counter = 0;
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
counter++;
return methodInvocation.proceed();
}
}
}
| test/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java | /*
* The Spring Framework is published under the terms
* of the Apache Software License.
*/
package org.springframework.transaction.interceptor;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.easymock.MockControl;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.aop.target.HotSwappableTargetSource;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.transaction.CountingTxManager;
import org.springframework.transaction.DummyTxManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
/**
* Test cases for AOP transaction management.
* @author Rod Johnson
* @since 23-Apr-2003
* @version $Id: BeanFactoryTransactionTests.java,v 1.12 2003-12-02 16:29:17 johnsonr Exp $
*/
public class BeanFactoryTransactionTests extends TestCase {
private BeanFactory factory;
public void setUp() {
InputStream is = getClass().getResourceAsStream("transactionalBeanFactory.xml");
this.factory = new XmlBeanFactory(is, null);
ITestBean testBean = (ITestBean) factory.getBean("target");
testBean.setAge(666);
}
public void testGetsAreNotTransactionalWithProxyFactory1() throws NoSuchMethodException {
ITestBean testBean = (ITestBean) factory.getBean("proxyFactory1");
assertTrue("testBean is a dynamic proxy", Proxy.isProxyClass(testBean.getClass()));
executeGetsAreNotTransactional(testBean);
}
public void testGetsAreNotTransactionalWithProxyFactory2() throws NoSuchMethodException {
ITestBean testBean = (ITestBean) factory.getBean("proxyFactory2");
assertTrue("testBean is a dynamic proxy", Proxy.isProxyClass(testBean.getClass()));
executeGetsAreNotTransactional(testBean);
}
public void testGetsAreNotTransactionalWithProxyFactory3() throws NoSuchMethodException {
ITestBean testBean = (ITestBean) factory.getBean("proxyFactory3");
assertTrue("testBean is a full proxy", testBean instanceof DerivedTestBean);
InvocationCounterPointcut txnCounter = (InvocationCounterPointcut) factory.getBean("txnInvocationCounterPointcut");
InvocationCounterInterceptor preCounter = (InvocationCounterInterceptor) factory.getBean("preInvocationCounterInterceptor");
InvocationCounterInterceptor postCounter = (InvocationCounterInterceptor) factory.getBean("postInvocationCounterInterceptor");
txnCounter.counter = 0;
preCounter.counter = 0;
postCounter.counter = 0;
executeGetsAreNotTransactional(testBean);
// Can't assert it's equal to 4 as the pointcut may be optimized and only invoked once
assertTrue(0 < txnCounter.counter && txnCounter.counter <= 4);
assertEquals(4, preCounter.counter);
assertEquals(4, postCounter.counter);
}
public void executeGetsAreNotTransactional(ITestBean testBean) throws NoSuchMethodException {
// Install facade
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Expect no methods
ptmControl.replay();
PlatformTransactionManagerFacade.delegate = ptm;
assertTrue("Age should not be " + testBean.getAge(), testBean.getAge() == 666);
// Check no calls
ptmControl.verify();
// Install facade expecting a call
ptmControl = MockControl.createControl(PlatformTransactionManager.class);
ptm = (PlatformTransactionManager) ptmControl.getMock();
TransactionStatus txStatus = new TransactionStatus(null, true);
TransactionInterceptor txInterceptor = (TransactionInterceptor) factory.getBean("txInterceptor");
MethodMapTransactionAttributeSource txAttSrc = (MethodMapTransactionAttributeSource) txInterceptor.getTransactionAttributeSource();
ptm.getTransaction((TransactionDefinition) txAttSrc.methodMap.values().iterator().next());
//ptm.getTransaction(null);
ptmControl.setReturnValue(txStatus);
ptm.commit(txStatus);
ptmControl.setVoidCallable();
ptmControl.replay();
PlatformTransactionManagerFacade.delegate = ptm;
// TODO same as old age to avoid ordering effect for now
int age = 666;
testBean.setAge(age);
assertTrue(testBean.getAge() == age);
ptmControl.verify();
}
/**
* Check that we fail gracefully if the user doesn't
* set any transaction attributes.
*/
public void testNoTransactionAttributeSource() {
InputStream is = getClass().getResourceAsStream("noTransactionAttributeSource.xml");
try {
XmlBeanFactory bf = new XmlBeanFactory(is, null);
ITestBean testBean = (ITestBean) bf.getBean("noTransactionAttributeSource");
fail("Should require TransactionAttributeSource to be set");
}
catch (FatalBeanException ex) {
// Ok
}
}
/**
* Test that we can set the target to a dynamic TargetSource
* @throws NoSuchMethodException
*/
public void testDynamicTargetSource() throws NoSuchMethodException {
// Install facade
CountingTxManager txMan = new CountingTxManager();
PlatformTransactionManagerFacade.delegate = txMan;
TestBean tb = (TestBean) factory.getBean("hotSwapped");
assertEquals(666, tb.getAge());
int newAge = 557;
tb.setAge(newAge);
assertEquals(newAge, tb.getAge());
TestBean target2 = new TestBean();
target2.setAge(65);
HotSwappableTargetSource ts = (HotSwappableTargetSource) factory.getBean("swapper");
ts.swap(target2);
assertEquals(target2.getAge(), tb.getAge());
tb.setAge(newAge);
assertEquals(newAge, target2.getAge());
assertEquals(0, txMan.inflight);
assertEquals(2, txMan.commits);
assertEquals(0, txMan.rollbacks);
}
public static class InvocationCounterPointcut extends StaticMethodMatcherPointcut {
int counter = 0;
public boolean matches(Method method, Class clazz) {
counter++;
return true;
}
}
public static class InvocationCounterInterceptor implements MethodInterceptor {
int counter = 0;
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
counter++;
return methodInvocation.proceed();
}
}
}
| Changed DummyTxManager class name because of CVS problem
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@778 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
| test/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java | Changed DummyTxManager class name because of CVS problem | <ide><path>est/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java
<ide> import org.springframework.beans.factory.BeanFactory;
<ide> import org.springframework.beans.factory.xml.XmlBeanFactory;
<ide> import org.springframework.transaction.CountingTxManager;
<del>import org.springframework.transaction.DummyTxManager;
<ide> import org.springframework.transaction.PlatformTransactionManager;
<ide> import org.springframework.transaction.TransactionDefinition;
<ide> import org.springframework.transaction.TransactionStatus;
<ide> * Test cases for AOP transaction management.
<ide> * @author Rod Johnson
<ide> * @since 23-Apr-2003
<del> * @version $Id: BeanFactoryTransactionTests.java,v 1.12 2003-12-02 16:29:17 johnsonr Exp $
<add> * @version $Id: BeanFactoryTransactionTests.java,v 1.13 2003-12-02 16:30:33 johnsonr Exp $
<ide> */
<ide> public class BeanFactoryTransactionTests extends TestCase {
<ide> |
|
Java | mit | error: pathspec 'src/java/net/sf/jabref/export/MSBibExportFormat.java' did not match any file(s) known to git
| 70397419e42797797b422e0cb6496c82d0462472 | 1 | zellerdev/jabref,ayanai1/jabref,mairdl/jabref,Siedlerchr/jabref,bartsch-dev/jabref,JabRef/jabref,shitikanth/jabref,grimes2/jabref,tschechlovdev/jabref,sauliusg/jabref,motokito/jabref,obraliar/jabref,grimes2/jabref,mairdl/jabref,shitikanth/jabref,Mr-DLib/jabref,mredaelli/jabref,jhshinn/jabref,zellerdev/jabref,tschechlovdev/jabref,ayanai1/jabref,Siedlerchr/jabref,tobiasdiez/jabref,Mr-DLib/jabref,motokito/jabref,shitikanth/jabref,mredaelli/jabref,zellerdev/jabref,Mr-DLib/jabref,mredaelli/jabref,ayanai1/jabref,mairdl/jabref,shitikanth/jabref,bartsch-dev/jabref,Mr-DLib/jabref,motokito/jabref,Braunch/jabref,bartsch-dev/jabref,tobiasdiez/jabref,zellerdev/jabref,grimes2/jabref,sauliusg/jabref,jhshinn/jabref,mairdl/jabref,oscargus/jabref,jhshinn/jabref,motokito/jabref,bartsch-dev/jabref,obraliar/jabref,ayanai1/jabref,oscargus/jabref,Siedlerchr/jabref,shitikanth/jabref,mairdl/jabref,mredaelli/jabref,Siedlerchr/jabref,tschechlovdev/jabref,tschechlovdev/jabref,JabRef/jabref,ayanai1/jabref,obraliar/jabref,Mr-DLib/jabref,jhshinn/jabref,sauliusg/jabref,oscargus/jabref,obraliar/jabref,oscargus/jabref,JabRef/jabref,JabRef/jabref,grimes2/jabref,mredaelli/jabref,grimes2/jabref,sauliusg/jabref,Braunch/jabref,tobiasdiez/jabref,tobiasdiez/jabref,bartsch-dev/jabref,Braunch/jabref,zellerdev/jabref,oscargus/jabref,Braunch/jabref,obraliar/jabref,Braunch/jabref,jhshinn/jabref,motokito/jabref,tschechlovdev/jabref | package net.sf.jabref.export;
import net.sf.jabref.Globals;
import net.sf.jabref.BibtexDatabase;
import net.sf.jabref.msbib.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import java.util.Set;
import java.io.IOException;
import java.io.File;
/*
* @author S M Mahbub Murshed
* @email [email protected]
*
* @version 1.0.0
* @see http://mahbub.wordpress.com/2007/03/24/details-of-microsoft-office-2007-bibliographic-format-compared-to-bibtex/
* @see http://mahbub.wordpress.com/2007/03/22/deciphering-microsoft-office-2007-bibliography-format/
*
* Date: May 03, 2007
*
*/
/**
* ExportFormat for exporting in MSBIB XML format.
*/
class MSBibExportFormat extends ExportFormat {
public MSBibExportFormat() {
super(Globals.lang("MS Office 2007"), "MSBib", null, null, ".xml");
}
public void performExport(final BibtexDatabase database, final String file, final String encoding, Set keySet) throws IOException {
SaveSession ss = getSaveSession(encoding, new File(file));
VerifyingWriter ps = ss.getWriter();
MSBibDatabase md = new MSBibDatabase(database, keySet);
// PS: DOES NOT SUPPORT EXPORTING ONLY A SET OF ENTRIES
try {
DOMSource source = new DOMSource(md.getDOMrepresentation());
StreamResult result = new StreamResult(ps);
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.transform(source, result);
}
catch (Exception e) {
throw new Error(e);
}
try {
finalizeSaveSession(ss);
} catch (SaveException ex) {
throw new IOException(ex.getMessage());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
return;
}
}
| src/java/net/sf/jabref/export/MSBibExportFormat.java | MSBibExportFormatter used to export in MSOffice 2007 format. Based on ModsExportFormat.
| src/java/net/sf/jabref/export/MSBibExportFormat.java | MSBibExportFormatter used to export in MSOffice 2007 format. Based on ModsExportFormat. | <ide><path>rc/java/net/sf/jabref/export/MSBibExportFormat.java
<add>package net.sf.jabref.export;
<add>
<add>import net.sf.jabref.Globals;
<add>import net.sf.jabref.BibtexDatabase;
<add>import net.sf.jabref.msbib.*;
<add>
<add>import javax.xml.transform.dom.DOMSource;
<add>import javax.xml.transform.stream.StreamResult;
<add>import javax.xml.transform.Transformer;
<add>import javax.xml.transform.TransformerFactory;
<add>import javax.xml.transform.OutputKeys;
<add>import java.util.Set;
<add>import java.io.IOException;
<add>import java.io.File;
<add>/*
<add> * @author S M Mahbub Murshed
<add>* @email [email protected]
<add>*
<add>* @version 1.0.0
<add>* @see http://mahbub.wordpress.com/2007/03/24/details-of-microsoft-office-2007-bibliographic-format-compared-to-bibtex/
<add>* @see http://mahbub.wordpress.com/2007/03/22/deciphering-microsoft-office-2007-bibliography-format/
<add>*
<add>* Date: May 03, 2007
<add>*
<add>*/
<add>
<add>/**
<add> * ExportFormat for exporting in MSBIB XML format.
<add> */
<add>class MSBibExportFormat extends ExportFormat {
<add> public MSBibExportFormat() {
<add> super(Globals.lang("MS Office 2007"), "MSBib", null, null, ".xml");
<add>
<add> }
<add>
<add> public void performExport(final BibtexDatabase database, final String file, final String encoding, Set keySet) throws IOException {
<add> SaveSession ss = getSaveSession(encoding, new File(file));
<add> VerifyingWriter ps = ss.getWriter();
<add> MSBibDatabase md = new MSBibDatabase(database, keySet);
<add>
<add> // PS: DOES NOT SUPPORT EXPORTING ONLY A SET OF ENTRIES
<add>
<add> try {
<add> DOMSource source = new DOMSource(md.getDOMrepresentation());
<add> StreamResult result = new StreamResult(ps);
<add> Transformer trans = TransformerFactory.newInstance().newTransformer();
<add> trans.setOutputProperty(OutputKeys.INDENT, "yes");
<add> trans.transform(source, result);
<add> }
<add> catch (Exception e) {
<add> throw new Error(e);
<add> }
<add>
<add> try {
<add> finalizeSaveSession(ss);
<add> } catch (SaveException ex) {
<add> throw new IOException(ex.getMessage());
<add> } catch (Exception e) {
<add> throw new IOException(e.getMessage());
<add> }
<add> return;
<add> }
<add>} |
|
JavaScript | agpl-3.0 | cf899afdc7c365ddc6fa6f0a786aaf265d2ccf12 | 0 | ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs | /*
* (c) Copyright Ascensio System SIA 2010-2016
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
* EU, LV-1021.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
/**
* @param {Window} window
* @param {undefined} undefined
*/
(function (window, undefined) {
var LOCKS_MASKS =
{
noGrp: 1,
noUngrp: 4,
noSelect: 16,
noRot: 64,
noChangeAspect: 256,
noMove: 1024,
noResize: 4096,
noEditPoints: 16384,
noAdjustHandles: 65536,
noChangeArrowheads: 262144,
noChangeShapeType: 1048576,
noDrilldown: 4194304,
noTextEdit: 8388608,
noCrop: 16777216
};
function checkNormalRotate(rot)
{
var _rot = normalizeRotate(rot);
return (_rot >= 0 && _rot < Math.PI * 0.25) || (_rot >= 3 * Math.PI * 0.25 && _rot < 5 * Math.PI * 0.25) || (_rot >= 7 * Math.PI * 0.25 && _rot < 2 * Math.PI);
}
function normalizeRotate(rot)
{
var new_rot = rot;
if(AscFormat.isRealNumber(new_rot))
{
while(new_rot >= 2*Math.PI)
new_rot -= 2*Math.PI;
while(new_rot < 0)
new_rot += 2*Math.PI;
return new_rot;
}
return new_rot;
}
/**
* Class represent bounds graphical object
* @param {number} l
* @param {number} t
* @param {number} r
* @param {number} b
* @constructor
*/
function CGraphicBounds(l, t, r, b){
this.l = l;
this.t = t;
this.r = r;
this.b = b;
this.x = l;
this.y = t;
this.w = r - l;
this.h = b - t;
}
/**
* Base class for all graphic objects
* @constructor
*/
function CGraphicObjectBase() {
/*Format fields*/
this.spPr = null;
this.group = null;
this.parent = null;
this.bDeleted = true;
this.locks = 0;
this.Id = '';
/*Calculated fields*/
this.posX = null;
this.posY = null;
this.x = 0;
this.y = 0;
this.extX = 0;
this.extY = 0;
this.rot = 0;
this.flipH = false;
this.flipV = false;
this.bounds = new CGraphicBounds(0, 0, 0, 0);
this.localTransform = new AscCommon.CMatrix();
this.transform = new AscCommon.CMatrix();
this.invertTransform = null;
this.pen = null;
this.brush = null;
this.snapArrayX = [];
this.snapArrayY = [];
this.selected = false;
this.Lock = new AscCommon.CLock();
this.setRecalculateInfo();
}
/**
* Create a scheme color
* @memberof CGraphicObjectBase
* @returns {CGraphicBounds}
*/
CGraphicObjectBase.prototype.checkBoundsRect = function(){
var aCheckX = [], aCheckY = [];
this.calculateSnapArrays(aCheckX, aCheckY, this.localTransform);
return new CGraphicBounds(Math.min.apply(Math, aCheckX), Math.min.apply(Math, aCheckY), Math.max.apply(Math, aCheckX), Math.max.apply(Math, aCheckY));
};
/**
* Set default recalculate info
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.setRecalculateInfo = function(){};
/**
* Get object Id
* @memberof CGraphicObjectBase
* @returns {string}
*/
CGraphicObjectBase.prototype.Get_Id = function () {
return this.Id;
};
/**
* Get type object
* @memberof CGraphicObjectBase
* @returns {number}
*/
CGraphicObjectBase.prototype.getObjectType = function () {
return AscDFH.historyitem_type_Unknown;
};
/**
* Write object to stream
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.Write_ToBinary2 = function (oWriter) {
oWriter.WriteLong(this.getObjectType());
oWriter.WriteString2(this.Get_Id());
};
/**
* Read object from stream
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.Read_FromBinary2 = function (oReader) {
this.Id = oReader.GetString2();
};
/**
* Get object Id
* @memberof CGraphicObjectBase
* @returns {string}
*/
CGraphicObjectBase.prototype.Get_Id = function () {
return this.Id;
};
/**
* Get object bounds for defining group size
* @memberof CGraphicObjectBase
* @returns {CGraphicBounds}
*/
CGraphicObjectBase.prototype.getBoundsInGroup = function () {
var r = this.rot;
if (!AscFormat.isRealNumber(r) || AscFormat.checkNormalRotate(r)) {
return new CGraphicBounds(this.x, this.y, this.x + this.extX, this.y + this.extY);
}
else {
var hc = this.extX * 0.5;
var vc = this.extY * 0.5;
var xc = this.x + hc;
var yc = this.y + vc;
return new CGraphicBounds(xc - vc, yc - hc, xc + vc, yc + hc);
}
};
/**
* Normalize a size object in group
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.normalize = function () {
var new_off_x, new_off_y, new_ext_x, new_ext_y;
var xfrm = this.spPr.xfrm;
if (!isRealObject(this.group)) {
new_off_x = xfrm.offX;
new_off_y = xfrm.offY;
new_ext_x = xfrm.extX;
new_ext_y = xfrm.extY;
}
else {
var scale_scale_coefficients = this.group.getResultScaleCoefficients();
new_off_x = scale_scale_coefficients.cx * (xfrm.offX - this.group.spPr.xfrm.chOffX);
new_off_y = scale_scale_coefficients.cy * (xfrm.offY - this.group.spPr.xfrm.chOffY);
new_ext_x = scale_scale_coefficients.cx * xfrm.extX;
new_ext_y = scale_scale_coefficients.cy * xfrm.extY;
}
Math.abs(new_off_x - xfrm.offX) > AscFormat.MOVE_DELTA && xfrm.setOffX(new_off_x);
Math.abs(new_off_y - xfrm.offY) > AscFormat.MOVE_DELTA && xfrm.setOffY(new_off_y);
Math.abs(new_ext_x - xfrm.extX) > AscFormat.MOVE_DELTA && xfrm.setExtX(new_ext_x);
Math.abs(new_ext_y - xfrm.extY) > AscFormat.MOVE_DELTA && xfrm.setExtY(new_ext_y);
};
/**
* Check point hit to bounds object
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.checkHitToBounds = function(x, y) {
if(this.parent && (this.parent.Get_ParentTextTransform && this.parent.Get_ParentTextTransform())) {
return true;
}
var _x, _y;
if(AscFormat.isRealNumber(this.posX) && AscFormat.isRealNumber(this.posY)){
_x = x - this.posX - this.bounds.x;
_y = y - this.posY - this.bounds.y;
}
else{
_x = x - this.bounds.x;
_y = y - this.bounds.y;
}
var delta = 3 + (this.pen && AscFormat.isRealNumber(this.pen.w) ? this.pen.w/36000 : 0);
return _x >= -delta && _x <= this.bounds.w + delta && _y >= -delta && _y <= this.bounds.h + delta;
};
/**
* Internal method for calculating snap arrays
* @param {Array} snapArrayX
* @param {Array} snapArrayY
* @param {CMatrix} transform
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.calculateSnapArrays = function(snapArrayX, snapArrayY, transform)
{
var t = transform ? transform : this.transform;
snapArrayX.push(t.TransformPointX(0, 0));
snapArrayY.push(t.TransformPointY(0, 0));
snapArrayX.push(t.TransformPointX(this.extX, 0));
snapArrayY.push(t.TransformPointY(this.extX, 0));
snapArrayX.push(t.TransformPointX(this.extX*0.5, this.extY*0.5));
snapArrayY.push(t.TransformPointY(this.extX*0.5, this.extY*0.5));
snapArrayX.push(t.TransformPointX(this.extX, this.extY));
snapArrayY.push(t.TransformPointY(this.extX, this.extY));
snapArrayX.push(t.TransformPointX(0, this.extY));
snapArrayY.push(t.TransformPointY(0, this.extY));
};
/**
* Public method for calculating snap arrays
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.recalculateSnapArrays = function()
{
this.snapArrayX.length = 0;
this.snapArrayY.length = 0;
this.calculateSnapArrays(this.snapArrayX, this.snapArrayY, null);
};
CGraphicObjectBase.prototype.setLocks = function(nLocks){
AscCommon.History.Add(this, {Type: AscDFH.historyitem_AutoShapes_SetLocks, oldPr: this.locks, newPr: nLocks});
this.locks = nLocks;
};
CGraphicObjectBase.prototype.getLockValue = function(nMask) {
return !!((this.locks & nMask) && (this.locks & (nMask << 1)));
};
CGraphicObjectBase.prototype.setLockValue = function(nMask, bValue) {
if(!AscFormat.isRealBool(bValue)) {
this.setLocks((~nMask) & this.locks);
}
else{
this.setLocks(this.locks | nMask | (bValue ? nMask << 1 : 0));
}
};
CGraphicObjectBase.prototype.getNoGrp = function(){
return this.getLockValue(LOCKS_MASKS.noGrp);
};
CGraphicObjectBase.prototype.getNoUngrp = function(){
return this.getLockValue(LOCKS_MASKS.noUngrp);
};
CGraphicObjectBase.prototype.getNoSelect = function(){
return this.getLockValue(LOCKS_MASKS.noSelect);
};
CGraphicObjectBase.prototype.getNoRot = function(){
return this.getLockValue(LOCKS_MASKS.noRot);
};
CGraphicObjectBase.prototype.getNoChangeAspect = function(){
return this.getLockValue(LOCKS_MASKS.noChangeAspect);
};
CGraphicObjectBase.prototype.getNoMove = function(){
return this.getLockValue(LOCKS_MASKS.noMove);
};
CGraphicObjectBase.prototype.getNoResize = function(){
return this.getLockValue(LOCKS_MASKS.noResize);
};
CGraphicObjectBase.prototype.getNoEditPoints = function(){
return this.getLockValue(LOCKS_MASKS.noEditPoints);
};
CGraphicObjectBase.prototype.getNoAdjustHandles = function(){
return this.getLockValue(LOCKS_MASKS.noAdjustHandles);
};
CGraphicObjectBase.prototype.getNoChangeArrowheads = function(){
return this.getLockValue(LOCKS_MASKS.noChangeArrowheads);
};
CGraphicObjectBase.prototype.getNoChangeShapeType = function(){
return this.getLockValue(LOCKS_MASKS.noChangeShapeType);
};
CGraphicObjectBase.prototype.getNoDrilldown = function(){
return this.getLockValue(LOCKS_MASKS.noDrilldown);
};
CGraphicObjectBase.prototype.getNoTextEdit = function(){
return this.getLockValue(LOCKS_MASKS.noTextEdit);
};
CGraphicObjectBase.prototype.getNoCrop = function(){
return this.getLockValue(LOCKS_MASKS.noCrop);
};
CGraphicObjectBase.prototype.setNoChangeAspect = function(bValue){
return this.setLockValue(LOCKS_MASKS.noChangeAspect, bValue);
};
CGraphicObjectBase.prototype.Reassign_ImageUrls = function(mapUrl){
if(this.blipFill){
if(mapUrl[this.blipFill.RasterImageId]){
if(this.setBlipFill){
var blip_fill = new AscFormat.CBlipFill();
blip_fill.setRasterImageId(mapUrl[this.blipFill.RasterImageId]);
blip_fill.setStretch(true);
this.setBlipFill(blip_fill);
}
}
}
if(this.spPr && this.spPr.Fill && this.spPr.Fill.fill && this.spPr.Fill.fill.RasterImageId){
if(mapUrl[this.spPr.Fill.fill.RasterImageId]){
var blip_fill = new AscFormat.CBlipFill();
blip_fill.setRasterImageId(mapUrl[this.spPr.Fill.fill.RasterImageId]);
blip_fill.setStretch(true);
var oUniFill = new AscFormat.CUniFill();
oUniFill.setFill(blip_fill);
this.spPr.setFill(oUniFill);
}
}
if(Array.isArray(this.spTree)){
for(var i = 0; i < this.spTree.length; ++i){
if(this.spTree[i].Reassign_ImageUrls){
this.spTree[i].Reassign_ImageUrls(mapUrl);
}
}
}
};
CGraphicObjectBase.prototype.getAllFonts = function(mapUrl){
};
window['AscFormat'] = window['AscFormat'] || {};
window['AscFormat'].CGraphicObjectBase = CGraphicObjectBase;
window['AscFormat'].CGraphicBounds = CGraphicBounds;
window['AscFormat'].checkNormalRotate = checkNormalRotate;
window['AscFormat'].normalizeRotate = normalizeRotate;
window['AscFormat'].LOCKS_MASKS = LOCKS_MASKS;
})(window); | common/Drawings/Format/GraphicObjectBase.js | /*
* (c) Copyright Ascensio System SIA 2010-2016
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
* EU, LV-1021.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
/**
* @param {Window} window
* @param {undefined} undefined
*/
(function (window, undefined) {
var LOCKS_MASKS =
{
noGrp: 1,
noUngrp: 4,
noSelect: 16,
noRot: 64,
noChangeAspect: 256,
noMove: 1024,
noResize: 4096,
noEditPoints: 16384,
noAdjustHandles: 65536,
noChangeArrowheads: 262144,
noChangeShapeType: 1048576,
noDrilldown: 4194304,
noTextEdit: 8388608,
noCrop: 16777216
};
function checkNormalRotate(rot)
{
var _rot = normalizeRotate(rot);
return (_rot >= 0 && _rot < Math.PI * 0.25) || (_rot >= 3 * Math.PI * 0.25 && _rot < 5 * Math.PI * 0.25) || (_rot >= 7 * Math.PI * 0.25 && _rot < 2 * Math.PI);
}
function normalizeRotate(rot)
{
var new_rot = rot;
if(AscFormat.isRealNumber(new_rot))
{
while(new_rot >= 2*Math.PI)
new_rot -= 2*Math.PI;
while(new_rot < 0)
new_rot += 2*Math.PI;
return new_rot;
}
return new_rot;
}
/**
* Class represent bounds graphical object
* @param {number} l
* @param {number} t
* @param {number} r
* @param {number} b
* @constructor
*/
function CGraphicBounds(l, t, r, b){
this.l = l;
this.t = t;
this.r = r;
this.b = b;
this.x = l;
this.y = t;
this.w = r - l;
this.h = b - t;
}
/**
* Base class for all graphic objects
* @constructor
*/
function CGraphicObjectBase() {
/*Format fields*/
this.spPr = null;
this.group = null;
this.parent = null;
this.bDeleted = true;
this.locks = 0;
this.Id = '';
/*Calculated fields*/
this.posX = null;
this.posY = null;
this.x = 0;
this.y = 0;
this.extX = 0;
this.extY = 0;
this.rot = 0;
this.flipH = false;
this.flipV = false;
this.bounds = new CGraphicBounds(0, 0, 0, 0);
this.localTransform = new AscCommon.CMatrix();
this.transform = new AscCommon.CMatrix();
this.invertTransform = null;
this.pen = null;
this.brush = null;
this.snapArrayX = [];
this.snapArrayY = [];
this.selected = false;
this.Lock = new AscCommon.CLock();
this.setRecalculateInfo();
}
/**
* Create a scheme color
* @memberof CGraphicObjectBase
* @returns {CGraphicBounds}
*/
CGraphicObjectBase.prototype.checkBoundsRect = function(){
var aCheckX = [], aCheckY = [];
this.calculateSnapArrays(aCheckX, aCheckY, this.localTransform);
return new CGraphicBounds(Math.min.apply(Math, aCheckX), Math.min.apply(Math, aCheckY), Math.max.apply(Math, aCheckX), Math.max.apply(Math, aCheckY));
};
/**
* Set default recalculate info
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.setRecalculateInfo = function(){};
/**
* Get object Id
* @memberof CGraphicObjectBase
* @returns {string}
*/
CGraphicObjectBase.prototype.Get_Id = function () {
return this.Id;
};
/**
* Get type object
* @memberof CGraphicObjectBase
* @returns {number}
*/
CGraphicObjectBase.prototype.getObjectType = function () {
return AscDFH.historyitem_type_Unknown;
};
/**
* Write object to stream
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.Write_ToBinary2 = function (oWriter) {
oWriter.WriteLong(this.getObjectType());
oWriter.WriteString2(this.Get_Id());
};
/**
* Read object from stream
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.Read_FromBinary2 = function (oReader) {
this.Id = oReader.GetString2();
};
/**
* Get object Id
* @memberof CGraphicObjectBase
* @returns {string}
*/
CGraphicObjectBase.prototype.Get_Id = function () {
return this.Id;
};
/**
* Get object bounds for defining group size
* @memberof CGraphicObjectBase
* @returns {CGraphicBounds}
*/
CGraphicObjectBase.prototype.getBoundsInGroup = function () {
var r = this.rot;
if (!AscFormat.isRealNumber(r) || AscFormat.checkNormalRotate(r)) {
return new CGraphicBounds(this.x, this.y, this.x + this.extX, this.y + this.extY);
}
else {
var hc = this.extX * 0.5;
var vc = this.extY * 0.5;
var xc = this.x + hc;
var yc = this.y + vc;
return new CGraphicBounds(xc - vc, yc - hc, xc + vc, yc + hc);
}
};
/**
* Normalize a size object in group
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.normalize = function () {
var new_off_x, new_off_y, new_ext_x, new_ext_y;
var xfrm = this.spPr.xfrm;
if (!isRealObject(this.group)) {
new_off_x = xfrm.offX;
new_off_y = xfrm.offY;
new_ext_x = xfrm.extX;
new_ext_y = xfrm.extY;
}
else {
var scale_scale_coefficients = this.group.getResultScaleCoefficients();
new_off_x = scale_scale_coefficients.cx * (xfrm.offX - this.group.spPr.xfrm.chOffX);
new_off_y = scale_scale_coefficients.cy * (xfrm.offY - this.group.spPr.xfrm.chOffY);
new_ext_x = scale_scale_coefficients.cx * xfrm.extX;
new_ext_y = scale_scale_coefficients.cy * xfrm.extY;
}
Math.abs(new_off_x - xfrm.offX) > AscFormat.MOVE_DELTA && xfrm.setOffX(new_off_x);
Math.abs(new_off_y - xfrm.offY) > AscFormat.MOVE_DELTA && xfrm.setOffY(new_off_y);
Math.abs(new_ext_x - xfrm.extX) > AscFormat.MOVE_DELTA && xfrm.setExtX(new_ext_x);
Math.abs(new_ext_y - xfrm.extY) > AscFormat.MOVE_DELTA && xfrm.setExtY(new_ext_y);
};
/**
* Check point hit to bounds object
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.checkHitToBounds = function(x, y) {
if(this.parent && (this.parent.Get_ParentTextTransform && this.parent.Get_ParentTextTransform())) {
return true;
}
var _x, _y;
if(AscFormat.isRealNumber(this.posX) && AscFormat.isRealNumber(this.posY)){
_x = x - this.posX - this.bounds.x;
_y = y - this.posY - this.bounds.y;
}
else{
_x = x - this.bounds.x;
_y = y - this.bounds.y;
}
var delta = 3 + (this.pen && AscFormat.isRealNumber(this.pen.w) ? this.pen.w/36000 : 0);
return _x >= -delta && _x <= this.bounds.w + delta && _y >= -delta && _y <= this.bounds.h + delta;
};
/**
* Internal method for calculating snap arrays
* @param {Array} snapArrayX
* @param {Array} snapArrayY
* @param {CMatrix} transform
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.calculateSnapArrays = function(snapArrayX, snapArrayY, transform)
{
var t = transform ? transform : this.transform;
snapArrayX.push(t.TransformPointX(0, 0));
snapArrayY.push(t.TransformPointY(0, 0));
snapArrayX.push(t.TransformPointX(this.extX, 0));
snapArrayY.push(t.TransformPointY(this.extX, 0));
snapArrayX.push(t.TransformPointX(this.extX*0.5, this.extY*0.5));
snapArrayY.push(t.TransformPointY(this.extX*0.5, this.extY*0.5));
snapArrayX.push(t.TransformPointX(this.extX, this.extY));
snapArrayY.push(t.TransformPointY(this.extX, this.extY));
snapArrayX.push(t.TransformPointX(0, this.extY));
snapArrayY.push(t.TransformPointY(0, this.extY));
};
/**
* Public method for calculating snap arrays
* @memberof CGraphicObjectBase
*/
CGraphicObjectBase.prototype.recalculateSnapArrays = function()
{
this.snapArrayX.length = 0;
this.snapArrayY.length = 0;
this.calculateSnapArrays(this.snapArrayX, this.snapArrayY, null);
};
CGraphicObjectBase.prototype.setLocks = function(nLocks){
AscCommon.History.Add(this, {Type: AscDFH.historyitem_AutoShapes_SetLocks, oldPr: this.locks, newPr: nLocks});
this.locks = nLocks;
};
CGraphicObjectBase.prototype.getLockValue = function(nMask) {
return !!((this.locks & nMask) && (this.locks & (nMask << 1)));
};
CGraphicObjectBase.prototype.setLockValue = function(nMask, bValue) {
if(!AscFormat.isRealBool(bValue)) {
this.setLocks((~nMask) & this.locks);
}
else{
this.setLocks(this.locks | nMask | (bValue ? nMask << 1 : 0));
}
};
CGraphicObjectBase.prototype.getNoGrp = function(){
return this.getLockValue(LOCKS_MASKS.noGrp);
};
CGraphicObjectBase.prototype.getNoUngrp = function(){
return this.getLockValue(LOCKS_MASKS.noUngrp);
};
CGraphicObjectBase.prototype.getNoSelect = function(){
return this.getLockValue(LOCKS_MASKS.noSelect);
};
CGraphicObjectBase.prototype.getNoRot = function(){
return this.getLockValue(LOCKS_MASKS.noRot);
};
CGraphicObjectBase.prototype.getNoChangeAspect = function(){
return this.getLockValue(LOCKS_MASKS.noChangeAspect);
};
CGraphicObjectBase.prototype.getNoMove = function(){
return this.getLockValue(LOCKS_MASKS.noMove);
};
CGraphicObjectBase.prototype.getNoResize = function(){
return this.getLockValue(LOCKS_MASKS.noResize);
};
CGraphicObjectBase.prototype.getNoEditPoints = function(){
return this.getLockValue(LOCKS_MASKS.noEditPoints);
};
CGraphicObjectBase.prototype.getNoAdjustHandles = function(){
return this.getLockValue(LOCKS_MASKS.noAdjustHandles);
};
CGraphicObjectBase.prototype.getNoChangeArrowheads = function(){
return this.getLockValue(LOCKS_MASKS.noChangeArrowheads);
};
CGraphicObjectBase.prototype.getNoChangeShapeType = function(){
return this.getLockValue(LOCKS_MASKS.noChangeShapeType);
};
CGraphicObjectBase.prototype.getNoDrilldown = function(){
return this.getLockValue(LOCKS_MASKS.noDrilldown);
};
CGraphicObjectBase.prototype.getNoTextEdit = function(){
return this.getLockValue(LOCKS_MASKS.noTextEdit);
};
CGraphicObjectBase.prototype.getNoCrop = function(){
return this.getLockValue(LOCKS_MASKS.noCrop);
};
CGraphicObjectBase.prototype.setNoChangeAspect = function(bValue){
return this.setLockValue(LOCKS_MASKS.noChangeAspect, bValue);
};
CGraphicObjectBase.prototype.Reassign_ImageUrls = function(mapUrl){
if(this.blipFill){
if(mapUrl[this.blipFill.RasterImageId]){
if(this.setBlipFill){
var blip_fill = new AscFormat.CBlipFill();
blip_fill.setRasterImageId(mapUrl[this.blipFill.RasterImageId]);
blip_fill.setStretch(true);
this.setBlipFill(blip_fill);
}
}
}
if(this.spPr && this.spPr.Fill && this.spPr.Fill.fill && this.spPr.Fill.fill.RasterImageId){
if(mapUrl[this.spPr.Fill.fill.RasterImageId]){
var blip_fill = new AscFormat.CBlipFill();
blip_fill.setRasterImageId(mapUrl[this.blipFill.RasterImageId]);
blip_fill.setStretch(true);
var oUniFill = new AscFormat.CUniFill();
oUniFill.setFill(blip_fill);
this.spPr.setFill(oUniFill);
}
}
if(Array.isArray(this.spTree)){
for(var i = 0; i < this.spTree.length; ++i){
if(this.spTree[i].Reassign_ImageUrls){
this.spTree[i].Reassign_ImageUrls(mapUrl);
}
}
}
};
CGraphicObjectBase.prototype.getAllFonts = function(mapUrl){
};
window['AscFormat'] = window['AscFormat'] || {};
window['AscFormat'].CGraphicObjectBase = CGraphicObjectBase;
window['AscFormat'].CGraphicBounds = CGraphicBounds;
window['AscFormat'].checkNormalRotate = checkNormalRotate;
window['AscFormat'].normalizeRotate = normalizeRotate;
window['AscFormat'].LOCKS_MASKS = LOCKS_MASKS;
})(window); | fix typo
| common/Drawings/Format/GraphicObjectBase.js | fix typo | <ide><path>ommon/Drawings/Format/GraphicObjectBase.js
<ide> if(this.spPr && this.spPr.Fill && this.spPr.Fill.fill && this.spPr.Fill.fill.RasterImageId){
<ide> if(mapUrl[this.spPr.Fill.fill.RasterImageId]){
<ide> var blip_fill = new AscFormat.CBlipFill();
<del> blip_fill.setRasterImageId(mapUrl[this.blipFill.RasterImageId]);
<add> blip_fill.setRasterImageId(mapUrl[this.spPr.Fill.fill.RasterImageId]);
<ide> blip_fill.setStretch(true);
<ide> var oUniFill = new AscFormat.CUniFill();
<ide> oUniFill.setFill(blip_fill); |
|
Java | mit | dfc77cc93a6edf81d05b55fe372ab02944695134 | 0 | anyazz/SimpleTweets | package com.codepath.apps.restclienttemplate.models;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.codepath.apps.restclienttemplate.ProfileActivity;
import com.codepath.apps.restclienttemplate.R;
import com.codepath.apps.restclienttemplate.TimelineActivity;
import com.codepath.apps.restclienttemplate.TweetDetailActivity;
import com.codepath.apps.restclienttemplate.TwitterApp;
import com.codepath.apps.restclienttemplate.TwitterClient;
import com.codepath.apps.restclienttemplate.fragments.ModalFragment;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import cz.msebera.android.httpclient.Header;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
/**
* Created by anyazhang on 6/26/17.
*/
public class TweetAdapter extends RecyclerView.Adapter<TweetAdapter.ViewHolder> {
public final static int IMAGE_HEIGHT = 150;
private List<Tweet> mTweets;
Context context;
// pass in Tweets array in the constructor
public TweetAdapter(List<Tweet> tweets) {
mTweets = tweets;
}
boolean wrapInScrollView = false;
private TwitterClient client = TwitterApp.getRestClient();
// for each row, inflate the layout and cache references into ViewHolder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View tweetView = inflater.inflate(R.layout.item_tweet, parent, false);
ViewHolder viewHolder = new ViewHolder(tweetView);
return viewHolder;
}
// convert dp to px - needed for image display
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
// bind values based on the position of the element
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// get the data according to position
final Tweet tweet = mTweets.get(position);
// populate the views according to this data
holder.tvUsername.setText(tweet.user.name);
holder.tvBody.setText(tweet.body);
holder.tvScreenName.setText("@" + tweet.user.screenName);
holder.tvTimestamp.setText(getRelativeTimeAgo(tweet.createdAt));
// shorten timestamps by converting "_ minutes ago" to "_m", etc
String shortTime = shortenRelativeTime((String) holder.tvTimestamp.getText());
holder.tvTimestamp.setText(shortTime);
// check retweet and favorite status
if (tweet.favorited) {
}
else {
}
if (tweet.retweeted) {
}
else {
}
// load profile image with Glide
Glide.with(context)
.load(tweet.user.profileImageUrl)
.bitmapTransform(new RoundedCornersTransformation(context, 5, 0))
.into(holder.ivProfileImage);
if (tweet.firstImageUrl == "") {
holder.ivFirstImage.setVisibility(View.GONE);
}
else {
holder.ivFirstImage.setVisibility(View.VISIBLE);
Glide.with(context)
.load(tweet.firstImageUrl)
.placeholder(R.drawable.default_placeholder)
.dontAnimate()
.bitmapTransform(new RoundedCornersTransformation(context, 15, 0))
.into(holder.ivFirstImage);
}
}
public String shortenRelativeTime(String timestamp) {
String[] splitTime = timestamp.trim().split("\\s+");
List<String> times = Arrays.asList("years", "year", "months", "month");
if (!times.contains(splitTime[1])) {
timestamp = splitTime[0] + splitTime[1].charAt(0);
}
return timestamp;
}
@Override
public int getItemCount() {
return mTweets.size();
}
// create ViewHolder class
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView ivProfileImage;
public TextView tvUsername;
public TextView tvBody;
public TextView tvScreenName;
public TextView tvTimestamp;
public ImageView ivReply;
public RelativeLayout itemTweet;
public ImageView ivFirstImage;
public ViewHolder (View itemView) {
super(itemView);
// perform findViewById lookups
ivProfileImage = (ImageView) itemView.findViewById(R.id.ivProfileImage);
tvUsername = (TextView) itemView.findViewById(R.id.tvUsername);
tvBody = (TextView) itemView.findViewById(R.id.tvBody);
tvScreenName = (TextView) itemView.findViewById(R.id.tvScreenName);
tvTimestamp = (TextView) itemView.findViewById(R.id.tvTimestamp);
ivReply = (ImageView) itemView.findViewById(R.id.ivReply);
itemTweet = (RelativeLayout) itemView.findViewById(R.id.itemTweet);
ivFirstImage = (ImageView) itemView.findViewById(R.id.ivFirstImage);
// set on click listeners
itemTweet.setOnClickListener(this);
ivReply.setOnClickListener(this);
ivProfileImage.setOnClickListener(this);
}
@Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
int position = getAdapterPosition();
Tweet tweet = mTweets.get(position);
Log.d("clicked", String.valueOf(v.getId()));
Intent i;
switch (v.getId()) {
// if reply button clicked
case R.id.ivReply:
Log.d("clicked", "reply");
ModalFragment modalFragment = ModalFragment.newInstance(tweet.uid, "@" + tweet.user.screenName + " ");
modalFragment.openComposeModal(context);
// FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//
// // make change
// ft.replace(R.id.flContainer, modalFragment);
//
// // commit
// ft.commit();
//
// openComposeModal(tweet.uid, "@" + tweet.user.screenName + " ", null);
break;
case R.id.ivProfileImage:
Log.d("clicked", "profile");
i = new Intent(context, ProfileActivity.class);
i.putExtra("screen_name", tweet.user.screenName);
i.putExtra("origin", "tweet");
context.startActivity(i);
break;
default:
Log.d("clicked", "tweet");
i = new Intent(context, TweetDetailActivity.class);
i.putExtra("tweet_id", tweet.uid);
context.startActivity(i);
}
}
}
public void openComposeModal(final long reply_id, String tag, final TimelineActivity instance) {
// Tweet tweet;
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
final int MAX_TWEET_LENGTH = 140;
Log.d("clicked", "reply");
// inflate compose layout into view
final View activity_compose = inflater.inflate(R.layout.activity_compose, null);
// load data into view
EditText etTweetBody = (EditText) activity_compose.findViewById(R.id.etTweetBody);
etTweetBody.setText(tag);
etTweetBody.setSelection(tag.length());
final TextView tvCharCount = (TextView) activity_compose.findViewById(R.id.tvCharCount);
tvCharCount.setText(String.valueOf(MAX_TWEET_LENGTH - tag.length()));
// build modal
new MaterialDialog.Builder(context)
.title("Compose Tweet")
.customView(activity_compose, wrapInScrollView)
.positiveText("TWEET")
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
EditText etTweet = (EditText) activity_compose.findViewById(R.id.etTweetBody);
String tweetText = etTweet.getText().toString();
Log.d("onSubmit", tweetText);
Log.d("onSubmit", "#" + String.valueOf(reply_id));
client.sendTweet(tweetText, reply_id, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d("Success", String.valueOf(reply_id));
try {
Tweet tweet = Tweet.fromJSON(response);
if (instance != null) {
// instance.updateTimeline(tweet);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Log.d("TwitterClient", response.toString());
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("TwitterClient", responseString);
throwable.printStackTrace();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d("TwitterClient", errorResponse.toString());
throwable.printStackTrace();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
Log.d("TwitterClient", errorResponse.toString());
throwable.printStackTrace();
}
});
}
})
.show();
// // set on click listeners
// activity_compose.findViewById(R.id.ivReply).setOnClickListener(this);
// Tweet body character counter: adapted from
// https://stackoverflow.com/questions/3013791/live-character-count-for-edittext
final TextWatcher charCounter = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
//This sets a textview to the current length
tvCharCount.setText(String.valueOf(MAX_TWEET_LENGTH - s.length()));
}
public void afterTextChanged(Editable s) {
}
};
etTweetBody.addTextChangedListener(charCounter);
}
// getRelativeTimeAgo("Mon Apr 01 21:16:23 +0000 2014");
public String getRelativeTimeAgo(String rawJsonDate) {
String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH);
sf.setLenient(true);
String relativeDate = "";
try {
long dateMillis = sf.parse(rawJsonDate).getTime();
relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return relativeDate;
}
// Clean all elements of the recycler
public void clear() {
mTweets.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Tweet> list) {
mTweets.addAll(list);
notifyDataSetChanged();
}
}
| app/src/main/java/com/codepath/apps/restclienttemplate/models/TweetAdapter.java | package com.codepath.apps.restclienttemplate.models;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.codepath.apps.restclienttemplate.ProfileActivity;
import com.codepath.apps.restclienttemplate.R;
import com.codepath.apps.restclienttemplate.TimelineActivity;
import com.codepath.apps.restclienttemplate.TweetDetailActivity;
import com.codepath.apps.restclienttemplate.TwitterApp;
import com.codepath.apps.restclienttemplate.TwitterClient;
import com.codepath.apps.restclienttemplate.fragments.ModalFragment;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import cz.msebera.android.httpclient.Header;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
/**
* Created by anyazhang on 6/26/17.
*/
public class TweetAdapter extends RecyclerView.Adapter<TweetAdapter.ViewHolder> {
public final static int IMAGE_HEIGHT = 150;
private List<Tweet> mTweets;
Context context;
// pass in Tweets array in the constructor
public TweetAdapter(List<Tweet> tweets) {
mTweets = tweets;
}
boolean wrapInScrollView = false;
private TwitterClient client = TwitterApp.getRestClient();
// for each row, inflate the layout and cache references into ViewHolder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View tweetView = inflater.inflate(R.layout.item_tweet, parent, false);
ViewHolder viewHolder = new ViewHolder(tweetView);
return viewHolder;
}
// convert dp to px - needed for image display
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
// bind values based on the position of the element
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// get the data according to position
final Tweet tweet = mTweets.get(position);
// populate the views according to this data
holder.tvUsername.setText(tweet.user.name);
holder.tvBody.setText(tweet.body);
holder.tvScreenName.setText("@" + tweet.user.screenName);
holder.tvTimestamp.setText(getRelativeTimeAgo(tweet.createdAt));
// convert "_ minutes ago" to "_m", etc
String timestamp = (String) holder.tvTimestamp.getText();
String[] splitTime = timestamp.trim().split("\\s+");
List<String> times = Arrays.asList("years", "year", "months", "month");
if (!times.contains(splitTime[1])) {
timestamp = splitTime[0] + splitTime[1].charAt(0);
}
holder.tvTimestamp.setText(timestamp);
// check retweet and favorite status
if (tweet.favorited) {
}
else {
}
if (tweet.retweeted) {
}
else {
}
// load profile image with Glide
Glide.with(context)
.load(tweet.user.profileImageUrl)
.bitmapTransform(new RoundedCornersTransformation(context, 5, 0))
.into(holder.ivProfileImage);
if (tweet.firstImageUrl == "") {
holder.ivFirstImage.setVisibility(View.GONE);
}
else {
holder.ivFirstImage.setVisibility(View.VISIBLE);
Glide.with(context)
.load(tweet.firstImageUrl)
.placeholder(R.drawable.default_placeholder)
.dontAnimate()
.bitmapTransform(new RoundedCornersTransformation(context, 15, 0))
.into(holder.ivFirstImage);
}
}
@Override
public int getItemCount() {
return mTweets.size();
}
// create ViewHolder class
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView ivProfileImage;
public TextView tvUsername;
public TextView tvBody;
public TextView tvScreenName;
public TextView tvTimestamp;
public ImageView ivReply;
public RelativeLayout itemTweet;
public ImageView ivFirstImage;
public ViewHolder (View itemView) {
super(itemView);
// perform findViewById lookups
ivProfileImage = (ImageView) itemView.findViewById(R.id.ivProfileImage);
tvUsername = (TextView) itemView.findViewById(R.id.tvUsername);
tvBody = (TextView) itemView.findViewById(R.id.tvBody);
tvScreenName = (TextView) itemView.findViewById(R.id.tvScreenName);
tvTimestamp = (TextView) itemView.findViewById(R.id.tvTimestamp);
ivReply = (ImageView) itemView.findViewById(R.id.ivReply);
itemTweet = (RelativeLayout) itemView.findViewById(R.id.itemTweet);
ivFirstImage = (ImageView) itemView.findViewById(R.id.ivFirstImage);
// set on click listeners
itemTweet.setOnClickListener(this);
ivReply.setOnClickListener(this);
ivProfileImage.setOnClickListener(this);
}
@Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
int position = getAdapterPosition();
Tweet tweet = mTweets.get(position);
Log.d("clicked", String.valueOf(v.getId()));
Intent i;
switch (v.getId()) {
// if reply button clicked
case R.id.ivReply:
Log.d("clicked", "reply");
ModalFragment modalFragment = ModalFragment.newInstance(tweet.uid, "@" + tweet.user.screenName + " ");
modalFragment.openComposeModal(context);
// FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//
// // make change
// ft.replace(R.id.flContainer, modalFragment);
//
// // commit
// ft.commit();
//
// openComposeModal(tweet.uid, "@" + tweet.user.screenName + " ", null);
break;
case R.id.ivProfileImage:
Log.d("clicked", "profile");
i = new Intent(context, ProfileActivity.class);
i.putExtra("screen_name", tweet.user.screenName);
i.putExtra("origin", "tweet");
context.startActivity(i);
break;
default:
Log.d("clicked", "tweet");
i = new Intent(context, TweetDetailActivity.class);
i.putExtra("tweet_id", tweet.uid);
context.startActivity(i);
}
}
}
public void openComposeModal(final long reply_id, String tag, final TimelineActivity instance) {
// Tweet tweet;
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
final int MAX_TWEET_LENGTH = 140;
Log.d("clicked", "reply");
// inflate compose layout into view
final View activity_compose = inflater.inflate(R.layout.activity_compose, null);
// load data into view
EditText etTweetBody = (EditText) activity_compose.findViewById(R.id.etTweetBody);
etTweetBody.setText(tag);
etTweetBody.setSelection(tag.length());
final TextView tvCharCount = (TextView) activity_compose.findViewById(R.id.tvCharCount);
tvCharCount.setText(String.valueOf(MAX_TWEET_LENGTH - tag.length()));
// build modal
new MaterialDialog.Builder(context)
.title("Compose Tweet")
.customView(activity_compose, wrapInScrollView)
.positiveText("TWEET")
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
EditText etTweet = (EditText) activity_compose.findViewById(R.id.etTweetBody);
String tweetText = etTweet.getText().toString();
Log.d("onSubmit", tweetText);
Log.d("onSubmit", "#" + String.valueOf(reply_id));
client.sendTweet(tweetText, reply_id, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d("Success", String.valueOf(reply_id));
try {
Tweet tweet = Tweet.fromJSON(response);
if (instance != null) {
// instance.updateTimeline(tweet);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Log.d("TwitterClient", response.toString());
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("TwitterClient", responseString);
throwable.printStackTrace();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d("TwitterClient", errorResponse.toString());
throwable.printStackTrace();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
Log.d("TwitterClient", errorResponse.toString());
throwable.printStackTrace();
}
});
}
})
.show();
// // set on click listeners
// activity_compose.findViewById(R.id.ivReply).setOnClickListener(this);
// Tweet body character counter: adapted from
// https://stackoverflow.com/questions/3013791/live-character-count-for-edittext
final TextWatcher charCounter = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
//This sets a textview to the current length
tvCharCount.setText(String.valueOf(MAX_TWEET_LENGTH - s.length()));
}
public void afterTextChanged(Editable s) {
}
};
etTweetBody.addTextChangedListener(charCounter);
}
// getRelativeTimeAgo("Mon Apr 01 21:16:23 +0000 2014");
public String getRelativeTimeAgo(String rawJsonDate) {
String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH);
sf.setLenient(true);
String relativeDate = "";
try {
long dateMillis = sf.parse(rawJsonDate).getTime();
relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return relativeDate;
}
// Clean all elements of the recycler
public void clear() {
mTweets.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Tweet> list) {
mTweets.addAll(list);
notifyDataSetChanged();
}
}
| separated into shortenRelativeTime function
| app/src/main/java/com/codepath/apps/restclienttemplate/models/TweetAdapter.java | separated into shortenRelativeTime function | <ide><path>pp/src/main/java/com/codepath/apps/restclienttemplate/models/TweetAdapter.java
<ide> holder.tvScreenName.setText("@" + tweet.user.screenName);
<ide> holder.tvTimestamp.setText(getRelativeTimeAgo(tweet.createdAt));
<ide>
<del> // convert "_ minutes ago" to "_m", etc
<del> String timestamp = (String) holder.tvTimestamp.getText();
<del> String[] splitTime = timestamp.trim().split("\\s+");
<del> List<String> times = Arrays.asList("years", "year", "months", "month");
<del> if (!times.contains(splitTime[1])) {
<del> timestamp = splitTime[0] + splitTime[1].charAt(0);
<del> }
<del> holder.tvTimestamp.setText(timestamp);
<add> // shorten timestamps by converting "_ minutes ago" to "_m", etc
<add> String shortTime = shortenRelativeTime((String) holder.tvTimestamp.getText());
<add> holder.tvTimestamp.setText(shortTime);
<ide>
<ide>
<ide> // check retweet and favorite status
<ide> .bitmapTransform(new RoundedCornersTransformation(context, 15, 0))
<ide> .into(holder.ivFirstImage);
<ide> }
<add> }
<add>
<add> public String shortenRelativeTime(String timestamp) {
<add> String[] splitTime = timestamp.trim().split("\\s+");
<add> List<String> times = Arrays.asList("years", "year", "months", "month");
<add> if (!times.contains(splitTime[1])) {
<add> timestamp = splitTime[0] + splitTime[1].charAt(0);
<add> }
<add> return timestamp;
<ide> }
<ide>
<ide> @Override |
|
Java | unlicense | c453143f1fcca4e7d4aeed28b7b2e7da225170e9 | 0 | fuzzyBSc/systemdesign,fuzzyBSc/systemdesign | /*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <http://unlicense.org/>
*/
package au.id.soundadvice.systemdesign.fxml;
import au.id.soundadvice.systemdesign.model.Baseline;
import au.id.soundadvice.systemdesign.baselines.EditState;
import au.id.soundadvice.systemdesign.concurrent.SingleRunnable;
import au.id.soundadvice.systemdesign.model.UndoState;
import au.id.soundadvice.systemdesign.concurrent.JFXExecutor;
import au.id.soundadvice.systemdesign.files.Identifiable;
import au.id.soundadvice.systemdesign.fxml.drag.DragTarget;
import au.id.soundadvice.systemdesign.model.Function;
import au.id.soundadvice.systemdesign.fxml.DropHandlers.FunctionDropHandler;
import au.id.soundadvice.systemdesign.fxml.drag.DragSource;
import au.id.soundadvice.systemdesign.model.Item;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.KeyCode;
import javax.annotation.CheckReturnValue;
/**
*
* @author Benjamin Carlyle <[email protected]>
*/
public class LogicalTreeController {
public LogicalTreeController(
Interactions interactions, EditState edit,
TreeView<Function> view) {
this.interactions = interactions;
this.edit = edit;
this.view = view;
this.changed = new SingleRunnable<>(edit.getExecutor(), new Changed());
this.updateView = new SingleRunnable<>(JFXExecutor.instance(), new UpdateView());
this.functionCreator = new FunctionCreator(edit);
}
public void start() {
addContextMenu();
edit.subscribe(changed);
changed.run();
}
public void stop() {
edit.unsubscribe(changed);
}
private void addContextMenu() {
view.setContextMenu(ContextMenus.logicalTreeBackgroundMenu(functionCreator));
}
public static final class FunctionAllocation {
public FunctionAllocation(Optional<Function> parent, SortedMap<String, Function> children) {
this.parent = parent;
this.children = children;
}
public String getDisplayName() {
return parent.map(Function::getName).orElse("Logical");
}
private final Optional<Function> parent;
private final SortedMap<String, Function> children;
private boolean isEmpty() {
return children.isEmpty();
}
}
private static class TreeState {
private final SortedMap<String, FunctionAllocation> allocation;
private final FunctionAllocation orphans;
private TreeState(UndoState state) {
Optional<Item> systemOfInterest = state.getSystemOfInterest();
Baseline functional = state.getFunctional();
Baseline allocated = state.getAllocated();
Map<UUID, Function> parentFunctions;
if (systemOfInterest.isPresent()) {
parentFunctions = systemOfInterest.get().getOwnedFunctions(functional)
.collect(Identifiable.toMap());
} else {
parentFunctions = Collections.emptyMap();
}
Map<Function, SortedMap<String, Function>> rawAllocation = new HashMap<>();
parentFunctions.values()
.forEach(parent -> rawAllocation.put(parent, new TreeMap<>()));
// Keep orphans separate to avoid null pointers in TreeMap
SortedMap<String, Function> rawOrphans = new TreeMap<>();
allocated.getFunctions()
.filter(function -> !function.isExternal())
.forEach(child -> {
// Parent may be null, ie child is orphaned
Optional<Function> trace = child.getTrace(functional);
SortedMap<String, Function> map = trace.isPresent()
? rawAllocation.get(trace.get()) : rawOrphans;
map.put(child.getDisplayName(allocated), child);
});
SortedMap<String, FunctionAllocation> tmpAllocation = new TreeMap<>();
rawAllocation.entrySet().stream()
.map(entry -> new FunctionAllocation(Optional.of(entry.getKey()), Collections.unmodifiableSortedMap(entry.getValue())))
.forEach(alloc -> {
tmpAllocation.put(alloc.getDisplayName(), alloc);
});
this.allocation = Collections.unmodifiableSortedMap(tmpAllocation);
this.orphans = new FunctionAllocation(
Optional.empty(), Collections.unmodifiableSortedMap(rawOrphans));
}
}
private class Changed implements Runnable {
@Override
public void run() {
TreeState newState = new TreeState(edit.getUndo().get());
TreeState oldState = treeState.getAndSet(newState);
if (!newState.equals(oldState)) {
updateView.run();
}
}
}
private class UpdateView implements Runnable {
@Override
public void run() {
TreeState state = treeState.get();
TreeItem root = new TreeItem();
root.setExpanded(true);
root.getChildren().addAll(
state.allocation.values().stream()
.filter(allocation -> allocation.parent.isPresent())
.map(allocation -> {
TreeItem parent = new TreeItem(allocation.parent.get());
parent.setExpanded(true);
parent.getChildren().addAll(allocation.children.values().stream()
.map((child) -> new TreeItem(child))
.toArray());
return parent;
}).toArray());
// Add orphans at the end
FunctionAllocation orphans = state.orphans;
if (!orphans.isEmpty()) {
TreeItem parent;
if (root.getChildren().isEmpty()) {
parent = root;
} else {
parent = new TreeItem();
parent.setExpanded(true);
root.getChildren().add(parent);
}
parent.getChildren().addAll(orphans.children.values().stream()
.map((child) -> new TreeItem(child))
.toArray());
}
view.setRoot(root);
view.setShowRoot(false);
view.setEditable(true);
view.setCellFactory(view -> {
FunctionTreeCell cell = new FunctionTreeCell();
cell.start();
return cell;
});
}
}
private final class FunctionTreeCell extends TreeCell<Function> {
private Optional<TextField> textField = Optional.empty();
private final ContextMenu contextMenu = new ContextMenu();
public FunctionTreeCell() {
MenuItem addMenuItem = new MenuItem("Add Function");
contextMenu.getItems().add(addMenuItem);
addMenuItem.setOnAction(event -> {
functionCreator.add(getItem());
event.consume();
});
MenuItem deleteMenuItem = new MenuItem("Delete Function");
contextMenu.getItems().add(deleteMenuItem);
deleteMenuItem.setOnAction(event -> {
edit.updateAllocated(baseline -> {
return getItem().removeFrom(baseline);
});
event.consume();
});
this.editableProperty().bind(this.itemProperty().isNotNull());
}
public void start() {
DragSource.bind(this, () -> Optional.ofNullable(getItem()), false);
DragTarget.bind(edit, this, () -> Optional.ofNullable(getItem()),
new FunctionDropHandler(interactions, edit));
}
@Override
public void startEdit() {
Function function = getItem();
if (function != null) {
super.startEdit();
if (!textField.isPresent()) {
textField = Optional.of(createTextField(getItem()));
}
setText(null);
setGraphic(textField.get());
textField.get().selectAll();
textField.get().requestFocus();
}
}
@Override
public void cancelEdit() {
if (isFocused()) {
super.cancelEdit();
setText(getString());
setGraphic(getTreeItem().getGraphic());
} else {
/*
* If the cancelEdit is due to a loss of focus, override it.
* Commit instead.
*/
if (textField.isPresent()) {
commitEdit(getItem());
}
}
}
@Override
public void commitEdit(Function function) {
edit.updateAllocated(allocated -> {
Optional<Function> current = allocated.get(function);
if (current.isPresent()) {
Baseline.BaselineAnd<Function> result = current.get().setName(
allocated, textField.get().getText());
super.commitEdit(result.getRelation());
return result.getBaseline();
} else {
return allocated;
}
});
}
@Override
public void updateItem(Function function, boolean empty) {
super.updateItem(function, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
setText(null);
if (textField.isPresent()) {
textField.get().setText(getString());
setGraphic(textField.get());
}
} else {
setText(getString());
setGraphic(getTreeItem().getGraphic());
setContextMenu(contextMenu);
}
}
}
@CheckReturnValue
private TextField createTextField(Function function) {
TextField node = new TextField(function.getName());
node.setOnKeyReleased(event -> {
if (event.getCode() == KeyCode.ENTER) {
commitEdit(getItem());
event.consume();
} else if (event.getCode() == KeyCode.ESCAPE) {
cancelEdit();
event.consume();
}
});
return node;
}
private String getString() {
return getItem() == null ? "(unallocated)" : getItem().toString();
}
}
private final Interactions interactions;
private final EditState edit;
private final TreeView<Function> view;
private final AtomicReference<TreeState> treeState = new AtomicReference<>();
private final SingleRunnable<Changed> changed;
private final SingleRunnable<UpdateView> updateView;
private final FunctionCreator functionCreator;
}
| SystemDesign/src/main/java/au/id/soundadvice/systemdesign/fxml/LogicalTreeController.java | /*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <http://unlicense.org/>
*/
package au.id.soundadvice.systemdesign.fxml;
import au.id.soundadvice.systemdesign.model.Baseline;
import au.id.soundadvice.systemdesign.baselines.EditState;
import au.id.soundadvice.systemdesign.concurrent.SingleRunnable;
import au.id.soundadvice.systemdesign.model.UndoState;
import au.id.soundadvice.systemdesign.concurrent.JFXExecutor;
import au.id.soundadvice.systemdesign.files.Identifiable;
import au.id.soundadvice.systemdesign.fxml.drag.DragTarget;
import au.id.soundadvice.systemdesign.model.Function;
import au.id.soundadvice.systemdesign.fxml.DropHandlers.FunctionDropHandler;
import au.id.soundadvice.systemdesign.fxml.drag.DragSource;
import au.id.soundadvice.systemdesign.model.Item;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.KeyCode;
import javax.annotation.CheckReturnValue;
/**
*
* @author Benjamin Carlyle <[email protected]>
*/
public class LogicalTreeController {
public LogicalTreeController(
Interactions interactions, EditState edit,
TreeView<Function> view) {
this.interactions = interactions;
this.edit = edit;
this.view = view;
this.changed = new SingleRunnable<>(edit.getExecutor(), new Changed());
this.updateView = new SingleRunnable<>(JFXExecutor.instance(), new UpdateView());
this.functionCreator = new FunctionCreator(edit);
}
public void start() {
addContextMenu();
edit.subscribe(changed);
changed.run();
}
public void stop() {
edit.unsubscribe(changed);
}
private void addContextMenu() {
view.setContextMenu(ContextMenus.logicalTreeBackgroundMenu(functionCreator));
}
public static final class FunctionAllocation {
public FunctionAllocation(Optional<Function> parent, SortedMap<String, Function> children) {
this.parent = parent;
this.children = children;
}
public String getDisplayName() {
return parent.map(Function::getName).orElse("Logical");
}
private final Optional<Function> parent;
private final SortedMap<String, Function> children;
private boolean isEmpty() {
return children.isEmpty();
}
}
private static class TreeState {
private final SortedMap<String, FunctionAllocation> allocation;
private final FunctionAllocation orphans;
private TreeState(UndoState state) {
Optional<Item> systemOfInterest = state.getSystemOfInterest();
Baseline functional = state.getFunctional();
Baseline allocated = state.getAllocated();
Map<UUID, Function> parentFunctions;
if (systemOfInterest.isPresent()) {
parentFunctions = systemOfInterest.get().getOwnedFunctions(functional)
.collect(Identifiable.toMap());
} else {
parentFunctions = Collections.emptyMap();
}
Map<Function, SortedMap<String, Function>> rawAllocation = new HashMap<>();
parentFunctions.values()
.forEach(parent -> rawAllocation.put(parent, new TreeMap<>()));
// Keep orphans separate to avoid null pointers in TreeMap
SortedMap<String, Function> rawOrphans = new TreeMap<>();
allocated.getFunctions()
.forEach(child -> {
// Parent may be null, ie child is orphaned
Optional<Function> trace = child.getTrace(functional);
SortedMap<String, Function> map = trace.isPresent()
? rawAllocation.get(trace.get()) : rawOrphans;
map.put(child.getDisplayName(allocated), child);
});
SortedMap<String, FunctionAllocation> tmpAllocation = new TreeMap<>();
rawAllocation.entrySet().stream()
.map(entry -> new FunctionAllocation(Optional.of(entry.getKey()), Collections.unmodifiableSortedMap(entry.getValue())))
.forEach(alloc -> {
tmpAllocation.put(alloc.getDisplayName(), alloc);
});
this.allocation = Collections.unmodifiableSortedMap(tmpAllocation);
this.orphans = new FunctionAllocation(
Optional.empty(), Collections.unmodifiableSortedMap(rawOrphans));
}
}
private class Changed implements Runnable {
@Override
public void run() {
TreeState newState = new TreeState(edit.getUndo().get());
TreeState oldState = treeState.getAndSet(newState);
if (!newState.equals(oldState)) {
updateView.run();
}
}
}
private class UpdateView implements Runnable {
@Override
public void run() {
TreeState state = treeState.get();
TreeItem root = new TreeItem();
root.setExpanded(true);
root.getChildren().addAll(
state.allocation.values().stream()
.filter(allocation -> allocation.parent.isPresent())
.map(allocation -> {
TreeItem parent = new TreeItem(allocation.parent.get());
parent.setExpanded(true);
parent.getChildren().addAll(allocation.children.values().stream()
.map((child) -> new TreeItem(child))
.toArray());
return parent;
}).toArray());
// Add orphans at the end
FunctionAllocation orphans = state.orphans;
if (!orphans.isEmpty()) {
TreeItem parent;
if (root.getChildren().isEmpty()) {
parent = root;
} else {
parent = new TreeItem();
parent.setExpanded(true);
root.getChildren().add(parent);
}
parent.getChildren().addAll(orphans.children.values().stream()
.map((child) -> new TreeItem(child))
.toArray());
}
view.setRoot(root);
view.setShowRoot(false);
view.setEditable(true);
view.setCellFactory(view -> {
FunctionTreeCell cell = new FunctionTreeCell();
cell.start();
return cell;
});
}
}
private final class FunctionTreeCell extends TreeCell<Function> {
private Optional<TextField> textField = Optional.empty();
private final ContextMenu contextMenu = new ContextMenu();
public FunctionTreeCell() {
MenuItem addMenuItem = new MenuItem("Add Function");
contextMenu.getItems().add(addMenuItem);
addMenuItem.setOnAction(event -> {
functionCreator.add(getItem());
event.consume();
});
MenuItem deleteMenuItem = new MenuItem("Delete Function");
contextMenu.getItems().add(deleteMenuItem);
deleteMenuItem.setOnAction(event -> {
edit.updateAllocated(baseline -> {
return getItem().removeFrom(baseline);
});
event.consume();
});
this.editableProperty().bind(this.itemProperty().isNotNull());
}
public void start() {
DragSource.bind(this, () -> Optional.ofNullable(getItem()), false);
DragTarget.bind(edit, this, () -> Optional.ofNullable(getItem()),
new FunctionDropHandler(interactions, edit));
}
@Override
public void startEdit() {
Function function = getItem();
if (function != null) {
super.startEdit();
if (!textField.isPresent()) {
textField = Optional.of(createTextField(getItem()));
}
setText(null);
setGraphic(textField.get());
textField.get().selectAll();
textField.get().requestFocus();
}
}
@Override
public void cancelEdit() {
if (isFocused()) {
super.cancelEdit();
setText(getString());
setGraphic(getTreeItem().getGraphic());
} else {
/*
* If the cancelEdit is due to a loss of focus, override it.
* Commit instead.
*/
if (textField.isPresent()) {
commitEdit(getItem());
}
}
}
@Override
public void commitEdit(Function function) {
edit.updateAllocated(allocated -> {
Optional<Function> current = allocated.get(function);
if (current.isPresent()) {
Baseline.BaselineAnd<Function> result = current.get().setName(
allocated, textField.get().getText());
super.commitEdit(result.getRelation());
return result.getBaseline();
} else {
return allocated;
}
});
}
@Override
public void updateItem(Function function, boolean empty) {
super.updateItem(function, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
setText(null);
if (textField.isPresent()) {
textField.get().setText(getString());
setGraphic(textField.get());
}
} else {
setText(getString());
setGraphic(getTreeItem().getGraphic());
setContextMenu(contextMenu);
}
}
}
@CheckReturnValue
private TextField createTextField(Function function) {
TextField node = new TextField(function.getName());
node.setOnKeyReleased(event -> {
if (event.getCode() == KeyCode.ENTER) {
commitEdit(getItem());
event.consume();
} else if (event.getCode() == KeyCode.ESCAPE) {
cancelEdit();
event.consume();
}
});
return node;
}
private String getString() {
return getItem() == null ? "(unallocated)" : getItem().toString();
}
}
private final Interactions interactions;
private final EditState edit;
private final TreeView<Function> view;
private final AtomicReference<TreeState> treeState = new AtomicReference<>();
private final SingleRunnable<Changed> changed;
private final SingleRunnable<UpdateView> updateView;
private final FunctionCreator functionCreator;
}
| Don't show external functions as unallocated | SystemDesign/src/main/java/au/id/soundadvice/systemdesign/fxml/LogicalTreeController.java | Don't show external functions as unallocated | <ide><path>ystemDesign/src/main/java/au/id/soundadvice/systemdesign/fxml/LogicalTreeController.java
<ide> // Keep orphans separate to avoid null pointers in TreeMap
<ide> SortedMap<String, Function> rawOrphans = new TreeMap<>();
<ide> allocated.getFunctions()
<add> .filter(function -> !function.isExternal())
<ide> .forEach(child -> {
<ide> // Parent may be null, ie child is orphaned
<ide> Optional<Function> trace = child.getTrace(functional); |
|
JavaScript | mit | 6844f2e014cbea4b0143625ae83da6b68f411188 | 0 | auth0/docs,auth0/docs,auth0/docs | // This is the list of APIs used in the old two-step quickstarts.
const apiNames = [
'aspnet-webapi',
'aws',
'azure-blob-storage',
'azure-mobile-services',
'azure-sb',
'falcor',
'firebase',
'golang',
'hapi',
'java-spring-security',
'java',
'nginx',
'nodejs',
'php-laravel',
'php-symfony',
'php',
'python',
'rails',
'ruby',
'salesforce-sandbox',
'salesforce',
'sap-odata',
'wcf-service',
'webapi-owin'
];
const apis = `:api(${apiNames.join('|')})`;
module.exports = [
/* MISCELLANEOUS AND OUTDATED */
{
from: ['/addons','/firebaseapi-tutorial','/salesforcesandboxapi-tutorial','/salesforceapi-tutorial','/sapapi-tutorial','/clients/addons','/applications/addons','/addons/azure-blob-storage','/addons/azure-mobile-services','/addons/azure-sb'],
to: '/'
},
{
from: '/topics/guides',
to: '/'
},
{
from: ['/design','/design/web'],
to: '/'
},
{
from: ['/design/browser-based-vs-native-experience-on-mobile','/tutorials/browser-based-vs-native-experience-on-mobile'],
to: '/best-practices/mobile-device-login-flow-best-practices'
},
{
from: '/topics/identity-glossary',
to: '/glossary'
},
{
from: ['/deploy/checklist'],
to: '/deploy/deploy-checklist'
},
/* QUICKSTARTS */
{
from: ['/android-tutorial', '/native-platforms/android', '/quickstart/native/android-vnext'],
to: '/quickstart/native/android'
},
{
from: [
'/angular-tutorial',
'/client-platforms/angularjs'
],
to: '/quickstart/spa/angularjs'
},
{
from: '/client-platforms/angular2',
to: '/quickstart/spa/angular'
},
{
from: ['/quickstart/spa/angularjs', '/quickstart/spa/angular2', '/quickstart/spa/angular-next'],
to: '/quickstart/spa/angular'
},
{
from: '/quickstarts/spa/vanillajs/01-login',
to: '/quickstart/spa/vanillajs/01-login'
},
{
from: [
'/quickstart/webapp/aspnet',
'/aspnet-tutorial',
'/mvc3-tutorial'
],
to: '/quickstart/webapp'
},
{
from: ['/aspnet-owin-tutorial', '/aspnetwebapi-owin-tutorial'],
to: '/quickstart/webapp/aspnet-owin'
},
{
from: [
'/aspnetwebapi-tutorial',
'/tutorials/aspnet-mvc4-enterprise-providers',
'/webapi',
'/mvc-tutorial-enterprise',
'/quickstart/backend/aspnet-webapi'
],
to: '/quickstart/backend'
},
{
from: [
'/quickstart/native/chrome-extension',
'/quickstart/native/chrome'
],
to: '/quickstart/native'
},
{
from: ['/ember-tutorial', '/client-platforms/emberjs'],
to: '/quickstart/spa/emberjs'
},
{
from: [
'/ionic-tutorial',
'/quickstart/native/ionic'
],
to: '/quickstart/native/ionic-angular'
},
{
from: ['/ios-tutorial', '/native-platforms/ios-objc', '/quickstart/native/ios-objc'],
to: '/quickstart/native/ios-swift'
},
{
from: '/java-tutorial',
to: '/quickstart/webapp/java'
},
{
from: '/javaapi-tutorial',
to: '/quickstart/backend/java'
},
{
from: '/server-platforms/golang',
to: '/quickstart/webapp/golang'
},
{
from: '/laravel-tutorial',
to: '/quickstart/webapp/laravel'
},
{
from: [
'/laravelapi-tutorial',
'/quickstart/backend/php-laravel'
],
to: '/quickstart/backend/laravel'
},
{
from: '/nodeapi-tutorial',
to: '/quickstart/backend/nodejs'
},
{
from: ['/nodejs-tutorial', '/server-platforms/nodejs'],
to: '/quickstart/webapp/nodejs'
},
{
from: '/phpapi-tutorial',
to: '/quickstart/backend/php'
},
{
from: '/pythonapi-tutorial',
to: '/quickstart/backend/python'
},
{
from: '/client-platforms/react',
to: '/quickstart/spa/react'
},
{
from: '/quickstart/native/ios-reactnative',
to: '/quickstart/native/react-native'
},
{
from: '/rubyapi-tutorial',
to: '/quickstart/backend/rails'
},
{
from: '/rails-tutorial',
to: '/quickstart/webapp/rails'
},
{
from: [
'/server-apis/ruby',
'/quickstart/backend/ruby'
],
to: '/quickstart/backend/rails'
},
{
from: '/python-tutorial',
to: '/quickstart/webapp/python'
},
{
from: ['/php-tutorial', '/server-platforms/php'],
to: '/quickstart/webapp/php'
},
{
from: [
'/phonegap-tutorial',
'/quickstart/native/phonegap'
],
to: '/quickstart/native'
},
{
from: [
'/servicestack-tutorial',
'/quickstart/webapp/servicestack'
],
to: '/quickstart/webapp'
},
{
from: [
'/singlepageapp-tutorial',
'/client-platforms/vanillajs',
'/quickstart/spa/javascript/:client?'
],
to: '/quickstart/spa/vanillajs'
},
{
from: [
'/quickstart/webapp/play-2-scala',
'/quickstart/webapp/scala'
],
to: '/quickstart/webapp'
},
{
from: [
'/symfony-tutorial',
'/quickstart/webapp/symfony'
],
to: '/quickstart/webapp'
},
{
from: [
'/wcf-tutorial',
'/quickstart/backend/wcf-service'
],
to: '/quickstart/backend'
},
{
from: [
'/win8-cs-tutorial',
'/windowsstore-auth0-tutorial',
'/native-platforms/windows-store-csharp',
'/quickstart/native-mobile/windows8-cp/:client?',
'/quickstart/native/windows8-cp'
],
to: '/quickstart/native/windows-uwp-csharp'
},
{
from: [
'/win8-tutorial',
'/windowsstore-js-auth0-tutorial',
'/native-platforms/windows-store-javascript',
'/quickstart/native-mobile/windows8/:client',
'/quickstart/native/windows-uwp-javascript'
],
to: '/quickstart/native'
},
{
from: [
'/windowsphone-tutorial',
'/quickstart/native/windowsphone'
],
to: '/quickstart/native'
},
{
from: '/wpf-winforms-tutorial',
to: '/quickstart/native/wpf-winforms'
},
{
from: '/xamarin-tutorial',
to: '/quickstart/native/xamarin'
},
{
from: '/quickstart/:platform/reactnative-ios/:backend?',
to: '/quickstart/native/react-native'
},
{
from: '/quickstart/:platform/reactnative-android/:backend?',
to: '/quickstart/native/react-native'
},
{
from: '/quickstart/native/react-native-ios',
to: '/quickstart/native/react-native'
},
{
from: '/quickstart/native/react-native-android',
to: '/quickstart/native/react-native'
},
{
from: '/quickstart/spa/auth0-react',
to: '/quickstart/spa/react'
},
{
from: '/quickstart/spa/auth0-react/01',
to: '/quickstart/spa/react'
},
{
from: '/quickstart/spa/auth0-react/02',
to: '/quickstart/spa/react/02-calling-an-api'
},
{
from: [
'/quickstart/backend/webapi-owin/04-authentication-rs256-deprecated',
'/quickstart/backend/webapi-owin/04-authentication-rs256-legacy'
],
to: '/quickstart/backend/webapi-owin'
},
{
from: [
'/quickstart/backend/webapi-owin/05-authentication-hs256-deprecated',
'/quickstart/backend/webapi-owin/05-authentication-hs256-legacy'
],
to: '/quickstart/backend/webapi-owin'
},
{
from: [
'/quickstart/backend/webapi-owin/06-authorization-deprecated',
'/quickstart/backend/webapi-owin/06-authorization-legacy'
],
to: '/quickstart/backend/webapi-owin'
},
{
from: [
'/quickstart/backend/aspnet-core-webapi/04-authentication-rs256-deprecated',
'/quickstart/backend/aspnet-core-webapi/04-authentication-rs256-legacy'
],
to: '/quickstart/backend/aspnet-core-webapi'
},
{
from: [
'/quickstart/backend/aspnet-core-webapi/05-authentication-hs256-deprecated',
'/quickstart/backend/aspnet-core-webapi/05-authentication-hs256-legacy'
],
to: '/quickstart/backend/aspnet-core-webapi'
},
{
from: [
'/quickstart/backend/aspnet-core-webapi/06-authorization-deprecated',
'/quickstart/backend/aspnet-core-webapi/06-authorization-legacy'
],
to: '/quickstart/backend/aspnet-core-webapi'
},
{
from: '/quickstart/webapp/aspnet-core-3',
to: '/quickstart/webapp/aspnet-core'
},
{
from: [
'/quickstart/spa/react/03-user-profile',
'/quickstart/spa/react/04-user-profile'
],
to: '/quickstart/spa/react'
},
{
from: '/quickstart/webapp/nodejs/02-user-profile',
to: '/quickstart/webapp/nodejs/01-login'
},
{
from: [
'/quickstart/hybrid',
'/quickstart/native-mobile'
],
to: '/quickstart/native'
},
{
from: [
'/quickstart/hybrid/:platform',
'/quickstart/native-mobile/:platform',
`/quickstart/hybrid/:platform/${apis}`,
`/quickstart/native-mobile/:platform/${apis}`,
`/quickstart/native/:platform/${apis}`,
'/quickstart/native/:platform'
],
to: '/quickstart/native'
},
{
from: [
`/quickstart/spa/:platform/${apis}`,
'/quickstart/spa/:platform'
],
to: '/quickstart/spa'
},
{
from: ['/quickstart/backend/:platform',`/quickstart/backend/:platform/${apis}`],
to: '/quickstart/backend'
},
{
from: '/quickstart/spa/emberjs',
to: '/quickstart/spa/ember'
},
{
from: [
'/quickstart/spa/aurelia',
'/quickstart/spa/ember',
'/quickstart/spa/jquery'
],
to: '/quickstart/spa'
},
{
from: '/quickstart',
to: '/'
},
{
from: '/quickstart/backend/java',
to: '/quickstart/backend/java-spring-security5',
},
{
from: '/quickstart/native/ios',
to: '/quickstart/native/ios-swift'
},
{
from: '/quickstart/native/ionic4',
to: '/quickstart/native/ionic-angular'
},
{
from: '/quickstart/native/ionic/00-intro',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/02-custom-login',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/03-user-profile',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/04-linking-accounts',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/05-rules',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/06-authorization',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/08-mfa',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/09-customizing-lock',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/backend/nodejs/00-getting-started',
to: '/quickstart/backend/nodejs'
},
{
from: '/quickstart/backend/aspnet-core-webapi/00-getting-started',
to: '/quickstart/backend/aspnet-core-webapi'
},
{
from: [
'/quickstart/backend/falcor/00-getting-started',
'/quickstart/backend/falcor'
],
to: '/quickstart/backend'
},
{
from: '/quickstart/backend/golang/00-getting-started',
to: '/quickstart/backend/golang'
},
{
from: [
'/quickstart/backend/hapi/00-getting-started',
'/quickstart/backend/hapi'
],
to: '/quickstart/backend'
},
{
from: [
'/quickstart/backend/java-spring-security',
'/quickstart/backend/java-spring-security/00-getting-started'
],
to: '/quickstart/backend/java-spring-security5'
},
{
from: '/quickstart/backend/laravel/00-getting-started',
to: '/quickstart/backend/laravel'
},
{
from: '/quickstart/backend/php/00-getting-started',
to: '/quickstart/backend/php'
},
{
from: '/quickstart/backend/python/00-getting-started',
to: '/quickstart/backend/python'
},
{
from: '/quickstart/backend/rails/00-getting-started',
to: '/quickstart/backend/rails'
},
{
from: '/quickstart/backend/ruby/00-getting-started',
to: '/quickstart/backend/ruby'
},
{
from: [
'/quickstart/backend/symfony/00-getting-started',
'/quickstart/backend/symfony'
],
to: '/quickstart/backend'
},
{
from: '/quickstart/backend/webapi-owin/00-getting-started',
to: '/quickstart/backend/webapi-owin'
},
{
from: '/quickstart/webapp/rails/00-introduction',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/02-custom-login',
to: '/quickstart/webapp/rails'
},
{
from: [
'/quickstart/webapp/rails/03-session-handling',
'/quickstart/webapp/rails/02-session-handling'
],
to: '/quickstart/webapp/rails'
},
{
from: [
'/quickstart/webapp/rails/04-user-profile',
'/quickstart/webapp/rails/03-user-profile'
],
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/05-linking-accounts',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/06-rules',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/07-authorization',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/08-mfa',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/09-customizing-lock',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/java/getting-started',
to: '/quickstart/webapp/java'
},
{
from: [
'/quickstart/webapp/java-spring-mvc/getting-started',
'/quickstart/webapp/java-spring-mvc'
],
to: '/quickstart/webapp/java-spring-boot'
},
{
from: [
'/quickstart/webapp/java-spring-security-mvc/00-intro',
'/quickstart/webapp/java-spring-security-mvc'
],
to: '/quickstart/webapp/java-spring-boot'
},
{
from: '/quickstart/spa/angular2/00-login',
to: '/quickstart/spa/angular'
},
{
from: '/quickstart/spa/angular2/03-user-profile',
to: '/quickstart/spa/angular'
},
{
from: '/quickstart/spa/angular2/04-calling-an-api',
to: '/quickstart/spa/angular'
},
{
from: '/quickstart/spa/angular2/05-authorization',
to: '/quickstart/spa/angular'
},
{
from: '/quickstart/spa/angular2/06-token-renewal',
to: '/quickstart/spa/angular'
},
/* CONNECTIONS */
{
from: [
'/37signals-clientid',
'/connections/social/37signals',
'/connections/social/basecamp'
],
to: 'https://marketplace.auth0.com/integrations/37signals-social-connection'
},
{
from: [
'/amazon-clientid',
'/connections/social/amazon'
],
to: 'https://marketplace.auth0.com/integrations/amazon-social-connection'
},
{
from: ['/connections/enterprise/azure-active-directory','/connections/social/active-directory','/waad-clientid','/users/guides/azure-access-control'],
to: '/connections/enterprise/azure-active-directory/v2'
},
{
from: '/connections/enterprise/azure-active-directory-classic',
to: '/connections/enterprise/azure-active-directory/v1'
},
{
from: '/connections/enterprise/samlp',
to: '/connections/enterprise/saml'
},
{
from: ['/connections/enterprise','/connections/enterprise/sharepoint-online','/connections/enterprise/ws-fed'],
to: '/connections/enterprise/saml'
},
{
from: [
'/dwolla-clientid',
'/connections/social/dwolla'
],
to: 'https://marketplace.auth0.com/integrations/dwolla-social-connection'
},
{
from: [
'/baidu-clientid',
'/connections/social/baidu'
],
to: 'https://marketplace.auth0.com/integrations/baidu-social-connection'
},
{
from: [
'/box-clientid',
'/connections/social/box'
],
to: 'https://marketplace.auth0.com/integrations/box-social-connection'
},
{
from: [
'/evernote-clientid',
'/connections/social/evernote'
],
to: 'https://marketplace.auth0.com/integrations/evernote-social-connection'
},
{
from: [
'/exact-clientid',
'/connections/social/exact'
],
to: 'https://marketplace.auth0.com/integrations/exact-social-connection'
},
{
from: [
'/facebook-clientid',
'/connections/social/facebook'
],
to: 'https://marketplace.auth0.com/integrations/facebook-social-connection'
},
{
from: [
'/fitbit-clientid',
'/connections/social/fitbit'
],
to: 'https://marketplace.auth0.com/integrations/fitbit-social-connection'
},
{
from: [
'/github-clientid',
'/connections/social/github'
],
to: 'https://marketplace.auth0.com/integrations/github-social-connection'
},
{
from: [
'/goog-clientid',
'/connections/social/google'
],
to: 'https://marketplace.auth0.com/integrations/google-social-connection'
},
{
from: [
'/ms-account-clientid',
'/connections/social/microsoft-account'
],
to: 'https://marketplace.auth0.com/integrations/microsoft-account-social-connection'
},
{
from: '/oauth2',
to: '/connections/social/oauth2'
},
{
from: '/connections/social/auth0-oidc',
to: '/connections/enterprise/oidc'
},
{
from: [
'/paypal-clientid',
'/connections/social/paypal'
],
to: 'https://marketplace.auth0.com/integrations/paypal-social-connection'
},
{
from: [
'/planningcenter-clientid',
'/connections/social/planning-center'
],
to: 'https://marketplace.auth0.com/integrations/planningcenter-social-connection'
},
{
from: [
'/salesforce-clientid',
'/connections/social/salesforce'
],
to: 'https://marketplace.auth0.com/integrations/salesforce-social-connection'
},
{
from: [
'/renren-clientid',
'/connections/social/renren'
],
to: 'https://marketplace.auth0.com/integrations/renren-social-connection'
},
{
from: [
'/shopify-clientid',
'/connections/social/shopify'
],
to: 'https://marketplace.auth0.com/integrations/shopify-social-connection'
},
{
from: [
'/twitter-clientid',
'/connections/social/twitter'
],
to: 'https://marketplace.auth0.com/integrations/twitter-social-connection'
},
{
from: [
'/vkontakte-clientid',
'/connections/social/vkontakte'
],
to: 'https://marketplace.auth0.com/integrations/vkontakte-social-connection'
},
{
from: [
'/weibo-clientid',
'/connections/social/weibo'
],
to: 'https://marketplace.auth0.com/integrations/weibo-social-connection'
},
{
from: [
'/wordpress-clientid',
'/connections/social/wordpress'
],
to: 'https://marketplace.auth0.com/integrations/wordpress-social-connection'
},
{
from: [
'/yahoo-clientid',
'/connections/social/yahoo'
],
to: 'https://marketplace.auth0.com/integrations/yahoo-social-connection'
},
{
from: [
'/yandex-clientid',
'/connections/social/yandex'
],
to: 'https://marketplace.auth0.com/integrations/yandex-social-connection'
},
{
from: [
'/linkedin-clientid',
'/connections/social/linkedin'
],
to: 'https://marketplace.auth0.com/integrations/linkedin-social-connection'
},
{
from: '/connections/social/bitbucket',
to: 'https://marketplace.auth0.com/integrations/bitbucket-social-connection'
},
{
from: '/connections/social/digitalocean',
to: 'https://marketplace.auth0.com/integrations/digitalocean-social-connection'
},
{
from: '/connections/social/discord',
to: 'https://marketplace.auth0.com/integrations/discord-social-connection'
},
{
from: '/connections/social/docomo',
to: 'https://marketplace.auth0.com/integrations/daccount-social-connection'
},
{
from: '/connections/social/dribbble',
to: 'https://marketplace.auth0.com/integrations/dribbble-social-connection'
},
{
from: '/connections/social/dropbox',
to: 'https://marketplace.auth0.com/integrations/dropbox-social-connection'
},
{
from: '/connections/social/evernote-sandbox',
to: 'https://marketplace.auth0.com/integrations/evernote-sandbox-social-connection'
},
{
from: '/connections/social/figma',
to: 'https://marketplace.auth0.com/integrations/figma-social-connection'
},
{
from: '/connections/social/paypal-sandbox',
to: 'https://marketplace.auth0.com/integrations/paypal-sandbox-social-connection'
},
{
from: '/connections/social/quickbooks-online',
to: 'https://marketplace.auth0.com/integrations/quickbooks-social-connection'
},
{
from: [
'/salesforce-community',
'/connections/social/salesforce-community'
],
to: 'https://marketplace.auth0.com/integrations/salesforce-community-social-connection'
},
{
from: '/connections/social/salesforce-sandbox',
to: 'https://marketplace.auth0.com/integrations/salesforce-sandbox-social-connection'
},
{
from: '/connections/social/slack',
to: 'https://marketplace.auth0.com/integrations/sign-in-with-slack'
},
{
from: '/connections/social/spotify',
to: 'https://marketplace.auth0.com/integrations/spotify-social-connection'
},
{
from: '/connections/social/stripe-connect',
to: 'https://marketplace.auth0.com/integrations/stripe-connect-social-connection'
},
{
from: '/connections/social/twitch',
to: 'https://marketplace.auth0.com/integrations/twitch-social-connection'
},
{
from: '/connections/social/vimeo',
to: 'https://marketplace.auth0.com/integrations/vimeo-social-connection'
},
{
from: '/connections/social/yammer',
to: 'https://marketplace.auth0.com/integrations/yammer-social-connection'
},
{
from: '/ad',
to: '/connections/enterprise/active-directory-ldap'
},
{
from: '/connections/enterprise/ldap',
to: '/connections/enterprise/active-directory-ldap'
},
{
from: '/connections/enterprise/active-directory',
to: '/connections/enterprise/active-directory-ldap'
},
{
from: '/adfs',
to: '/connections/enterprise/adfs'
},
{
from: [
'/passwordless',
'/dashboard/guides/connections/set-up-connections-passwordless',
'/api-auth/passwordless',
'/connections/passwordless/ios',
'/connections/passwordless/native-passwordless-universal',
'/connections/passwordless/reference/troubleshoot',
'/connections/passwordless/faq',
'/connections/passwordless/spa-email-code',
'/connections/passwordless/spa-email-link',
'/connections/passwordless/spa-sms',
'/connections/passwordless/guides/',
'/connections/passwordless/ios-sms-objc',
'/connections/passwordless/ios-sms'
],
to: '/connections/passwordless'
},
{
from: '/password-strength',
to: '/connections/database/password-strength'
},
{
from: [
'/identityproviders',
'/applications/concepts/connections',
'/applications/connections',
'/clients/connections'
],
to: '/connections'
},
{
from: ['/connections/database/mysql','/mysql-connection-tutorial','/connections/database/custom-db/custom-db-connection-overview'],
to: '/connections/database/custom-db'
},
{
from: ['/connections/database/password'],
to: '/connections/database/password-options'
},
{
from: ['/tutorials/adding-generic-oauth1-connection','/oauth1'],
to: '/connections/adding-generic-oauth1-connection',
},
{
from: ['/tutorials/adding-scopes-for-an-external-idp','/what-to-do-once-the-user-is-logged-in/adding-scopes-for-an-external-idp'],
to: '/connections/adding-scopes-for-an-external-idp',
},
{
from: ['/tutorials/generic-oauth2-connection-examples','/oauth2-examples'],
to: '/connections/generic-oauth2-connection-examples',
},
{
from: ['/tutorials/calling-an-external-idp-api','/what-to-do-once-the-user-is-logged-in/calling-an-external-idp-api'],
to: '/connections/calling-an-external-idp-api',
},
{
from: ['/tutorials/how-to-test-partner-connection','/test-partner-connection'],
to: '/connections/how-to-test-partner-connection',
},
{
from: '/connections/social/imgur',
to: 'https://marketplace.auth0.com/integrations/imgur-social-connection'
},
{
from: [
'/connections/grean/bankid-no',
'/connections/criipto/bankid-no',
'/connections/grean/bankid-se',
'/connections/criipto/bankid-se',
'/connections/grean/nemid',
'/connections/criipto/nemid'
],
to: 'https://marketplace.auth0.com/integrations/criipto-verify-e-id'
},
{
from: [
'/connections/passwordless/sms-gateway',
'/connections/passwordless/guides/use-sms-gateway-passwordless'
],
to: '/connections/passwordless/use-sms-gateway-passwordless'
},
{
from: [
'/connections/apple-setup',
'/connections/apple-siwa/set-up-apple',
'/connections/apple-siwa/add-siwa-web-app',
'/connections/apple-siwa/add-siwa-to-web-app',
'/connections/social/apple',
'/connections/apple-siwa/test-siwa-connection'
],
to: 'https://marketplace.auth0.com/integrations/apple-social-connection'
},
{
from: [
'/connections/apple-siwa/add-siwa-to-native-app',
'/connections/nativesocial/add-siwa-to-native-app',
'/connections/nativesocial/apple'
],
to: '/connections/social/apple-native'
},
{
from: [
'/connections/nativesocial/facebook-native'
],
to: '/connections/social/facebook-native'
},
{
from: [
'/connections/passwordless/email',
'/connections/passwordless/guides/email-otp'
],
to: '/connections/passwordless/email-otp'
},
{
from: [
'/connections/passwordless/sms',
'/connections/passwordless/guides/sms-otp'
],
to: '/connections/passwordless/sms-otp'
},
{
from: [
'/connections/passwordless/spa',
'/connections/passwordless/guides/universal-login'
],
to: '/connections/passwordless/universal-login'
},
{
from: [
'/connections/passwordless/regular-web-app',
'/connections/passwordless/guides/universal-login'
],
to: '/connections/passwordless/universal-login'
},
{
from: [
'/connections/identity-providers-social',
'/connections/social/aol',
'/aol-clientid',
'/connections/social/thecity',
'/thecity-clientid',
'/connections/social/miicard',
'/miicard-clientid',
'/connections/social',
'/connections/nativesocial/'],
to: '/connections/social/identity-providers'
},
{
from: [
'/connections/identity-providers-enterprise',
'/connections/enterprise/sharepoint-apps',
'/sharepoint-clientid'
],
to: '/connections/enterprise/identity-providers'
},
{
from: [
'/connections/identity-providers-legal'
],
to: '/connections/legal/identity-providers'
},
{
from: [
'/line',
'/connections/social/line'
],
to: 'https://marketplace.auth0.com/integrations/line-social-connection'
},
{
from: [
'/connections/passwordless/concepts/sample-use-cases-rules'
],
to: '/connections/passwordless/sample-use-cases-rules'
},
/* MICROSITES */
/* ARCHITECTURE SCENARIOS */
{
from: '/architecture-scenarios/application/mobile-api',
to: '/architecture-scenarios/mobile-api'
},
{
from: '/architecture-scenarios/application/server-api',
to: '/architecture-scenarios/server-api'
},
{
from: [
'/architecture-scenarios/application/spa-api',
'/architecture-scenarios/sequence-diagrams',
'/sequence-diagrams'
],
to: '/architecture-scenarios/spa-api'
},
{
from: '/architecture-scenarios/application/web-app-sso',
to: '/architecture-scenarios/web-app-sso'
},
{
from: '/architecture-scenarios/business/b2b',
to: '/architecture-scenarios/b2b'
},
{
from: [
'/architecture-scenarios/b2b/b2b-architecture',
'/architecture-scenarios/implementation/b2b/b2b-architecture'
],
to: '/architecture-scenarios/b2b/architecture'
},
{
from: [
'/architecture-scenarios/b2b/b2b-authentication',
'/architecture-scenarios/implementation/b2b/b2b-authentication'
],
to: '/architecture-scenarios/b2b/authentication'
},
{
from: [
'/architecture-scenarios/b2b/b2b-authorization',
'/architecture-scenarios/implementation/b2b/b2b-authorization'
],
to: '/architecture-scenarios/b2b/authorization'
},
{
from: [
'/architecture-scenarios/b2b/b2b-branding',
'/architecture-scenarios/implementation/b2b/b2b-branding'
],
to: '/architecture-scenarios/b2b/branding'
},
{
from: [
'/architecture-scenarios/b2b/b2b-deployment',
'/architecture-scenarios/implementation/b2b/b2b-deployment'
],
to: '/architecture-scenarios/b2b/deployment'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch',
'/architecture-scenarios/implementation/b2b/b2b-launch'
],
to: '/architecture-scenarios/b2b/launch'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-compliance',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-compliance'
],
to: '/architecture-scenarios/b2b/launch/compliance-readiness'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-launch',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-launch'
],
to: '/architecture-scenarios/b2b/launch/launch-day'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-operations',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-operations'
],
to: '/architecture-scenarios/b2b/launch/operations-readiness'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-support',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-support'
],
to: '/architecture-scenarios/b2b/launch/support-readiness'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-testing',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-testing'
],
to: '/architecture-scenarios/b2b/launch/testing'
},
{
from: [
'/architecture-scenarios/b2b/b2b-logout',
'/architecture-scenarios/implementation/b2b/b2b-logout'
],
to: '/architecture-scenarios/b2b/logout'
},
{
from: [
'/architecture-scenarios/b2b/b2b-operations',
'/architecture-scenarios/implementation/b2b/b2b-operations'
],
to: '/architecture-scenarios/b2b/operations'
},
{
from: [
'/architecture-scenarios/b2b/b2b-profile-mgmt',
'/architecture-scenarios/implementation/b2b/b2b-profile-mgmt'
],
to: '/architecture-scenarios/b2b/profile-management'
},
{
from: [
'/architecture-scenarios/b2b/b2b-provisioning',
'/architecture-scenarios/implementation/b2b/b2b-provisioning'
],
to: '/architecture-scenarios/b2b/provisioning'
},
{
from: [
'/architecture-scenarios/b2b/b2b-qa',
'/architecture-scenarios/implementation/b2b/b2b-qa'
],
to: '/architecture-scenarios/b2b/quality-assurance'
},
{
from: '/architecture-scenarios/business/b2c',
to: '/architecture-scenarios/b2c'
},
{
from: [
'/architecture-scenarios/b2c/b2c-architecture',
'/architecture-scenarios/implementation/b2c/b2c-architecture'
],
to: '/architecture-scenarios/b2c/architecture'
},
{
from: [
'/architecture-scenarios/b2c/b2c-authentication',
'/architecture-scenarios/implementation/b2c/b2c-authentication'
],
to: '/architecture-scenarios/b2c/authentication'
},
{
from: [
'/architecture-scenarios/b2c/b2c-authorization',
'/architecture-scenarios/implementation/b2c/b2c-authorization'
],
to: '/architecture-scenarios/b2c/authorization'
},
{
from: [
'/architecture-scenarios/b2c/b2c-branding',
'/architecture-scenarios/implementation/b2c/b2c-branding'
],
to: '/architecture-scenarios/b2c/branding'
},
{
from: [
'/architecture-scenarios/b2c/b2c-deployment',
'/architecture-scenarios/implementation/b2c/b2c-deployment'
],
to: '/architecture-scenarios/b2c/deployment'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch',
'/architecture-scenarios/implementation/b2c/b2c-launch'
],
to: '/architecture-scenarios/b2c/launch'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-compliance',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-compliance'
],
to: '/architecture-scenarios/b2c/launch/compliance-readiness'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-launch',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-launch'
],
to: '/architecture-scenarios/b2c/launch/launch-day'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-operations',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-operations'
],
to: '/architecture-scenarios/b2c/launch/operations-readiness'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-support',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-support'
],
to: '/architecture-scenarios/b2c/launch/support-readiness'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-testing',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-testing'
],
to: '/architecture-scenarios/b2c/launch/testing'
},
{
from: [
'/architecture-scenarios/b2c/b2c-logout',
'/architecture-scenarios/implementation/b2c/b2c-logout'
],
to: '/architecture-scenarios/b2c/logout'
},
{
from: [
'/architecture-scenarios/b2c/b2c-operations',
'/architecture-scenarios/implementation/b2c/b2c-operations'
],
to: '/architecture-scenarios/b2c/operations'
},
{
from: [
'/architecture-scenarios/b2c/b2c-profile-mgmt',
'/architecture-scenarios/implementation/b2c/b2c-profile-mgmt'
],
to: '/architecture-scenarios/b2c/profile-management'
},
{
from: [
'/architecture-scenarios/b2c/b2c-provisioning',
'/architecture-scenarios/implementation/b2c/b2c-provisioning'
],
to: '/architecture-scenarios/b2c/provisioning'
},
{
from: [
'/architecture-scenarios/b2c/b2c-qa',
'/architecture-scenarios/implementation/b2c/b2c-qa'
],
to: '/architecture-scenarios/b2c/quality-assurance'
},
{
from: '/architecture-scenarios/business/b2e',
to: '/architecture-scenarios/b2e'
},
{
from: '/architecture-scenarios/application/mobile-api/api-implementation-nodejs',
to: '/architecture-scenarios/mobile-api/api-implementation-nodejs'
},
{
from: '/architecture-scenarios/application/mobile-api/mobile-implementation-android',
to: '/architecture-scenarios/mobile-api/mobile-implementation-android'
},
{
from: '/architecture-scenarios/application/server-api/api-implementation-nodejs',
to: '/architecture-scenarios/server-api/api-implementation-nodejs'
},
{
from: '/architecture-scenarios/application/server-api/cron-implementation-python',
to: '/architecture-scenarios/server-api/cron-implementation-python'
},
{
from: '/architecture-scenarios/application/spa-api/spa-implementation-angular2',
to: '/architecture-scenarios/spa-api/spa-implementation-angular2'
},
{
from: '/architecture-scenarios/application/spa-api/api-implementation-nodejs',
to: '/architecture-scenarios/spa-api/api-implementation-nodejs'
},
{
from: '/architecture-scenarios/application/web-app-sso/implementation-aspnetcore',
to: '/architecture-scenarios/web-app-sso/implementation-aspnetcore'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/provisioning',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/provisioning'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/provisioning'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/authentication',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/authentication'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/authentication'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/branding',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/branding'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/branding'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/authorization',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/authorization'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/authorization'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/profile-management',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/profile-management'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/profile-management'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/logout',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/logout'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/logout'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/multiple-identity-provider-organizations',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/multiple-identity-provider-organizations'
],
to: '/architecture-scenarios/multiple-orgs/multiple-idp-orgs'
},
/* CONTENTFUL REDIRECTS */
/* Configure */
{
from: ['/configuration-overview','/config'],
to: '/configure'
},
/* Tenants */
{
from: [
'/dashboard/tenant-settings',
'/get-started/dashboard/tenant-settings',
'/best-practices/tenant-settings-best-practices',
'/best-practices/tenant-settings',
'/dashboard/reference/settings-tenant',
'/tutorials/dashboard-tenant-settings',
'/dashboard-account-settings',
'/dashboard/dashboard-tenant-settings',
'/config/tenant-settings'
],
to: '/configure/tenant-settings'
},
{
from: [
'/tokens/manage-signing-keys',
'/tokens/guides/manage-signing-keys',
'/config/tenant-settings/signing-keys'
],
to: '/configure/tenant-settings/signing-keys'
},
{
from: '/config/tenant-settings/signing-keys/rotate-signing-keys',
to: '/configure/tenant-settings/signing-keys/rotate-signing-keys'
},
{
from: '/config/tenant-settings/signing-keys/revoke-signing-keys',
to: '/configure/tenant-settings/signing-keys/revoke-signing-keys'
},
{
from: '/config/tenant-settings/signing-keys/view-signing-certificates',
to: '/configure/tenant-settings/signing-keys/view-signing-certificates'
},
{
from: '/anomaly-detection/suspicious-ip-throttling',
to: '/configure/anomaly-detection/suspicious-ip-throttling'
},
{
from: [
'/get-started/dashboard/configure-device-user-code-settings',
'/dashboard/guides/tenants/configure-device-user-code-settings',
'/config/tenant-settings/configure-device-user-code-settings'
],
to: '/configure/tenant-settings/configure-device-user-code-settings'
},
/* Applications */
{
from: [
'/applications',
'/application',
'/applications/concepts/app-types-auth0',
'/clients',
'/api-auth/tutorials/adoption/oidc-conformant',
'/api-auth/client-types','/clients/client-types',
'/applications/application-types',
'/applications/concepts/client-secret'
],
to: '/configure/applications'
},
{
from: [
'/clients/client-settings',
'/dashboard/reference/settings-application',
'/get-started/dashboard/application-settings',
'/best-practices/application-settings',
'/best-practices/app-settings-best-practices',
'/applications/application-settings'
],
to: '/configure/applications/application-settings'
},
{
from: [
'/applications/dynamic-client-registration',
'/api-auth/dynamic-client-registration',
'/api-auth/dynamic-application-registration'
],
to: '/configure/applications/dynamic-client-registration'
},
{
from: [
'/dashboard/guides/applications/enable-android-app-links',
'/clients/enable-android-app-links',
'/applications/enable-android-app-links',
'/applications/guides/enable-android-app-links-dashboard',
'/applications/enable-android-app-links-support'
],
to: '/configure/applications/enable-android-app-links-support'
},
{
from: [
'/dashboard/guides/applications/enable-universal-links',
'/clients/enable-universal-links',
'/applications/enable-universal-links',
'/applications/guides/enable-universal-links-dashboard',
'/enable-universal-links-support-in-apple-xcode',
'/applications/enable-universal-links-support-in-apple-xcode'
],
to: '/configure/applications/enable-universal-links-support-in-apple-xcode'
},
{
from: [
'/dashboard/guides/applications/enable-sso-app',
'/sso/enable-sso-for-applications'
],
to: '/configure/applications/enable-sso-for-applications'
},
{
from: '/applications/configure-application-metadata',
to: '/configure/applications/configure-application-metadata'
},
{
from: [
'/applications/reference/grant-types-available',
'/applications/reference/grant-types-auth0-mapping',
'/clients/client-grant-types',
'/applications/concepts/application-grant-types',
'/applications/concepts/grant-types-legacy',
'/applications/application-grant-types'
],
to: '/configure/applications/application-grant-types'
},
{
from: [
'/api-auth/config/using-the-auth0-dashboard',
'/api-auth/config/using-the-management-api',
'/api/management/guides/applications/update-grant-types',
'/dashboard/guides/applications/update-grant-types',
'/applications/update-grant-types'
],
to: '/configure/applications/update-grant-types'
},
{
from: [
'/dashboard/guides/applications/rotate-client-secret',
'/api/management/guides/applications/rotate-client-secret',
'/get-started/dashboard/rotate-client-secret',
'/applications/rotate-client-secret'
],
to: '/configure/applications/rotate-client-secret'
},
{
from: [
'/dashboard/guides/applications/update-signing-algorithm',
'/tokens/guides/update-signing-algorithm-application',
'/applications/change-application-signing-algorithms'
],
to: '/configure/applications/change-application-signing-algorithms'
},
{
from: ['/applications/set-up-cors','/dashboard/guides/applications/set-up-cors'],
to: '/configure/applications/set-up-cors'
},
{
from: ['/applications/update-application-connections','/dashboard/guides/applications/update-app-connections'],
to: '/configure/applications/update-application-connections'
},
{
from: ['/applications/concepts/app-types-confidential-public','/applications/confidential-and-public-applications'],
to: '/configure/applications/confidential-public-apps'
},
{
from: [
'/dashboard/guides/applications/view-app-type-confidential-public',
'/applications/view-application-type'
],
to: '/configure/applications/confidential-public-apps/view-application-type'
},
{
from: [
'/applications/first-party-and-third-party-applications',
'/applications/concepts/app-types-first-third-party'
],
to: '/configure/applications/confidential-public-apps/first-party-and-third-party-applications'
},
{
from: ['/applications/view-application-ownership','/api/management/guides/applications/view-ownership'],
to: '/configure/applications/confidential-public-apps/view-application-ownership'
},
{
from: [
'/api/management/guides/applications/update-ownership',
'/api/management/guides/applications/remove-app',
'/applications/update-application-ownership'
],
to: '/configure/applications/confidential-public-apps/update-application-ownership'
},
{
from: [
'/applications/guides/enable-third-party-applications',
'/applications/guides/enable-third-party-apps',
'/applications/enable-third-party-applications'
],
to: '/configure/applications/confidential-public-apps/enable-third-party-applications'
},
{
from: ['/applications/wildcards-for-subdomains','/applications/reference/wildcard-subdomains'],
to: '/configure/applications/wildcards-for-subdomains'
},
{
from: ['/applications/remove-applications','/dashboard/guides/applications/remove-app'],
to: '/configure/applications/remove-applications'
},
{
from: [
'/dev-lifecycle/work-with-auth0-locally',
'/dev-lifecycle/local-testing-and-development',
'/applications/work-with-auth0-locally'
],
to: '/configure/applications/work-with-auth0-locally'
},
{
from: ['/applications/set-up-database-connections','/dashboard/guides/connections/set-up-connections-database'],
to: '/configure/applications/set-up-database-connections'
},
/* APIs */
{
from: [
'/api-auth/references/dashboard/api-settings',
'/dashboard/reference/settings-api',
'/get-started/dashboard/api-settings',
'/config/api-settings'
],
to: '/configure/api-settings'
},
{
from: [
'/dashboard/guides/apis/add-permissions-apis',
'/api/management/guides/apis/update-permissions-apis',
'/scopes/current/guides/define-scopes-using-dashboard',
'/scopes/current/guides/define-api-scope-dashboard',
'/get-started/dashboard/add-api-permissions',
'/config/api-settings/add-api-permissions'
],
to: '/configure/api-settings/add-api-permissions'
},
{
from: [
'/dashboard/guides/apis/delete-permissions-apis',
'/get-started/dashboard/delete-api-permissions',
'/config/api-settings/delete-api-permissions'
],
to: '/configure/api-settings/delete-api-permissions'
},
{
from: [
'/authorization/set-logical-api',
'/authorization/represent-multiple-apis-using-a-single-logical-api',
'/api-auth/tutorials/represent-multiple-apis'
],
to: '/configure/api-settings/set-logical-api'
},
/* Single Sign-On */
{
from: [
'/api-auth/tutorials/adoption/single-sign-on',
'/sso/legacy',
'/sso/legacy/single-page-apps',
'/sso/legacy/regular-web-apps-sso',
'/sso/legacy/single-page-apps-sso',
'/sso/current/single-page-apps-sso',
'/sso/current/single-page-apps',
'/sso/current/sso-auth0',
'/sso/current/introduction',
'/sso/single-sign-on',
'/sso/current',
'/sso/current/setup',
'/sso/current/index_old',
'/sso'
],
to: '/configure/sso'
},
{
from: ['/sso/inbound-single-sign-on','/sso/current/inbound'],
to: '/configure/sso/inbound-single-sign-on'
},
{
from: ['/sso/outbound-single-sign-on','/sso/current/outbound'],
to: '/configure/sso/outbound-single-sign-on'
},
{
from: [
'/single-sign-on/api-endpoints-for-single-sign-on',
'/sso/current/relevant-api-endpoints',
'/sso/api-endpoints-for-single-sign-on'
],
to: '/configure/sso/api-endpoints-for-single-sign-on'
},
/* SAML */
{
from: [
'/saml-apps',
'/protocols/saml/identity-providers',
'/samlp-providers',
'/protocols/saml/samlp-providers',
'/protocols/saml',
'/protocols/saml-protocol',
'/configure/saml-protocol',
'/protocols/saml-configuration-options',
'/protocols/saml/saml-apps',
'/protocols/saml/saml-configuration/supported-options-and-bindings',
'/protocols/saml/saml-configuration/design-considerations',
'/protocols/saml/saml-configuration-options',
'/saml-configuration'
],
to: '/configure/saml-configuration'
},
{
from: [
'/protocols/saml/saml-configuration',
'/protocols/saml/saml-configuration/special-configuration-scenarios',
'/protocols/saml-protocol/saml-configuration-options/special-saml-configuration-scenarios'
],
to: '/configure/saml-configuration/saml-sso-integrations'
},
{
from: [
'/protocols/saml/idp-initiated-sso',
'/protocols/saml-configuration-options/identity-provider-initiated-single-sign-on',
'/protocols/saml/saml-configuration/special-configuration-scenarios/idp-initiated-sso',
'/protocols/saml-protocol/saml-configuration-options/identity-provider-initiated-single-sign-on'
],
to: '/configure/saml-configuration/saml-sso-integrations/identity-provider-initiated-single-sign-on'
},
{
from: [
'/protocols/saml-configuration-options/sign-and-encrypt-saml-requests',
'/protocols/saml/saml-configuration/special-configuration-scenarios/signing-and-encrypting-saml-requests',
'/protocols/saml-protocol/saml-configuration-options/sign-and-encrypt-saml-requests'
],
to: '/configure/saml-configuration/saml-sso-integrations/sign-and-encrypt-saml-requests'
},
{
from: '/protocols/saml-protocol/saml-configuration-options/work-with-certificates-and-keys-as-strings',
to: '/configure/saml-configuration/saml-sso-integrations/work-with-certificates-and-keys-as-strings'
},
{
from: [
'/protocols/saml/adfs',
'/protocols/saml-protocol/saml-configuration-options/configure-adfs-saml-connections'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-adfs-saml-connections'
},
{
from: [
'/protocols/saml/identity-providers/okta',
'/okta',
'/saml/identity-providers/okta',
'/protocols/saml-configuration-options/configure-okta-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-okta-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-okta-as-saml-identity-provider'
},
{
from: [
'/onelogin',
'/saml/identity-providers/onelogin',
'/protocols/saml/identity-providers/onelogin',
'/protocols/saml-configuration-options/configure-onelogin-as-saml-identity-provider',
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-onelogin-as-saml-identity-provider'
},
{
from: [
'/ping7',
'/saml/identity-providers/ping7',
'/protocols/saml/identity-providers/ping7',
'/protocols/saml-configuration-options/configure-pingfederate-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration/configure-pingfederate-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-pingfederate-as-saml-identity-provider'
},
{
from: [
'/saml/identity-providers/salesforce',
'/protocols/saml/identity-providers/salesforce',
'/protocols/saml-configuration-options/configure-salesforce-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-salesforce-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-salesforce-as-saml-identity-provider'
},
{
from: [
'/siteminder',
'/saml/identity-providers/siteminder',
'/protocols/saml/identity-providers/siteminder',
'/protocols/saml-configuration-options/configure-siteminder-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-siteminder-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-siteminder-as-saml-identity-provider'
},
{
from: [
'/ssocircle',
'/saml/identity-providers/ssocircle',
'/protocols/saml/identity-providers/ssocircle',
'/protocols/saml-configuration-options/configure-ssocircle-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-ssocircle-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-ssocircle-as-saml-identity-provider'
},
{
from: [
'/saml2webapp-tutorial',
'/protocols/saml/saml2webapp-tutorial',
'/protocols/saml-protocol/saml-configuration-options/enable-saml2-web-app-addon'
],
to: '/configure/saml-configuration/saml-sso-integrations/enable-saml2-web-app-addon'
},
{
from: [
'/configure/saml-configuration-options/configure-saml2-web-app-addon-for-aws',
'/dashboard/guides/applications/set-up-addon-saml2-aws',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-aws'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-aws'
},
{
from: [
'/protocols/saml/saml-apps/atlassian',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-atlassian'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-atlassian'
},
{
from: [
'/saml-apps/cisco-webex',
'/protocols/saml/saml-apps/cisco-webex',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-cisco-webex',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-cisco-webex'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-cisco-webex'
},
{
from: [
'/saml-apps/datadog',
'/protocols/saml/saml-apps/datadog',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-datadog',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-datadog'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-datadog'
},
{
from: [
'/protocols/saml/saml-apps/egencia',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-egencia'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-egencia'
},
{
from: [
'/saml-apps/freshdesk',
'/protocols/saml/saml-apps/freshdesk',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-freshdesk',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-freshdesk'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-freshdesk'
},
{
from: [
'/protocols/saml/saml-apps/github-cloud',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-github-enterprise-cloud'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-github-enterprise-cloud'
},
{
from: [
'/integrations/using-auth0-as-an-identity-provider-with-github-enterprise',
'/protocols/saml/saml-apps/github-server',
'/tutorials/using-auth0-as-an-identity-provider-with-github-enterprise',
'/scenarios/github',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-github-enterprise-server'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-github-enterprise-server'
},
{
from: [
'/protocols/saml/saml-apps/google-apps',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-idp-for-google-g-suite'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-idp-for-google-g-suite'
},
{
from: [
'/protocols/saml/saml-apps/heroku','/saml-apps/heroku-sso',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-heroku'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-heroku'
},
{
from: [
'/protocols/saml/saml-apps/hosted-graphite',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-hosted-graphite'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-hosted-graphite'
},
{
from: [
'/protocols/saml/saml-apps/litmos',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-litmos',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-litmos'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-litmos'
},
{
from: [
'/protocols/saml/saml-idp-eloqua',
'/protocols/saml/saml-apps/eloqua',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-addon-eloqua'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-addon-eloqua'
},
{
from: [
'/protocols/saml/saml-apps/pluralsight',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-pluralsight'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-pluralsight'
},
{
from: [
'/protocols/saml/saml-apps/sprout-video',
'/saml-apps/sprout-video',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-sprout-video',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-sprout-video'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-sprout-video'
},
{
from: [
'/protocols/saml/saml-apps/tableau-online',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-tableau-online'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-tableau-online'
},
{
from: [
'/protocols/saml/saml-apps/tableau-server',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-tableau-server'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-tableau-server'
},
{
from: [
'/protocols/saml/saml-apps/workday',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-workday'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-workday'
},
{
from: [
'/protocols/saml/saml-apps/workpath',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-workpath'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-workpath'
},
{
from: [
'/protocols/saml-configuration-options/configure-auth0-saml-service-provider',
'/protocols/saml/saml-sp-generic',
'/saml-sp-generic',
'/protocols/saml/saml-configuration/auth0-as-service-provider',
'/protocols/saml-protocol/configure-auth0-saml-service-provider'
],
to: '/configure/saml-configuration/configure-auth0-saml-service-provider'
},
{
from: [
'/protocols/saml-configuration-options/configure-auth0-as-saml-identity-provider',
'/saml-idp-generic','/protocols/saml/saml-idp-generic',
'/protocols/saml/saml-configuration/auth0-as-identity-provider',
'/protocols/saml-protocol/configure-auth0-as-saml-identity-provider'
],
to: '/configure/saml-configuration/configure-auth0-as-saml-identity-provider'
},
{
from: [
'/protocols/saml-configuration-options/saml-identity-provider-configuration-settings',
'/samlp',
'/protocols/saml/samlp',
'/protocols/saml-protocol/saml-identity-provider-configuration-settings'
],
to: '/configure/saml-configuration/saml-identity-provider-configuration-settings'
},
{
from: [
'/protocols/saml-configuration-options/customize-saml-assertions',
'/protocols/saml/saml-configuration/saml-assertions',
'/protocols/saml-protocol/customize-saml-assertions'
],
to: '/configure/saml-configuration/customize-saml-assertions'
},
{
from: [
'/protocols/saml-configuration-options/test-saml-sso-with-auth0-as-service-and-identity-provider',
'/protocols/saml/samlsso-auth0-to-auth0',
'/samlsso-auth0-to-auth0',
'/protocols/saml-configuration-options/configure-auth0-as-service-and-identity-provider',
'/protocols/saml/saml-configuration/auth0-as-identity-and-service-provider',
'/protocols/saml-protocol/configure-auth0-as-service-and-identity-provider'
],
to: '/configure/saml-configuration/configure-auth0-as-service-and-identity-provider'
},
{
from: [
'/protocols/saml-configuration-options/deprovision-users-in-saml-integrations',
'/protocols/saml/saml-configuration/deprovision-users',
'/protocols/saml-protocol/deprovision-users-in-saml-integrations'
],
to: '/configure/saml-configuration/deprovision-users-in-saml-integrations'
},
/* Signing Keys */
{
from: [
'/authorization/set-logical-api',
'/authorization/represent-multiple-apis-using-a-single-logical-api',
'/api-auth/tutorials/represent-multiple-apis'
],
to: '/configure/api-settings/set-logical-api'
},
/* Single Sign-On */
{
from: [
'/api-auth/tutorials/adoption/single-sign-on',
'/sso/legacy',
'/sso/legacy/single-page-apps',
'/sso/legacy/regular-web-apps-sso',
'/sso/legacy/single-page-apps-sso',
'/sso/current/single-page-apps-sso',
'/sso/current/single-page-apps',
'/sso/current/sso-auth0',
'/sso/current/introduction',
'/sso/single-sign-on',
'/sso/current',
'/sso/current/setup',
'/sso/current/index_old',
'/sso'
],
to: '/configure/sso'
},
{
from: ['/sso/inbound-single-sign-on','/sso/current/inbound'],
to: '/configure/sso/inbound-single-sign-on'
},
{
from: ['/sso/outbound-single-sign-on','/sso/current/outbound'],
to: '/configure/sso/outbound-single-sign-on'
},
{
from: [
'/single-sign-on/api-endpoints-for-single-sign-on',
'/sso/current/relevant-api-endpoints',
'/sso/api-endpoints-for-single-sign-on'
],
to: '/configure/sso/api-endpoints-for-single-sign-on'
},
/* SAML */
{
from: [
'/saml-apps',
'/protocols/saml/identity-providers',
'/samlp-providers',
'/protocols/saml/samlp-providers',
'/protocols/saml',
'/protocols/saml-protocol',
'/configure/saml-protocol',
'/protocols/saml-configuration-options',
'/protocols/saml/saml-apps',
'/protocols/saml/saml-configuration/supported-options-and-bindings',
'/protocols/saml/saml-configuration/design-considerations',
'/protocols/saml/saml-configuration-options',
'/saml-configuration'
],
to: '/configure/saml-configuration'
},
{
from: [
'/protocols/saml/saml-configuration',
'/protocols/saml/saml-configuration/special-configuration-scenarios',
'/protocols/saml-protocol/saml-configuration-options/special-saml-configuration-scenarios'
],
to: '/configure/saml-configuration/saml-sso-integrations'
},
{
from: [
'/protocols/saml/idp-initiated-sso',
'/protocols/saml-configuration-options/identity-provider-initiated-single-sign-on',
'/protocols/saml/saml-configuration/special-configuration-scenarios/idp-initiated-sso',
'/protocols/saml-protocol/saml-configuration-options/identity-provider-initiated-single-sign-on'
],
to: '/configure/saml-configuration/saml-sso-integrations/identity-provider-initiated-single-sign-on'
},
{
from: [
'/protocols/saml-configuration-options/sign-and-encrypt-saml-requests',
'/protocols/saml/saml-configuration/special-configuration-scenarios/signing-and-encrypting-saml-requests',
'/protocols/saml-protocol/saml-configuration-options/sign-and-encrypt-saml-requests'
],
to: '/configure/saml-configuration/saml-sso-integrations/sign-and-encrypt-saml-requests'
},
{
from: '/protocols/saml-protocol/saml-configuration-options/work-with-certificates-and-keys-as-strings',
to: '/configure/saml-configuration/saml-sso-integrations/work-with-certificates-and-keys-as-strings'
},
{
from: [
'/protocols/saml/adfs',
'/protocols/saml-protocol/saml-configuration-options/configure-adfs-saml-connections'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-adfs-saml-connections'
},
{
from: [
'/protocols/saml/identity-providers/okta',
'/okta',
'/saml/identity-providers/okta',
'/protocols/saml-configuration-options/configure-okta-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-okta-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-okta-as-saml-identity-provider'
},
{
from: [
'/onelogin',
'/saml/identity-providers/onelogin',
'/protocols/saml/identity-providers/onelogin',
'/protocols/saml-configuration-options/configure-onelogin-as-saml-identity-provider',
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-onelogin-as-saml-identity-provider'
},
{
from: [
'/ping7',
'/saml/identity-providers/ping7',
'/protocols/saml/identity-providers/ping7',
'/protocols/saml-configuration-options/configure-pingfederate-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration/configure-pingfederate-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-pingfederate-as-saml-identity-provider'
},
{
from: [
'/saml/identity-providers/salesforce',
'/protocols/saml/identity-providers/salesforce',
'/protocols/saml-configuration-options/configure-salesforce-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-salesforce-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-salesforce-as-saml-identity-provider'
},
{
from: [
'/siteminder',
'/saml/identity-providers/siteminder',
'/protocols/saml/identity-providers/siteminder',
'/protocols/saml-configuration-options/configure-siteminder-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-siteminder-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-siteminder-as-saml-identity-provider'
},
{
from: [
'/ssocircle',
'/saml/identity-providers/ssocircle',
'/protocols/saml/identity-providers/ssocircle',
'/protocols/saml-configuration-options/configure-ssocircle-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-ssocircle-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-ssocircle-as-saml-identity-provider'
},
{
from: [
'/saml2webapp-tutorial',
'/protocols/saml/saml2webapp-tutorial',
'/protocols/saml-protocol/saml-configuration-options/enable-saml2-web-app-addon'
],
to: '/configure/saml-configuration/saml-sso-integrations/enable-saml2-web-app-addon'
},
{
from: [
'/configure/saml-configuration-options/configure-saml2-web-app-addon-for-aws',
'/dashboard/guides/applications/set-up-addon-saml2-aws',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-aws'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-aws'
},
{
from: [
'/protocols/saml/saml-apps/atlassian',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-atlassian'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-atlassian'
},
{
from: [
'/saml-apps/cisco-webex',
'/protocols/saml/saml-apps/cisco-webex',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-cisco-webex',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-cisco-webex'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-cisco-webex'
},
{
from: [
'/saml-apps/datadog',
'/protocols/saml/saml-apps/datadog',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-datadog',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-datadog'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-datadog'
},
{
from: [
'/protocols/saml/saml-apps/egencia',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-egencia'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-egencia'
},
{
from: [
'/saml-apps/freshdesk',
'/protocols/saml/saml-apps/freshdesk',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-freshdesk',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-freshdesk'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-freshdesk'
},
{
from: [
'/protocols/saml/saml-apps/github-cloud',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-github-enterprise-cloud'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-github-enterprise-cloud'
},
{
from: [
'/integrations/using-auth0-as-an-identity-provider-with-github-enterprise',
'/protocols/saml/saml-apps/github-server',
'/tutorials/using-auth0-as-an-identity-provider-with-github-enterprise',
'/scenarios/github',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-github-enterprise-server'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-github-enterprise-server'
},
{
from: [
'/protocols/saml/saml-apps/google-apps',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-idp-for-google-g-suite'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-idp-for-google-g-suite'
},
{
from: [
'/protocols/saml/saml-apps/heroku','/saml-apps/heroku-sso',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-heroku'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-heroku'
},
{
from: [
'/protocols/saml/saml-apps/hosted-graphite',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-hosted-graphite'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-hosted-graphite'
},
{
from: [
'/protocols/saml/saml-apps/litmos',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-litmos',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-litmos'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-litmos'
},
{
from: [
'/protocols/saml/saml-idp-eloqua',
'/protocols/saml/saml-apps/eloqua',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-addon-eloqua'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-addon-eloqua'
},
{
from: [
'/protocols/saml/saml-apps/pluralsight',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-pluralsight'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-pluralsight'
},
{
from: [
'/protocols/saml/saml-apps/sprout-video',
'/saml-apps/sprout-video',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-sprout-video',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-sprout-video'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-sprout-video'
},
{
from: [
'/protocols/saml/saml-apps/tableau-online',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-tableau-online'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-tableau-online'
},
{
from: [
'/protocols/saml/saml-apps/tableau-server',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-tableau-server'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-tableau-server'
},
{
from: [
'/protocols/saml/saml-apps/workday',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-workday'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-workday'
},
{
from: [
'/protocols/saml/saml-apps/workpath',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-workpath'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-workpath'
},
{
from: [
'/protocols/saml-configuration-options/configure-auth0-saml-service-provider',
'/protocols/saml/saml-sp-generic',
'/saml-sp-generic',
'/protocols/saml/saml-configuration/auth0-as-service-provider',
'/protocols/saml-protocol/configure-auth0-saml-service-provider'
],
to: '/configure/saml-configuration/configure-auth0-saml-service-provider'
},
{
from: [
'/protocols/saml-configuration-options/configure-auth0-as-saml-identity-provider',
'/saml-idp-generic','/protocols/saml/saml-idp-generic',
'/protocols/saml/saml-configuration/auth0-as-identity-provider',
'/protocols/saml-protocol/configure-auth0-as-saml-identity-provider'
],
to: '/configure/saml-configuration/configure-auth0-as-saml-identity-provider'
},
{
from: [
'/protocols/saml-configuration-options/saml-identity-provider-configuration-settings',
'/samlp',
'/protocols/saml/samlp',
'/protocols/saml-protocol/saml-identity-provider-configuration-settings'
],
to: '/configure/saml-configuration/saml-identity-provider-configuration-settings'
},
{
from: [
'/protocols/saml-configuration-options/customize-saml-assertions',
'/protocols/saml/saml-configuration/saml-assertions',
'/protocols/saml-protocol/customize-saml-assertions'
],
to: '/configure/saml-configuration/customize-saml-assertions'
},
{
from: [
'/protocols/saml-configuration-options/test-saml-sso-with-auth0-as-service-and-identity-provider',
'/protocols/saml/samlsso-auth0-to-auth0',
'/samlsso-auth0-to-auth0',
'/protocols/saml-configuration-options/configure-auth0-as-service-and-identity-provider',
'/protocols/saml/saml-configuration/auth0-as-identity-and-service-provider',
'/protocols/saml-protocol/configure-auth0-as-service-and-identity-provider'
],
to: '/configure/saml-configuration/configure-auth0-as-service-and-identity-provider'
},
{
from: [
'/protocols/saml-configuration-options/deprovision-users-in-saml-integrations',
'/protocols/saml/saml-configuration/deprovision-users',
'/protocols/saml-protocol/deprovision-users-in-saml-integrations'
],
to: '/configure/saml-configuration/deprovision-users-in-saml-integrations'
},
/* Signing Keys */
{
from: [
'/actions/build-actions-flows',
'/actions/edit-actions',
'/actions/troubleshoot-actions'
],
to: '/actions/write-your-first-action'
},
{
from: [
'/actions/actions-context-object',
'/actions/actions-event-object',
'/actions/blueprints'
],
to: '/actions/triggers'
},
{
from: [
'/actions/manage-action-versions'
],
to: '/actions/manage-versions'
},
/* Anomaly Detection */
{
from: [
'/anomaly-',
'/anomaly',
'/anomaly-detection/references/anomaly-detection-faqs',
'/anomaly-detection/references/anomaly-detection-restrictions-limitations',
'/anomaly-detection/guides/set-anomaly-detection-preferences',
'/anomaly-detection/set-anomaly-detection-preferences',
'/attack-protection/set-attack-protection-preferences',
'/anomaly-detection',
'/attack-protection'
],
to: '/configure/attack-protection'
},
{
from: [
'/anomaly-detection/references/breached-password-detection-triggers-actions',
'/anomaly-detection/concepts/breached-passwords',
'/anomaly-detection/breached-passwords',
'/anomaly-detection/breached-password-security',
'/attack-protection/breached-password-detection'
],
to: '/configure/attack-protection/breached-password-detection'
},
{
from: [
'/anomaly-detection/bot-protection',
'/anomaly-detection/guides/prevent-credential-stuffing-attacks',
'/anomaly-detection/bot-and-credential-stuffing-protection',
'/anomaly-detection/bot-detection',
'/attack-protection/bot-detection'
],
to: '/configure/attack-protection/bot-detection'
},
{
from: '/anomaly-detection/bot-detection/configure-recaptcha-enterprise',
to: '/configure/anomaly-detection/bot-detection/configure-recaptcha-enterprise'
},
{
from: '/anomaly-detection/bot-detection/bot-detection-custom-login-pages',
to: '/configure/anomaly-detection/bot-detection/bot-detection-custom-login-pages'
},
{
from: '/anomaly-detection/bot-detection/bot-detection-native-apps',
to: '/configure/anomaly-detection/bot-detection/bot-detection-native-apps'
},
{
from: [
'/anomaly-detection/references/brute-force-protection-triggers-actions',
'/anomaly-detection/guides/enable-disable-brute-force-protection',
'/anomaly-detection/concepts/brute-force-protection',
'/anomaly-detection/enable-and-disable-brute-force-protection',
'/anomaly-detection/brute-force-protection',
'/attack-protection/brute-force-protection'
],
to: '/configure/attack-protection/brute-force-protection'
},
{
from: '/anomaly-detection/suspicious-ip-throttling',
to: '/configure/anomaly-detection/suspicious-ip-throttling'
},
{
from: [
'/anomaly-detection/guides/use-tenant-data-for-anomaly-detection',
'/anomaly-detection/view-anomaly-detection-events',
'/attack-protection/view-attack-protection-events'
],
to: '/configure/attack-protection/view-attack-protection-events'
},
/* API */
{
from: ['/auth-api', '/api/authentication/reference'],
to: '/api/authentication'
},
{
from: ['/apiv2', '/api/v2','/api/management'],
to: '/api/management/v2'
},
{
from: ['/auth0-apis', '/api/info'],
to: '/api'
},
{
from: ['/api/management/v1','/api-reference','/api/v1/reference','/api/management/v1/reference'],
to: '/api/management-api-v1-deprecated'
},
{
from: ['/api/management/v2/changes','/apiv2Changes', '/api/v2/changes'],
to: '/api/management-api-changes-v1-to-v2'
},
{
from: ['/api/use-auth0-apis-with-postman-collections','/api/postman'],
to: '/api'
},
/* Authorization */
{
from: ['/apis'],
to: '/authorization/apis'
},
{
from: [
'/flows/concepts/auth-code',
'/flows/concepts/regular-web-app-login-flow',
'/api-auth/grant/authorization-code',
'/api-auth/tutorials/adoption/authorization-code',
'/api-auth/adoption/authorization-code',
'/flows/authorization-code-flow'
],
to: '/authorization/authorization-flows/authorization-code-flow'
},
{
from: [
'/flows/concepts/auth-code-pkce',
'/api-auth/grant/authorization-code-pkce',
'/flows/concepts/mobile-login-flow',
'/flows/concepts/single-page-login-flow',
'/flows/authorization-code-flow-with-proof-key-for-code-exchange-pkce'
],
to: '/authorization/authorization-flows/authorization-code-flow-with-proof-key-for-code-exchange-pkce'
},
{
from: [
'/flows/guides/implicit/call-api-implicit',
'/flows/guides/implicit/includes/sample-use-cases-call-api',
'/flows/guides/implicit/includes/call-api',
'/flows/guides/implicit/includes/authorize-user-call-api',
'/flows/guides/single-page-login-flow/call-api-using-single-page-login-flow',
'/api-auth/grant/implicit',
'/api-auth/tutorials/adoption/implicit',
'/api-auth/tutorials/implicit-grant',
'/protocols/oauth2/oauth-implicit-protocol',
'/flows/concepts/implicit',
'/flows/implicit-flow-with-form-post'
],
to: '/authorization/authorization-flows/implicit-flow-with-form-post'
},
{
from: ['/flows/hybrid-flow','/api-auth/grant/hybrid'],
to: '/authorization/authorization-flows/hybrid-flow'
},
{
from: [
'/flows/concepts/client-credentials',
'/flows/concepts/m2m-flow',
'/api-auth/grant/client-credentials',
'/api-auth/tutorials/adoption/client-credentials',
'/flows/client-credentials-flow'
],
to: '/authorization/authorization-flows/client-credentials-flow'
},
{
from: [
'/flows/concepts/device-auth',
'/flows/guides/device-auth/call-api-device-auth',
'/flows/device-authorization-flow'
],
to: '/authorization/authorization-flows/device-authorization-flow'
},
{
from: [
'/api-auth/grant/password',
'/api-auth/tutorials/adoption/password',
'/flows/resource-owner-password-flow'
],
to: '/authorization/authorization-flows/resource-owner-password-flow'
},
{
from: [
'/authorization/revoke-access-to-apis-using-blacklists-or-application-grants',
'/api-auth/blacklists-vs-grants','/blacklists-vs-application-grants'
],
to: '/authorization/revoke-api-access'
},
{
from: [
'/authorization/rbac/roles/view-users-assigned-to-roles',
'/api/management/guides/roles/view-role-users',
'/dashboard/guides/roles/view-role-users'
],
to: '/authorization/auth-core-features/roles/view-users-assigned-to-roles'
},
{
from: [
'/authorization/rbac/roles/delete-roles',
'/dashboard/guides/roles/delete-roles',
'/api/management/guides/roles/delete-roles'
],
to: '/authorization/auth-core-features/roles/delete-roles'
},
{
from: [
'/authorization/rbac/roles/edit-role-definitions',
'/authorization/rbac/roles/edit-role-definitions',
'/dashboard/guides/roles/edit-role-definitions',
'/api/management/guides/roles/edit-role-definitions',
'/authorization/guides/api/edit-role-definitions'
],
to: '/authorization/auth-core-features/roles/edit-role-definitions'
},
{
from: [
'/authorization/rbac/roles/remove-permissions-from-roles',
'/dashboard/guides/roles/remove-role-permissions',
'/api/management/guides/roles/remove-role-permissions'
],
to: '/authorization/auth-core-features/roles/remove-permissions-from-roles'
},
{
from: [
'/authorization/rbac/roles/view-role-permissions',
'/dashboard/guides/roles/view-role-permissions',
'/api/management/guides/roles/view-role-permissions'
],
to: '/authorization/auth-core-features/roles/view-role-permissions'
},
{
from: [
'/api/management/guides/apis/enable-rbac',
'/dashboard/guides/apis/enable-rbac',
'/authorization/guides/dashboard/enable-rbac',
'/authorization/rbac/enable-role-based-access-control-for-apis'
],
to: '/authorization/auth-core-features/enable-role-based-access-control-for-apis'
},
{
from: [
'/authorization/rbac/roles/add-permissions-to-roles',
'/dashboard/guides/roles/add-permissions-roles',
'/api/management/guides/roles/add-permissions-roles'
],
to: '/authorization/auth-core-features/roles/add-permissions-to-roles'
},
{
from: [
'/authorization/rbac/roles/create-roles',
'/dashboard/guides/roles/create-roles',
'/api/management/guides/roles/create-roles'
],
to: '/authorization/auth-core-features/roles/create-roles'
},
{
from: ['/authorization/reference/rbac-limits','/authorization/rbac/authorization-core-rbac-limits'],
to: '/policies/entity-limit-policy'
},
{
from: ['/authorization/authentication-and-authorization', '/authorization/concepts/authz-and-authn','/application-auth/current','/application-auth/legacy','/application-auth'],
to: '/get-started/authentication-and-authorization'
},
{
from: ['/authorization/concepts/authz-rules'],
to: '/authorization/rules-for-authorization-policies'
},
{
from: ['/authorization/concepts/core-vs-extension'],
to: '/authorization/authorization-core-vs-authorization-extension'
},
{
from: ['/authorization/concepts/policies'],
to: '/authorization/authorization-policies'
},
{
from: ['/authorization/concepts/rbac'],
to: '/authorization/rbac'
},
{
from: ['/authorization/concepts/sample-use-cases-rbac'],
to: '/authorization/sample-use-cases-role-based-access-control'
},
{
from: ['/authorization/how-to-use-auth0s-core-authorization-feature-set','/authorization/guides/how-to'],
to: '/authorization/auth-core-features'
},
{
from: ['/authorization/guides/manage-permissions'],
to: '/authorization/manage-permissions'
},
{
from: ['/authorization/rbac/roles','/authorization/guides/manage-roles'],
to: '/authorization/auth-core-features/roles'
},
{
from: ['/api-auth/apis','/overview/apis'],
to: '/authorization/apis'
},
{
from: ['/api-auth','/api-auth/tutorials','/api/tutorials'],
to: '/authorization'
},
{
from: ['/api-auth/restrict-access-api','/api-auth/restrict-requests-for-scopes','/authorization/concepts/sample-use-cases-rules','/authorization/restrict-access-api'],
to: '/authorization/sample-use-cases-rules-with-authorization'
},
{
from: ['/api-auth/token-renewal-in-safari'],
to: '/authorization/renew-tokens-when-using-safari'
},
{
from: ['/api-auth/user-consent'],
to: '/authorization/user-consent-and-third-party-applications'
},
{
from: ['/api-auth/which-oauth-flow-to-use', '/api-auth/faq', '/authorization/authentication-and-authorization-api-faq'],
to: '/authorization/which-oauth-2-0-flow-should-i-use'
},
{
from: ['/api-auth/tutorials/nonce'],
to: '/authorization/mitigate-replay-attacks-when-using-the-implicit-flow'
},
{
from: ['/api-auth/tutorials/using-resource-owner-password-from-server-side','/authorization/avoid-common-issues-with-resource-owner-password-flow-and-anomaly-detection'],
to: '/authorization/avoid-common-issues-with-resource-owner-password-flow-and-attack-protection'
},
{
from: ['/api-auth/tutorials/client-credentials/customize-with-hooks','/api-auth/grant/using-rules'],
to: '/authorization/customize-tokens-using-hooks-with-client-credentials-flow'
},
{
from: ['/authorization/rbac-users','/authorization/guides/manage-users'],
to: '/authorization/auth-core-features/rbac-users'
},
/* Best Practices */
{
from: [
'/best-practices/custom-db-connections',
'/best-practices/custom-db-connections-scripts',
'/best-practices/custom-database-connection-and-action-script-best-practices'
],
to: '/best-practices/custom-database-connections-scripts'
},
{
from: [
'/best-practices/custom-db-connections/anatomy',
'/best-practices/custom-db-connections/size',
'/best-practices/custom-database-connection-and-action-script-best-practices/custom-db-connection-anatomy-best-practices'
],
to: '/best-practices/custom-database-connections-scripts/anatomy'
},
{
from: [
'/best-practices/custom-db-connections/environment',
'/best-practices/custom-database-connection-and-action-script-best-practices/custom-db-action-script-environment-best-practices'
],
to: '/best-practices/custom-database-connections-scripts/environment'
},
{
from: [
'/best-practices/custom-db-connections/execution',
'/best-practices/custom-database-connection-and-action-script-best-practices/custom-database-action-script-execution-best-practices'
],
to: '/best-practices/custom-database-connections-scripts/execution'
},
{
from: [
'/best-practices/custom-db-connections/security',
'/best-practices/custom-database-connection-and-action-script-best-practices/custom-db-connection-security-best-practices'
],
to: '/best-practices/custom-database-connections-scripts/connection-security'
},
{
from: ['/best-practices/connection-settings'],
to: '/best-practices/connection-settings-best-practices'
},
{
from: ['/best-practices/debugging'],
to: '/best-practices/debugging-best-practices'
},
{
from: ['/best-practices/deployment'],
to: '/best-practices/deployment-best-practices'
},
{
from: ['/best-practices/error-handling'],
to: '/best-practices/error-handling-best-practices'
},
{
from: ['/best-practices/operations'],
to: '/best-practices/general-usage-and-operations-best-practices'
},
{
from: ['/best-practices/performance'],
to: '/best-practices/performance-best-practices'
},
{
from: ['/best-practices/rules'],
to: '/best-practices/rules-best-practices'
},
{
from: ['/best-practices/search-best-practices','/users/search/best-practices'],
to: '/best-practices/user-search-best-practices'
},
{
from: ['/best-practices/testing'],
to: '/best-practices/rules-best-practices/rules-testing-best-practices'
},
{
from: ['/tokens/concepts/token-best-practices','/design/web-apps-vs-web-apis-cookies-vs-tokens'],
to: '/best-practices/token-best-practices'
},
{
from: ['/design/using-auth0-with-multi-tenant-apps','/applications/concepts/multiple-tenants','/tutorials/using-auth0-with-multi-tenant-apps','/saas-apps'],
to: '/best-practices/multi-tenant-apps-best-practices'
},
/* Brand and Customize */
{
from: ['/branding-customization'],
to: '/brand-and-customize'
},
{
from: ['/universal-login/new-experience/universal-login-page-templates','/universal-login/page-templates'],
to: '/brand-and-customize/universal-login-page-templates'
},
{
from: [
'/universal-login/classic-experience/customization-classic',
'/universal-login/customization-classic',
'/universal-login/advanced-customization'
],
to: '/brand-and-customize/customization-classic'
},
{
from: [
'/universal-login/version-control-universal-login-pages',
'/universal-login/version-control',
'/hosted-pages/version-control'
],
to: '/brand-and-customize/version-control-universal-login-pages'
},
/* Custom Domains */
{
from: '/custom-domains',
to: '/brand-and-customize/custom-domains'
},
{
from: ['/custom-domains/configure-custom-domains-with-auth0-managed-certificates','/custom-domains/auth0-managed-certificates'],
to: '/brand-and-customize/custom-domains/auth0-managed-certificates'
},
{
from: ['/custom-domains/self-managed-certificates','/custom-domains/configure-custom-domains-with-self-managed-certificates'],
to: '/brand-and-customize/custom-domains/self-managed-certificates'
},
{
from: '/custom-domains/tls-ssl',
to: '/brand-and-customize/custom-domains/self-managed-certificates/tls-ssl'
},
{
from: '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-gcp-as-reverse-proxy',
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-gcp-as-reverse-proxy'
},
{
from: [
'/custom-domains/set-up-cloudfront',
'/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-aws-cloudfront-for-use-as-reverse-proxy'
],
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-aws-cloudfront-for-use-as-reverse-proxy'
},
{
from: [
'/custom-domains/set-up-cloudflare',
'/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-cloudflare-for-use-as-reverse-proxy'
],
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-cloudflare-for-use-as-reverse-proxy'
},
{
from: [
'/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-azure-cdn-for-use-as-reverse-proxy',
'/custom-domains/set-up-azure-cdn'
],
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-azure-cdn-for-use-as-reverse-proxy'
},
{
from: '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-akamai-for-use-as-reverse-proxy',
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-akamai-for-use-as-reverse-proxy'
},
{
from: ['/custom-domains/configure-features-to-use-custom-domains','/custom-domains/additional-configuration'],
to: '/brand-and-customize/custom-domains/configure-features-to-use-custom-domains'
},
/* Email */
{
from: ['/email','/auth0-email-services'],
to: '/brand-and-customize/email'
},
{
from: [
'/email/custom',
'/auth0-email-services/manage-email-flow',
'/email/manage-email-flow'
],
to: '/brand-and-customize/email/manage-email-flow'
},
{
from: [
'/email/templates',
'/auth0-email-services/customize-email-templates',
'/email/spa-redirect',
'/auth0-email-services/spa-redirect',
'/email/customize-email-templates'
],
to: '/brand-and-customize/email/customize-email-templates'
},
{
from: [
'/email/customize-email-templates/email-template-descriptions',
'/auth0-email-services/email-template-descriptions'
],
to: '/brand-and-customize/email/email-template-descriptions'
},
{
from: [
'/anomaly-detection/guides/customize-blocked-account-emails',
'/anomaly-detection/customize-blocked-account-emails',
'/attack-protection/customize-blocked-account-emails'
],
to: '/brand-and-customize/email/customize-blocked-account-emails'
},
{
from: [
'/email/liquid-syntax',
'/auth0-email-services/customize-email-templates/use-liquid-syntax-in-email-templates',
'/email/customize-email-templates/use-liquid-syntax-in-email-templates'
],
to: '/brand-and-customize/email/use-liquid-syntax-in-email-templates'
},
{
from: [
'/design/creating-invite-only-applications',
'/invite-only',
'/tutorials/creating-invite-only-applications',
'/auth0-email-services/send-email-invitations-for-application-signup',
'/email/send-email-invitations-for-application-signup'
],
to: '/brand-and-customize/email/send-email-invitations-for-application-signup'
},
{
from: '/email/send-email-invitations-for-application-signup',
to: '/brand-and-customize/email/send-email-invitations-for-application-signup'
},
{
from: [
'/auth0-email-services/configure-external-smtp-email-providers',
'/email/providers',
'/email/configure-external-smtp-email-providers'
],
to: '/brand-and-customize/email/smtp-email-providers'
},
{
from: '/email/configure-external-smtp-email-providers/configure-amazon-ses-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-amazon-ses-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-mandrill-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-mandrill-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-sendgrid-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-sendgrid-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-sparkpost-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-sparkpost-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-mailgun-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-mailgun-as-external-smtp-email-provider'
},
{
from: [
'/auth0-email-services/configure-external-smtp-email-providers/configure-custom-external-smtp-email-provider',
'/email/configure-custom-external-smtp-email-provider'
],
to: '/brand-and-customize/email/smtp-email-providers/configure-custom-external-smtp-email-provider'
},
{
from: [
'/email/testing',
'/auth0-email-services/configure-external-smtp-email-providers/configure-test-smtp-email-servers',
'/email/configure-test-smtp-email-servers'
],
to: '/brand-and-customize/email/configure-test-smtp-email-servers'
},
{
from: [
'/universal-login/new-experience/text-customization-new-universal-login',
'/universal-login/text-customization'
],
to: '/brand-and-customize/text-customization-new-universal-login'
},
{
from: ['/scopes/customize-consent-prompts','/scopes/current/guides/customize-consent-prompt'],
to: '/brand-and-customize/customize-consent-prompts'
},
{
from: ['/universal-login/custom-error-pages','/error-pages/custom', '/hosted-pages/custom-error-pages'],
to: '/brand-and-customize/custom-error-pages'
},
{
from: [
'/libraries/lock/customize-lock-error-messages',
'/libraries/lock/v11/customizing-error-messages',
'/libraries/lock/customizing-error-messages'
],
to: '/brand-and-customize/customize-lock-error-messages'
},
{
from: [
'/universal-login/customize-password-reset-page',
'/universal-login/password-reset',
'/hosted-pages/password-reset'
],
to: '/brand-and-customize/customize-password-reset-page'
},
{
from: [
'/multifactor-authentication/administrator/sms-templates',
'/mfa/guides/guardian/customize-sms-messages',
'/multifactor-authentication/sms-templates',
'/mfa/guides/customize-phone-messages',
'/mfa/customize-sms-or-voice-messages'
],
to: '/brand-and-customize/customize-sms-or-voice-messages'
},
/* Internationalization and Localization */
{
from: ['/i18n','/i18n/i18n-custom-login-page'],
to: '/brand-and-customize/i18n'
},
{
from: [
'/i18n/universal-login-internationalization',
'/universal-login/i18n',
'/universal-login/universal-login-internationalization'
],
to: '/brand-and-customize/i18n/universal-login-internationalization'
},
{
from: ['/libraries/lock/v11/i18n', '/libraries/lock/v10/i18n', '/libraries/lock/lock-internationalization'],
to: '/brand-and-customize/i18n/lock-internationalization'
},
{
from: [
'/libraries/lock-swift/lock-swift-internationalization',
'/i18n/i18n-guide-ios',
'/libraries/lock-ios/v2/internationalization',
'/libraries/lock-swift/lock-swift-internationalization'
],
to: '/brand-and-customize/i18n/lock-swift-internationalization'
},
{
from: [
'/i18n/i18n-guide-android',
'/libraries/lock-android/v2/internationalization',
'/libraries/lock-android/v1/internationalization',
'/libraries/lock-android/lock-android-internationalization'
],
to: '/brand-and-customize/i18n/lock-android-internationalization'
},
{
from: [
'/i18n/password-options-translation',
'/i18n/password-options',
'/i18n/password-strength'
],
to: '/brand-and-customize/i18n/password-options-translation'
},
{
from: ['/universal-login/new-experience/universal-login-page-templates','/universal-login/page-templates'],
to: '/brand-and-customize/universal-login-page-templates'
},
/* Custom Domains */
{
from: '/custom-domains',
to: '/brand-and-customize/custom-domains'
},
{
from: ['/custom-domains/configure-custom-domains-with-auth0-managed-certificates','/custom-domains/auth0-managed-certificates'],
to: '/brand-and-customize/custom-domains/auth0-managed-certificates'
},
{
from: ['/custom-domains/self-managed-certificates','/custom-domains/configure-custom-domains-with-self-managed-certificates'],
to: '/brand-and-customize/custom-domains/self-managed-certificates'
},
{
from: '/custom-domains/tls-ssl',
to: '/brand-and-customize/custom-domains/self-managed-certificates/tls-ssl'
},
{
from: '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-gcp-as-reverse-proxy',
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-gcp-as-reverse-proxy'
},
{
from: [
'/custom-domains/set-up-cloudfront',
'/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-aws-cloudfront-for-use-as-reverse-proxy'
],
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-aws-cloudfront-for-use-as-reverse-proxy'
},
{
from: [
'/custom-domains/set-up-cloudflare',
'/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-cloudflare-for-use-as-reverse-proxy'
],
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-cloudflare-for-use-as-reverse-proxy'
},
{
from: [
'/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-azure-cdn-for-use-as-reverse-proxy',
'/custom-domains/set-up-azure-cdn'
],
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-azure-cdn-for-use-as-reverse-proxy'
},
{
from: '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-akamai-for-use-as-reverse-proxy',
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-akamai-for-use-as-reverse-proxy'
},
{
from: ['/custom-domains/configure-features-to-use-custom-domains','/custom-domains/additional-configuration'],
to: '/brand-and-customize/custom-domains/configure-features-to-use-custom-domains'
},
/* Email */
{
from: ['/email','/auth0-email-services'],
to: '/brand-and-customize/email'
},
{
from: [
'/email/custom',
'/auth0-email-services/manage-email-flow',
'/email/manage-email-flow'
],
to: '/brand-and-customize/email/manage-email-flow'
},
{
from: [
'/email/templates',
'/auth0-email-services/customize-email-templates',
'/email/spa-redirect',
'/auth0-email-services/spa-redirect',
'/email/customize-email-templates'
],
to: '/brand-and-customize/email/customize-email-templates'
},
{
from: [
'/email/customize-email-templates/email-template-descriptions',
'/auth0-email-services/email-template-descriptions'
],
to: '/brand-and-customize/email/email-template-descriptions'
},
{
from: [
'/email/liquid-syntax',
'/auth0-email-services/customize-email-templates/use-liquid-syntax-in-email-templates',
'/email/customize-email-templates/use-liquid-syntax-in-email-templates'
],
to: '/brand-and-customize/email/use-liquid-syntax-in-email-templates'
},
{
from: [
'/design/creating-invite-only-applications',
'/invite-only',
'/tutorials/creating-invite-only-applications',
'/auth0-email-services/send-email-invitations-for-application-signup',
'/email/send-email-invitations-for-application-signup'
],
to: '/brand-and-customize/email/send-email-invitations-for-application-signup'
},
{
from: '/email/send-email-invitations-for-application-signup',
to: '/brand-and-customize/email/send-email-invitations-for-application-signup'
},
{
from: [
'/auth0-email-services/configure-external-smtp-email-providers',
'/email/providers',
'/email/configure-external-smtp-email-providers'
],
to: '/brand-and-customize/email/smtp-email-providers'
},
{
from: '/email/configure-external-smtp-email-providers/configure-amazon-ses-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-amazon-ses-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-mandrill-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-mandrill-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-sendgrid-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-sendgrid-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-sparkpost-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-sparkpost-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-mailgun-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-mailgun-as-external-smtp-email-provider'
},
{
from: [
'/auth0-email-services/configure-external-smtp-email-providers/configure-custom-external-smtp-email-provider',
'/email/configure-custom-external-smtp-email-provider'
],
to: '/brand-and-customize/email/smtp-email-providers/configure-custom-external-smtp-email-provider'
},
{
from: [
'/email/testing',
'/auth0-email-services/configure-external-smtp-email-providers/configure-test-smtp-email-servers',
'/email/configure-test-smtp-email-servers'
],
to: '/brand-and-customize/email/configure-test-smtp-email-servers'
},
/* CMS */
{
from: ['/cms/joomla/configuration'],
to: '/cms/integrate-with-joomla'
},
{
from: ['/cms/joomla/installation'],
to: '/cms/joomla-installation'
},
{
from: ['/cms/wordpress','/cms/wordpress/jwt-authentication'],
to: '/cms/wordpress-plugin'
},
{
from: ['/cms/wordpress/installation'],
to: '/cms/wordpress-plugin/install-login-by-auth0'
},
{
from: ['/cms/wordpress/configuration'],
to: '/cms/wordpress-plugin/configure-login-by-auth0'
},
{
from: ['/cms/wordpress/extending'],
to: '/cms/wordpress-plugin/extend-login-by-auth0'
},
{
from: ['/cms/wordpress/troubleshoot'],
to: '/cms/wordpress-plugin/troubleshoot-login-by-auth0'
},
{
from: ['/cms/wordpress/invalid-state'],
to: '/cms/wordpress-plugin/troubleshoot-wordpress-plugin-invalid-state-errors'
},
{
from: ['/cms/wordpress/user-migration'],
to: '/cms/wordpress-plugin/user-migration-in-login-by-auth0'
},
{
from: ['/cms/wordpress/user-migration'],
to: '/cms/wordpress-plugin/user-migration-in-login-by-auth0'
},
{
from: ['/cms/wordpress/how-does-it-work'],
to: '/cms/wordpress-plugin/integrate-with-wordpress'
},
/* Compliance */
{
from: ['/compliance-and-certifications'],
to: '/compliance'
},
{
from: ['/compliance/gdpr/data-processing'],
to: '/compliance/data-processing'
},
{
from: ['/compliance/gdpr/features-aiding-compliance','/compliance/gdpr/security-advice-for-customers','/compliance/gdpr/roles-responsibilities','/compliance/gdpr/gdpr-summary','/compliance/gdpr/definitions','/compliance/auth0-gdpr-compliance'],
to: '/compliance/gdpr'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/user-consent'],
to: '/compliance/gdpr/gdpr-conditions-for-consent'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/data-minimization'],
to: '/compliance/gdpr/gdpr-data-minimization'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/data-portability'],
to: '/compliance/gdpr/gdpr-data-portability'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/protect-user-data'],
to: '/compliance/gdpr/gdpr-protect-and-secure-user-data'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/right-to-access-data'],
to: '/compliance/gdpr/gdpr-right-to-access-correct-and-erase-data'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/user-consent/track-consent-with-custom-ui'],
to: '/compliance/gdpr/gdpr-track-consent-with-custom-ui'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/user-consent/track-consent-with-lock'],
to: '/compliance/gdpr/gdpr-track-consent-with-lock'
},
/* Deploy */
{
from: ['/get-started/deployment-options', '/getting-started/deployment-models','/overview/deployment-models','/deployment'],
to: '/deploy'
},
{
from: ['/private-cloud/private-cloud-deployments/private-cloud-addon-options','/private-saas-deployment/add-ons','/private-cloud/add-ons','/appliance/infrastructure/internet-restricted-deployment','/private-saas-deployment','/private-cloud/managed-private-cloud','/private-cloud','/appliance','/appliance/checksum','/appliance/proxy-updater','/appliance/update','/updating-appliance','/enterprise/private-cloud/overview','/appliance/dashboard/instrumentation','/appliance/instrumentation','/appliance/appliance-overview'],
to: '/deploy/private-cloud'
},
{
from: ['/services/private-cloud-configuration','/services/private-saas-configuration','/private-saas-deployment/onboarding','/private-saas-deployment/onboarding/private-cloud','/private-cloud/onboarding','/private-cloud/onboarding/private-cloud','/enterprise-support','/onboarding/appliance-outage','/onboarding/enterprise-support','/private-cloud/managed-private-cloud/zones','/private-cloud/managed-private-cloud/raci', '/private-cloud/private-cloud-onboarding'],
to: '/deploy/private-cloud/private-cloud-onboarding'
},
{
from: ['/private-cloud/private-cloud-onboarding/customer-hosted-managed-private-cloud-infrastructure-requirements'],
to: '/deploy/private-cloud/private-cloud-onboarding/customer-hosted-managed-private-cloud-infrastructure-requirements'
},
{
from: ['/private-cloud/private-cloud-onboarding/private-cloud-ip-domain-and-port-list','/private-saas-deployment/onboarding/managed-private-cloud/ip-domain-port-list','/private-cloud/onboarding/managed-private-cloud/ip-domain-port-list', '/appliance/infrastructure/ip-domain-port-list'],
to: '/deploy/private-cloud/private-cloud-onboarding/private-cloud-ip-domain-and-port-list'
},
{
from: ['/private-cloud/private-cloud-onboarding/private-cloud-remote-access-options','/private-cloud/onboarding/managed-private-cloud/remote-access-options','/private-cloud/private-cloud-onboarding/private-cloud-remote-access-options'],
to: '/deploy/private-cloud/private-cloud-onboarding/private-cloud-remote-access-options'
},
{
from: ['/private-cloud/private-cloud-onboarding/standard-private-cloud-infrastructure-requirements','/private-saas-deployment/private-cloud','/private-cloud/standard-private-cloud','/private-saas-deployment/onboarding/managed-private-cloud/infrastructure','/private-cloud/onboarding/managed-private-cloud/infrastructure','/private-saas-deployment/managed-private-cloud','/private-cloud/onboarding/managed-private-cloud','/private-saas-deployment/onboarding/managed-private-cloud','/private-cloud/onboarding/managed-private-cloud','/appliance/infrastructure','/appliance/infrastructure/security'],
to: '/deploy/private-cloud/private-cloud-onboarding/standard-private-cloud-infrastructure-requirements'
},
{
from: ['/private-cloud/private-cloud-operations','/services/private-saas-management','/services/private-cloud-management'],
to: '/deploy/private-cloud/private-cloud-operations'
},
{
from: ['/private-cloud/private-cloud-migrations'],
to: '/deploy/private-cloud/private-cloud-migrations'
},
{
from: ['/private-cloud/private-cloud-migrations/migrate-from-public-cloud-to-private-cloud'],
to: '/deploy/private-cloud/private-cloud-migrations/migrate-from-public-cloud-to-private-cloud'
},
{
from: ['/private-cloud/private-cloud-migrations/migrate-from-standard-private-cloud-to-managed-private-cloud'],
to: '/deploy/private-cloud/private-cloud-migrations/migrate-from-standard-private-cloud-to-managed-private-cloud'
},
{
from: ['/private-cloud/private-cloud-migrations/migrate-private-cloud-custom-domains','/appliance/custom-domains','/private-saas-deployment/custom-domain-migration','/private-cloud/custom-domain-migration','/private-cloud/migrate-private-cloud-custom-domains'],
to: '/deploy/private-cloud/private-cloud-migrations/migrate-private-cloud-custom-domains'
},
{
from: ['/pre-deployment'],
to: '/deploy/pre-deployment'
},
{
from: ['/pre-deployment/how-to-run-production-checks','/pre-deployment/how-to-run-test'],
to: '/deploy/pre-deployment/how-to-run-production-checks'
},
{
from: [
'/deploy/pre-deployment/how-to-run-production-checks/production-check-required-fixes',
'/pre-deployment/how-to-run-production-checks/production-check-required-fixes',
'/pre-deployment/tests/required'
],
to: '/deploy/pre-deployment/production-check-required-fixes'
},
{
from: [
'/pre-deployment/how-to-run-production-checks/production-check-recommended-fixes',
'/pre-deployment/tests/recommended',
'/deploy/pre-deployment/how-to-run-production-checks/production-check-recommended-fixes'
],
to: '/deploy/pre-deployment/production-check-recommended-fixes'
},
{
from: [
'/pre-deployment/how-to-run-production-checks/production-checks-best-practices',
'/pre-deployment/tests/best-practice',
'/deploy/pre-deployment/how-to-run-production-checks/production-checks-best-practices'
],
to: '/deploy/pre-deployment/production-checks-best-practices'
},
{
from: ['/support/predeployment-tests','/support/testing'],
to: '/deploy/pre-deployment/predeployment-tests'
},
{
from: ['/pre-deployment/pre-launch-tips','/pre-deployment/prelaunch-tips'],
to: '/deploy/pre-deployment/pre-launch-tips'
},
/* Extensions */
{
from: [
'/extensions/using-provided-extensions',
'/topics/extensibility',
'/extend-integrate',
'/extensions/visual-studio-team-services-deploy',
'/extensions/visual-studio-team-services-deployments'
],
to: '/extensions'
},
{
from: [
'/extensions/authorization-extension/v2',
'/extensions/authorization-extension/v1',
'/api/authorization-dashboard-extension',
'/extensions/authorization-dashboard-extension'
],
to: '/extensions/authorization-extension'
},
{
from: ['/extensions/authorization-extension/v2/implementation/configuration'],
to: '/extensions/authorization-extension/configure-authorization-extension'
},
{
from: ['/extensions/authorization-extension/v2/implementation/installation'],
to: '/extensions/authorization-extension/install-authorization-extension'
},
{
from: ['/extensions/authorization-extension/v2/implementation/setup'],
to: '/extensions/authorization-extension/set-up-authorization-extension-users'
},
{
from: ['/extensions/authorization-extension/v2/api-access'],
to: '/extensions/authorization-extension/enable-api-access-to-authorization-extension'
},
{
from: ['/extensions/authorization-extension/v2/import-export-data'],
to: '/extensions/authorization-extension/import-and-export-authorization-extension-data'
},
{
from: ['/extensions/authorization-extension/v2/migration'],
to: '/extensions/authorization-extension/migrate-to-authorization-extension-v2'
},
{
from: ['/extensions/authorization-extension/v2/rules'],
to: '/extensions/authorization-extension/use-rules-with-the-authorization-extension'
},
{
from: ['/extensions/delegated-admin/v3','/extensions/delegated-admin/v2','/extensions/delegated-admin'],
to: '/extensions/delegated-administration-extension'
},
{
from: [
'/extensions/delegated-admin/v3/hooks',
'/extensions/delegated-admin/v2/hooks',
'/extensions/delegated-admin/hooks'
],
to: '/extensions/delegated-administration-extension/delegated-administration-hooks'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/access',
'/extensions/delegated-admin/v2/hooks/access',
'/extensions/delegated-admin/hooks/access',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-access-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-access-hook'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/filter',
'/extensions/delegated-admin/v2/hooks/filter',
'/extensions/delegated-admin/hooks/filter',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-filter-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-filter-hook'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/membership',
'/extensions/delegated-admin/v2/hooks/membership',
'/extensions/delegated-admin/hooks/membership',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-memberships-query-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-memberships-query-hook'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/settings',
'/extensions/delegated-admin/v2/hooks/settings',
'/extensions/delegated-admin/hooks/settings',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-settings-query-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-settings-query-hook'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/write',
'/extensions/delegated-admin/v2/hooks/write',
'/extensions/delegated-admin/hooks/write',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-write-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-write-hook'
},
{
from: ['/extensions/delegated-admin/v3/manage-users','/extensions/delegated-admin/v2/manage-users','/extensions/delegated-admin/manage-users'],
to: '/extensions/delegated-administration-extension/delegated-administration-manage-users'
},
{
from: ['/extensions/sso-dashboard'],
to: '/extensions/single-sign-on-dashboard-extension'
},
{
from: [
'/get-started/dashboard/create-sso-dashboard-application',
'/dashboard/guides/extensions/sso-dashboard-create-app'
],
to: '/extensions/single-sign-on-dashboard-extensions/create-sso-dashboard-application'
},
{
from: ['/dashboard/guides/extensions/sso-dashboard-install-extension'],
to: '/extensions/single-sign-on-dashboard-extension/install-sso-dashboard-extension'
},
{
from: ['/dashboard/guides/extensions/sso-dashboard-add-apps'],
to: '/extensions/single-sign-on-dashboard-extension/add-applications-to-the-sso-dashboard'
},
{
from: ['/dashboard/guides/extensions/sso-dashboard-update-apps'],
to: '/extensions/single-sign-on-dashboard-extension/update-applications-on-the-sso-dashboard'
},
/* LDAP Connector */
{
from: ['/connector','/connector/overview','/connector/considerations-non-ad','/ad-ldap-connector'],
to: '/extensions/ad-ldap-connector'
},
{
from: ['/connector/prerequisites','/ad-ldap-connector/ad-ldap-connector-requirements'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-requirements'
},
{
from: ['/adldap-x','/connector/install-other-platforms','/connector/install','/adldap-auth'],
to: '/extensions/ad-ldap-connector/install-configure-ad-ldap-connector'
},
{
from: ['/connector/client-certificates','/ad-ldap-connector/configure-ad-ldap-connector-authentication-with-client-certificates'],
to: '/extensions/ad-ldap-connector/configure-ad-ldap-connector-client-certificates'
},
{
from: ['/connector/kerberos','/ad-ldap-connector/configure-ad-ldap-connector-authentication-with-kerberos'],
to: '/extensions/ad-ldap-connector/configure-ad-ldap-connector-with-kerberos'
},
{
from: ['/connector/high-availability','/ad-ldap-connector/ad-ldap-high-availability'],
to: '/extensions/ad-ldap-connector/ad-ldap-high-availability'
},
{
from: ['/extensions/adldap-connector','/extensions/ad-ldap-connector-health-monitor'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-health-monitor'
},
{
from: ['/dashboard/guides/connections/disable-cache-ad-ldap'],
to: '/extensions/ad-ldap-connector/disable-credential-caching'
},
{
from: ['/connector/scom-monitoring','/ad-ldap-connector/ad-ldap-connector-scorm'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-scom'
},
{
from: ['/connector/modify','/ad-ldap-connector/ad-ldap-connectors-to-auth0'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-to-auth0'
},
{
from: ['/connector/test-dc','/ad-ldap-connector/ad-ldap-connector-test-environment'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-test-environment'
},
{
from: ['/connector/update','/ad-ldap-connector/update-ad-ldap-connectors'],
to: '/extensions/ad-ldap-connector/update-ad-ldap-connectors'
},
{
from: ['/extensions/account-link'],
to: '/extensions/account-link-extension'
},
{
from: ['/logs/export-log-events-with-extensions', '/logs/log-export-extensions'],
to: '/extensions/log-export-extensions'
},
{
from: ['/extensions/export-logs-to-application-insights','/extensions/application-insight'],
to: '/extensions/log-export-extensions/export-logs-to-application-insights'
},
{
from: ['/extensions/export-logs-to-cloudwatch','/extensions/cloudwatch'],
to: '/extensions/log-export-extensions/export-logs-to-cloudwatch'
},
{
from: ['/extensions/export-logs-to-azure-blob-storage','/extensions/azure-blob-storage'],
to: '/extensions/log-export-extensions/export-logs-to-azure-blob-storage'
},
{
from: ['/extensions/export-logs-to-logentries','/extensions/logentries'],
to: '/extensions/log-export-extensions/export-logs-to-logentries'
},
{
from: ['/extensions/export-logs-to-loggly','/extensions/loggly'],
to: '/extensions/log-export-extensions/export-logs-to-loggly'
},
{
from: ['/extensions/export-logs-to-logstash','/extensions/logstash'],
to: '/extensions/log-export-extensions/export-logs-to-logstash'
},
{
from: ['/extensions/export-logs-to-mixpanel','/extensions/mixpanel'],
to: '/extensions/log-export-extensions/export-logs-to-mixpanel'
},
{
from: ['/extensions/export-logs-to-papertrail','/extensions/papertrail'],
to: '/extensions/log-export-extensions/export-logs-to-papertrail'
},
{
from: ['/extensions/export-logs-to-segment','/extensions/segment'],
to: '/extensions/log-export-extensions/export-logs-to-segment'
},
{
from: ['/extensions/export-logs-to-splunk','/extensions/splunk'],
to: '/extensions/log-export-extensions/export-logs-to-splunk'
},
{
from: ['/extensions/auth0-logs-to-sumo-logic','/extensions/sumologic'],
to: '/extensions/log-export-extensions/auth0-logs-to-sumo-logic'
},
{
from: ['/extensions/authentication-api-debugger'],
to: '/extensions/authentication-api-debugger-extension'
},
{
from: ['/extensions/authentication-api-webhooks'],
to: '/extensions/auth0-authentication-api-webhooks'
},
{
from: ['/extensions/user-import-export'],
to: '/extensions/user-import-export-extension'
},
{
from: [
'/extensions/bitbucket-deploy',
'/extensions/bitbucket-deployments'
],
to: 'https://marketplace.auth0.com/integrations/bitbucket-pipeline'
},
{
from: ['/extensions/custom-social-connections','/extensions/custom-social-extensions'],
to: '/connections/social/oauth2'
},
{
from: [
'/extensions/github-deploy',
'/extensions/github-deployments'
],
to: 'https://marketplace.auth0.com/integrations/github-actions'
},
{
from: [
'/extensions/gitlab-deploy',
'/extensions/gitlab-deployments'
],
to: 'https://marketplace.auth0.com/integrations/gitlab-pipeline'
},
{
from: ['/extensions/management-api-webhooks'],
to: '/extensions/auth0-management-api-webhooks'
},
{
from: ['/extensions/realtime-webtask-logs'],
to: '/extensions/real-time-webtask-logs'
},
{
from: ['/dashboard/guides/extensions/delegated-admin-create-app'],
to: '/extensions/delegated-administration-extension/create-delegated-admin-applications'
},
{
from: ['/dashboard/guides/extensions/delegated-admin-install-extension','/dashboard/guides/extensions/delegated-admin-use-extension'],
to: '/extensions/delegated-administration-extension/install-delegated-admin-extension'
},
/* Deploy CLI Tool */
{
from: ['/extensions/deploy-cli-tool','/extensions/deploy-cli'],
to: '/deploy/deploy-cli-tool'
},
{
from: [
'/extensions/deploy-cli-tool/call-deploy-cli-tool-programmatically',
'/extensions/deploy-cli/guides/call-deploy-cli-programmatically'
],
to: '/deploy/deploy-cli-tool/call-deploy-cli-tool-programmatically'
},
{
from: [
'/extensions/deploy-cli/guides/create-deploy-cli-application-manually',
'/extensions/deploy-cli-tool/create-and-configure-the-deploy-cli-application-manually',
'/extensions/deploy-cli-tool/create-and-configure-the-deploy-cli-application'
],
to: '/deploy/deploy-cli-tool/create-and-configure-the-deploy-cli-application'
},
{
from: [
'/extensions/deploy-cli/guides/import-export-directory-structure',
'/extensions/deploy-cli-tool/import-export-tenant-configuration-to-directory-structure'
],
to: '/deploy/deploy-cli-tool/import-export-tenant-configuration-to-directory-structure'
},
{
from: [
'/extensions/deploy-cli/guides/import-export-yaml-file',
'/extensions/deploy-cli-tool/import-export-tenant-configuration-to-yaml-file'
],
to: '/deploy/deploy-cli-tool/import-export-tenant-configuration-to-yaml-file'
},
{
from: [
'/extensions/deploy-cli/guides/incorporate-deploy-cli-into-build-environment',
'/extensions/deploy-cli-tool/incorporate-deploy-cli-into-build-environment'
],
to: '/deploy/deploy-cli-tool/incorporate-deploy-cli-into-build-environment'
},
{
from: [
'/extensions/deploy-cli/guides/install-deploy-cli',
'/extensions/deploy-cli-tool/install-and-configure-the-deploy-cli-tool'
],
to: '/deploy/deploy-cli-tool/install-and-configure-the-deploy-cli-tool'
},
{
from: [
'/extensions/deploy-cli/references/deploy-cli-options',
'/extensions/deploy-cli-tool/deploy-cli-tool-options'
],
to: '/deploy/deploy-cli-tool/deploy-cli-tool-options'
},
{
from: [
'/extensions/deploy-cli/references/environment-variables-keyword-mappings',
'/extensions/deploy-cli-tool/environment-variables-and-keyword-mappings'
],
to: '/deploy/deploy-cli-tool/environment-variables-and-keyword-mappings'
},
{
from: [
'/extensions/deploy-cli/references/whats-new',
'/extensions/deploy-cli/references/whats-new-v2',
'/extensions/deploy-cli-tool/whats-new-in-deploy-cli-tool'
],
to: '/deploy/deploy-cli-tool/whats-new-in-deploy-cli-tool'
},
/* Get Started */
{
from: ['/getting-started'],
to: '/get-started'
},
{
from: ['/overview','/get-started/overview','/getting-started/overview'],
to: '/get-started/auth0-overview'
},
{
from: ['/getting-started/set-up-app', '/applications/set-up-an-application'],
to: '/get-started/create-apps'
},
{
from: [
'/dashboard/guides/applications/register-app-m2m',
'/applications/application-settings/non-interactive',
'/applications/application-settings/machine-to-machine',
'/applications/machine-to-machine',
'/applications/set-up-an-application/register-machine-to-machine-applications'
],
to: '/get-started/create-apps/machine-to-machine-apps'
},
{
from: [
'/dashboard/guides/applications/register-app-native',
'/applications/application-settings/native',
'/applications/native',
'/applications/set-up-an-application/register-native-applications'
],
to: '/get-started/create-apps/native-apps'
},
{
from: [
'/dashboard/guides/applications/register-app-regular-web',
'/applications/application-settings/regular-web-app',
'/applications/webapps',
'/applications/register-regular-web-applications',
'/applications/set-up-an-application/register-regular-web-applications'
],
to: '/get-started/create-apps/regular-web-apps'
},
{
from: [
'/dashboard/guides/applications/register-app-spa',
'/applications/spa',
'/applications/application-settings/single-page-app',
'/applications/register-single-page-app',
'/applications/set-up-an-application/register-single-page-app'
],
to: '/get-started/create-apps/single-page-web-apps'
},
{
from: ['/getting-started/set-up-api','/dashboard/reference/views-api'],
to: '/get-started/set-up-apis'
},
{
from: ['/dashboard','/getting-started/dashboard-overview'],
to: '/get-started/dashboard'
},
{
from: ['/get-started/learn-the-basics','/getting-started/the-basics','/getting-started/create-tenant'],
to: '/get-started/create-tenants'
},
{
from: ['/dev-lifecycle/child-tenants'],
to: '/get-started/create-tenants/child-tenants'
},
{
from: ['/dev-lifecycle/set-up-multiple-environments','/dev-lifecycle/setting-up-env'],
to: '/get-started/create-tenants/set-up-multiple-environments'
},
{
from: ['/get-started/dashboard/create-multiple-tenants','/dashboard/guides/tenants/create-multiple-tenants'],
to: '/get-started/create-tenants/create-multiple-tenants'
},
{
from: ['/dashboard/guides/tenants/enable-sso-tenant'],
to: '/get-started/dashboard/enable-sso-for-legacy-tenants'
},
{
from: [
'/dashboard/guides/connections/set-up-connections-social',
'/get-started/dashboard/set-up-social-connections'
],
to: 'https://marketplace.auth0.com/features/social-connections'
},
{
from: ['/dashboard/guides/connections/test-connections-database'],
to: '/get-started/dashboard/test-database-connections'
},
{
from: ['/dashboard/guides/connections/test-connections-enterprise'],
to: '/get-started/dashboard/test-enterprise-connections'
},
{
from: ['/dashboard/guides/connections/test-connections-social'],
to: '/get-started/dashboard/test-social-connections'
},
{
from: ['/dashboard/guides/connections/view-connections'],
to: '/get-started/dashboard/view-connections'
},
{
from: ['/dashboard/guides/connections/enable-connections-enterprise'],
to: '/get-started/dashboard/enable-enterprise-connections'
},
{
from: ['/api/management/guides/connections/promote-connection-domain-level'],
to: '/get-started/dashboard/promote-connections-to-domain-level'
},
{
from: ['/api/management/guides/connections/retrieve-connection-options','/api/management/guides/retrieve-connection-options'],
to: '/get-started/dashboard/retrieve-connection-options'
},
{
from: ['/dashboard-access/dashboard-roles','/dashboard-access/manage-dashboard-users','/dashboard/manage-dashboard-admins','/tutorials/manage-dashboard-admins','/get-started/dashboard/manage-dashboard-users'],
to: '/dashboard-access'
},
{
from: ['/dashboard-access/dashboard-roles/feature-access-by-role'],
to: '/dashboard-access/feature-access-by-role'
},
{
from: ['/product-lifecycle/deprecations-and-migrations/migrate-to-manage-dashboard-new-roles'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-tenant-member-roles'
},
/* Hooks */
{
from: ['/hooks/cli','/auth0-hooks/cli','/hooks/dashboard','/hooks/overview','/auth0-hooks','/auth0-hooks/dashboard'],
to: '/hooks'
},
{
from: ['/hooks/concepts/extensibility-points','/hooks/concepts/overview-extensibility-points'],
to: '/hooks/extensibility-points'
},
{
from: ['/hooks/concepts/credentials-exchange-extensibility-point','/hooks/guides/use-the-credentials-exchange-extensibility-point','/hooks/client-credentials-exchange','/hooks/extensibility-points/credentials-exchange'],
to: '/hooks/extensibility-points/client-credentials-exchange'
},
{
from: ['/hooks/create','/hooks/dashboard/create-delete','/hooks/cli/create-delete','/hooks/guides/create-hooks-using-cli','/hooks/guides/create-hooks-using-dashboard','/auth0-hooks/cli/create-delete'],
to: '/hooks/create-hooks'
},
{
from: ['/hooks/delete','/hooks/guides/delete-hooks-using-cli','/hooks/guides/delete-hooks-using-dashboard'],
to: '/hooks/delete-hooks'
},
{
from: ['/hooks/enable-disable','/hooks/cli/enable-disable','/hooks/dashboard/enable-disable','/hooks/guides/enable-disable-hooks-using-cli','/hooks/guides/enable-disable-hooks-using-dashboard','/auth0-hooks/cli/enable-disable'],
to: '/hooks/enable-disable-hooks'
},
{
from: ['/hooks/guides/post-change-password','/hooks/post-change-password'],
to: '/hooks/extensibility-points/post-change-password'
},
{
from: ['/hooks/concepts/post-user-registration-extensibility-point','/hooks/guides/use-the-post-user-registration-extensibility-point','/hooks/post-user-registration'],
to: '/hooks/extensibility-points/post-user-registration'
},
{
from: ['/hooks/concepts/pre-user-registration-extensibility-point','/hooks/guides/use-the-pre-user-registration-extensibility-point','/auth0-hooks/extensibility-points/pre-user-registration','/hooks/pre-user-registration'],
to: '/hooks/extensibility-points/pre-user-registration'
},
{
from: ['/hooks/secrets/create'],
to: '/hooks/hook-secrets/create-hook-secrets'
},
{
from: ['/hooks/secrets/delete'],
to: '/hooks/hook-secrets/delete-hook-secrets'
},
{
from: ['/hooks/secrets'],
to: '/hooks/hook-secrets'
},
{
from: ['/hooks/secrets/update'],
to: '/hooks/hook-secrets/update-hook-secrets'
},
{
from: ['/hooks/secrets/view'],
to: '/hooks/hook-secrets/view-hook-secrets'
},
{
from: ['/hooks/update','/hooks/cli/edit','/hooks/dashboard/edit','/hooks/guides/edit-hooks-using-cli','/hooks/guides/edit-hooks-using-dashboard'],
to: '/hooks/update-hooks'
},
{
from: ['/hooks/view-logs','/hooks/cli/logs','/hooks/logs','/hooks/guides/logging-hooks-using-cli','/auth0-hooks/cli/logs'],
to: '/hooks/view-logs-for-hooks'
},
{
from: ['/hooks/view'],
to: '/hooks/view-hooks'
},
/* Identity Labs */
{
from: ['/labs'],
to: '/identity-labs'
},
{
from: ['/identity-labs/01-web-sign-in'],
to: '/identity-labs/lab-1-web-sign-in'
},
{
from: ['/identity-labs/01-web-sign-in/exercise-01'],
to: '/identity-labs/lab-1-web-sign-in/identity-lab-1-exercise-1'
},
{
from: ['/identity-labs/01-web-sign-in/exercise-02'],
to: '/identity-labs/lab-1-web-sign-in/identity-lab-1-exercise-2'
},
{
from: ['/identity-labs/02-calling-an-api'],
to: '/identity-labs/identity-lab-2-calling-api'
},
{
from: ['/identity-labs/02-calling-an-api/exercise-01'],
to: '/identity-labs/identity-lab-2-calling-api/identity-lab-2-exercise-1'
},
{
from: ['/identity-labs/02-calling-an-api/exercise-02'],
to: '/identity-labs/identity-lab-2-calling-api/identity-lab-2-exercise-2'
},
{
from: ['/identity-labs/02-calling-an-api/exercise-03'],
to: '/identity-labs/identity-lab-2-calling-api/identity-lab-2-exercise-3'
},
{
from: ['/identity-labs/03-mobile-native-app'],
to: '/identity-labs/lab-3-mobile-native-app'
},
{
from: ['/identity-labs/03-mobile-native-app/exercise-01'],
to: '/identity-labs/lab-3-mobile-native-app/identity-lab-3-exercise-1'
},
{
from: ['/identity-labs/03-mobile-native-app/exercise-02'],
to: '/identity-labs/lab-3-mobile-native-app/identity-lab-3-exercise-2'
},
{
from: ['/identity-labs/03-mobile-native-app/exercise-03'],
to: '/identity-labs/lab-3-mobile-native-app/identity-lab-3-exercise-3'
},
{
from: ['/identity-labs/04-single-page-app'],
to: '/identity-labs/lab-4-single-page-app'
},
{
from: ['/identity-labs/04-single-page-app/exercise-01'],
to: '/identity-labs/lab-4-single-page-app/identity-lab-4-exercise-1'
},
{
from: ['/identity-labs/04-single-page-app/exercise-02'],
to: '/identity-labs/lab-4-single-page-app/identity-lab-4-exercise-2'
},
/* Integrations */
{
from: ['/integration'],
to: '/integrations'
},
{
from: ['/aws-api-setup'],
to: '/integrations/how-to-set-up-aws-for-delegated-authentication'
},
{
from: ['/integrations/aws/sso','/configure-amazon-web-services-for-sso'],
to: '/integrations/aws/configure-amazon-web-services-for-sso'
},
{
from: ['/integrations/aws/tokens','/integrations/call-aws-apis-and-resources-with-tokens'],
to: '/integrations/aws-api-gateway-delegation'
},
{
from: ['/scenarios/amazon-cognito', '/tutorials/integrating-auth0-amazon-cognito-mobile-apps', '/integrations/integrating-auth0-amazon-cognito-mobile-apps', '/integrations/integrate-with-amazon-cognito'],
to: '/integrations/amazon-cognito'
},
{
from: ['/scenarios-mqtt','/tutorials/authenticating-devices-using-mqtt','/integrations/authenticating-devices-using-mqtt'],
to: '/integrations/authenticate-devices-using-mqtt'
},
{
from: ['/scenarios-tessel', '/tutorials/authenticating-a-tessel-device', '/integrations/authenticating-a-tessel-device'],
to: '/integrations/authenticating-and-authorizing-a-tessel-device-with-auth0'
},
{
from: ['/aws', '/awsapi-tutorial'],
to: '/integrations/aws'
},
{
from: ['/integrations/aws-api-gateway/delegation','/integrations/aws-api-gateway'],
to: '/integrations/aws-api-gateway-delegation'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-1','/integrations/aws-api-gateway/part-1','/integrations/aws-api-gateway/aws-api-gateway-step-1'],
to: '/integrations/aws-api-gateway-delegation-1'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-2','/integrations/aws-api-gateway/part-2','/integrations/aws-api-gateway/aws-api-gateway-step-2'],
to: '/integrations/aws-api-gateway-delegation-2'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-3','/integrations/aws-api-gateway/part-3','/integrations/aws-api-gateway/aws-api-gateway-step-3'],
to: '/integrations/aws-api-gateway-delegation-3'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-4','/integrations/aws-api-gateway/part-4','/integrations/aws-api-gateway/aws-api-gateway-step-4'],
to: '/integrations/aws-api-gateway-delegation-4'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-5','/integrations/aws-api-gateway/part-5','/integrations/aws-api-gateway/aws-api-gateway-step-5'],
to: '/integrations/aws-api-gateway-delegation-5'
},
{
from: ['/integrations/aws-api-gateway/delegation/secure-api-with-cognito','/integrations/aws-api-gateway/secure-api-with-cognito'],
to: '/integrations/aws-api-gateway-cognito'
},
{
from: ['/integrations/aws-api-gateway/custom-authorizers', '/integrations/aws-api-gateway/custom-authorizers/part-1', '/integrations/aws-api-gateway/custom-authorizers/part-2', '/integrations/aws-api-gateway/custom-authorizers/part-3', '/integrations/aws-api-gateway/custom-authorizers/part-4'],
to: '/integrations/aws-api-gateway-custom-authorizers'
},
{
from: ['/sharepoint-apps', '/integrations/sharepoint-apps'],
to: '/integrations/connecting-provider-hosted-apps-to-sharepoint-online'
},
{
from: ['/integrations/google-cloud-platform', '/tutorials/google-cloud-platform'],
to: '/integrations/google-cloud-endpoints'
},
{
from: ['/integrations/marketing/salesforce'],
to: '/integrations/marketing/export-user-data-salesforce'
},
{
from: ['/tutorials/office365-connection-deprecation-guide', '/integrations/office365-connection-deprecation-guide','/office365-deprecated'],
to: '/integrations/migrate-office365-connections-to-windows-azure-ad'
},
{
from: ['/tutorials/using-auth0-to-secure-a-cli', '/integrations/using-auth0-to-secure-a-cli','/tutorials/using-auth0-to-secure-an-api','/cli'],
to: '/integrations/secure-a-cli-with-auth0'
},
{
from: ['/integrations/sharepoint'],
to: '/integrations/sharepoint-2010-2013'
},
{
from: [
'/integrations/sso-integrations',
'/sso/current/integrations'
],
to: '/integrations/sso'
},
{
from: [
'/integrations/sso-integrations/ad-rms',
'/integrations/sso-integrations/ad-rms-sso-integration',
'/sso/current/integrations/ad-rms',
'/integrations/sso/ad-rms'
],
to: 'https://marketplace.auth0.com/integrations/ad-rms-sso'
},
{
from: [
'/integrations/sso-integrations/box',
'/sso/current/integrations/box',
'/integrations/sso/box'
],
to: 'https://marketplace.auth0.com/integrations/box-sso'
},
{
from: [
'/integrations/sso-integrations/cloudbees',
'/sso/current/integrations/cloudbees',
'/integrations/sso/cloudbees'
],
to: 'https://marketplace.auth0.com/integrations/cloudbees-sso'
},
{
from: [
'/integrations/sso-integrations/concur',
'/sso/current/integrations/concur',
'/integrations/sso/concur'
],
to: 'https://marketplace.auth0.com/integrations/concur-sso'
},
{
from: [
'/integrations/sso-integrations/disqus',
'/sso/current/integrations/disqus',
'/integrations/disqus',
'/integrations/sso/disqus'
],
to: 'https://marketplace.auth0.com/features/sso-integrations'
},
{
from: [
'/integrations/sso-integrations/dropbox',
'/sso/current/integrations/dropbox',
'/integrations/dropbox',
'/integrations/sso/dropbox'
],
to: 'https://marketplace.auth0.com/integrations/dropbox-sso'
},
{
from: [
'/integrations/sso-integrations/dynamics-crm',
'/sso/current/integrations/dynamics-crm',
'/integrations/dynamics-crm',
'/integrations/sso/dynamics-crm'
],
to: 'https://marketplace.auth0.com/integrations/dynamics-crm-sso'
},
{
from: [
'/integrations/sso-integrations/adobe-sign',
'/integrations/sso-integrations/echosign',
'/sso/current/integrations/echosign',
'/integrations/echosign',
'/integrations/sso/adobe-sign'
],
to: 'https://marketplace.auth0.com/integrations/adobe-sign-sso'
},
{
from: [
'/integrations/sso-integrations/egnyte',
'/sso/current/integrations/egnyte',
'/integrations/egnyte',
'/integrations/sso/egnyte'
],
to: 'https://marketplace.auth0.com/integrations/egnyte-sso'
},
{
from: [
'/integrations/sso-integrations/new-relic',
'/sso/current/integrations/new-relic',
'/integrations/new-relic',
'/integrations/sso/new-relic'
],
to: 'https://marketplace.auth0.com/integrations/new-relic-sso'
},
{
from: [
'/integrations/sso-integrations/office-365',
'/sso/current/integrations/office-365',
'/integrations/office-365',
'/integrations/sso/office-365'
],
to: 'https://marketplace.auth0.com/integrations/office-365-sso'
},
{
from: [
'/integrations/sso-integrations/salesforce',
'/sso/current/integrations/salesforce',
'/integrations/salesforce',
'/integrations/sso/salesforce'
],
to: 'https://marketplace.auth0.com/integrations/salesforce-sso'
},
{
from: [
'/integrations/sso-integrations/slack',
'/sso/current/integrations/slack',
'/integrations/integrating-with-slack',
'/tutorials/integrating-with-slack',
'/scenarios/slack',
'/integrations/slack',
'/integrations/sso/slack'
],
to: 'https://marketplace.auth0.com/integrations/slack-sso'
},
{
from: [
'/integrations/sso-integrations/sentry',
'/sso/current/integrations/sentry',
'/integrations/sentry',
'/integrations/sso/sentry'
],
to: 'https://marketplace.auth0.com/integrations/sentry-sso'
},
{
from: [
'/integrations/sso-integrations/sharepoint',
'/sso/current/integrations/sharepoint',
'/integrations/sso/sharepoint'
],
to: 'https://marketplace.auth0.com/integrations/sharepoint-sso'
},
{
from: [
'/integrations/sso-integrations/springcm',
'/sso/current/integrations/springcm',
'/integrations/springcm',
'/integrations/sso/springcm'
],
to: 'https://marketplace.auth0.com/integrations/springcm-sso'
},
{
from: [
'/integrations/sso-integrations/zendesk',
'/sso/current/integrations/zendesk',
'/integrations/zendesk',
'/integrations/sso/zendesk'
],
to: 'https://marketplace.auth0.com/integrations/zendesk-sso'
},
{
from: [
'/integrations/sso-integrations/zoom',
'/sso/current/integrations/zoom',
'/integrations/zoom',
'/integrations/sso/zoom'
],
to: 'https://marketplace.auth0.com/integrations/zoom-sso'
},
{
from: [
'/integrations/sso-integrations/cisco-webex',
'/integrations/sso/cisco-webex'
],
to: 'https://marketplace.auth0.com/integrations/cisco-webex-sso'
},
{
from: [
'/integrations/sso-integrations/datadog',
'/integrations/sso/datadog'
],
to: 'https://marketplace.auth0.com/integrations/datadog-sso'
},
{
from: [
'/integrations/sso-integrations/egencia',
'/integrations/sso/egencia'
],
to: 'https://marketplace.auth0.com/integrations/egencia-sso'
},
{
from: [
'/integrations/sso-integrations/eloqua',
'/integrations/sso/eloqua'
],
to: 'https://marketplace.auth0.com/integrations/eloqua-sso'
},
{
from: [
'/integrations/sso-integrations/freshdesk',
'/integrations/sso/freshdesk'
],
to: 'https://marketplace.auth0.com/integrations/freshdesk-sso'
},
{
from: [
'/integrations/sso-integrations/g-suite',
'/integrations/sso/g-suite'
],
to: 'https://marketplace.auth0.com/integrations/g-suite-sso'
},
{
from: [
'/integrations/sso-integrations/github-enterprise-cloud',
'/integrations/sso/github-enterprise-cloud'
],
to: 'https://marketplace.auth0.com/integrations/github-enterprise-cloud-sso'
},
{
from: [
'/integrations/sso-integrations/github-enterprise-server',
'/integrations/sso/github-enterprise-server'
],
to: 'https://marketplace.auth0.com/integrations/github-enterprise-server-sso'
},
{
from: [
'/integrations/sso-integrations/heroku',
'/integrations/sso/heroku'
],
to: 'https://marketplace.auth0.com/integrations/heroku-sso'
},
{
from: [
'/integrations/sso-integrations/hosted-graphite',
'/integrations/sso/hosted-graphite'
],
to: 'https://marketplace.auth0.com/integrations/hosted-graphite-sso'
},
{
from: [
'/integrations/sso-integrations/litmos',
'/integrations/sso/litmos'
],
to: 'https://marketplace.auth0.com/integrations/litmos-sso'
},
{
from: [
'/integrations/sso-integrations/pluralsight',
'/integrations/sso/pluralsight'
],
to: 'https://marketplace.auth0.com/integrations/pluralsight-sso'
},
{
from: [
'/integrations/sso-integrations/sprout-video',
'/integrations/sso/sprout-video'
],
to: 'https://marketplace.auth0.com/integrations/sprout-video-sso'
},
{
from: [
'/integrations/sso-integrations/tableau-online',
'/integrations/sso/tableau-online'
],
to: 'https://marketplace.auth0.com/integrations/tableau-online-sso'
},
{
from: [
'/integrations/sso-integrations/tableau-server',
'/integrations/sso/tableau-server'
],
to: 'https://marketplace.auth0.com/integrations/tableau-server-sso'
},
{
from: [
'/integrations/sso-integrations/workday',
'/integrations/sso/workday'
],
to: 'https://marketplace.auth0.com/integrations/workday-sso'
},
{
from: [
'/integrations/sso-integrations/workpath',
'/integrations/sso/workpath'
],
to: 'https://marketplace.auth0.com/integrations/workpath-sso'
},
{
from: ['/integrations/azure-tutorial','/azure-tutorial','/tutorials/azure-tutorial','/integrations/azure-api-management/configure-auth0','/integrations/azure-api-management/configure-azure'],
to: '/integrations/azure-api-management'
},
/* LDAP Connector */
{
from: ['/connector','/connector/overview','/connector/considerations-non-ad','/ad-ldap-connector'],
to: '/extensions/ad-ldap-connector'
},
{
from: [,'/extensions/adldap-connector','/extensions/ad-ldap-connector-health-monitor'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-health-monitor'
},
{
from: ['/connector/prerequisites','/ad-ldap-connector/ad-ldap-connector-requirements'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-requirements'
},
{
from: ['/connector/client-certificates','/ad-ldap-connector/configure-ad-ldap-connector-authentication-with-client-certificates'],
to: '/extensions/ad-ldap-connector/configure-ad-ldap-connector-client-certificates'
},
{
from: ['/connector/kerberos','/ad-ldap-connector/configure-ad-ldap-connector-authentication-with-kerberos'],
to: '/extensions/ad-ldap-connector/configure-ad-ldap-connector-with-kerberos'
},
{
from: ['/connector/high-availability','/ad-ldap-connector/ad-ldap-high-availability'],
to: '/extensions/ad-ldap-connector/ad-ldap-high-availability'
},
{
from: ['/dashboard/guides/connections/disable-cache-ad-ldap'],
to: '/extensions/ad-ldap-connector/disable-credential-caching'
},
{
from: ['/adldap-x','/connector/install-other-platforms','/connector/install','/adldap-auth'],
to: '/extensions/ad-ldap-connector/install-configure-ad-ldap-connector'
},
{
from: ['/connector/scom-monitoring','/ad-ldap-connector/ad-ldap-connector-scorm'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-scom'
},
{
from: ['/connector/modify','/ad-ldap-connector/ad-ldap-connectors-to-auth0'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-to-auth0'
},
{
from: ['/connector/test-dc','/ad-ldap-connector/ad-ldap-connector-test-environment'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-test-environment'
},
{
from: ['/connector/troubleshooting','/ad-ldap-connector/troubleshoot-ad-ldap-connector'],
to: '/extensions/ad-ldap-connector/troubleshoot-ad-ldap-connector'
},
{
from: ['/connector/update','/ad-ldap-connector/update-ad-ldap-connectors'],
to: '/extensions/ad-ldap-connector/update-ad-ldap-connectors'
},
/* Libraries */
{
from: '/sdks',
to: '/libraries'
},
{
from: ['/custom-signup', '/libraries/lock/v10/custom-signup', '/libraries/lock/v11/custom-signup'],
to: '/libraries/custom-signup'
},
{
from: ['/libraries/error-messages','/libraries/lock-android/error-messages','/errors/libraries/auth0-js/invalid-token'],
to: '/libraries/common-auth0-library-authentication-errors'
},
{
from: [
'/widget',
'/login-widget2',
'/lock',
'/migrations/guides/legacy-lock-api-deprecation',
'/libraries/lock/v9',
'/libraries/lock/v9/display-modes',
'/libraries/lock/v9/types-of-applications',
'/libraries/lock/v10',
'/libraries/lock/v10/installation',
'/libraries/lock/v11',
'/libraries/lock/using-refresh-tokens',
'/libraries/lock/using-a-refresh-token'
],
to: '/libraries/lock'
},
{
from: ['/libraries/lock/display-modes','/libraries/lock/customization','/libraries/lock/v9/customization','/libraries/lock/v10/customization','/libraries/lock/v11/customization','/libraries/lock/v9/configuration','/libraries/lock/v10/configuration','/libraries/lock/v11/configuration'],
to: '/libraries/lock/lock-configuration'
},
{
from: ['/libraries/lock/v10/popup-mode','/libraries/lock/v10/authentication-modes','/libraries/lock/v11/popup-mode','/libraries/lock/v11/authentication-modes','/libraries/lock/authentication-modes'],
to: '/libraries/lock/lock-authentication-modes'
},
{
from: ['/hrd','/libraries/lock/v11/selecting-the-connection-for-multiple-logins','/protocols/saml/saml-configuration/selecting-between-multiple-idp','/libraries/lock/v10/selecting-the-connection-for-multiple-logins'],
to: '/libraries/lock/selecting-from-multiple-connection-options'
},
{
from: ['/libraries/lock/v11/api'],
to: '/libraries/lock/lock-api-reference'
},
{
from: ['/libraries/lock/v11/sending-authentication-parameters','/libraries/lock/sending-authentication-parameters'],
to: '/libraries/lock/lock-authentication-parameters'
},
{
from: ['/libraries/lock/v11/ui-customization','/libraries/lock/v9/ui-customization'],
to: '/libraries/lock/lock-ui-customization'
},
{
from: ['/libraries/lock-ios/v2','/libraries/lock-ios/delegation-api','/libraries/lock-ios/v1/delegation-api','/libraries/lock-ios','/libraries/lock-ios/v1','/libraries/lock-ios/lock-ios-api','/libraries/lock-ios/v1/lock-ios-api','/libraries/lock-ios/native-social-authentication','/libraries/lock-ios/v1/native-social-authentication','/libraries/lock-ios/password-reset-ios','/libraries/lock-ios/v1/password-reset-ios','/libraries/lock-ios/save-and-refresh-jwt-tokens','/libraries/lock-ios/v1/save-and-refresh-jwt-tokens','/libraries/lock-ios/sending-authentication-parameters','/libraries/lock-ios/v1/sending-authentication-parameters','/libraries/lock-ios/swift','/libraries/lock-ios/v1/swift'],
to: '/libraries/lock-swift'
},
{
from: ['/libraries/lock-ios/logging','/libraries/lock-ios/v2/logging','/libraries/lock-ios/v1/logging'],
to: '/libraries/lock-swift/lock-swift-logging'
},
{
from: ['/libraries/lock-ios/v2/passwordless','/libraries/lock-ios/sms-lock-ios','/libraries/lock-ios/v1/sms-lock-ios','/libraries/lock-ios/touchid-authentication','/libraries/lock-ios/v1/touchid-authentication','/libraries/lock-ios/passwordless','/libraries/lock-ios/v1/passwordless'],
to: '/libraries/lock-swift/lock-swift-passwordless'
},
{
from: ['/libraries/lock-ios/v2/customization','/libraries/lock-ios/use-your-own-ui','/libraries/lock-ios/v1/use-your-own-uis','/libraries/lock-ios/v1/use-your-own-ui','/libraries/lock-ios/v1/customization'],
to: '/libraries/lock-swift/lock-swift-customization'
},
{
from: ['/libraries/lock-ios/v2/custom-fields'],
to: '/libraries/lock-swift/lock-swift-custom-fields-at-signup'
},
{
from: ['/libraries/lock-ios/v2/configuration'],
to: '/libraries/lock-swift/lock-swift-configuration-options'
},
{
from: ['/auth0js','/libraries/auth0js/v7','/libraries/auth0js/v8','/libraries/auth0js/v9','/libraries/lock/v10/auth0js','/libraries/lock/v11/auth0js','/libraries/auth0js-v9-reference'],
to: '/libraries/auth0js'
},
{
from: ['/libraries/auth0-android/configuration'],
to: '/libraries/auth0-android/auth0-android-configuration'
},
{
from: ['/libraries/lock-android/v2','/libraries/lock-android/v1','/libraries/lock-android/v1/sending-authentication-parameters','/libraries/lock-android/v1/use-your-own-ui'],
to: '/libraries/lock-android'
},
{
from: ['/libraries/lock-android/v2/custom-authentication-providers','/libraries/lock-android/v2/custom-oauth-connections'],
to: '/libraries/lock-android/lock-android-custom-authentication-providers'
},
{
from: ['/tutorials/local-testing-and-development','/local-testing-and-development'],
to: '/libraries/secure-local-development'
},
{
from: ['/libraries/lock-android/v2/refresh-jwt-tokens','/libraries/lock-android/v1/refresh-jwt-tokens','/libraries/lock-android/refresh-jwt-tokens','/libraries/auth0-android/save-and-refresh-tokens'],
to: '/libraries/lock-android/lock-android-refresh-jwt'
},
{
from: ['/libraries/lock-android/lock-android-delegation'],
to: '/libraries/lock-android/v2/refresh-jwt-tokens'
},
{
from: ['/libraries/lock-android/custom-fields','/libraries/lock-android/v2/custom-fields'],
to: '/libraries/lock-android/lock-android-custom-fields-at-signup'
},
{
from: ['/libraries/auth0-android/passwordless','/libraries/lock-android/passwordless','/connections/passwordless/android-email','/libraries/lock-android/v2/passwordless','/libraries/lock-android/v1/passwordless'],
to: '/libraries/lock-android/lock-android-passwordless'
},
{
from: ['/libraries/lock-android/v2/configuration','/libraries/lock-android/v1/configuration'],
to: '/libraries/lock-android/lock-android-configuration'
},
{
from: ['/libraries/lock-android/v2/delegation-api','/libraries/lock-android/v1/delegation-api'],
to: '/libraries/lock-android/lock-android-delegation'
},
{
from: ['/libraries/lock-android/v2/custom-theming'],
to: '/libraries/lock-android/lock-android-custom-theming'
},
{
from: ['/libraries/lock-android/v2/native-social-authentication','/libraries/lock-android/v1/native-social-authentication'],
to: '/libraries/lock-android/lock-android-native-social-authentication'
},
{
from: ['/libraries/lock-android/v2/passwordless-magic-link','/libraries/lock-android/v1/passwordless-magic-link'],
to: '/libraries/lock-android/lock-android-passwordless-with-magic-link'
},
{
from: ['/libraries/lock-android/v2/keystore','/libraries/lock-android/keystore','/libraries/lock-android/android-development-keystores-hashes'],
to: '/libraries/auth0-android/android-development-keystores-hashes'
},
{
from: ['/libraries/auth0-android/user-management'],
to: '/libraries/auth0-android/auth0-android-user-management'
},
{
from: ['/libraries/auth0-spa-js'],
to: '/libraries/auth0-single-page-app-sdk'
},
{
from: ['/libraries/auth0-android/database-authentication'],
to: '/libraries/auth0-android/auth0-android-database-authentication'
},
{
from: ['/libraries/auth0-spa-js/migrate-from-auth0js'],
to: '/libraries/auth0-single-page-app-sdk/migrate-from-auth0-js-to-the-auth0-single-page-app-sdk'
},
{
from: ['/libraries/auth0-swift/database-authentication'],
to: '/libraries/auth0-swift/auth0-swift-database-connections'
},
{
from: ['/libraries/auth0-swift/passwordless'],
to: '/libraries/auth0-swift/auth0-swift-passwordless'
},
{
from: ['/libraries/auth0-swift/save-and-refresh-jwt-tokens'],
to: '/libraries/auth0-swift/auth0-swift-save-and-renew-tokens'
},
{
from: ['/libraries/auth0-swift/touchid-authentication'],
to: '/libraries/auth0-swift/auth0-swift-touchid-faceid'
},
{
from: ['/libraries/auth0-swift/user-management'],
to: '/libraries/auth0-swift/auth0-swift-user-management'
},
{
from: ['/libraries/auth0-php/authentication-api'],
to: '/libraries/auth0-php/using-the-authentication-api-with-auth0-php'
},
{
from: ['/libraries/auth0-php/basic-use'],
to: '/libraries/auth0-php/auth0-php-basic-use'
},
{
from: ['/libraries/auth0-php/jwt-validation'],
to: '/libraries/auth0-php/validating-jwts-with-auth0-php'
},
{
from: ['/libraries/auth0-php/management-api'],
to: '/libraries/auth0-php/using-the-management-api-with-auth0-php'
},
{
from: ['/libraries/auth0-php/troubleshooting'],
to: '/libraries/auth0-php/troubleshoot-auth0-php-library'
},
/* Login */
{
from: ['/flows/login'],
to: '/login'
},
{
from: ['/login/embedded', '/flows/login/embedded', '/flows/login/embedded-login'],
to: '/login/embedded-login'
},
{
from: ['/cross-origin-authentication', '/flows/login/embedded-login/cross-origin-authentication'],
to: '/login/embedded-login/cross-origin-authentication'
},
{
from: ['/authorization/configure-silent-authentication','/api-auth/tutorials/silent-authentication'],
to: '/login/configure-silent-authentication'
},
{
from: '/flows',
to: '/login/flows'
},
{
from: [
'/flows/guides/auth-code/add-login-auth-code',
'/flows/guides/auth-code/includes/authorize-user-add-login',
'/flows/guides/auth-code/includes/sample-use-cases-add-login',
'/flows/guides/auth-code/includes/refresh-tokens',
'/flows/guides/auth-code/includes/request-tokens',
'/flows/guides/regular-web-app-login-flow/add-login-using-regular-web-app-login-flow',
'/oauth-web-protocol',
'/protocols/oauth-web-protocol',
'/protocols/oauth2/oauth-web-protocol',
'/application-auth/current/server-side-web',
'/client-auth/server-side-web',
'/application-auth/legacy/server-side-web',
'/flows/add-login-auth-code-flow'
],
to: '/login/flows/add-login-auth-code-flow'
},
{
from: [
'/authorization/flows/call-your-api-using-the-authorization-code-flow',
'/flows/guides/auth-code/call-api-auth-code',
'/flows/guides/auth-code/includes/authorize-user-call-api',
'/flows/guides/auth-code/includes/sample-use-cases-call-api',
'/flows/guides/auth-code/includes/call-api',
'/flows/guides/regular-web-app-login-flow/call-api-using-regular-web-app-login-flow',
'/api-auth/tutorials/authorization-code-grant',
'/flows/call-your-api-using-the-authorization-code-flow'
],
to: '/login/flows/call-your-api-using-the-authorization-code-flow'
},
{
from: [
'/flows/guides/auth-code-pkce/add-login-auth-code-pkce',
'/flows/guides/auth-code-pkce/includes/sample-use-cases-add-login',
'/flows/guides/auth-code-pkce/includes/request-tokens',
'/flows/guides/auth-code-pkce/includes/refresh-tokens',
'/flows/guides/auth-code-pkce/includes/create-code-verifier',
'/flows/guides/auth-code-pkce/includes/create-code-challenge',
'/flows/guides/auth-code-pkce/includes/authorize-user-add-login',
'/application-auth/current/mobile-desktop',
'/application-auth/legacy/mobile-desktop',
'/application-auth/legacy/mobile-desktop',
'/flows/guides/mobile-login-flow/add-login-using-mobile-login-flow',
'/flows/add-login-using-the-authorization-code-flow-with-pkce'
],
to: '/login/flows/add-login-using-the-authorization-code-flow-with-pkce'
},
{
from: [
'/flows/guides/auth-code-pkce/call-api-auth-code-pkce',
'/flows/guides/auth-code-pkce/includes/sample-use-cases-call-api',
'/flows/guides/auth-code-pkce/includes/call-api',
'/flows/guides/auth-code-pkce/includes/authorize-user-call-api',
'/flows/guides/mobile-login-flow/call-api-using-mobile-login-flow',
'/api-auth/tutorials/authorization-code-grant-pkce',
'/flows/call-your-api-using-the-authorization-code-flow-with-pkce'
],
to: '/login/flows/call-your-api-using-the-authorization-code-flow-with-pkce'
},
{
from: [
'/flows/guides/implicit/add-login-implicit',
'/flows/guides/implicit/includes/sample-use-cases-add-login',
'/flows/guides/implicit/includes/refresh-tokens',
'/flows/guides/implicit/includes/request-tokens',
'/flows/guides/implicit/includes/authorize-user-add-login',
'/application-auth/current/client-side-web',
'/flows/guides/single-page-login-flow/add-login-using-single-page-login-flow',
'/client-auth/client-side-web','/application-auth/legacy/client-side-web',
'/flows/add-login-using-the-implicit-flow-with-form-post'
],
to: '/login/flows/add-login-using-the-implicit-flow-with-form-post'
},
{
from: ['/api-auth/tutorials/hybrid-flow','/flows/call-api-hybrid-flow'],
to: '/login/flows/call-api-hybrid-flow'
},
{
from: [
'/flows/guides/client-credentials/call-api-client-credentials',
'/flows/guides/client-credentials/includes/sample-use-cases',
'/flows/guides/client-credentials/includes/call-api',
'/flows/guides/client-credentials/includes/request-token',
'/flows/guides/m2m-flow/call-api-using-m2m-flow',
'/api-auth/tutorials/client-credentials',
'/api-auth/config/asking-for-access-tokens',
'/flows/call-your-api-using-the-client-credentials-flow'
],
to: '/login/flows/call-your-api-using-the-client-credentials-flow'
},
{
from: ['/flows/guides/device-auth/call-api-device-auth'],
to: '/login/flows/call-your-api-using-the-device-authorization-flow'
},
{
from: ['/flows/call-your-api-using-resource-owner-password-flow','/api-auth/tutorials/password-grant'],
to: '/login/flows/call-your-api-using-resource-owner-password-flow'
},
/* Logout */
{
from: ['/logout/log-users-out-of-applications','/logout/guides/logout-applications'],
to: '/login/logout/log-users-out-of-applications'
},
{
from: ['/logout/log-users-out-of-auth0','/logout/guides/logout-auth0'],
to: '/login/logout/log-users-out-of-auth0'
},
{
from: ['/logout/log-users-out-of-idps','/logout/guides/logout-idps'],
to: '/login/logout/log-users-out-of-idps'
},
{
from: ['/logout/log-users-out-of-saml-idps','/protocols/saml/saml-configuration/logout','/logout/guides/logout-saml-idps'],
to: '/login/logout/log-users-out-of-saml-idps'
},
{
from: ['/logout/redirect-users-after-logout','/logout/guides/redirect-users-after-logout'],
to: '/login/logout/redirect-users-after-logout'
},
/* Monitor - Logs */
{
from: ['/logs','/logs/concepts/logs-admins-devs'],
to: '/monitor-auth0/logs'
},
{
from: ['/logs/pii-in-logs','/logs/personally-identifiable-information-pii-in-auth0-logs'],
to: '/monitor-auth0/logs/pii-in-logs'
},
{
from: ['/logs/log-data-retention','/logs/references/log-data-retention'],
to: '/monitor-auth0/logs/log-data-retention'
},
{
from: ['/logs/view-log-events','/logs/guides/view-log-data-dashboard','/logs/view-log-events-in-the-dashboard'],
to: '/monitor-auth0/logs/view-log-events'
},
{
from: ['/logs/log-event-filters','/logs/references/log-event-filters'],
to: '/monitor-auth0/logs/log-event-filters'
},
{
from: ['/logs/retrieve-log-events-using-mgmt-api','/logs/guides/retrieve-logs-mgmt-api'],
to: '/monitor-auth0/logs/retrieve-log-events-using-mgmt-api'
},
{
from: ['/logs/log-event-type-codes','/logs/references/log-event-data','/logs/references/log-events-data','/logs/references/log-event-type-codes'],
to: '/monitor-auth0/logs/log-event-type-codes'
},
{
from: ['/logs/log-search-query-syntax','/logs/references/query-syntax','/logs/query-syntax'],
to: '/monitor-auth0/logs/log-search-query-syntax'
},
{
from: [
'/monitoring/guides/send-events-to-splunk',
'/monitoring/guides/send-events-to-keenio',
'/monitoring/guides/send-events-to-segmentio',
'/logs/export-log-events-with-rules'
],
to: '/monitor-auth0/logs/export-log-events-with-rules'
},
{
from: ['/logs/export-log-events-with-log-streaming','/logs/streams'],
to: '/monitor-auth0/streams'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-http-event-logs',
'/logs/streams/http-event',
'/logs/streams/stream-http-event-logs'
],
to: '/monitor-auth0/streams/custom-log-streams'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-log-events-to-slack',
'/logs/streams/http-event-to-slack'
],
to: '/monitor-auth0/streams/stream-log-events-to-slack'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-logs-to-splunk',
'/logs/streams/splunk',
'/logs/streams/stream-logs-to-splunk',
'/monitor-auth0/streams/stream-logs-to-splunk'
],
to: 'https://marketplace.auth0.com/integrations/splunk-log-streaming'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-logs-to-amazon-eventbridge',
'/logs/streams/aws-eventbridge',
'/integrations/aws-eventbridge',
'/logs/streams/amazon-eventbridge',
'/logs/streams/stream-logs-to-amazon-eventbridge',
'/monitor-auth0/streams/stream-logs-to-amazon-eventbridge'
],
to: 'https://marketplace.auth0.com/integrations/amazon-log-streaming'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-logs-to-azure-event-grid',
'/logs/streams/azure-event-grid',
'/logs/streams/stream-logs-to-azure-event-grid',
'/monitor-auth0/streams/stream-logs-to-azure-event-grid'
],
to: 'https://marketplace.auth0.com/integrations/azure-log-streaming'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-logs-to-datadog',
'/logs/streams/datadog',
'/logs/streams/stream-logs-to-datadog',
'/monitor-auth0/streams/stream-logs-to-datadog'
],
to: 'https://marketplace.auth0.com/integrations/datadog-log-streaming'
},
{
from: [
'/logs/export-log-events-with-log-streaming/datadog-dashboard-templates',
'/logs/streams/datadog-dashboard-templates'
],
to: '/monitor-auth0/streams/datadog-dashboard-templates'
},
{
from: ['/logs/streams/event-filters'],
to: '/monitor-auth0/streams/event-filters'
},
{
from: [
'/logs/export-log-events-with-log-streaming/splunk-dashboard',
'/logs/streams/splunk-dashboard'
],
to: '/monitor-auth0/streams/splunk-dashboard'
},
{
from: ['/logs/streams/stream-logs-to-sumo-logic'],
to: '/monitor-auth0/streams/stream-logs-to-sumo-logic'
},
{
from: ['/logs/streams/sumo-logic-dashboard'],
to: '/monitor-auth0/streams/sumo-logic-dashboard'
},
/* MFA */
{
from: ['/multi-factor-authentication','/multi-factor-authentication2','/multifactor-authentication/custom-provider','/multifactor-authentication','/mfa-in-auth0','/multifactor-authentication/yubikey','/multifactor-authentication/guardian','/multifactor-authentication/guardian/user-guide','/multi-factor-authentication/yubikey'],
to: '/mfa'
},
{
from: ['/mfa/configure-webauthn-with-security-keys-for-mfa'],
to: '/mfa/configure-webauthn-security-keys-for-mfa'
},
{
from: ['/multifactor-authentication/api', '/multifactor-authentication/api/faq','/mfa/concepts/mfa-api'],
to: '/mfa/mfa-api'
},
{
from: ['/api-auth/tutorials/multifactor-resource-owner-password','/mfa/guides/mfa-api/authenticate','/mfa/guides/mfa-api/multifactor-resource-owner-password'],
to: '/mfa/authenticate-with-ropg-and-mfa'
},
{
from: ['/mfa/guides/mfa-api/manage','/multifactor-authentication/api/manage'],
to: '/mfa/authenticate-with-ropg-and-mfa/manage-authenticator-factors-mfa-api'
},
{
from: ['/mfa/guides/mfa-api/phone','/multifactor-authentication/api/oob','/mfa/guides/mfa-api/oob'],
to: '/mfa/authenticate-with-ropg-and-mfa/enroll-challenge-sms-voice-authenticators'
},
{
from: ['/mfa/guides/mfa-api/push'],
to: '/mfa/authenticate-with-ropg-and-mfa/enroll-and-challenge-push-authenticators'
},
{
from: ['/multifactor-authentication/api/otp','/mfa/guides/mfa-api/otp','/multifactor-authentication/google-authenticator'],
to: '/mfa/authenticate-with-ropg-and-mfa/enroll-and-challenge-otp-authenticators'
},
{
from: ['/multifactor-authentication/api/email','/mfa/guides/mfa-api/email','/multifactor-authentication/administrator/guardian-enrollment-email'],
to: '/mfa/authenticate-with-ropg-and-mfa/enroll-and-challenge-email-authenticators'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-amazon-sns','/mfa/send-phone-message-hook-amazon-sns'],
to: '/mfa/configure-amazon-sns-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-esendex','/mfa/send-phone-message-hook-esendex'],
to: '/mfa/configure-esendex-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-infobip','/mfa/send-phone-message-hook-infobip'],
to: '/mfa/configure-infobip-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-mitto','/mfa/send-phone-message-hook-mitto'],
to: '/mfa/configure-mitto-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-telesign','/mfa/send-phone-message-hook-telesign'],
to: '/mfa/configure-telesign-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-twilio','/mfa/send-phone-message-hook-twilio'],
to: '/mfa/configure-twilio-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-vonage','/mfa/send-phone-message-hook-vonage'],
to: '/mfa/configure-vonage-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/factors','/mfa/concepts/mfa-factors'],
to: '/mfa/mfa-factors'
},
{
from: ['/multifactor-authentication/factors/duo','/multifactor-authentication/duo','/multifactor-authentication/duo/admin-guide','/mfa/guides/configure-cisco-duo','/multifactor-authentication/duo/dev-guide','/multifactor-authentication/duo/user-guide'],
to: '/mfa/configure-cisco-duo-for-mfa'
},
{
from: ['/multifactor-authentication/factors/otp','/mfa/guides/configure-otp'],
to: '/mfa/configure-otp-notifications-for-mfa'
},
{
from: ['/mfa/guides/configure-email-universal-login','/multifactor-authentication/factors/email','/mfa/guides/configure-email'],
to: '/mfa/configure-email-notifications-for-mfa'
},
{
from: ['/multifactor-authentication/developer/sns-configuration','/multifactor-authentication/factors/push','/mfa/guides/configure-push','/multifactor-authentication/administrator/push-notifications'],
to: '/mfa/configure-push-notifications-for-mfa'
},
{
from: ['/multifactor-authentication/administrator/twilio-configuration','/multifactor-authentication/administrator/sms-notifications','/multifactor-authentication/twilio-configuration','/multifactor-authentication/factors/sms','/mfa/guides/configure-sms','/mfa/guides/configure-phone'],
to: '/mfa/configure-sms-voice-notifications-mfa'
},
{
from: ['/multifactor-authentication/google-auth/admin-guide','/multifactor-authentication/google-auth/user-guide','/multifactor-authentication/troubleshooting','/mfa/references/troubleshoot-mfa','/mfa/references/troubleshooting'],
to: '/mfa/troubleshoot-mfa-issues'
},
{
from: ['/multifactor-authentication/developer/step-up-authentication','/step-up-authentication','/tutorials/step-up-authentication','/tutorials/setup-up-authentication','/multifactor-authentication/step-up-authentication','/mfa/concepts/step-up-authentication','/multifactor-authentication/developer/step-up-with-acr'],
to: '/mfa/step-up-authentication'
},
{
from: ['/multifactor-authentication/api/challenges','/multifactor-authentication/developer/step-up-authentication/step-up-for-apis','/multifactor-authentication/step-up-authentication/step-up-for-apis','/mfa/guides/configure-step-up-apis'],
to: '/mfa/step-up-authentication/configure-step-up-authentication-for-apis'
},
{
from: ['/multifactor-authentication/developer/step-up-authentication/step-up-for-web-apps','/multifactor-authentication/step-up-authentication/step-up-for-web-apps','/mfa/guides/configure-step-up-web-apps'],
to: '/mfa/step-up-authentication/configure-step-up-authentication-for-web-apps'
},
{
from: ['/multifactor-authentication/reset-user','/multifactor-authentication/administrator/reset-user','/mfa/guides/reset-user-mfa','/multifactor-authentication/administrator/disabling-mfa'],
to: '/mfa/reset-user-mfa'
},
{
from: ['/mfa/concepts/guardian','/multifactor-authentication/guardian/dev-guide','/multifactor-authentication/guardian/admin-guide'],
to: '/mfa/auth0-guardian'
},
{
from: ['/multifactor-authentication/developer/custom-enrollment-ticket','/mfa/guides/guardian/create-enrollment-ticket'],
to: '/mfa/auth0-guardian/create-custom-enrollment-tickets'
},
{
from: ['/multifactor-authentication/developer/libraries/ios','/mfa/guides/guardian/guardian-ios-sdk','/mfa/guides/guardian/configure-guardian-ios'],
to: '/mfa/auth0-guardian/guardian-for-ios-sdk'
},
{
from: ['/multifactor-authentication/developer/libraries/android','/mfa/guides/guardian/guardian-android-sdk'],
to: '/mfa/auth0-guardian/guardian-for-android-sdk'
},
{
from: ['/mfa/guides/guardian/install-guardian-sdk'],
to: '/mfa/auth0-guardian/install-guardian-sdk'
},
{
from: ['/mfa/references/guardian-error-code-reference'],
to: '/mfa/auth0-guardian/guardian-error-code-reference'
},
{
from: ['/mfa/guides/import-user-mfa'],
to: '/mfa/import-user-mfa-authenticator-enrollments'
},
{
from: ['/mfa/concepts/mfa-developer-resources','/multifactor-authentication/developer','/mfa/concepts/developer-resources'],
to: '/mfa/mfa-developer-resources'
},
{
from: ['/mfa/guides/enable-mfa'],
to: '/mfa/enable-mfa'
},
{
from: ['/multifactor-authentication/custom','/mfa/guides/customize-mfa-universal-login','/multifactor-authentication/google-auth/dev-guide'],
to: '/mfa/customize-mfa-user-pages'
},
{
from: ['/mfa/guides/mfa-api/recovery-code'],
to: '/mfa/authenticate-with-ropg-and-mfa/manage-authenticator-factors-mfa-api/challenge-with-recovery-codes'
},
{
from: ['/mfa/references/language-dictionary'],
to: '/mfa/customize-mfa-user-pages/mfa-theme-language-dictionary'
},
{
from: ['/mfa/references/mfa-widget-reference'],
to: '/mfa/customize-mfa-user-pages/mfa-widget-theme-options'
},
/* Monitoring */
{
from: ['/monitoring','/tutorials/how-to-monitor-auth0','/monitoring/how-to-monitor-auth0'],
to: '/monitor-auth0'
},
{
from: ['/monitoring/guides/check-external-services'],
to: '/monitor-auth0/check-external-services-status'
},
{
from: ['/monitoring/guides/check-status'],
to: '/monitor-auth0/check-auth0-status'
},
{
from: ['/monitoring/guides/monitor-applications'],
to: '/monitor-auth0/monitor-applications'
},
{
from: ['/monitoring/guides/monitor-using-SCOM'],
to: '/monitor-auth0/monitor-using-scom'
},
/* Policies */
{
from: ['/policies/billing'],
to: '/policies/billing-policy'
},
{
from: ['/policies/endpoints','/security/public-cloud-service-endpoints'],
to: '/policies/public-cloud-service-endpoints'
},
{
from: ['/policies/dashboard-authentication','/policies/restore-deleted-tenant','/policies/unsupported-requests'],
to: '/policies'
},
{
from: ['/policies/data-export','/policies/data-transfer'],
to: '/policies/data-export-and-transfer-policy'
},
{
from: ['/policies/entity-limits','/policies/global-limit'],
to: '/policies/entity-limit-policy'
},
{
from: ['/policies/load-testing'],
to: '/policies/load-testing-policy'
},
{
from: [
'/rate-limits',
'/policies/rate-limit',
'/policies/rate-limits',
'/policies/legacy-rate-limits'
],
to: '/policies/rate-limit-policy'
},
{
from: [
'/policies/rate-limit-policy/authentication-api-endpoint-rate-limits',
'/policies/rate-limits-auth-api',
'/policies/rate-limits-api'
],
to: '/policies/authentication-api-endpoint-rate-limits'
},
{
from: [
'/policies/rate-limit-policy/mgmt-api-endpoint-rate-limits-before-19-may-2020',
'/policies/rate-limit-policy/management-api-endpoint-rate-limits',
'/policies/rate-limits-mgmt-api'
],
to: '/policies/management-api-endpoint-rate-limits'
},
{
from: ['/policies/penetration-testing'],
to: '/policies/penetration-testing-policy'
},
{
from: ['/policies/rate-limit-policy/database-connections-rate-limits','/connections/database/rate-limits'],
to: '/policies/database-connections-rate-limits'
},
/* Product-Lifecycle */
{
from: '/lifecycle',
to: '/product-lifecycle'
},
{
from: ['/product-lifecycle/deprecation-eol'],
to: '/product-lifecycle/migration-process'
},
{
from: ['/product-lifecycle/migrations','/migrations'],
to: '/product-lifecycle/deprecations-and-migrations'
},
{
from: ['/migrations/guides/account-linking','/users/guides/link-user-accounts-auth-api'],
to: '/product-lifecycle/deprecations-and-migrations/link-user-accounts-with-access-tokens-migration'
},
{
from: ['/migrations/guides/calling-api-with-idtokens'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-calling-api-with-access-tokens'
},
{
from: ['/guides/login/migration-embedded-universal','/guides/login/migration-embedded-centralized','/guides/login/migrating-lock-v10-webapp','/guides/login/migrating-lock-v9-spa','/guides/login/migrating-lock-v9-spa-popup','/guides/login/migrating-lock-v9-webapp','/guides/login/migrating-lock-v10-spa','/guides/login/migrating-lock-v8','/guides/login/migration-sso'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-from-embedded-login-to-universal-login'
},
{
from: ['/guides/migration-legacy-flows'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-from-legacy-auth-flows'
},
{
from: ['/migrations/guides/clickjacking-protection'],
to: '/product-lifecycle/deprecations-and-migrations/clickjacking-protection-for-universal-login'
},
{
from: ['/migrations/guides/extensibility-node12'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-nodejs-12'
},
{
from: ['/migrations/guides/facebook-graph-api-deprecation'],
to: '/product-lifecycle/deprecations-and-migrations/facebook-graph-api-changes'
},
{
from: ['/migrations/guides/facebook-social-context'],
to: '/product-lifecycle/deprecations-and-migrations/facebook-social-context-field-deprecation'
},
{
from: ['/migrations/guides/google_cloud_messaging'],
to: '/product-lifecycle/deprecations-and-migrations/google-firebase-migration'
},
{
from: ['/migrations/guides/instagram-deprecation'],
to: '/product-lifecycle/deprecations-and-migrations/instagram-connection-deprecation'
},
{
from: [
'/product-lifecycle/deprecations-and-migrations/migrate-to-management-api-v2',
'/api/management-api-v1-deprecated',
'/api/management-api-changes-v1-to-v2',
'/migrations/guides/management-api-v1-v2',
'/api/management/v1/use-cases',
'/api/v1'
],
to: '/product-lifecycle/deprecations-and-migrations/past-migrations'
},
{
from: ['/migrations/guides/migration-oauthro-oauthtoken'],
to: '/product-lifecycle/deprecations-and-migrations/migration-oauthro-oauthtoken'
},
{
from: ['/migrations/guides/migration-oauthro-oauthtoken-pwdless'],
to: '/product-lifecycle/deprecations-and-migrations/resource-owner-passwordless-credentials-exchange'
},
{
from: ['/migrations/guides/passwordless-start'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-passwordless'
},
{
from: ['/migrations/guides/unpaginated-requests'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-paginated-queries'
},
{
from: ['/migrations/guides/yahoo-userinfo-updates'],
to: '/product-lifecycle/deprecations-and-migrations/yahoo-api-changes'
},
{
from: ['/migrations/past-migrations'],
to: '/product-lifecycle/deprecations-and-migrations/past-migrations'
},
{
from: ['/logs/guides/migrate-logs-v2-v3'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-tenant-log-search-v3'
},
{
from: ['/deprecations-and-migrations/migrate-tenant-member-roles'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-tenant-member-roles'
},
/* Professional Services */
{
from: ['/services','/auth0-professional-services','/services/auth0-advanced','/services/auth0-introduction','/services/discover-and-design','/services/maintain-and-improve'],
to: '/professional-services'
},
{
from: ['/services/architectural-design','/professional-services/architectural-design-services','/professional-services/solution-design-services','/services/solution-design'],
to: '/professional-services/discover-design'
},
{
from: ['/professional-services/custom-implementation-services','/services/custom-implementation','/services/implement'],
to: '/professional-services/implement'
},
{
from: ['/services/performance-scalability','/professional-services/performance-and-scalability-services','/professional-services/advisory-sessions','/services/scenario-guidance','/services/code-review','/services/pair-programming'],
to: '/professional-services/maintain-improve'
},
{
from: ['/services/packages'],
to: '/professional-services/packages'
},
/* Protocols */
{
from: ['/tutorials/openid-connect-discovery','/protocols/oidc/openid-connect-discovery','/oidc-rs256-owin'],
to: '/protocols/configure-applications-with-oidc-discovery'
},
{
from: ['/protocols/oidc/identity-providers/okta','/protocols/configure-okta-as-oidc-identity-provider'],
to: '/protocols/configure-okta-as-oauth2-identity-provider'
},
{
from: ['/integrations/configure-wsfed-application','/tutorials/configure-wsfed-application'],
to: '/protocols/configure-ws-fed-applications'
},
{
from: ['/protocols/oauth2/oauth-state','/protocols/oauth-state','/protocols/oauth2/mitigate-csrf-attacks'],
to: '/protocols/state-parameters'
},
{
from: ['/protocols/oauth2'],
to: '/protocols/protocol-oauth2'
},
{
from: ['/protocols/oidc','/api-auth/intro','/api-auth/tutorials/adoption'],
to: '/protocols/openid-connect-protocol'
},
{
from: ['/protocols/ws-fed','/tutorials/wsfed-web-app','/wsfedwebapp-tutorial'],
to: '/protocols/ws-fed-protocol'
},
{
from: ['/protocols/ldap'],
to: '/protocols/ldap-protocol'
},
/* Rules */
{
from: ['/rules/current', '/rules/current/csharp', '/rules/guides/csharp', '/rules/legacy', '/rules/references/legacy','/rules/references/modules','/rule'],
to: '/rules'
},
{
from: ['/rules/guides/automatically-generate-leads-in-shopify','/rules/guides/automatically-generate-leads-shopify'],
to: '/rules/automatically-generate-leads-in-shopify'
},
{
from: ['/rules/guides/cache-resources','/rules/cache-expensive-resources-in-rules'],
to: '/rules/cache-resources'
},
{
from: ['/rules/guides/configuration'],
to: '/rules/configuration'
},
{
from: ['/dashboard/guides/rules/configure-variables'],
to: '/rules/configure-global-variables-for-rules'
},
{
from: ['/rules/current/context', '/rules/context', '/rules/references/context-object','/rules/context-prop-authentication'],
to: '/rules/context-object'
},
{
from: ['/api/management/guides/rules/create-rules', '/dashboard/guides/rules/create-rules','/rules/guides/create'],
to: '/rules/create-rules'
},
{
from: ['/rules/guides/debug'],
to: '/rules/debug-rules'
},
{
from: ['/rules/references/samples'],
to: '/rules/examples'
},
{
from: [
'/rules/guides/integrate-user-id-verification',
'/rules/integrate-user-id-verification'
],
to: 'https://marketplace.auth0.com/integrations/onfido-identity-verification'
},
{
from: '/rules/guides/integrate-efm-solutions',
to: '/rules/integrate-efm-solutions'
},
{
from: '/rules/guides/integrate-erfm-solutions',
to: '/rules/integrate-erfm-solutions'
},
{
from: '/rules/guides/integrate-hubspot',
to: '/rules/integrate-hubspot'
},
{
from: '/rules/guides/integrate-maxmind',
to: '/rules/integrate-maxmind'
},
{
from: '/rules/guides/integrate-mixpanel',
to: '/rules/integrate-mixpanel'
},
{
from: '/rules/guides/integrate-salesforce',
to: '/rules/integrate-salesforce'
},
{
from: ['/rules/current/redirect', '/rules/redirect', '/rules/guides/redirect'],
to: '/rules/redirect-users'
},
{
from: ['/rules/references/use-cases'],
to: '/rules/use-cases'
},
{
from: ['/rules/current/management-api', '/rules/guides/management-api'],
to: '/rules/use-management-api'
},
{
from: ['/rules/references/user-object'],
to: '/rules/user-object-in-rules'
},
{
from: [
'/monitoring/guides/track-leads-salesforce',
'/tutorials/tracking-new-leads-in-salesforce-and-raplead',
'/scenarios-rapleaf-salesforce',
'/scenarios/rapleaf-salesforce',
'/monitor-auth0/track-new-leads-in-salesforce'
],
to: '/rules/use-cases/track-new-leads-in-salesforce'
},
{
from: [
'/monitoring/guides/track-signups-salesforce',
'/tutorials/track-signups-enrich-user-profile-generate-leads',
'/scenarios-mixpanel-fullcontact-salesforce',
'/scenarios/mixpanel-fullcontact-salesforce',
'/monitor-auth0/track-new-sign-ups-in-salesforce'
],
to: '/rules/use-cases/track-new-sign-ups-in-salesforce'
},
/* Scopes */
{
from: ['/scopes/current','/scopes/legacy','/scopes/preview'],
to: '/scopes'
},
{
from: ['/scopes/current/api-scopes'],
to: '/scopes/api-scopes'
},
{
from: ['/scopes/current/oidc-scopes','/api-auth/tutorials/adoption/scope-custom-claims','/scopes/oidc-scopes'],
to: '/scopes/openid-connect-scopes'
},
{
from: ['/scopes/current/sample-use-cases'],
to: '/scopes/sample-use-cases-scopes-and-claims'
},
/* Security */
{
from: ['/security/general-security-tips'],
to: '/security/tips'
},
{
from: [
'/security/blacklist-user-attributes',
'/security/blacklisting-attributes',
'/tutorials/blacklisting-attributes',
'/blacklist-attributes',
'/security/denylist-user-attributes'
],
to: '/security/data-security/denylist'
},
{
from: [
'/security/whitelist-ip-addresses',
'/guides/ip-whitelist',
'/security/allowlist-ip-addresses'
],
to: '/security/data-security/allowlist'
},
{
from: [
'/users/normalized/auth0/store-user-data',
'/users/store-user-data',
'/users/references/user-data-storage-scenario',
'/users/user-data-storage-scenario',
'/best-practices/user-data-storage-best-practices',
'/users/references/user-data-storage-best-practices',
'/users/user-data-storage',
'/user-profile/user-data-storage'
],
to: '/security/data-security/user-data-storage'
},
{
from: [
'/tokens/concepts/token-storage',
'/videos/session-and-cookies',
'/security/store-tokens',
'/tokens/guides/store-tokens',
'/tokens/token-storage'
],
to: '/security/data-security/token-storage'
},
{
from: ['/security/common-threats','/security/prevent-common-cybersecurity-threats'],
to: '/security/prevent-threats'
},
/* Security Bulletins */
{
from: ['/security/bulletins'],
to: '/security/security-bulletins'
},
{
from: ['/security/bulletins/cve-2020-15259','/security/cve-2020-15259'],
to: '/security/security-bulletins/cve-2020-15259'
},
{
from: ['/security/bulletin/cve-2020-15240', '/security/cve-2020-15240'],
to: '/security/security-bulletins/cve-2020-15240'
},
{
from: ['/security/bulletins/cve-2020-15125','/security/cve-2020-15125'],
to: '/security/security-bulletins/cve-2020-15125'
},
{
from: ['/security/bulletins/cve-2020-15084','/security/cve-2020-15084'],
to: '/security/security-bulletins/cve-2020-15084'
},
{
from: ['/security/bulletins/2020-03-31_wpauth0','/security/2020-03-31-wpauth0'],
to: '/security/security-bulletins/2020-03-31-wpauth0'
},
{
from: ['/security/bulletins/cve-2020-5263','/security/cve-2020-5263'],
to: '/security/security-bulletins/cve-2020-5263'
},
{
from: ['/security/bulletins/2019-01-10_rules','/security/2019-01-10-rules'],
to: '/security/security-bulletins/2019-01-10-rules'
},
{
from: ['/security/bulletins/2019-09-05_scopes','/security/2019-09-05-scopes'],
to: '/security/security-bulletins/2019-09-05-scopes'
},
{
from: ['/security/bulletins/cve-2019-20174','/security/cve-2019-20174'],
to: '/security/security-bulletins/cve-2019-20174'
},
{
from: ['/security/bulletins/cve-2019-20173','/security/cve-2019-20173'],
to: '/security/security-bulletins/cve-2019-20173'
},
{
from: ['/security/bulletins/cve-2019-16929','/security/cve-2019-16929'],
to: '/security/security-bulletins/cve-2019-16929'
},
{
from: ['/security/bulletins/cve-2019-13483','/security/cve-2019-13483'],
to: '/security/security-bulletins/cve-2019-13483'
},
{
from: ['/security/bulletins/cve-2019-7644','/security/cve-2019-7644'],
to: '/security/security-bulletins/cve-2019-7644'
},
{
from: ['/security/bulletins/cve-2018-15121','/security/cve-2018-15121'],
to: '/security/security-bulletins/cve-2018-15121'
},
{
from: ['/security/bulletins/cve-2018-11537','/security/cve-2018-11537'],
to: '/security/security-bulletins/cve-2018-11537'
},
{
from: ['/security/bulletins/cve-2018-7307','/security/cve-2018-7307'],
to: '/security/security-bulletins/cve-2018-7307'
},
{
from: ['/security/bulletins/cve-2018-6874','/security/cve-2018-6874'],
to: '/security/security-bulletins/cve-2018-6874'
},
{
from: ['/security/bulletins/cve-2018-6873','/security/cve-2018-6873'],
to: '/security/security-bulletins/cve-2018-6873'
},
{
from: ['/security/bulletins/cve-2017-16897','/security/cve-2017-16897'],
to: '/security/security-bulletins/cve-2017-16897'
},
{
from: ['/security/bulletins/cve-2017-17068','/security/cve-2017-17068'],
to: '/security/security-bulletins/cve-2017-17068'
},
/* Sessions */
{
from: ['/sessions-and-cookies', '/sessions/concepts/session', '/sessions/concepts/session-lifetime','/sessions/references/sample-use-cases-sessions', '/sessions-and-cookies/session-use-cases'],
to: '/sessions'
},
{
from: ['/sessions/concepts/session-layers'],
to: '/sessions/session-layers'
},
{
from: ['/get-started/dashboard/configure-session-lifetime-settings','/dashboard/guides/tenants/configure-session-lifetime-settings','/api/management/guides/tenants/configure-session-lifetime-settings','/sso/current/configure-session-lifetime-limits'],
to: '/sessions/configure-session-lifetime-settings'
},
{
from: ['/sessions/concepts/cookie-attributes', '/sessions-and-cookies/samesite-cookie-attribute-changes'],
to: '/sessions/cookies/samesite-cookie-attribute-changes'
},
{
from: ['/sessions/references/example-short-lived-session-mgmt', '/sessions-and-cookies/manage-multi-site-short-long-lived-sessions'],
to: '/sessions/manage-multi-site-sessions'
},
{
from: ['/sessions/concepts/cookies', '/sessions-and-cookies/cookies'],
to: '/sessions/cookies'
},
{
from: [
'/sessions/spa-authenticate-with-cookies',
'/login/spa/authenticate-with-cookies',
'/sessions-and-cookies/spa-authenticate-with-cookies'
],
to: '/sessions/cookies/spa-authenticate-with-cookies'
},
/* Support */
{
from: ['/policies/requests','/premium-support'],
to: '/support'
},
{
from: ['/sla', '/support/sla','/support/sld'],
to: '/support/services-level-descriptions'
},
{
from: ['/support/subscription'],
to: '/support/manage-subscriptions'
},
{
from: ['/tutorials/removing-auth0-exporting-data','/support/removing-auth0-exporting-data','/moving-out'],
to: '/support/export-data'
},
{
from: ['/support/cancel-paid-subscriptions','/tutorials/cancel-paid-subscriptions','/cancel-paid-subscriptions'],
to: '/support/downgrade-or-cancel-subscriptions'
},
{
from: ['/support/how-auth0-versions-software','/tutorials/how-auth0-versions-software','/versioning'],
to: '/support/versioning-strategy'
},
{
from: ['/support/matrix'],
to: '/support/product-support-matrix'
},
{
from: ['/support/reset-account-password','/tutorials/reset-account-password'],
to: '/support/reset-account-passwords'
},
{
from: ['/support/tickets'],
to: '/support/open-and-manage-support-tickets'
},
{
from: ['/support/delete-reset-tenant','/tutorials/delete-reset-tenant'],
to: '/support/delete-or-reset-tenant'
},
/* Tokens */
{
from: ['/security/token-exp','/token','/tokens/concepts','/tokens/guides'],
to: '/tokens'
},
{
from: ['/api-auth/tutorials/adoption/api-tokens','/tokens/concepts/access-tokens','/tokens/concepts/access-token','/tokens/overview-access-tokens','/tokens/access-token','/tokens/access_token','/api-auth/why-use-access-tokens-to-secure-apis','/api-auth/asking-for-access-tokens'],
to: '/tokens/access-tokens'
},
{
from: ['/tokens/guides/get-access-tokens','/tokens/get-access-tokens', '/tokens/guides/access-token/get-access-tokens'],
to: '/tokens/access-tokens/get-access-tokens'
},
{
from: ['/tokens/guides/use-access-tokens','/tokens/use-access-tokens', '/tokens/guides/access-token/use-access-tokens'],
to: '/tokens/access-tokens/use-access-tokens'
},
{
from: ['/tokens/guides/validate-access-tokens', '/api-auth/tutorials/verify-access-token', '/tokens/guides/access-token/validate-access-token'],
to: '/tokens/access-tokens/validate-access-tokens'
},
{
from: ['/tokens/guides/create-namespaced-custom-claims','/tokens/concepts/claims-namespacing'],
to: '/tokens/create-namespaced-custom-claims'
},
{
from: ['/tokens/concepts/idp-access-tokens', '/tokens/overview-idp-access-tokens','/tokens/idp'],
to: '/tokens/identity-provider-access-tokens'
},
{
from: ['/tokens/overview-id-tokens','/tokens/id-token', '/tokens/concepts/id-tokens','/tokens/id_token'],
to: '/tokens/id-tokens'
},
{
from: ['/tokens/guides/id-token/get-id-tokens', '/tokens/guides/get-id-tokens'],
to: '/tokens/id-tokens/get-id-tokens'
},
{
from: ['/tokens/references/id-token-structure'],
to: '/tokens/id-tokens/id-token-structure'
},
{
from: ['/tokens/guides/validate-id-token','/tokens/guides/validate-id-tokens','/tokens/guides/id-token/validate-id-token'],
to: '/tokens/id-tokens/validate-id-tokens'
},
{
from: ['/tokens/concepts/jwts', '/tokens/concepts/why-use-jwt','/tokens/jwt','/jwt'],
to: '/tokens/json-web-tokens'
},
{
from: ['/tokens/jwks', '/jwks','/tokens/concepts/jwks'],
to: '/tokens/json-web-tokens/json-web-key-sets'
},
{
from: ['/tokens/references/jwks-properties', '/tokens/reference/jwt/jwks-properties'],
to: '/tokens/json-web-tokens/json-web-key-set-properties'
},
{
from: ['/tokens/guides/locate-jwks', '/tokens/guides/jwt/verify-jwt-signature-using-jwks', '/tokens/guides/jwt/use-jwks'],
to: '/tokens/json-web-tokens/json-web-key-sets/locate-json-web-key-sets'
},
{
from: ['/tokens/jwt-claims', '/tokens/concepts/jwt-claims','/tokens/add-custom-claims','/scopes/current/custom-claims'],
to: '/tokens/json-web-tokens/json-web-token-claims'
},
{
from: ['/tokens/references/jwt-structure','/tokens/reference/jwt/jwt-structure'],
to: '/tokens/json-web-tokens/json-web-token-structure'
},
{
from: ['/tokens/guides/validate-jwts', '/tokens/guides/jwt/parse-validate-jwt-programmatically', '/tokens/guides/jwt/validate-jwt'],
to: '/tokens/json-web-tokens/validate-json-web-tokens'
},
{
from: ['/api-auth/tutorials/adoption/refresh-tokens','/refresh-token','/tokens/refresh_token','/tokens/refresh-token','/tokens/refresh-token/legacy','/tokens/refresh-token/current','/tokens/concepts/refresh-tokens','/tokens/access-tokens/refresh-tokens','/tokens/preview/refresh-token'],
to: '/tokens/refresh-tokens'
},
{
from: ['/tokens/guides/configure-refresh-token-rotation'],
to: '/tokens/refresh-tokens/configure-refresh-token-rotation'
},
{
from: ['/tokens/guides/disable-refresh-token-rotation','/tokens/access-tokens/refresh-tokens/disable-refresh-token-rotation'],
to: '/tokens/refresh-tokens/disable-refresh-token-rotation'
},
{
from: ['/tokens/guides/get-refresh-tokens'],
to: '/tokens/refresh-tokens/get-refresh-tokens'
},
{
from: ['/tokens/concepts/refresh-token-rotation','/tokens/access-tokens/refresh-tokens/refresh-token-rotation'],
to: '/tokens/refresh-tokens/refresh-token-rotation'
},
{
from: ['/tokens/guides/use-refresh-token-rotation', '/tokens/refresh-token-rotation/use-refresh-token-rotation'],
to: '/tokens/refresh-tokens/refresh-token-rotation/use-refresh-token-rotation'
},
{
from: ['/tokens/guides/revoke-refresh-tokens'],
to: '/tokens/refresh-tokens/revoke-refresh-tokens'
},
{
from: ['/tokens/guides/use-refresh-tokens'],
to: '/tokens/refresh-tokens/use-refresh-tokens'
},
{
from: ['/tokens/guides/revoke-tokens'],
to: '/tokens/revoke-tokens'
},
{
from: ['/applications/concepts/signing-algorithms','/tokens/concepts/signing-algorithms'],
to: '/tokens/signing-algorithms'
},
{
from: ['/api-auth/tutorials/adoption/delegation','/tokens/delegation','/tokens/concepts/delegation-tokens'],
to: '/tokens/delegation-tokens'
},
{
from: ['/api/management/v2/get-access-tokens-for-production'],
to: '/tokens/management-api-access-tokens/get-management-api-access-tokens-for-production'
},
{
from: ['/api/management/v2/get-access-tokens-for-spas'],
to: '/tokens/management-api-access-tokens/get-management-api-tokens-for-single-page-applications'
},
{
from: ['/api/management/v2/get-access-tokens-for-test'],
to: '/tokens/management-api-access-tokens/get-management-api-access-tokens-for-testing'
},
{
from: ['/api/management/v2/tokens','/tokens/apiv2', '/api/v2/tokens', '/api/management/v2/concepts/tokens'],
to: '/tokens/management-api-access-tokens'
},
{
from: ['/api/management/v2/tokens-flows'],
to: '/tokens/management-api-access-tokens/changes-in-auth0-management-apiv2-tokens'
},
{
from: ['/dashboard/guides/apis/update-token-lifetime'],
to: '/tokens/access-tokens/update-access-token-lifetime'
},
{
from: ['/dashboard/guides/applications/update-token-lifetime'],
to: '/tokens/id-tokens/update-id-token-lifetime'
},
{
from: ['/api/management/v2/create-m2m-app', '/tokens/management-api-access-tokens/create-and-authorize-a-machine-to-machine-application'],
to: '/config/api-settings/create-m2m-app-test'
},
{
from: ['/api/management/v2/faq-management-api-access-tokens', '/tokens/management-api-access-tokens/management-api-access-token-faqs'],
to: '/tokens/management-api-access-tokens'
},
/* Troubleshoot */
{
from: ['/troubleshoot/basics'],
to: '/troubleshoot'
},
{
from: ['/troubleshoot/guides/check-error-messages', '/troubleshoot/check-error-messages'],
to: '/troubleshoot/troubleshoot-basic/check-error-messages'
},
{
from: [
'/har',
'/tutorials/troubleshooting-with-har-files',
'/troubleshoot/har',
'/support/troubleshooting-with-har-files',
'/troubleshoot/guides/generate-har-files',
'/troubleshoot/generate-and-analyze-har-files'
],
to: '/troubleshoot/tools/generate-and-analyze-har-files'
},
{
from: ['/troubleshoot/references/invalid-token','/troubleshoot/invalid-token-errors'],
to: '/troubleshoot/troubleshoot-basic/invalid-token-errors'
},
{
from: [
'/troubleshoot/concepts/auth-issues',
'/troubleshoot/troubleshoot-authentication-issues'
],
to: '/troubleshoot/troubleshoot-authentication'
},
{
from: [
'/protocols/saml/saml-configuration/troubleshoot/auth0-as-idp',
'/protocols/saml/saml-configuration/troubleshoot',
'/protocols/saml/saml-configuration/troubleshoot/common-saml-errors',
'/protocols/saml/saml-configuration/troubleshoot/auth0-as-sp',
'/troubleshoot/troubleshoot-saml-configurations',
'/protocols/saml-protocol/troubleshoot-saml-configurations'
],
to: '/troubleshoot/troubleshoot-authentication/troubleshoot-saml-configurations'
},
{
from: ['/troubleshoot/guides/check-api-calls', '/troubleshoot/troubleshoot-authentication-issues/check-api-calls'],
to: '/troubleshoot/troubleshoot-authentication/check-api-calls'
},
{
from: [
'/errors/deprecation-errors',
'/troubleshoot/guides/check-deprecation-errors',
'/troubleshoot/troubleshoot-authentication-issues/check-deprecation-errors'],
to: '/troubleshoot/troubleshoot-basic/check-deprecation-errors'
},
{
from: ['/troubleshoot/guides/check-login-logout-issues', '/troubleshoot/troubleshoot-authentication-issues/check-login-and-logout-issues'],
to: '/troubleshoot/troubleshoot-authentication/check-login-and-logout-issues'
},
{
from: ['/troubleshoot/guides/check-user-profiles', '/troubleshoot/troubleshoot-authentication-issues/check-user-profiles'],
to: '/troubleshoot/troubleshoot-authentication/check-user-profiles'
},
{
from: ['/troubleshoot/references/saml-errors', '/troubleshoot/troubleshoot-authentication-issues/saml-errors'],
to: '/troubleshoot/troubleshoot-authentication/saml-errors'
},
{
from: ['/troubleshoot/basic-troubleshooting','/troubleshoot/concepts/basics'],
to: '/troubleshoot/troubleshoot-basic'
},
{
from: ['/troubleshoot/basic-troubleshooting/verify-connections','/troubleshoot/guides/verify-connections'],
to: '/troubleshoot/troubleshoot-basic/verify-connections'
},
{
from: ['/troubleshoot/basic-troubleshooting/verify-domain','/troubleshoot/guides/verify-domain'],
to: '/troubleshoot/troubleshoot-basic/verify-domain'
},
{
from: ['/troubleshoot/basic-troubleshooting/verify-platform','/troubleshoot/guides/verify-platform'],
to: '/troubleshoot/troubleshoot-basic/verify-platform'
},
{
from: ['/troubleshoot/concepts/integration-extensibility-issues'],
to: '/troubleshoot/troubleshoot-integration-and-extensibility'
},
{
from: ['/custom-domains/troubleshoot-custom-domains','/custom-domains/troubleshoot'],
to: '/troubleshoot/troubleshoot-integrations-and-extensibility/troubleshoot-custom-domains'
},
{
from: [
'/connector/troubleshooting',
'/ad-ldap-connector/troubleshoot-ad-ldap-connector',
'/extensions/ad-ldap-connector/troubleshoot-ad-ldap-connector'
],
to: '/troubleshoot/troubleshoot-integrations-and-extensibility/troubleshoot-ad-ldap-connector'
},
{
from: ['/extensions/troubleshoot-extensions','/extensions/troubleshoot'],
to: '/troubleshoot/troubleshoot-integrations-and-extensibility/troubleshoot-extensions'
},
{
from: [
'/extensions/deploy-cli/references/troubleshooting',
'/extensions/deploy-cli-tool/troubleshoot-the-deploy-cli-tool',
'/deploy/deploy-cli-tool/troubleshoot-the-deploy-cli-tool'
],
to: '/troubleshoot/troubleshoot-integrations-and-extensibility/troubleshoot-the-deploy-cli-tool'
},
{
from: ['/troubleshoot/self-change-password-errors','/troubleshoot/references/self_change_password'],
to: '/troubleshoot/troubleshoot-authentication/self-change-password-errors'
},
{
from: [
'/extensions/authorization-extension/v2/troubleshooting',
'/extensions/authorization-dashboard-extension/troubleshoot-authorization-extension',
'/extensions/authorization-extension/troubleshoot-authorization-extension'
],
to: '/troubleshoot/troubleshoot-authentication/troubleshoot-authorization-extension'
},
{
from: ['/troubleshoot/guides/verify-rules', '/troubleshoot/verify-rules'],
to: '/troubleshoot/troubleshoot-basic/verify-rules'
},
{
from: ['/authorization/concepts/troubleshooting', '/authorization/troubleshoot-role-based-access-control-and-authorization'],
to: '/troubleshoot/troubleshoot-authentication/troubleshoot-rbac-authorization'
},
/* Tutorials */
{
from: ['/scenarios', '/tutorials'],
to: '/'
},
/* Universal Login */
{
from: [
'/hosted-pages/hosted-login-auth0js',
'/hosted-pages/login/auth0js',
'/hosted-pages/login/lock',
'/hosted-pages/login/lock-passwordless',
'/hosted-pages/hosted-login-auth0js/v7',
'/hosted-pages/hosted-login-auth0js/v8',
'/hosted-pages/login',
'/hosted-pages',
'/universal-login/customization-new',
'/login_page'
],
to: '/universal-login'
},
{
from: ['/error-pages', '/error-pages/generic', '/hosted-pages/error-pages'],
to: '/universal-login/error-pages'
},
{
from: ['/universal-login/classic'],
to: '/universal-login/classic-experience'
},
{
from: ['/universal-login/multifactor-authentication','/hosted-pages/guardian','/universal-login/guardian'],
to: '/universal-login/classic-experience/mfa-classic-experience'
},
{
from: ['/universal-login/new'],
to: '/universal-login/new-experience'
},
{
from: ['/dashboard/guides/universal-login/configure-login-page-passwordless','/dashboard/guides/connections/configure-passwordless-sms'],
to: '/universal-login/configure-universal-login-with-passwordless'
},
{
from: ['/universal-login/text-customization-prompts/common'],
to: '/universal-login/prompt-common'
},
{
from: ['/universal-login/text-customization-prompts/consent'],
to: '/universal-login/prompt-consent'
},
{
from: ['/universal-login/text-customization-prompts/device-flow'],
to: '/universal-login/prompt-device-flow'
},
{
from: ['/universal-login/text-customization-prompts/email-verification'],
to: '/universal-login/prompt-email-verification'
},
{
from: ['/universal-login/text-customization-prompts/login'],
to: '/universal-login/prompt-login'
},
{
from: ['/universal-login/text-customization-prompts/mfa'],
to: '/universal-login/prompt-mfa'
},
{
from: ['/universal-login/text-customization-prompts/mfa-email'],
to: '/universal-login/prompt-mfa-email'
},
{
from: ['/universal-login/text-customization-prompts/mfa-otp'],
to: '/universal-login/prompt-mfa-otp'
},
{
from: ['/universal-login/text-customization-prompts/mfa-push'],
to: '/universal-login/prompt-mfa-push'
},
{
from: ['/universal-login/text-customization-prompts/mfa-recovery-code'],
to: '/universal-login/prompt-mfa-recovery-code'
},
{
from: ['/universal-login/text-customization-prompts/mfa-sms'],
to: '/universal-login/prompt-mfa-sms'
},
{
from: ['/universal-login/text-customization-prompts/reset-password'],
to: '/universal-login/prompt-reset-password'
},
{
from: ['/universal-login/text-customization-prompts/signup'],
to: '/universal-login/prompt-signup'
},
{
from: ['/guides/login/universal-vs-embedded','/guides/login/centralized-vs-embedded'],
to: '/universal-login/universal-vs-embedded-login'
},
{
from: ['/libraries/when-to-use-lock'],
to: '/universal-login/universal-login-page-customization'
},
{
from: ['/universal-login/default-login-url','/hosted-pages/default-login-url'],
to: '/universal-login/configure-default-login-routes'
},
/* Users */
{
from: ['/users/concepts/overview-users'],
to: '/users'
},
{
from: ['/users/guides/block-and-unblock-users'],
to: '/users/block-and-unblock-users'
},
{
from: ['/users/guides/delete-users'],
to: '/users/delete-users'
},
{
from: ['/dashboard/guides/users/unlink-user-devices'],
to: '/users/unlink-devices-from-users'
},
{
from: ['/user-profile/progressive-profiling','/users/concepts/overview-progressive-profiling','/users/guides/implement-progressive-profiling'],
to: '/users/progressive-profiling'
},
{
from: [
'/users/concepts/overview-user-metadata',
'/metadata',
'/users/read-metadata',
'/users/guides/read-metadata',
'/users/guides/manage-user-metadata',
'/users/manage-user-metadata'
],
to: '/users/metadata'
},
{
from: [
'/users/references/metadata-field-name-rules',
'/best-practices/metadata-best-practices'
],
to: '/users/metadata/metadata-fields-data'
},
{
from: [
'/users/guides/update-metadata-properties-with-management-api',
'/update-metadata-with-the-management-api',
'/users/update-metadata-with-the-management-api',
'/metadata/management-api',
'/metadata/apiv2',
'/metadata/apis',
'/users/guides/set-metadata-properties-on-creation',
'/users/set-metadata-properties-on-creation'
],
to: '/users/metadata/manage-metadata-api'
},
{
from: ['/metadata/lock'],
to: '/users/metadata/manage-metadata-lock'
},
{
from: [
'/rules/current/metadata-in-rules',
'/rules/guides/metadata',
'/rules/metadata-in-rules',
'/metadata-in-rules',
'/metadata/rules',
'/rules/metadata'
],
to: '/users/metadata/manage-metadata-rules'
},
{
from: ['/users/concepts/overview-user-migration'],
to: '/users/import-and-export-users'
},
{
from: ['/user-profile/normalized','/user-profile/normalized/oidc','/user-profile','/users/concepts/overview-user-profile','/user-profile/user-profile-details','/users/normalized/oidc','/users/user-profiles-returned-from-oidc-compliant-pipelines'],
to: '/users/user-profiles'
},
{
from: ['/users/guides/bulk-user-exports'],
to: '/users/bulk-user-exports'
},
{
from: ['/tutorials/bulk-importing-users-into-auth0','/users/guides/bulk-user-imports', '/users/guides/bulk-user-import','/users/bulk-importing-users-into-auth0', '/users/migrations/bulk-import','/bulk-import'],
to: '/users/bulk-user-imports'
},
{
from: ['/user-profile/user-picture','/users/guides/change-user-pictures'],
to: '/users/change-user-picture'
},
{
from: ['/connections/database/migrating','/migrating','/users/migrations/automatic','/users/guides/configure-automatic-migration'],
to: '/users/configure-automatic-migration-from-your-database'
},
{
from: ['/tutorials/creating-users-in-the-management-portal','/users/guides/create-users','/creating-users','/dashboard/guides/users/create-users'],
to: '/users/create-users'
},
{
from: ['/users/guides/email-verified'],
to: '/users/verified-email-usage'
},
{
from: ['/tutorials/get-user-information-with-unbounce-landing-pages','/users/guides/get-user-information-with-unbounce-landing-pages','/scenarios-unbounce'],
to: '/users/get-user-information-on-unbounce-landing-pages'
},
{
from: ['/users/guides/link-user-accounts','/link-accounts/suggested-linking'],
to: '/users/link-user-accounts'
},
{
from: ['/users/guides/manage-user-access-to-applications'],
to: '/users/manage-user-access-to-applications'
},
{
from: ['/users/guides/manage-users-using-the-dashboard'],
to: '/users/manage-users-using-the-dashboard'
},
{
from: ['/users/guides/manage-users-using-the-management-api'],
to: '/users/manage-users-using-the-management-api'
},
{
from: ['/tutorials/redirecting-users','/users/redirecting-users','/users/guides/redirect-users-after-login','/protocols/oauth2/redirect-users','/users/concepts/redirect-users-after-login'],
to: '/users/redirect-users-after-login'
},
{
from: ['/users/guides/unlink-user-accounts'],
to: '/users/unlink-user-accounts'
},
{
from: ['/user-profile/customdb','/users/guides/update-user-profiles-using-your-database'],
to: '/users/update-user-profiles-using-your-database'
},
{
from: ['/users/guides/view-users'],
to: '/users/view-user-details'
},
{
from: ['/users/normalized'],
to: '/users/normalized-user-profiles'
},
{
from: ['/users/normalized/auth0/identify-users'],
to: '/users/identify-users'
},
{
from: ['/user-profile/normalized/auth0','/users/normalized/auth0'],
to: '/users/normalized-user-profiles'
},
{
from: ['/users/normalized/auth0/normalized-user-profile-schema'],
to: '/users/normalized-user-profile-schema'
},
{
from: ['/users/normalized/auth0/sample-user-profiles'],
to: '/users/sample-user-profiles'
},
{
from: ['/users/normalized/auth0/update-root-attributes'],
to: '/users/updating-user-profile-root-attributes'
},
{
from: ['/users/references/bulk-import-database-schema-examples'],
to: '/users/bulk-user-import-database-schema-and-examples'
},
{
from: ['/link-accounts/user-initiated', '/link-accounts/user-initiated-linking','/users/references/link-accounts-user-initiated-scenario','/users/references/link-accounts-client-side-scenario','/user/references/link-accounts-client-side-scenario'],
to: '/users/user-initiated-account-linking-client-side-implementation'
},
{
from: ['/users/references/link-accounts-server-side-scenario'],
to: '/users/suggested-account-linking-server-side-implementation'
},
{
from: ['/connections/database/migrating-okta', '/users/migrations/okta','/users/references/user-migration-scenarios','/users/migrations'],
to: '/users/user-migration-scenarios'
},
{
from: ['/user-profile/user-profile-structure','/users/references/user-profile-structure'],
to: '/users/user-profile-structure'
},
{
from: ['/dashboard/guides/connections/configure-connection-sync','/api/management/guides/connections/configure-connection-sync'],
to: '/users/configure-connection-sync-with-auth0'
},
{
from: ['/api/management/guides/users/set-root-attributes-user-import'],
to: '/users/set-root-attributes-during-user-import'
},
{
from: ['/api/management/guides/users/set-root-attributes-user-signup'],
to: '/users/set-root-attributes-during-user-sign-up'
},
{
from: ['/api/management/guides/users/update-root-attributes-users'],
to: '/users/update-root-attributes-for-users'
},
{
from: ['/users/search/v3','/users/normalized/auth0/retrieve-user-profiles','/users/search','/users-search'],
to: '/users/user-search'
},
{
from: ['/users/search/v3/query-syntax'],
to: '/users/user-search/user-search-query-syntax'
},
{
from: ['/api/management/v2/user-search','/users/search/v2', '/api/v2/user-search'],
to: '/users/user-search/v2'
},
{
from: ['/api/management/v2/query-string-syntax', '/users/search/v2/query-syntax'],
to: '/users/user-search/v2/query-syntax'
},
{
from: ['/users/search/v3/migrate-search-v2-v3','/users/user-search/migrate-search-v2-v3'],
to: '/users/user-search/migrate-v2-v3'
},
{
from: ['/users/search/v3/get-users-by-email-endpoint'],
to: '/users/user-search/retrieve-users-with-get-users-by-email-endpoint'
},
{
from: ['/users/search/v3/get-users-by-id-endpoint'],
to: '/users/user-search/retrieve-users-with-get-users-by-id-endpoint'
},
{
from: ['/users/search/v3/get-users-endpoint','/users/user-search/retrieve-users-with-the-get-users-endpoint'],
to: '/users/user-search/retrieve-users-with-get-users-endpoint'
},
{
from: ['/users/search/v3/sort-search-results'],
to: '/users/user-search/sort-search-results'
},
{
from: ['/users/search/v3/view-search-results-by-page'],
to: '/users/user-search/view-search-results-by-page'
},
{
from: ['/dashboard/guides/users/assign-permissions-users','/api/management/guides/users/assign-permissions-users'],
to: '/users/assign-permissions-to-users'
},
{
from: ['/dashboard/guides/users/assign-roles-users','/api/management/guides/users/assign-roles-users'],
to: '/users/assign-roles-to-users'
},
{
from: ['/dashboard/guides/users/remove-user-permissions','/api/management/guides/users/remove-user-permissions'],
to: '/users/remove-permissions-from-users'
},
{
from: ['/dashboard/guides/users/remove-user-roles','/dashboard/guides/roles/remove-role-users','/api/management/guides/users/remove-user-roles'],
to: '/users/remove-roles-from-users'
},
{
from: ['/dashboard/guides/users/view-user-permissions','/api/management/guides/users/view-user-permissions'],
to: '/users/view-user-permissions'
},
{
from: ['/dashboard/guides/users/view-user-roles','/api/management/guides/users/view-user-roles'],
to: '/users/view-user-roles'
},
{
from: ['/users/concepts/overview-progressive-profiling'],
to: '/users/progressive-profiling'
},
{
from: ['/link-accounts/auth-api','/link-accounts','/users/concepts/overview-user-account-linking','/users/guide/concepts/overview-user-account-linking'],
to: '/users/user-account-linking'
},
{
from: ['/users/guides/get-user-information-with-unbounce-landing-pages'],
to: '/users/get-user-information-on-unbounce-landing-pages'
},
/* Videos */
{
from: ['/video-series/main/videos'],
to: '/videos'
},
{
from: ['/videos/learn-identity'],
to: '/videos/learn-identity-series'
},
{
from: ['/videos/learn-identity/01-introduction-to-identity','/videos/learn-identity-series/learn-identity-series/introduction-to-identity'],
to: '/videos/learn-identity-series/introduction-to-identity'
},
{
from: ['/videos/learn-identity/02-oidc-and-oauth'],
to: '/videos/learn-identity-series/openid-connect-and-oauth2'
},
{
from: ['/videos/learn-identity/03-web-sign-in'],
to: '/videos/learn-identity-series/web-sign-in'
},
{
from: ['/videos/learn-identity/04-calling-an-api'],
to: '/videos/learn-identity-series/calling-an-api'
},
{
from: ['/videos/learn-identity/05-desktop-and-mobile-apps'],
to: '/videos/learn-identity-series/desktop-and-mobile-apps'
},
{
from: ['/videos/learn-identity/06-single-page-apps'],
to: '/videos/learn-identity-series/single-page-apps'
},
{
from: ['/videos/get-started'],
to: '/videos/get-started-series'
},
{
from: ['/videos/get-started/01-architecture-your-tenant'],
to: '/videos/get-started-series/architect-your-tenant'
},
{
from: ['/videos/get-started/02-provision-user-stores'],
to: '/videos/get-started-series/provision-user-stores'
},
{
from: ['/videos/get-started/03-provision-import-users'],
to: '/videos/get-started-series/provision-import-users'
},
{
from: ['/videos/get-started/04_01-authenticate-how-it-works'],
to: '/videos/get-started-series/authenticate-how-it-works'
},
{
from: ['/videos/get-started/04_02-authenticate-spa-example','/videos/get-started/04_01-authenticate-spa-example'],
to: '/videos/get-started-series/authenticate-spa-example'
},
{
from: ['/videos/get-started/05_01-authorize-id-tokens-access-control'],
to: '/videos/get-started-series/authorize-id-tokens-and-access-control'
},
{
from: ['/videos/get-started/05_02-authorize-get-validate-id-tokens'],
to: '/videos/get-started-series/authorize-get-and-validate-id-tokens'
},
{
from: ['/videos/get-started/06-user-profiles'],
to: '/videos/get-started-series/learn-user-profiles'
},
{
from: ['/videos/get-started/07_01-brand-how-it-works'],
to: '/videos/get-started-series/brand-how-it-works'
},
{
from: ['/videos/get-started/07_02-brand-signup-login-pages'],
to: '/videos/get-started-series/brand-signup-and-login-pages'
},
{
from: ['/videos/get-started/08-brand-emails-error-pages'],
to: '/videos/get-started-series/brand-emails-and-error-pages'
},
{
from: ['/videos/get-started/10-logout'],
to: '/videos/get-started-series/learn-logout'
},
/* Support */
{
from: ['/support/support-overview'],
to: '/support/support-plans'
}
];
| config/redirects.js | // This is the list of APIs used in the old two-step quickstarts.
const apiNames = [
'aspnet-webapi',
'aws',
'azure-blob-storage',
'azure-mobile-services',
'azure-sb',
'falcor',
'firebase',
'golang',
'hapi',
'java-spring-security',
'java',
'nginx',
'nodejs',
'php-laravel',
'php-symfony',
'php',
'python',
'rails',
'ruby',
'salesforce-sandbox',
'salesforce',
'sap-odata',
'wcf-service',
'webapi-owin'
];
const apis = `:api(${apiNames.join('|')})`;
module.exports = [
/* MISCELLANEOUS AND OUTDATED */
{
from: ['/addons','/firebaseapi-tutorial','/salesforcesandboxapi-tutorial','/salesforceapi-tutorial','/sapapi-tutorial','/clients/addons','/applications/addons','/addons/azure-blob-storage','/addons/azure-mobile-services','/addons/azure-sb'],
to: '/'
},
{
from: '/topics/guides',
to: '/'
},
{
from: ['/design','/design/web'],
to: '/'
},
{
from: ['/design/browser-based-vs-native-experience-on-mobile','/tutorials/browser-based-vs-native-experience-on-mobile'],
to: '/best-practices/mobile-device-login-flow-best-practices'
},
{
from: '/topics/identity-glossary',
to: '/glossary'
},
{
from: ['/deploy/checklist'],
to: '/deploy/deploy-checklist'
},
/* QUICKSTARTS */
{
from: ['/android-tutorial', '/native-platforms/android', '/quickstart/native/android-vnext'],
to: '/quickstart/native/android'
},
{
from: [
'/angular-tutorial',
'/client-platforms/angularjs'
],
to: '/quickstart/spa/angularjs'
},
{
from: '/client-platforms/angular2',
to: '/quickstart/spa/angular'
},
{
from: ['/quickstart/spa/angularjs', '/quickstart/spa/angular2', '/quickstart/spa/angular-next'],
to: '/quickstart/spa/angular'
},
{
from: '/quickstarts/spa/vanillajs/01-login',
to: '/quickstart/spa/vanillajs/01-login'
},
{
from: [
'/quickstart/webapp/aspnet',
'/aspnet-tutorial',
'/mvc3-tutorial'
],
to: '/quickstart/webapp'
},
{
from: ['/aspnet-owin-tutorial', '/aspnetwebapi-owin-tutorial'],
to: '/quickstart/webapp/aspnet-owin'
},
{
from: [
'/aspnetwebapi-tutorial',
'/tutorials/aspnet-mvc4-enterprise-providers',
'/webapi',
'/mvc-tutorial-enterprise',
'/quickstart/backend/aspnet-webapi'
],
to: '/quickstart/backend'
},
{
from: [
'/quickstart/native/chrome-extension',
'/quickstart/native/chrome'
],
to: '/quickstart/native'
},
{
from: ['/ember-tutorial', '/client-platforms/emberjs'],
to: '/quickstart/spa/emberjs'
},
{
from: [
'/ionic-tutorial',
'/quickstart/native/ionic'
],
to: '/quickstart/native/ionic-angular'
},
{
from: ['/ios-tutorial', '/native-platforms/ios-objc', '/quickstart/native/ios-objc'],
to: '/quickstart/native/ios-swift'
},
{
from: '/java-tutorial',
to: '/quickstart/webapp/java'
},
{
from: '/javaapi-tutorial',
to: '/quickstart/backend/java'
},
{
from: '/server-platforms/golang',
to: '/quickstart/webapp/golang'
},
{
from: '/laravel-tutorial',
to: '/quickstart/webapp/laravel'
},
{
from: [
'/laravelapi-tutorial',
'/quickstart/backend/php-laravel'
],
to: '/quickstart/backend/laravel'
},
{
from: '/nodeapi-tutorial',
to: '/quickstart/backend/nodejs'
},
{
from: ['/nodejs-tutorial', '/server-platforms/nodejs'],
to: '/quickstart/webapp/nodejs'
},
{
from: '/phpapi-tutorial',
to: '/quickstart/backend/php'
},
{
from: '/pythonapi-tutorial',
to: '/quickstart/backend/python'
},
{
from: '/client-platforms/react',
to: '/quickstart/spa/react'
},
{
from: '/quickstart/native/ios-reactnative',
to: '/quickstart/native/react-native'
},
{
from: '/rubyapi-tutorial',
to: '/quickstart/backend/rails'
},
{
from: '/rails-tutorial',
to: '/quickstart/webapp/rails'
},
{
from: [
'/server-apis/ruby',
'/quickstart/backend/ruby'
],
to: '/quickstart/backend/rails'
},
{
from: '/python-tutorial',
to: '/quickstart/webapp/python'
},
{
from: ['/php-tutorial', '/server-platforms/php'],
to: '/quickstart/webapp/php'
},
{
from: [
'/phonegap-tutorial',
'/quickstart/native/phonegap'
],
to: '/quickstart/native'
},
{
from: [
'/servicestack-tutorial',
'/quickstart/webapp/servicestack'
],
to: '/quickstart/webapp'
},
{
from: [
'/singlepageapp-tutorial',
'/client-platforms/vanillajs',
'/quickstart/spa/javascript/:client?'
],
to: '/quickstart/spa/vanillajs'
},
{
from: [
'/quickstart/webapp/play-2-scala',
'/quickstart/webapp/scala'
],
to: '/quickstart/webapp'
},
{
from: [
'/symfony-tutorial',
'/quickstart/webapp/symfony'
],
to: '/quickstart/webapp'
},
{
from: [
'/wcf-tutorial',
'/quickstart/backend/wcf-service'
],
to: '/quickstart/backend'
},
{
from: [
'/win8-cs-tutorial',
'/windowsstore-auth0-tutorial',
'/native-platforms/windows-store-csharp',
'/quickstart/native-mobile/windows8-cp/:client?',
'/quickstart/native/windows8-cp'
],
to: '/quickstart/native/windows-uwp-csharp'
},
{
from: [
'/win8-tutorial',
'/windowsstore-js-auth0-tutorial',
'/native-platforms/windows-store-javascript',
'/quickstart/native-mobile/windows8/:client',
'/quickstart/native/windows-uwp-javascript'
],
to: '/quickstart/native'
},
{
from: [
'/windowsphone-tutorial',
'/quickstart/native/windowsphone'
],
to: '/quickstart/native'
},
{
from: '/wpf-winforms-tutorial',
to: '/quickstart/native/wpf-winforms'
},
{
from: '/xamarin-tutorial',
to: '/quickstart/native/xamarin'
},
{
from: '/quickstart/:platform/reactnative-ios/:backend?',
to: '/quickstart/native/react-native'
},
{
from: '/quickstart/:platform/reactnative-android/:backend?',
to: '/quickstart/native/react-native'
},
{
from: '/quickstart/native/react-native-ios',
to: '/quickstart/native/react-native'
},
{
from: '/quickstart/native/react-native-android',
to: '/quickstart/native/react-native'
},
{
from: '/quickstart/spa/auth0-react',
to: '/quickstart/spa/react'
},
{
from: '/quickstart/spa/auth0-react/01',
to: '/quickstart/spa/react'
},
{
from: '/quickstart/spa/auth0-react/02',
to: '/quickstart/spa/react/02-calling-an-api'
},
{
from: [
'/quickstart/backend/webapi-owin/04-authentication-rs256-deprecated',
'/quickstart/backend/webapi-owin/04-authentication-rs256-legacy'
],
to: '/quickstart/backend/webapi-owin'
},
{
from: [
'/quickstart/backend/webapi-owin/05-authentication-hs256-deprecated',
'/quickstart/backend/webapi-owin/05-authentication-hs256-legacy'
],
to: '/quickstart/backend/webapi-owin'
},
{
from: [
'/quickstart/backend/webapi-owin/06-authorization-deprecated',
'/quickstart/backend/webapi-owin/06-authorization-legacy'
],
to: '/quickstart/backend/webapi-owin'
},
{
from: [
'/quickstart/backend/aspnet-core-webapi/04-authentication-rs256-deprecated',
'/quickstart/backend/aspnet-core-webapi/04-authentication-rs256-legacy'
],
to: '/quickstart/backend/aspnet-core-webapi'
},
{
from: [
'/quickstart/backend/aspnet-core-webapi/05-authentication-hs256-deprecated',
'/quickstart/backend/aspnet-core-webapi/05-authentication-hs256-legacy'
],
to: '/quickstart/backend/aspnet-core-webapi'
},
{
from: [
'/quickstart/backend/aspnet-core-webapi/06-authorization-deprecated',
'/quickstart/backend/aspnet-core-webapi/06-authorization-legacy'
],
to: '/quickstart/backend/aspnet-core-webapi'
},
{
from: '/quickstart/webapp/aspnet-core-3',
to: '/quickstart/webapp/aspnet-core'
},
{
from: [
'/quickstart/spa/react/03-user-profile',
'/quickstart/spa/react/04-user-profile'
],
to: '/quickstart/spa/react'
},
{
from: '/quickstart/webapp/nodejs/02-user-profile',
to: '/quickstart/webapp/nodejs/01-login'
},
{
from: [
'/quickstart/hybrid',
'/quickstart/native-mobile'
],
to: '/quickstart/native'
},
{
from: [
'/quickstart/hybrid/:platform',
'/quickstart/native-mobile/:platform',
`/quickstart/hybrid/:platform/${apis}`,
`/quickstart/native-mobile/:platform/${apis}`,
`/quickstart/native/:platform/${apis}`,
'/quickstart/native/:platform'
],
to: '/quickstart/native'
},
{
from: [
`/quickstart/spa/:platform/${apis}`,
'/quickstart/spa/:platform'
],
to: '/quickstart/spa'
},
{
from: ['/quickstart/backend/:platform',`/quickstart/backend/:platform/${apis}`],
to: '/quickstart/backend'
},
{
from: '/quickstart/spa/emberjs',
to: '/quickstart/spa/ember'
},
{
from: [
'/quickstart/spa/aurelia',
'/quickstart/spa/ember',
'/quickstart/spa/jquery'
],
to: '/quickstart/spa'
},
{
from: '/quickstart',
to: '/'
},
{
from: '/quickstart/backend/java',
to: '/quickstart/backend/java-spring-security5',
},
{
from: '/quickstart/native/ios',
to: '/quickstart/native/ios-swift'
},
{
from: '/quickstart/native/ionic4',
to: '/quickstart/native/ionic-angular'
},
{
from: '/quickstart/native/ionic/00-intro',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/02-custom-login',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/03-user-profile',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/04-linking-accounts',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/05-rules',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/06-authorization',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/08-mfa',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/native/ionic/09-customizing-lock',
to: '/quickstart/native/ionic'
},
{
from: '/quickstart/backend/nodejs/00-getting-started',
to: '/quickstart/backend/nodejs'
},
{
from: '/quickstart/backend/aspnet-core-webapi/00-getting-started',
to: '/quickstart/backend/aspnet-core-webapi'
},
{
from: [
'/quickstart/backend/falcor/00-getting-started',
'/quickstart/backend/falcor'
],
to: '/quickstart/backend'
},
{
from: '/quickstart/backend/golang/00-getting-started',
to: '/quickstart/backend/golang'
},
{
from: [
'/quickstart/backend/hapi/00-getting-started',
'/quickstart/backend/hapi'
],
to: '/quickstart/backend'
},
{
from: [
'/quickstart/backend/java-spring-security',
'/quickstart/backend/java-spring-security/00-getting-started'
],
to: '/quickstart/backend/java-spring-security5'
},
{
from: '/quickstart/backend/laravel/00-getting-started',
to: '/quickstart/backend/laravel'
},
{
from: '/quickstart/backend/php/00-getting-started',
to: '/quickstart/backend/php'
},
{
from: '/quickstart/backend/python/00-getting-started',
to: '/quickstart/backend/python'
},
{
from: '/quickstart/backend/rails/00-getting-started',
to: '/quickstart/backend/rails'
},
{
from: '/quickstart/backend/ruby/00-getting-started',
to: '/quickstart/backend/ruby'
},
{
from: [
'/quickstart/backend/symfony/00-getting-started',
'/quickstart/backend/symfony'
],
to: '/quickstart/backend'
},
{
from: '/quickstart/backend/webapi-owin/00-getting-started',
to: '/quickstart/backend/webapi-owin'
},
{
from: '/quickstart/webapp/rails/00-introduction',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/02-custom-login',
to: '/quickstart/webapp/rails'
},
{
from: [
'/quickstart/webapp/rails/03-session-handling',
'/quickstart/webapp/rails/02-session-handling'
],
to: '/quickstart/webapp/rails'
},
{
from: [
'/quickstart/webapp/rails/04-user-profile',
'/quickstart/webapp/rails/03-user-profile'
],
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/05-linking-accounts',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/06-rules',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/07-authorization',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/08-mfa',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/rails/09-customizing-lock',
to: '/quickstart/webapp/rails'
},
{
from: '/quickstart/webapp/java/getting-started',
to: '/quickstart/webapp/java'
},
{
from: [
'/quickstart/webapp/java-spring-mvc/getting-started',
'/quickstart/webapp/java-spring-mvc'
],
to: '/quickstart/webapp/java-spring-boot'
},
{
from: [
'/quickstart/webapp/java-spring-security-mvc/00-intro',
'/quickstart/webapp/java-spring-security-mvc'
],
to: '/quickstart/webapp/java-spring-boot'
},
{
from: '/quickstart/spa/angular2/00-login',
to: '/quickstart/spa/angular'
},
{
from: '/quickstart/spa/angular2/03-user-profile',
to: '/quickstart/spa/angular'
},
{
from: '/quickstart/spa/angular2/04-calling-an-api',
to: '/quickstart/spa/angular'
},
{
from: '/quickstart/spa/angular2/05-authorization',
to: '/quickstart/spa/angular'
},
{
from: '/quickstart/spa/angular2/06-token-renewal',
to: '/quickstart/spa/angular'
},
/* CONNECTIONS */
{
from: [
'/37signals-clientid',
'/connections/social/37signals',
'/connections/social/basecamp'
],
to: 'https://marketplace.auth0.com/integrations/37signals-social-connection'
},
{
from: [
'/amazon-clientid',
'/connections/social/amazon'
],
to: 'https://marketplace.auth0.com/integrations/amazon-social-connection'
},
{
from: ['/connections/enterprise/azure-active-directory','/connections/social/active-directory','/waad-clientid','/users/guides/azure-access-control'],
to: '/connections/enterprise/azure-active-directory/v2'
},
{
from: '/connections/enterprise/azure-active-directory-classic',
to: '/connections/enterprise/azure-active-directory/v1'
},
{
from: '/connections/enterprise/samlp',
to: '/connections/enterprise/saml'
},
{
from: ['/connections/enterprise','/connections/enterprise/sharepoint-online','/connections/enterprise/ws-fed'],
to: '/connections/enterprise/saml'
},
{
from: [
'/dwolla-clientid',
'/connections/social/dwolla'
],
to: 'https://marketplace.auth0.com/integrations/dwolla-social-connection'
},
{
from: [
'/baidu-clientid',
'/connections/social/baidu'
],
to: 'https://marketplace.auth0.com/integrations/baidu-social-connection'
},
{
from: [
'/box-clientid',
'/connections/social/box'
],
to: 'https://marketplace.auth0.com/integrations/box-social-connection'
},
{
from: [
'/evernote-clientid',
'/connections/social/evernote'
],
to: 'https://marketplace.auth0.com/integrations/evernote-social-connection'
},
{
from: [
'/exact-clientid',
'/connections/social/exact'
],
to: 'https://marketplace.auth0.com/integrations/exact-social-connection'
},
{
from: [
'/facebook-clientid',
'/connections/social/facebook'
],
to: 'https://marketplace.auth0.com/integrations/facebook-social-connection'
},
{
from: [
'/fitbit-clientid',
'/connections/social/fitbit'
],
to: 'https://marketplace.auth0.com/integrations/fitbit-social-connection'
},
{
from: [
'/github-clientid',
'/connections/social/github'
],
to: 'https://marketplace.auth0.com/integrations/github-social-connection'
},
{
from: [
'/goog-clientid',
'/connections/social/google'
],
to: 'https://marketplace.auth0.com/integrations/google-social-connection'
},
{
from: [
'/ms-account-clientid',
'/connections/social/microsoft-account'
],
to: 'https://marketplace.auth0.com/integrations/microsoft-account-social-connection'
},
{
from: '/oauth2',
to: '/connections/social/oauth2'
},
{
from: '/connections/social/auth0-oidc',
to: '/connections/enterprise/oidc'
},
{
from: [
'/paypal-clientid',
'/connections/social/paypal'
],
to: 'https://marketplace.auth0.com/integrations/paypal-social-connection'
},
{
from: [
'/planningcenter-clientid',
'/connections/social/planning-center'
],
to: 'https://marketplace.auth0.com/integrations/planningcenter-social-connection'
},
{
from: [
'/salesforce-clientid',
'/connections/social/salesforce'
],
to: 'https://marketplace.auth0.com/integrations/salesforce-social-connection'
},
{
from: [
'/renren-clientid',
'/connections/social/renren'
],
to: 'https://marketplace.auth0.com/integrations/renren-social-connection'
},
{
from: [
'/shopify-clientid',
'/connections/social/shopify'
],
to: 'https://marketplace.auth0.com/integrations/shopify-social-connection'
},
{
from: [
'/twitter-clientid',
'/connections/social/twitter'
],
to: 'https://marketplace.auth0.com/integrations/twitter-social-connection'
},
{
from: [
'/vkontakte-clientid',
'/connections/social/vkontakte'
],
to: 'https://marketplace.auth0.com/integrations/vkontakte-social-connection'
},
{
from: [
'/weibo-clientid',
'/connections/social/weibo'
],
to: 'https://marketplace.auth0.com/integrations/weibo-social-connection'
},
{
from: [
'/wordpress-clientid',
'/connections/social/wordpress'
],
to: 'https://marketplace.auth0.com/integrations/wordpress-social-connection'
},
{
from: [
'/yahoo-clientid',
'/connections/social/yahoo'
],
to: 'https://marketplace.auth0.com/integrations/yahoo-social-connection'
},
{
from: [
'/yandex-clientid',
'/connections/social/yandex'
],
to: 'https://marketplace.auth0.com/integrations/yandex-social-connection'
},
{
from: [
'/linkedin-clientid',
'/connections/social/linkedin'
],
to: 'https://marketplace.auth0.com/integrations/linkedin-social-connection'
},
{
from: '/connections/social/bitbucket',
to: 'https://marketplace.auth0.com/integrations/bitbucket-social-connection'
},
{
from: '/connections/social/digitalocean',
to: 'https://marketplace.auth0.com/integrations/digitalocean-social-connection'
},
{
from: '/connections/social/discord',
to: 'https://marketplace.auth0.com/integrations/discord-social-connection'
},
{
from: '/connections/social/docomo',
to: 'https://marketplace.auth0.com/integrations/daccount-social-connection'
},
{
from: '/connections/social/dribbble',
to: 'https://marketplace.auth0.com/integrations/dribbble-social-connection'
},
{
from: '/connections/social/dropbox',
to: 'https://marketplace.auth0.com/integrations/dropbox-social-connection'
},
{
from: '/connections/social/evernote-sandbox',
to: 'https://marketplace.auth0.com/integrations/evernote-sandbox-social-connection'
},
{
from: '/connections/social/figma',
to: 'https://marketplace.auth0.com/integrations/figma-social-connection'
},
{
from: '/connections/social/paypal-sandbox',
to: 'https://marketplace.auth0.com/integrations/paypal-sandbox-social-connection'
},
{
from: '/connections/social/quickbooks-online',
to: 'https://marketplace.auth0.com/integrations/quickbooks-social-connection'
},
{
from: [
'/salesforce-community',
'/connections/social/salesforce-community'
],
to: 'https://marketplace.auth0.com/integrations/salesforce-community-social-connection'
},
{
from: '/connections/social/salesforce-sandbox',
to: 'https://marketplace.auth0.com/integrations/salesforce-sandbox-social-connection'
},
{
from: '/connections/social/slack',
to: 'https://marketplace.auth0.com/integrations/sign-in-with-slack'
},
{
from: '/connections/social/spotify',
to: 'https://marketplace.auth0.com/integrations/spotify-social-connection'
},
{
from: '/connections/social/stripe-connect',
to: 'https://marketplace.auth0.com/integrations/stripe-connect-social-connection'
},
{
from: '/connections/social/twitch',
to: 'https://marketplace.auth0.com/integrations/twitch-social-connection'
},
{
from: '/connections/social/vimeo',
to: 'https://marketplace.auth0.com/integrations/vimeo-social-connection'
},
{
from: '/connections/social/yammer',
to: 'https://marketplace.auth0.com/integrations/yammer-social-connection'
},
{
from: '/ad',
to: '/connections/enterprise/active-directory-ldap'
},
{
from: '/connections/enterprise/ldap',
to: '/connections/enterprise/active-directory-ldap'
},
{
from: '/connections/enterprise/active-directory',
to: '/connections/enterprise/active-directory-ldap'
},
{
from: '/adfs',
to: '/connections/enterprise/adfs'
},
{
from: [
'/passwordless',
'/dashboard/guides/connections/set-up-connections-passwordless',
'/api-auth/passwordless',
'/connections/passwordless/ios',
'/connections/passwordless/native-passwordless-universal',
'/connections/passwordless/reference/troubleshoot',
'/connections/passwordless/faq',
'/connections/passwordless/spa-email-code',
'/connections/passwordless/spa-email-link',
'/connections/passwordless/spa-sms',
'/connections/passwordless/guides/',
'/connections/passwordless/ios-sms-objc',
'/connections/passwordless/ios-sms'
],
to: '/connections/passwordless'
},
{
from: '/password-strength',
to: '/connections/database/password-strength'
},
{
from: [
'/identityproviders',
'/applications/concepts/connections',
'/applications/connections',
'/clients/connections'
],
to: '/connections'
},
{
from: ['/connections/database/mysql','/mysql-connection-tutorial','/connections/database/custom-db/custom-db-connection-overview'],
to: '/connections/database/custom-db'
},
{
from: ['/connections/database/password'],
to: '/connections/database/password-options'
},
{
from: ['/tutorials/adding-generic-oauth1-connection','/oauth1'],
to: '/connections/adding-generic-oauth1-connection',
},
{
from: ['/tutorials/adding-scopes-for-an-external-idp','/what-to-do-once-the-user-is-logged-in/adding-scopes-for-an-external-idp'],
to: '/connections/adding-scopes-for-an-external-idp',
},
{
from: ['/tutorials/generic-oauth2-connection-examples','/oauth2-examples'],
to: '/connections/generic-oauth2-connection-examples',
},
{
from: ['/tutorials/calling-an-external-idp-api','/what-to-do-once-the-user-is-logged-in/calling-an-external-idp-api'],
to: '/connections/calling-an-external-idp-api',
},
{
from: ['/tutorials/how-to-test-partner-connection','/test-partner-connection'],
to: '/connections/how-to-test-partner-connection',
},
{
from: '/connections/social/imgur',
to: 'https://marketplace.auth0.com/integrations/imgur-social-connection'
},
{
from: [
'/connections/grean/bankid-no',
'/connections/criipto/bankid-no',
'/connections/grean/bankid-se',
'/connections/criipto/bankid-se',
'/connections/grean/nemid',
'/connections/criipto/nemid'
],
to: 'https://marketplace.auth0.com/integrations/criipto-verify-e-id'
},
{
from: [
'/connections/passwordless/sms-gateway',
'/connections/passwordless/guides/use-sms-gateway-passwordless'
],
to: '/connections/passwordless/use-sms-gateway-passwordless'
},
{
from: [
'/connections/apple-setup',
'/connections/apple-siwa/set-up-apple',
'/connections/apple-siwa/add-siwa-web-app',
'/connections/apple-siwa/add-siwa-to-web-app',
'/connections/social/apple',
'/connections/apple-siwa/test-siwa-connection'
],
to: 'https://marketplace.auth0.com/integrations/apple-social-connection'
},
{
from: [
'/connections/apple-siwa/add-siwa-to-native-app',
'/connections/nativesocial/add-siwa-to-native-app',
'/connections/nativesocial/apple'
],
to: '/connections/social/apple-native'
},
{
from: [
'/connections/nativesocial/facebook-native'
],
to: '/connections/social/facebook-native'
},
{
from: [
'/connections/passwordless/email',
'/connections/passwordless/guides/email-otp'
],
to: '/connections/passwordless/email-otp'
},
{
from: [
'/connections/passwordless/sms',
'/connections/passwordless/guides/sms-otp'
],
to: '/connections/passwordless/sms-otp'
},
{
from: [
'/connections/passwordless/spa',
'/connections/passwordless/guides/universal-login'
],
to: '/connections/passwordless/universal-login'
},
{
from: [
'/connections/passwordless/regular-web-app',
'/connections/passwordless/guides/universal-login'
],
to: '/connections/passwordless/universal-login'
},
{
from: [
'/connections/identity-providers-social',
'/connections/social/aol',
'/aol-clientid',
'/connections/social/thecity',
'/thecity-clientid',
'/connections/social/miicard',
'/miicard-clientid',
'/connections/social',
'/connections/nativesocial/'],
to: '/connections/social/identity-providers'
},
{
from: [
'/connections/identity-providers-enterprise',
'/connections/enterprise/sharepoint-apps',
'/sharepoint-clientid'
],
to: '/connections/enterprise/identity-providers'
},
{
from: [
'/connections/identity-providers-legal'
],
to: '/connections/legal/identity-providers'
},
{
from: [
'/line',
'/connections/social/line'
],
to: 'https://marketplace.auth0.com/integrations/line-social-connection'
},
{
from: [
'/connections/passwordless/concepts/sample-use-cases-rules'
],
to: '/connections/passwordless/sample-use-cases-rules'
},
/* MICROSITES */
/* ARCHITECTURE SCENARIOS */
{
from: '/architecture-scenarios/application/mobile-api',
to: '/architecture-scenarios/mobile-api'
},
{
from: '/architecture-scenarios/application/server-api',
to: '/architecture-scenarios/server-api'
},
{
from: [
'/architecture-scenarios/application/spa-api',
'/architecture-scenarios/sequence-diagrams',
'/sequence-diagrams'
],
to: '/architecture-scenarios/spa-api'
},
{
from: '/architecture-scenarios/application/web-app-sso',
to: '/architecture-scenarios/web-app-sso'
},
{
from: '/architecture-scenarios/business/b2b',
to: '/architecture-scenarios/b2b'
},
{
from: [
'/architecture-scenarios/b2b/b2b-architecture',
'/architecture-scenarios/implementation/b2b/b2b-architecture'
],
to: '/architecture-scenarios/b2b/architecture'
},
{
from: [
'/architecture-scenarios/b2b/b2b-authentication',
'/architecture-scenarios/implementation/b2b/b2b-authentication'
],
to: '/architecture-scenarios/b2b/authentication'
},
{
from: [
'/architecture-scenarios/b2b/b2b-authorization',
'/architecture-scenarios/implementation/b2b/b2b-authorization'
],
to: '/architecture-scenarios/b2b/authorization'
},
{
from: [
'/architecture-scenarios/b2b/b2b-branding',
'/architecture-scenarios/implementation/b2b/b2b-branding'
],
to: '/architecture-scenarios/b2b/branding'
},
{
from: [
'/architecture-scenarios/b2b/b2b-deployment',
'/architecture-scenarios/implementation/b2b/b2b-deployment'
],
to: '/architecture-scenarios/b2b/deployment'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch',
'/architecture-scenarios/implementation/b2b/b2b-launch'
],
to: '/architecture-scenarios/b2b/launch'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-compliance',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-compliance'
],
to: '/architecture-scenarios/b2b/launch/compliance-readiness'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-launch',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-launch'
],
to: '/architecture-scenarios/b2b/launch/launch-day'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-operations',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-operations'
],
to: '/architecture-scenarios/b2b/launch/operations-readiness'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-support',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-support'
],
to: '/architecture-scenarios/b2b/launch/support-readiness'
},
{
from: [
'/architecture-scenarios/b2b/b2b-launch-testing',
'/architecture-scenarios/implementation/b2b/b2b-launch/b2b-launch-testing'
],
to: '/architecture-scenarios/b2b/launch/testing'
},
{
from: [
'/architecture-scenarios/b2b/b2b-logout',
'/architecture-scenarios/implementation/b2b/b2b-logout'
],
to: '/architecture-scenarios/b2b/logout'
},
{
from: [
'/architecture-scenarios/b2b/b2b-operations',
'/architecture-scenarios/implementation/b2b/b2b-operations'
],
to: '/architecture-scenarios/b2b/operations'
},
{
from: [
'/architecture-scenarios/b2b/b2b-profile-mgmt',
'/architecture-scenarios/implementation/b2b/b2b-profile-mgmt'
],
to: '/architecture-scenarios/b2b/profile-management'
},
{
from: [
'/architecture-scenarios/b2b/b2b-provisioning',
'/architecture-scenarios/implementation/b2b/b2b-provisioning'
],
to: '/architecture-scenarios/b2b/provisioning'
},
{
from: [
'/architecture-scenarios/b2b/b2b-qa',
'/architecture-scenarios/implementation/b2b/b2b-qa'
],
to: '/architecture-scenarios/b2b/quality-assurance'
},
{
from: '/architecture-scenarios/business/b2c',
to: '/architecture-scenarios/b2c'
},
{
from: [
'/architecture-scenarios/b2c/b2c-architecture',
'/architecture-scenarios/implementation/b2c/b2c-architecture'
],
to: '/architecture-scenarios/b2c/architecture'
},
{
from: [
'/architecture-scenarios/b2c/b2c-authentication',
'/architecture-scenarios/implementation/b2c/b2c-authentication'
],
to: '/architecture-scenarios/b2c/authentication'
},
{
from: [
'/architecture-scenarios/b2c/b2c-authorization',
'/architecture-scenarios/implementation/b2c/b2c-authorization'
],
to: '/architecture-scenarios/b2c/authorization'
},
{
from: [
'/architecture-scenarios/b2c/b2c-branding',
'/architecture-scenarios/implementation/b2c/b2c-branding'
],
to: '/architecture-scenarios/b2c/branding'
},
{
from: [
'/architecture-scenarios/b2c/b2c-deployment',
'/architecture-scenarios/implementation/b2c/b2c-deployment'
],
to: '/architecture-scenarios/b2c/deployment'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch',
'/architecture-scenarios/implementation/b2c/b2c-launch'
],
to: '/architecture-scenarios/b2c/launch'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-compliance',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-compliance'
],
to: '/architecture-scenarios/b2c/launch/compliance-readiness'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-launch',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-launch'
],
to: '/architecture-scenarios/b2c/launch/launch-day'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-operations',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-operations'
],
to: '/architecture-scenarios/b2c/launch/operations-readiness'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-support',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-support'
],
to: '/architecture-scenarios/b2c/launch/support-readiness'
},
{
from: [
'/architecture-scenarios/b2c/b2c-launch-testing',
'/architecture-scenarios/implementation/b2c/b2c-launch/b2c-launch-testing'
],
to: '/architecture-scenarios/b2c/launch/testing'
},
{
from: [
'/architecture-scenarios/b2c/b2c-logout',
'/architecture-scenarios/implementation/b2c/b2c-logout'
],
to: '/architecture-scenarios/b2c/logout'
},
{
from: [
'/architecture-scenarios/b2c/b2c-operations',
'/architecture-scenarios/implementation/b2c/b2c-operations'
],
to: '/architecture-scenarios/b2c/operations'
},
{
from: [
'/architecture-scenarios/b2c/b2c-profile-mgmt',
'/architecture-scenarios/implementation/b2c/b2c-profile-mgmt'
],
to: '/architecture-scenarios/b2c/profile-management'
},
{
from: [
'/architecture-scenarios/b2c/b2c-provisioning',
'/architecture-scenarios/implementation/b2c/b2c-provisioning'
],
to: '/architecture-scenarios/b2c/provisioning'
},
{
from: [
'/architecture-scenarios/b2c/b2c-qa',
'/architecture-scenarios/implementation/b2c/b2c-qa'
],
to: '/architecture-scenarios/b2c/quality-assurance'
},
{
from: '/architecture-scenarios/business/b2e',
to: '/architecture-scenarios/b2e'
},
{
from: '/architecture-scenarios/application/mobile-api/api-implementation-nodejs',
to: '/architecture-scenarios/mobile-api/api-implementation-nodejs'
},
{
from: '/architecture-scenarios/application/mobile-api/mobile-implementation-android',
to: '/architecture-scenarios/mobile-api/mobile-implementation-android'
},
{
from: '/architecture-scenarios/application/server-api/api-implementation-nodejs',
to: '/architecture-scenarios/server-api/api-implementation-nodejs'
},
{
from: '/architecture-scenarios/application/server-api/cron-implementation-python',
to: '/architecture-scenarios/server-api/cron-implementation-python'
},
{
from: '/architecture-scenarios/application/spa-api/spa-implementation-angular2',
to: '/architecture-scenarios/spa-api/spa-implementation-angular2'
},
{
from: '/architecture-scenarios/application/spa-api/api-implementation-nodejs',
to: '/architecture-scenarios/spa-api/api-implementation-nodejs'
},
{
from: '/architecture-scenarios/application/web-app-sso/implementation-aspnetcore',
to: '/architecture-scenarios/web-app-sso/implementation-aspnetcore'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/provisioning',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/provisioning'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/provisioning'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/authentication',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/authentication'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/authentication'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/branding',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/branding'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/branding'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/authorization',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/authorization'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/authorization'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/profile-management',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/profile-management'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/profile-management'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/single-identity-provider-organizations/logout',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/single-identity-provider-organizations/logout'
],
to: '/architecture-scenarios/multiple-orgs/single-idp-orgs/logout'
},
{
from: [
'/architecture-scenarios/multiple-organization-architecture/multiple-identity-provider-organizations',
'/architecture-scenarios/multiple-organization-architecture/users-isolated-by-organization/multiple-identity-provider-organizations'
],
to: '/architecture-scenarios/multiple-orgs/multiple-idp-orgs'
},
/* CONTENTFUL REDIRECTS */
/* Configure */
{
from: ['/configuration-overview','/config'],
to: '/configure'
},
/* Tenants */
{
from: [
'/dashboard/tenant-settings',
'/get-started/dashboard/tenant-settings',
'/best-practices/tenant-settings-best-practices',
'/best-practices/tenant-settings',
'/dashboard/reference/settings-tenant',
'/tutorials/dashboard-tenant-settings',
'/dashboard-account-settings',
'/dashboard/dashboard-tenant-settings',
'/config/tenant-settings'
],
to: '/configure/tenant-settings'
},
{
from: [
'/tokens/manage-signing-keys',
'/tokens/guides/manage-signing-keys',
'/config/tenant-settings/signing-keys'
],
to: '/configure/tenant-settings/signing-keys'
},
{
from: '/config/tenant-settings/signing-keys/rotate-signing-keys',
to: '/configure/tenant-settings/signing-keys/rotate-signing-keys'
},
{
from: '/config/tenant-settings/signing-keys/revoke-signing-keys',
to: '/configure/tenant-settings/signing-keys/revoke-signing-keys'
},
{
from: '/config/tenant-settings/signing-keys/view-signing-certificates',
to: '/configure/tenant-settings/signing-keys/view-signing-certificates'
},
{
from: '/anomaly-detection/suspicious-ip-throttling',
to: '/configure/anomaly-detection/suspicious-ip-throttling'
},
{
from: [
'/get-started/dashboard/configure-device-user-code-settings',
'/dashboard/guides/tenants/configure-device-user-code-settings',
'/config/tenant-settings/configure-device-user-code-settings'
],
to: '/configure/tenant-settings/configure-device-user-code-settings'
},
/* Applications */
{
from: [
'/applications',
'/application',
'/applications/concepts/app-types-auth0',
'/clients',
'/api-auth/tutorials/adoption/oidc-conformant',
'/api-auth/client-types','/clients/client-types',
'/applications/application-types',
'/applications/concepts/client-secret'
],
to: '/configure/applications'
},
{
from: [
'/clients/client-settings',
'/dashboard/reference/settings-application',
'/get-started/dashboard/application-settings',
'/best-practices/application-settings',
'/best-practices/app-settings-best-practices',
'/applications/application-settings'
],
to: '/configure/applications/application-settings'
},
{
from: [
'/applications/dynamic-client-registration',
'/api-auth/dynamic-client-registration',
'/api-auth/dynamic-application-registration'
],
to: '/configure/applications/dynamic-client-registration'
},
{
from: [
'/dashboard/guides/applications/enable-android-app-links',
'/clients/enable-android-app-links',
'/applications/enable-android-app-links',
'/applications/guides/enable-android-app-links-dashboard',
'/applications/enable-android-app-links-support'
],
to: '/configure/applications/enable-android-app-links-support'
},
{
from: [
'/dashboard/guides/applications/enable-universal-links',
'/clients/enable-universal-links',
'/applications/enable-universal-links',
'/applications/guides/enable-universal-links-dashboard',
'/enable-universal-links-support-in-apple-xcode',
'/applications/enable-universal-links-support-in-apple-xcode'
],
to: '/configure/applications/enable-universal-links-support-in-apple-xcode'
},
{
from: [
'/dashboard/guides/applications/enable-sso-app',
'/sso/enable-sso-for-applications'
],
to: '/configure/applications/enable-sso-for-applications'
},
{
from: '/applications/configure-application-metadata',
to: '/configure/applications/configure-application-metadata'
},
{
from: [
'/applications/reference/grant-types-available',
'/applications/reference/grant-types-auth0-mapping',
'/clients/client-grant-types',
'/applications/concepts/application-grant-types',
'/applications/concepts/grant-types-legacy',
'/applications/application-grant-types'
],
to: '/configure/applications/application-grant-types'
},
{
from: [
'/api-auth/config/using-the-auth0-dashboard',
'/api-auth/config/using-the-management-api',
'/api/management/guides/applications/update-grant-types',
'/dashboard/guides/applications/update-grant-types',
'/applications/update-grant-types'
],
to: '/configure/applications/update-grant-types'
},
{
from: [
'/dashboard/guides/applications/rotate-client-secret',
'/api/management/guides/applications/rotate-client-secret',
'/get-started/dashboard/rotate-client-secret',
'/applications/rotate-client-secret'
],
to: '/configure/applications/rotate-client-secret'
},
{
from: [
'/dashboard/guides/applications/update-signing-algorithm',
'/tokens/guides/update-signing-algorithm-application',
'/applications/change-application-signing-algorithms'
],
to: '/configure/applications/change-application-signing-algorithms'
},
{
from: ['/applications/set-up-cors','/dashboard/guides/applications/set-up-cors'],
to: '/configure/applications/set-up-cors'
},
{
from: ['/applications/update-application-connections','/dashboard/guides/applications/update-app-connections'],
to: '/configure/applications/update-application-connections'
},
{
from: ['/applications/concepts/app-types-confidential-public','/applications/confidential-and-public-applications'],
to: '/configure/applications/confidential-public-apps'
},
{
from: [
'/dashboard/guides/applications/view-app-type-confidential-public',
'/applications/view-application-type'
],
to: '/configure/applications/confidential-public-apps/view-application-type'
},
{
from: [
'/applications/first-party-and-third-party-applications',
'/applications/concepts/app-types-first-third-party'
],
to: '/configure/applications/confidential-public-apps/first-party-and-third-party-applications'
},
{
from: ['/applications/view-application-ownership','/api/management/guides/applications/view-ownership'],
to: '/configure/applications/confidential-public-apps/view-application-ownership'
},
{
from: [
'/api/management/guides/applications/update-ownership',
'/api/management/guides/applications/remove-app',
'/applications/update-application-ownership'
],
to: '/configure/applications/confidential-public-apps/update-application-ownership'
},
{
from: [
'/applications/guides/enable-third-party-applications',
'/applications/guides/enable-third-party-apps',
'/applications/enable-third-party-applications'
],
to: '/configure/applications/confidential-public-apps/enable-third-party-applications'
},
{
from: ['/applications/wildcards-for-subdomains','/applications/reference/wildcard-subdomains'],
to: '/configure/applications/wildcards-for-subdomains'
},
{
from: ['/applications/remove-applications','/dashboard/guides/applications/remove-app'],
to: '/configure/applications/remove-applications'
},
{
from: [
'/dev-lifecycle/work-with-auth0-locally',
'/dev-lifecycle/local-testing-and-development',
'/applications/work-with-auth0-locally'
],
to: '/configure/applications/work-with-auth0-locally'
},
{
from: ['/applications/set-up-database-connections','/dashboard/guides/connections/set-up-connections-database'],
to: '/configure/applications/set-up-database-connections'
},
/* APIs */
{
from: [
'/api-auth/references/dashboard/api-settings',
'/dashboard/reference/settings-api',
'/get-started/dashboard/api-settings',
'/config/api-settings'
],
to: '/configure/api-settings'
},
{
from: [
'/dashboard/guides/apis/add-permissions-apis',
'/api/management/guides/apis/update-permissions-apis',
'/scopes/current/guides/define-scopes-using-dashboard',
'/scopes/current/guides/define-api-scope-dashboard',
'/get-started/dashboard/add-api-permissions',
'/config/api-settings/add-api-permissions'
],
to: '/configure/api-settings/add-api-permissions'
},
{
from: [
'/dashboard/guides/apis/delete-permissions-apis',
'/get-started/dashboard/delete-api-permissions',
'/config/api-settings/delete-api-permissions'
],
to: '/configure/api-settings/delete-api-permissions'
},
{
from: [
'/authorization/set-logical-api',
'/authorization/represent-multiple-apis-using-a-single-logical-api',
'/api-auth/tutorials/represent-multiple-apis'
],
to: '/configure/api-settings/set-logical-api'
},
/* Single Sign-On */
{
from: [
'/api-auth/tutorials/adoption/single-sign-on',
'/sso/legacy',
'/sso/legacy/single-page-apps',
'/sso/legacy/regular-web-apps-sso',
'/sso/legacy/single-page-apps-sso',
'/sso/current/single-page-apps-sso',
'/sso/current/single-page-apps',
'/sso/current/sso-auth0',
'/sso/current/introduction',
'/sso/single-sign-on',
'/sso/current',
'/sso/current/setup',
'/sso/current/index_old',
'/sso'
],
to: '/configure/sso'
},
{
from: ['/sso/inbound-single-sign-on','/sso/current/inbound'],
to: '/configure/sso/inbound-single-sign-on'
},
{
from: ['/sso/outbound-single-sign-on','/sso/current/outbound'],
to: '/configure/sso/outbound-single-sign-on'
},
{
from: [
'/single-sign-on/api-endpoints-for-single-sign-on',
'/sso/current/relevant-api-endpoints',
'/sso/api-endpoints-for-single-sign-on'
],
to: '/configure/sso/api-endpoints-for-single-sign-on'
},
/* SAML */
{
from: [
'/saml-apps',
'/protocols/saml/identity-providers',
'/samlp-providers',
'/protocols/saml/samlp-providers',
'/protocols/saml',
'/protocols/saml-protocol',
'/configure/saml-protocol',
'/protocols/saml-configuration-options',
'/protocols/saml/saml-apps',
'/protocols/saml/saml-configuration/supported-options-and-bindings',
'/protocols/saml/saml-configuration/design-considerations',
'/protocols/saml/saml-configuration-options',
'/saml-configuration'
],
to: '/configure/saml-configuration'
},
{
from: [
'/protocols/saml/saml-configuration',
'/protocols/saml/saml-configuration/special-configuration-scenarios',
'/protocols/saml-protocol/saml-configuration-options/special-saml-configuration-scenarios'
],
to: '/configure/saml-configuration/saml-sso-integrations'
},
{
from: [
'/protocols/saml/idp-initiated-sso',
'/protocols/saml-configuration-options/identity-provider-initiated-single-sign-on',
'/protocols/saml/saml-configuration/special-configuration-scenarios/idp-initiated-sso',
'/protocols/saml-protocol/saml-configuration-options/identity-provider-initiated-single-sign-on'
],
to: '/configure/saml-configuration/saml-sso-integrations/identity-provider-initiated-single-sign-on'
},
{
from: [
'/protocols/saml-configuration-options/sign-and-encrypt-saml-requests',
'/protocols/saml/saml-configuration/special-configuration-scenarios/signing-and-encrypting-saml-requests',
'/protocols/saml-protocol/saml-configuration-options/sign-and-encrypt-saml-requests'
],
to: '/configure/saml-configuration/saml-sso-integrations/sign-and-encrypt-saml-requests'
},
{
from: '/protocols/saml-protocol/saml-configuration-options/work-with-certificates-and-keys-as-strings',
to: '/configure/saml-configuration/saml-sso-integrations/work-with-certificates-and-keys-as-strings'
},
{
from: [
'/protocols/saml/adfs',
'/protocols/saml-protocol/saml-configuration-options/configure-adfs-saml-connections'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-adfs-saml-connections'
},
{
from: [
'/protocols/saml/identity-providers/okta',
'/okta',
'/saml/identity-providers/okta',
'/protocols/saml-configuration-options/configure-okta-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-okta-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-okta-as-saml-identity-provider'
},
{
from: [
'/onelogin',
'/saml/identity-providers/onelogin',
'/protocols/saml/identity-providers/onelogin',
'/protocols/saml-configuration-options/configure-onelogin-as-saml-identity-provider',
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-onelogin-as-saml-identity-provider'
},
{
from: [
'/ping7',
'/saml/identity-providers/ping7',
'/protocols/saml/identity-providers/ping7',
'/protocols/saml-configuration-options/configure-pingfederate-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration/configure-pingfederate-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-pingfederate-as-saml-identity-provider'
},
{
from: [
'/saml/identity-providers/salesforce',
'/protocols/saml/identity-providers/salesforce',
'/protocols/saml-configuration-options/configure-salesforce-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-salesforce-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-salesforce-as-saml-identity-provider'
},
{
from: [
'/siteminder',
'/saml/identity-providers/siteminder',
'/protocols/saml/identity-providers/siteminder',
'/protocols/saml-configuration-options/configure-siteminder-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-siteminder-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-siteminder-as-saml-identity-provider'
},
{
from: [
'/ssocircle',
'/saml/identity-providers/ssocircle',
'/protocols/saml/identity-providers/ssocircle',
'/protocols/saml-configuration-options/configure-ssocircle-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-ssocircle-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-ssocircle-as-saml-identity-provider'
},
{
from: [
'/saml2webapp-tutorial',
'/protocols/saml/saml2webapp-tutorial',
'/protocols/saml-protocol/saml-configuration-options/enable-saml2-web-app-addon'
],
to: '/configure/saml-configuration/saml-sso-integrations/enable-saml2-web-app-addon'
},
{
from: [
'/configure/saml-configuration-options/configure-saml2-web-app-addon-for-aws',
'/dashboard/guides/applications/set-up-addon-saml2-aws',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-aws'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-aws'
},
{
from: [
'/protocols/saml/saml-apps/atlassian',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-atlassian'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-atlassian'
},
{
from: [
'/saml-apps/cisco-webex',
'/protocols/saml/saml-apps/cisco-webex',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-cisco-webex',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-cisco-webex'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-cisco-webex'
},
{
from: [
'/saml-apps/datadog',
'/protocols/saml/saml-apps/datadog',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-datadog',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-datadog'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-datadog'
},
{
from: [
'/protocols/saml/saml-apps/egencia',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-egencia'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-egencia'
},
{
from: [
'/saml-apps/freshdesk',
'/protocols/saml/saml-apps/freshdesk',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-freshdesk',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-freshdesk'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-freshdesk'
},
{
from: [
'/protocols/saml/saml-apps/github-cloud',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-github-enterprise-cloud'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-github-enterprise-cloud'
},
{
from: [
'/integrations/using-auth0-as-an-identity-provider-with-github-enterprise',
'/protocols/saml/saml-apps/github-server',
'/tutorials/using-auth0-as-an-identity-provider-with-github-enterprise',
'/scenarios/github',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-github-enterprise-server'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-github-enterprise-server'
},
{
from: [
'/protocols/saml/saml-apps/google-apps',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-idp-for-google-g-suite'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-idp-for-google-g-suite'
},
{
from: [
'/protocols/saml/saml-apps/heroku','/saml-apps/heroku-sso',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-heroku'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-heroku'
},
{
from: [
'/protocols/saml/saml-apps/hosted-graphite',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-hosted-graphite'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-hosted-graphite'
},
{
from: [
'/protocols/saml/saml-apps/litmos',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-litmos',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-litmos'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-litmos'
},
{
from: [
'/protocols/saml/saml-idp-eloqua',
'/protocols/saml/saml-apps/eloqua',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-addon-eloqua'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-addon-eloqua'
},
{
from: [
'/protocols/saml/saml-apps/pluralsight',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-pluralsight'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-pluralsight'
},
{
from: [
'/protocols/saml/saml-apps/sprout-video',
'/saml-apps/sprout-video',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-sprout-video',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-sprout-video'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-sprout-video'
},
{
from: [
'/protocols/saml/saml-apps/tableau-online',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-tableau-online'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-tableau-online'
},
{
from: [
'/protocols/saml/saml-apps/tableau-server',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-tableau-server'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-tableau-server'
},
{
from: [
'/protocols/saml/saml-apps/workday',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-workday'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-workday'
},
{
from: [
'/protocols/saml/saml-apps/workpath',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-workpath'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-workpath'
},
{
from: [
'/protocols/saml-configuration-options/configure-auth0-saml-service-provider',
'/protocols/saml/saml-sp-generic',
'/saml-sp-generic',
'/protocols/saml/saml-configuration/auth0-as-service-provider',
'/protocols/saml-protocol/configure-auth0-saml-service-provider'
],
to: '/configure/saml-configuration/configure-auth0-saml-service-provider'
},
{
from: [
'/protocols/saml-configuration-options/configure-auth0-as-saml-identity-provider',
'/saml-idp-generic','/protocols/saml/saml-idp-generic',
'/protocols/saml/saml-configuration/auth0-as-identity-provider',
'/protocols/saml-protocol/configure-auth0-as-saml-identity-provider'
],
to: '/configure/saml-configuration/configure-auth0-as-saml-identity-provider'
},
{
from: [
'/protocols/saml-configuration-options/saml-identity-provider-configuration-settings',
'/samlp',
'/protocols/saml/samlp',
'/protocols/saml-protocol/saml-identity-provider-configuration-settings'
],
to: '/configure/saml-configuration/saml-identity-provider-configuration-settings'
},
{
from: [
'/protocols/saml-configuration-options/customize-saml-assertions',
'/protocols/saml/saml-configuration/saml-assertions',
'/protocols/saml-protocol/customize-saml-assertions'
],
to: '/configure/saml-configuration/customize-saml-assertions'
},
{
from: [
'/protocols/saml-configuration-options/test-saml-sso-with-auth0-as-service-and-identity-provider',
'/protocols/saml/samlsso-auth0-to-auth0',
'/samlsso-auth0-to-auth0',
'/protocols/saml-configuration-options/configure-auth0-as-service-and-identity-provider',
'/protocols/saml/saml-configuration/auth0-as-identity-and-service-provider',
'/protocols/saml-protocol/configure-auth0-as-service-and-identity-provider'
],
to: '/configure/saml-configuration/configure-auth0-as-service-and-identity-provider'
},
{
from: [
'/protocols/saml-configuration-options/deprovision-users-in-saml-integrations',
'/protocols/saml/saml-configuration/deprovision-users',
'/protocols/saml-protocol/deprovision-users-in-saml-integrations'
],
to: '/configure/saml-configuration/deprovision-users-in-saml-integrations'
},
/* Signing Keys */
{
from: [
'/authorization/set-logical-api',
'/authorization/represent-multiple-apis-using-a-single-logical-api',
'/api-auth/tutorials/represent-multiple-apis'
],
to: '/configure/api-settings/set-logical-api'
},
/* Single Sign-On */
{
from: [
'/api-auth/tutorials/adoption/single-sign-on',
'/sso/legacy',
'/sso/legacy/single-page-apps',
'/sso/legacy/regular-web-apps-sso',
'/sso/legacy/single-page-apps-sso',
'/sso/current/single-page-apps-sso',
'/sso/current/single-page-apps',
'/sso/current/sso-auth0',
'/sso/current/introduction',
'/sso/single-sign-on',
'/sso/current',
'/sso/current/setup',
'/sso/current/index_old',
'/sso'
],
to: '/configure/sso'
},
{
from: ['/sso/inbound-single-sign-on','/sso/current/inbound'],
to: '/configure/sso/inbound-single-sign-on'
},
{
from: ['/sso/outbound-single-sign-on','/sso/current/outbound'],
to: '/configure/sso/outbound-single-sign-on'
},
{
from: [
'/single-sign-on/api-endpoints-for-single-sign-on',
'/sso/current/relevant-api-endpoints',
'/sso/api-endpoints-for-single-sign-on'
],
to: '/configure/sso/api-endpoints-for-single-sign-on'
},
/* SAML */
{
from: [
'/saml-apps',
'/protocols/saml/identity-providers',
'/samlp-providers',
'/protocols/saml/samlp-providers',
'/protocols/saml',
'/protocols/saml-protocol',
'/configure/saml-protocol',
'/protocols/saml-configuration-options',
'/protocols/saml/saml-apps',
'/protocols/saml/saml-configuration/supported-options-and-bindings',
'/protocols/saml/saml-configuration/design-considerations',
'/protocols/saml/saml-configuration-options',
'/saml-configuration'
],
to: '/configure/saml-configuration'
},
{
from: [
'/protocols/saml/saml-configuration',
'/protocols/saml/saml-configuration/special-configuration-scenarios',
'/protocols/saml-protocol/saml-configuration-options/special-saml-configuration-scenarios'
],
to: '/configure/saml-configuration/saml-sso-integrations'
},
{
from: [
'/protocols/saml/idp-initiated-sso',
'/protocols/saml-configuration-options/identity-provider-initiated-single-sign-on',
'/protocols/saml/saml-configuration/special-configuration-scenarios/idp-initiated-sso',
'/protocols/saml-protocol/saml-configuration-options/identity-provider-initiated-single-sign-on'
],
to: '/configure/saml-configuration/saml-sso-integrations/identity-provider-initiated-single-sign-on'
},
{
from: [
'/protocols/saml-configuration-options/sign-and-encrypt-saml-requests',
'/protocols/saml/saml-configuration/special-configuration-scenarios/signing-and-encrypting-saml-requests',
'/protocols/saml-protocol/saml-configuration-options/sign-and-encrypt-saml-requests'
],
to: '/configure/saml-configuration/saml-sso-integrations/sign-and-encrypt-saml-requests'
},
{
from: '/protocols/saml-protocol/saml-configuration-options/work-with-certificates-and-keys-as-strings',
to: '/configure/saml-configuration/saml-sso-integrations/work-with-certificates-and-keys-as-strings'
},
{
from: [
'/protocols/saml/adfs',
'/protocols/saml-protocol/saml-configuration-options/configure-adfs-saml-connections'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-adfs-saml-connections'
},
{
from: [
'/protocols/saml/identity-providers/okta',
'/okta',
'/saml/identity-providers/okta',
'/protocols/saml-configuration-options/configure-okta-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-okta-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-okta-as-saml-identity-provider'
},
{
from: [
'/onelogin',
'/saml/identity-providers/onelogin',
'/protocols/saml/identity-providers/onelogin',
'/protocols/saml-configuration-options/configure-onelogin-as-saml-identity-provider',
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-onelogin-as-saml-identity-provider'
},
{
from: [
'/ping7',
'/saml/identity-providers/ping7',
'/protocols/saml/identity-providers/ping7',
'/protocols/saml-configuration-options/configure-pingfederate-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration/configure-pingfederate-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-pingfederate-as-saml-identity-provider'
},
{
from: [
'/saml/identity-providers/salesforce',
'/protocols/saml/identity-providers/salesforce',
'/protocols/saml-configuration-options/configure-salesforce-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-salesforce-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-salesforce-as-saml-identity-provider'
},
{
from: [
'/siteminder',
'/saml/identity-providers/siteminder',
'/protocols/saml/identity-providers/siteminder',
'/protocols/saml-configuration-options/configure-siteminder-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-siteminder-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-siteminder-as-saml-identity-provider'
},
{
from: [
'/ssocircle',
'/saml/identity-providers/ssocircle',
'/protocols/saml/identity-providers/ssocircle',
'/protocols/saml-configuration-options/configure-ssocircle-as-saml-identity-provider',
'/protocols/saml-protocol/saml-configuration-options/configure-ssocircle-as-saml-identity-provider'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-ssocircle-as-saml-identity-provider'
},
{
from: [
'/saml2webapp-tutorial',
'/protocols/saml/saml2webapp-tutorial',
'/protocols/saml-protocol/saml-configuration-options/enable-saml2-web-app-addon'
],
to: '/configure/saml-configuration/saml-sso-integrations/enable-saml2-web-app-addon'
},
{
from: [
'/configure/saml-configuration-options/configure-saml2-web-app-addon-for-aws',
'/dashboard/guides/applications/set-up-addon-saml2-aws',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-aws'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-aws'
},
{
from: [
'/protocols/saml/saml-apps/atlassian',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-atlassian'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-atlassian'
},
{
from: [
'/saml-apps/cisco-webex',
'/protocols/saml/saml-apps/cisco-webex',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-cisco-webex',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-cisco-webex'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-cisco-webex'
},
{
from: [
'/saml-apps/datadog',
'/protocols/saml/saml-apps/datadog',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-datadog',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-datadog'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-datadog'
},
{
from: [
'/protocols/saml/saml-apps/egencia',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-egencia'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-egencia'
},
{
from: [
'/saml-apps/freshdesk',
'/protocols/saml/saml-apps/freshdesk',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-freshdesk',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-freshdesk'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-freshdesk'
},
{
from: [
'/protocols/saml/saml-apps/github-cloud',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-github-enterprise-cloud'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-github-enterprise-cloud'
},
{
from: [
'/integrations/using-auth0-as-an-identity-provider-with-github-enterprise',
'/protocols/saml/saml-apps/github-server',
'/tutorials/using-auth0-as-an-identity-provider-with-github-enterprise',
'/scenarios/github',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-github-enterprise-server'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-github-enterprise-server'
},
{
from: [
'/protocols/saml/saml-apps/google-apps',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-idp-for-google-g-suite'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-idp-for-google-g-suite'
},
{
from: [
'/protocols/saml/saml-apps/heroku','/saml-apps/heroku-sso',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-web-app-addon-for-heroku'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-web-app-addon-for-heroku'
},
{
from: [
'/protocols/saml/saml-apps/hosted-graphite',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-hosted-graphite'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-hosted-graphite'
},
{
from: [
'/protocols/saml/saml-apps/litmos',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-litmos',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-litmos'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-litmos'
},
{
from: [
'/protocols/saml/saml-idp-eloqua',
'/protocols/saml/saml-apps/eloqua',
'/protocols/saml-protocol/saml-configuration-options/configure-saml2-addon-eloqua'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-saml2-addon-eloqua'
},
{
from: [
'/protocols/saml/saml-apps/pluralsight',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-pluralsight'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-pluralsight'
},
{
from: [
'/protocols/saml/saml-apps/sprout-video',
'/saml-apps/sprout-video',
'/protocols/saml-configuration-options/configure-auth0-as-identity-provider-for-sprout-video',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-sprout-video'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-sprout-video'
},
{
from: [
'/protocols/saml/saml-apps/tableau-online',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-tableau-online'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-tableau-online'
},
{
from: [
'/protocols/saml/saml-apps/tableau-server',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-tableau-server'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-tableau-server'
},
{
from: [
'/protocols/saml/saml-apps/workday',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-workday'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-workday'
},
{
from: [
'/protocols/saml/saml-apps/workpath',
'/protocols/saml-protocol/saml-configuration-options/configure-auth0-as-identity-provider-for-workpath'
],
to: '/configure/saml-configuration/saml-sso-integrations/configure-auth0-as-identity-provider-for-workpath'
},
{
from: [
'/protocols/saml-configuration-options/configure-auth0-saml-service-provider',
'/protocols/saml/saml-sp-generic',
'/saml-sp-generic',
'/protocols/saml/saml-configuration/auth0-as-service-provider',
'/protocols/saml-protocol/configure-auth0-saml-service-provider'
],
to: '/configure/saml-configuration/configure-auth0-saml-service-provider'
},
{
from: [
'/protocols/saml-configuration-options/configure-auth0-as-saml-identity-provider',
'/saml-idp-generic','/protocols/saml/saml-idp-generic',
'/protocols/saml/saml-configuration/auth0-as-identity-provider',
'/protocols/saml-protocol/configure-auth0-as-saml-identity-provider'
],
to: '/configure/saml-configuration/configure-auth0-as-saml-identity-provider'
},
{
from: [
'/protocols/saml-configuration-options/saml-identity-provider-configuration-settings',
'/samlp',
'/protocols/saml/samlp',
'/protocols/saml-protocol/saml-identity-provider-configuration-settings'
],
to: '/configure/saml-configuration/saml-identity-provider-configuration-settings'
},
{
from: [
'/protocols/saml-configuration-options/customize-saml-assertions',
'/protocols/saml/saml-configuration/saml-assertions',
'/protocols/saml-protocol/customize-saml-assertions'
],
to: '/configure/saml-configuration/customize-saml-assertions'
},
{
from: [
'/protocols/saml-configuration-options/test-saml-sso-with-auth0-as-service-and-identity-provider',
'/protocols/saml/samlsso-auth0-to-auth0',
'/samlsso-auth0-to-auth0',
'/protocols/saml-configuration-options/configure-auth0-as-service-and-identity-provider',
'/protocols/saml/saml-configuration/auth0-as-identity-and-service-provider',
'/protocols/saml-protocol/configure-auth0-as-service-and-identity-provider'
],
to: '/configure/saml-configuration/configure-auth0-as-service-and-identity-provider'
},
{
from: [
'/protocols/saml-configuration-options/deprovision-users-in-saml-integrations',
'/protocols/saml/saml-configuration/deprovision-users',
'/protocols/saml-protocol/deprovision-users-in-saml-integrations'
],
to: '/configure/saml-configuration/deprovision-users-in-saml-integrations'
},
/* Signing Keys */
{
from: [
'/actions/build-actions-flows',
'/actions/edit-actions',
'/actions/troubleshoot-actions'
],
to: '/actions/write-your-first-action'
},
{
from: [
'/actions/actions-context-object',
'/actions/actions-event-object',
'/actions/blueprints'
],
to: '/actions/triggers'
},
{
from: [
'/actions/manage-action-versions'
],
to: '/actions/manage-versions'
},
/* Anomaly Detection */
{
from: [
'/anomaly-',
'/anomaly',
'/anomaly-detection/references/anomaly-detection-faqs',
'/anomaly-detection/references/anomaly-detection-restrictions-limitations',
'/anomaly-detection/guides/set-anomaly-detection-preferences',
'/anomaly-detection/set-anomaly-detection-preferences',
'/attack-protection/set-attack-protection-preferences',
'/anomaly-detection',
'/attack-protection'
],
to: '/configure/attack-protection'
},
{
from: [
'/anomaly-detection/references/breached-password-detection-triggers-actions',
'/anomaly-detection/concepts/breached-passwords',
'/anomaly-detection/breached-passwords',
'/anomaly-detection/breached-password-security',
'/attack-protection/breached-password-detection'
],
to: '/configure/attack-protection/breached-password-detection'
},
{
from: [
'/anomaly-detection/bot-protection',
'/anomaly-detection/guides/prevent-credential-stuffing-attacks',
'/anomaly-detection/bot-and-credential-stuffing-protection',
'/anomaly-detection/bot-detection',
'/attack-protection/bot-detection'
],
to: '/configure/attack-protection/bot-detection'
},
{
from: '/anomaly-detection/bot-detection/configure-recaptcha-enterprise',
to: '/configure/anomaly-detection/bot-detection/configure-recaptcha-enterprise'
},
{
from: '/anomaly-detection/bot-detection/bot-detection-custom-login-pages',
to: '/configure/anomaly-detection/bot-detection/bot-detection-custom-login-pages'
},
{
from: '/anomaly-detection/bot-detection/bot-detection-native-apps',
to: '/configure/anomaly-detection/bot-detection/bot-detection-native-apps'
},
{
from: [
'/anomaly-detection/references/brute-force-protection-triggers-actions',
'/anomaly-detection/guides/enable-disable-brute-force-protection',
'/anomaly-detection/concepts/brute-force-protection',
'/anomaly-detection/enable-and-disable-brute-force-protection',
'/anomaly-detection/brute-force-protection',
'/attack-protection/brute-force-protection'
],
to: '/configure/attack-protection/brute-force-protection'
},
{
from: '/anomaly-detection/suspicious-ip-throttling',
to: '/configure/anomaly-detection/suspicious-ip-throttling'
},
{
from: [
'/anomaly-detection/guides/use-tenant-data-for-anomaly-detection',
'/anomaly-detection/view-anomaly-detection-events',
'/attack-protection/view-attack-protection-events'
],
to: '/configure/attack-protection/view-attack-protection-events'
},
/* API */
{
from: ['/auth-api', '/api/authentication/reference'],
to: '/api/authentication'
},
{
from: ['/apiv2', '/api/v2','/api/management'],
to: '/api/management/v2'
},
{
from: ['/auth0-apis', '/api/info'],
to: '/api'
},
{
from: ['/api/management/v1','/api-reference','/api/v1/reference','/api/management/v1/reference'],
to: '/api/management-api-v1-deprecated'
},
{
from: ['/api/management/v2/changes','/apiv2Changes', '/api/v2/changes'],
to: '/api/management-api-changes-v1-to-v2'
},
{
from: ['/api/use-auth0-apis-with-postman-collections','/api/postman'],
to: '/api'
},
/* Authorization */
{
from: ['/apis'],
to: '/authorization/apis'
},
{
from: [
'/flows/concepts/auth-code',
'/flows/concepts/regular-web-app-login-flow',
'/api-auth/grant/authorization-code',
'/api-auth/tutorials/adoption/authorization-code',
'/api-auth/adoption/authorization-code',
'/flows/authorization-code-flow'
],
to: '/authorization/authorization-flows/authorization-code-flow'
},
{
from: [
'/flows/concepts/auth-code-pkce',
'/api-auth/grant/authorization-code-pkce',
'/flows/concepts/mobile-login-flow',
'/flows/concepts/single-page-login-flow',
'/flows/authorization-code-flow-with-proof-key-for-code-exchange-pkce'
],
to: '/authorization/authorization-flows/authorization-code-flow-with-proof-key-for-code-exchange-pkce'
},
{
from: [
'/flows/guides/implicit/call-api-implicit',
'/flows/guides/implicit/includes/sample-use-cases-call-api',
'/flows/guides/implicit/includes/call-api',
'/flows/guides/implicit/includes/authorize-user-call-api',
'/flows/guides/single-page-login-flow/call-api-using-single-page-login-flow',
'/api-auth/grant/implicit',
'/api-auth/tutorials/adoption/implicit',
'/api-auth/tutorials/implicit-grant',
'/protocols/oauth2/oauth-implicit-protocol',
'/flows/concepts/implicit',
'/flows/implicit-flow-with-form-post'
],
to: '/authorization/authorization-flows/implicit-flow-with-form-post'
},
{
from: ['/flows/hybrid-flow','/api-auth/grant/hybrid'],
to: '/authorization/authorization-flows/hybrid-flow'
},
{
from: [
'/flows/concepts/client-credentials',
'/flows/concepts/m2m-flow',
'/api-auth/grant/client-credentials',
'/api-auth/tutorials/adoption/client-credentials',
'/flows/client-credentials-flow'
],
to: '/authorization/authorization-flows/client-credentials-flow'
},
{
from: [
'/flows/concepts/device-auth',
'/flows/guides/device-auth/call-api-device-auth',
'/flows/device-authorization-flow'
],
to: '/authorization/authorization-flows/device-authorization-flow'
},
{
from: [
'/api-auth/grant/password',
'/api-auth/tutorials/adoption/password',
'/flows/resource-owner-password-flow'
],
to: '/authorization/authorization-flows/resource-owner-password-flow'
},
{
from: [
'/authorization/revoke-access-to-apis-using-blacklists-or-application-grants',
'/api-auth/blacklists-vs-grants','/blacklists-vs-application-grants'
],
to: '/authorization/revoke-api-access'
},
{
from: [
'/authorization/rbac/roles/view-users-assigned-to-roles',
'/api/management/guides/roles/view-role-users',
'/dashboard/guides/roles/view-role-users'
],
to: '/authorization/auth-core-features/roles/view-users-assigned-to-roles'
},
{
from: [
'/authorization/rbac/roles/delete-roles',
'/dashboard/guides/roles/delete-roles',
'/api/management/guides/roles/delete-roles'
],
to: '/authorization/auth-core-features/roles/delete-roles'
},
{
from: [
'/authorization/rbac/roles/edit-role-definitions',
'/authorization/rbac/roles/edit-role-definitions',
'/dashboard/guides/roles/edit-role-definitions',
'/api/management/guides/roles/edit-role-definitions',
'/authorization/guides/api/edit-role-definitions'
],
to: '/authorization/auth-core-features/roles/edit-role-definitions'
},
{
from: [
'/authorization/rbac/roles/remove-permissions-from-roles',
'/dashboard/guides/roles/remove-role-permissions',
'/api/management/guides/roles/remove-role-permissions'
],
to: '/authorization/auth-core-features/roles/remove-permissions-from-roles'
},
{
from: [
'/authorization/rbac/roles/view-role-permissions',
'/dashboard/guides/roles/view-role-permissions',
'/api/management/guides/roles/view-role-permissions'
],
to: '/authorization/auth-core-features/roles/view-role-permissions'
},
{
from: [
'/api/management/guides/apis/enable-rbac',
'/dashboard/guides/apis/enable-rbac',
'/authorization/guides/dashboard/enable-rbac',
'/authorization/rbac/enable-role-based-access-control-for-apis'
],
to: '/authorization/auth-core-features/enable-role-based-access-control-for-apis'
},
{
from: [
'/authorization/rbac/roles/add-permissions-to-roles',
'/dashboard/guides/roles/add-permissions-roles',
'/api/management/guides/roles/add-permissions-roles'
],
to: '/authorization/auth-core-features/roles/add-permissions-to-roles'
},
{
from: [
'/authorization/rbac/roles/create-roles',
'/dashboard/guides/roles/create-roles',
'/api/management/guides/roles/create-roles'
],
to: '/authorization/auth-core-features/roles/create-roles'
},
{
from: ['/authorization/reference/rbac-limits','/authorization/rbac/authorization-core-rbac-limits'],
to: '/policies/entity-limit-policy'
},
{
from: ['/authorization/authentication-and-authorization', '/authorization/concepts/authz-and-authn','/application-auth/current','/application-auth/legacy','/application-auth'],
to: '/get-started/authentication-and-authorization'
},
{
from: ['/authorization/concepts/authz-rules'],
to: '/authorization/rules-for-authorization-policies'
},
{
from: ['/authorization/concepts/core-vs-extension'],
to: '/authorization/authorization-core-vs-authorization-extension'
},
{
from: ['/authorization/concepts/policies'],
to: '/authorization/authorization-policies'
},
{
from: ['/authorization/concepts/rbac'],
to: '/authorization/rbac'
},
{
from: ['/authorization/concepts/sample-use-cases-rbac'],
to: '/authorization/sample-use-cases-role-based-access-control'
},
{
from: ['/authorization/how-to-use-auth0s-core-authorization-feature-set','/authorization/guides/how-to'],
to: '/authorization/auth-core-features'
},
{
from: ['/authorization/guides/manage-permissions'],
to: '/authorization/manage-permissions'
},
{
from: ['/authorization/rbac/roles','/authorization/guides/manage-roles'],
to: '/authorization/auth-core-features/roles'
},
{
from: ['/api-auth/apis','/overview/apis'],
to: '/authorization/apis'
},
{
from: ['/api-auth','/api-auth/tutorials','/api/tutorials'],
to: '/authorization'
},
{
from: ['/api-auth/restrict-access-api','/api-auth/restrict-requests-for-scopes','/authorization/concepts/sample-use-cases-rules','/authorization/restrict-access-api'],
to: '/authorization/sample-use-cases-rules-with-authorization'
},
{
from: ['/api-auth/token-renewal-in-safari'],
to: '/authorization/renew-tokens-when-using-safari'
},
{
from: ['/api-auth/user-consent'],
to: '/authorization/user-consent-and-third-party-applications'
},
{
from: ['/api-auth/which-oauth-flow-to-use', '/api-auth/faq', '/authorization/authentication-and-authorization-api-faq'],
to: '/authorization/which-oauth-2-0-flow-should-i-use'
},
{
from: ['/api-auth/tutorials/nonce'],
to: '/authorization/mitigate-replay-attacks-when-using-the-implicit-flow'
},
{
from: ['/api-auth/tutorials/using-resource-owner-password-from-server-side','/authorization/avoid-common-issues-with-resource-owner-password-flow-and-anomaly-detection'],
to: '/authorization/avoid-common-issues-with-resource-owner-password-flow-and-attack-protection'
},
{
from: ['/api-auth/tutorials/client-credentials/customize-with-hooks','/api-auth/grant/using-rules'],
to: '/authorization/customize-tokens-using-hooks-with-client-credentials-flow'
},
{
from: ['/authorization/rbac-users','/authorization/guides/manage-users'],
to: '/authorization/auth-core-features/rbac-users'
},
/* Best Practices */
{
from: [
'/best-practices/custom-db-connections',
'/best-practices/custom-db-connections-scripts',
'/best-practices/custom-database-connection-and-action-script-best-practices'
],
to: '/best-practices/custom-database-connections-scripts'
},
{
from: [
'/best-practices/custom-db-connections/anatomy',
'/best-practices/custom-db-connections/size',
'/best-practices/custom-database-connection-and-action-script-best-practices/custom-db-connection-anatomy-best-practices'
],
to: '/best-practices/custom-database-connections-scripts/anatomy'
},
{
from: [
'/best-practices/custom-db-connections/environment',
'/best-practices/custom-database-connection-and-action-script-best-practices/custom-db-action-script-environment-best-practices'
],
to: '/best-practices/custom-database-connections-scripts/environment'
},
{
from: [
'/best-practices/custom-db-connections/execution',
'/best-practices/custom-database-connection-and-action-script-best-practices/custom-database-action-script-execution-best-practices'
],
to: '/best-practices/custom-database-connections-scripts/execution'
},
{
from: [
'/best-practices/custom-db-connections/security',
'/best-practices/custom-database-connection-and-action-script-best-practices/custom-db-connection-security-best-practices'
],
to: '/best-practices/custom-database-connections-scripts/connection-security'
},
{
from: ['/best-practices/connection-settings'],
to: '/best-practices/connection-settings-best-practices'
},
{
from: ['/best-practices/debugging'],
to: '/best-practices/debugging-best-practices'
},
{
from: ['/best-practices/deployment'],
to: '/best-practices/deployment-best-practices'
},
{
from: ['/best-practices/error-handling'],
to: '/best-practices/error-handling-best-practices'
},
{
from: ['/best-practices/operations'],
to: '/best-practices/general-usage-and-operations-best-practices'
},
{
from: ['/best-practices/performance'],
to: '/best-practices/performance-best-practices'
},
{
from: ['/best-practices/rules'],
to: '/best-practices/rules-best-practices'
},
{
from: ['/best-practices/search-best-practices','/users/search/best-practices'],
to: '/best-practices/user-search-best-practices'
},
{
from: ['/best-practices/testing'],
to: '/best-practices/rules-best-practices/rules-testing-best-practices'
},
{
from: ['/tokens/concepts/token-best-practices','/design/web-apps-vs-web-apis-cookies-vs-tokens'],
to: '/best-practices/token-best-practices'
},
{
from: ['/design/using-auth0-with-multi-tenant-apps','/applications/concepts/multiple-tenants','/tutorials/using-auth0-with-multi-tenant-apps','/saas-apps'],
to: '/best-practices/multi-tenant-apps-best-practices'
},
/* Brand and Customize */
{
from: ['/branding-customization'],
to: '/brand-and-customize'
},
{
from: ['/universal-login/new-experience/universal-login-page-templates','/universal-login/page-templates'],
to: '/brand-and-customize/universal-login-page-templates'
},
{
from: [
'/universal-login/classic-experience/customization-classic',
'/universal-login/customization-classic',
'/universal-login/advanced-customization'
],
to: '/brand-and-customize/customization-classic'
},
{
from: [
'/universal-login/version-control-universal-login-pages',
'/universal-login/version-control',
'/hosted-pages/version-control'
],
to: '/brand-and-customize/version-control-universal-login-pages'
},
/* Custom Domains */
{
from: '/custom-domains',
to: '/brand-and-customize/custom-domains'
},
{
from: ['/custom-domains/configure-custom-domains-with-auth0-managed-certificates','/custom-domains/auth0-managed-certificates'],
to: '/brand-and-customize/custom-domains/auth0-managed-certificates'
},
{
from: ['/custom-domains/self-managed-certificates','/custom-domains/configure-custom-domains-with-self-managed-certificates'],
to: '/brand-and-customize/custom-domains/self-managed-certificates'
},
{
from: '/custom-domains/tls-ssl',
to: '/brand-and-customize/custom-domains/self-managed-certificates/tls-ssl'
},
{
from: '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-gcp-as-reverse-proxy',
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-gcp-as-reverse-proxy'
},
{
from: [
'/custom-domains/set-up-cloudfront',
'/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-aws-cloudfront-for-use-as-reverse-proxy'
],
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-aws-cloudfront-for-use-as-reverse-proxy'
},
{
from: [
'/custom-domains/set-up-cloudflare',
'/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-cloudflare-for-use-as-reverse-proxy'
],
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-cloudflare-for-use-as-reverse-proxy'
},
{
from: [
'/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-azure-cdn-for-use-as-reverse-proxy',
'/custom-domains/set-up-azure-cdn'
],
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-azure-cdn-for-use-as-reverse-proxy'
},
{
from: '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-akamai-for-use-as-reverse-proxy',
to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-akamai-for-use-as-reverse-proxy'
},
{
from: ['/custom-domains/configure-features-to-use-custom-domains','/custom-domains/additional-configuration'],
to: '/brand-and-customize/custom-domains/configure-features-to-use-custom-domains'
},
/* Email */
{
from: ['/email','/auth0-email-services'],
to: '/brand-and-customize/email'
},
{
from: [
'/email/custom',
'/auth0-email-services/manage-email-flow',
'/email/manage-email-flow'
],
to: '/brand-and-customize/email/manage-email-flow'
},
{
from: [
'/email/templates',
'/auth0-email-services/customize-email-templates',
'/email/spa-redirect',
'/auth0-email-services/spa-redirect',
'/email/customize-email-templates'
],
to: '/brand-and-customize/email/customize-email-templates'
},
{
from: [
'/email/customize-email-templates/email-template-descriptions',
'/auth0-email-services/email-template-descriptions'
],
to: '/brand-and-customize/email/email-template-descriptions'
},
{
from: [
'/anomaly-detection/guides/customize-blocked-account-emails',
'/anomaly-detection/customize-blocked-account-emails',
'/attack-protection/customize-blocked-account-emails'
],
to: '/brand-and-customize/email/customize-blocked-account-emails'
},
{
from: [
'/email/liquid-syntax',
'/auth0-email-services/customize-email-templates/use-liquid-syntax-in-email-templates',
'/email/customize-email-templates/use-liquid-syntax-in-email-templates'
],
to: '/brand-and-customize/email/use-liquid-syntax-in-email-templates'
},
{
from: [
'/design/creating-invite-only-applications',
'/invite-only',
'/tutorials/creating-invite-only-applications',
'/auth0-email-services/send-email-invitations-for-application-signup',
'/email/send-email-invitations-for-application-signup'
],
to: '/brand-and-customize/email/send-email-invitations-for-application-signup'
},
{
from: '/email/send-email-invitations-for-application-signup',
to: '/brand-and-customize/email/send-email-invitations-for-application-signup'
},
{
from: [
'/auth0-email-services/configure-external-smtp-email-providers',
'/email/providers',
'/email/configure-external-smtp-email-providers'
],
to: '/brand-and-customize/email/smtp-email-providers'
},
{
from: '/email/configure-external-smtp-email-providers/configure-amazon-ses-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-amazon-ses-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-mandrill-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-mandrill-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-sendgrid-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-sendgrid-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-sparkpost-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-sparkpost-as-external-smtp-email-provider'
},
{
from: '/email/configure-external-smtp-email-providers/configure-mailgun-as-external-smtp-email-provider',
to: '/brand-and-customize/email/smtp-email-providers/configure-mailgun-as-external-smtp-email-provider'
},
{
from: [
'/auth0-email-services/configure-external-smtp-email-providers/configure-custom-external-smtp-email-provider',
'/email/configure-custom-external-smtp-email-provider'
],
to: '/brand-and-customize/email/smtp-email-providers/configure-custom-external-smtp-email-provider'
},
{
from: [
'/email/testing',
'/auth0-email-services/configure-external-smtp-email-providers/configure-test-smtp-email-servers',
'/email/configure-test-smtp-email-servers'
],
to: '/brand-and-customize/email/configure-test-smtp-email-servers'
},
{
from: [
'/universal-login/new-experience/text-customization-new-universal-login',
'/universal-login/text-customization'
],
to: '/brand-and-customize/text-customization-new-universal-login'
},
{
from: ['/scopes/customize-consent-prompts','/scopes/current/guides/customize-consent-prompt'],
to: '/brand-and-customize/customize-consent-prompts'
},
{
from: ['/universal-login/custom-error-pages','/error-pages/custom', '/hosted-pages/custom-error-pages'],
to: '/brand-and-customize/custom-error-pages'
},
{
from: [
'/libraries/lock/customize-lock-error-messages',
'/libraries/lock/v11/customizing-error-messages',
'/libraries/lock/customizing-error-messages'
],
to: '/brand-and-customize/customize-lock-error-messages'
},
{
from: [
'/universal-login/customize-password-reset-page',
'/universal-login/password-reset',
'/hosted-pages/password-reset'
],
to: '/brand-and-customize/customize-password-reset-page'
},
{
from: [
'/multifactor-authentication/administrator/sms-templates',
'/mfa/guides/guardian/customize-sms-messages',
'/multifactor-authentication/sms-templates',
'/mfa/guides/customize-phone-messages',
'/mfa/customize-sms-or-voice-messages'
],
to: '/brand-and-customize/customize-sms-or-voice-messages'
},
/* Internationalization and Localization */
{
from: ['/i18n','/i18n/i18n-custom-login-page'],
to: '/brand-and-customize/i18n'
},
{
from: [
'/i18n/universal-login-internationalization',
'/universal-login/i18n',
'/universal-login/universal-login-internationalization'
],
to: '/brand-and-customize/i18n/universal-login-internationalization'
},
{
from: ['/libraries/lock/v11/i18n', '/libraries/lock/v10/i18n', '/libraries/lock/lock-internationalization'],
to: '/brand-and-customize/i18n/lock-internationalization'
},
{
from: [
'/libraries/lock-swift/lock-swift-internationalization',
'/i18n/i18n-guide-ios',
'/libraries/lock-ios/v2/internationalization',
'/libraries/lock-swift/lock-swift-internationalization'
],
to: '/brand-and-customize/i18n/lock-swift-internationalization'
},
{
from: [
'/i18n/i18n-guide-android',
'/libraries/lock-android/v2/internationalization',
'/libraries/lock-android/v1/internationalization',
'/libraries/lock-android/lock-android-internationalization'
],
to: '/brand-and-customize/i18n/lock-android-internationalization'
},
{
from: [
'/i18n/password-options-translation',
'/i18n/password-options',
'/i18n/password-strength'
],
to: '/brand-and-customize/i18n/password-options-translation'
},
/* CMS */
{
from: ['/cms/joomla/configuration'],
to: '/cms/integrate-with-joomla'
},
{
from: ['/cms/joomla/installation'],
to: '/cms/joomla-installation'
},
{
from: ['/cms/wordpress','/cms/wordpress/jwt-authentication'],
to: '/cms/wordpress-plugin'
},
{
from: ['/cms/wordpress/installation'],
to: '/cms/wordpress-plugin/install-login-by-auth0'
},
{
from: ['/cms/wordpress/configuration'],
to: '/cms/wordpress-plugin/configure-login-by-auth0'
},
{
from: ['/cms/wordpress/extending'],
to: '/cms/wordpress-plugin/extend-login-by-auth0'
},
{
from: ['/cms/wordpress/troubleshoot'],
to: '/cms/wordpress-plugin/troubleshoot-login-by-auth0'
},
{
from: ['/cms/wordpress/invalid-state'],
to: '/cms/wordpress-plugin/troubleshoot-wordpress-plugin-invalid-state-errors'
},
{
from: ['/cms/wordpress/user-migration'],
to: '/cms/wordpress-plugin/user-migration-in-login-by-auth0'
},
{
from: ['/cms/wordpress/user-migration'],
to: '/cms/wordpress-plugin/user-migration-in-login-by-auth0'
},
{
from: ['/cms/wordpress/how-does-it-work'],
to: '/cms/wordpress-plugin/integrate-with-wordpress'
},
/* Compliance */
{
from: ['/compliance-and-certifications'],
to: '/compliance'
},
{
from: ['/compliance/gdpr/data-processing'],
to: '/compliance/data-processing'
},
{
from: ['/compliance/gdpr/features-aiding-compliance','/compliance/gdpr/security-advice-for-customers','/compliance/gdpr/roles-responsibilities','/compliance/gdpr/gdpr-summary','/compliance/gdpr/definitions','/compliance/auth0-gdpr-compliance'],
to: '/compliance/gdpr'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/user-consent'],
to: '/compliance/gdpr/gdpr-conditions-for-consent'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/data-minimization'],
to: '/compliance/gdpr/gdpr-data-minimization'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/data-portability'],
to: '/compliance/gdpr/gdpr-data-portability'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/protect-user-data'],
to: '/compliance/gdpr/gdpr-protect-and-secure-user-data'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/right-to-access-data'],
to: '/compliance/gdpr/gdpr-right-to-access-correct-and-erase-data'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/user-consent/track-consent-with-custom-ui'],
to: '/compliance/gdpr/gdpr-track-consent-with-custom-ui'
},
{
from: ['/compliance/gdpr/features-aiding-compliance/user-consent/track-consent-with-lock'],
to: '/compliance/gdpr/gdpr-track-consent-with-lock'
},
/* Deploy */
{
from: ['/get-started/deployment-options', '/getting-started/deployment-models','/overview/deployment-models','/deployment'],
to: '/deploy'
},
{
from: ['/private-cloud/private-cloud-deployments/private-cloud-addon-options','/private-saas-deployment/add-ons','/private-cloud/add-ons','/appliance/infrastructure/internet-restricted-deployment','/private-saas-deployment','/private-cloud/managed-private-cloud','/private-cloud','/appliance','/appliance/checksum','/appliance/proxy-updater','/appliance/update','/updating-appliance','/enterprise/private-cloud/overview','/appliance/dashboard/instrumentation','/appliance/instrumentation','/appliance/appliance-overview'],
to: '/deploy/private-cloud'
},
{
from: ['/services/private-cloud-configuration','/services/private-saas-configuration','/private-saas-deployment/onboarding','/private-saas-deployment/onboarding/private-cloud','/private-cloud/onboarding','/private-cloud/onboarding/private-cloud','/enterprise-support','/onboarding/appliance-outage','/onboarding/enterprise-support','/private-cloud/managed-private-cloud/zones','/private-cloud/managed-private-cloud/raci', '/private-cloud/private-cloud-onboarding'],
to: '/deploy/private-cloud/private-cloud-onboarding'
},
{
from: ['/private-cloud/private-cloud-onboarding/customer-hosted-managed-private-cloud-infrastructure-requirements'],
to: '/deploy/private-cloud/private-cloud-onboarding/customer-hosted-managed-private-cloud-infrastructure-requirements'
},
{
from: ['/private-cloud/private-cloud-onboarding/private-cloud-ip-domain-and-port-list','/private-saas-deployment/onboarding/managed-private-cloud/ip-domain-port-list','/private-cloud/onboarding/managed-private-cloud/ip-domain-port-list', '/appliance/infrastructure/ip-domain-port-list'],
to: '/deploy/private-cloud/private-cloud-onboarding/private-cloud-ip-domain-and-port-list'
},
{
from: ['/private-cloud/private-cloud-onboarding/private-cloud-remote-access-options','/private-cloud/onboarding/managed-private-cloud/remote-access-options','/private-cloud/private-cloud-onboarding/private-cloud-remote-access-options'],
to: '/deploy/private-cloud/private-cloud-onboarding/private-cloud-remote-access-options'
},
{
from: ['/private-cloud/private-cloud-onboarding/standard-private-cloud-infrastructure-requirements','/private-saas-deployment/private-cloud','/private-cloud/standard-private-cloud','/private-saas-deployment/onboarding/managed-private-cloud/infrastructure','/private-cloud/onboarding/managed-private-cloud/infrastructure','/private-saas-deployment/managed-private-cloud','/private-cloud/onboarding/managed-private-cloud','/private-saas-deployment/onboarding/managed-private-cloud','/private-cloud/onboarding/managed-private-cloud','/appliance/infrastructure','/appliance/infrastructure/security'],
to: '/deploy/private-cloud/private-cloud-onboarding/standard-private-cloud-infrastructure-requirements'
},
{
from: ['/private-cloud/private-cloud-operations','/services/private-saas-management','/services/private-cloud-management'],
to: '/deploy/private-cloud/private-cloud-operations'
},
{
from: ['/private-cloud/private-cloud-migrations'],
to: '/deploy/private-cloud/private-cloud-migrations'
},
{
from: ['/private-cloud/private-cloud-migrations/migrate-from-public-cloud-to-private-cloud'],
to: '/deploy/private-cloud/private-cloud-migrations/migrate-from-public-cloud-to-private-cloud'
},
{
from: ['/private-cloud/private-cloud-migrations/migrate-from-standard-private-cloud-to-managed-private-cloud'],
to: '/deploy/private-cloud/private-cloud-migrations/migrate-from-standard-private-cloud-to-managed-private-cloud'
},
{
from: ['/private-cloud/private-cloud-migrations/migrate-private-cloud-custom-domains','/appliance/custom-domains','/private-saas-deployment/custom-domain-migration','/private-cloud/custom-domain-migration','/private-cloud/migrate-private-cloud-custom-domains'],
to: '/deploy/private-cloud/private-cloud-migrations/migrate-private-cloud-custom-domains'
},
{
from: ['/pre-deployment'],
to: '/deploy/pre-deployment'
},
{
from: ['/pre-deployment/how-to-run-production-checks','/pre-deployment/how-to-run-test'],
to: '/deploy/pre-deployment/how-to-run-production-checks'
},
{
from: [
'/deploy/pre-deployment/how-to-run-production-checks/production-check-required-fixes',
'/pre-deployment/how-to-run-production-checks/production-check-required-fixes',
'/pre-deployment/tests/required'
],
to: '/deploy/pre-deployment/production-check-required-fixes'
},
{
from: [
'/pre-deployment/how-to-run-production-checks/production-check-recommended-fixes',
'/pre-deployment/tests/recommended',
'/deploy/pre-deployment/how-to-run-production-checks/production-check-recommended-fixes'
],
to: '/deploy/pre-deployment/production-check-recommended-fixes'
},
{
from: [
'/pre-deployment/how-to-run-production-checks/production-checks-best-practices',
'/pre-deployment/tests/best-practice',
'/deploy/pre-deployment/how-to-run-production-checks/production-checks-best-practices'
],
to: '/deploy/pre-deployment/production-checks-best-practices'
},
{
from: ['/support/predeployment-tests','/support/testing'],
to: '/deploy/pre-deployment/predeployment-tests'
},
{
from: ['/pre-deployment/pre-launch-tips','/pre-deployment/prelaunch-tips'],
to: '/deploy/pre-deployment/pre-launch-tips'
},
/* Extensions */
{
from: [
'/extensions/using-provided-extensions',
'/topics/extensibility',
'/extend-integrate',
'/extensions/visual-studio-team-services-deploy',
'/extensions/visual-studio-team-services-deployments'
],
to: '/extensions'
},
{
from: [
'/extensions/authorization-extension/v2',
'/extensions/authorization-extension/v1',
'/api/authorization-dashboard-extension',
'/extensions/authorization-dashboard-extension'
],
to: '/extensions/authorization-extension'
},
{
from: ['/extensions/authorization-extension/v2/implementation/configuration'],
to: '/extensions/authorization-extension/configure-authorization-extension'
},
{
from: ['/extensions/authorization-extension/v2/implementation/installation'],
to: '/extensions/authorization-extension/install-authorization-extension'
},
{
from: ['/extensions/authorization-extension/v2/implementation/setup'],
to: '/extensions/authorization-extension/set-up-authorization-extension-users'
},
{
from: ['/extensions/authorization-extension/v2/api-access'],
to: '/extensions/authorization-extension/enable-api-access-to-authorization-extension'
},
{
from: ['/extensions/authorization-extension/v2/import-export-data'],
to: '/extensions/authorization-extension/import-and-export-authorization-extension-data'
},
{
from: ['/extensions/authorization-extension/v2/migration'],
to: '/extensions/authorization-extension/migrate-to-authorization-extension-v2'
},
{
from: ['/extensions/authorization-extension/v2/rules'],
to: '/extensions/authorization-extension/use-rules-with-the-authorization-extension'
},
{
from: ['/extensions/delegated-admin/v3','/extensions/delegated-admin/v2','/extensions/delegated-admin'],
to: '/extensions/delegated-administration-extension'
},
{
from: [
'/extensions/delegated-admin/v3/hooks',
'/extensions/delegated-admin/v2/hooks',
'/extensions/delegated-admin/hooks'
],
to: '/extensions/delegated-administration-extension/delegated-administration-hooks'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/access',
'/extensions/delegated-admin/v2/hooks/access',
'/extensions/delegated-admin/hooks/access',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-access-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-access-hook'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/filter',
'/extensions/delegated-admin/v2/hooks/filter',
'/extensions/delegated-admin/hooks/filter',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-filter-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-filter-hook'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/membership',
'/extensions/delegated-admin/v2/hooks/membership',
'/extensions/delegated-admin/hooks/membership',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-memberships-query-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-memberships-query-hook'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/settings',
'/extensions/delegated-admin/v2/hooks/settings',
'/extensions/delegated-admin/hooks/settings',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-settings-query-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-settings-query-hook'
},
{
from: [
'/extensions/delegated-admin/v3/hooks/write',
'/extensions/delegated-admin/v2/hooks/write',
'/extensions/delegated-admin/hooks/write',
'/extensions/delegated-administration-extension/delegated-administration-hooks/delegated-administration-write-hook'
],
to: '/extensions/delegated-administration-extension/delegated-administration-write-hook'
},
{
from: ['/extensions/delegated-admin/v3/manage-users','/extensions/delegated-admin/v2/manage-users','/extensions/delegated-admin/manage-users'],
to: '/extensions/delegated-administration-extension/delegated-administration-manage-users'
},
{
from: ['/extensions/sso-dashboard'],
to: '/extensions/single-sign-on-dashboard-extension'
},
{
from: [
'/get-started/dashboard/create-sso-dashboard-application',
'/dashboard/guides/extensions/sso-dashboard-create-app'
],
to: '/extensions/single-sign-on-dashboard-extensions/create-sso-dashboard-application'
},
{
from: ['/dashboard/guides/extensions/sso-dashboard-install-extension'],
to: '/extensions/single-sign-on-dashboard-extension/install-sso-dashboard-extension'
},
{
from: ['/dashboard/guides/extensions/sso-dashboard-add-apps'],
to: '/extensions/single-sign-on-dashboard-extension/add-applications-to-the-sso-dashboard'
},
{
from: ['/dashboard/guides/extensions/sso-dashboard-update-apps'],
to: '/extensions/single-sign-on-dashboard-extension/update-applications-on-the-sso-dashboard'
},
/* LDAP Connector */
{
from: ['/connector','/connector/overview','/connector/considerations-non-ad','/ad-ldap-connector'],
to: '/extensions/ad-ldap-connector'
},
{
from: ['/connector/prerequisites','/ad-ldap-connector/ad-ldap-connector-requirements'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-requirements'
},
{
from: ['/adldap-x','/connector/install-other-platforms','/connector/install','/adldap-auth'],
to: '/extensions/ad-ldap-connector/install-configure-ad-ldap-connector'
},
{
from: ['/connector/client-certificates','/ad-ldap-connector/configure-ad-ldap-connector-authentication-with-client-certificates'],
to: '/extensions/ad-ldap-connector/configure-ad-ldap-connector-client-certificates'
},
{
from: ['/connector/kerberos','/ad-ldap-connector/configure-ad-ldap-connector-authentication-with-kerberos'],
to: '/extensions/ad-ldap-connector/configure-ad-ldap-connector-with-kerberos'
},
{
from: ['/connector/high-availability','/ad-ldap-connector/ad-ldap-high-availability'],
to: '/extensions/ad-ldap-connector/ad-ldap-high-availability'
},
{
from: ['/extensions/adldap-connector','/extensions/ad-ldap-connector-health-monitor'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-health-monitor'
},
{
from: ['/dashboard/guides/connections/disable-cache-ad-ldap'],
to: '/extensions/ad-ldap-connector/disable-credential-caching'
},
{
from: ['/connector/scom-monitoring','/ad-ldap-connector/ad-ldap-connector-scorm'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-scom'
},
{
from: ['/connector/modify','/ad-ldap-connector/ad-ldap-connectors-to-auth0'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-to-auth0'
},
{
from: ['/connector/test-dc','/ad-ldap-connector/ad-ldap-connector-test-environment'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-test-environment'
},
{
from: ['/connector/update','/ad-ldap-connector/update-ad-ldap-connectors'],
to: '/extensions/ad-ldap-connector/update-ad-ldap-connectors'
},
{
from: ['/extensions/account-link'],
to: '/extensions/account-link-extension'
},
{
from: ['/logs/export-log-events-with-extensions', '/logs/log-export-extensions'],
to: '/extensions/log-export-extensions'
},
{
from: ['/extensions/export-logs-to-application-insights','/extensions/application-insight'],
to: '/extensions/log-export-extensions/export-logs-to-application-insights'
},
{
from: ['/extensions/export-logs-to-cloudwatch','/extensions/cloudwatch'],
to: '/extensions/log-export-extensions/export-logs-to-cloudwatch'
},
{
from: ['/extensions/export-logs-to-azure-blob-storage','/extensions/azure-blob-storage'],
to: '/extensions/log-export-extensions/export-logs-to-azure-blob-storage'
},
{
from: ['/extensions/export-logs-to-logentries','/extensions/logentries'],
to: '/extensions/log-export-extensions/export-logs-to-logentries'
},
{
from: ['/extensions/export-logs-to-loggly','/extensions/loggly'],
to: '/extensions/log-export-extensions/export-logs-to-loggly'
},
{
from: ['/extensions/export-logs-to-logstash','/extensions/logstash'],
to: '/extensions/log-export-extensions/export-logs-to-logstash'
},
{
from: ['/extensions/export-logs-to-mixpanel','/extensions/mixpanel'],
to: '/extensions/log-export-extensions/export-logs-to-mixpanel'
},
{
from: ['/extensions/export-logs-to-papertrail','/extensions/papertrail'],
to: '/extensions/log-export-extensions/export-logs-to-papertrail'
},
{
from: ['/extensions/export-logs-to-segment','/extensions/segment'],
to: '/extensions/log-export-extensions/export-logs-to-segment'
},
{
from: ['/extensions/export-logs-to-splunk','/extensions/splunk'],
to: '/extensions/log-export-extensions/export-logs-to-splunk'
},
{
from: ['/extensions/auth0-logs-to-sumo-logic','/extensions/sumologic'],
to: '/extensions/log-export-extensions/auth0-logs-to-sumo-logic'
},
{
from: ['/extensions/authentication-api-debugger'],
to: '/extensions/authentication-api-debugger-extension'
},
{
from: ['/extensions/authentication-api-webhooks'],
to: '/extensions/auth0-authentication-api-webhooks'
},
{
from: ['/extensions/user-import-export'],
to: '/extensions/user-import-export-extension'
},
{
from: [
'/extensions/bitbucket-deploy',
'/extensions/bitbucket-deployments'
],
to: 'https://marketplace.auth0.com/integrations/bitbucket-pipeline'
},
{
from: ['/extensions/custom-social-connections','/extensions/custom-social-extensions'],
to: '/connections/social/oauth2'
},
{
from: [
'/extensions/github-deploy',
'/extensions/github-deployments'
],
to: 'https://marketplace.auth0.com/integrations/github-actions'
},
{
from: [
'/extensions/gitlab-deploy',
'/extensions/gitlab-deployments'
],
to: 'https://marketplace.auth0.com/integrations/gitlab-pipeline'
},
{
from: ['/extensions/management-api-webhooks'],
to: '/extensions/auth0-management-api-webhooks'
},
{
from: ['/extensions/realtime-webtask-logs'],
to: '/extensions/real-time-webtask-logs'
},
{
from: ['/dashboard/guides/extensions/delegated-admin-create-app'],
to: '/extensions/delegated-administration-extension/create-delegated-admin-applications'
},
{
from: ['/dashboard/guides/extensions/delegated-admin-install-extension','/dashboard/guides/extensions/delegated-admin-use-extension'],
to: '/extensions/delegated-administration-extension/install-delegated-admin-extension'
},
/* Deploy CLI Tool */
{
from: ['/extensions/deploy-cli-tool','/extensions/deploy-cli'],
to: '/deploy/deploy-cli-tool'
},
{
from: [
'/extensions/deploy-cli-tool/call-deploy-cli-tool-programmatically',
'/extensions/deploy-cli/guides/call-deploy-cli-programmatically'
],
to: '/deploy/deploy-cli-tool/call-deploy-cli-tool-programmatically'
},
{
from: [
'/extensions/deploy-cli/guides/create-deploy-cli-application-manually',
'/extensions/deploy-cli-tool/create-and-configure-the-deploy-cli-application-manually',
'/extensions/deploy-cli-tool/create-and-configure-the-deploy-cli-application'
],
to: '/deploy/deploy-cli-tool/create-and-configure-the-deploy-cli-application'
},
{
from: [
'/extensions/deploy-cli/guides/import-export-directory-structure',
'/extensions/deploy-cli-tool/import-export-tenant-configuration-to-directory-structure'
],
to: '/deploy/deploy-cli-tool/import-export-tenant-configuration-to-directory-structure'
},
{
from: [
'/extensions/deploy-cli/guides/import-export-yaml-file',
'/extensions/deploy-cli-tool/import-export-tenant-configuration-to-yaml-file'
],
to: '/deploy/deploy-cli-tool/import-export-tenant-configuration-to-yaml-file'
},
{
from: [
'/extensions/deploy-cli/guides/incorporate-deploy-cli-into-build-environment',
'/extensions/deploy-cli-tool/incorporate-deploy-cli-into-build-environment'
],
to: '/deploy/deploy-cli-tool/incorporate-deploy-cli-into-build-environment'
},
{
from: [
'/extensions/deploy-cli/guides/install-deploy-cli',
'/extensions/deploy-cli-tool/install-and-configure-the-deploy-cli-tool'
],
to: '/deploy/deploy-cli-tool/install-and-configure-the-deploy-cli-tool'
},
{
from: [
'/extensions/deploy-cli/references/deploy-cli-options',
'/extensions/deploy-cli-tool/deploy-cli-tool-options'
],
to: '/deploy/deploy-cli-tool/deploy-cli-tool-options'
},
{
from: [
'/extensions/deploy-cli/references/environment-variables-keyword-mappings',
'/extensions/deploy-cli-tool/environment-variables-and-keyword-mappings'
],
to: '/deploy/deploy-cli-tool/environment-variables-and-keyword-mappings'
},
{
from: [
'/extensions/deploy-cli/references/whats-new',
'/extensions/deploy-cli/references/whats-new-v2',
'/extensions/deploy-cli-tool/whats-new-in-deploy-cli-tool'
],
to: '/deploy/deploy-cli-tool/whats-new-in-deploy-cli-tool'
},
/* Get Started */
{
from: ['/getting-started'],
to: '/get-started'
},
{
from: ['/overview','/get-started/overview','/getting-started/overview'],
to: '/get-started/auth0-overview'
},
{
from: ['/getting-started/set-up-app', '/applications/set-up-an-application'],
to: '/get-started/create-apps'
},
{
from: [
'/dashboard/guides/applications/register-app-m2m',
'/applications/application-settings/non-interactive',
'/applications/application-settings/machine-to-machine',
'/applications/machine-to-machine',
'/applications/set-up-an-application/register-machine-to-machine-applications'
],
to: '/get-started/create-apps/machine-to-machine-apps'
},
{
from: [
'/dashboard/guides/applications/register-app-native',
'/applications/application-settings/native',
'/applications/native',
'/applications/set-up-an-application/register-native-applications'
],
to: '/get-started/create-apps/native-apps'
},
{
from: [
'/dashboard/guides/applications/register-app-regular-web',
'/applications/application-settings/regular-web-app',
'/applications/webapps',
'/applications/register-regular-web-applications',
'/applications/set-up-an-application/register-regular-web-applications'
],
to: '/get-started/create-apps/regular-web-apps'
},
{
from: [
'/dashboard/guides/applications/register-app-spa',
'/applications/spa',
'/applications/application-settings/single-page-app',
'/applications/register-single-page-app',
'/applications/set-up-an-application/register-single-page-app'
],
to: '/get-started/create-apps/single-page-web-apps'
},
{
from: ['/getting-started/set-up-api','/dashboard/reference/views-api'],
to: '/get-started/set-up-apis'
},
{
from: ['/dashboard','/getting-started/dashboard-overview'],
to: '/get-started/dashboard'
},
{
from: ['/get-started/learn-the-basics','/getting-started/the-basics','/getting-started/create-tenant'],
to: '/get-started/create-tenants'
},
{
from: ['/dev-lifecycle/child-tenants'],
to: '/get-started/create-tenants/child-tenants'
},
{
from: ['/dev-lifecycle/set-up-multiple-environments','/dev-lifecycle/setting-up-env'],
to: '/get-started/create-tenants/set-up-multiple-environments'
},
{
from: ['/get-started/dashboard/create-multiple-tenants','/dashboard/guides/tenants/create-multiple-tenants'],
to: '/get-started/create-tenants/create-multiple-tenants'
},
{
from: ['/dashboard/guides/tenants/enable-sso-tenant'],
to: '/get-started/dashboard/enable-sso-for-legacy-tenants'
},
{
from: [
'/dashboard/guides/connections/set-up-connections-social',
'/get-started/dashboard/set-up-social-connections'
],
to: 'https://marketplace.auth0.com/features/social-connections'
},
{
from: ['/dashboard/guides/connections/test-connections-database'],
to: '/get-started/dashboard/test-database-connections'
},
{
from: ['/dashboard/guides/connections/test-connections-enterprise'],
to: '/get-started/dashboard/test-enterprise-connections'
},
{
from: ['/dashboard/guides/connections/test-connections-social'],
to: '/get-started/dashboard/test-social-connections'
},
{
from: ['/dashboard/guides/connections/view-connections'],
to: '/get-started/dashboard/view-connections'
},
{
from: ['/dashboard/guides/connections/enable-connections-enterprise'],
to: '/get-started/dashboard/enable-enterprise-connections'
},
{
from: ['/api/management/guides/connections/promote-connection-domain-level'],
to: '/get-started/dashboard/promote-connections-to-domain-level'
},
{
from: ['/api/management/guides/connections/retrieve-connection-options','/api/management/guides/retrieve-connection-options'],
to: '/get-started/dashboard/retrieve-connection-options'
},
{
from: ['/dashboard-access/dashboard-roles','/dashboard-access/manage-dashboard-users','/dashboard/manage-dashboard-admins','/tutorials/manage-dashboard-admins','/get-started/dashboard/manage-dashboard-users'],
to: '/dashboard-access'
},
{
from: ['/dashboard-access/dashboard-roles/feature-access-by-role'],
to: '/dashboard-access/feature-access-by-role'
},
{
from: ['/product-lifecycle/deprecations-and-migrations/migrate-to-manage-dashboard-new-roles'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-tenant-member-roles'
},
/* Hooks */
{
from: ['/hooks/cli','/auth0-hooks/cli','/hooks/dashboard','/hooks/overview','/auth0-hooks','/auth0-hooks/dashboard'],
to: '/hooks'
},
{
from: ['/hooks/concepts/extensibility-points','/hooks/concepts/overview-extensibility-points'],
to: '/hooks/extensibility-points'
},
{
from: ['/hooks/concepts/credentials-exchange-extensibility-point','/hooks/guides/use-the-credentials-exchange-extensibility-point','/hooks/client-credentials-exchange','/hooks/extensibility-points/credentials-exchange'],
to: '/hooks/extensibility-points/client-credentials-exchange'
},
{
from: ['/hooks/create','/hooks/dashboard/create-delete','/hooks/cli/create-delete','/hooks/guides/create-hooks-using-cli','/hooks/guides/create-hooks-using-dashboard','/auth0-hooks/cli/create-delete'],
to: '/hooks/create-hooks'
},
{
from: ['/hooks/delete','/hooks/guides/delete-hooks-using-cli','/hooks/guides/delete-hooks-using-dashboard'],
to: '/hooks/delete-hooks'
},
{
from: ['/hooks/enable-disable','/hooks/cli/enable-disable','/hooks/dashboard/enable-disable','/hooks/guides/enable-disable-hooks-using-cli','/hooks/guides/enable-disable-hooks-using-dashboard','/auth0-hooks/cli/enable-disable'],
to: '/hooks/enable-disable-hooks'
},
{
from: ['/hooks/guides/post-change-password','/hooks/post-change-password'],
to: '/hooks/extensibility-points/post-change-password'
},
{
from: ['/hooks/concepts/post-user-registration-extensibility-point','/hooks/guides/use-the-post-user-registration-extensibility-point','/hooks/post-user-registration'],
to: '/hooks/extensibility-points/post-user-registration'
},
{
from: ['/hooks/concepts/pre-user-registration-extensibility-point','/hooks/guides/use-the-pre-user-registration-extensibility-point','/auth0-hooks/extensibility-points/pre-user-registration','/hooks/pre-user-registration'],
to: '/hooks/extensibility-points/pre-user-registration'
},
{
from: ['/hooks/secrets/create'],
to: '/hooks/hook-secrets/create-hook-secrets'
},
{
from: ['/hooks/secrets/delete'],
to: '/hooks/hook-secrets/delete-hook-secrets'
},
{
from: ['/hooks/secrets'],
to: '/hooks/hook-secrets'
},
{
from: ['/hooks/secrets/update'],
to: '/hooks/hook-secrets/update-hook-secrets'
},
{
from: ['/hooks/secrets/view'],
to: '/hooks/hook-secrets/view-hook-secrets'
},
{
from: ['/hooks/update','/hooks/cli/edit','/hooks/dashboard/edit','/hooks/guides/edit-hooks-using-cli','/hooks/guides/edit-hooks-using-dashboard'],
to: '/hooks/update-hooks'
},
{
from: ['/hooks/view-logs','/hooks/cli/logs','/hooks/logs','/hooks/guides/logging-hooks-using-cli','/auth0-hooks/cli/logs'],
to: '/hooks/view-logs-for-hooks'
},
{
from: ['/hooks/view'],
to: '/hooks/view-hooks'
},
/* Identity Labs */
{
from: ['/labs'],
to: '/identity-labs'
},
{
from: ['/identity-labs/01-web-sign-in'],
to: '/identity-labs/lab-1-web-sign-in'
},
{
from: ['/identity-labs/01-web-sign-in/exercise-01'],
to: '/identity-labs/lab-1-web-sign-in/identity-lab-1-exercise-1'
},
{
from: ['/identity-labs/01-web-sign-in/exercise-02'],
to: '/identity-labs/lab-1-web-sign-in/identity-lab-1-exercise-2'
},
{
from: ['/identity-labs/02-calling-an-api'],
to: '/identity-labs/identity-lab-2-calling-api'
},
{
from: ['/identity-labs/02-calling-an-api/exercise-01'],
to: '/identity-labs/identity-lab-2-calling-api/identity-lab-2-exercise-1'
},
{
from: ['/identity-labs/02-calling-an-api/exercise-02'],
to: '/identity-labs/identity-lab-2-calling-api/identity-lab-2-exercise-2'
},
{
from: ['/identity-labs/02-calling-an-api/exercise-03'],
to: '/identity-labs/identity-lab-2-calling-api/identity-lab-2-exercise-3'
},
{
from: ['/identity-labs/03-mobile-native-app'],
to: '/identity-labs/lab-3-mobile-native-app'
},
{
from: ['/identity-labs/03-mobile-native-app/exercise-01'],
to: '/identity-labs/lab-3-mobile-native-app/identity-lab-3-exercise-1'
},
{
from: ['/identity-labs/03-mobile-native-app/exercise-02'],
to: '/identity-labs/lab-3-mobile-native-app/identity-lab-3-exercise-2'
},
{
from: ['/identity-labs/03-mobile-native-app/exercise-03'],
to: '/identity-labs/lab-3-mobile-native-app/identity-lab-3-exercise-3'
},
{
from: ['/identity-labs/04-single-page-app'],
to: '/identity-labs/lab-4-single-page-app'
},
{
from: ['/identity-labs/04-single-page-app/exercise-01'],
to: '/identity-labs/lab-4-single-page-app/identity-lab-4-exercise-1'
},
{
from: ['/identity-labs/04-single-page-app/exercise-02'],
to: '/identity-labs/lab-4-single-page-app/identity-lab-4-exercise-2'
},
/* Integrations */
{
from: ['/integration'],
to: '/integrations'
},
{
from: ['/aws-api-setup'],
to: '/integrations/how-to-set-up-aws-for-delegated-authentication'
},
{
from: ['/integrations/aws/sso','/configure-amazon-web-services-for-sso'],
to: '/integrations/aws/configure-amazon-web-services-for-sso'
},
{
from: ['/integrations/aws/tokens','/integrations/call-aws-apis-and-resources-with-tokens'],
to: '/integrations/aws-api-gateway-delegation'
},
{
from: ['/scenarios/amazon-cognito', '/tutorials/integrating-auth0-amazon-cognito-mobile-apps', '/integrations/integrating-auth0-amazon-cognito-mobile-apps', '/integrations/integrate-with-amazon-cognito'],
to: '/integrations/amazon-cognito'
},
{
from: ['/scenarios-mqtt','/tutorials/authenticating-devices-using-mqtt','/integrations/authenticating-devices-using-mqtt'],
to: '/integrations/authenticate-devices-using-mqtt'
},
{
from: ['/scenarios-tessel', '/tutorials/authenticating-a-tessel-device', '/integrations/authenticating-a-tessel-device'],
to: '/integrations/authenticating-and-authorizing-a-tessel-device-with-auth0'
},
{
from: ['/aws', '/awsapi-tutorial'],
to: '/integrations/aws'
},
{
from: ['/integrations/aws-api-gateway/delegation','/integrations/aws-api-gateway'],
to: '/integrations/aws-api-gateway-delegation'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-1','/integrations/aws-api-gateway/part-1','/integrations/aws-api-gateway/aws-api-gateway-step-1'],
to: '/integrations/aws-api-gateway-delegation-1'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-2','/integrations/aws-api-gateway/part-2','/integrations/aws-api-gateway/aws-api-gateway-step-2'],
to: '/integrations/aws-api-gateway-delegation-2'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-3','/integrations/aws-api-gateway/part-3','/integrations/aws-api-gateway/aws-api-gateway-step-3'],
to: '/integrations/aws-api-gateway-delegation-3'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-4','/integrations/aws-api-gateway/part-4','/integrations/aws-api-gateway/aws-api-gateway-step-4'],
to: '/integrations/aws-api-gateway-delegation-4'
},
{
from: ['/integrations/aws-api-gateway/delegation/part-5','/integrations/aws-api-gateway/part-5','/integrations/aws-api-gateway/aws-api-gateway-step-5'],
to: '/integrations/aws-api-gateway-delegation-5'
},
{
from: ['/integrations/aws-api-gateway/delegation/secure-api-with-cognito','/integrations/aws-api-gateway/secure-api-with-cognito'],
to: '/integrations/aws-api-gateway-cognito'
},
{
from: ['/integrations/aws-api-gateway/custom-authorizers', '/integrations/aws-api-gateway/custom-authorizers/part-1', '/integrations/aws-api-gateway/custom-authorizers/part-2', '/integrations/aws-api-gateway/custom-authorizers/part-3', '/integrations/aws-api-gateway/custom-authorizers/part-4'],
to: '/integrations/aws-api-gateway-custom-authorizers'
},
{
from: ['/sharepoint-apps', '/integrations/sharepoint-apps'],
to: '/integrations/connecting-provider-hosted-apps-to-sharepoint-online'
},
{
from: ['/integrations/google-cloud-platform', '/tutorials/google-cloud-platform'],
to: '/integrations/google-cloud-endpoints'
},
{
from: ['/integrations/marketing/salesforce'],
to: '/integrations/marketing/export-user-data-salesforce'
},
{
from: ['/tutorials/office365-connection-deprecation-guide', '/integrations/office365-connection-deprecation-guide','/office365-deprecated'],
to: '/integrations/migrate-office365-connections-to-windows-azure-ad'
},
{
from: ['/tutorials/using-auth0-to-secure-a-cli', '/integrations/using-auth0-to-secure-a-cli','/tutorials/using-auth0-to-secure-an-api','/cli'],
to: '/integrations/secure-a-cli-with-auth0'
},
{
from: ['/integrations/sharepoint'],
to: '/integrations/sharepoint-2010-2013'
},
{
from: [
'/integrations/sso-integrations',
'/sso/current/integrations'
],
to: '/integrations/sso'
},
{
from: [
'/integrations/sso-integrations/ad-rms',
'/integrations/sso-integrations/ad-rms-sso-integration',
'/sso/current/integrations/ad-rms',
'/integrations/sso/ad-rms'
],
to: 'https://marketplace.auth0.com/integrations/ad-rms-sso'
},
{
from: [
'/integrations/sso-integrations/box',
'/sso/current/integrations/box',
'/integrations/sso/box'
],
to: 'https://marketplace.auth0.com/integrations/box-sso'
},
{
from: [
'/integrations/sso-integrations/cloudbees',
'/sso/current/integrations/cloudbees',
'/integrations/sso/cloudbees'
],
to: 'https://marketplace.auth0.com/integrations/cloudbees-sso'
},
{
from: [
'/integrations/sso-integrations/concur',
'/sso/current/integrations/concur',
'/integrations/sso/concur'
],
to: 'https://marketplace.auth0.com/integrations/concur-sso'
},
{
from: [
'/integrations/sso-integrations/disqus',
'/sso/current/integrations/disqus',
'/integrations/disqus',
'/integrations/sso/disqus'
],
to: 'https://marketplace.auth0.com/features/sso-integrations'
},
{
from: [
'/integrations/sso-integrations/dropbox',
'/sso/current/integrations/dropbox',
'/integrations/dropbox',
'/integrations/sso/dropbox'
],
to: 'https://marketplace.auth0.com/integrations/dropbox-sso'
},
{
from: [
'/integrations/sso-integrations/dynamics-crm',
'/sso/current/integrations/dynamics-crm',
'/integrations/dynamics-crm',
'/integrations/sso/dynamics-crm'
],
to: 'https://marketplace.auth0.com/integrations/dynamics-crm-sso'
},
{
from: [
'/integrations/sso-integrations/adobe-sign',
'/integrations/sso-integrations/echosign',
'/sso/current/integrations/echosign',
'/integrations/echosign',
'/integrations/sso/adobe-sign'
],
to: 'https://marketplace.auth0.com/integrations/adobe-sign-sso'
},
{
from: [
'/integrations/sso-integrations/egnyte',
'/sso/current/integrations/egnyte',
'/integrations/egnyte',
'/integrations/sso/egnyte'
],
to: 'https://marketplace.auth0.com/integrations/egnyte-sso'
},
{
from: [
'/integrations/sso-integrations/new-relic',
'/sso/current/integrations/new-relic',
'/integrations/new-relic',
'/integrations/sso/new-relic'
],
to: 'https://marketplace.auth0.com/integrations/new-relic-sso'
},
{
from: [
'/integrations/sso-integrations/office-365',
'/sso/current/integrations/office-365',
'/integrations/office-365',
'/integrations/sso/office-365'
],
to: 'https://marketplace.auth0.com/integrations/office-365-sso'
},
{
from: [
'/integrations/sso-integrations/salesforce',
'/sso/current/integrations/salesforce',
'/integrations/salesforce',
'/integrations/sso/salesforce'
],
to: 'https://marketplace.auth0.com/integrations/salesforce-sso'
},
{
from: [
'/integrations/sso-integrations/slack',
'/sso/current/integrations/slack',
'/integrations/integrating-with-slack',
'/tutorials/integrating-with-slack',
'/scenarios/slack',
'/integrations/slack',
'/integrations/sso/slack'
],
to: 'https://marketplace.auth0.com/integrations/slack-sso'
},
{
from: [
'/integrations/sso-integrations/sentry',
'/sso/current/integrations/sentry',
'/integrations/sentry',
'/integrations/sso/sentry'
],
to: 'https://marketplace.auth0.com/integrations/sentry-sso'
},
{
from: [
'/integrations/sso-integrations/sharepoint',
'/sso/current/integrations/sharepoint',
'/integrations/sso/sharepoint'
],
to: 'https://marketplace.auth0.com/integrations/sharepoint-sso'
},
{
from: [
'/integrations/sso-integrations/springcm',
'/sso/current/integrations/springcm',
'/integrations/springcm',
'/integrations/sso/springcm'
],
to: 'https://marketplace.auth0.com/integrations/springcm-sso'
},
{
from: [
'/integrations/sso-integrations/zendesk',
'/sso/current/integrations/zendesk',
'/integrations/zendesk',
'/integrations/sso/zendesk'
],
to: 'https://marketplace.auth0.com/integrations/zendesk-sso'
},
{
from: [
'/integrations/sso-integrations/zoom',
'/sso/current/integrations/zoom',
'/integrations/zoom',
'/integrations/sso/zoom'
],
to: 'https://marketplace.auth0.com/integrations/zoom-sso'
},
{
from: [
'/integrations/sso-integrations/cisco-webex',
'/integrations/sso/cisco-webex'
],
to: 'https://marketplace.auth0.com/integrations/cisco-webex-sso'
},
{
from: [
'/integrations/sso-integrations/datadog',
'/integrations/sso/datadog'
],
to: 'https://marketplace.auth0.com/integrations/datadog-sso'
},
{
from: [
'/integrations/sso-integrations/egencia',
'/integrations/sso/egencia'
],
to: 'https://marketplace.auth0.com/integrations/egencia-sso'
},
{
from: [
'/integrations/sso-integrations/eloqua',
'/integrations/sso/eloqua'
],
to: 'https://marketplace.auth0.com/integrations/eloqua-sso'
},
{
from: [
'/integrations/sso-integrations/freshdesk',
'/integrations/sso/freshdesk'
],
to: 'https://marketplace.auth0.com/integrations/freshdesk-sso'
},
{
from: [
'/integrations/sso-integrations/g-suite',
'/integrations/sso/g-suite'
],
to: 'https://marketplace.auth0.com/integrations/g-suite-sso'
},
{
from: [
'/integrations/sso-integrations/github-enterprise-cloud',
'/integrations/sso/github-enterprise-cloud'
],
to: 'https://marketplace.auth0.com/integrations/github-enterprise-cloud-sso'
},
{
from: [
'/integrations/sso-integrations/github-enterprise-server',
'/integrations/sso/github-enterprise-server'
],
to: 'https://marketplace.auth0.com/integrations/github-enterprise-server-sso'
},
{
from: [
'/integrations/sso-integrations/heroku',
'/integrations/sso/heroku'
],
to: 'https://marketplace.auth0.com/integrations/heroku-sso'
},
{
from: [
'/integrations/sso-integrations/hosted-graphite',
'/integrations/sso/hosted-graphite'
],
to: 'https://marketplace.auth0.com/integrations/hosted-graphite-sso'
},
{
from: [
'/integrations/sso-integrations/litmos',
'/integrations/sso/litmos'
],
to: 'https://marketplace.auth0.com/integrations/litmos-sso'
},
{
from: [
'/integrations/sso-integrations/pluralsight',
'/integrations/sso/pluralsight'
],
to: 'https://marketplace.auth0.com/integrations/pluralsight-sso'
},
{
from: [
'/integrations/sso-integrations/sprout-video',
'/integrations/sso/sprout-video'
],
to: 'https://marketplace.auth0.com/integrations/sprout-video-sso'
},
{
from: [
'/integrations/sso-integrations/tableau-online',
'/integrations/sso/tableau-online'
],
to: 'https://marketplace.auth0.com/integrations/tableau-online-sso'
},
{
from: [
'/integrations/sso-integrations/tableau-server',
'/integrations/sso/tableau-server'
],
to: 'https://marketplace.auth0.com/integrations/tableau-server-sso'
},
{
from: [
'/integrations/sso-integrations/workday',
'/integrations/sso/workday'
],
to: 'https://marketplace.auth0.com/integrations/workday-sso'
},
{
from: [
'/integrations/sso-integrations/workpath',
'/integrations/sso/workpath'
],
to: 'https://marketplace.auth0.com/integrations/workpath-sso'
},
{
from: ['/integrations/azure-tutorial','/azure-tutorial','/tutorials/azure-tutorial','/integrations/azure-api-management/configure-auth0','/integrations/azure-api-management/configure-azure'],
to: '/integrations/azure-api-management'
},
/* LDAP Connector */
{
from: ['/connector','/connector/overview','/connector/considerations-non-ad','/ad-ldap-connector'],
to: '/extensions/ad-ldap-connector'
},
{
from: [,'/extensions/adldap-connector','/extensions/ad-ldap-connector-health-monitor'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-health-monitor'
},
{
from: ['/connector/prerequisites','/ad-ldap-connector/ad-ldap-connector-requirements'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-requirements'
},
{
from: ['/connector/client-certificates','/ad-ldap-connector/configure-ad-ldap-connector-authentication-with-client-certificates'],
to: '/extensions/ad-ldap-connector/configure-ad-ldap-connector-client-certificates'
},
{
from: ['/connector/kerberos','/ad-ldap-connector/configure-ad-ldap-connector-authentication-with-kerberos'],
to: '/extensions/ad-ldap-connector/configure-ad-ldap-connector-with-kerberos'
},
{
from: ['/connector/high-availability','/ad-ldap-connector/ad-ldap-high-availability'],
to: '/extensions/ad-ldap-connector/ad-ldap-high-availability'
},
{
from: ['/dashboard/guides/connections/disable-cache-ad-ldap'],
to: '/extensions/ad-ldap-connector/disable-credential-caching'
},
{
from: ['/adldap-x','/connector/install-other-platforms','/connector/install','/adldap-auth'],
to: '/extensions/ad-ldap-connector/install-configure-ad-ldap-connector'
},
{
from: ['/connector/scom-monitoring','/ad-ldap-connector/ad-ldap-connector-scorm'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-scom'
},
{
from: ['/connector/modify','/ad-ldap-connector/ad-ldap-connectors-to-auth0'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-to-auth0'
},
{
from: ['/connector/test-dc','/ad-ldap-connector/ad-ldap-connector-test-environment'],
to: '/extensions/ad-ldap-connector/ad-ldap-connector-test-environment'
},
{
from: ['/connector/troubleshooting','/ad-ldap-connector/troubleshoot-ad-ldap-connector'],
to: '/extensions/ad-ldap-connector/troubleshoot-ad-ldap-connector'
},
{
from: ['/connector/update','/ad-ldap-connector/update-ad-ldap-connectors'],
to: '/extensions/ad-ldap-connector/update-ad-ldap-connectors'
},
/* Libraries */
{
from: '/sdks',
to: '/libraries'
},
{
from: ['/custom-signup', '/libraries/lock/v10/custom-signup', '/libraries/lock/v11/custom-signup'],
to: '/libraries/custom-signup'
},
{
from: ['/libraries/error-messages','/libraries/lock-android/error-messages','/errors/libraries/auth0-js/invalid-token'],
to: '/libraries/common-auth0-library-authentication-errors'
},
{
from: [
'/widget',
'/login-widget2',
'/lock',
'/migrations/guides/legacy-lock-api-deprecation',
'/libraries/lock/v9',
'/libraries/lock/v9/display-modes',
'/libraries/lock/v9/types-of-applications',
'/libraries/lock/v10',
'/libraries/lock/v10/installation',
'/libraries/lock/v11',
'/libraries/lock/using-refresh-tokens',
'/libraries/lock/using-a-refresh-token'
],
to: '/libraries/lock'
},
{
from: ['/libraries/lock/display-modes','/libraries/lock/customization','/libraries/lock/v9/customization','/libraries/lock/v10/customization','/libraries/lock/v11/customization','/libraries/lock/v9/configuration','/libraries/lock/v10/configuration','/libraries/lock/v11/configuration'],
to: '/libraries/lock/lock-configuration'
},
{
from: ['/libraries/lock/v10/popup-mode','/libraries/lock/v10/authentication-modes','/libraries/lock/v11/popup-mode','/libraries/lock/v11/authentication-modes','/libraries/lock/authentication-modes'],
to: '/libraries/lock/lock-authentication-modes'
},
{
from: ['/hrd','/libraries/lock/v11/selecting-the-connection-for-multiple-logins','/protocols/saml/saml-configuration/selecting-between-multiple-idp','/libraries/lock/v10/selecting-the-connection-for-multiple-logins'],
to: '/libraries/lock/selecting-from-multiple-connection-options'
},
{
from: ['/libraries/lock/v11/api'],
to: '/libraries/lock/lock-api-reference'
},
{
from: ['/libraries/lock/v11/sending-authentication-parameters','/libraries/lock/sending-authentication-parameters'],
to: '/libraries/lock/lock-authentication-parameters'
},
{
from: ['/libraries/lock/v11/ui-customization','/libraries/lock/v9/ui-customization'],
to: '/libraries/lock/lock-ui-customization'
},
{
from: ['/libraries/lock-ios/v2','/libraries/lock-ios/delegation-api','/libraries/lock-ios/v1/delegation-api','/libraries/lock-ios','/libraries/lock-ios/v1','/libraries/lock-ios/lock-ios-api','/libraries/lock-ios/v1/lock-ios-api','/libraries/lock-ios/native-social-authentication','/libraries/lock-ios/v1/native-social-authentication','/libraries/lock-ios/password-reset-ios','/libraries/lock-ios/v1/password-reset-ios','/libraries/lock-ios/save-and-refresh-jwt-tokens','/libraries/lock-ios/v1/save-and-refresh-jwt-tokens','/libraries/lock-ios/sending-authentication-parameters','/libraries/lock-ios/v1/sending-authentication-parameters','/libraries/lock-ios/swift','/libraries/lock-ios/v1/swift'],
to: '/libraries/lock-swift'
},
{
from: ['/libraries/lock-ios/logging','/libraries/lock-ios/v2/logging','/libraries/lock-ios/v1/logging'],
to: '/libraries/lock-swift/lock-swift-logging'
},
{
from: ['/libraries/lock-ios/v2/passwordless','/libraries/lock-ios/sms-lock-ios','/libraries/lock-ios/v1/sms-lock-ios','/libraries/lock-ios/touchid-authentication','/libraries/lock-ios/v1/touchid-authentication','/libraries/lock-ios/passwordless','/libraries/lock-ios/v1/passwordless'],
to: '/libraries/lock-swift/lock-swift-passwordless'
},
{
from: ['/libraries/lock-ios/v2/customization','/libraries/lock-ios/use-your-own-ui','/libraries/lock-ios/v1/use-your-own-uis','/libraries/lock-ios/v1/use-your-own-ui','/libraries/lock-ios/v1/customization'],
to: '/libraries/lock-swift/lock-swift-customization'
},
{
from: ['/libraries/lock-ios/v2/custom-fields'],
to: '/libraries/lock-swift/lock-swift-custom-fields-at-signup'
},
{
from: ['/libraries/lock-ios/v2/configuration'],
to: '/libraries/lock-swift/lock-swift-configuration-options'
},
{
from: ['/auth0js','/libraries/auth0js/v7','/libraries/auth0js/v8','/libraries/auth0js/v9','/libraries/lock/v10/auth0js','/libraries/lock/v11/auth0js','/libraries/auth0js-v9-reference'],
to: '/libraries/auth0js'
},
{
from: ['/libraries/auth0-android/configuration'],
to: '/libraries/auth0-android/auth0-android-configuration'
},
{
from: ['/libraries/lock-android/v2','/libraries/lock-android/v1','/libraries/lock-android/v1/sending-authentication-parameters','/libraries/lock-android/v1/use-your-own-ui'],
to: '/libraries/lock-android'
},
{
from: ['/libraries/lock-android/v2/custom-authentication-providers','/libraries/lock-android/v2/custom-oauth-connections'],
to: '/libraries/lock-android/lock-android-custom-authentication-providers'
},
{
from: ['/tutorials/local-testing-and-development','/local-testing-and-development'],
to: '/libraries/secure-local-development'
},
{
from: ['/libraries/lock-android/v2/refresh-jwt-tokens','/libraries/lock-android/v1/refresh-jwt-tokens','/libraries/lock-android/refresh-jwt-tokens','/libraries/auth0-android/save-and-refresh-tokens'],
to: '/libraries/lock-android/lock-android-refresh-jwt'
},
{
from: ['/libraries/lock-android/lock-android-delegation'],
to: '/libraries/lock-android/v2/refresh-jwt-tokens'
},
{
from: ['/libraries/lock-android/custom-fields','/libraries/lock-android/v2/custom-fields'],
to: '/libraries/lock-android/lock-android-custom-fields-at-signup'
},
{
from: ['/libraries/auth0-android/passwordless','/libraries/lock-android/passwordless','/connections/passwordless/android-email','/libraries/lock-android/v2/passwordless','/libraries/lock-android/v1/passwordless'],
to: '/libraries/lock-android/lock-android-passwordless'
},
{
from: ['/libraries/lock-android/v2/configuration','/libraries/lock-android/v1/configuration'],
to: '/libraries/lock-android/lock-android-configuration'
},
{
from: ['/libraries/lock-android/v2/delegation-api','/libraries/lock-android/v1/delegation-api'],
to: '/libraries/lock-android/lock-android-delegation'
},
{
from: ['/libraries/lock-android/v2/custom-theming'],
to: '/libraries/lock-android/lock-android-custom-theming'
},
{
from: ['/libraries/lock-android/v2/native-social-authentication','/libraries/lock-android/v1/native-social-authentication'],
to: '/libraries/lock-android/lock-android-native-social-authentication'
},
{
from: ['/libraries/lock-android/v2/passwordless-magic-link','/libraries/lock-android/v1/passwordless-magic-link'],
to: '/libraries/lock-android/lock-android-passwordless-with-magic-link'
},
{
from: ['/libraries/lock-android/v2/keystore','/libraries/lock-android/keystore','/libraries/lock-android/android-development-keystores-hashes'],
to: '/libraries/auth0-android/android-development-keystores-hashes'
},
{
from: ['/libraries/auth0-android/user-management'],
to: '/libraries/auth0-android/auth0-android-user-management'
},
{
from: ['/libraries/auth0-spa-js'],
to: '/libraries/auth0-single-page-app-sdk'
},
{
from: ['/libraries/auth0-android/database-authentication'],
to: '/libraries/auth0-android/auth0-android-database-authentication'
},
{
from: ['/libraries/auth0-spa-js/migrate-from-auth0js'],
to: '/libraries/auth0-single-page-app-sdk/migrate-from-auth0-js-to-the-auth0-single-page-app-sdk'
},
{
from: ['/libraries/auth0-swift/database-authentication'],
to: '/libraries/auth0-swift/auth0-swift-database-connections'
},
{
from: ['/libraries/auth0-swift/passwordless'],
to: '/libraries/auth0-swift/auth0-swift-passwordless'
},
{
from: ['/libraries/auth0-swift/save-and-refresh-jwt-tokens'],
to: '/libraries/auth0-swift/auth0-swift-save-and-renew-tokens'
},
{
from: ['/libraries/auth0-swift/touchid-authentication'],
to: '/libraries/auth0-swift/auth0-swift-touchid-faceid'
},
{
from: ['/libraries/auth0-swift/user-management'],
to: '/libraries/auth0-swift/auth0-swift-user-management'
},
{
from: ['/libraries/auth0-php/authentication-api'],
to: '/libraries/auth0-php/using-the-authentication-api-with-auth0-php'
},
{
from: ['/libraries/auth0-php/basic-use'],
to: '/libraries/auth0-php/auth0-php-basic-use'
},
{
from: ['/libraries/auth0-php/jwt-validation'],
to: '/libraries/auth0-php/validating-jwts-with-auth0-php'
},
{
from: ['/libraries/auth0-php/management-api'],
to: '/libraries/auth0-php/using-the-management-api-with-auth0-php'
},
{
from: ['/libraries/auth0-php/troubleshooting'],
to: '/libraries/auth0-php/troubleshoot-auth0-php-library'
},
/* Login */
{
from: ['/flows/login'],
to: '/login'
},
{
from: ['/login/embedded', '/flows/login/embedded', '/flows/login/embedded-login'],
to: '/login/embedded-login'
},
{
from: ['/cross-origin-authentication', '/flows/login/embedded-login/cross-origin-authentication'],
to: '/login/embedded-login/cross-origin-authentication'
},
{
from: ['/authorization/configure-silent-authentication','/api-auth/tutorials/silent-authentication'],
to: '/login/configure-silent-authentication'
},
{
from: '/flows',
to: '/login/flows'
},
{
from: [
'/flows/guides/auth-code/add-login-auth-code',
'/flows/guides/auth-code/includes/authorize-user-add-login',
'/flows/guides/auth-code/includes/sample-use-cases-add-login',
'/flows/guides/auth-code/includes/refresh-tokens',
'/flows/guides/auth-code/includes/request-tokens',
'/flows/guides/regular-web-app-login-flow/add-login-using-regular-web-app-login-flow',
'/oauth-web-protocol',
'/protocols/oauth-web-protocol',
'/protocols/oauth2/oauth-web-protocol',
'/application-auth/current/server-side-web',
'/client-auth/server-side-web',
'/application-auth/legacy/server-side-web',
'/flows/add-login-auth-code-flow'
],
to: '/login/flows/add-login-auth-code-flow'
},
{
from: [
'/authorization/flows/call-your-api-using-the-authorization-code-flow',
'/flows/guides/auth-code/call-api-auth-code',
'/flows/guides/auth-code/includes/authorize-user-call-api',
'/flows/guides/auth-code/includes/sample-use-cases-call-api',
'/flows/guides/auth-code/includes/call-api',
'/flows/guides/regular-web-app-login-flow/call-api-using-regular-web-app-login-flow',
'/api-auth/tutorials/authorization-code-grant',
'/flows/call-your-api-using-the-authorization-code-flow'
],
to: '/login/flows/call-your-api-using-the-authorization-code-flow'
},
{
from: [
'/flows/guides/auth-code-pkce/add-login-auth-code-pkce',
'/flows/guides/auth-code-pkce/includes/sample-use-cases-add-login',
'/flows/guides/auth-code-pkce/includes/request-tokens',
'/flows/guides/auth-code-pkce/includes/refresh-tokens',
'/flows/guides/auth-code-pkce/includes/create-code-verifier',
'/flows/guides/auth-code-pkce/includes/create-code-challenge',
'/flows/guides/auth-code-pkce/includes/authorize-user-add-login',
'/application-auth/current/mobile-desktop',
'/application-auth/legacy/mobile-desktop',
'/application-auth/legacy/mobile-desktop',
'/flows/guides/mobile-login-flow/add-login-using-mobile-login-flow',
'/flows/add-login-using-the-authorization-code-flow-with-pkce'
],
to: '/login/flows/add-login-using-the-authorization-code-flow-with-pkce'
},
{
from: [
'/flows/guides/auth-code-pkce/call-api-auth-code-pkce',
'/flows/guides/auth-code-pkce/includes/sample-use-cases-call-api',
'/flows/guides/auth-code-pkce/includes/call-api',
'/flows/guides/auth-code-pkce/includes/authorize-user-call-api',
'/flows/guides/mobile-login-flow/call-api-using-mobile-login-flow',
'/api-auth/tutorials/authorization-code-grant-pkce',
'/flows/call-your-api-using-the-authorization-code-flow-with-pkce'
],
to: '/login/flows/call-your-api-using-the-authorization-code-flow-with-pkce'
},
{
from: [
'/flows/guides/implicit/add-login-implicit',
'/flows/guides/implicit/includes/sample-use-cases-add-login',
'/flows/guides/implicit/includes/refresh-tokens',
'/flows/guides/implicit/includes/request-tokens',
'/flows/guides/implicit/includes/authorize-user-add-login',
'/application-auth/current/client-side-web',
'/flows/guides/single-page-login-flow/add-login-using-single-page-login-flow',
'/client-auth/client-side-web','/application-auth/legacy/client-side-web',
'/flows/add-login-using-the-implicit-flow-with-form-post'
],
to: '/login/flows/add-login-using-the-implicit-flow-with-form-post'
},
{
from: ['/api-auth/tutorials/hybrid-flow','/flows/call-api-hybrid-flow'],
to: '/login/flows/call-api-hybrid-flow'
},
{
from: [
'/flows/guides/client-credentials/call-api-client-credentials',
'/flows/guides/client-credentials/includes/sample-use-cases',
'/flows/guides/client-credentials/includes/call-api',
'/flows/guides/client-credentials/includes/request-token',
'/flows/guides/m2m-flow/call-api-using-m2m-flow',
'/api-auth/tutorials/client-credentials',
'/api-auth/config/asking-for-access-tokens',
'/flows/call-your-api-using-the-client-credentials-flow'
],
to: '/login/flows/call-your-api-using-the-client-credentials-flow'
},
{
from: ['/flows/guides/device-auth/call-api-device-auth'],
to: '/login/flows/call-your-api-using-the-device-authorization-flow'
},
{
from: ['/flows/call-your-api-using-resource-owner-password-flow','/api-auth/tutorials/password-grant'],
to: '/login/flows/call-your-api-using-resource-owner-password-flow'
},
/* Logout */
{
from: ['/logout/log-users-out-of-applications','/logout/guides/logout-applications'],
to: '/login/logout/log-users-out-of-applications'
},
{
from: ['/logout/log-users-out-of-auth0','/logout/guides/logout-auth0'],
to: '/login/logout/log-users-out-of-auth0'
},
{
from: ['/logout/log-users-out-of-idps','/logout/guides/logout-idps'],
to: '/login/logout/log-users-out-of-idps'
},
{
from: ['/logout/log-users-out-of-saml-idps','/protocols/saml/saml-configuration/logout','/logout/guides/logout-saml-idps'],
to: '/login/logout/log-users-out-of-saml-idps'
},
{
from: ['/logout/redirect-users-after-logout','/logout/guides/redirect-users-after-logout'],
to: '/login/logout/redirect-users-after-logout'
},
/* Monitor - Logs */
{
from: ['/logs','/logs/concepts/logs-admins-devs'],
to: '/monitor-auth0/logs'
},
{
from: ['/logs/pii-in-logs','/logs/personally-identifiable-information-pii-in-auth0-logs'],
to: '/monitor-auth0/logs/pii-in-logs'
},
{
from: ['/logs/log-data-retention','/logs/references/log-data-retention'],
to: '/monitor-auth0/logs/log-data-retention'
},
{
from: ['/logs/view-log-events','/logs/guides/view-log-data-dashboard','/logs/view-log-events-in-the-dashboard'],
to: '/monitor-auth0/logs/view-log-events'
},
{
from: ['/logs/log-event-filters','/logs/references/log-event-filters'],
to: '/monitor-auth0/logs/log-event-filters'
},
{
from: ['/logs/retrieve-log-events-using-mgmt-api','/logs/guides/retrieve-logs-mgmt-api'],
to: '/monitor-auth0/logs/retrieve-log-events-using-mgmt-api'
},
{
from: ['/logs/log-event-type-codes','/logs/references/log-event-data','/logs/references/log-events-data','/logs/references/log-event-type-codes'],
to: '/monitor-auth0/logs/log-event-type-codes'
},
{
from: ['/logs/log-search-query-syntax','/logs/references/query-syntax','/logs/query-syntax'],
to: '/monitor-auth0/logs/log-search-query-syntax'
},
{
from: [
'/monitoring/guides/send-events-to-splunk',
'/monitoring/guides/send-events-to-keenio',
'/monitoring/guides/send-events-to-segmentio',
'/logs/export-log-events-with-rules'
],
to: '/monitor-auth0/logs/export-log-events-with-rules'
},
{
from: ['/logs/export-log-events-with-log-streaming','/logs/streams'],
to: '/monitor-auth0/streams'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-http-event-logs',
'/logs/streams/http-event',
'/logs/streams/stream-http-event-logs'
],
to: '/monitor-auth0/streams/custom-log-streams'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-log-events-to-slack',
'/logs/streams/http-event-to-slack'
],
to: '/monitor-auth0/streams/stream-log-events-to-slack'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-logs-to-splunk',
'/logs/streams/splunk',
'/logs/streams/stream-logs-to-splunk',
'/monitor-auth0/streams/stream-logs-to-splunk'
],
to: 'https://marketplace.auth0.com/integrations/splunk-log-streaming'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-logs-to-amazon-eventbridge',
'/logs/streams/aws-eventbridge',
'/integrations/aws-eventbridge',
'/logs/streams/amazon-eventbridge',
'/logs/streams/stream-logs-to-amazon-eventbridge',
'/monitor-auth0/streams/stream-logs-to-amazon-eventbridge'
],
to: 'https://marketplace.auth0.com/integrations/amazon-log-streaming'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-logs-to-azure-event-grid',
'/logs/streams/azure-event-grid',
'/logs/streams/stream-logs-to-azure-event-grid',
'/monitor-auth0/streams/stream-logs-to-azure-event-grid'
],
to: 'https://marketplace.auth0.com/integrations/azure-log-streaming'
},
{
from: [
'/logs/export-log-events-with-log-streaming/stream-logs-to-datadog',
'/logs/streams/datadog',
'/logs/streams/stream-logs-to-datadog',
'/monitor-auth0/streams/stream-logs-to-datadog'
],
to: 'https://marketplace.auth0.com/integrations/datadog-log-streaming'
},
{
from: [
'/logs/export-log-events-with-log-streaming/datadog-dashboard-templates',
'/logs/streams/datadog-dashboard-templates'
],
to: '/monitor-auth0/streams/datadog-dashboard-templates'
},
{
from: ['/logs/streams/event-filters'],
to: '/monitor-auth0/streams/event-filters'
},
{
from: [
'/logs/export-log-events-with-log-streaming/splunk-dashboard',
'/logs/streams/splunk-dashboard'
],
to: '/monitor-auth0/streams/splunk-dashboard'
},
{
from: ['/logs/streams/stream-logs-to-sumo-logic'],
to: '/monitor-auth0/streams/stream-logs-to-sumo-logic'
},
{
from: ['/logs/streams/sumo-logic-dashboard'],
to: '/monitor-auth0/streams/sumo-logic-dashboard'
},
/* MFA */
{
from: ['/multi-factor-authentication','/multi-factor-authentication2','/multifactor-authentication/custom-provider','/multifactor-authentication','/mfa-in-auth0','/multifactor-authentication/yubikey','/multifactor-authentication/guardian','/multifactor-authentication/guardian/user-guide','/multi-factor-authentication/yubikey'],
to: '/mfa'
},
{
from: ['/mfa/configure-webauthn-with-security-keys-for-mfa'],
to: '/mfa/configure-webauthn-security-keys-for-mfa'
},
{
from: ['/multifactor-authentication/api', '/multifactor-authentication/api/faq','/mfa/concepts/mfa-api'],
to: '/mfa/mfa-api'
},
{
from: ['/api-auth/tutorials/multifactor-resource-owner-password','/mfa/guides/mfa-api/authenticate','/mfa/guides/mfa-api/multifactor-resource-owner-password'],
to: '/mfa/authenticate-with-ropg-and-mfa'
},
{
from: ['/mfa/guides/mfa-api/manage','/multifactor-authentication/api/manage'],
to: '/mfa/authenticate-with-ropg-and-mfa/manage-authenticator-factors-mfa-api'
},
{
from: ['/mfa/guides/mfa-api/phone','/multifactor-authentication/api/oob','/mfa/guides/mfa-api/oob'],
to: '/mfa/authenticate-with-ropg-and-mfa/enroll-challenge-sms-voice-authenticators'
},
{
from: ['/mfa/guides/mfa-api/push'],
to: '/mfa/authenticate-with-ropg-and-mfa/enroll-and-challenge-push-authenticators'
},
{
from: ['/multifactor-authentication/api/otp','/mfa/guides/mfa-api/otp','/multifactor-authentication/google-authenticator'],
to: '/mfa/authenticate-with-ropg-and-mfa/enroll-and-challenge-otp-authenticators'
},
{
from: ['/multifactor-authentication/api/email','/mfa/guides/mfa-api/email','/multifactor-authentication/administrator/guardian-enrollment-email'],
to: '/mfa/authenticate-with-ropg-and-mfa/enroll-and-challenge-email-authenticators'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-amazon-sns','/mfa/send-phone-message-hook-amazon-sns'],
to: '/mfa/configure-amazon-sns-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-esendex','/mfa/send-phone-message-hook-esendex'],
to: '/mfa/configure-esendex-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-infobip','/mfa/send-phone-message-hook-infobip'],
to: '/mfa/configure-infobip-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-mitto','/mfa/send-phone-message-hook-mitto'],
to: '/mfa/configure-mitto-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-telesign','/mfa/send-phone-message-hook-telesign'],
to: '/mfa/configure-telesign-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-twilio','/mfa/send-phone-message-hook-twilio'],
to: '/mfa/configure-twilio-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/send-phone-message-hook-vonage','/mfa/send-phone-message-hook-vonage'],
to: '/mfa/configure-vonage-as-mfa-sms-provider'
},
{
from: ['/multifactor-authentication/factors','/mfa/concepts/mfa-factors'],
to: '/mfa/mfa-factors'
},
{
from: ['/multifactor-authentication/factors/duo','/multifactor-authentication/duo','/multifactor-authentication/duo/admin-guide','/mfa/guides/configure-cisco-duo','/multifactor-authentication/duo/dev-guide','/multifactor-authentication/duo/user-guide'],
to: '/mfa/configure-cisco-duo-for-mfa'
},
{
from: ['/multifactor-authentication/factors/otp','/mfa/guides/configure-otp'],
to: '/mfa/configure-otp-notifications-for-mfa'
},
{
from: ['/mfa/guides/configure-email-universal-login','/multifactor-authentication/factors/email','/mfa/guides/configure-email'],
to: '/mfa/configure-email-notifications-for-mfa'
},
{
from: ['/multifactor-authentication/developer/sns-configuration','/multifactor-authentication/factors/push','/mfa/guides/configure-push','/multifactor-authentication/administrator/push-notifications'],
to: '/mfa/configure-push-notifications-for-mfa'
},
{
from: ['/multifactor-authentication/administrator/twilio-configuration','/multifactor-authentication/administrator/sms-notifications','/multifactor-authentication/twilio-configuration','/multifactor-authentication/factors/sms','/mfa/guides/configure-sms','/mfa/guides/configure-phone'],
to: '/mfa/configure-sms-voice-notifications-mfa'
},
{
from: ['/multifactor-authentication/google-auth/admin-guide','/multifactor-authentication/google-auth/user-guide','/multifactor-authentication/troubleshooting','/mfa/references/troubleshoot-mfa','/mfa/references/troubleshooting'],
to: '/mfa/troubleshoot-mfa-issues'
},
{
from: ['/multifactor-authentication/developer/step-up-authentication','/step-up-authentication','/tutorials/step-up-authentication','/tutorials/setup-up-authentication','/multifactor-authentication/step-up-authentication','/mfa/concepts/step-up-authentication','/multifactor-authentication/developer/step-up-with-acr'],
to: '/mfa/step-up-authentication'
},
{
from: ['/multifactor-authentication/api/challenges','/multifactor-authentication/developer/step-up-authentication/step-up-for-apis','/multifactor-authentication/step-up-authentication/step-up-for-apis','/mfa/guides/configure-step-up-apis'],
to: '/mfa/step-up-authentication/configure-step-up-authentication-for-apis'
},
{
from: ['/multifactor-authentication/developer/step-up-authentication/step-up-for-web-apps','/multifactor-authentication/step-up-authentication/step-up-for-web-apps','/mfa/guides/configure-step-up-web-apps'],
to: '/mfa/step-up-authentication/configure-step-up-authentication-for-web-apps'
},
{
from: ['/multifactor-authentication/reset-user','/multifactor-authentication/administrator/reset-user','/mfa/guides/reset-user-mfa','/multifactor-authentication/administrator/disabling-mfa'],
to: '/mfa/reset-user-mfa'
},
{
from: ['/mfa/concepts/guardian','/multifactor-authentication/guardian/dev-guide','/multifactor-authentication/guardian/admin-guide'],
to: '/mfa/auth0-guardian'
},
{
from: ['/multifactor-authentication/developer/custom-enrollment-ticket','/mfa/guides/guardian/create-enrollment-ticket'],
to: '/mfa/auth0-guardian/create-custom-enrollment-tickets'
},
{
from: ['/multifactor-authentication/developer/libraries/ios','/mfa/guides/guardian/guardian-ios-sdk','/mfa/guides/guardian/configure-guardian-ios'],
to: '/mfa/auth0-guardian/guardian-for-ios-sdk'
},
{
from: ['/multifactor-authentication/developer/libraries/android','/mfa/guides/guardian/guardian-android-sdk'],
to: '/mfa/auth0-guardian/guardian-for-android-sdk'
},
{
from: ['/mfa/guides/guardian/install-guardian-sdk'],
to: '/mfa/auth0-guardian/install-guardian-sdk'
},
{
from: ['/mfa/references/guardian-error-code-reference'],
to: '/mfa/auth0-guardian/guardian-error-code-reference'
},
{
from: ['/mfa/guides/import-user-mfa'],
to: '/mfa/import-user-mfa-authenticator-enrollments'
},
{
from: ['/mfa/concepts/mfa-developer-resources','/multifactor-authentication/developer','/mfa/concepts/developer-resources'],
to: '/mfa/mfa-developer-resources'
},
{
from: ['/mfa/guides/enable-mfa'],
to: '/mfa/enable-mfa'
},
{
from: ['/multifactor-authentication/custom','/mfa/guides/customize-mfa-universal-login','/multifactor-authentication/google-auth/dev-guide'],
to: '/mfa/customize-mfa-user-pages'
},
{
from: ['/mfa/guides/mfa-api/recovery-code'],
to: '/mfa/authenticate-with-ropg-and-mfa/manage-authenticator-factors-mfa-api/challenge-with-recovery-codes'
},
{
from: ['/mfa/references/language-dictionary'],
to: '/mfa/customize-mfa-user-pages/mfa-theme-language-dictionary'
},
{
from: ['/mfa/references/mfa-widget-reference'],
to: '/mfa/customize-mfa-user-pages/mfa-widget-theme-options'
},
/* Monitoring */
{
from: ['/monitoring','/tutorials/how-to-monitor-auth0','/monitoring/how-to-monitor-auth0'],
to: '/monitor-auth0'
},
{
from: ['/monitoring/guides/check-external-services'],
to: '/monitor-auth0/check-external-services-status'
},
{
from: ['/monitoring/guides/check-status'],
to: '/monitor-auth0/check-auth0-status'
},
{
from: ['/monitoring/guides/monitor-applications'],
to: '/monitor-auth0/monitor-applications'
},
{
from: ['/monitoring/guides/monitor-using-SCOM'],
to: '/monitor-auth0/monitor-using-scom'
},
/* Policies */
{
from: ['/policies/billing'],
to: '/policies/billing-policy'
},
{
from: ['/policies/endpoints','/security/public-cloud-service-endpoints'],
to: '/policies/public-cloud-service-endpoints'
},
{
from: ['/policies/dashboard-authentication','/policies/restore-deleted-tenant','/policies/unsupported-requests'],
to: '/policies'
},
{
from: ['/policies/data-export','/policies/data-transfer'],
to: '/policies/data-export-and-transfer-policy'
},
{
from: ['/policies/entity-limits','/policies/global-limit'],
to: '/policies/entity-limit-policy'
},
{
from: ['/policies/load-testing'],
to: '/policies/load-testing-policy'
},
{
from: [
'/rate-limits',
'/policies/rate-limit',
'/policies/rate-limits',
'/policies/legacy-rate-limits'
],
to: '/policies/rate-limit-policy'
},
{
from: [
'/policies/rate-limit-policy/authentication-api-endpoint-rate-limits',
'/policies/rate-limits-auth-api',
'/policies/rate-limits-api'
],
to: '/policies/authentication-api-endpoint-rate-limits'
},
{
from: [
'/policies/rate-limit-policy/mgmt-api-endpoint-rate-limits-before-19-may-2020',
'/policies/rate-limit-policy/management-api-endpoint-rate-limits',
'/policies/rate-limits-mgmt-api'
],
to: '/policies/management-api-endpoint-rate-limits'
},
{
from: ['/policies/penetration-testing'],
to: '/policies/penetration-testing-policy'
},
{
from: ['/policies/rate-limit-policy/database-connections-rate-limits','/connections/database/rate-limits'],
to: '/policies/database-connections-rate-limits'
},
/* Product-Lifecycle */
{
from: '/lifecycle',
to: '/product-lifecycle'
},
{
from: ['/product-lifecycle/deprecation-eol'],
to: '/product-lifecycle/migration-process'
},
{
from: ['/product-lifecycle/migrations','/migrations'],
to: '/product-lifecycle/deprecations-and-migrations'
},
{
from: ['/migrations/guides/account-linking','/users/guides/link-user-accounts-auth-api'],
to: '/product-lifecycle/deprecations-and-migrations/link-user-accounts-with-access-tokens-migration'
},
{
from: ['/migrations/guides/calling-api-with-idtokens'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-calling-api-with-access-tokens'
},
{
from: ['/guides/login/migration-embedded-universal','/guides/login/migration-embedded-centralized','/guides/login/migrating-lock-v10-webapp','/guides/login/migrating-lock-v9-spa','/guides/login/migrating-lock-v9-spa-popup','/guides/login/migrating-lock-v9-webapp','/guides/login/migrating-lock-v10-spa','/guides/login/migrating-lock-v8','/guides/login/migration-sso'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-from-embedded-login-to-universal-login'
},
{
from: ['/guides/migration-legacy-flows'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-from-legacy-auth-flows'
},
{
from: ['/migrations/guides/clickjacking-protection'],
to: '/product-lifecycle/deprecations-and-migrations/clickjacking-protection-for-universal-login'
},
{
from: ['/migrations/guides/extensibility-node12'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-nodejs-12'
},
{
from: ['/migrations/guides/facebook-graph-api-deprecation'],
to: '/product-lifecycle/deprecations-and-migrations/facebook-graph-api-changes'
},
{
from: ['/migrations/guides/facebook-social-context'],
to: '/product-lifecycle/deprecations-and-migrations/facebook-social-context-field-deprecation'
},
{
from: ['/migrations/guides/google_cloud_messaging'],
to: '/product-lifecycle/deprecations-and-migrations/google-firebase-migration'
},
{
from: ['/migrations/guides/instagram-deprecation'],
to: '/product-lifecycle/deprecations-and-migrations/instagram-connection-deprecation'
},
{
from: [
'/product-lifecycle/deprecations-and-migrations/migrate-to-management-api-v2',
'/api/management-api-v1-deprecated',
'/api/management-api-changes-v1-to-v2',
'/migrations/guides/management-api-v1-v2',
'/api/management/v1/use-cases',
'/api/v1'
],
to: '/product-lifecycle/deprecations-and-migrations/past-migrations'
},
{
from: ['/migrations/guides/migration-oauthro-oauthtoken'],
to: '/product-lifecycle/deprecations-and-migrations/migration-oauthro-oauthtoken'
},
{
from: ['/migrations/guides/migration-oauthro-oauthtoken-pwdless'],
to: '/product-lifecycle/deprecations-and-migrations/resource-owner-passwordless-credentials-exchange'
},
{
from: ['/migrations/guides/passwordless-start'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-passwordless'
},
{
from: ['/migrations/guides/unpaginated-requests'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-paginated-queries'
},
{
from: ['/migrations/guides/yahoo-userinfo-updates'],
to: '/product-lifecycle/deprecations-and-migrations/yahoo-api-changes'
},
{
from: ['/migrations/past-migrations'],
to: '/product-lifecycle/deprecations-and-migrations/past-migrations'
},
{
from: ['/logs/guides/migrate-logs-v2-v3'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-to-tenant-log-search-v3'
},
{
from: ['/deprecations-and-migrations/migrate-tenant-member-roles'],
to: '/product-lifecycle/deprecations-and-migrations/migrate-tenant-member-roles'
},
/* Professional Services */
{
from: ['/services','/auth0-professional-services','/services/auth0-advanced','/services/auth0-introduction','/services/discover-and-design','/services/maintain-and-improve'],
to: '/professional-services'
},
{
from: ['/services/architectural-design','/professional-services/architectural-design-services','/professional-services/solution-design-services','/services/solution-design'],
to: '/professional-services/discover-design'
},
{
from: ['/professional-services/custom-implementation-services','/services/custom-implementation','/services/implement'],
to: '/professional-services/implement'
},
{
from: ['/services/performance-scalability','/professional-services/performance-and-scalability-services','/professional-services/advisory-sessions','/services/scenario-guidance','/services/code-review','/services/pair-programming'],
to: '/professional-services/maintain-improve'
},
{
from: ['/services/packages'],
to: '/professional-services/packages'
},
/* Protocols */
{
from: ['/tutorials/openid-connect-discovery','/protocols/oidc/openid-connect-discovery','/oidc-rs256-owin'],
to: '/protocols/configure-applications-with-oidc-discovery'
},
{
from: ['/protocols/oidc/identity-providers/okta','/protocols/configure-okta-as-oidc-identity-provider'],
to: '/protocols/configure-okta-as-oauth2-identity-provider'
},
{
from: ['/integrations/configure-wsfed-application','/tutorials/configure-wsfed-application'],
to: '/protocols/configure-ws-fed-applications'
},
{
from: ['/protocols/oauth2/oauth-state','/protocols/oauth-state','/protocols/oauth2/mitigate-csrf-attacks'],
to: '/protocols/state-parameters'
},
{
from: ['/protocols/oauth2'],
to: '/protocols/protocol-oauth2'
},
{
from: ['/protocols/oidc','/api-auth/intro','/api-auth/tutorials/adoption'],
to: '/protocols/openid-connect-protocol'
},
{
from: ['/protocols/ws-fed','/tutorials/wsfed-web-app','/wsfedwebapp-tutorial'],
to: '/protocols/ws-fed-protocol'
},
{
from: ['/protocols/ldap'],
to: '/protocols/ldap-protocol'
},
/* Rules */
{
from: ['/rules/current', '/rules/current/csharp', '/rules/guides/csharp', '/rules/legacy', '/rules/references/legacy','/rules/references/modules','/rule'],
to: '/rules'
},
{
from: ['/rules/guides/automatically-generate-leads-in-shopify','/rules/guides/automatically-generate-leads-shopify'],
to: '/rules/automatically-generate-leads-in-shopify'
},
{
from: ['/rules/guides/cache-resources','/rules/cache-expensive-resources-in-rules'],
to: '/rules/cache-resources'
},
{
from: ['/rules/guides/configuration'],
to: '/rules/configuration'
},
{
from: ['/dashboard/guides/rules/configure-variables'],
to: '/rules/configure-global-variables-for-rules'
},
{
from: ['/rules/current/context', '/rules/context', '/rules/references/context-object','/rules/context-prop-authentication'],
to: '/rules/context-object'
},
{
from: ['/api/management/guides/rules/create-rules', '/dashboard/guides/rules/create-rules','/rules/guides/create'],
to: '/rules/create-rules'
},
{
from: ['/rules/guides/debug'],
to: '/rules/debug-rules'
},
{
from: ['/rules/references/samples'],
to: '/rules/examples'
},
{
from: [
'/rules/guides/integrate-user-id-verification',
'/rules/integrate-user-id-verification'
],
to: 'https://marketplace.auth0.com/integrations/onfido-identity-verification'
},
{
from: '/rules/guides/integrate-efm-solutions',
to: '/rules/integrate-efm-solutions'
},
{
from: '/rules/guides/integrate-erfm-solutions',
to: '/rules/integrate-erfm-solutions'
},
{
from: '/rules/guides/integrate-hubspot',
to: '/rules/integrate-hubspot'
},
{
from: '/rules/guides/integrate-maxmind',
to: '/rules/integrate-maxmind'
},
{
from: '/rules/guides/integrate-mixpanel',
to: '/rules/integrate-mixpanel'
},
{
from: '/rules/guides/integrate-salesforce',
to: '/rules/integrate-salesforce'
},
{
from: ['/rules/current/redirect', '/rules/redirect', '/rules/guides/redirect'],
to: '/rules/redirect-users'
},
{
from: ['/rules/references/use-cases'],
to: '/rules/use-cases'
},
{
from: ['/rules/current/management-api', '/rules/guides/management-api'],
to: '/rules/use-management-api'
},
{
from: ['/rules/references/user-object'],
to: '/rules/user-object-in-rules'
},
{
from: [
'/monitoring/guides/track-leads-salesforce',
'/tutorials/tracking-new-leads-in-salesforce-and-raplead',
'/scenarios-rapleaf-salesforce',
'/scenarios/rapleaf-salesforce',
'/monitor-auth0/track-new-leads-in-salesforce'
],
to: '/rules/use-cases/track-new-leads-in-salesforce'
},
{
from: [
'/monitoring/guides/track-signups-salesforce',
'/tutorials/track-signups-enrich-user-profile-generate-leads',
'/scenarios-mixpanel-fullcontact-salesforce',
'/scenarios/mixpanel-fullcontact-salesforce',
'/monitor-auth0/track-new-sign-ups-in-salesforce'
],
to: '/rules/use-cases/track-new-sign-ups-in-salesforce'
},
/* Scopes */
{
from: ['/scopes/current','/scopes/legacy','/scopes/preview'],
to: '/scopes'
},
{
from: ['/scopes/current/api-scopes'],
to: '/scopes/api-scopes'
},
{
from: ['/scopes/current/oidc-scopes','/api-auth/tutorials/adoption/scope-custom-claims','/scopes/oidc-scopes'],
to: '/scopes/openid-connect-scopes'
},
{
from: ['/scopes/current/sample-use-cases'],
to: '/scopes/sample-use-cases-scopes-and-claims'
},
/* Security */
{
from: ['/security/general-security-tips'],
to: '/security/tips'
},
{
from: [
'/security/blacklist-user-attributes',
'/security/blacklisting-attributes',
'/tutorials/blacklisting-attributes',
'/blacklist-attributes',
'/security/denylist-user-attributes'
],
to: '/security/data-security/denylist'
},
{
from: [
'/security/whitelist-ip-addresses',
'/guides/ip-whitelist',
'/security/allowlist-ip-addresses'
],
to: '/security/data-security/allowlist'
},
{
from: [
'/users/normalized/auth0/store-user-data',
'/users/store-user-data',
'/users/references/user-data-storage-scenario',
'/users/user-data-storage-scenario',
'/best-practices/user-data-storage-best-practices',
'/users/references/user-data-storage-best-practices',
'/users/user-data-storage',
'/user-profile/user-data-storage'
],
to: '/security/data-security/user-data-storage'
},
{
from: [
'/tokens/concepts/token-storage',
'/videos/session-and-cookies',
'/security/store-tokens',
'/tokens/guides/store-tokens',
'/tokens/token-storage'
],
to: '/security/data-security/token-storage'
},
{
from: ['/security/common-threats','/security/prevent-common-cybersecurity-threats'],
to: '/security/prevent-threats'
},
/* Security Bulletins */
{
from: ['/security/bulletins'],
to: '/security/security-bulletins'
},
{
from: ['/security/bulletins/cve-2020-15259','/security/cve-2020-15259'],
to: '/security/security-bulletins/cve-2020-15259'
},
{
from: ['/security/bulletin/cve-2020-15240', '/security/cve-2020-15240'],
to: '/security/security-bulletins/cve-2020-15240'
},
{
from: ['/security/bulletins/cve-2020-15125','/security/cve-2020-15125'],
to: '/security/security-bulletins/cve-2020-15125'
},
{
from: ['/security/bulletins/cve-2020-15084','/security/cve-2020-15084'],
to: '/security/security-bulletins/cve-2020-15084'
},
{
from: ['/security/bulletins/2020-03-31_wpauth0','/security/2020-03-31-wpauth0'],
to: '/security/security-bulletins/2020-03-31-wpauth0'
},
{
from: ['/security/bulletins/cve-2020-5263','/security/cve-2020-5263'],
to: '/security/security-bulletins/cve-2020-5263'
},
{
from: ['/security/bulletins/2019-01-10_rules','/security/2019-01-10-rules'],
to: '/security/security-bulletins/2019-01-10-rules'
},
{
from: ['/security/bulletins/2019-09-05_scopes','/security/2019-09-05-scopes'],
to: '/security/security-bulletins/2019-09-05-scopes'
},
{
from: ['/security/bulletins/cve-2019-20174','/security/cve-2019-20174'],
to: '/security/security-bulletins/cve-2019-20174'
},
{
from: ['/security/bulletins/cve-2019-20173','/security/cve-2019-20173'],
to: '/security/security-bulletins/cve-2019-20173'
},
{
from: ['/security/bulletins/cve-2019-16929','/security/cve-2019-16929'],
to: '/security/security-bulletins/cve-2019-16929'
},
{
from: ['/security/bulletins/cve-2019-13483','/security/cve-2019-13483'],
to: '/security/security-bulletins/cve-2019-13483'
},
{
from: ['/security/bulletins/cve-2019-7644','/security/cve-2019-7644'],
to: '/security/security-bulletins/cve-2019-7644'
},
{
from: ['/security/bulletins/cve-2018-15121','/security/cve-2018-15121'],
to: '/security/security-bulletins/cve-2018-15121'
},
{
from: ['/security/bulletins/cve-2018-11537','/security/cve-2018-11537'],
to: '/security/security-bulletins/cve-2018-11537'
},
{
from: ['/security/bulletins/cve-2018-7307','/security/cve-2018-7307'],
to: '/security/security-bulletins/cve-2018-7307'
},
{
from: ['/security/bulletins/cve-2018-6874','/security/cve-2018-6874'],
to: '/security/security-bulletins/cve-2018-6874'
},
{
from: ['/security/bulletins/cve-2018-6873','/security/cve-2018-6873'],
to: '/security/security-bulletins/cve-2018-6873'
},
{
from: ['/security/bulletins/cve-2017-16897','/security/cve-2017-16897'],
to: '/security/security-bulletins/cve-2017-16897'
},
{
from: ['/security/bulletins/cve-2017-17068','/security/cve-2017-17068'],
to: '/security/security-bulletins/cve-2017-17068'
},
/* Sessions */
{
from: ['/sessions-and-cookies', '/sessions/concepts/session', '/sessions/concepts/session-lifetime','/sessions/references/sample-use-cases-sessions', '/sessions-and-cookies/session-use-cases'],
to: '/sessions'
},
{
from: ['/sessions/concepts/session-layers'],
to: '/sessions/session-layers'
},
{
from: ['/get-started/dashboard/configure-session-lifetime-settings','/dashboard/guides/tenants/configure-session-lifetime-settings','/api/management/guides/tenants/configure-session-lifetime-settings','/sso/current/configure-session-lifetime-limits'],
to: '/sessions/configure-session-lifetime-settings'
},
{
from: ['/sessions/concepts/cookie-attributes', '/sessions-and-cookies/samesite-cookie-attribute-changes'],
to: '/sessions/cookies/samesite-cookie-attribute-changes'
},
{
from: ['/sessions/references/example-short-lived-session-mgmt', '/sessions-and-cookies/manage-multi-site-short-long-lived-sessions'],
to: '/sessions/manage-multi-site-sessions'
},
{
from: ['/sessions/concepts/cookies', '/sessions-and-cookies/cookies'],
to: '/sessions/cookies'
},
{
from: [
'/sessions/spa-authenticate-with-cookies',
'/login/spa/authenticate-with-cookies',
'/sessions-and-cookies/spa-authenticate-with-cookies'
],
to: '/sessions/cookies/spa-authenticate-with-cookies'
},
/* Support */
{
from: ['/policies/requests','/premium-support'],
to: '/support'
},
{
from: ['/sla', '/support/sla','/support/sld'],
to: '/support/services-level-descriptions'
},
{
from: ['/support/subscription'],
to: '/support/manage-subscriptions'
},
{
from: ['/tutorials/removing-auth0-exporting-data','/support/removing-auth0-exporting-data','/moving-out'],
to: '/support/export-data'
},
{
from: ['/support/cancel-paid-subscriptions','/tutorials/cancel-paid-subscriptions','/cancel-paid-subscriptions'],
to: '/support/downgrade-or-cancel-subscriptions'
},
{
from: ['/support/how-auth0-versions-software','/tutorials/how-auth0-versions-software','/versioning'],
to: '/support/versioning-strategy'
},
{
from: ['/support/matrix'],
to: '/support/product-support-matrix'
},
{
from: ['/support/reset-account-password','/tutorials/reset-account-password'],
to: '/support/reset-account-passwords'
},
{
from: ['/support/tickets'],
to: '/support/open-and-manage-support-tickets'
},
{
from: ['/support/delete-reset-tenant','/tutorials/delete-reset-tenant'],
to: '/support/delete-or-reset-tenant'
},
/* Tokens */
{
from: ['/security/token-exp','/token','/tokens/concepts','/tokens/guides'],
to: '/tokens'
},
{
from: ['/api-auth/tutorials/adoption/api-tokens','/tokens/concepts/access-tokens','/tokens/concepts/access-token','/tokens/overview-access-tokens','/tokens/access-token','/tokens/access_token','/api-auth/why-use-access-tokens-to-secure-apis','/api-auth/asking-for-access-tokens'],
to: '/tokens/access-tokens'
},
{
from: ['/tokens/guides/get-access-tokens','/tokens/get-access-tokens', '/tokens/guides/access-token/get-access-tokens'],
to: '/tokens/access-tokens/get-access-tokens'
},
{
from: ['/tokens/guides/use-access-tokens','/tokens/use-access-tokens', '/tokens/guides/access-token/use-access-tokens'],
to: '/tokens/access-tokens/use-access-tokens'
},
{
from: ['/tokens/guides/validate-access-tokens', '/api-auth/tutorials/verify-access-token', '/tokens/guides/access-token/validate-access-token'],
to: '/tokens/access-tokens/validate-access-tokens'
},
{
from: ['/tokens/guides/create-namespaced-custom-claims','/tokens/concepts/claims-namespacing'],
to: '/tokens/create-namespaced-custom-claims'
},
{
from: ['/tokens/concepts/idp-access-tokens', '/tokens/overview-idp-access-tokens','/tokens/idp'],
to: '/tokens/identity-provider-access-tokens'
},
{
from: ['/tokens/overview-id-tokens','/tokens/id-token', '/tokens/concepts/id-tokens','/tokens/id_token'],
to: '/tokens/id-tokens'
},
{
from: ['/tokens/guides/id-token/get-id-tokens', '/tokens/guides/get-id-tokens'],
to: '/tokens/id-tokens/get-id-tokens'
},
{
from: ['/tokens/references/id-token-structure'],
to: '/tokens/id-tokens/id-token-structure'
},
{
from: ['/tokens/guides/validate-id-token','/tokens/guides/validate-id-tokens','/tokens/guides/id-token/validate-id-token'],
to: '/tokens/id-tokens/validate-id-tokens'
},
{
from: ['/tokens/concepts/jwts', '/tokens/concepts/why-use-jwt','/tokens/jwt','/jwt'],
to: '/tokens/json-web-tokens'
},
{
from: ['/tokens/jwks', '/jwks','/tokens/concepts/jwks'],
to: '/tokens/json-web-tokens/json-web-key-sets'
},
{
from: ['/tokens/references/jwks-properties', '/tokens/reference/jwt/jwks-properties'],
to: '/tokens/json-web-tokens/json-web-key-set-properties'
},
{
from: ['/tokens/guides/locate-jwks', '/tokens/guides/jwt/verify-jwt-signature-using-jwks', '/tokens/guides/jwt/use-jwks'],
to: '/tokens/json-web-tokens/json-web-key-sets/locate-json-web-key-sets'
},
{
from: ['/tokens/jwt-claims', '/tokens/concepts/jwt-claims','/tokens/add-custom-claims','/scopes/current/custom-claims'],
to: '/tokens/json-web-tokens/json-web-token-claims'
},
{
from: ['/tokens/references/jwt-structure','/tokens/reference/jwt/jwt-structure'],
to: '/tokens/json-web-tokens/json-web-token-structure'
},
{
from: ['/tokens/guides/validate-jwts', '/tokens/guides/jwt/parse-validate-jwt-programmatically', '/tokens/guides/jwt/validate-jwt'],
to: '/tokens/json-web-tokens/validate-json-web-tokens'
},
{
from: ['/api-auth/tutorials/adoption/refresh-tokens','/refresh-token','/tokens/refresh_token','/tokens/refresh-token','/tokens/refresh-token/legacy','/tokens/refresh-token/current','/tokens/concepts/refresh-tokens','/tokens/access-tokens/refresh-tokens','/tokens/preview/refresh-token'],
to: '/tokens/refresh-tokens'
},
{
from: ['/tokens/guides/configure-refresh-token-rotation'],
to: '/tokens/refresh-tokens/configure-refresh-token-rotation'
},
{
from: ['/tokens/guides/disable-refresh-token-rotation','/tokens/access-tokens/refresh-tokens/disable-refresh-token-rotation'],
to: '/tokens/refresh-tokens/disable-refresh-token-rotation'
},
{
from: ['/tokens/guides/get-refresh-tokens'],
to: '/tokens/refresh-tokens/get-refresh-tokens'
},
{
from: ['/tokens/concepts/refresh-token-rotation','/tokens/access-tokens/refresh-tokens/refresh-token-rotation'],
to: '/tokens/refresh-tokens/refresh-token-rotation'
},
{
from: ['/tokens/guides/use-refresh-token-rotation', '/tokens/refresh-token-rotation/use-refresh-token-rotation'],
to: '/tokens/refresh-tokens/refresh-token-rotation/use-refresh-token-rotation'
},
{
from: ['/tokens/guides/revoke-refresh-tokens'],
to: '/tokens/refresh-tokens/revoke-refresh-tokens'
},
{
from: ['/tokens/guides/use-refresh-tokens'],
to: '/tokens/refresh-tokens/use-refresh-tokens'
},
{
from: ['/tokens/guides/revoke-tokens'],
to: '/tokens/revoke-tokens'
},
{
from: ['/applications/concepts/signing-algorithms','/tokens/concepts/signing-algorithms'],
to: '/tokens/signing-algorithms'
},
{
from: ['/api-auth/tutorials/adoption/delegation','/tokens/delegation','/tokens/concepts/delegation-tokens'],
to: '/tokens/delegation-tokens'
},
{
from: ['/api/management/v2/get-access-tokens-for-production'],
to: '/tokens/management-api-access-tokens/get-management-api-access-tokens-for-production'
},
{
from: ['/api/management/v2/get-access-tokens-for-spas'],
to: '/tokens/management-api-access-tokens/get-management-api-tokens-for-single-page-applications'
},
{
from: ['/api/management/v2/get-access-tokens-for-test'],
to: '/tokens/management-api-access-tokens/get-management-api-access-tokens-for-testing'
},
{
from: ['/api/management/v2/tokens','/tokens/apiv2', '/api/v2/tokens', '/api/management/v2/concepts/tokens'],
to: '/tokens/management-api-access-tokens'
},
{
from: ['/api/management/v2/tokens-flows'],
to: '/tokens/management-api-access-tokens/changes-in-auth0-management-apiv2-tokens'
},
{
from: ['/dashboard/guides/apis/update-token-lifetime'],
to: '/tokens/access-tokens/update-access-token-lifetime'
},
{
from: ['/dashboard/guides/applications/update-token-lifetime'],
to: '/tokens/id-tokens/update-id-token-lifetime'
},
{
from: ['/api/management/v2/create-m2m-app', '/tokens/management-api-access-tokens/create-and-authorize-a-machine-to-machine-application'],
to: '/config/api-settings/create-m2m-app-test'
},
{
from: ['/api/management/v2/faq-management-api-access-tokens', '/tokens/management-api-access-tokens/management-api-access-token-faqs'],
to: '/tokens/management-api-access-tokens'
},
/* Troubleshoot */
{
from: ['/troubleshoot/basics'],
to: '/troubleshoot'
},
{
from: ['/troubleshoot/guides/check-error-messages', '/troubleshoot/check-error-messages'],
to: '/troubleshoot/troubleshoot-basic/check-error-messages'
},
{
from: [
'/har',
'/tutorials/troubleshooting-with-har-files',
'/troubleshoot/har',
'/support/troubleshooting-with-har-files',
'/troubleshoot/guides/generate-har-files',
'/troubleshoot/generate-and-analyze-har-files'
],
to: '/troubleshoot/tools/generate-and-analyze-har-files'
},
{
from: ['/troubleshoot/references/invalid-token','/troubleshoot/invalid-token-errors'],
to: '/troubleshoot/troubleshoot-basic/invalid-token-errors'
},
{
from: [
'/troubleshoot/concepts/auth-issues',
'/troubleshoot/troubleshoot-authentication-issues'
],
to: '/troubleshoot/troubleshoot-authentication'
},
{
from: [
'/protocols/saml/saml-configuration/troubleshoot/auth0-as-idp',
'/protocols/saml/saml-configuration/troubleshoot',
'/protocols/saml/saml-configuration/troubleshoot/common-saml-errors',
'/protocols/saml/saml-configuration/troubleshoot/auth0-as-sp',
'/troubleshoot/troubleshoot-saml-configurations',
'/protocols/saml-protocol/troubleshoot-saml-configurations'
],
to: '/troubleshoot/troubleshoot-authentication/troubleshoot-saml-configurations'
},
{
from: ['/troubleshoot/guides/check-api-calls', '/troubleshoot/troubleshoot-authentication-issues/check-api-calls'],
to: '/troubleshoot/troubleshoot-authentication/check-api-calls'
},
{
from: [
'/errors/deprecation-errors',
'/troubleshoot/guides/check-deprecation-errors',
'/troubleshoot/troubleshoot-authentication-issues/check-deprecation-errors'],
to: '/troubleshoot/troubleshoot-basic/check-deprecation-errors'
},
{
from: ['/troubleshoot/guides/check-login-logout-issues', '/troubleshoot/troubleshoot-authentication-issues/check-login-and-logout-issues'],
to: '/troubleshoot/troubleshoot-authentication/check-login-and-logout-issues'
},
{
from: ['/troubleshoot/guides/check-user-profiles', '/troubleshoot/troubleshoot-authentication-issues/check-user-profiles'],
to: '/troubleshoot/troubleshoot-authentication/check-user-profiles'
},
{
from: ['/troubleshoot/references/saml-errors', '/troubleshoot/troubleshoot-authentication-issues/saml-errors'],
to: '/troubleshoot/troubleshoot-authentication/saml-errors'
},
{
from: ['/troubleshoot/basic-troubleshooting','/troubleshoot/concepts/basics'],
to: '/troubleshoot/troubleshoot-basic'
},
{
from: ['/troubleshoot/basic-troubleshooting/verify-connections','/troubleshoot/guides/verify-connections'],
to: '/troubleshoot/troubleshoot-basic/verify-connections'
},
{
from: ['/troubleshoot/basic-troubleshooting/verify-domain','/troubleshoot/guides/verify-domain'],
to: '/troubleshoot/troubleshoot-basic/verify-domain'
},
{
from: ['/troubleshoot/basic-troubleshooting/verify-platform','/troubleshoot/guides/verify-platform'],
to: '/troubleshoot/troubleshoot-basic/verify-platform'
},
{
from: ['/troubleshoot/concepts/integration-extensibility-issues'],
to: '/troubleshoot/troubleshoot-integration-and-extensibility'
},
{
from: ['/custom-domains/troubleshoot-custom-domains','/custom-domains/troubleshoot'],
to: '/troubleshoot/troubleshoot-integrations-and-extensibility/troubleshoot-custom-domains'
},
{
from: [
'/connector/troubleshooting',
'/ad-ldap-connector/troubleshoot-ad-ldap-connector',
'/extensions/ad-ldap-connector/troubleshoot-ad-ldap-connector'
],
to: '/troubleshoot/troubleshoot-integrations-and-extensibility/troubleshoot-ad-ldap-connector'
},
{
from: ['/extensions/troubleshoot-extensions','/extensions/troubleshoot'],
to: '/troubleshoot/troubleshoot-integrations-and-extensibility/troubleshoot-extensions'
},
{
from: [
'/extensions/deploy-cli/references/troubleshooting',
'/extensions/deploy-cli-tool/troubleshoot-the-deploy-cli-tool',
'/deploy/deploy-cli-tool/troubleshoot-the-deploy-cli-tool'
],
to: '/troubleshoot/troubleshoot-integrations-and-extensibility/troubleshoot-the-deploy-cli-tool'
},
{
from: ['/troubleshoot/self-change-password-errors','/troubleshoot/references/self_change_password'],
to: '/troubleshoot/troubleshoot-authentication/self-change-password-errors'
},
{
from: [
'/extensions/authorization-extension/v2/troubleshooting',
'/extensions/authorization-dashboard-extension/troubleshoot-authorization-extension',
'/extensions/authorization-extension/troubleshoot-authorization-extension'
],
to: '/troubleshoot/troubleshoot-authentication/troubleshoot-authorization-extension'
},
{
from: ['/troubleshoot/guides/verify-rules', '/troubleshoot/verify-rules'],
to: '/troubleshoot/troubleshoot-basic/verify-rules'
},
{
from: ['/authorization/concepts/troubleshooting', '/authorization/troubleshoot-role-based-access-control-and-authorization'],
to: '/troubleshoot/troubleshoot-authentication/troubleshoot-rbac-authorization'
},
/* Tutorials */
{
from: ['/scenarios', '/tutorials'],
to: '/'
},
/* Universal Login */
{
from: [
'/hosted-pages/hosted-login-auth0js',
'/hosted-pages/login/auth0js',
'/hosted-pages/login/lock',
'/hosted-pages/login/lock-passwordless',
'/hosted-pages/hosted-login-auth0js/v7',
'/hosted-pages/hosted-login-auth0js/v8',
'/hosted-pages/login',
'/hosted-pages',
'/universal-login/customization-new',
'/login_page'
],
to: '/universal-login'
},
{
from: ['/error-pages', '/error-pages/generic', '/hosted-pages/error-pages'],
to: '/universal-login/error-pages'
},
{
from: ['/universal-login/classic'],
to: '/universal-login/classic-experience'
},
{
from: ['/universal-login/multifactor-authentication','/hosted-pages/guardian','/universal-login/guardian'],
to: '/universal-login/classic-experience/mfa-classic-experience'
},
{
from: ['/universal-login/new'],
to: '/universal-login/new-experience'
},
{
from: ['/dashboard/guides/universal-login/configure-login-page-passwordless','/dashboard/guides/connections/configure-passwordless-sms'],
to: '/universal-login/configure-universal-login-with-passwordless'
},
{
from: ['/universal-login/text-customization-prompts/common'],
to: '/universal-login/prompt-common'
},
{
from: ['/universal-login/text-customization-prompts/consent'],
to: '/universal-login/prompt-consent'
},
{
from: ['/universal-login/text-customization-prompts/device-flow'],
to: '/universal-login/prompt-device-flow'
},
{
from: ['/universal-login/text-customization-prompts/email-verification'],
to: '/universal-login/prompt-email-verification'
},
{
from: ['/universal-login/text-customization-prompts/login'],
to: '/universal-login/prompt-login'
},
{
from: ['/universal-login/text-customization-prompts/mfa'],
to: '/universal-login/prompt-mfa'
},
{
from: ['/universal-login/text-customization-prompts/mfa-email'],
to: '/universal-login/prompt-mfa-email'
},
{
from: ['/universal-login/text-customization-prompts/mfa-otp'],
to: '/universal-login/prompt-mfa-otp'
},
{
from: ['/universal-login/text-customization-prompts/mfa-push'],
to: '/universal-login/prompt-mfa-push'
},
{
from: ['/universal-login/text-customization-prompts/mfa-recovery-code'],
to: '/universal-login/prompt-mfa-recovery-code'
},
{
from: ['/universal-login/text-customization-prompts/mfa-sms'],
to: '/universal-login/prompt-mfa-sms'
},
{
from: ['/universal-login/text-customization-prompts/reset-password'],
to: '/universal-login/prompt-reset-password'
},
{
from: ['/universal-login/text-customization-prompts/signup'],
to: '/universal-login/prompt-signup'
},
{
from: ['/guides/login/universal-vs-embedded','/guides/login/centralized-vs-embedded'],
to: '/universal-login/universal-vs-embedded-login'
},
{
from: ['/libraries/when-to-use-lock'],
to: '/universal-login/universal-login-page-customization'
},
{
from: ['/universal-login/default-login-url','/hosted-pages/default-login-url'],
to: '/universal-login/configure-default-login-routes'
},
/* Users */
{
from: ['/users/concepts/overview-users'],
to: '/users'
},
{
from: ['/users/guides/block-and-unblock-users'],
to: '/users/block-and-unblock-users'
},
{
from: ['/users/guides/delete-users'],
to: '/users/delete-users'
},
{
from: ['/dashboard/guides/users/unlink-user-devices'],
to: '/users/unlink-devices-from-users'
},
{
from: ['/user-profile/progressive-profiling','/users/concepts/overview-progressive-profiling','/users/guides/implement-progressive-profiling'],
to: '/users/progressive-profiling'
},
{
from: [
'/users/concepts/overview-user-metadata',
'/metadata',
'/users/read-metadata',
'/users/guides/read-metadata',
'/users/guides/manage-user-metadata',
'/users/manage-user-metadata'
],
to: '/users/metadata'
},
{
from: [
'/users/references/metadata-field-name-rules',
'/best-practices/metadata-best-practices'
],
to: '/users/metadata/metadata-fields-data'
},
{
from: [
'/users/guides/update-metadata-properties-with-management-api',
'/update-metadata-with-the-management-api',
'/users/update-metadata-with-the-management-api',
'/metadata/management-api',
'/metadata/apiv2',
'/metadata/apis',
'/users/guides/set-metadata-properties-on-creation',
'/users/set-metadata-properties-on-creation'
],
to: '/users/metadata/manage-metadata-api'
},
{
from: ['/metadata/lock'],
to: '/users/metadata/manage-metadata-lock'
},
{
from: [
'/rules/current/metadata-in-rules',
'/rules/guides/metadata',
'/rules/metadata-in-rules',
'/metadata-in-rules',
'/metadata/rules',
'/rules/metadata'
],
to: '/users/metadata/manage-metadata-rules'
},
{
from: ['/users/concepts/overview-user-migration'],
to: '/users/import-and-export-users'
},
{
from: ['/user-profile/normalized','/user-profile/normalized/oidc','/user-profile','/users/concepts/overview-user-profile','/user-profile/user-profile-details','/users/normalized/oidc','/users/user-profiles-returned-from-oidc-compliant-pipelines'],
to: '/users/user-profiles'
},
{
from: ['/users/guides/bulk-user-exports'],
to: '/users/bulk-user-exports'
},
{
from: ['/tutorials/bulk-importing-users-into-auth0','/users/guides/bulk-user-imports', '/users/guides/bulk-user-import','/users/bulk-importing-users-into-auth0', '/users/migrations/bulk-import','/bulk-import'],
to: '/users/bulk-user-imports'
},
{
from: ['/user-profile/user-picture','/users/guides/change-user-pictures'],
to: '/users/change-user-picture'
},
{
from: ['/connections/database/migrating','/migrating','/users/migrations/automatic','/users/guides/configure-automatic-migration'],
to: '/users/configure-automatic-migration-from-your-database'
},
{
from: ['/tutorials/creating-users-in-the-management-portal','/users/guides/create-users','/creating-users','/dashboard/guides/users/create-users'],
to: '/users/create-users'
},
{
from: ['/users/guides/email-verified'],
to: '/users/verified-email-usage'
},
{
from: ['/tutorials/get-user-information-with-unbounce-landing-pages','/users/guides/get-user-information-with-unbounce-landing-pages','/scenarios-unbounce'],
to: '/users/get-user-information-on-unbounce-landing-pages'
},
{
from: ['/users/guides/link-user-accounts','/link-accounts/suggested-linking'],
to: '/users/link-user-accounts'
},
{
from: ['/users/guides/manage-user-access-to-applications'],
to: '/users/manage-user-access-to-applications'
},
{
from: ['/users/guides/manage-users-using-the-dashboard'],
to: '/users/manage-users-using-the-dashboard'
},
{
from: ['/users/guides/manage-users-using-the-management-api'],
to: '/users/manage-users-using-the-management-api'
},
{
from: ['/tutorials/redirecting-users','/users/redirecting-users','/users/guides/redirect-users-after-login','/protocols/oauth2/redirect-users','/users/concepts/redirect-users-after-login'],
to: '/users/redirect-users-after-login'
},
{
from: ['/users/guides/unlink-user-accounts'],
to: '/users/unlink-user-accounts'
},
{
from: ['/user-profile/customdb','/users/guides/update-user-profiles-using-your-database'],
to: '/users/update-user-profiles-using-your-database'
},
{
from: ['/users/guides/view-users'],
to: '/users/view-user-details'
},
{
from: ['/users/normalized'],
to: '/users/normalized-user-profiles'
},
{
from: ['/users/normalized/auth0/identify-users'],
to: '/users/identify-users'
},
{
from: ['/user-profile/normalized/auth0','/users/normalized/auth0'],
to: '/users/normalized-user-profiles'
},
{
from: ['/users/normalized/auth0/normalized-user-profile-schema'],
to: '/users/normalized-user-profile-schema'
},
{
from: ['/users/normalized/auth0/sample-user-profiles'],
to: '/users/sample-user-profiles'
},
{
from: ['/users/normalized/auth0/update-root-attributes'],
to: '/users/updating-user-profile-root-attributes'
},
{
from: ['/users/references/bulk-import-database-schema-examples'],
to: '/users/bulk-user-import-database-schema-and-examples'
},
{
from: ['/link-accounts/user-initiated', '/link-accounts/user-initiated-linking','/users/references/link-accounts-user-initiated-scenario','/users/references/link-accounts-client-side-scenario','/user/references/link-accounts-client-side-scenario'],
to: '/users/user-initiated-account-linking-client-side-implementation'
},
{
from: ['/users/references/link-accounts-server-side-scenario'],
to: '/users/suggested-account-linking-server-side-implementation'
},
{
from: ['/connections/database/migrating-okta', '/users/migrations/okta','/users/references/user-migration-scenarios','/users/migrations'],
to: '/users/user-migration-scenarios'
},
{
from: ['/user-profile/user-profile-structure','/users/references/user-profile-structure'],
to: '/users/user-profile-structure'
},
{
from: ['/dashboard/guides/connections/configure-connection-sync','/api/management/guides/connections/configure-connection-sync'],
to: '/users/configure-connection-sync-with-auth0'
},
{
from: ['/api/management/guides/users/set-root-attributes-user-import'],
to: '/users/set-root-attributes-during-user-import'
},
{
from: ['/api/management/guides/users/set-root-attributes-user-signup'],
to: '/users/set-root-attributes-during-user-sign-up'
},
{
from: ['/api/management/guides/users/update-root-attributes-users'],
to: '/users/update-root-attributes-for-users'
},
{
from: ['/users/search/v3','/users/normalized/auth0/retrieve-user-profiles','/users/search','/users-search'],
to: '/users/user-search'
},
{
from: ['/users/search/v3/query-syntax'],
to: '/users/user-search/user-search-query-syntax'
},
{
from: ['/api/management/v2/user-search','/users/search/v2', '/api/v2/user-search'],
to: '/users/user-search/v2'
},
{
from: ['/api/management/v2/query-string-syntax', '/users/search/v2/query-syntax'],
to: '/users/user-search/v2/query-syntax'
},
{
from: ['/users/search/v3/migrate-search-v2-v3','/users/user-search/migrate-search-v2-v3'],
to: '/users/user-search/migrate-v2-v3'
},
{
from: ['/users/search/v3/get-users-by-email-endpoint'],
to: '/users/user-search/retrieve-users-with-get-users-by-email-endpoint'
},
{
from: ['/users/search/v3/get-users-by-id-endpoint'],
to: '/users/user-search/retrieve-users-with-get-users-by-id-endpoint'
},
{
from: ['/users/search/v3/get-users-endpoint','/users/user-search/retrieve-users-with-the-get-users-endpoint'],
to: '/users/user-search/retrieve-users-with-get-users-endpoint'
},
{
from: ['/users/search/v3/sort-search-results'],
to: '/users/user-search/sort-search-results'
},
{
from: ['/users/search/v3/view-search-results-by-page'],
to: '/users/user-search/view-search-results-by-page'
},
{
from: ['/dashboard/guides/users/assign-permissions-users','/api/management/guides/users/assign-permissions-users'],
to: '/users/assign-permissions-to-users'
},
{
from: ['/dashboard/guides/users/assign-roles-users','/api/management/guides/users/assign-roles-users'],
to: '/users/assign-roles-to-users'
},
{
from: ['/dashboard/guides/users/remove-user-permissions','/api/management/guides/users/remove-user-permissions'],
to: '/users/remove-permissions-from-users'
},
{
from: ['/dashboard/guides/users/remove-user-roles','/dashboard/guides/roles/remove-role-users','/api/management/guides/users/remove-user-roles'],
to: '/users/remove-roles-from-users'
},
{
from: ['/dashboard/guides/users/view-user-permissions','/api/management/guides/users/view-user-permissions'],
to: '/users/view-user-permissions'
},
{
from: ['/dashboard/guides/users/view-user-roles','/api/management/guides/users/view-user-roles'],
to: '/users/view-user-roles'
},
{
from: ['/users/concepts/overview-progressive-profiling'],
to: '/users/progressive-profiling'
},
{
from: ['/link-accounts/auth-api','/link-accounts','/users/concepts/overview-user-account-linking','/users/guide/concepts/overview-user-account-linking'],
to: '/users/user-account-linking'
},
{
from: ['/users/guides/get-user-information-with-unbounce-landing-pages'],
to: '/users/get-user-information-on-unbounce-landing-pages'
},
/* Videos */
{
from: ['/video-series/main/videos'],
to: '/videos'
},
{
from: ['/videos/learn-identity'],
to: '/videos/learn-identity-series'
},
{
from: ['/videos/learn-identity/01-introduction-to-identity','/videos/learn-identity-series/learn-identity-series/introduction-to-identity'],
to: '/videos/learn-identity-series/introduction-to-identity'
},
{
from: ['/videos/learn-identity/02-oidc-and-oauth'],
to: '/videos/learn-identity-series/openid-connect-and-oauth2'
},
{
from: ['/videos/learn-identity/03-web-sign-in'],
to: '/videos/learn-identity-series/web-sign-in'
},
{
from: ['/videos/learn-identity/04-calling-an-api'],
to: '/videos/learn-identity-series/calling-an-api'
},
{
from: ['/videos/learn-identity/05-desktop-and-mobile-apps'],
to: '/videos/learn-identity-series/desktop-and-mobile-apps'
},
{
from: ['/videos/learn-identity/06-single-page-apps'],
to: '/videos/learn-identity-series/single-page-apps'
},
{
from: ['/videos/get-started'],
to: '/videos/get-started-series'
},
{
from: ['/videos/get-started/01-architecture-your-tenant'],
to: '/videos/get-started-series/architect-your-tenant'
},
{
from: ['/videos/get-started/02-provision-user-stores'],
to: '/videos/get-started-series/provision-user-stores'
},
{
from: ['/videos/get-started/03-provision-import-users'],
to: '/videos/get-started-series/provision-import-users'
},
{
from: ['/videos/get-started/04_01-authenticate-how-it-works'],
to: '/videos/get-started-series/authenticate-how-it-works'
},
{
from: ['/videos/get-started/04_02-authenticate-spa-example','/videos/get-started/04_01-authenticate-spa-example'],
to: '/videos/get-started-series/authenticate-spa-example'
},
{
from: ['/videos/get-started/05_01-authorize-id-tokens-access-control'],
to: '/videos/get-started-series/authorize-id-tokens-and-access-control'
},
{
from: ['/videos/get-started/05_02-authorize-get-validate-id-tokens'],
to: '/videos/get-started-series/authorize-get-and-validate-id-tokens'
},
{
from: ['/videos/get-started/06-user-profiles'],
to: '/videos/get-started-series/learn-user-profiles'
},
{
from: ['/videos/get-started/07_01-brand-how-it-works'],
to: '/videos/get-started-series/brand-how-it-works'
},
{
from: ['/videos/get-started/07_02-brand-signup-login-pages'],
to: '/videos/get-started-series/brand-signup-and-login-pages'
},
{
from: ['/videos/get-started/08-brand-emails-error-pages'],
to: '/videos/get-started-series/brand-emails-and-error-pages'
},
{
from: ['/videos/get-started/10-logout'],
to: '/videos/get-started-series/learn-logout'
},
/* Support */
{
from: ['/support/support-overview'],
to: '/support/support-plans'
}
];
| Brand and Customize redirects
Brand and customize redirect fixes
| config/redirects.js | Brand and Customize redirects | <ide><path>onfig/redirects.js
<ide> '/i18n/password-strength'
<ide> ],
<ide> to: '/brand-and-customize/i18n/password-options-translation'
<add> },
<add> {
<add> from: ['/universal-login/new-experience/universal-login-page-templates','/universal-login/page-templates'],
<add> to: '/brand-and-customize/universal-login-page-templates'
<add> },
<add>
<add> /* Custom Domains */
<add>
<add> {
<add> from: '/custom-domains',
<add> to: '/brand-and-customize/custom-domains'
<add> },
<add> {
<add> from: ['/custom-domains/configure-custom-domains-with-auth0-managed-certificates','/custom-domains/auth0-managed-certificates'],
<add> to: '/brand-and-customize/custom-domains/auth0-managed-certificates'
<add> },
<add> {
<add> from: ['/custom-domains/self-managed-certificates','/custom-domains/configure-custom-domains-with-self-managed-certificates'],
<add> to: '/brand-and-customize/custom-domains/self-managed-certificates'
<add> },
<add> {
<add> from: '/custom-domains/tls-ssl',
<add> to: '/brand-and-customize/custom-domains/self-managed-certificates/tls-ssl'
<add> },
<add> {
<add> from: '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-gcp-as-reverse-proxy',
<add> to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-gcp-as-reverse-proxy'
<add> },
<add> {
<add> from: [
<add> '/custom-domains/set-up-cloudfront',
<add> '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-aws-cloudfront-for-use-as-reverse-proxy'
<add> ],
<add> to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-aws-cloudfront-for-use-as-reverse-proxy'
<add> },
<add> {
<add> from: [
<add> '/custom-domains/set-up-cloudflare',
<add> '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-cloudflare-for-use-as-reverse-proxy'
<add> ],
<add> to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-cloudflare-for-use-as-reverse-proxy'
<add> },
<add> {
<add> from: [
<add> '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-azure-cdn-for-use-as-reverse-proxy',
<add> '/custom-domains/set-up-azure-cdn'
<add> ],
<add> to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-azure-cdn-for-use-as-reverse-proxy'
<add> },
<add> {
<add> from: '/custom-domains/configure-custom-domains-with-self-managed-certificates/configure-akamai-for-use-as-reverse-proxy',
<add> to: '/brand-and-customize/custom-domains/self-managed-certificates/configure-akamai-for-use-as-reverse-proxy'
<add> },
<add> {
<add> from: ['/custom-domains/configure-features-to-use-custom-domains','/custom-domains/additional-configuration'],
<add> to: '/brand-and-customize/custom-domains/configure-features-to-use-custom-domains'
<add> },
<add>
<add> /* Email */
<add>
<add> {
<add> from: ['/email','/auth0-email-services'],
<add> to: '/brand-and-customize/email'
<add> },
<add> {
<add> from: [
<add> '/email/custom',
<add> '/auth0-email-services/manage-email-flow',
<add> '/email/manage-email-flow'
<add> ],
<add> to: '/brand-and-customize/email/manage-email-flow'
<add> },
<add> {
<add> from: [
<add> '/email/templates',
<add> '/auth0-email-services/customize-email-templates',
<add> '/email/spa-redirect',
<add> '/auth0-email-services/spa-redirect',
<add> '/email/customize-email-templates'
<add> ],
<add> to: '/brand-and-customize/email/customize-email-templates'
<add> },
<add> {
<add> from: [
<add> '/email/customize-email-templates/email-template-descriptions',
<add> '/auth0-email-services/email-template-descriptions'
<add> ],
<add> to: '/brand-and-customize/email/email-template-descriptions'
<add> },
<add> {
<add> from: [
<add> '/email/liquid-syntax',
<add> '/auth0-email-services/customize-email-templates/use-liquid-syntax-in-email-templates',
<add> '/email/customize-email-templates/use-liquid-syntax-in-email-templates'
<add> ],
<add> to: '/brand-and-customize/email/use-liquid-syntax-in-email-templates'
<add> },
<add> {
<add> from: [
<add> '/design/creating-invite-only-applications',
<add> '/invite-only',
<add> '/tutorials/creating-invite-only-applications',
<add> '/auth0-email-services/send-email-invitations-for-application-signup',
<add> '/email/send-email-invitations-for-application-signup'
<add> ],
<add> to: '/brand-and-customize/email/send-email-invitations-for-application-signup'
<add> },
<add> {
<add> from: '/email/send-email-invitations-for-application-signup',
<add> to: '/brand-and-customize/email/send-email-invitations-for-application-signup'
<add> },
<add> {
<add> from: [
<add> '/auth0-email-services/configure-external-smtp-email-providers',
<add> '/email/providers',
<add> '/email/configure-external-smtp-email-providers'
<add> ],
<add> to: '/brand-and-customize/email/smtp-email-providers'
<add> },
<add> {
<add> from: '/email/configure-external-smtp-email-providers/configure-amazon-ses-as-external-smtp-email-provider',
<add> to: '/brand-and-customize/email/smtp-email-providers/configure-amazon-ses-as-external-smtp-email-provider'
<add> },
<add> {
<add> from: '/email/configure-external-smtp-email-providers/configure-mandrill-as-external-smtp-email-provider',
<add> to: '/brand-and-customize/email/smtp-email-providers/configure-mandrill-as-external-smtp-email-provider'
<add> },
<add> {
<add> from: '/email/configure-external-smtp-email-providers/configure-sendgrid-as-external-smtp-email-provider',
<add> to: '/brand-and-customize/email/smtp-email-providers/configure-sendgrid-as-external-smtp-email-provider'
<add> },
<add> {
<add> from: '/email/configure-external-smtp-email-providers/configure-sparkpost-as-external-smtp-email-provider',
<add> to: '/brand-and-customize/email/smtp-email-providers/configure-sparkpost-as-external-smtp-email-provider'
<add> },
<add> {
<add> from: '/email/configure-external-smtp-email-providers/configure-mailgun-as-external-smtp-email-provider',
<add> to: '/brand-and-customize/email/smtp-email-providers/configure-mailgun-as-external-smtp-email-provider'
<add> },
<add> {
<add> from: [
<add> '/auth0-email-services/configure-external-smtp-email-providers/configure-custom-external-smtp-email-provider',
<add> '/email/configure-custom-external-smtp-email-provider'
<add> ],
<add> to: '/brand-and-customize/email/smtp-email-providers/configure-custom-external-smtp-email-provider'
<add> },
<add> {
<add> from: [
<add> '/email/testing',
<add> '/auth0-email-services/configure-external-smtp-email-providers/configure-test-smtp-email-servers',
<add> '/email/configure-test-smtp-email-servers'
<add> ],
<add> to: '/brand-and-customize/email/configure-test-smtp-email-servers'
<ide> },
<ide>
<ide> /* CMS */ |
|
Java | apache-2.0 | ad42821bc281f0a5eb4de6a12b100277e97d8431 | 0 | arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint | /*
* Copyright (c) 2010-2017 Evolveum
*
* 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.evolveum.midpoint.web.component.prism.show;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.model.api.ModelInteractionService;
import com.evolveum.midpoint.model.api.context.ModelContext;
import com.evolveum.midpoint.model.api.context.ModelProjectionContext;
import com.evolveum.midpoint.model.api.visualizer.Scene;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectResolver;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.application.PageDescriptor;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.breadcrumbs.Breadcrumb;
import com.evolveum.midpoint.web.component.breadcrumbs.BreadcrumbPageInstance;
import com.evolveum.midpoint.web.component.util.EnableBehaviour;
import com.evolveum.midpoint.web.component.util.VisibleBehaviour;
import com.evolveum.midpoint.web.component.wf.ApprovalProcessesPreviewPanel;
import com.evolveum.midpoint.web.page.admin.PageAdmin;
import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails;
import com.evolveum.midpoint.web.page.admin.workflow.EvaluatedTriggerGroupListPanel;
import com.evolveum.midpoint.web.page.admin.workflow.dto.ApprovalProcessExecutionInformationDto;
import com.evolveum.midpoint.web.page.admin.workflow.dto.EvaluatedTriggerGroupDto;
import com.evolveum.midpoint.web.util.OnePageParameterEncoder;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ApprovalSchemaExecutionInformationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.PolicyRuleEnforcerHookPreviewOutputType;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.apache.commons.collections.CollectionUtils.addIgnoreNull;
/**
* @author mederly
*/
@PageDescriptor(url = "/admin/previewChanges", encoder = OnePageParameterEncoder.class)
public class PagePreviewChanges extends PageAdmin {
private static final String ID_PRIMARY_DELTAS_SCENE = "primaryDeltas";
private static final String ID_SECONDARY_DELTAS_SCENE = "secondaryDeltas";
private static final String ID_APPROVALS_CONTAINER = "approvalsContainer";
private static final String ID_APPROVALS = "approvals";
private static final String ID_POLICY_VIOLATIONS_CONTAINER = "policyViolationsContainer";
private static final String ID_POLICY_VIOLATIONS = "policyViolations";
private static final String ID_CONTINUE_EDITING = "continueEditing";
private static final String ID_SAVE = "save";
private static final Trace LOGGER = TraceManager.getTrace(PagePreviewChanges.class);
private IModel<SceneDto> primaryDeltasModel;
private IModel<SceneDto> secondaryDeltasModel;
private IModel<List<EvaluatedTriggerGroupDto>> policyViolationsModel;
private IModel<List<ApprovalProcessExecutionInformationDto>> approvalsModel;
public PagePreviewChanges(ModelContext<? extends ObjectType> modelContext, ModelInteractionService modelInteractionService) {
final List<ObjectDelta<? extends ObjectType>> primaryDeltas = new ArrayList<>();
final List<ObjectDelta<? extends ObjectType>> secondaryDeltas = new ArrayList<>();
final List<? extends Scene> primaryScenes;
final List<? extends Scene> secondaryScenes;
try {
if (modelContext != null) {
if (modelContext.getFocusContext() != null) {
addIgnoreNull(primaryDeltas, modelContext.getFocusContext().getPrimaryDelta());
addIgnoreNull(secondaryDeltas, modelContext.getFocusContext().getSecondaryDelta());
}
for (ModelProjectionContext projCtx : modelContext.getProjectionContexts()) {
addIgnoreNull(primaryDeltas, projCtx.getPrimaryDelta());
addIgnoreNull(secondaryDeltas, projCtx.getExecutableDelta());
}
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Primary deltas:\n{}", DebugUtil.debugDump(primaryDeltas));
LOGGER.trace("Secondary deltas:\n{}", DebugUtil.debugDump(secondaryDeltas));
}
Task task = createSimpleTask("visualize");
primaryScenes = modelInteractionService.visualizeDeltas(primaryDeltas, task, task.getResult());
secondaryScenes = modelInteractionService.visualizeDeltas(secondaryDeltas, task, task.getResult());
} catch (SchemaException | ExpressionEvaluationException e) {
throw new SystemException(e); // TODO
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Creating context DTO for primary deltas:\n{}", DebugUtil.debugDump(primaryScenes));
LOGGER.trace("Creating context DTO for secondary deltas:\n{}", DebugUtil.debugDump(secondaryScenes));
}
final WrapperScene primaryScene = new WrapperScene(primaryScenes,
primaryScenes.size() != 1 ? "PagePreviewChanges.primaryChangesMore" : "PagePreviewChanges.primaryChangesOne", primaryScenes.size());
final WrapperScene secondaryScene = new WrapperScene(secondaryScenes,
secondaryScenes.size() != 1 ? "PagePreviewChanges.secondaryChangesMore" : "PagePreviewChanges.secondaryChangesOne", secondaryScenes.size());
final SceneDto primarySceneDto = new SceneDto(primaryScene);
final SceneDto secondarySceneDto = new SceneDto(secondaryScene);
primaryDeltasModel = new AbstractReadOnlyModel<SceneDto>() {
@Override
public SceneDto getObject() {
return primarySceneDto;
}
};
secondaryDeltasModel = new AbstractReadOnlyModel<SceneDto>() {
@Override
public SceneDto getObject() {
return secondarySceneDto;
}
};
PolicyRuleEnforcerHookPreviewOutputType enforcements = modelContext != null
? modelContext.getHookPreviewResult(PolicyRuleEnforcerHookPreviewOutputType.class)
: null;
List<EvaluatedTriggerGroupDto> triggerGroups = enforcements != null
? Collections.singletonList(EvaluatedTriggerGroupDto.initializeFromRules(enforcements.getRule(), false, null))
: Collections.emptyList();
policyViolationsModel = Model.ofList(triggerGroups);
List<ApprovalSchemaExecutionInformationType> approvalsExecutionList = modelContext != null
? modelContext.getHookPreviewResults(ApprovalSchemaExecutionInformationType.class)
: Collections.emptyList();
List<ApprovalProcessExecutionInformationDto> approvals = new ArrayList<>();
if (!approvalsExecutionList.isEmpty()) {
Task opTask = createSimpleTask(PagePreviewChanges.class + ".createApprovals"); // TODO
OperationResult result = opTask.getResult();
ObjectResolver modelObjectResolver = getModelObjectResolver();
try {
for (ApprovalSchemaExecutionInformationType execution : approvalsExecutionList) {
approvals.add(ApprovalProcessExecutionInformationDto
.createFrom(execution, modelObjectResolver, true, opTask, result)); // TODO reuse session
}
result.computeStatus();
} catch (Throwable t) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't prepare approval information", t);
result.recordFatalError("Couldn't prepare approval information: " + t.getMessage(), t);
}
if (WebComponentUtil.showResultInPage(result)) {
showResult(result);
}
}
approvalsModel = Model.ofList(approvals);
initLayout();
}
@Override
protected void createBreadcrumb() {
createInstanceBreadcrumb();
}
private void initLayout() {
Form mainForm = new com.evolveum.midpoint.web.component.form.Form("mainForm");
mainForm.setMultiPart(true);
add(mainForm);
mainForm.add(new ScenePanel(ID_PRIMARY_DELTAS_SCENE, primaryDeltasModel));
mainForm.add(new ScenePanel(ID_SECONDARY_DELTAS_SCENE, secondaryDeltasModel));
WebMarkupContainer policyViolationsContainer = new WebMarkupContainer(ID_POLICY_VIOLATIONS_CONTAINER);
policyViolationsContainer.add(new VisibleBehaviour(() -> !violationsEmpty()));
policyViolationsContainer.add(new EvaluatedTriggerGroupListPanel(ID_POLICY_VIOLATIONS, policyViolationsModel));
mainForm.add(policyViolationsContainer);
WebMarkupContainer approvalsContainer = new WebMarkupContainer(ID_APPROVALS_CONTAINER);
approvalsContainer.add(new VisibleBehaviour(() -> violationsEmpty() && !approvalsEmpty()));
approvalsContainer.add(new ApprovalProcessesPreviewPanel(ID_APPROVALS, approvalsModel));
mainForm.add(approvalsContainer);
initButtons(mainForm);
}
private boolean approvalsEmpty() {
return approvalsModel.getObject().isEmpty();
}
private boolean violationsEmpty() {
return EvaluatedTriggerGroupDto.isEmpty(policyViolationsModel.getObject());
}
private void initButtons(Form mainForm) {
AjaxButton cancel = new AjaxButton(ID_CONTINUE_EDITING, createStringResource("PagePreviewChanges.button.continueEditing")) {
@Override
public void onClick(AjaxRequestTarget target) {
cancelPerformed(target);
}
};
mainForm.add(cancel);
AjaxButton save = new AjaxButton(ID_SAVE, createStringResource("PagePreviewChanges.button.save")) {
@Override
public void onClick(AjaxRequestTarget target) {
savePerformed(target);
}
};
//save.add(new EnableBehaviour(() -> violationsEmpty())); // does not work as expected (MID-4252)
save.add(new VisibleBehaviour(() -> violationsEmpty())); // so hiding the button altogether
mainForm.add(save);
}
private void cancelPerformed(AjaxRequestTarget target) {
redirectBack();
}
private void savePerformed(AjaxRequestTarget target) {
Breadcrumb bc = redirectBack();
if (bc instanceof BreadcrumbPageInstance) {
BreadcrumbPageInstance bcpi = (BreadcrumbPageInstance) bc;
WebPage page = bcpi.getPage();
if (page instanceof PageAdminObjectDetails) {
((PageAdminObjectDetails) page).setSaveOnConfigure(true);
} else {
error("Couldn't save changes - unexpected referring page: " + page);
}
} else {
error("Couldn't save changes - no instance for referring page; breadcrumb is " + bc);
}
}
}
| gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/show/PagePreviewChanges.java | /*
* Copyright (c) 2010-2017 Evolveum
*
* 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.evolveum.midpoint.web.component.prism.show;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.model.api.ModelInteractionService;
import com.evolveum.midpoint.model.api.context.ModelContext;
import com.evolveum.midpoint.model.api.context.ModelProjectionContext;
import com.evolveum.midpoint.model.api.visualizer.Scene;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectResolver;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.application.PageDescriptor;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.breadcrumbs.Breadcrumb;
import com.evolveum.midpoint.web.component.breadcrumbs.BreadcrumbPageInstance;
import com.evolveum.midpoint.web.component.util.EnableBehaviour;
import com.evolveum.midpoint.web.component.util.VisibleBehaviour;
import com.evolveum.midpoint.web.component.wf.ApprovalProcessesPreviewPanel;
import com.evolveum.midpoint.web.page.admin.PageAdmin;
import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails;
import com.evolveum.midpoint.web.page.admin.workflow.EvaluatedTriggerGroupListPanel;
import com.evolveum.midpoint.web.page.admin.workflow.dto.ApprovalProcessExecutionInformationDto;
import com.evolveum.midpoint.web.page.admin.workflow.dto.EvaluatedTriggerGroupDto;
import com.evolveum.midpoint.web.util.OnePageParameterEncoder;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ApprovalSchemaExecutionInformationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.PolicyRuleEnforcerHookPreviewOutputType;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.apache.commons.collections.CollectionUtils.addIgnoreNull;
/**
* @author mederly
*/
@PageDescriptor(url = "/admin/previewChanges", encoder = OnePageParameterEncoder.class)
public class PagePreviewChanges extends PageAdmin {
private static final String ID_PRIMARY_DELTAS_SCENE = "primaryDeltas";
private static final String ID_SECONDARY_DELTAS_SCENE = "secondaryDeltas";
private static final String ID_APPROVALS_CONTAINER = "approvalsContainer";
private static final String ID_APPROVALS = "approvals";
private static final String ID_POLICY_VIOLATIONS_CONTAINER = "policyViolationsContainer";
private static final String ID_POLICY_VIOLATIONS = "policyViolations";
private static final String ID_CONTINUE_EDITING = "continueEditing";
private static final String ID_SAVE = "save";
private static final Trace LOGGER = TraceManager.getTrace(PagePreviewChanges.class);
private IModel<SceneDto> primaryDeltasModel;
private IModel<SceneDto> secondaryDeltasModel;
private IModel<List<EvaluatedTriggerGroupDto>> policyViolationsModel;
private IModel<List<ApprovalProcessExecutionInformationDto>> approvalsModel;
public PagePreviewChanges(ModelContext<? extends ObjectType> modelContext, ModelInteractionService modelInteractionService) {
final List<ObjectDelta<? extends ObjectType>> primaryDeltas = new ArrayList<>();
final List<ObjectDelta<? extends ObjectType>> secondaryDeltas = new ArrayList<>();
final List<? extends Scene> primaryScenes;
final List<? extends Scene> secondaryScenes;
try {
if (modelContext != null) {
if (modelContext.getFocusContext() != null) {
addIgnoreNull(primaryDeltas, modelContext.getFocusContext().getPrimaryDelta());
addIgnoreNull(secondaryDeltas, modelContext.getFocusContext().getSecondaryDelta());
}
for (ModelProjectionContext projCtx : modelContext.getProjectionContexts()) {
addIgnoreNull(primaryDeltas, projCtx.getPrimaryDelta());
addIgnoreNull(secondaryDeltas, projCtx.getExecutableDelta());
}
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Primary deltas:\n{}", DebugUtil.debugDump(primaryDeltas));
LOGGER.trace("Secondary deltas:\n{}", DebugUtil.debugDump(secondaryDeltas));
}
Task task = createSimpleTask("visualize");
primaryScenes = modelInteractionService.visualizeDeltas(primaryDeltas, task, task.getResult());
secondaryScenes = modelInteractionService.visualizeDeltas(secondaryDeltas, task, task.getResult());
} catch (SchemaException | ExpressionEvaluationException e) {
throw new SystemException(e); // TODO
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Creating context DTO for primary deltas:\n{}", DebugUtil.debugDump(primaryScenes));
LOGGER.trace("Creating context DTO for secondary deltas:\n{}", DebugUtil.debugDump(secondaryScenes));
}
final WrapperScene primaryScene = new WrapperScene(primaryScenes,
primaryScenes.size() != 1 ? "PagePreviewChanges.primaryChangesMore" : "PagePreviewChanges.primaryChangesOne", primaryScenes.size());
final WrapperScene secondaryScene = new WrapperScene(secondaryScenes,
secondaryScenes.size() != 1 ? "PagePreviewChanges.secondaryChangesMore" : "PagePreviewChanges.secondaryChangesOne", secondaryScenes.size());
final SceneDto primarySceneDto = new SceneDto(primaryScene);
final SceneDto secondarySceneDto = new SceneDto(secondaryScene);
primaryDeltasModel = new AbstractReadOnlyModel<SceneDto>() {
@Override
public SceneDto getObject() {
return primarySceneDto;
}
};
secondaryDeltasModel = new AbstractReadOnlyModel<SceneDto>() {
@Override
public SceneDto getObject() {
return secondarySceneDto;
}
};
PolicyRuleEnforcerHookPreviewOutputType enforcements = modelContext != null
? modelContext.getHookPreviewResult(PolicyRuleEnforcerHookPreviewOutputType.class)
: null;
List<EvaluatedTriggerGroupDto> triggerGroups = enforcements != null
? Collections.singletonList(EvaluatedTriggerGroupDto.initializeFromRules(enforcements.getRule(), false, null))
: Collections.emptyList();
policyViolationsModel = Model.ofList(triggerGroups);
List<ApprovalSchemaExecutionInformationType> approvalsExecutionList = modelContext != null
? modelContext.getHookPreviewResults(ApprovalSchemaExecutionInformationType.class)
: Collections.emptyList();
List<ApprovalProcessExecutionInformationDto> approvals = new ArrayList<>();
if (!approvalsExecutionList.isEmpty()) {
Task opTask = createSimpleTask(PagePreviewChanges.class + ".createApprovals"); // TODO
OperationResult result = opTask.getResult();
ObjectResolver modelObjectResolver = getModelObjectResolver();
try {
for (ApprovalSchemaExecutionInformationType execution : approvalsExecutionList) {
approvals.add(ApprovalProcessExecutionInformationDto
.createFrom(execution, modelObjectResolver, true, opTask, result)); // TODO reuse session
}
result.computeStatus();
} catch (Throwable t) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't prepare approval information", t);
result.recordFatalError("Couldn't prepare approval information: " + t.getMessage(), t);
}
if (WebComponentUtil.showResultInPage(result)) {
showResult(result);
}
}
approvalsModel = Model.ofList(approvals);
initLayout();
}
@Override
protected void createBreadcrumb() {
createInstanceBreadcrumb();
}
private void initLayout() {
Form mainForm = new com.evolveum.midpoint.web.component.form.Form("mainForm");
mainForm.setMultiPart(true);
add(mainForm);
mainForm.add(new ScenePanel(ID_PRIMARY_DELTAS_SCENE, primaryDeltasModel));
mainForm.add(new ScenePanel(ID_SECONDARY_DELTAS_SCENE, secondaryDeltasModel));
WebMarkupContainer policyViolationsContainer = new WebMarkupContainer(ID_POLICY_VIOLATIONS_CONTAINER);
policyViolationsContainer.add(new VisibleBehaviour(() -> !violationsEmpty()));
policyViolationsContainer.add(new EvaluatedTriggerGroupListPanel(ID_POLICY_VIOLATIONS, policyViolationsModel));
mainForm.add(policyViolationsContainer);
WebMarkupContainer approvalsContainer = new WebMarkupContainer(ID_APPROVALS_CONTAINER);
approvalsContainer.add(new VisibleBehaviour(() -> violationsEmpty() && !approvalsEmpty()));
approvalsContainer.add(new ApprovalProcessesPreviewPanel(ID_APPROVALS, approvalsModel));
mainForm.add(approvalsContainer);
initButtons(mainForm);
}
private boolean approvalsEmpty() {
return approvalsModel.getObject().isEmpty();
}
private boolean violationsEmpty() {
return EvaluatedTriggerGroupDto.isEmpty(policyViolationsModel.getObject());
}
private void initButtons(Form mainForm) {
AjaxButton cancel = new AjaxButton(ID_CONTINUE_EDITING, createStringResource("PagePreviewChanges.button.continueEditing")) {
@Override
public void onClick(AjaxRequestTarget target) {
cancelPerformed(target);
}
};
mainForm.add(cancel);
AjaxButton save = new AjaxButton(ID_SAVE, createStringResource("PagePreviewChanges.button.save")) {
@Override
public void onClick(AjaxRequestTarget target) {
savePerformed(target);
}
};
save.add(new EnableBehaviour(() -> violationsEmpty()));
mainForm.add(save);
}
private void cancelPerformed(AjaxRequestTarget target) {
redirectBack();
}
private void savePerformed(AjaxRequestTarget target) {
Breadcrumb bc = redirectBack();
if (bc instanceof BreadcrumbPageInstance) {
BreadcrumbPageInstance bcpi = (BreadcrumbPageInstance) bc;
WebPage page = bcpi.getPage();
if (page instanceof PageAdminObjectDetails) {
((PageAdminObjectDetails) page).setSaveOnConfigure(true);
} else {
error("Couldn't save changes - unexpected referring page: " + page);
}
} else {
error("Couldn't save changes - no instance for referring page; breadcrumb is " + bc);
}
}
}
| Fix for MID-4252 (perhaps temporary)
| gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/show/PagePreviewChanges.java | Fix for MID-4252 (perhaps temporary) | <ide><path>ui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/show/PagePreviewChanges.java
<ide> savePerformed(target);
<ide> }
<ide> };
<del> save.add(new EnableBehaviour(() -> violationsEmpty()));
<add> //save.add(new EnableBehaviour(() -> violationsEmpty())); // does not work as expected (MID-4252)
<add> save.add(new VisibleBehaviour(() -> violationsEmpty())); // so hiding the button altogether
<ide> mainForm.add(save);
<ide> }
<ide> |
|
Java | apache-2.0 | 1b1254d8484e5dbf0ecff1445bd835d57197c841 | 0 | bkirschn/sakai,duke-compsci290-spring2016/sakai,kingmook/sakai,hackbuteer59/sakai,buckett/sakai-gitflow,kwedoff1/sakai,rodriguezdevera/sakai,willkara/sakai,clhedrick/sakai,whumph/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,clhedrick/sakai,wfuedu/sakai,wfuedu/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,clhedrick/sakai,colczr/sakai,kwedoff1/sakai,noondaysun/sakai,conder/sakai,kingmook/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,bkirschn/sakai,wfuedu/sakai,Fudan-University/sakai,zqian/sakai,introp-software/sakai,puramshetty/sakai,udayg/sakai,surya-janani/sakai,noondaysun/sakai,OpenCollabZA/sakai,ktakacs/sakai,kwedoff1/sakai,noondaysun/sakai,colczr/sakai,kwedoff1/sakai,kingmook/sakai,duke-compsci290-spring2016/sakai,bzhouduke123/sakai,ktakacs/sakai,ktakacs/sakai,lorenamgUMU/sakai,whumph/sakai,joserabal/sakai,conder/sakai,ouit0408/sakai,udayg/sakai,liubo404/sakai,puramshetty/sakai,Fudan-University/sakai,colczr/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,clhedrick/sakai,bzhouduke123/sakai,kingmook/sakai,whumph/sakai,liubo404/sakai,willkara/sakai,hackbuteer59/sakai,conder/sakai,surya-janani/sakai,conder/sakai,ouit0408/sakai,conder/sakai,wfuedu/sakai,kwedoff1/sakai,bkirschn/sakai,colczr/sakai,liubo404/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,rodriguezdevera/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,noondaysun/sakai,pushyamig/sakai,colczr/sakai,wfuedu/sakai,zqian/sakai,duke-compsci290-spring2016/sakai,udayg/sakai,pushyamig/sakai,hackbuteer59/sakai,udayg/sakai,kingmook/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,lorenamgUMU/sakai,noondaysun/sakai,pushyamig/sakai,colczr/sakai,surya-janani/sakai,frasese/sakai,pushyamig/sakai,conder/sakai,frasese/sakai,buckett/sakai-gitflow,introp-software/sakai,Fudan-University/sakai,Fudan-University/sakai,bzhouduke123/sakai,ktakacs/sakai,willkara/sakai,kwedoff1/sakai,liubo404/sakai,whumph/sakai,bkirschn/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,OpenCollabZA/sakai,puramshetty/sakai,zqian/sakai,joserabal/sakai,colczr/sakai,introp-software/sakai,liubo404/sakai,conder/sakai,kingmook/sakai,willkara/sakai,noondaysun/sakai,rodriguezdevera/sakai,hackbuteer59/sakai,willkara/sakai,noondaysun/sakai,joserabal/sakai,udayg/sakai,tl-its-umich-edu/sakai,rodriguezdevera/sakai,surya-janani/sakai,Fudan-University/sakai,introp-software/sakai,OpenCollabZA/sakai,wfuedu/sakai,lorenamgUMU/sakai,hackbuteer59/sakai,liubo404/sakai,whumph/sakai,surya-janani/sakai,conder/sakai,bkirschn/sakai,hackbuteer59/sakai,bkirschn/sakai,rodriguezdevera/sakai,liubo404/sakai,pushyamig/sakai,willkara/sakai,ktakacs/sakai,zqian/sakai,tl-its-umich-edu/sakai,joserabal/sakai,liubo404/sakai,joserabal/sakai,ktakacs/sakai,introp-software/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,frasese/sakai,surya-janani/sakai,whumph/sakai,zqian/sakai,puramshetty/sakai,noondaysun/sakai,frasese/sakai,OpenCollabZA/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,willkara/sakai,wfuedu/sakai,clhedrick/sakai,kwedoff1/sakai,pushyamig/sakai,clhedrick/sakai,wfuedu/sakai,ouit0408/sakai,whumph/sakai,Fudan-University/sakai,clhedrick/sakai,bkirschn/sakai,puramshetty/sakai,Fudan-University/sakai,introp-software/sakai,rodriguezdevera/sakai,introp-software/sakai,clhedrick/sakai,hackbuteer59/sakai,whumph/sakai,joserabal/sakai,joserabal/sakai,Fudan-University/sakai,hackbuteer59/sakai,frasese/sakai,lorenamgUMU/sakai,frasese/sakai,lorenamgUMU/sakai,ouit0408/sakai,udayg/sakai,udayg/sakai,puramshetty/sakai,zqian/sakai,frasese/sakai,udayg/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,ouit0408/sakai,bkirschn/sakai,puramshetty/sakai,ouit0408/sakai,surya-janani/sakai,lorenamgUMU/sakai,buckett/sakai-gitflow,ktakacs/sakai,joserabal/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,introp-software/sakai,ouit0408/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,zqian/sakai,bzhouduke123/sakai,surya-janani/sakai,OpenCollabZA/sakai,colczr/sakai,kingmook/sakai,willkara/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,zqian/sakai,kingmook/sakai,kwedoff1/sakai,pushyamig/sakai | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-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.sakaiproject.calendar.tool;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.Vector;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEdit;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarEventEdit;
import org.sakaiproject.calendar.api.CalendarEventVector;
import org.sakaiproject.calendar.api.ExternalSubscription;
import org.sakaiproject.calendar.api.RecurrenceRule;
import org.sakaiproject.calendar.cover.CalendarImporterService;
import org.sakaiproject.calendar.cover.CalendarService;
import org.sakaiproject.calendar.cover.ExternalCalendarSubscriptionService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.VelocityPortletStateAction;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.content.cover.ContentTypeImageService;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.entitybroker.EntityBroker;
import org.sakaiproject.entitybroker.entityprovider.extension.ActionReturn;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.ImportException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.api.TimeRange;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.CalendarChannelReferenceMaker;
import org.sakaiproject.util.CalendarReferenceToChannelConverter;
import org.sakaiproject.util.CalendarUtil;
import org.sakaiproject.util.EntryProvider;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.MergedList;
import org.sakaiproject.util.MergedListEntryProviderFixedListWrapper;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.Validator;
/**
* The schedule tool.
*/
public class CalendarAction
extends VelocityPortletStateAction
{
/**
*
*/
private static final long serialVersionUID = -8571818334710261359L;
/** Our logger. */
private static Log M_log = LogFactory.getLog(CalendarAction.class);
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("calendar");
// configuration properties (initialized in initState()
Properties configProps = null;
private static final String ALERT_MSG_KEY = "alertMessage";
private static final String CONFIRM_IMPORT_WIZARD_STATE = "CONFIRM_IMPORT";
private static final String WIZARD_IMPORT_FILE = "importFile";
private static final String GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE = "GENERIC_SELECT_FILE";
private static final String OTHER_SELECT_FILE_IMPORT_WIZARD_STATE = "OTHER_SELECT_FILE";
private static final String ICAL_SELECT_FILE_IMPORT_WIZARD_STATE = "ICAL_SELECT_FILE";
private static final String WIZARD_IMPORT_TYPE = "importType";
private static final String SELECT_TYPE_IMPORT_WIZARD_STATE = "SELECT_TYPE";
private static final String IMPORT_WIZARD_SELECT_TYPE_STATE = SELECT_TYPE_IMPORT_WIZARD_STATE;
private static final String STATE_SCHEDULE_IMPORT = "scheduleImport";
private static final String CALENDAR_INIT_PARAMETER = "calendar";
private static final int HOURS_PER_DAY = 24;
private static final int NUMBER_HOURS_PER_PAGE_FOR_WEEK_VIEW = 10;
private static final int FIRST_PAGE_START_HOUR = 0;
private static final int SECOND_PAGE_START_HOUR = 8;
private static final int THIRD_PAGE_START_HOUR = 14;
private static final String STATE_YEAR = "calYear";
private static final String STATE_MONTH = "calMonth";
private static final String STATE_DAY = "calDay";
private static final String STATE_REVISE = "revise";
private static final String STATE_SET_FREQUENCY = "setFrequency";
private static final String FREQUENCY_SELECT = "frequencySelect";
private static final String TEMP_FREQ_SELECT = "tempFrequencySelect";
private static final String FREQ_ONCE = "once";
private static final String DEFAULT_FREQ = FREQ_ONCE;
private static final String SSTATE__RECURRING_RULE = "rule";
private static final String STATE_BEFORE_SET_RECURRENCE = "state_before_set_recurrence";
private final static String TIME_FILTER_OPTION_VAR = "timeFilterOption";
private final static String TIME_FILTER_SETTING_CUSTOM_START_DATE_VAR = "customStartDate";
private final static String TIME_FILTER_SETTING_CUSTOM_END_DATE_VAR = "customEndDate";
private final static String TIME_FILTER_SETTING_CUSTOM_START_YEAR = "customStartYear";
private final static String TIME_FILTER_SETTING_CUSTOM_END_YEAR = "customEndYear";
private final static String TIME_FILTER_SETTING_CUSTOM_START_MONTH = "customStartMonth";
private final static String TIME_FILTER_SETTING_CUSTOM_END_MONTH = "customEndMonth";
private final static String TIME_FILTER_SETTING_CUSTOM_START_DAY = "customStartDay";
private final static String TIME_FILTER_SETTING_CUSTOM_END_DAY = "customEndDay";
private static final String FORM_ALIAS = "alias";
private static final String FORM_ICAL_ENABLE = "icalEnable";
/** The attachments from assignment */
private static final String ATTACHMENTS = "Assignment.attachments";
/** state selected view */
private static final String STATE_SELECTED_VIEW = "state_selected_view";
/** DELIMITER used to separate the list of custom fields for this calendar. */
private final static String ADDFIELDS_DELIMITER = "_,_";
protected final static String STATE_INITED = "calendar.state.inited";
/** for sorting in list view */
private static final String STATE_DATE_SORT_DSC = "dateSortedDsc";
// for group/section awareness
private final static String STATE_SCHEDULE_TO = "scheduleTo";
private final static String STATE_SCHEDULE_TO_GROUPS = "scheduleToGroups";
private static final String STATE_SELECTED_GROUPS_FILTER = "groups_filters";
private ContentHostingService contentHostingService;
private EntityBroker entityBroker;
// tbd fix shared definition from org.sakaiproject.assignment.api.AssignmentEntityProvider
private final static String ASSN_ENTITY_ID = "assignment";
private final static String ASSN_ENTITY_ACTION = "deepLink";
private final static String ASSN_ENTITY_PREFIX = EntityReference.SEPARATOR+ASSN_ENTITY_ID+EntityReference.SEPARATOR+ASSN_ENTITY_ACTION+EntityReference.SEPARATOR;
private NumberFormat monthFormat = null;
/**
* Converts a string that is used to store additional attribute fields to an array of strings.
*/
private String[] fieldStringToArray(String addfields_str, String delimiter)
{
String [] fields = addfields_str.split(delimiter);
List destStringList = new ArrayList();
// Don't copy empty fields.
for ( int i=0; i < fields.length; i++)
{
if ( fields[i].length() > 0 )
{
destStringList.add(fields[i]);
}
}
return (String[]) destStringList.toArray(new String[destStringList.size()]);
}
/**
* Enable or disable the observer
* @param enable if true, the observer is enabled, if false, it is disabled
*/
protected void enableObserver(SessionState sstate, boolean enable)
{
if (enable)
{
enableObservers(sstate);
}
else
{
disableObservers(sstate);
}
}
// myYear class
public class MyYear
{
private MyMonth[][] yearArray;
private int year;
private MyMonth m;
public MyYear()
{
yearArray = new MyMonth[4][3];
m = null;
year = 0;
}
public void setMonth(MyMonth m, int x, int y)
{
yearArray[x][y] = m;
}
public MyMonth getMonth(int x, int y)
{
m = yearArray[x][y];
return (m);
}
public void setYear(int y)
{
year = y;
}
public int getYear()
{
return year;
}
}// myYear class
// my week
public class MyWeek
{
private MyDate[] week;
private int weekOfMonth;
public MyWeek()
{
week = new MyDate[7];
weekOfMonth = 0;
}
public void setWeek(int i, MyDate date)
{
week[i] = date;
}
public MyDate getWeek(int i)
{
return week[i];
}
public String getWeekRange()
{
String range = null;
range = week[0].getTodayDate() + " "+ "-" + " " + week[6].getTodayDate();
return range;
}
public void setWeekOfMonth(int w)
{
weekOfMonth = w;
}
public int getWeekOfMonth()
{
return weekOfMonth+1;
}
}
// myMonth class
public class MyMonth
{
private MyDate[][] monthArray;
private MyDate result;
private String monthName;
private int month;
private int row;
private int numberOfDaysInMonth;
public MyMonth()
{
result = null;
monthArray = new MyDate[6][7];
month = 0;
row = 0;
numberOfDaysInMonth=0;
}
public void setRow(int r)
{
row = r;
}
public int getRow()
{
return row;
}
public void setNumberOfDaysInMonth(int daysInMonth)
{
numberOfDaysInMonth = daysInMonth;
}
public int getNumberOfDaysInMonth()
{
return numberOfDaysInMonth;
}
public void setDay(MyDate d,int x, int y)
{
monthArray[x][y] = d;
}
public MyDate getDay(int x,int y)
{
result = monthArray[x][y];
return (result);
}
public void setMonthName(String name)
{
monthName = name;
}
public String getMonthName()
{
return monthName;
}
public void setMonth(int m)
{
month = m;
}
public int getMonth()
{
return month;
}
}// myMonth
// myDay class
public class MyDay
{
private String m_data; // data will have the days in the month
private String m_attachment_data; // data need to be displayed and attached, currently
// this si a string and it can be any structure in the future.
private int m_flag; // 0 if it is not a current date , 1 if it is a current date
private int day;
private int year;
private int month;
private String dayName; // name for each day
private String todayDate;
public MyDay()
{
m_data = "";
m_flag = 0;
m_attachment_data = "";
day = 0;
dayName = "";
todayDate = "";
}
public void setDay(int d)
{
day = d;
}
public int getDay()
{
return day;
}
public void setFlag(int flag)
{
m_flag = flag;
}
public void setData(String data)
{
m_data = data;
}
public int getFlag()
{
return m_flag;
}
public String getData()
{
return(m_data);
}
public void setAttachment(String data)
{
m_attachment_data = data;
}
public String getAttachment()
{
return(m_attachment_data);
}
public void setDayName(String dname)
{
dayName = dname;
}
public String getDayName()
{
return dayName;
}
public void setTodayDate(String date)
{
todayDate = date;
}
public String getTodayDate()
{
return todayDate;
}
public void setYear(int y)
{
year = y;
}
public int getYear()
{
return year;
}
public void setMonth(int m)
{
month = m;
}
public int getMonth()
{
return month;
}
}// myDay class
public class EventClass
{
private String displayName;
private long firstTime;
private String eventId;
public EventClass()
{
displayName = "";
firstTime = 0;
}
public void setDisplayName(String name)
{
displayName = name;
}
public void setFirstTime(long time)
{
firstTime = time;
}
public String getDisplayName()
{
return displayName;
}
public long getfirstTime()
{
return firstTime;
}
public void setId(String id)
{
eventId = id;
}
public String getId()
{
return eventId;
}
}
public class EventDisplayClass
{
private CalendarEvent calendareventobj;
private boolean eventConflict;
private int eventPosition;
public EventDisplayClass()
{
eventConflict = false;
calendareventobj = null;
eventPosition = 0;
}
public void setEvent(CalendarEvent ce, boolean eventconf, int pos)
{
eventConflict = eventconf;
calendareventobj = ce;
eventPosition = pos;
}
public void setFlag(boolean conflict)
{
eventConflict = conflict;
}
public void setPosition(int position)
{
eventPosition = position;
}
public int getPosition()
{
return eventPosition;
}
public CalendarEvent getEvent()
{
return calendareventobj;
}
public boolean getFlag()
{
return eventConflict;
}
}
public class MyDate
{
private MyDay day = null;
private MyMonth month = null;
private MyYear year = null;
private String dayName = "";
private Iterator iteratorObj = null;
private int flag = -1;
private Vector eVector;
public MyDate()
{
day = new MyDay();
month = new MyMonth();
year = new MyYear();
}
public void setTodayDate(int m, int d, int y)
{
day.setDay(d);
month.setMonth(m);
year.setYear(y);
}
public void setNumberOfDaysInMonth(int daysInMonth)
{
month.setNumberOfDaysInMonth(daysInMonth);
}
public int getNumberOfDaysInMonth()
{
return month.getNumberOfDaysInMonth();
}
public String getTodayDate()
{
DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT);
return f.format(new Date(year.getYear(), month.getMonth(), day.getDay()));
}
public void setFlag(int i)
{
flag = i;
}
public int getFlag()
{
return flag;
}
public void setDayName(String name)
{
dayName = name;
}
public void setNameOfMonth(String name)
{
month.setMonthName(name);
}
public String getDayName()
{
return dayName;
}
public int getDay()
{
return day.getDay();
}
public int getMonth()
{
return month.getMonth();
}
public String getNameOfMonth()
{
return month.getMonthName();
}
public int getYear()
{
return year.getYear();
}
public void setEventBerWeek(Vector eventVector)
{
eVector = eventVector;
}
public void setEventBerDay(Vector eventVector)
{
eVector = eventVector;
}
public Vector getEventsBerDay(int index)
{
Vector dayVector = new Vector();
if (eVector != null)
dayVector = (Vector)eVector.get(index);
if (dayVector == null)
dayVector = new Vector();
return dayVector;
}
public Vector getEventsBerWeek(int index)
{
Vector dayVector = new Vector();
if (eVector != null)
dayVector = (Vector)eVector.get(index);
if (dayVector == null)
dayVector = new Vector();
return dayVector;
}
public void setEvents(Iterator t)
{
iteratorObj = t;
}
public Vector getEvents()
{
Vector vectorObj = new Vector();
int i = 0;
if (iteratorObj!=null)
{
while(iteratorObj.hasNext())
{
vectorObj.add(i,iteratorObj.next());
i++;
}
}
return vectorObj;
}
}
public class Helper
{
private int numberOfActivity =0;
public int getduration(long x, int b)
{
Long l = Long.valueOf(x);
int v = l.intValue()/3600000;
return v;
}
public int getFractionIn(long x,int b)
{
Long ll = Long.valueOf(x);
int y = (ll.intValue()-(b*3600000));
int m = (y/60000);
return m;
}
public CalendarEvent getActivity(Vector mm)
{
int size = mm.size();
numberOfActivity = size;
CalendarEvent activityEvent,event=null;
if(size>0)
{
activityEvent = (CalendarEvent)mm.elementAt(0);
long temp = activityEvent.getRange().duration();
for(int i =0; i<size;i++)
{
activityEvent = (CalendarEvent)mm.elementAt(i);
if(temp<activityEvent.getRange().duration())
{
temp = activityEvent.getRange().duration();
event = activityEvent;
}
}
}
else
event = null;
return event;
}
public int getNumberOfActivity()
{
return numberOfActivity;
}
public int getInt(long x)
{
Long temp = Long.valueOf(x);
return(temp.intValue());
}
}
/**
* An inner class that can be initiated to perform text formatting
*/
public class CalendarFormattedText
{
// constructor
public CalendarFormattedText()
{
}
/**
* Use of FormattedText object's trimFormattedText function.
* @param formattedText The formatted text to trim
* @param maxNumOfChars The maximum number of displayed characters in the returned trimmed formatted text.
* @return String A String to hold the trimmed formatted text
*/
public String trimFormattedText(String formattedText, int maxNumOfChars)
{
StringBuilder sb = new StringBuilder();
FormattedText.trimFormattedText(formattedText, maxNumOfChars, sb);
return sb.toString();
}
}
/**
* Given a current date via the calendarUtil paramter, returns a TimeRange for the week.
*/
public TimeRange getWeekTimeRange(
CalendarUtil calendarUtil)
{
int dayofweek = 0;
dayofweek = calendarUtil.getDay_Of_Week(true)-1;
int tempCurrentYear = calendarUtil.getYear();
int tempCurrentMonth = calendarUtil.getMonthInteger();
int tempCurrentDay = calendarUtil.getDayOfMonth();
calendarUtil.setPrevDate(dayofweek);
Time startTime = TimeService.newTimeLocal(calendarUtil.getYear(),calendarUtil.getMonthInteger(),calendarUtil.getDayOfMonth(),00,00,00,000);
calendarUtil.setDay(tempCurrentYear,tempCurrentMonth,tempCurrentDay);
dayofweek = calendarUtil.getDay_Of_Week(true);
if (dayofweek< 7)
{
for(int i = dayofweek; i<=6;i++)
{
calendarUtil.nextDate();
}
}
Time endTime = TimeService.newTimeLocal(calendarUtil.getYear(),calendarUtil.getMonthInteger(),calendarUtil.getDayOfMonth(),23,59,59,000);
return TimeService.newTimeRange(startTime,endTime,true,true);
} // etWeekTimeRange
/**
* Given a current date via the calendarUtil paramter, returns a TimeRange for the month.
*/
public TimeRange getMonthTimeRange(CalendarUtil calendarUtil)
{
int dayofweek = 0;
calendarUtil.setDay(calendarUtil.getYear(), calendarUtil.getMonthInteger(), 1);
int numberOfCurrentDays = calendarUtil.getNumberOfDays();
int tempCurrentMonth = calendarUtil.getMonthInteger();
int tempCurrentYear = calendarUtil.getYear();
// get the index of the first day in the month
int firstDay_of_Month = calendarUtil.getDay_Of_Week(true) - 1;
// Construct the time range to get all the days in the current month plus the days in the first week in the previous month and
// the days in the last week from the last month
// get the days in the first week that exists in the prev month
calendarUtil.setPrevDate(firstDay_of_Month);
Time startTime = TimeService.newTimeLocal(calendarUtil.getYear(),calendarUtil.getMonthInteger(),calendarUtil.getDayOfMonth(),00,00,00,000);
// set the date object to the current month and last day in the current month
calendarUtil.setDay(tempCurrentYear,tempCurrentMonth,numberOfCurrentDays);
// get the index of the last day in the current month
dayofweek = calendarUtil.getDay_Of_Week(true);
// move the date object to the last day in the last week of the current month , this day will be one of those days in the
// following month
if (dayofweek < 7)
{
for(int i = dayofweek; i<=6;i++)
{
calendarUtil.nextDate();
}
}
Time endTime = TimeService.newTimeLocal(calendarUtil.getYear(),calendarUtil.getMonthInteger(),calendarUtil.getDayOfMonth(),23,59,59,000);
return TimeService.newTimeRange(startTime,endTime,true,true);
}
/**
* Given a current date in the year, month, and day parameters, returns a TimeRange for the day.
*/
public TimeRange getDayTimeRange(
int year,
int month,
int day)
{
Time startTime = TimeService.newTimeLocal(year,month,day,00,00,00,000);
Time endTime = TimeService.newTimeLocal(year,month,day,23,59,59,000);
return TimeService.newTimeRange(startTime,endTime,true,true);
}
/**
* This class controls the page that allows the user to customize which
* calendars will be merged with the current group.
*/
public class MergePage
{
private final String mergeScheduleButtonHandler = "doMerge";
// Name used in the velocity template for the list of merged/non-merged calendars
private final String mergedCalendarsCollection = "mergedCalendarsCollection";
public MergePage()
{
super();
}
/**
* Build the context for showing merged view
*/
public void buildContext(
VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state,
SessionState sstate)
{
// load all calendar channels (either primary or merged calendars)
MergedList calendarList =
loadChannels( state.getPrimaryCalendarReference(),
portlet.getPortletConfig().getInitParameter(PORTLET_CONFIG_PARM_MERGED_CALENDARS),
new EntryProvider() );
// Place this object in the context so that the velocity template
// can get at it.
context.put(mergedCalendarsCollection, calendarList);
context.put("tlang",rb);
context.put("config",configProps);
sstate.setAttribute(
CalendarAction.SSTATE_ATTRIBUTE_MERGED_CALENDARS,
calendarList);
}
/**
* Action is used when the docancel is requested when the user click on cancel in the new view
*/
public void doCancel(
RunData data,
Context context,
CalendarActionState state,
SessionState sstate)
{
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
// cancel the options, release the site lock, cleanup
cancelOptions();
// Clear the previous state so that we don't get confused elsewhere.
state.setPrevState("");
sstate.removeAttribute(STATE_MODE);
enableObserver(sstate, true);
} // doCancel
/**
* Handle the "Merge" button on the toolbar
*/
public void doMerge(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
// TODO: really?
// get a lock on the site and setup for options work
doOptions(runData, context);
// if we didn't end up in options mode, bail out
if (!MODE_OPTIONS.equals(sstate.getAttribute(STATE_MODE))) return;
// Disable the observer
enableObserver(sstate, false);
// Save the previous state so that we can get to it after we're done with the options mode.
// if the previous state is Description, we need to remember one more step back
// coz there is a back link in description view
if ((state.getState()).equalsIgnoreCase("description"))
{
state.setPrevState(state.getReturnState() + "!!!fromDescription");
}
else
{
state.setPrevState(state.getState());
}
state.setState(CalendarAction.STATE_MERGE_CALENDARS);
} // doMerge
/**
* Handles the user clicking on the save button on the page to specify which
* calendars will be merged into the present schedule.
*/
public void doUpdate(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
// Get the merged calendar list out of our session state
MergedList mergedCalendarList =
(MergedList) sstate.getAttribute(
CalendarAction.SSTATE_ATTRIBUTE_MERGED_CALENDARS);
if (mergedCalendarList != null)
{
// Get the information from the run data and load it into
// our calendar list that we have in the session state.
mergedCalendarList.loadFromRunData(runData.getParameters());
}
// update the tool config
Placement placement = ToolManager.getCurrentPlacement();
// myWorkspace is special (a null mergedCalendar list defaults to all channels),
// so we add the primary calendar here to indicate no other channels are wanted
if (mergedCalendarList != null && isOnWorkspaceTab())
{
String channelRef = mergedCalendarList.getDelimitedChannelReferenceString();
if (StringUtils.trimToNull(channelRef) == null )
channelRef = state.getPrimaryCalendarReference();
placement.getPlacementConfig().setProperty(
PORTLET_CONFIG_PARM_MERGED_CALENDARS, channelRef );
}
// Otherwise, just set the list as specified
else if (mergedCalendarList != null && !isOnWorkspaceTab())
{
placement.getPlacementConfig().setProperty(
PORTLET_CONFIG_PARM_MERGED_CALENDARS,
mergedCalendarList.getDelimitedChannelReferenceString());
}
// handle the case of no merge calendars
else
{
placement.getPlacementConfig().remove(PORTLET_CONFIG_PARM_MERGED_CALENDARS);
}
// commit the change
saveOptions();
// Turn the observer back on.
enableObserver(sstate, true);
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
// Clear the previous state so that we don't get confused elsewhere.
state.setPrevState("");
sstate.removeAttribute(STATE_MODE);
} // doUpdate
/* (non-Javadoc)
* @see org.chefproject.actions.schedulePages.SchedulePage#getMenuHandlerID()
*/
public String getButtonHandlerID()
{
return mergeScheduleButtonHandler;
}
/* (non-Javadoc)
* @see org.chefproject.actions.schedulePages.SchedulePage#getMenuText()
*/
public String getButtonText()
{
return rb.getString("java.merge");
}
}
/**
* This class controls the page that allows the user to add arbitrary
* attributes to the attribute list for the primary calendar that
* corresponds to the current group.
*/
public class CustomizeCalendarPage
{
//This is the session attribute name to store init and current addFields list
// Name used in the velocity template for the list of calendar addFields
private final static String ADDFIELDS_CALENDARS_COLLECTION = "addFieldsCalendarsCollection";
private final static String ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY = "addFieldsCalendarsCollectionIsEmpty";
private final static String OPTIONS_BUTTON_HANDLER = "doCustomize";
public CustomizeCalendarPage()
{
super();
}
/**
* Build the context for addfields calendar (Options menu)
*/
public void buildContext(
VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state,
SessionState sstate)
{
String[] addFieldsCalendarArray = null;
// Get a list of current calendar addFields. This is a comma-delimited list.
if (sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE).toString().equals(CalendarAction.PAGE_MAIN)) //when the 'Options' button click
{
//when the 'Options' button click
Calendar calendarObj = null;
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch (IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.warn(".buildCustomizeContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.warn(".buildCustomizeContext(): " + e);
return;
}
// Get a current list of add fields. This is a comma-delimited string.
String addfieldsCalendars = calendarObj.getEventFields();
if (addfieldsCalendars != null)
{
addFieldsCalendarArray =
fieldStringToArray(
addfieldsCalendars,
ADDFIELDS_DELIMITER);
}
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS_INIT, addfieldsCalendars);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, addfieldsCalendars);
context.put("delFields", (List)sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS));
sstate.removeAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS_CONFIRM, "N");
state.setDelfieldAlertOff(true);
}
else //after the 'Options' button click
{
String addFieldsCollection = (String) sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS);
if (addFieldsCollection != null)
addFieldsCalendarArray = fieldStringToArray(addFieldsCollection, ADDFIELDS_DELIMITER);
}
// Place this object in the context so that the velocity template
// can get at it.
context.put(ADDFIELDS_CALENDARS_COLLECTION, addFieldsCalendarArray);
context.put("tlang",rb);
context.put("config",configProps);
if (addFieldsCalendarArray == null)
context.put(ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY, Boolean.valueOf(true));
else
context.put(ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY, Boolean.valueOf(false));
} //buildCustomizeCalendarContext
/**
* Handles the click on the page to add a field to events that will
* be added to the calendar. Changes aren't complete until the user
* commits changes with a save.
*/
public void doAddfield(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
String addFields = (String) sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS);
String [] addFieldsCalendarList = null;
if (addFields != null)
addFieldsCalendarList = fieldStringToArray(addFields,ADDFIELDS_DELIMITER);
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
enableObserver(sstate, true);
String addField = "";
addField = runData.getParameters().getString("textfield").trim();
String dupAddfield = "N";
//prevent entry of some characters (can cause problem)
addField = addField.replaceAll(" "," ");
addField = addField.replaceAll("'","");
addField = addField.replaceAll("\"","");
if (addField.length()==0)
{
addAlert(sstate, rb.getString("java.alert.youneed"));
}
else
{
if (addFieldsCalendarList != null)
{
for (int i=0; i < addFieldsCalendarList.length; i++)
{
if (addField.toUpperCase().equals(addFieldsCalendarList[i].toUpperCase()))
{
addAlert(sstate, rb.getString("java.alert.theadd"));
dupAddfield = "Y";
i = addFieldsCalendarList.length + 1;
}
}
if (dupAddfield.equals("N"))
addFieldsCalendarList = fieldStringToArray(addFields+ADDFIELDS_DELIMITER+addField, ADDFIELDS_DELIMITER);
}
else
{
String [] initString = new String[1];
initString[0] = addField;
addFieldsCalendarList = initString;
}
if (dupAddfield.equals("N"))
{
if (addFields != null)
addFields = addFields + ADDFIELDS_DELIMITER + addField;
else
addFields = addField;
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, addFields);
}
}
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, CalendarAction.PAGE_ADDFIELDS);
}
/**
* Handles a click on the cancel button in the page that allows the
* user to add/remove events to/from events that will be added to
* the calendar.
*/
public void doCancel(
RunData data,
Context context,
CalendarActionState state,
SessionState sstate)
{
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS_INIT));
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, CalendarAction.PAGE_MAIN);
enableObserver(sstate, true);
} // doCancel
/**
* This initiates the page where the user can add/remove additional
* properties to/from events that will be added to the calendar.
*/
public void doCustomize(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
// Disable the observer
enableObserver(sstate, false);
// Save the previous state so that we can get to it after we're done with the options mode.
// if the previous state is Description, we need to remember one more step back
// coz there is a back link in description view
if ((state.getState()).equalsIgnoreCase("description"))
{
state.setPrevState(state.getReturnState() + "!!!fromDescription");
}
else
{
state.setPrevState(state.getState());
}
state.setState(CalendarAction.STATE_CUSTOMIZE_CALENDAR);
}
/**
* Handles the click on the page to remove a field from events in the
* calendar. Changes aren't complete until the user commits changes
* with a save.
*/
public void doDeletefield(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
ParameterParser params = runData.getParameters();
String addFields = (String) sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS);
String [] addFieldsCalendarList = null, newAddFieldsCalendarList = null;
List delFields = new Vector();
int nextNewFieldsIndex = 0;
if (addFields != null)
{
addFieldsCalendarList = fieldStringToArray(addFields,ADDFIELDS_DELIMITER);
// The longest the new array can possibly be is the current size of the list.
newAddFieldsCalendarList = new String[addFieldsCalendarList.length];
for (int i=0; i< addFieldsCalendarList.length; i++)
{
String fieldName = params.getString(addFieldsCalendarList[i]);
// If a value is present, then that means that the user has checked
// the box for the field to be removed. Don't add it to the
// new list of field names. If it is not present, then add it
// to the new list of field names.
if ( fieldName == null || fieldName.length() == 0 )
{
newAddFieldsCalendarList[nextNewFieldsIndex++] = addFieldsCalendarList[i];
}
else
{
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS_CONFIRM, "Y");
delFields.add(addFieldsCalendarList[i]);
}
}
addFields = arrayToString(newAddFieldsCalendarList, ADDFIELDS_DELIMITER);
}
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
enableObserver(sstate, true);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, addFields);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS, delFields);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, CalendarAction.PAGE_ADDFIELDS);
}
/**
* Handles the user clicking on the save button on the page to add or
* remove additional attributes for all calendar events.
*/
public void doUpdate(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
if (sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS_CONFIRM).equals("Y") && state.getDelfieldAlertOff() )
{
String errorCode = rb.getString("java.alert.areyou");
List delFields = (List) sstate.getAttribute(SSTATE_ATTRIBUTE_DELFIELDS);
errorCode = errorCode.concat((String)(delFields.get(0)));
for(int i=1; i<delFields.size(); i++)
{
errorCode = errorCode.concat(", " + (String)(delFields.get(i)));
}
errorCode = errorCode.concat(rb.getString("java.alert.ifyes"));
addAlert(sstate, errorCode);
state.setDelfieldAlertOff(false);
}
else
{
state.setDelfieldAlertOff(true);
String addfields = (String) sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS);
while (addfields.startsWith(ADDFIELDS_DELIMITER))
{
addfields = addfields.substring(ADDFIELDS_DELIMITER.length());
}
String calId = state.getPrimaryCalendarReference();
try
{
CalendarEdit edit = CalendarService.editCalendar(calId);
edit.setEventFields(addfields);
CalendarService.commitCalendar(edit);
}
catch (IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereisno"));
M_log.debug(".doUpdate customize calendar IdUnusedException"+e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdonthave"));
M_log.debug(".doUpdate customize calendar "+e);
return;
}
catch (InUseException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.someone"));
M_log.debug(".doUpdate() for CustomizeCalendar: " + e);
return;
}
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, addfields);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, CalendarAction.PAGE_MAIN);
}
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
enableObserver(sstate, true);
} // doUpdate
/* (non-Javadoc)
* @see org.chefproject.actions.schedulePages.SchedulePage#getMenuHandlerID()
*/
public String getButtonHandlerID()
{
return OPTIONS_BUTTON_HANDLER;
}
/* (non-Javadoc)
* @see org.chefproject.actions.schedulePages.SchedulePage#getMenuText()
*/
public String getButtonText()
{
return rb.getString("java.fields");
}
/**
* Loads additional fields information from the calendar object passed
* as a parameter and loads them into the context object for the Velocity
* template.
*/
public void loadAdditionalFieldsIntoContextFromCalendar(
Calendar calendarObj,
Context context)
{
// Get a current list of add fields. This is a ADDFIELDS_DELIMITER string.
String addfieldsCalendars = calendarObj.getEventFields();
String[] addfieldsCalendarArray = null;
if (addfieldsCalendars != null)
{
addfieldsCalendarArray =
fieldStringToArray(
addfieldsCalendars,
ADDFIELDS_DELIMITER);
}
// Place this object in the context so that the velocity template
// can get at it.
context.put(ADDFIELDS_CALENDARS_COLLECTION, addfieldsCalendarArray);
context.put("tlang",rb);
context.put("config",configProps);
if (addfieldsCalendarArray == null)
context.put(ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY, Boolean.valueOf(true));
else
context.put(ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY, Boolean.valueOf(false));
}
/**
* Loads additional fields from the run data into a provided map object.
*/
public void loadAdditionalFieldsMapFromRunData(
RunData rundata,
Map addfieldsMap,
Calendar calendarObj)
{
String addfields_str = calendarObj.getEventFields();
if ( addfields_str != null && addfields_str.trim().length() != 0)
{
String [] addfields = fieldStringToArray(addfields_str, ADDFIELDS_DELIMITER);
String eachfield;
for (int i=0; i < addfields.length; i++)
{
eachfield = addfields[i];
addfieldsMap.put(eachfield, rundata.getParameters().getString(eachfield));
}
}
}
}
/**
* This class controls the page that allows the user to configure
* external calendar subscriptions.
*/
public class CalendarSubscriptionsPage
{
private final String institutionalSubscriptionsCollection = "institutionalSubscriptionsCollection";
private final String institutionalSubscriptionsAvailable = "institutionalSubscriptionsAvailable";
private final String userSubscriptionsCollection = "userSubscriptionsCollection";
private final String REF_DELIMITER = ExternalCalendarSubscriptionService.SUBS_REF_DELIMITER;
private final String NAME_DELIMITER = ExternalCalendarSubscriptionService.SUBS_NAME_DELIMITER;
public CalendarSubscriptionsPage()
{
super();
}
/**
* Build the context
*/
public void buildContext(VelocityPortlet portlet, Context context,
RunData runData, CalendarActionState state, SessionState sstate)
{
String channel = state.getPrimaryCalendarReference();
Set<ExternalSubscription> availableSubscriptions = ExternalCalendarSubscriptionService
.getAvailableInstitutionalSubscriptionsForChannel(channel);
Set<ExternalSubscription> subscribedByUser = ExternalCalendarSubscriptionService
.getSubscriptionsForChannel(channel, false);
// Institutional subscriptions
List<SubscriptionWrapper> institutionalSubscriptions = new ArrayList<SubscriptionWrapper>();
for (ExternalSubscription available : availableSubscriptions)
{
boolean selected = false;
for (ExternalSubscription subscribed : subscribedByUser)
{
if (subscribed.getReference().equals(available.getReference()))
{
selected = true;
break;
}
}
if (available.isInstitutional())
institutionalSubscriptions.add(new SubscriptionWrapper(available,
selected));
}
// User subscriptions
List<SubscriptionWrapper> userSubscriptions = (List<SubscriptionWrapper>) sstate
.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
if (userSubscriptions == null)
{
userSubscriptions = new ArrayList<SubscriptionWrapper>();
for (ExternalSubscription subscribed : subscribedByUser)
{
if (!subscribed.isInstitutional())
{
userSubscriptions.add(new SubscriptionWrapper(subscribed, true));
}
}
}
// Sort collections by name
Collections.sort(institutionalSubscriptions);
Collections.sort(userSubscriptions);
// Place in context so that the velocity template can get at it.
context.put("tlang", rb);
context.put(institutionalSubscriptionsAvailable, !institutionalSubscriptions
.isEmpty());
context.put(institutionalSubscriptionsCollection, institutionalSubscriptions);
context.put(userSubscriptionsCollection, userSubscriptions);
sstate.setAttribute(SSTATE_ATTRIBUTE_SUBSCRIPTIONS,
institutionalSubscriptions);
sstate.setAttribute(SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS, userSubscriptions);
}
/**
* Action is used when the doCancel is requested when the user click on
* cancel
*/
public void doCancel(RunData data, Context context, CalendarActionState state,
SessionState sstate)
{
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
// cancel the options, release the site lock, cleanup
cancelOptions();
// Clear the previous state so that we don't get confused elsewhere.
state.setPrevState("");
sstate.removeAttribute(STATE_MODE);
sstate.removeAttribute(SSTATE_ATTRIBUTE_SUBSCRIPTIONS);
sstate.removeAttribute(SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
enableObserver(sstate, true);
} // doCancel
/**
* Action is used when the doAddSubscription is requested
*/
public void doAddSubscription(RunData runData, Context context,
CalendarActionState state, SessionState sstate)
{
List<SubscriptionWrapper> addSubscriptions = (List<SubscriptionWrapper>) sstate
.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
enableObserver(sstate, true);
String calendarName = runData.getParameters().getString("calendarName")
.trim();
String calendarUrl = runData.getParameters().getString("calendarUrl").trim();
calendarUrl = calendarUrl.replaceAll("webcals://", "https://");
calendarUrl = calendarUrl.replaceAll("webcal://", "http://");
if (calendarName.length() == 0)
{
addAlert(sstate, rb.getString("java.alert.subsnameempty"));
}
else if (calendarUrl.length() == 0)
{
addAlert(sstate, rb.getString("java.alert.subsurlempty"));
}
else
{
String contextId = EntityManager.newReference(
state.getPrimaryCalendarReference()).getContext();
String id = ExternalCalendarSubscriptionService
.getIdFromSubscriptionUrl(calendarUrl);
String ref = ExternalCalendarSubscriptionService
.calendarSubscriptionReference(contextId, id);
addSubscriptions.add(new SubscriptionWrapper(calendarName, ref, true));
// Sort collections by name
Collections.sort(addSubscriptions);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS,
addSubscriptions);
}
} // doAddSubscription
/**
* Handle the "Subscriptions" button on the toolbar
*/
public void doSubscriptions(RunData runData, Context context,
CalendarActionState state, SessionState sstate)
{
doOptions(runData, context);
// if we didn't end up in options mode, bail out
if (!MODE_OPTIONS.equals(sstate.getAttribute(STATE_MODE))) return;
// Disable the observer
enableObserver(sstate, false);
// Save the previous state so that we can get to it after we're done
// with the options mode.
// state.setPrevState(state.getState());
// Save the previous state so that we can get to it after we're done
// with the options mode.
// if the previous state is Description, we need to remember one
// more step back
// coz there is a back link in description view
if ((state.getState()).equalsIgnoreCase("description"))
{
state.setPrevState(state.getReturnState() + "!!!fromDescription");
}
else
{
state.setPrevState(state.getState());
}
state.setState(CalendarAction.STATE_CALENDAR_SUBSCRIPTIONS);
} // doSubscriptions
/**
* Handles the user clicking on the save button on the page to specify
* which calendars will be merged into the present schedule.
*/
public void doUpdate(RunData runData, Context context, CalendarActionState state,
SessionState sstate)
{
List<SubscriptionWrapper> calendarSubscriptions = (List<SubscriptionWrapper>) sstate
.getAttribute(SSTATE_ATTRIBUTE_SUBSCRIPTIONS);
List<SubscriptionWrapper> addSubscriptions = (List<SubscriptionWrapper>) sstate
.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
List<String> subscriptionTC = new LinkedList<String>();
ParameterParser params = runData.getParameters();
// Institutional Calendars
if (calendarSubscriptions != null)
{
for (SubscriptionWrapper subs : calendarSubscriptions)
{
if (params.getString(subs.getReference()) != null)
{
String name = subs.getDisplayName();
if (name == null || name.equals("")) name = subs.getUrl();
subscriptionTC.add(subs.getReference());
}
}
}
// Other Calendars
if (addSubscriptions != null)
{
for (SubscriptionWrapper add : addSubscriptions)
{
if (params.getString(add.getReference()) != null)
{
String name = add.getDisplayName();
if (name == null || name.equals("")) name = add.getUrl();
subscriptionTC.add(add.getReference() + NAME_DELIMITER
+ add.getDisplayName());
}
}
}
// Update the tool config
Placement placement = ToolManager.getCurrentPlacement();
if (placement != null)
{
Properties config = placement.getPlacementConfig();
if (config != null)
{
boolean first = true;
StringBuffer propValue = new StringBuffer();
for (String ref : subscriptionTC)
{
if (!first) propValue.append(REF_DELIMITER);
first = false;
propValue.append(ref);
}
config.setProperty(
ExternalCalendarSubscriptionService.TC_PROP_SUBCRIPTIONS,
propValue.toString());
// commit the change
saveOptions();
}
}
// Turn the observer back on.
enableObserver(sstate, true);
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
// Clear the previous state so that we don't get confused elsewhere.
state.setPrevState("");
sstate.removeAttribute(STATE_MODE);
sstate.removeAttribute(SSTATE_ATTRIBUTE_SUBSCRIPTIONS);
sstate.removeAttribute(SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
} // doUpdate
public class SubscriptionWrapper implements Comparable<SubscriptionWrapper>
{
private String reference;
private String url;
private String displayName;
private boolean isInstitutional;
private boolean isSelected;
public SubscriptionWrapper()
{
}
public SubscriptionWrapper(ExternalSubscription subscription, boolean selected)
{
this.reference = subscription.getReference();
this.url = subscription.getSubscriptionUrl();
this.displayName = subscription.getSubscriptionName();
this.isInstitutional = subscription.isInstitutional();
this.isSelected = selected;
}
public SubscriptionWrapper(String calendarName, String ref, boolean selected)
{
Reference _reference = EntityManager.newReference(ref);
this.reference = ref;
// this.id = _reference.getId();
this.url = ExternalCalendarSubscriptionService
.getSubscriptionUrlFromId(_reference.getId());
this.displayName = calendarName;
this.isInstitutional = ExternalCalendarSubscriptionService
.isInstitutionalCalendar(ref);
this.isSelected = selected;
}
public String getReference()
{
return reference;
}
public void setReference(String ref)
{
this.reference = ref;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public String getDisplayName()
{
return displayName;
}
public void setDisplayName(String displayName)
{
this.displayName = displayName;
}
public boolean isInstitutional()
{
return isInstitutional;
}
public void setInstitutional(boolean isInstitutional)
{
this.isInstitutional = isInstitutional;
}
public boolean isSelected()
{
return isSelected;
}
public void setSelected(boolean isSelected)
{
this.isSelected = isSelected;
}
public int compareTo(SubscriptionWrapper sub)
{
if(this.getDisplayName() == null || sub.getDisplayName() == null)
return this.getUrl().compareTo(sub.getUrl());
else
return this.getDisplayName().compareTo(sub.getDisplayName());
}
}
}
/**
* Utility class to figure out permissions for a calendar object.
*/
static public class CalendarPermissions
{
/**
* Priate constructor, doesn't allow instances of this object.
*/
private CalendarPermissions()
{
super();
}
/**
* Returns true if the primary and selected calendar are the same, but not null.
*/
static boolean verifyPrimarySelectedMatch(String primaryCalendarReference, String selectedCalendarReference)
{
//
// Both primary and secondary calendar ids must be specified.
// These must also match to be able to delete an event
//
if ( primaryCalendarReference == null ||
selectedCalendarReference == null ||
!primaryCalendarReference.equals(selectedCalendarReference) )
{
return false;
}
else
{
return true;
}
}
/**
* Utility routint to get the calendar for a given calendar id.
*/
static private Calendar getTheCalendar(String calendarReference)
{
Calendar calendarObj = null;
try
{
calendarObj = CalendarService.getCalendar(calendarReference);
if (calendarObj == null)
{
// If the calendar isn't there, try adding it.
CalendarService.commitCalendar(
CalendarService.addCalendar(calendarReference));
calendarObj = CalendarService.getCalendar(calendarReference);
}
}
catch (IdUnusedException e)
{
M_log.debug("CalendarPermissions.getTheCalendar(): ",e);
}
catch (PermissionException e)
{
M_log.debug("CalendarPermissions.getTheCalendar(): " + e);
}
catch (IdUsedException e)
{
M_log.debug("CalendarPermissions.getTheCalendar(): " + e);
}
catch (IdInvalidException e)
{
M_log.debug("CalendarPermissions.getTheCalendar(): " + e);
}
return calendarObj;
}
/**
* Returns true if the current user can see the events in a calendar.
*/
static public boolean allowViewEvents(String calendarReference)
{
Calendar calendarObj = getTheCalendar(calendarReference);
if (calendarObj == null)
{
return false;
}
else
{
return calendarObj.allowGetEvents();
}
}
/**
* Returns true if the current user is allowed to delete events on the calendar id
* passed in as the selectedCalendarReference parameter. The selected calendar must match
* the primary calendar for this function to return true.
* @param primaryCalendarReference calendar id for the default channel
* @param selectedCalendarReference calendar id for the event the user has just selected
*/
public static boolean allowDeleteEvent(String primaryCalendarReference, String selectedCalendarReference, String eventId)
{
//
// Both primary and secondary calendar ids must be specified.
// These must also match to be able to delete an event
//
if ( !verifyPrimarySelectedMatch(primaryCalendarReference, selectedCalendarReference) )
{
return false;
}
Calendar calendarObj = getTheCalendar(primaryCalendarReference);
if (calendarObj == null)
{
return false;
}
else
{
CalendarEvent event = null;
try
{
event = calendarObj.getEvent(eventId);
}
catch (IdUnusedException e)
{
M_log.debug("CalendarPermissions.canDeleteEvent(): " + e);
}
catch (PermissionException e)
{
M_log.debug("CalendarPermissions.canDeleteEvent(): " + e);
}
if (event == null)
{
return false;
}
else
{
return calendarObj.allowRemoveEvent(event);
}
}
}
/**
* Returns true if the current user is allowed to revise events on the calendar id
* passed in as the selectedCalendarReference parameter. The selected calendar must match
* the primary calendar for this function to return true.
* @param primaryCalendarReference calendar id for the default channel
* @param selectedCalendarReference calendar reference for the event the user has just selected
*/
static public boolean allowReviseEvents(String primaryCalendarReference, String selectedCalendarReference, String eventId)
{
//
// Both primary and secondary calendar ids must be specified.
// These must also match to be able to delete an event
//
if ( !verifyPrimarySelectedMatch(primaryCalendarReference, selectedCalendarReference) )
{
return false;
}
Calendar calendarObj = getTheCalendar(primaryCalendarReference);
if (calendarObj == null)
{
return false;
}
else
{
return calendarObj.allowEditEvent(eventId);
}
}
/**
* Returns true if the current user is allowed to create events on the calendar id
* passed in as the selectedCalendarReference parameter. The selected calendar must match
* the primary calendar for this function to return true.
* @param primaryCalendarReference calendar reference for the default channel
* @param selectedCalendarReference calendar reference for the event the user has just selected
*/
static public boolean allowCreateEvents(String primaryCalendarReference, String selectedCalendarReference)
{
// %%% Note: disabling this check as the allow create events should ONLY be on the primary,
// we don't care about the selected -ggolden
/*
//
// The primary and selected calendar ids must match, unless the selected calendar
// is null or empty.
//
if ( selectedCalendarReference != null &&
selectedCalendarReference.length() > 0 &&
!verifyPrimarySelectedMatch(primaryCalendarReference, selectedCalendarReference) )
{
return false;
}
*/
Calendar calendarObj = getTheCalendar(primaryCalendarReference);
if (calendarObj == null)
{
return false;
}
else
{
return calendarObj.allowAddEvent();
}
}
/**
* Returns true if the user is allowed to merge events from different calendars
* within the default channel.
*/
static public boolean allowMergeCalendars(String calendarReference)
{
return CalendarService.allowMergeCalendar(calendarReference);
}
/**
* Returns true if the use is allowed to modify properties of the calendar itself,
* and not just the events within the calendar.
*/
static public boolean allowModifyCalendarProperties(String calendarReference)
{
return CalendarService.allowEditCalendar(calendarReference);
}
/**
* Returns true if the use is allowed to import (and export) events
* into the calendar.
*/
static public boolean allowImport(String calendarReference)
{
return CalendarService.allowImportCalendar(calendarReference);
}
/**
* Returns true if the user is allowed to subscribe external calendars
* into the calendar.
*/
static public boolean allowSubscribe(String calendarReference)
{
return CalendarService.allowSubscribeCalendar(calendarReference);
}
}
private final static String SSTATE_ATTRIBUTE_ADDFIELDS_PAGE =
"addfieldsPage";
private final static String SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS_INIT =
"addfieldsInit";
private final static String SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS =
"addfields";
private final static String SSTATE_ATTRIBUTE_DELFIELDS = "delFields";
private final static String SSTATE_ATTRIBUTE_DELFIELDS_CONFIRM =
"delfieldsConfirm";
private final static String SSTATE_ATTRIBUTE_SUBSCRIPTIONS_SERVICE = "calendarSubscriptionsService";
private final static String SSTATE_ATTRIBUTE_SUBSCRIPTIONS = "calendarSubscriptions";
private final static String SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS = "addCalendarSubscriptions";
private final static String STATE_NEW = "new";
private static final String EVENT_REFERENCE_PARAMETER = "eventReference";
private static final String EVENT_CONTEXT_VAR = "event";
private static final String NO_EVENT_FLAG_CONTEXT_VAR = "noEvent";
//
// These are variables used in the context for communication between this
// action class and the Velocity template.
//
// False/true string values are used in the context variables in a number of places.
private static final String FALSE_STRING = "false";
private static final String TRUE_STRING = "true";
// This is the property name in the portlet config for the list of calendars
// that are not merged.
private final static String PORTLET_CONFIG_PARM_MERGED_CALENDARS = "mergedCalendarReferences";
// default calendar view property
private final static String PORTLET_CONFIG_DEFAULT_VIEW = "defaultCalendarView";
private final static String PAGE_MAIN = "main";
private final static String PAGE_ADDFIELDS = "addFields";
/** The flag name and value in state to indicate an update to the portlet is needed. */
private final static String SSTATE_ATTRIBUTE_MERGED_CALENDARS = "mergedCalendars";
// String constants for user interface states
private final static String STATE_MERGE_CALENDARS = "mergeCalendars";
private final static String STATE_CALENDAR_SUBSCRIPTIONS = "calendarSubscriptions";
private final static String STATE_CUSTOMIZE_CALENDAR = "customizeCalendar";
// for detailed event view navigator
private final static String STATE_PREV_ACT = "toPrevActivity";
private final static String STATE_NEXT_ACT = "toNextActivity";
private final static String STATE_CURRENT_ACT = "toCurrentActivity";
private final static String STATE_EVENTS_LIST ="eventIds";
private final static String STATE_NAV_DIRECTION = "navigationDirection";
private MergePage mergedCalendarPage = new MergePage();
private CustomizeCalendarPage customizeCalendarPage = new CustomizeCalendarPage();
private CalendarSubscriptionsPage calendarSubscriptionsPage = new CalendarSubscriptionsPage();
/**
* See if the current tab is the workspace tab (i.e. user site)
* @return true if we are currently on the "My Workspace" tab.
*/
private static boolean isOnWorkspaceTab()
{
return SiteService.isUserSite(ToolManager.getCurrentPlacement().getContext());
}
protected Class getStateClass()
{
return CalendarActionState.class;
} // getStateClass
/**
** loadChannels -- load specified primaryCalendarReference
** or merged calendars if initMergeList is defined
**/
private MergedList loadChannels( String primaryCalendarReference,
String initMergeList,
MergedList.EntryProvider entryProvider )
{
MergedList mergedCalendarList = new MergedList();
String[] channelArray = null;
// Figure out the list of channel references that we'll be using.
// MyWorkspace is special: if not superuser, and not otherwise defined, get all channels
if ( isOnWorkspaceTab() && !SecurityService.isSuperUser() && initMergeList == null )
channelArray = mergedCalendarList.getAllPermittedChannels(new CalendarChannelReferenceMaker());
else
channelArray = mergedCalendarList.getChannelReferenceArrayFromDelimitedString(
primaryCalendarReference, initMergeList );
if (entryProvider == null )
{
entryProvider = new MergedListEntryProviderFixedListWrapper(
new EntryProvider(),
primaryCalendarReference,
channelArray,
new CalendarReferenceToChannelConverter());
}
mergedCalendarList.loadChannelsFromDelimitedString(
isOnWorkspaceTab(),
false,
entryProvider,
StringUtils.trimToEmpty(SessionManager.getCurrentSessionUserId()),
channelArray,
SecurityService.isSuperUser(),
ToolManager.getCurrentPlacement().getContext());
return mergedCalendarList;
}
/**
* Gets an array of all the calendars whose events we can access.
*/
private List getCalendarReferenceList(VelocityPortlet portlet, String primaryCalendarReference, boolean isOnWorkspaceTab)
{
// load all calendar channels (either primary or merged calendars)
MergedList mergedCalendarList =
loadChannels( primaryCalendarReference,
portlet.getPortletConfig().getInitParameter(PORTLET_CONFIG_PARM_MERGED_CALENDARS),
null );
// add external calendar subscriptions
List referenceList = mergedCalendarList.getReferenceList();
Set subscriptionRefList = ExternalCalendarSubscriptionService.getCalendarSubscriptionChannelsForChannels(
primaryCalendarReference,
referenceList);
referenceList.addAll(subscriptionRefList);
return referenceList;
}
/**
* Gets the session state from the Jetspeed RunData
*/
static private SessionState getSessionState(RunData runData)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData)runData).getJs_peid();
return ((JetspeedRunData)runData).getPortletSessionState(peid);
}
public String buildMainPanelContext( VelocityPortlet portlet,
Context context,
RunData runData,
SessionState sstate)
{
CalendarActionState state = (CalendarActionState)getState(portlet, runData, CalendarActionState.class);
String template = (String)getContext(runData).get("template");
// get current state (view); if not set use tool default or default to week view
String stateName = state.getState();
if (stateName == null)
{
stateName = portlet.getPortletConfig().getInitParameter(PORTLET_CONFIG_DEFAULT_VIEW);
if (stateName == null)
stateName = ServerConfigurationService.getString("calendar.default.view", "week");
state.setState(stateName);
}
if ( stateName.equals(STATE_SCHEDULE_IMPORT) )
{
buildImportContext(portlet, context, runData, state, getSessionState(runData));
}
else if ( stateName.equals(STATE_MERGE_CALENDARS) )
{
// build the context to display the options panel
mergedCalendarPage.buildContext(portlet, context, runData, state, getSessionState(runData));
}
else if ( stateName.equals(STATE_CALENDAR_SUBSCRIPTIONS) )
{
// build the context to display the options panel
calendarSubscriptionsPage.buildContext(portlet, context, runData, state, getSessionState(runData));
}
else if ( stateName.equals(STATE_CUSTOMIZE_CALENDAR) )
{
// build the context to display the options panel
//needed to track when user clicks 'Save' or 'Cancel'
String sstatepage = "";
Object statepageAttribute = sstate.getAttribute(SSTATE_ATTRIBUTE_ADDFIELDS_PAGE);
if ( statepageAttribute != null )
{
sstatepage = statepageAttribute.toString();
}
if (!sstatepage.equals(PAGE_ADDFIELDS))
{
sstate.setAttribute(SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, PAGE_MAIN);
}
customizeCalendarPage.buildContext(portlet, context, runData, state, getSessionState(runData));
}
else if ((stateName.equals("revise"))|| (stateName.equals("goToReviseCalendar")))
{
// build the context for the normal view show
buildReviseContext(portlet, context, runData, state);
}
else if (stateName.equals("description"))
{
// build the context for the basic step of adding file
buildDescriptionContext(portlet, context, runData, state);
}
else if (stateName.equals("year"))
{
// build the context for the advanced step of adding file
buildYearContext(portlet, context, runData, state);
}
else if (stateName.equals("month"))
{
// build the context for the basic step of adding folder
buildMonthContext(portlet, context, runData, state);
}
else if (stateName.equals("day"))
{
// build the context for the basic step of adding simple text
buildDayContext(portlet, context, runData, state);
}
else if (stateName.equals("week"))
{
// build the context for the basic step of delete confirm page
buildWeekContext(portlet, context, runData, state);
}
else if (stateName.equals("new"))
{
// build the context to display the property list
buildNewContext(portlet, context, runData, state);
}
else if (stateName.equals("icalEx"))
{
buildIcalExportPanelContext(portlet, context, runData, state);
}
else if (stateName.equals("delete"))
{
// build the context to display the property list
buildDeleteContext(portlet, context, runData, state);
}
else if (stateName.equals("list"))
{
// build the context to display the list view
buildListContext(portlet, context, runData, state);
}
else if (stateName.equals(STATE_SET_FREQUENCY))
{
buildFrequencyContext(portlet, context, runData, state);
}
TimeZone timeZone = TimeService.getLocalTimeZone();
context.put("timezone", timeZone.getDisplayName(timeZone.inDaylightTime(new Date()), TimeZone.SHORT) );
//the AM/PM strings
context.put("amString", CalendarUtil.getLocalAMString());
context.put("pmString", CalendarUtil.getLocalPMString());
// group realted variables
context.put("siteAccess", CalendarEvent.EventAccess.SITE);
context.put("groupAccess", CalendarEvent.EventAccess.GROUPED);
context.put("message", state.getState());
context.put("state", state.getKey());
context.put("tlang",rb);
context.put("config",configProps);
context.put("dateFormat", getDateFormatString());
return template;
} // buildMainPanelContext
private void buildImportContext(VelocityPortlet portlet, Context context, RunData runData, CalendarActionState state, SessionState state2)
{
// Place this object in the context so that the velocity template
// can get at it.
// Start at the beginning if nothing is set yet.
if ( state.getImportWizardState() == null )
{
state.setImportWizardState(IMPORT_WIZARD_SELECT_TYPE_STATE);
}
// (optional) ical.experimental import
context.put("icalEnable",
ServerConfigurationService.getString("ical.experimental"));
// Set whatever the current wizard state is.
context.put("importWizardState", state.getImportWizardState());
context.put("tlang",rb);
context.put("config",configProps);
// Set the imported events into the context.
context.put("wizardImportedEvents", state.getWizardImportedEvents());
String calId = state.getPrimaryCalendarReference();
try
{
Calendar calendarObj = CalendarService.getCalendar(calId);
String scheduleTo = (String)state2.getAttribute(STATE_SCHEDULE_TO);
if (scheduleTo != null && scheduleTo.length() != 0)
{
context.put("scheduleTo", scheduleTo);
}
else
{
if (calendarObj.allowAddEvent())
{
// default to make site selection
context.put("scheduleTo", "site");
}
else if (calendarObj.getGroupsAllowAddEvent().size() > 0)
{
// to group otherwise
context.put("scheduleTo", "groups");
}
}
Collection groups = calendarObj.getGroupsAllowAddEvent();
if (groups.size() > 0)
{
context.put("groups", groups);
}
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".buildImportContext(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".buildImportContext(): " + e);
}
}
/**
* Addes the primary calendar reference (this site's default calendar)
* to the calendar action state object.
*/
private void setPrimaryCalendarReferenceInState(VelocityPortlet portlet, CalendarActionState state)
{
String calendarReference = state.getPrimaryCalendarReference();
if (calendarReference == null)
{
calendarReference = StringUtils.trimToNull(portlet.getPortletConfig().getInitParameter(CALENDAR_INIT_PARAMETER));
if (calendarReference == null)
{
// form a reference to the default calendar for this request's site
calendarReference = CalendarService.calendarReference(ToolManager.getCurrentPlacement().getContext(), SiteService.MAIN_CONTAINER);
state.setPrimaryCalendarReference(calendarReference);
}
}
}
/**
* Build the context for editing the frequency
*/
protected void buildFrequencyContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
// under 3 conditions, we get into this page
// 1st, brand new event, no freq or rule set up, coming from revise page
// 2nd, exisitng event, coming from revise page
// 3rd, new event, stay in this page after changing frequency by calling js function onchange()
// 4th, existing event, stay in this page after changing frequency by calling js function onchange()
// sstate attribute TEMP_FREQ_SELECT is one of the flags
// if this attribute is not null, means changeFrequency() is called thru onchange().
// Then rule is another flag, if rule is null, means new event
// Combination of these 2 flags should cover all the conditions
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
// defaultly set frequency to be once
// if there is a saved state frequency attribute, replace the default one
String freq = CalendarAction.DEFAULT_FREQ;
if (sstate.getAttribute(TEMP_FREQ_SELECT) != null)
{
freq = (String)sstate.getAttribute(TEMP_FREQ_SELECT);
if (rule != null)
context.put("rule", rule);
sstate.removeAttribute(TEMP_FREQ_SELECT);
}
else
{
if (rule != null)
{
freq = rule.getFrequency();
context.put("rule", rule);
}
}
context.put("freq", freq);
context.put("tlang",rb);
context.put("config",configProps);
// get the data the user just input in the preview new/revise page
context.put("savedData",state.getNewData());
context.put("realDate", TimeService.newTime());
} // buildFrequencyContext
/**
* Build the context for showing revise view
*/
protected void buildReviseContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
context.put("tlang",rb);
context.put("config",configProps);
Calendar calendarObj = null;
CalendarEvent calEvent = null;
CalendarUtil calObj= new CalendarUtil(); //null;
MyDate dateObj1 = null;
dateObj1 = new MyDate();
boolean getEventsFlag = false;
List attachments = state.getAttachments();
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
calObj.setDay(stateYear, stateMonth, stateDay);
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
String calId = state.getPrimaryCalendarReference();
if( state.getIsNewCalendar() == false)
{
if (CalendarService.allowGetCalendar(calId)== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
return;
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
if(calendarObj.allowGetEvent(state.getCalendarEventId()))
{
calEvent = calendarObj.getEvent(state.getCalendarEventId());
getEventsFlag = true;
context.put("selectedGroupRefsCollection", calEvent.getGroups());
// all the groups the user is allowed to do remove from
context.put("allowedRemoveGroups", calendarObj.getGroupsAllowRemoveEvent(calEvent.isUserOwner()));
}
else
getEventsFlag = false;
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsIntoContextFromCalendar( calendarObj, context);
context.put("tlang",rb);
context.put("config",configProps);
context.put("calEventFlag","true");
context.put("new", "false");
// if from the metadata view of announcement, the message is already the system resource
if ( state.getState().equals("goToReviseCalendar") )
{
context.put("backToRevise", "false");
}
// if from the attachments editing view or preview view of announcement
else if (state.getState().equals("revise"))
{
context.put("backToRevise", "true");
}
//Vector attachments = state.getAttachments();
if ( attachments != null )
{
context.put("attachments", attachments);
}
else
{
context.put("attachNull", "true");
}
context.put("fromAttachmentFlag",state.getfromAttachmentFlag());
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY, rb.getString("java.alert.therenoactv"));
M_log.debug(".buildReviseContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildReviseContext(): " + e);
return;
}
}
}
else
{
// if this a new annoucement, get the subject and body from temparory record
context.put("new", "true");
context.put("tlang",rb);
context.put("config",configProps);
context.put("attachments", attachments);
context.put("fromAttachmentFlag",state.getfromAttachmentFlag());
}
// Output for recurring events
// for an existing event
// if the saved recurring rule equals to string FREQ_ONCE, set it as not recurring
// if there is a saved recurring rule in sstate, display it
// otherwise, output the event's rule instead
if ((((String) sstate.getAttribute(FREQUENCY_SELECT)) != null)
&& (((String) sstate.getAttribute(FREQUENCY_SELECT)).equals(FREQ_ONCE)))
{
context.put("rule", null);
}
else
{
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
if (rule == null)
{
rule = calEvent.getRecurrenceRule();
}
else
context.put("rule", rule);
if (rule != null)
{
context.put("freq", rule.getFrequencyDescription());
} // if (rule != null)
} //if ((String) sstate.getAttribute(FREQUENCY_SELECT).equals(FREQ_ONCE))
try
{
calendarObj = CalendarService.getCalendar(calId);
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
if (scheduleTo != null && scheduleTo.length() != 0)
{
context.put("scheduleTo", scheduleTo);
}
else
{
if (calendarObj.allowAddCalendarEvent())
{
// default to make site selection
context.put("scheduleTo", "site");
}
else if (calendarObj.getGroupsAllowAddEvent().size() > 0)
{
// to group otherwise
context.put("scheduleTo", "groups");
}
}
Collection groups = calendarObj.getGroupsAllowAddEvent();
// add to these any groups that the message already has
calEvent = calendarObj.getEvent(state.getCalendarEventId());
if (calEvent != null)
{
Collection otherGroups = calEvent.getGroupObjects();
for (Iterator i = otherGroups.iterator(); i.hasNext();)
{
Group g = (Group) i.next();
if (!groups.contains(g))
{
groups.add(g);
}
}
}
if (groups.size() > 0)
{
context.put("groups", groups);
}
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".buildNewContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".buildNewContext(): " + e);
return;
}
context.put("tlang",rb);
context.put("config",configProps);
context.put("event", calEvent);
context.put("helper",new Helper());
context.put("message","revise");
context.put("savedData",state.getNewData());
context.put("getEventsFlag", Boolean.valueOf(getEventsFlag));
if(state.getIsNewCalendar()==true)
context.put("vmtype","new");
else
context.put("vmtype","revise");
context.put("service", contentHostingService);
// output the real time
context.put("realDate", TimeService.newTime());
} // buildReviseContext
/**
* Build the context for showing description for events
*/
protected void buildDescriptionContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
context.put("tlang",rb);
context.put("config",configProps);
context.put("Context", ToolManager.getCurrentPlacement().getContext());
context.put("CalendarService", CalendarService.getInstance());
context.put("SiteService", SiteService.getInstance());
Calendar calendarObj = null;
CalendarEvent calEvent = null;
MyDate dateObj1 = null;
dateObj1 = new MyDate();
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
navigatorContextControl(portlet, context, runData, (String)sstate.getAttribute(STATE_NAV_DIRECTION));
boolean prevAct = sstate.getAttribute(STATE_PREV_ACT) != null;
boolean nextAct = sstate.getAttribute(STATE_NEXT_ACT) != null;
context.put("prevAct", Boolean.valueOf(prevAct));
context.put("nextAct", Boolean.valueOf(nextAct));
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj= new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
// get the today date in month/day/year format
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
// get the event id from the CalendarService.
// send the event to the vm
String ce = state.getCalendarEventId();
String selectedCalendarReference = state.getSelectedCalendarReference();
if ( !CalendarPermissions.allowViewEvents(selectedCalendarReference) )
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
M_log.debug("here in buildDescription not showing event");
return;
}
else
{
try
{
calendarObj = CalendarService.getCalendar(selectedCalendarReference);
calEvent = calendarObj.getEvent(ce);
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsIntoContextFromCalendar( calendarObj, context);
context.put(EVENT_CONTEXT_VAR, calEvent);
context.put("tlang",rb);
context.put("config",configProps);
// Get the attachments from assignment tool for viewing
String assignmentId = calEvent.getField(CalendarUtil.NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID);
if (assignmentId != null && assignmentId.length() > 0)
{
// pass in the assignment reference to get the assignment data we need
Map<String, Object> assignData = new HashMap<String, Object>();
StringBuilder entityId = new StringBuilder( ASSN_ENTITY_PREFIX );
entityId.append( (CalendarService.getCalendar(calEvent.getCalendarReference())).getContext() );
entityId.append( EntityReference.SEPARATOR );
entityId.append( assignmentId );
ActionReturn ret = entityBroker.executeCustomAction(entityId.toString(), ASSN_ENTITY_ACTION, null, null);
if (ret != null && ret.getEntityData() != null) {
Object returnData = ret.getEntityData().getData();
assignData = (Map<String, Object>)returnData;
}
context.put("assignmenturl", (String) assignData.get("assignmentUrl"));
context.put("assignmentTitle", (String) assignData.get("assignmentTitle"));
}
String ownerId = calEvent.getCreator();
if ( ownerId != null && ! ownerId.equals("") )
{
String ownerName =
UserDirectoryService.getUser( ownerId ).getDisplayName();
context.put("owner_name", ownerName);
}
String siteName = calEvent.getSiteName();
if ( siteName != null )
context.put("site_name", siteName );
RecurrenceRule rule = calEvent.getRecurrenceRule();
// for a brand new event, there is no saved recurring rule
if (rule != null)
{
context.put("freq", rule.getFrequencyDescription());
context.put("rule", rule);
}
// show all the groups in this calendar that user has get event in
Collection groups = calendarObj.getGroupsAllowGetEvent();
if (groups != null)
{
context.put("groupRange", calEvent.getGroupRangeForDisplay(calendarObj));
}
}
catch (IdUnusedException e)
{
M_log.debug(".buildDescriptionContext(): " + e);
context.put(NO_EVENT_FLAG_CONTEXT_VAR, TRUE_STRING);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotpermadd"));
M_log.debug(".buildDescriptionContext(): " + e);
return;
}
catch (UserNotDefinedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotpermadd"));
M_log.debug(".buildDescriptionContext(): " + e);
return;
}
}
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
context.put(
"allowDelete",
Boolean.valueOf(CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId())));
context.put(
"allowRevise",
Boolean.valueOf(CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId())));
} // buildDescriptionContext
/**
* Build the context for showing Year view
*/
protected void buildYearContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
CalendarUtil calObj= new CalendarUtil();
MyYear yearObj = null;
MyMonth monthObj1, monthObj2 = null;
MyDay dayObj = null;
MyDate dateObj1 = null;
boolean allowed = false;
CalendarEventVector CalendarEventVectorObj = null;
// new objects of myYear, myMonth, myDay, myWeek classes
yearObj = new MyYear();
monthObj1 = new MyMonth();
dayObj = new MyDay();
dateObj1 = new MyDate();
int month = 1;
int col = 3;
int row = 4;
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
calObj.setDay(stateYear, stateMonth, stateDay);
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
yearObj.setYear(calObj.getYear());
monthObj1.setMonth(calObj.getMonthInteger());
dayObj.setDay(calObj.getDayOfMonth());
if (CalendarService.allowGetCalendar(state.getPrimaryCalendarReference())== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallowsee"));
}
else
{
try
{
allowed = CalendarService.getCalendar(state.getPrimaryCalendarReference()).allowAddEvent();
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.therenoactv"));
M_log.debug(".buildYearContext(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildYearContext(): " + e);
}
}
for(int r = 0; r<row; r++)
{
for (int c = 0; c<col;c++)
{
monthObj2 = new MyMonth();
calObj.setDay(dateObj1.getYear(),month,1);
CalendarEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
getMonthTimeRange(calObj));
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
monthObj2 = calMonth(month, calObj,state,CalendarEventVectorObj);
month++;
yearObj.setMonth(monthObj2,r,c);
}
}
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
context.put("tlang",rb);
context.put("config",configProps);
context.put("yearArray",yearObj);
context.put("year",Integer.valueOf(calObj.getYear()));
context.put("date",dateObj1);
state.setState("year");
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
// added by zqian for toolbar
context.put("allow_new", Boolean.valueOf(allowed));
context.put("allow_delete", Boolean.valueOf(false));
context.put("allow_revise", Boolean.valueOf(false));
context.put("tlang",rb);
context.put("config",configProps);
context.put(Menu.CONTEXT_ACTION, "CalendarAction");
context.put("selectedView", rb.getString("java.byyear"));
context.put("dayOfWeekNames", calObj.getCalendarDaysOfWeekNames(false));
} // buildYearContext
/**
* Build the context for showing month view
*/
protected void buildMonthContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
MyMonth monthObj2 = null;
MyDate dateObj1 = null;
CalendarEventVector CalendarEventVectorObj = null;
dateObj1 = new MyDate();
// read calendar object saved in state object
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
// fill this month object with all days avilable for this month
if (CalendarService.allowGetCalendar(state.getPrimaryCalendarReference())== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
return;
}
CalendarEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
getMonthTimeRange(calObj));
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
monthObj2 = calMonth(calObj.getMonthInteger(), calObj,state, CalendarEventVectorObj);
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
// retrieve the information from day, month and year to calObj again since calObj changed during the process of CalMonth().
context.put("nameOfMonth",calendarUtilGetMonth(calObj.getMonthInteger()));
context.put("year", Integer.valueOf(calObj.getYear()));
context.put("monthArray",monthObj2);
context.put("tlang",rb);
context.put("config",configProps);
int row = 5;
context.put("row",Integer.valueOf(row));
context.put("date",dateObj1);
context.put("realDate", TimeService.newTime());
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
state.setState("month");
context.put("selectedView", rb.getString("java.bymonth"));
context.put("dayOfWeekNames", calObj.getCalendarDaysOfWeekNames(false));
} // buildMonthContext
protected Vector getNewEvents(int year, int month, int day, CalendarActionState state, RunData rundata, int time, int numberofcycles,Context context,CalendarEventVector CalendarEventVectorObj)
{
boolean firstTime = true;
Vector events = new Vector();
Time timeObj = TimeService.newTimeLocal(year,month,day,time,00,00,000);
long duration = ((30*60)*(1000));
Time updatedTime = TimeService.newTime(timeObj.getTime()+ duration);
/*** include the start time ***/
TimeRange timeRangeObj = TimeService.newTimeRange(timeObj,updatedTime,true,false);
for (int range = 0; range <=numberofcycles;range++)
{
Iterator calEvent = null;
calEvent = CalendarEventVectorObj.getEvents(timeRangeObj);
Vector vectorObj = new Vector();
EventDisplayClass eventDisplayObj;
Vector newVectorObj = null;
boolean swapflag=true;
EventDisplayClass eventdisplayobj = null;
if (calEvent.hasNext())
{
int i = 0;
while (calEvent.hasNext())
{
eventdisplayobj = new EventDisplayClass();
eventdisplayobj.setEvent((CalendarEvent)calEvent.next(),false,i);
vectorObj.add(i,eventdisplayobj);
i++;
} // while
if(firstTime)
{
events.add(range,vectorObj);
firstTime = false;
}
else
{
while(swapflag == true)
{
swapflag=false;
for(int mm = 0; mm<events.size();mm++)
{
int eom, mv =0;
Vector evectorObj = (Vector)events.elementAt(mm);
if(evectorObj.isEmpty()==false)
{
for(eom = 0; eom<evectorObj.size();eom++)
{
if(!"".equals(evectorObj.elementAt(eom)))
{
String eomId = (((EventDisplayClass)evectorObj.elementAt(eom)).getEvent()).getId();
newVectorObj = new Vector();
for(mv = 0; mv<vectorObj.size();mv++)
{
if(!"".equals(vectorObj.elementAt(mv)))
{
String vectorId = (((EventDisplayClass)vectorObj.elementAt(mv)).getEvent()).getId();
if (vectorId.equals(eomId))
{
eventDisplayObj = (EventDisplayClass)vectorObj.elementAt(mv);
eventDisplayObj.setFlag(true);
if (mv != eom)
{
swapflag = true;
vectorObj.removeElementAt(mv);
for(int x = 0 ; x<eom;x++)
{
if(vectorObj.isEmpty()==false)
{
newVectorObj.add(x,vectorObj.elementAt(0));
vectorObj.removeElementAt(0);
}
else
{
newVectorObj.add(x,"");
}
}// for
newVectorObj.add(eom, eventDisplayObj);
int neweom = eom;
neweom = neweom+1;
while(vectorObj.isEmpty()==false)
{
newVectorObj.add(neweom,vectorObj.elementAt(0));
vectorObj.removeElementAt(0);
neweom++;
}
for(int vv =0;vv<newVectorObj.size();vv++)
{
vectorObj.add(vv,newVectorObj.elementAt(vv));
}
} // if
} // if
} // if
} //for
} // if
} // for
} // if
} // for
} // while
events.add(range,vectorObj);
} // if - else firstTime
timeRangeObj.shiftForward(1800000);
}
else
{
events.add(range,vectorObj);
timeRangeObj.shiftForward(1800000);
}
} // for
return events;
} // getNewEvents
/**
* Build the context for showing day view
*/
protected void buildDayContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
Calendar calendarObj = null;
boolean allowed = false;
MyDate dateObj1 = null;
CalendarEventVector CalendarEventVectorObj = null;
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
context.put("todayYear", Integer.valueOf(stateYear));
context.put("todayMonth", Integer.valueOf(stateMonth));
context.put("todayDay", Integer.valueOf(stateDay));
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
// new objects of myYear, myMonth, myDay, myWeek classes
dateObj1 = new MyDate();
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
int year = dateObj1.getYear();
int month = dateObj1.getMonth();
int day = dateObj1.getDay();
Vector eventVector = new Vector();
String calId = state.getPrimaryCalendarReference();
if (CalendarService.allowGetCalendar(calId)== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
return;
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
allowed = calendarObj.allowAddEvent();
CalendarEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
getDayTimeRange(year, month, day));
String currentPage = state.getCurrentPage();
// if coming from clicking the the day number in month view, year view or list view
// select the time slot first, go to the slot containing earliest event on that day
if (state.getPrevState() != null)
{
if ( (state.getPrevState()).equalsIgnoreCase("list")
|| (state.getPrevState()).equalsIgnoreCase("month")
|| (state.getPrevState()).equalsIgnoreCase("year"))
{
CalendarEventVector vec = null;
Time timeObj = TimeService.newTimeLocal(year,month,day,FIRST_PAGE_START_HOUR,00,00,000);
Time timeObj2 = TimeService.newTimeLocal(year,month,day,7,59,59,000);
TimeRange timeRangeObj = TimeService.newTimeRange(timeObj,timeObj2);
vec = CalendarService.getEvents(getCalendarReferenceList(portlet, state.getPrimaryCalendarReference(),isOnWorkspaceTab()), timeRangeObj);
if (vec.size() > 0)
currentPage = "first";
else
{
timeObj = TimeService.newTimeLocal(year,month,day,SECOND_PAGE_START_HOUR,00,00,000);
timeObj2 = TimeService.newTimeLocal(year,month,day,17,59,59,000);
timeRangeObj = TimeService.newTimeRange(timeObj,timeObj2);
vec = CalendarService.getEvents(getCalendarReferenceList(portlet, state.getPrimaryCalendarReference(),isOnWorkspaceTab()), timeRangeObj);
if (vec.size() > 0)
currentPage = "second";
else
{
timeObj = TimeService.newTimeLocal(year,month,day,THIRD_PAGE_START_HOUR,00,00,000);
timeObj2 = TimeService.newTimeLocal(year,month,day,23,59,59,000);
timeRangeObj = TimeService.newTimeRange(timeObj,timeObj2);
vec = CalendarService.getEvents(getCalendarReferenceList(portlet, state.getPrimaryCalendarReference(),isOnWorkspaceTab()), timeRangeObj);
if (vec.size() > 0)
currentPage = "third";
else
currentPage = "second";
}
}
state.setCurrentPage(currentPage);
}
}
if(currentPage.equals("third"))
{
eventVector = getNewEvents(year,month,day, state, runData,THIRD_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
}
else if (currentPage.equals("second"))
{
eventVector = getNewEvents(year,month,day, state, runData,SECOND_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
}
else
{
eventVector = getNewEvents(year,month,day, state, runData,FIRST_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
}
dateObj1.setEventBerDay(eventVector);
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.therenoactv"));
M_log.debug(".buildDayContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildDayContext(): " + e);
return;
}
}
context.put("nameOfMonth",calendarUtilGetMonth(calObj.getMonthInteger()));
context.put("monthInt", Integer.valueOf(calObj.getMonthInteger()));
context.put("firstpage","true");
context.put("secondpage","false");
context.put("page",state.getCurrentPage());
context.put("date",dateObj1);
context.put("helper",new Helper());
context.put("calObj", calObj);
context.put("tlang",rb);
context.put("config",configProps);
state.setState("day");
context.put("message", state.getState());
DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL, new ResourceLoader().getLocale());
try{
context.put("today",formatter.format(calObj.getTime()));
}catch(Exception e){
context.put("today", calObj.getTodayDate());
}
state.setPrevState("");
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
context.put("permissionallowed",Boolean.valueOf(allowed));
context.put("tlang",rb);
context.put("config",configProps);
context.put("selectedView", rb.getString("java.byday"));
context.put("dayName", calendarUtilGetDay(calObj.getDay_Of_Week(false)));
} // buildDayContext
/**
* Build the context for showing week view
*/
protected void buildWeekContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
Calendar calendarObj = null;
//Time st,et = null;
//CalendarUtil calObj= null;
MyYear yearObj = null;
MyMonth monthObj1 = null;
MyWeek weekObj =null;
MyDay dayObj = null;
MyDate dateObj1, dateObj2 = null;
int dayofweek = 0;
// new objects of myYear, myMonth, myDay, myWeek classes
yearObj = new MyYear();
monthObj1 = new MyMonth();
weekObj = new MyWeek();
dayObj = new MyDay();
dateObj1 = new MyDate();
CalendarEventVector CalendarEventVectorObj = null;
//calObj = state.getCalObj();
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
int iii =0;
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
yearObj.setYear(calObj.getYear());
monthObj1.setMonth(calObj.getMonthInteger());
dayObj.setDay(calObj.getDayOfMonth());
String calId = state.getPrimaryCalendarReference();
// this loop will move the calendar to the begining of the week
if (CalendarService.allowGetCalendar(calId)== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
return;
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch(IdUnusedException e)
{
try
{
CalendarService.commitCalendar(CalendarService.addCalendar(calId));
calendarObj = CalendarService.getCalendar(calId);
}
catch (Exception err)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.therenoactv"));
M_log.debug(".buildWeekContext(): " + err);
return;
}
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildWeekContext(): " + e);
return;
}
}
if (calendarObj.allowGetEvents() == true)
{
CalendarEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
getWeekTimeRange(calObj));
}
else
{
CalendarEventVectorObj = new CalendarEventVector();
}
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
dayofweek = calObj.getDay_Of_Week(true);
calObj.setPrevDate(dayofweek-1);
dayofweek = calObj.getDay_Of_Week(true);
Time[] pageStartTime = new Time[7];
Time[] pageEndTime = new Time[7];
for(int i = 7; i>=dayofweek; i--)
{
Vector eventVector = new Vector();
Vector eventVector1;
dateObj2 = new MyDate();
dateObj2.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
dateObj2.setDayName(calendarUtilGetDay(calObj.getDay_Of_Week(false)));
dateObj2.setNameOfMonth(calendarUtilGetMonth(calObj.getMonthInteger()));
if (calObj.getDayOfMonth() == dayObj.getDay())
dateObj2.setFlag(1);
if(state.getCurrentPage().equals("third"))
{
eventVector1 = new Vector();
// JS -- the third page starts at 2PM(14 o'clock), and lasts 20 half-hour
eventVector = getNewEvents(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), state, runData,THIRD_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
for(int index = 0;index<eventVector1.size();index++)
{
eventVector.add(eventVector.size(),eventVector1.get(index));
}
// Reminder: weekview vm is using 0..6
pageStartTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), THIRD_PAGE_START_HOUR, 0, 0, 0);
pageEndTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), 23, 59, 0, 0);
}
else if (state.getCurrentPage().equals("second"))
{
eventVector = getNewEvents(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), state, runData,SECOND_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
// Reminder: weekview vm is using 0..6
pageStartTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), SECOND_PAGE_START_HOUR, 0, 0, 0);
pageEndTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), 17, 59, 0, 0);
}
else
{
eventVector1 = new Vector();
// JS -- the first page starts at 12AM(0 o'clock), and lasts 20 half-hour
eventVector1 = getNewEvents(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), state, runData, FIRST_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
for(int index = 0;index<eventVector1.size();index++)
{
eventVector.insertElementAt(eventVector1.get(index),index);
}
// Reminder: weekview vm is using 0..6
pageStartTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), 0, 0, 0, 0);
pageEndTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), 9, 59, 0, 0);
}
dateObj2.setEventBerWeek(eventVector);
weekObj.setWeek(7-i,dateObj2);
// the purpose of this if condition is to check if we reached day 7 if yes do not
// call next day.
if (i > dayofweek)
calObj.nextDate();
}
calObj.setDay(yearObj.getYear(),monthObj1.getMonth(),dayObj.getDay());
context.put("week", weekObj);
context.put("helper",new Helper());
context.put("date",dateObj1);
context.put("page",state.getCurrentPage());
state.setState("week");
context.put("tlang",rb);
context.put("config",configProps);
context.put("message",state.getState());
DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL, new ResourceLoader().getLocale());
formatter.setTimeZone(TimeService.getLocalTimeZone());
try{
context.put("beginWeek", formatter.format(calObj.getPrevTime(calObj.getDay_Of_Week(true)-1)));
}catch(Exception e){
context.put("beginWeek", calObj.getTodayDate());
}
try{
calObj.setNextWeek();
context.put("endWeek",formatter.format(calObj.getPrevTime(1)));
}catch(Exception e){
context.put("endWeek", calObj.getTodayDate());
}
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
calObj.setDay(yearObj.getYear(),monthObj1.getMonth(),dayObj.getDay());
context.put("realDate", TimeService.newTime());
context.put("tlang",rb);
context.put("config",configProps);
Vector vec = new Vector();
context.put("vec", vec);
Vector conflictVec = new Vector();
context.put("conflictVec", conflictVec);
Vector calVec = new Vector();
context.put("calVec", calVec);
HashMap hm = new HashMap();
context.put("hm", hm);
Integer intObj = Integer.valueOf(0);
context.put("intObj", intObj);
context.put("pageStartTime", pageStartTime);
context.put("pageEndTime", pageEndTime);
context.put("selectedView", rb.getString("java.byweek"));
context.put("dayOfWeekNames", calObj.getCalendarDaysOfWeekNames(false));
} // buildWeekContext
/**
* Build the context for showing New view
*/
protected void buildNewContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
context.put("tlang",rb);
context.put("config",configProps);
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
MyDate dateObj1 = new MyDate();
CalendarUtil calObj= new CalendarUtil();
// set real today's date as default
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
calObj.setDay(b.getYear(), b.getMonth(), b.getDay());
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
// get the event id from the CalendarService.
// send the event to the vm
dateObj1.setNumberOfDaysInMonth(calObj.getNumberOfDays());
List attachments = state.getAttachments();
context.put("attachments",attachments);
String calId = state.getPrimaryCalendarReference();
Calendar calendarObj = null;
try
{
calendarObj = CalendarService.getCalendar(calId);
Collection groups = calendarObj.getGroupsAllowAddEvent();
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
if (scheduleTo != null && scheduleTo.length() != 0)
{
context.put("scheduleTo", scheduleTo);
}
else
{
if (calendarObj.allowAddCalendarEvent())
{
// default to make site selection
context.put("scheduleTo", "site");
}
else if (groups.size() > 0)
{
// to group otherwise
context.put("scheduleTo", "groups");
}
}
if (groups.size() > 0)
{
List schToGroups = (List)(sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS));
context.put("scheduleToGroups", schToGroups);
context.put("groups", groups);
}
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".buildNewContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".buildNewContext(): " + e);
return;
}
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsIntoContextFromCalendar( calendarObj, context);
// Output for recurring events
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
// if the saved recurring rule equals to string FREQ_ONCE, set it as not recurring
// if there is a saved recurring rule in sstate, display it
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
if (rule != null)
{
context.put("freq", rule.getFrequencyDescription());
context.put("rule", rule);
}
context.put("date",dateObj1);
context.put("savedData",state.getNewData());
context.put("helper",new Helper());
context.put("realDate", TimeService.newTime());
} // buildNewContext
/**
* Setup for iCal Export.
*/
public String buildIcalExportPanelContext(VelocityPortlet portlet, Context context, RunData rundata, CalendarActionState state)
{
String calId = state.getPrimaryCalendarReference();
Calendar calendarObj = null;
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch ( Exception e )
{
M_log.debug(".buildIcalExportPanelContext: " + e);
}
context.put("tlang", rb);
context.put("config",configProps);
// provide form names
context.put("form-alias", FORM_ALIAS);
context.put("form-ical-enable", FORM_ICAL_ENABLE);
context.put("form-submit", BUTTON + "doIcalExport");
context.put("form-cancel", BUTTON + "doCancel");
if ( calendarObj != null )
{
List aliasList = AliasService.getAliases( calendarObj.getReference() );
if ( ! aliasList.isEmpty() )
{
String alias[] = ((Alias)aliasList.get(0)).getId().split("\\.");
context.put("alias", alias[0] );
}
}
context.put("serverName", ServerConfigurationService.getServerName());
// Add iCal Export URL
Reference calendarRef = EntityManager.newReference(calId);
String icalUrl = ServerConfigurationService.getAccessUrl()
+ CalendarService.calendarICalReference(calendarRef);
context.put("icalUrl", icalUrl );
boolean exportAllowed = CalendarPermissions.allowImport( calId );
context.put("allow_export", String.valueOf(exportAllowed) );
boolean exportEnabled = CalendarService.getExportEnabled(calId);
context.put("enable_export", String.valueOf(exportEnabled) );
// pick the "export" template based on the standard template name
String template = (String) getContext(rundata).get("template");
return template + "_icalexport";
} // buildIcalExportPanelContext
/**
* Build the context for showing delete view
*/
protected void buildDeleteContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
context.put("tlang",rb);
context.put("config",configProps);
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
Calendar calendarObj = null;
CalendarEvent calEvent = null;
// get the event id from the CalendarService.
// send the event to the vm
String calId = state.getPrimaryCalendarReference();
String calendarEventObj = state.getCalendarEventId();
try
{
calendarObj = CalendarService.getCalendar(calId);
calEvent = calendarObj.getEvent(calendarEventObj);
RecurrenceRule rule = calEvent.getRecurrenceRule();
// for a brand new event, there is no saved recurring rule
if (rule != null)
{
context.put("freq", rule.getFrequencyDescription());
context.put("rule", rule);
}
context.put("message","delete");
context.put("event",calEvent);
// show all the groups in this calendar that user has get event in
Collection groups = calendarObj.getGroupsAllowGetEvent();
if (groups != null)
{
context.put("groupRange", calEvent.getGroupRangeForDisplay(calendarObj));
}
}
catch (IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.noexist"));
M_log.debug(".buildDeleteContext(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youcreate"));
M_log.debug(".buildDeleteContext(): " + e);
}
} // buildDeleteContext
/**
* calculate the days in the month and there events if any
* @param month is int
* @param m_calObj is object of calendar
*/
public MyMonth calMonth(int month, CalendarUtil m_calObj, CalendarActionState state, CalendarEventVector CalendarEventVectorObj)
{
int numberOfDays = 0;
int firstDay_of_Month = 0;
boolean start = true;
MyMonth monthObj = null;
MyDate dateObj = null;
Iterator eventList = null;
Time startTime = null;
Time endTime = null;
TimeRange timeRange = null;
// new objects of myYear, myMonth, myDay, myWeek classes.
monthObj = new MyMonth();
// set the calendar to the begining of the month
m_calObj.setDay(m_calObj.getYear(), month, 1);
numberOfDays = m_calObj.getNumberOfDays();
// get the index of the first day in the month
firstDay_of_Month = m_calObj.getDay_Of_Week(true) - 1;
// get the index of the day
monthObj.setMonthName(calendarUtilGetMonth(m_calObj.getMonthInteger()));
// get the index of first day (-1) to display (may be in previous month)
m_calObj.setPrevDate(firstDay_of_Month+1);
for(int weekInMonth = 0; weekInMonth < 1; weekInMonth++)
{
// got the seven days in the first week of the month do..
for(int dayInWeek = 0; dayInWeek < 7; dayInWeek++)
{
dateObj = new MyDate();
m_calObj.nextDate();
// check if reach the first day of the month.
if ((dayInWeek == firstDay_of_Month) || (start == false))
{
// check if the current day of the month has been match, if yes set the flag to highlight the day in the
// user interface.
if ((m_calObj.getDayOfMonth() == state.getcurrentDay()) && (state.getcurrentMonth()== m_calObj.getMonthInteger()) && (state.getcurrentYear() == m_calObj.getYear()))
{
dateObj.setFlag(1);
}
// Each monthObj contains dayObjs for the number of the days in the month.
dateObj.setTodayDate(m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),m_calObj.getYear());
startTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),00,00,00,001);
endTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),23,59,00,000);
eventList = CalendarEventVectorObj.getEvents(TimeService.newTimeRange(startTime,endTime,true,true));
dateObj.setEvents(eventList);
// keep iterator of events in the dateObj
numberOfDays--;
monthObj.setDay(dateObj,weekInMonth,dayInWeek);
start = false;
}
else if (start == true)
{
// fill empty spaces for the first days in the first week in the month before reach the first day of the month
dateObj.setTodayDate(m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),m_calObj.getYear());
startTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),00,00,00,001);
endTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),23,59,00,000);
timeRange = TimeService.newTimeRange(startTime,endTime,true,true);
eventList = CalendarEventVectorObj.getEvents(timeRange);
dateObj.setEvents(eventList);
monthObj.setDay(dateObj,weekInMonth,dayInWeek);
dateObj.setFlag(0);
}// end else
}// end for m
}// end for i
// Construct the weeks left in the month and save it in the monthObj.
// row is the max number of rows in the month., Col is equal to 7 which is the max number of col in the month.
for(int row = 1; row<6; row++)
{
// Col is equal to 7 which is the max number of col in tin he month.
for(int col = 0; col<7; col++)
{
if (numberOfDays != 0)
{
dateObj = new MyDate();
m_calObj.nextDate();
if ((m_calObj.getDayOfMonth() == state.getcurrentDay()) && (state.getcurrentMonth()== m_calObj.getMonthInteger()) && (state.getcurrentYear() == m_calObj.getYear()))
dateObj.setFlag(1);
dateObj.setTodayDate(m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),m_calObj.getYear());
startTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),00,00,00,001);
endTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),23,59,00,000);
timeRange = TimeService.newTimeRange(startTime,endTime,true,true);
eventList = CalendarEventVectorObj.getEvents(timeRange);
dateObj.setEvents(eventList);
numberOfDays--;
monthObj.setDay(dateObj,row,col);
monthObj.setRow(row);
}
else // if it is not the end of week , complete the week wih days from next month.
{
if ((m_calObj.getDay_Of_Week(true))== 7) // if end of week, exit the loop
{
row = 7;
col = SECOND_PAGE_START_HOUR;
}
else // if it is not the end of week, complete with days from next month
{
dateObj = new MyDate();
m_calObj.nextDate();
dateObj.setTodayDate(m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),m_calObj.getYear());
startTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),00,00,00,001);
endTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),23,59,00,000);
timeRange = TimeService.newTimeRange(startTime,endTime,true,true);
eventList = CalendarEventVectorObj.getEvents(timeRange);
dateObj.setEvents(eventList);
monthObj.setDay(dateObj,row,col);
monthObj.setRow(row);
dateObj.setFlag(0);
}
}
}// end for
}// end for
return monthObj;
}
public void doAttachments(RunData rundata, Context context)
{
// get into helper mode with this helper tool
startHelper(rundata.getRequest(), "sakai.filepicker");
// setup the parameters for the helper
SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid());
CalendarActionState State = (CalendarActionState)getState( context, rundata, CalendarActionState.class );
int houri;
// put a the real attachments into the stats - let the helper update it directly if the user chooses to save their attachment editing.
List attachments = State.getAttachments();
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, attachments);
String hour = "";
hour = rundata.getParameters().getString("startHour");
String title ="";
title = rundata.getParameters().getString("activitytitle");
String minute = "";
minute = rundata.getParameters().getString("startMinute");
String dhour = "";
dhour = rundata.getParameters().getString("duHour");
String dminute = "";
dminute = rundata.getParameters().getString("duMinute");
String description = "";
description = rundata.getParameters().getString("description");
description = processFormattedTextFromBrowser(state, description);
String month = "";
month = rundata.getParameters().getString("month");
String day = "";
day = rundata.getParameters().getString("day");
String year = "";
year = rundata.getParameters().getString("yearSelect");
String timeType = "";
timeType = rundata.getParameters().getString("startAmpm");
String type = "";
type = rundata.getParameters().getString("eventType");
String location = "";
location = rundata.getParameters().getString("location");
readEventGroupForm(rundata, context);
// read the recurrence modification intention
String intentionStr = rundata.getParameters().getString("intention");
if (intentionStr == null) intentionStr = "";
Calendar calendarObj = null;
String calId = State.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".buildCustomizeContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".buildCustomizeContext(): " + e);
return;
}
Map addfieldsMap = new HashMap();
// Add any additional fields in the calendar.
customizeCalendarPage. loadAdditionalFieldsMapFromRunData(rundata, addfieldsMap, calendarObj);
if (timeType.equals("pm"))
{
if (Integer.parseInt(hour)>11)
houri = Integer.parseInt(hour);
else
houri = Integer.parseInt(hour)+12;
}
else if (timeType.equals("am") && Integer.parseInt(hour)==12)
{
houri = 24;
}
else
{
houri = Integer.parseInt(hour);
}
State.clearData();
State.setNewData(State.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
// **************** changed for the new attachment editor **************************
} // doAttachments
/**
* Action is used when doMonth requested in the menu
*/
public void doMonth(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
state.setState("month");
} // doMonth
/**
* Action is used when doDescription is requested when the user click on an event
*/
public void doDescription(RunData data, Context context)
{
CalendarEvent calendarEventObj = null;
Calendar calendarObj = null;
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
// "crack" the reference (a.k.a dereference, i.e. make a Reference)
// and get the event id and calendar reference
Reference ref = EntityManager.newReference(data.getParameters().getString(EVENT_REFERENCE_PARAMETER));
String eventId = ref.getId();
String calId = null;
if(CalendarService.REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
calId = CalendarService.calendarSubscriptionReference(ref.getContext(), ref.getContainer());
else
calId = CalendarService.calendarReference(ref.getContext(), ref.getContainer());
// %%% get the event object from the reference new Reference(data.getParameters().getString(EVENT_REFERENCE_PARAMETER)).getResource() -ggolden
try
{
calendarObj = CalendarService.getCalendar(calId);
try
{
calendarEventObj = calendarObj.getEvent(eventId);
TimeBreakdown b = calendarEventObj.getRange().firstTime().breakdownLocal();
sstate.setAttribute(STATE_YEAR, Integer.valueOf(b.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(b.getMonth()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(b.getDay()));
sstate.setAttribute(STATE_NAV_DIRECTION, STATE_CURRENT_ACT);
}
catch (IdUnusedException err)
{
// if this event doesn't exist, let user not go to the detail view
// set the state recorded ID as null
// show the alert message
M_log.debug(".IdUnusedException " + err);
state.setCalendarEventId("", "");
String errorCode = rb.getString("java.error");
addAlert(sstate, errorCode);
return;
}
catch (PermissionException err)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.debug(".PermissionException " + err);
return;
}
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
return;
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
return;
}
// store the state coming from, like day view, week view, month view or list view
String returnState = state.getState();
state.setPrevState(returnState);
state.setReturnState(returnState);
state.setState("description");
state.setAttachments(null);
state.setCalendarEventId(calId, eventId);
} // doDescription
/**
* Action is used when doGomonth requested in the year/list view
*/
public void doGomonth(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil();
m_calObj.setDay(stateYear, stateMonth, stateDay);
String month = "";
month = data.getParameters().getString("month");
m_calObj.setMonth(Integer.parseInt(month));
// if this function is called from list view
// the value of year must be caught also
int yearInt = m_calObj.getYear();
String currentState = state.getState();
if (currentState.equalsIgnoreCase("list"))
{
String year = "";
year = data.getParameters().getString("year");
yearInt = Integer.parseInt(year);
}
m_calObj.setDay(yearInt, m_calObj.getMonthInteger(), m_calObj.getDayOfMonth());
sstate.setAttribute(STATE_YEAR, Integer.valueOf(yearInt));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
state.setState("month");
} // doGomonth
/**
* Action is used when doGoyear requested in the list view
*/
public void doGoyear(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil();
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
m_calObj.setDay(stateYear, stateMonth, stateDay);
// catch the year value from the list view
int yearInt = m_calObj.getYear();
String currentState = state.getState();
if (currentState.equalsIgnoreCase("list"))
{
String year = "";
year = data.getParameters().getString("year");
yearInt = Integer.parseInt(year);
}
m_calObj.setDay(yearInt, m_calObj.getMonthInteger(), m_calObj.getDayOfMonth());
sstate.setAttribute(STATE_YEAR, Integer.valueOf(yearInt));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
state.setState("year");
} // doGoyear
/**
* Action is used when doOk is requested when user click on Back button
*/
public void doOk(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
// return to the state coming from
String returnState = state.getReturnState();
state.setState(returnState);
}
/**
* Action is used when the user click on the doRevise in the menu
*/
public void doRevise(RunData data, Context context)
{
CalendarEvent calendarEventObj = null;
Calendar calendarObj = null;
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String calId = state.getPrimaryCalendarReference();
state.setPrevState(state.getState());
state.setState("goToReviseCalendar");
state.setIsNewCalendar(false);
state.setfromAttachmentFlag("false");
sstate.setAttribute(FREQUENCY_SELECT, null);
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
state.clearData();
try
{
calendarObj = CalendarService.getCalendar(calId);
try
{
String eventId = state.getCalendarEventId();
// get the edit object, and lock the event for the furthur revise
CalendarEventEdit edit = calendarObj.getEditEvent(eventId, org.sakaiproject.calendar.api.CalendarService.EVENT_MODIFY_CALENDAR);
state.setEdit(edit);
state.setPrimaryCalendarEdit(edit);
calendarEventObj = calendarObj.getEvent(eventId);
state.setAttachments(calendarEventObj.getAttachments());
}
catch (IdUnusedException err)
{
// if this event doesn't exist, let user stay in activity view
// set the state recorded ID as null
// show the alert message
// reset the menu button display, no revise/delete
M_log.debug(".IdUnusedException " + err);
state.setState("description");
state.setCalendarEventId("", "");
String errorCode = rb.getString("java.alert.event");
addAlert(sstate, errorCode);
}
catch (PermissionException err)
{
M_log.debug(".PermissionException " + err);
}
catch (InUseException err)
{
M_log.debug(".InUseException " + err);
state.setState("description");
String errorCode = rb.getString("java.alert.eventbeing");
addAlert(sstate, errorCode);
}
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
}
} // doRevise
/**
* Handle the "continue" button on the schedule import wizard.
*/
public void doScheduleContinue(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
if ( SELECT_TYPE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) )
{
// If the type is Outlook or MeetingMaker, the next state is
// the "other" file select mode where we just select a file without
// all of the extra info on the generic import page.
String importType = data.getParameters ().getString(WIZARD_IMPORT_TYPE);
if ( CalendarImporterService.OUTLOOK_IMPORT.equals(importType) || CalendarImporterService.MEETINGMAKER_IMPORT.equals(importType) || CalendarImporterService.ICALENDAR_IMPORT.equals(importType))
{
if (CalendarImporterService.OUTLOOK_IMPORT.equals(importType))
{
state.setImportWizardType(CalendarImporterService.OUTLOOK_IMPORT);
state.setImportWizardState(OTHER_SELECT_FILE_IMPORT_WIZARD_STATE);
}
else if (CalendarImporterService.MEETINGMAKER_IMPORT.equals(importType))
{
state.setImportWizardType(CalendarImporterService.MEETINGMAKER_IMPORT);
state.setImportWizardState(OTHER_SELECT_FILE_IMPORT_WIZARD_STATE);
}
else
{
state.setImportWizardType(CalendarImporterService.ICALENDAR_IMPORT);
state.setImportWizardState(ICAL_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
else
{
// Remember the type we're importing
state.setImportWizardType(CalendarImporterService.CSV_IMPORT);
state.setImportWizardState(GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
else if ( GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) )
{
boolean importSucceeded = false;
// Do the import and send us to the confirm page
FileItem importFile = data.getParameters().getFileItem(WIZARD_IMPORT_FILE);
try
{
Map columnMap = CalendarImporterService.getDefaultColumnMap(CalendarImporterService.CSV_IMPORT);
String [] addFieldsCalendarArray = getCustomFieldsArray(state, sstate);
if ( addFieldsCalendarArray != null )
{
// Add all custom columns. Assume that there will be no
// name collisions. (Maybe a marginal assumption.)
for ( int i=0; i < addFieldsCalendarArray.length; i++)
{
columnMap.put(
addFieldsCalendarArray[i],
addFieldsCalendarArray[i]);
}
}
state.setWizardImportedEvents(
CalendarImporterService.doImport(
CalendarImporterService.CSV_IMPORT,
new ByteArrayInputStream(importFile.get()),
columnMap,
addFieldsCalendarArray));
importSucceeded = true;
}
catch (ImportException e)
{
addAlert(sstate, e.getMessage());
}
if ( importSucceeded )
{
// If all is well, go on to the confirmation page.
state.setImportWizardState(CONFIRM_IMPORT_WIZARD_STATE);
}
else
{
// If there are errors, send us back to the file selection page.
state.setImportWizardState(GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
else if ( OTHER_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) ||
ICAL_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) )
{
boolean importSucceeded = false;
// Do the import and send us to the confirm page
FileItem importFile = data.getParameters().getFileItem(WIZARD_IMPORT_FILE);
String [] addFieldsCalendarArray = getCustomFieldsArray(state, sstate);
try
{
state.setWizardImportedEvents(
CalendarImporterService.doImport(
state.getImportWizardType(),
new ByteArrayInputStream(importFile.get()),
null,
addFieldsCalendarArray));
importSucceeded = true;
}
catch (ImportException e)
{
addAlert(sstate, e.getMessage());
}
if ( importSucceeded )
{
// If all is well, go on to the confirmation page.
state.setImportWizardState(CONFIRM_IMPORT_WIZARD_STATE);
}
else
{
// If there are errors, send us back to the file selection page.
state.setImportWizardState(OTHER_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
else if ( CONFIRM_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) )
{
// If there are errors, send us back to Either
// the OTHER_SELECT_FILE or GENERIC_SELECT_FILE states.
// Otherwise, we're done.
List wizardCandidateEventList = state.getWizardImportedEvents();
// for group awareness - read user selection
readEventGroupForm(data, context);
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
Collection groupChoice = (Collection) sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS);
if ( scheduleTo != null &&
( scheduleTo.equals("site") ||
(scheduleTo.equals("groups") && groupChoice!=null && groupChoice.size()>0) ) )
{
for ( int i =0; i < wizardCandidateEventList.size(); i++ )
{
// The line numbers are one-based.
String selectionName = "eventSelected" + (i+1);
String selectdValue = data.getParameters().getString(selectionName);
if ( TRUE_STRING.equals(selectdValue) )
{
// Add the events
String calId = state.getPrimaryCalendarReference();
try
{
Calendar calendarObj = CalendarService.getCalendar(calId);
CalendarEvent event = (CalendarEvent) wizardCandidateEventList.get(i);
CalendarEventEdit newEvent = calendarObj.addEvent();
state.setEdit(newEvent);
if ( event.getDescriptionFormatted() != null )
{
newEvent.setDescriptionFormatted( event.getDescriptionFormatted() );
}
// Range must be present at this point, so don't check for null.
newEvent.setRange(event.getRange());
if ( event.getDisplayName() != null )
{
newEvent.setDisplayName(event.getDisplayName());
}
// The type must have either been set or defaulted by this point.
newEvent.setType(event.getType());
if ( event.getLocation() != null )
{
newEvent.setLocation(event.getLocation());
}
if ( event.getRecurrenceRule() != null )
{
newEvent.setRecurrenceRule(event.getRecurrenceRule());
}
String [] customFields = getCustomFieldsArray(state, sstate);
// Set the creator
newEvent.setCreator();
// Copy any custom fields.
if ( customFields != null )
{
for ( int j = 0; j < customFields.length; j++ )
{
newEvent.setField(customFields[j], event.getField(customFields[j]));
}
}
// group awareness
try
{
// for site event
if (scheduleTo.equals("site"))
{
newEvent.clearGroupAccess();
}
// for grouped event
else if (scheduleTo.equals("groups"))
{
Site site = SiteService.getSite(calendarObj.getContext());
// make a collection of Group objects from the collection of group ref strings
Collection groups = new Vector();
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupRef = (String) iGroups.next();
groups.add(site.getGroup(groupRef));
}
newEvent.setGroupAccess(groups, true);
}
}
catch (Exception e)
{
M_log.warn("doScheduleContinue: " + e);
}
calendarObj.commitEvent(newEvent);
state.setEdit(null);
}
catch (IdUnusedException e)
{
addAlert(sstate, e.getMessage());
M_log.debug(".doScheduleContinue(): " + e);
break;
}
catch (PermissionException e)
{
addAlert(sstate, e.getMessage());
M_log.debug(".doScheduleContinue(): " + e);
break;
}
}
}
// Cancel wizard mode.
doCancelImportWizard(data, context);
}
else
{
addAlert(sstate, rb.getString("java.alert.youchoosegroup"));
}
}
}
/**
* Get an array of custom field names (if any)
*/
private String[] getCustomFieldsArray(
CalendarActionState state,
SessionState sstate)
{
Calendar calendarObj = null;
try
{
calendarObj =
CalendarService.getCalendar(
state.getPrimaryCalendarReference());
}
catch (IdUnusedException e1)
{
// Ignore
}
catch (PermissionException e)
{
addAlert(sstate, e.getMessage());
}
// Get a current list of add fields. This is a comma-delimited string.
String[] addFieldsCalendarArray = null;
if ( calendarObj != null )
{
String addfieldsCalendars = calendarObj.getEventFields();
if (addfieldsCalendars != null)
{
addFieldsCalendarArray =
fieldStringToArray(
addfieldsCalendars,
ADDFIELDS_DELIMITER);
}
}
return addFieldsCalendarArray;
}
/**
* Handle the back button on the schedule import wizard
*/
public void doScheduleBack(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
if (GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState())
|| OTHER_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()))
{
state.setImportWizardState(SELECT_TYPE_IMPORT_WIZARD_STATE);
}
else
if (CONFIRM_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()))
{
if (CalendarImporterService.OUTLOOK_IMPORT.equals(state.getImportWizardType())
|| CalendarImporterService.MEETINGMAKER_IMPORT.equals(state.getImportWizardType()))
{
state.setImportWizardState(OTHER_SELECT_FILE_IMPORT_WIZARD_STATE);
}
else if (CalendarImporterService.ICALENDAR_IMPORT.equals(state.getImportWizardType()))
{
state.setImportWizardState(ICAL_SELECT_FILE_IMPORT_WIZARD_STATE);
}
else
{
state.setImportWizardState(GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
}
/**
* Called when the user cancels the import wizard.
*/
public void doCancelImportWizard(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
// Get rid of any events
state.setWizardImportedEvents(null);
// Make sure that we start the wizard at the beginning.
state.setImportWizardState(null);
// Return to the previous state.
state.setState(state.getPrevState());
}
/**
* Action is used when the docancel is requested when the user click on cancel in the new view
*/
public void doCancel(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Calendar calendarObj = null;
String currentState = state.getState();
String returnState = state.getReturnState();
if (currentState.equals(STATE_NEW))
{
// no need to release the lock.
// clear the saved recurring rule and the selected frequency
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, null);
}
else
if (currentState.equals(STATE_CUSTOMIZE_CALENDAR))
{
customizeCalendarPage.doCancel(data, context, state, getSessionState(data));
returnState=state.getPrevState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
returnState = "description";
}
}
else
if (currentState.equals(STATE_CALENDAR_SUBSCRIPTIONS))
{
calendarSubscriptionsPage.doCancel(data, context, state, getSessionState(data));
//returnState=state.getPrevState();
returnState=state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
returnState = "description";
}
}
else
if (currentState.equals(STATE_MERGE_CALENDARS))
{
mergedCalendarPage.doCancel(data, context, state, getSessionState(data));
returnState=state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
returnState = "description";
}
}
else // in revise view, state name varies
if ((currentState.equals("revise"))|| (currentState.equals("goToReviseCalendar")))
{
String calId = state.getPrimaryCalendarReference();
if (state.getPrimaryCalendarEdit() != null)
{
try
{
calendarObj = CalendarService.getCalendar(calId);
// the event is locked, now we need to release the lock
calendarObj.cancelEvent(state.getPrimaryCalendarEdit());
state.setPrimaryCalendarEdit(null);
state.setEdit(null);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
}
}
// clear the saved recurring rule and the selected frequency
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, null);
}
else if (currentState.equals(STATE_SET_FREQUENCY))// cancel at frequency editing page
{
returnState = (String)sstate.getAttribute(STATE_BEFORE_SET_RECURRENCE);
}
state.setState(returnState);
state.setAttachments(null);
} // doCancel
/**
* Action is used when the doBack is called when the user click on the back on the EventActivity view
*/
public void doBack(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Calendar calendarObj = null;
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
// the event is locked, now we need to release the lock
calendarObj.cancelEvent(state.getPrimaryCalendarEdit());
state.setPrimaryCalendarEdit(null);
state.setEdit(null);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
}
String returnState = state.getReturnState();
state.setState(returnState);
} // doBack
/**
* Action is used when the doDelete is called when the user click on delete in menu
*/
public void doDelete(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
CalendarEvent calendarEventObj = null;
Calendar calendarObj = null;
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
try
{
String eventId = state.getCalendarEventId();
// get the edit object, and lock the event for the furthur revise
CalendarEventEdit edit = calendarObj.getEditEvent(eventId,
org.sakaiproject.calendar.api.CalendarService.EVENT_REMOVE_CALENDAR);
state.setEdit(edit);
state.setPrimaryCalendarEdit(edit);
calendarEventObj = calendarObj.getEvent(eventId);
state.setAttachments(calendarEventObj.getAttachments());
// after deletion, it needs to go back to previous page
// if coming from description, it won't go back to description
// but the state one step ealier
String returnState = state.getState();
if (!returnState.equals("description"))
{
state.setReturnState(returnState);
}
state.setState("delete");
}
catch (IdUnusedException err)
{
// if this event doesn't exist, let user stay in activity view
// set the state recorded ID as null
// show the alert message
// reset the menu button display, no revise/delete
M_log.debug(".IdUnusedException " + err);
state.setState("description");
state.setCalendarEventId("", "");
String errorCode = rb.getString("java.alert.event");
addAlert(sstate, errorCode);
}
catch (PermissionException err)
{
M_log.debug(".PermissionException " + err);
}
catch (InUseException err)
{
M_log.debug(".InUseException delete" + err);
state.setState("description");
String errorCode = rb.getString("java.alert.eventbeing");
addAlert(sstate, errorCode);
}
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
}
} // doDelete
/**
* Action is used when the doConfirm is called when the user click on confirm to delete event in the delete view.
*/
public void doConfirm(RunData data, Context context)
{
Calendar calendarObj = null;
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
// read the intention field
String intentionStr = data.getParameters().getString("intention");
int intention = CalendarService.MOD_NA;
if ("t".equals(intentionStr)) intention = CalendarService.MOD_THIS;
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
CalendarEventEdit edit = state.getPrimaryCalendarEdit();
calendarObj.removeEvent(edit, intention);
state.setPrimaryCalendarEdit(null);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doConfirm(): " + e);
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.debug(".doConfirm(): " + e);
}
String returnState = state.getReturnState();
state.setState(returnState);
} // doConfirm
public void doView (RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String viewMode = data.getParameters ().getString("view");
if (viewMode.equalsIgnoreCase(rb.getString("java.byday")))
{
doMenueday(data, context);
}
else if (viewMode.equalsIgnoreCase(rb.getString("java.byweek")))
{
doWeek(data, context);
}
else if (viewMode.equalsIgnoreCase(rb.getString("java.bymonth")))
{
doMonth(data, context);
}
else if (viewMode.equalsIgnoreCase(rb.getString("java.byyear")))
{
doYear(data, context);
}
else if (viewMode.equalsIgnoreCase(rb.getString("java.listeve")))
{
doList(data, context);
}
state.setAttribute(STATE_SELECTED_VIEW, viewMode);
} // doView
/**
* Action doYear is requested when the user click on Year on menu
*/
public void doYear(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
state.setState("year");
} // doYear
/**
* Action doWeek is requested when the user click on the week item in then menu
*/
public void doWeek(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
state.setState("week");
} // doWeek
/**
* Action doDay is requested when the user click on the day item in the menue
*/
public void doDay(RunData data, Context context)
{
String year = null;
year = data.getParameters().getString("year");
String month = null;
month = data.getParameters().getString("month");
String day = null;
day = data.getParameters().getString("day");
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
sstate.setAttribute(STATE_YEAR, Integer.valueOf(Integer.parseInt(year)));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(Integer.parseInt(month)));
sstate.setAttribute(STATE_DAY, Integer.valueOf(Integer.parseInt(day)));
state.setPrevState(state.getState()); // remember the coming state from Month, Year or List
state.setState("day");
} // doDay
/**
* Action doToday is requested when the user click on "Go to today" button
*/
public void doToday(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
CalendarUtil m_calObj = new CalendarUtil();
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
m_calObj.setDay(b.getYear(), b.getMonth(), b.getDay());
sstate.setAttribute(STATE_YEAR, Integer.valueOf(b.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(b.getMonth()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(b.getDay()));
state.setState("day");
//for dropdown menu display purpose
sstate.setAttribute(STATE_SELECTED_VIEW, rb.getString("java.byday"));
} // doToday
/**
* Action doCustomDate is requested when the user specifies a start/end date
* to filter the list view.
*/
public void doCustomdate(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String sY = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_START_YEAR);
String sM = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_START_MONTH);
String sD = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_START_DAY);
String eY = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_END_YEAR);
String eM = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_END_MONTH);
String eD = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_END_DAY);
if (sM.length() == 1) sM = "0"+sM;
if (eM.length() == 1) eM = "0"+eM;
if (sD.length() == 1) sD = "0"+sD;
if (eD.length() == 1) eD = "0"+eD;
sY = sY.substring(2);
eY = eY.substring(2);
String startingDateStr = sM + "/" + sD + "/" + sY;
String endingDateStr = eM + "/" + eD + "/" + eY;
// Pass in a buffer for a possible error message.
StringBuilder errorMessage = new StringBuilder();
// Try to simultaneously set the start/end dates.
// If that doesn't work, add an error message.
if ( !state.getCalendarFilter().setStartAndEndListViewDates(startingDateStr, endingDateStr, errorMessage) )
{
addAlert(sstate, errorMessage.toString());
}
} // doCustomdate
/**
* Action doFilter is requested when the user clicks on the list box
* to select a filtering mode for the list view.
*/
public void doFilter(RunData data, Context context)
{
CalendarActionState state =
(CalendarActionState) getState(context,
data,
CalendarActionState.class);
state.getCalendarFilter().setListViewFilterMode(
data.getParameters().getString(TIME_FILTER_OPTION_VAR));
} // doFilter
/**
* Action is requestd when the user select day from the menu avilable in some views.
*/
public void doMenueday(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
state.setState("day");
} // doMenueday
/**
* Action is requsted when the user select day from menu in Activityevent view.
*/
public void doActivityday(RunData data, Context context)
{
CalendarEvent ce = null;
Calendar calendarObj = null;
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
CalendarUtil m_calObj = new CalendarUtil();
String id = state.getCalendarEventId();
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
ce = calendarObj.getEvent(id);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.warn(".doActivityday(): " + e);
return;
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.warn(".doActivityday(): " + e);
return;
}
TimeRange tr = ce.getRange();
Time t = tr.firstTime();
TimeBreakdown b = t.breakdownLocal();
m_calObj.setDay(b.getYear(),b.getMonth(),b.getDay()) ;
sstate.setAttribute(STATE_YEAR, Integer.valueOf(b.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(b.getMonth()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(b.getDay()));
state.setState("day");
} // doActivityDay
/**
* Action doNext is called when the user click on next button to move to next day, next week, next month or next year.
*/
public void doNext(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String currentstate = state.getState();
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil();
m_calObj.setDay(stateYear, stateMonth, stateDay);
if (currentstate.equals("month"))
{
m_calObj.getNextMonth();
}
if (currentstate.equals("year"))
{
m_calObj.setNextYear();
}
if (currentstate.equals("day"))
{
String date = m_calObj.getNextDate();
state.setnextDate(date);
}
if (currentstate.equals("week"))
{
m_calObj.setNextWeek();
}
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
} // doNext
/**
* Action doNextday is called when the user click on "Tomorrow" link in day view
*/
public void doNextday(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String currentstate = state.getState();
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil(); //null;
m_calObj.setDay(stateYear, stateMonth, stateDay);
if (currentstate.equals("day"))
{
String date = m_calObj.getNextDate();
state.setnextDate(date);
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
// if this function is called thru "tomorrow" link
// the default page has to be changed to "first"
state.setCurrentPage("first");
}
} // doNextday
/**
* Action doPrev is requested when the user click on the prev button to move into pre day, month, year, or week.
*/
public void doPrev(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil();
m_calObj.setDay(stateYear, stateMonth, stateDay);
String currentstate = state.getState();
if (currentstate.equals("month"))
{
m_calObj.getPrevMonth();
}
if (currentstate.equals("year"))
{
m_calObj.setPrevYear();
}
if (currentstate.equals("day"))
{
String date = m_calObj.getPrevDate();
state.setprevDate(date);
}
if (currentstate.equals("week"))
{
m_calObj.setPrevWeek();
}
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
} // doPrev
/**
* Action doPreday is called when the user click on "Yesterday" link in day view
*/
public void doPreday(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String currentstate = state.getState();
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil(); //null;
m_calObj.setDay(stateYear, stateMonth, stateDay);
if (currentstate.equals("day"))
{
String date = m_calObj.getPrevDate();
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
state.setprevDate(date);
// if this function is called thru "Yesterday" link, it goes the last page of yesterday
// the default page has to be changed to "third"
state.setCurrentPage("third");
}
} // doPreday
/**
* Enter the schedule import wizard
*/
public void doImport(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
// Remember the state prior to entering the wizard.
state.setPrevState(state.getState());
// Enter wizard mode.
state.setState(STATE_SCHEDULE_IMPORT);
} // doImport
/**
* Action doIcalExportName acts on a "Export" request
*/
public void doIcalExportName(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
// store the state coming from
String returnState = state.getState();
if ( ! returnState.equals("description") )
{
state.setReturnState(returnState);
}
state.clearData();
state.setAttachments(null);
state.setPrevState(state.getState());
state.setState("icalEx");
} // doIcalExportName
/**
* Action doIcalExport acts on a "Submit" request in the icalexport form
*/
public void doIcalExport(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String enable = StringUtils.trimToNull(data.getParameters().getString(FORM_ICAL_ENABLE));
String alias = StringUtils.trimToNull(data.getParameters().getString(FORM_ALIAS));
// this will verify that no invalid characters are used
if ( ! Validator.escapeResourceName(alias).equals(alias) )
{
addAlert(sstate, rb.getString("java.alert.invalidname"));
return;
}
String calId = state.getPrimaryCalendarReference();
Calendar calendarObj = null;
boolean oldExportEnabled = CalendarService.getExportEnabled(calId);
try
{
calendarObj = CalendarService.getCalendar(calId);
List aliasList = AliasService.getAliases( calendarObj.getReference() );
String oldAlias = null;
if ( ! aliasList.isEmpty() )
{
String aliasSplit[] = ((Alias)aliasList.get(0)).getId().split("\\.");
oldAlias = aliasSplit[0];
}
// Add the desired alias (if changed)
if ( alias != null && (oldAlias == null || !oldAlias.equals(alias)) )
{
// first, clear any alias set to this calendar
AliasService.removeTargetAliases(calendarObj.getReference());
alias += ".ics";
AliasService.setAlias(alias, calendarObj.getReference());
}
}
catch (IdUnusedException ie)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doIcalExport() Other: " + ie);
return;
}
catch (IdUsedException ue)
{
addAlert(sstate, rb.getString("java.alert.dupalias"));
return;
}
catch (PermissionException pe)
{
addAlert(sstate, rb.getString("java.alert.youdont"));
return;
}
catch (IdInvalidException e)
{
addAlert(sstate, rb.getString("java.alert.unknown"));
M_log.debug(".doIcalExport() Other: " + e);
return;
}
// enable/disable export (if changed)
if ( enable != null && !oldExportEnabled )
CalendarService.setExportEnabled( calId, true );
else if ( enable == null && oldExportEnabled )
CalendarService.setExportEnabled( calId, false );
String returnState = state.getReturnState();
state.setState(returnState);
} // doIcalExport
public void doNew(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
//clean group awareness state info
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
// store the state coming from
String returnState = state.getState();
if ( ! returnState.equals("description") )
{
state.setReturnState(returnState);
}
state.clearData();
state.setAttachments(null);
state.setPrevState(state.getState());
state.setState("new");
state.setCalendarEventId("", "");
state.setIsNewCalendar(true);
state.setIsPastAlertOff(true);
sstate.setAttribute(FREQUENCY_SELECT, null);
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
} // doNew
/**
* Read user inputs in announcement form
* @param data
* @param checkForm need to check form data or not
*/
protected void readEventGroupForm(RunData rundata, Context context)
{
String peid = ((JetspeedRunData) rundata).getJs_peid();
SessionState state =
((JetspeedRunData) rundata).getPortletSessionState(peid);
String scheduleTo = rundata.getParameters().getString("scheduleTo");
state.setAttribute(STATE_SCHEDULE_TO, scheduleTo);
if (scheduleTo.equals("groups"))
{
String[] groupChoice = rundata.getParameters().getStrings("selectedGroups");
if (groupChoice != null)
{
state.setAttribute(STATE_SCHEDULE_TO_GROUPS, new ArrayList(Arrays.asList(groupChoice)));
}
if (groupChoice== null || groupChoice.length == 0)
{
state.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
}
}
else
{
state.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
}
} // readEventGroupForm
/**
* Action doAdd is requested when the user click on the add in the new view to add an event into a calendar.
*/
public void doAdd(RunData runData, Context context)
{
CalendarUtil m_calObj = new CalendarUtil();// null;
Calendar calendarObj = null;
int houri;
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
m_calObj.setDay(stateYear, stateMonth, stateDay);
String hour = "";
hour = runData.getParameters().getString("startHour");
String title ="";
title = runData.getParameters().getString("activitytitle");
String minute = "";
minute = runData.getParameters().getString("startMinute");
String dhour = "";
dhour = runData.getParameters().getString("duHour");
String dminute = "";
dminute = runData.getParameters().getString("duMinute");
String description = "";
description = runData.getParameters().getString("description");
description = processFormattedTextFromBrowser(sstate, description);
String month = "";
month = runData.getParameters().getString("month");
String day = "";
day = runData.getParameters().getString("day");
String year = "";
year = runData.getParameters().getString("yearSelect");
String timeType = "";
timeType = runData.getParameters().getString("startAmpm");
String type = "";
type = runData.getParameters().getString("eventType");
String location = "";
location = runData.getParameters().getString("location");
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereisno"));
M_log.debug(".doAdd(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".doAdd(): " + e);
return;
}
// for section awareness - read user selection
readEventGroupForm(runData, context);
Map addfieldsMap = new HashMap();
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsMapFromRunData(runData, addfieldsMap, calendarObj);
if (timeType.equals("pm"))
{
if (Integer.parseInt(hour)>11)
houri = Integer.parseInt(hour);
else
houri = Integer.parseInt(hour)+12;
}
else if (timeType.equals("am") && Integer.parseInt(hour)==12)
{
// set 12 AM as the beginning of one day
houri = 0;
}
else
{
houri = Integer.parseInt(hour);
}
Time now_time = TimeService.newTime();
Time event_startTime = TimeService.newTimeLocal(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day), houri, Integer.parseInt(minute), 0, 0);
// conditions for an new event:
// 1st, frequency not touched, no save state rule or state freq (0, 0)
// --> non-recurring, no alert needed (0)
// 2st, frequency revised, there is a state-saved rule, and state-saved freq exists (1, 1)
// --> no matter if the start has been modified, compare the ending and starting date, show alert if needed (1)
// 3th, frequency revised, the state saved rule is null, but state-saved freq exists (0, 1)
// --> non-recurring, no alert needed (0)
// so the only possiblityto show the alert is under condistion 2.
boolean earlierEnding = false;
String freq = "";
if ((( freq = (String) sstate.getAttribute(FREQUENCY_SELECT))!= null)
&& (!(freq.equals(FREQ_ONCE))))
{
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
if (rule != null)
{
Time startingTime = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),houri,Integer.parseInt(minute),00,000);
Time endingTime = rule.getUntil();
if ((endingTime != null) && endingTime.before(startingTime))
earlierEnding = true;
} // if (rule != null)
} // if state saved freq is not null, and it not equals "once"
String intentionStr = ""; // there is no recurrence modification intention for new event
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
Collection groupChoice = (Collection) sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS);
if(title.length()==0)
{
String errorCode = rb.getString("java.pleasetitle");
addAlert(sstate, errorCode);
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
}
else if(hour.equals("100") || minute.equals("100"))
{
String errorCode = rb.getString("java.pleasetime");
addAlert(sstate, errorCode);
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
}
else if( earlierEnding ) // if ending date is earlier than the starting date, show alert
{
addAlert(sstate, rb.getString("java.theend") );
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
}
else if( event_startTime.before(now_time) && state.getIsPastAlertOff() )
{
// IsPastAlertOff
// true: no alert shown -> then show the alert, set false;
// false: Alert shown, if user click ADD - doAdd again -> accept it, set true, set alert empty;
String errorCode = rb.getString("java.alert.past");
addAlert(sstate, errorCode);
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
state.setIsPastAlertOff(false);
}
else if (!Validator.checkDate(Integer.parseInt(day), Integer.parseInt(month), Integer.parseInt(year)))
{
addAlert(sstate, rb.getString("date.invalid"));
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
}
else if (scheduleTo.equals("groups") && ((groupChoice == null) || (groupChoice.size() == 0)))
{
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
addAlert(sstate, rb.getString("java.alert.youchoosegroup"));
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
Time timeObj = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),houri,Integer.parseInt(minute),00,000);
long du = (((Integer.parseInt(dhour) * 60)*60)*1000) + ((Integer.parseInt(dminute)*60)*(1000));
Time endTime = TimeService.newTime(timeObj.getTime() + du);
boolean includeEndTime = false;
if (du==0)
{
includeEndTime = true;
}
TimeRange range = TimeService.newTimeRange(timeObj, endTime, true, includeEndTime);
List attachments = state.getAttachments();
// prepare to create the event
Collection groups = new Vector();
CalendarEvent.EventAccess access = CalendarEvent.EventAccess.GROUPED;
if (scheduleTo.equals("site")) access = CalendarEvent.EventAccess.SITE;
if (access == CalendarEvent.EventAccess.GROUPED)
{
// make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite(calendarObj.getContext());
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupRef = (String) iGroups.next();
groups.add(site.getGroup(groupRef));
}
}
// create the event = must create it with grouping / access to start with
CalendarEvent event = calendarObj.addEvent(range, title, "", type, location, access, groups, attachments);
// edit it further
CalendarEventEdit edit = calendarObj.getEditEvent(event.getId(),
org.sakaiproject.calendar.api.CalendarService.EVENT_ADD_CALENDAR);
edit.setDescriptionFormatted(description);
edit.setCreator();
String timeZone = TimeService.getLocalTimeZone().getID();
// we obtain the time zone where the event is created
// and save it as an event's property
// it is necessary to generate re-occurring events correctly
edit.setField("createdInTimeZone",timeZone);
setFields(edit, addfieldsMap);
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
// for a brand new event, there is no saved recurring rule
if (rule != null)
edit.setRecurrenceRule(rule);
else
edit.setRecurrenceRule(null);
// save it
calendarObj.commitEvent(edit);
state.setEdit(null);
state.setIsNewCalendar(false);
m_calObj.setDay(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day));
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
// clear the saved recurring rule and the selected frequency
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, null);
// set the return state to be the state before new/revise
String returnState = state.getReturnState();
if (returnState != null)
{
state.setState(returnState);
}
else
{
state.setState("week");
}
// if going back to week/day view, we need to know which slot to go
// -- the slot containing the starting time of the new added event
if (state.getState().equals("week")||state.getState().equals("day"))
{
Time timeObj_p1 = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),FIRST_PAGE_START_HOUR,00,00,000);
Time timeObj_p2 = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),SECOND_PAGE_START_HOUR,00,00,000);
Time timeObj_p3 = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),THIRD_PAGE_START_HOUR,00,00,000);
if (timeObj.after(timeObj_p2) && timeObj.before(timeObj_p3))
state.setCurrentPage("second");
else if (timeObj.before(timeObj_p2))
state.setCurrentPage("first");
else if (timeObj.after(timeObj_p3))
state.setCurrentPage("third");
}
// clean state
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doAdd(): " + e);
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.debug(".doAdd(): " + e);
}
catch (InUseException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doAdd(): " + e);
}
} // elseif
} // doAdd
/**
* Action doUpdateGroupView is requested when the user click on the Update button on the list view.
*/
public void doUpdateGroupView(RunData runData, Context context)
{
readEventGroupForm(runData, context);
//stay at the list view
}
/**
* Action doUpdate is requested when the user click on the save button on the revise screen.
*/
public void doUpdate(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
CalendarUtil m_calObj= new CalendarUtil();
// read the intention field
String intentionStr = runData.getParameters().getString("intention");
int intention = CalendarService.MOD_NA;
if ("t".equals(intentionStr)) intention = CalendarService.MOD_THIS;
// See if we're in the "options" state.
if (state.getState().equalsIgnoreCase(STATE_MERGE_CALENDARS))
{
mergedCalendarPage.doUpdate(runData, context, state, getSessionState(runData));
// ReturnState was set up above. Switch states now.
String returnState = state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
state.setState("description");
}
else
{
state.setReturnState("");
state.setState(returnState);
}
}
else
if (state.getState().equalsIgnoreCase(STATE_CALENDAR_SUBSCRIPTIONS))
{
calendarSubscriptionsPage.doUpdate(runData, context, state, getSessionState(runData));
// ReturnState was set up above. Switch states now.
String returnState = state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
state.setState("description");
}
else
{
state.setReturnState("");
state.setState(returnState);
}
}
else
if (state.getState().equalsIgnoreCase(STATE_CUSTOMIZE_CALENDAR))
{
customizeCalendarPage.doDeletefield( runData, context, state, getSessionState(runData));
customizeCalendarPage.doUpdate(runData, context, state, getSessionState(runData));
if (!state.getDelfieldAlertOff())
{
state.setState(CalendarAction.STATE_CUSTOMIZE_CALENDAR);
}
else
{
// ReturnState was set up above. Switch states now.
String returnState = state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
state.setState("description");
}
else
{
state.setReturnState("");
state.setState(returnState);
}
} // if (!state.getDelfieldAlertOff())
}
else
{
int houri;
Calendar calendarObj = null;
String hour = "";
hour = runData.getParameters().getString("startHour");
String title = "";
title = runData.getParameters().getString("activitytitle");
String minute = "";
minute = runData.getParameters().getString("startMinute");
String dhour = "";
dhour = runData.getParameters().getString("duHour");
String dminute = "";
dminute = runData.getParameters().getString("duMinute");
String description = "";
description = runData.getParameters().getString("description");
description = processFormattedTextFromBrowser(sstate, description);
String month = "";
month = runData.getParameters().getString("month");
String day = "";
day = runData.getParameters().getString("day");
String year = "";
year = runData.getParameters().getString("yearSelect");
String timeType = "";
timeType = runData.getParameters().getString("startAmpm");
String type = "";
type = runData.getParameters().getString("eventType");
String location = "";
location = runData.getParameters().getString("location");
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch (IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.theresisno"));
M_log.debug(".doUpdate() Other: " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".doUpdate() Other: " + e);
return;
}
// for group/section awareness
readEventGroupForm(runData, context);
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
Collection groupChoice = (Collection) sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS);
Map addfieldsMap = new HashMap();
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsMapFromRunData(runData, addfieldsMap, calendarObj);
if (timeType.equals("pm"))
{
if (Integer.parseInt(hour)>11)
houri = Integer.parseInt(hour);
else
houri = Integer.parseInt(hour)+12;
}
else if (timeType.equals("am") && Integer.parseInt(hour)==12)
{
houri = 0;
}
else
{
houri = Integer.parseInt(hour);
}
// conditions for an existing event: (if recurring event, if state-saved-rule exists, if state-saved-freq exists)
// 1st, an existing recurring one, just revised without frequency change, no save state rule or state freq (1, 0, 0)
// --> the starting time might has been modified, compare the ending and starting date, show alert if needed (1)
// 2st, and existing non-recurring one, just revised, no save state rule or state freq (0, 0, 0)
// --> non-recurring, no alert needed (0)
// 3rd, an existing recurring one, frequency revised, there is a state-saved rule, and state-saved freq exists (1, 1, 1)
// --> no matter if the start has been modified, compare the ending and starting date, show alert if needed (1)
// 4th, an existing recurring one, changed to non-recurring, the state saved rule is null, but state-saved freq exists (1, 0, 1)
// --> non-recurring, no alert needed (0)
// 5th, an existing non-recurring one, changed but kept as non-recurring, the state-saved rule is null, but state-saved freq exists (1, 0, 1)
// --> non-recurring, no alert needed (0)
// 6th, an existing recurring one, changed only the starting time, showed alert for ealier ending time,
// so the only possiblity to show the alert is under condistion 1 & 3: recurring one stays as recurring
boolean earlierEnding = false;
CalendarEventEdit edit = state.getPrimaryCalendarEdit();
if (edit != null)
{
RecurrenceRule editRule = edit.getRecurrenceRule();
if ( editRule != null)
{
String freq = (String) sstate.getAttribute(FREQUENCY_SELECT);
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
boolean comparisonNeeded = false;
if ((freq == null) && (rule == null))
{
// condition 1: recurring without frequency touched, but the starting might change
rule = editRule;
comparisonNeeded = true;
}
else if ((freq != null) && (!(freq.equals(FREQ_ONCE))))
{
// condition 3: recurring with frequency changed, and stays at recurring
comparisonNeeded = true;
}
if (comparisonNeeded) // if under condition 1 or 3
{
if (rule != null)
{
Time startingTime = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),houri,Integer.parseInt(minute),00,000);
Time endingTime = rule.getUntil();
if ((endingTime != null) && endingTime.before(startingTime))
earlierEnding = true;
} // if (editRule != null)
} // if (comparisonNeeded) // if under condition 1 or 3
} // if (calEvent.getRecurrenceRule() != null)
} // if (edit != null)
if(title.length()==0)
{
String errorCode = rb.getString("java.pleasetitle");
addAlert(sstate, errorCode);
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("revise");
}
/*
else if(hour.equals("0") && minute.equals("0"))
{
String errorCode = "Please enter a time";
addAlert(sstate, errorCode);
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap);
state.setState("revise");
}
*/
else if( earlierEnding ) // if ending date is earlier than the starting date, show alert
{
addAlert(sstate, rb.getString("java.theend") );
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("revise");
}
else if (!Validator.checkDate(Integer.parseInt(day), Integer.parseInt(month), Integer.parseInt(year)))
{
addAlert(sstate, rb.getString("date.invalid"));
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("revise");
}
else if (scheduleTo.equals("groups") && ((groupChoice == null) || (groupChoice.size() == 0)))
{
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("revise");
addAlert(sstate, rb.getString("java.alert.youchoosegroup"));
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
Time timeObj = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),houri,Integer.parseInt(minute),00,000);
long du = (((Integer.parseInt(dhour) * 60)*60)*1000) + ((Integer.parseInt(dminute)*60)*(1000));
Time endTime = TimeService.newTime(timeObj.getTime() + du);
boolean includeEndTime = false;
TimeRange range = null;
if (du==0)
{
range = TimeService.newTimeRange(timeObj);
}
else
{
range = TimeService.newTimeRange(timeObj, endTime, true, includeEndTime);
}
List attachments = state.getAttachments();
if (edit != null)
{
edit.setRange(range);
edit.setDescriptionFormatted(description);
edit.setDisplayName(title);
edit.setType(type);
edit.setLocation(location);
setFields(edit, addfieldsMap);
edit.replaceAttachments(attachments);
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
// conditions:
// 1st, an existing recurring one, just revised, no save state rule or state freq (0, 0)
// --> let edit rule untouched
// 2st, and existing non-recurring one, just revised, no save state rule or state freq (0, 0)
// --> let edit rule untouched
// 3rd, an existing recurring one, frequency revised, there is a state-saved rule, and state-saved freq exists (1, 1)
// --> replace the edit rule with state-saved rule
// 4th, and existing recurring one, changed to non-recurring, the state saved rule is null, but state-saved freq exists (0, 1)
// --> replace the edit rule with state-saved rule
// 5th, and existing non-recurring one, changed but kept as non-recurring, the state-saved rule is null, but state-saved freq exists (0, 1)
// --> replace the edit rule with state-saved rule
// so if the state-saved freq exists, replace the event rule
String freq = (String) sstate.getAttribute(FREQUENCY_SELECT);
if (sstate.getAttribute(FREQUENCY_SELECT) != null)
{
edit.setRecurrenceRule(rule);
}
// section awareness
try
{
// for site event
if (scheduleTo.equals("site"))
{
edit.clearGroupAccess();
}
// for grouped event
else if (scheduleTo.equals("groups"))
{
Site site = SiteService.getSite(calendarObj.getContext());
// make a collection of Group objects from the collection of group ref strings
Collection groups = new Vector();
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupRef = (String) iGroups.next();
groups.add(site.getGroup(groupRef));
}
edit.setGroupAccess(groups, edit.isUserOwner());
}
}
catch (Exception e)
{
M_log.warn("doUpdate", e);
}
calendarObj.commitEvent(edit, intention);
state.setPrimaryCalendarEdit(null);
state.setEdit(null);
state.setIsNewCalendar(false);
} // if (edit != null)
m_calObj.setDay(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day));
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
// clear the saved recurring rule and the selected frequency
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, null);
// set the return state as the one before new/revise
String returnState = state.getReturnState();
if (returnState != null)
{
state.setState(returnState);
}
else
{
state.setState("week");
}
// clean state
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doUpdate(): " + e);
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.debug(".doUpdate(): " + e);
} // try-catch
} // if(title.length()==0)
} // if (state.getState().equalsIgnoreCase(STATE_CUSTOMIZE_CALENDAR))
} // doUpdate
public void doDeletefield(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
customizeCalendarPage.doDeletefield( runData, context, state, getSessionState(runData));
}
/**
* Handle the button click to add a field to the list of optional attributes.
*/
public void doAddfield(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
customizeCalendarPage.doAddfield( runData, context, state, getSessionState(runData));
}
public void doAddSubscription(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
calendarSubscriptionsPage.doAddSubscription( runData, context, state, getSessionState(runData));
}
/**
* Action doNpagew is requested when the user click on the next arrow to move to the next page in the week view.
*/
public void doNpagew(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
if(state.getCurrentPage().equals("third"))
state.setCurrentPage("first");
else if(state.getCurrentPage().equals("second"))
state.setCurrentPage("third");
else if(state.getCurrentPage().equals("first"))
state.setCurrentPage("second");
state.setState("week");
}
/**
* Action doPpagew is requested when the user click on the previous arrow to move to the previous page in week view.
*/
public void doPpagew(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
if(state.getCurrentPage().equals("first"))
state.setCurrentPage("third");
else if (state.getCurrentPage().equals("third"))
state.setCurrentPage("second");
else if (state.getCurrentPage().equals("second"))
state.setCurrentPage("first");
state.setState("week");
}
/**
* Action doDpagen is requested when the user click on the next arrow to move to the next page in day view.
*/
public void doDpagen(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
if(state.getCurrentPage().equals("third"))
state.setCurrentPage("first");
else if(state.getCurrentPage().equals("second"))
state.setCurrentPage("third");
else if(state.getCurrentPage().equals("first"))
state.setCurrentPage("second");
state.setState("day");
}
/**
* Action doDpagep is requested when the user click on the upper arrow to move to the previous page in day view.
*/
public void doDpagep(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
if(state.getCurrentPage().equals("first"))
state.setCurrentPage("third");
else if (state.getCurrentPage().equals("third"))
state.setCurrentPage("second");
else if (state.getCurrentPage().equals("second"))
state.setCurrentPage("first");
state.setState("day");
} // doDpagep
/**
* Action doPrev_activity is requested when the user navigates to the previous message in the detailed view.
*/
public void doPrev_activity(RunData runData, Context context)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
sstate.setAttribute(STATE_NAV_DIRECTION, STATE_PREV_ACT);
} //doPrev_activity
/**
* Action doNext_activity is requested when the user navigates to the previous message in the detailed view.
*/
public void doNext_activity(RunData runData, Context context)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
sstate.setAttribute(STATE_NAV_DIRECTION, STATE_NEXT_ACT);
} // doNext_activity
/*
* detailNavigatorControl will handle the goNext/goPrev buttons in detailed view,
* as well as figure out the prev/next message if available
*/
private void navigatorContextControl(VelocityPortlet portlet, Context context, RunData runData, String direction)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
String eventId = state.getCalendarEventId();
List events = prepEventList(portlet, context, runData);
int index = -1;
int size = events.size();
for (int i=0; i<size; i++)
{
CalendarEvent e = (CalendarEvent) events.get(i);
if (e.getId().equals(eventId))
index = i;
}
// navigate to the previous activity
if (STATE_PREV_ACT.equals(direction) && index > 0)
{
CalendarEvent ce = (CalendarEvent) events.get(--index);
Reference ref = EntityManager.newReference(ce.getReference());
eventId = ref.getId();
String calId = null;
if(CalendarService.REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
calId = CalendarService.calendarSubscriptionReference(ref.getContext(), ref.getContainer());
else
calId = CalendarService.calendarReference(ref.getContext(), ref.getContainer());
state.setCalendarEventId(calId, eventId);
state.setAttachments(null);
}
// navigate to the next activity
else if (STATE_NEXT_ACT.equals(direction) && index < size-1)
{
CalendarEvent ce = (CalendarEvent) events.get(++index);
Reference ref = EntityManager.newReference(ce.getReference());
eventId = ref.getId();
String calId = null;
if(CalendarService.REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
calId = CalendarService.calendarSubscriptionReference(ref.getContext(), ref.getContainer());
else
calId = CalendarService.calendarReference(ref.getContext(), ref.getContainer());
state.setCalendarEventId(calId, eventId);
state.setAttachments(null);
}
if (index > 0)
sstate.setAttribute(STATE_PREV_ACT, "");
else
sstate.removeAttribute(STATE_PREV_ACT);
if(index < size-1)
sstate.setAttribute(STATE_NEXT_ACT, "");
else
sstate.removeAttribute(STATE_NEXT_ACT);
sstate.setAttribute(STATE_NAV_DIRECTION, STATE_CURRENT_ACT);
} // navigatorControl
private CalendarEventVector prepEventList(VelocityPortlet portlet,
Context context,
RunData runData)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
TimeRange fullTimeRange =
TimeService.newTimeRange(
TimeService.newTimeLocal(
CalendarFilter.LIST_VIEW_STARTING_YEAR,
1,
1,
0,
0,
0,
0),
TimeService.newTimeLocal(
CalendarFilter.LIST_VIEW_ENDING_YEAR,
12,
31,
23,
59,
59,
999));
// We need to get events from all calendars for the full time range.
CalendarEventVector masterEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
fullTimeRange);
sstate.setAttribute(STATE_EVENTS_LIST, masterEventVectorObj);
return masterEventVectorObj;
} // eventList
/**
* Action is to parse the function calls
**/
public void doParse(RunData data, Context context)
{
ParameterParser params = data.getParameters();
String source = params.getString("source");
if (source.equalsIgnoreCase("new"))
{
// create new event
doNew(data, context);
}
else if (source.equalsIgnoreCase("revise"))
{
// revise an event
doRevise(data, context);
}
else if (source.equalsIgnoreCase("delete"))
{
// delete event
doDelete(data, context);
}
else if (source.equalsIgnoreCase("byday"))
{
// view by day
doMenueday(data, context);
}
else if (source.equalsIgnoreCase("byweek"))
{
// view by week
doWeek(data, context);
}
else if (source.equalsIgnoreCase("bymonth"))
{
// view by month
doMonth(data, context);
}
else if (source.equalsIgnoreCase("byyear"))
{
// view by year
doYear(data, context);
}
else if (source.equalsIgnoreCase("prev"))
{
// go previous
doPrev(data, context);
}
else if (source.equalsIgnoreCase("next"))
{
// go next
doNext(data, context);
}
else if (source.equalsIgnoreCase("bylist"))
{
// view by list
doList(data, context);
}
} // doParse
/**
* Action doList is requested when the user click on the list in the toolbar
*/
public void doList(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
String sM;
String eM;
String sD;
String eD;
String sY;
String eY;
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
String prevState = state.getState().toString();
if (prevState.equals("day"))
{
sY = Integer.valueOf(calObj.getYear()).toString();
sM = Integer.valueOf(calObj.getMonthInteger()).toString();
sD = Integer.valueOf(calObj.getDayOfMonth()).toString();
eY = Integer.valueOf(calObj.getYear()).toString();
eM = Integer.valueOf(calObj.getMonthInteger()).toString();
eD = Integer.valueOf(calObj.getDayOfMonth()).toString();
}
else if (prevState.equals("week"))
{
int dayofweek = calObj.getDay_Of_Week(true);
calObj.setPrevDate(dayofweek-1);
sY = Integer.valueOf(calObj.getYear()).toString();
sM = Integer.valueOf(calObj.getMonthInteger()).toString();
sD = Integer.valueOf(calObj.getDayOfMonth()).toString();
for(int i = 0; i<6; i++)
{
calObj.getNextDate();
}
eY = Integer.valueOf(calObj.getYear()).toString();
eM = Integer.valueOf(calObj.getMonthInteger()).toString();
eD = Integer.valueOf(calObj.getDayOfMonth()).toString();
}
else if (prevState.equals("month"))
{
sY = Integer.valueOf(calObj.getYear()).toString();
sM = Integer.valueOf(calObj.getMonthInteger()).toString();
sD = String.valueOf("1");
calObj.setDay(stateYear, stateMonth, 1);
GregorianCalendar cal = new GregorianCalendar(calObj.getYear(), calObj.getMonthInteger()-1, 1);
int daysInMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
for (int i=1; i<daysInMonth; i++)
calObj.getNextDate();
eY = Integer.valueOf(calObj.getYear()).toString();
eM = Integer.valueOf(calObj.getMonthInteger()).toString();
eD = Integer.valueOf(calObj.getDayOfMonth()).toString();
}
else
{
// for other conditions: show the current year
sY = Integer.valueOf(stateYear).toString();
sM = "1";
sD = "1";
eY = Integer.valueOf(stateYear).toString();
eM = "12";
eD = "31";
}
if (sM.length() == 1) sM = "0"+sM;
if (eM.length() == 1) eM = "0"+eM;
if (sD.length() == 1) sD = "0"+sD;
if (eD.length() == 1) eD = "0"+eD;
sY = sY.substring(2);
eY = eY.substring(2);
String startingDateStr = sM + "/" + sD + "/" + sY;
String endingDateStr = eM + "/" + eD + "/" + eY;
state.getCalendarFilter().setListViewFilterMode(CalendarFilter.SHOW_CUSTOM_RANGE);
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
// Pass in a buffer for a possible error message.
StringBuilder errorMessage = new StringBuilder();
// Try to simultaneously set the start/end dates.
// If that doesn't work, add an error message.
if ( !state.getCalendarFilter().setStartAndEndListViewDates(startingDateStr, endingDateStr, errorMessage) )
{
addAlert(sstate, errorMessage.toString());
}
state.setState("list");
} // doList
/**
* Action doSort_by_date_toggle is requested when the user click on the sorting icon in the list view
*/
public void doSort_by_date_toggle(RunData data, Context context)
{
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
boolean dateDsc = sstate.getAttribute(STATE_DATE_SORT_DSC) != null;
if (dateDsc)
sstate.removeAttribute(STATE_DATE_SORT_DSC);
else
sstate.setAttribute(STATE_DATE_SORT_DSC, "");
} // doSort_by_date_toggle
/**
* Handle a request from the "merge" page to merge calendars from other groups into this group's Schedule display.
*/
public void doMerge(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
mergedCalendarPage.doMerge( runData, context, state, getSessionState(runData));
} // doMerge
/**
* Handle a request from the "subscriptions" page to subscribe calendars.
*/
public void doSubscriptions(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
calendarSubscriptionsPage.doSubscriptions( runData, context, state, getSessionState(runData));
} // doMerge
/**
* Handle a request to set options.
*/
public void doCustomize(RunData runData, Context context)
{
CalendarActionState state =
(CalendarActionState) getState(context,
runData,
CalendarActionState.class);
customizeCalendarPage.doCustomize(
runData,
context,
state,
getSessionState(runData));
}
/**
* Build the context for showing list view
*/
protected void buildListContext(VelocityPortlet portlet, Context context, RunData runData, CalendarActionState state)
{
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
context.put("tlang",rb);
context.put("config",configProps);
MyMonth monthObj2 = null;
MyDate dateObj1 = new MyDate();
CalendarEventVector calendarEventVectorObj = null;
boolean allowed = false;
LinkedHashMap yearMap = new LinkedHashMap();
// Initialize month format object
if ( monthFormat == null )
{
monthFormat = NumberFormat.getInstance(new ResourceLoader().getLocale());
monthFormat.setMinimumIntegerDigits(2);
}
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
// Set up list filtering information in the context.
context.put(TIME_FILTER_OPTION_VAR, state.getCalendarFilter().getListViewFilterMode());
//
// Fill in the custom dates
//
String sDate; // starting date
String eDate; // ending date
java.util.Calendar userCal = java.util.Calendar.getInstance();
context.put("ddStartYear", Integer.valueOf(userCal.get(java.util.Calendar.YEAR) - 3));
context.put("ddEndYear", Integer.valueOf(userCal.get(java.util.Calendar.YEAR) + 4));
String sM;
String eM;
String sD;
String eD;
String sY;
String eY;
if (state.getCalendarFilter().isCustomListViewDates() )
{
sDate = state.getCalendarFilter().getStartingListViewDateString();
eDate = state.getCalendarFilter().getEndingListViewDateString();
sM = sDate.substring(0, 2);
eM = eDate.substring(0, 2);
sD = sDate.substring(3, 5);
eD = eDate.substring(3, 5);
sY = "20" + sDate.substring(6);
eY = "20" + eDate.substring(6);
}
else
{
//default to current week
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
TimeRange weekRange = getWeekTimeRange( calObj );
sD = String.valueOf( weekRange.firstTime().breakdownLocal().getDay() );
sY = String.valueOf( weekRange.firstTime().breakdownLocal().getYear() );
sM = monthFormat.format( weekRange.firstTime().breakdownLocal().getMonth() );
eD = String.valueOf( weekRange.lastTime().breakdownLocal().getDay() );
eY = String.valueOf( weekRange.lastTime().breakdownLocal().getYear() );
eM = monthFormat.format( weekRange.lastTime().breakdownLocal().getMonth() );
}
context.put(TIME_FILTER_SETTING_CUSTOM_START_YEAR, Integer.valueOf(sY));
context.put(TIME_FILTER_SETTING_CUSTOM_END_YEAR, Integer.valueOf(eY));
context.put(TIME_FILTER_SETTING_CUSTOM_START_MONTH, Integer.valueOf(sM));
context.put(TIME_FILTER_SETTING_CUSTOM_END_MONTH, Integer.valueOf(eM));
context.put(TIME_FILTER_SETTING_CUSTOM_START_DAY, Integer.valueOf(sD));
context.put(TIME_FILTER_SETTING_CUSTOM_END_DAY, Integer.valueOf(eD));
CalendarUtil calObj= new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
// fill this month object with all days avilable for this month
if (CalendarService.allowGetCalendar(state.getPrimaryCalendarReference())== false)
{
allowed = false;
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
calendarEventVectorObj = new CalendarEventVector();
}
else
{
try
{
allowed = CalendarService.getCalendar(state.getPrimaryCalendarReference()).allowAddEvent();
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.therenoactv"));
M_log.debug(".buildMonthContext(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildMonthContext(): " + e);
}
}
int yearInt, monthInt, dayInt=1;
TimeRange fullTimeRange =
TimeService.newTimeRange(
TimeService.newTimeLocal(
CalendarFilter.LIST_VIEW_STARTING_YEAR,
1,
1,
0,
0,
0,
0),
TimeService.newTimeLocal(
CalendarFilter.LIST_VIEW_ENDING_YEAR,
12,
31,
23,
59,
59,
999));
// We need to get events from all calendars for the full time range.
CalendarEventVector masterEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
fullTimeRange);
// groups awareness - filtering
String calId = state.getPrimaryCalendarReference();
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
try
{
Calendar calendarObj = CalendarService.getCalendar(calId);
context.put("cal", calendarObj);
if (scheduleTo != null && scheduleTo.length() != 0)
{
context.put("scheduleTo", scheduleTo);
}
else
{
if (calendarObj.allowGetEvents())
{
// default to make site selection
context.put("scheduleTo", "site");
}
else if (calendarObj.getGroupsAllowGetEvent().size() > 0)
{
// to group otherwise
context.put("scheduleTo", "groups");
}
}
Collection groups = calendarObj.getGroupsAllowGetEvent();
if (groups.size() > 0)
{
context.put("groups", groups);
}
List schToGroups = (List)(sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS));
context.put("scheduleToGroups", schToGroups);
CalendarEventVector newEventVectorObj = new CalendarEventVector();
newEventVectorObj.addAll(masterEventVectorObj);
for (Iterator i = masterEventVectorObj.iterator(); i.hasNext();)
{
CalendarEvent e = (CalendarEvent)(i.next());
String origSiteId = (CalendarService.getCalendar(e.getCalendarReference())).getContext();
if (!origSiteId.equals(ToolManager.getCurrentPlacement().getContext()))
{
context.put("fromColExist", Boolean.TRUE);
}
if ((schToGroups != null) && (schToGroups.size()>0))
{
boolean eventInGroup = false;
for (Iterator j = schToGroups.iterator(); j.hasNext();)
{
String groupRangeForDisplay = e.getGroupRangeForDisplay(calendarObj);
String groupId = j.next().toString();
Site site = SiteService.getSite(calendarObj.getContext());
Group group = site.getGroup(groupId);
if (groupRangeForDisplay.equals("")||groupRangeForDisplay.equals("site"))
eventInGroup = true;
if (groupRangeForDisplay.indexOf(group.getTitle()) != -1)
eventInGroup = true;
}
if ( ! eventInGroup )
newEventVectorObj.remove(e);
}
}
if ((schToGroups != null) && (schToGroups.size()>0))
{
masterEventVectorObj.clear();
masterEventVectorObj.addAll(newEventVectorObj);
}
}
catch(IdUnusedException e)
{
M_log.debug(".buildListContext(): " + e);
}
catch (PermissionException e)
{
M_log.debug(".buildListContext(): " + e);
}
boolean dateDsc = sstate.getAttribute(STATE_DATE_SORT_DSC) != null;
context.put("currentDateSortAsc", Boolean.valueOf(!dateDsc));
if (!dateDsc)
{
for (yearInt = CalendarFilter.LIST_VIEW_STARTING_YEAR;
yearInt <= CalendarFilter.LIST_VIEW_ENDING_YEAR;
yearInt++)
{
Vector arrayOfMonths = new Vector(20);
for(monthInt = 1; monthInt <13; monthInt++)
{
CalendarUtil AcalObj = new CalendarUtil();
monthObj2 = new MyMonth();
AcalObj.setDay(yearInt, monthInt, dayInt);
dateObj1.setTodayDate(AcalObj.getMonthInteger(),AcalObj.getDayOfMonth(),AcalObj.getYear());
// Get the events for the particular month from the
// master list of events.
calendarEventVectorObj =
new CalendarEventVector(
state.getCalendarFilter().filterEvents(
masterEventVectorObj.getEvents(
getMonthTimeRange((CalendarUtil) AcalObj))));
if (!calendarEventVectorObj.isEmpty())
{
AcalObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
monthObj2 = calMonth(monthInt, (CalendarUtil)AcalObj, state, calendarEventVectorObj);
AcalObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
if (!calendarEventVectorObj.isEmpty())
arrayOfMonths.addElement(monthObj2);
}
}
if (!arrayOfMonths.isEmpty())
yearMap.put(Integer.valueOf(yearInt), arrayOfMonths.iterator());
}
}
else
{
for (yearInt = CalendarFilter.LIST_VIEW_ENDING_YEAR;
yearInt >= CalendarFilter.LIST_VIEW_STARTING_YEAR;
yearInt--)
{
Vector arrayOfMonths = new Vector(20);
for(monthInt = 12; monthInt >=1; monthInt--)
{
CalendarUtil AcalObj = new CalendarUtil();
monthObj2 = new MyMonth();
AcalObj.setDay(yearInt, monthInt, dayInt);
dateObj1.setTodayDate(AcalObj.getMonthInteger(),AcalObj.getDayOfMonth(),AcalObj.getYear());
// Get the events for the particular month from the
// master list of events.
calendarEventVectorObj =
new CalendarEventVector(
state.getCalendarFilter().filterEvents(
masterEventVectorObj.getEvents(
getMonthTimeRange((CalendarUtil) AcalObj))));
if (!calendarEventVectorObj.isEmpty())
{
AcalObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
monthObj2 = calMonth(monthInt, (CalendarUtil)AcalObj, state, calendarEventVectorObj);
AcalObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
if (!calendarEventVectorObj.isEmpty())
arrayOfMonths.addElement(monthObj2);
}
}
if (!arrayOfMonths.isEmpty())
yearMap.put(Integer.valueOf(yearInt), arrayOfMonths.iterator());
}
}
context.put("yearMap", yearMap);
int row = 5;
context.put("row",Integer.valueOf(row));
calObj.setDay(stateYear, stateMonth, stateDay);
// using session state stored year-month-day to replace saving calObj
sstate.setAttribute(STATE_YEAR, Integer.valueOf(stateYear));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(stateMonth));
sstate.setAttribute(STATE_DAY, Integer.valueOf(stateDay));
state.setState("list");
context.put("date",dateObj1);
// output CalendarService and SiteService
context.put("CalendarService", CalendarService.getInstance());
context.put("SiteService", SiteService.getInstance());
context.put("Context", ToolManager.getCurrentPlacement().getContext());
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
// added by zqian for toolbar
context.put("allow_new", Boolean.valueOf(allowed));
context.put("allow_delete", Boolean.valueOf(false));
context.put("allow_revise", Boolean.valueOf(false));
context.put("realDate", TimeService.newTime());
context.put("selectedView", rb.getString("java.listeve"));
context.put("tlang",rb);
context.put("config",configProps);
context.put("calendarFormattedText", new CalendarFormattedText());
} // buildListContext
private void buildPrintMenu( VelocityPortlet portlet,
RunData runData,
CalendarActionState state,
Menu bar_print )
{
String stateName = state.getState();
if (stateName.equals("month")
|| stateName.equals("day")
|| stateName.equals("week")
|| stateName.equals("list"))
{
int printType = CalendarService.UNKNOWN_VIEW;
String timeRangeString = "";
TimeRange dailyStartTime = null;
int startHour = 0, startMinute = 0;
int endHour = 0, endMinute = 0;
int endSeconds = 0, endMSeconds = 0;
//
// Depending what page we are on, there will be
// a different time of the day on which we start.
//
if (state.getCurrentPage().equals("first"))
{
startHour = FIRST_PAGE_START_HOUR;
endHour = startHour + NUMBER_HOURS_PER_PAGE_FOR_WEEK_VIEW;
}
else
if (state.getCurrentPage().equals("second"))
{
startHour = SECOND_PAGE_START_HOUR;
endHour = startHour + NUMBER_HOURS_PER_PAGE_FOR_WEEK_VIEW;
}
else
if (state.getCurrentPage().equals("third"))
{
startHour = THIRD_PAGE_START_HOUR;
endHour = startHour + NUMBER_HOURS_PER_PAGE_FOR_WEEK_VIEW;
}
else
{
startHour = 0;
endHour = startHour + HOURS_PER_DAY;
}
// If we go over twenty-four hours, stop at the end of the day.
if ( endHour >= HOURS_PER_DAY )
{
endHour = 23;
endMinute = 59;
endSeconds = 59;
endMSeconds = 999;
}
dailyStartTime =
TimeService.newTimeRange(
TimeService.newTimeLocal(
state.getcurrentYear(),
state.getcurrentMonth(),
state.getcurrentDay(),
startHour,
startMinute,
00,
000),
TimeService.newTimeLocal(
state.getcurrentYear(),
state.getcurrentMonth(),
state.getcurrentDay(),
endHour,
endMinute,
endSeconds,
endMSeconds));
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
if (stateName.equals("month"))
{
printType = CalendarService.MONTH_VIEW;
timeRangeString = getMonthTimeRange(calObj).toString();
}
else
if (stateName.equals("day"))
{
printType = CalendarService.DAY_VIEW;
timeRangeString =
getDayTimeRange(
calObj.getYear(),
calObj.getMonthInteger(),
calObj.getDayOfMonth())
.toString();
}
else
if (stateName.equals("week"))
{
printType = CalendarService.WEEK_VIEW;
timeRangeString = getWeekTimeRange(calObj).toString();
}
else
if (stateName.equals("list"))
{
printType = CalendarService.LIST_VIEW;
timeRangeString =
TimeService
.newTimeRange(
state.getCalendarFilter().getListViewStartingTime(),
state.getCalendarFilter().getListViewEndingTime())
.toString();
}
// set the actual list of calendars into the user's session:
List calRefList = getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab());
SessionManager.getCurrentSession().setAttribute(CalendarService.SESSION_CALENDAR_LIST,calRefList);
Reference calendarRef = EntityManager.newReference(state.getPrimaryCalendarReference());
// Add PDF print menu option
String accessPointUrl = ServerConfigurationService.getAccessUrl()
+ CalendarService.calendarPdfReference(calendarRef.getContext(),
calendarRef.getId(),
printType,
timeRangeString,
UserDirectoryService.getCurrentUser().getDisplayName(),
dailyStartTime);
bar_print.add(new MenuEntry(rb.getString("java.print"), "").setUrl(accessPointUrl));
}
}
/**
* Build the menu.
*/
private void buildMenu( VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state,
boolean allow_new,
boolean allow_delete,
boolean allow_revise,
boolean allow_merge_calendars,
boolean allow_modify_calendar_properties,
boolean allow_import_export,
boolean allow_subscribe)
{
Menu bar = new MenuImpl(portlet, runData, "CalendarAction");
String status = state.getState();
if ((status.equals("day"))
||(status.equals("week"))
||(status.equals("month"))
||(status.equals("year"))
||(status.equals("list")))
{
allow_revise = false;
allow_delete = false;
}
bar.add( new MenuEntry(rb.getString("java.new"), null, allow_new, MenuItem.CHECKED_NA, "doNew") );
//
// See if we are allowed to merge items.
//
bar.add( new MenuEntry(mergedCalendarPage.getButtonText(), null, allow_merge_calendars, MenuItem.CHECKED_NA, mergedCalendarPage.getButtonHandlerID()) );
// See if we are allowed to import items.
if ( allow_import_export )
{
bar.add( new MenuEntry(rb.getString("java.import"), null, allow_new, MenuItem.CHECKED_NA, "doImport") );
}
// See if we are allowed to export items.
String calId = state.getPrimaryCalendarReference();
if ( (allow_import_export || CalendarService.getExportEnabled(calId)) &&
ServerConfigurationService.getBoolean("ical.experimental",false))
{
bar.add( new MenuEntry(rb.getString("java.export"), null, allow_new, MenuItem.CHECKED_NA, "doIcalExportName") );
}
// See if we are allowed to configure external calendar subscriptions
if ( allow_subscribe && ServerConfigurationService.getBoolean(ExternalCalendarSubscriptionService.SAK_PROP_EXTSUBSCRIPTIONS_ENABLED,false))
{
bar.add( new MenuEntry(rb.getString("java.subscriptions"), null, allow_subscribe, MenuItem.CHECKED_NA, "doSubscriptions") );
}
//2nd menu bar for the PDF print only
Menu bar_print = new MenuImpl(portlet, runData, "CalendarAction");
buildPrintMenu( portlet, runData, state, bar_print );
if (SiteService.allowUpdateSite(ToolManager.getCurrentPlacement().getContext()))
{
bar_print.add( new MenuEntry(rb.getString("java.default_view"), "doDefaultview") );
}
bar.add( new MenuEntry(customizeCalendarPage.getButtonText(), null, allow_modify_calendar_properties, MenuItem.CHECKED_NA, customizeCalendarPage.getButtonHandlerID()) );
// add permissions, if allowed
//SAK-21684 don't show in myworkspace site unless super user.
String currentSiteId = ToolManager.getCurrentPlacement().getContext();
if (SecurityService.isSuperUser() || (SiteService.allowUpdateSite(currentSiteId) && !SiteService.isUserSite(currentSiteId)))
{
bar.add( new MenuEntry(rb.getString("java.permissions"), "doPermissions") );
}
// Set menu state attribute
SessionState stateForMenus = ((JetspeedRunData)runData).getPortletSessionState(portlet.getID());
stateForMenus.setAttribute(MenuItem.STATE_MENU, bar);
context.put("tlang",rb);
context.put("config",configProps);
context.put(Menu.CONTEXT_MENU, bar);
context.put("menu_PDF", bar_print);
context.put(Menu.CONTEXT_ACTION, "CalendarAction");
} // buildMenu
/**
* Align the edit's fields with these values.
* @param edit The CalendarEventEdit.
* @param values The map of name-value pairs.
*/
private void setFields(CalendarEventEdit edit, Map values)
{
Set<Entry<String, String>> keys = values.entrySet();
for (Iterator<Entry<String, String>> it = keys.iterator(); it.hasNext(); )
{
Entry entry = it.next();
String name = (String)entry.getKey() ;
String value = (String) entry.getValue();
edit.setField(name, value);
}
} // setFields
/** Set current calendar view as tool default
**/
public void doDefaultview( RunData rundata, Context context )
{
CalendarActionState state = (CalendarActionState)getState(context, rundata, CalendarActionState.class);
SessionState sstate = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid());
String view = state.getState();
Placement placement = ToolManager.getCurrentPlacement();
placement.getPlacementConfig().setProperty(
PORTLET_CONFIG_DEFAULT_VIEW, view );
saveOptions();
addAlert(sstate, rb.getString("java.alert.default_view"));
}
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context)
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
// setup the parameters for the helper
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
CalendarActionState cstate = (CalendarActionState) getState(context, data, CalendarActionState.class);
String calendarRefStr = cstate.getPrimaryCalendarReference();
Reference calendarRef = EntityManager.newReference(calendarRefStr);
String siteRef = SiteService.siteReference(calendarRef.getContext());
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("java.set")
+ SiteService.getSiteDisplay(calendarRef.getContext()));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "calendar.");
// ... pass the resource loader object
ResourceLoader pRb = new ResourceLoader("permissions");
HashMap<String, String> pRbValues = new HashMap<String, String>();
for (Iterator<Entry<String, String>> iKeys = pRb.entrySet().iterator();iKeys.hasNext();)
{
Entry entry = iKeys.next();
String key = (String)entry.getKey();
pRbValues.put(key, (String)entry.getValue());
}
state.setAttribute("permissionDescriptions", pRbValues);
String groupAware = ToolManager.getCurrentTool().getRegisteredConfig().getProperty("groupAware");
state.setAttribute("groupAware", groupAware != null?Boolean.valueOf(groupAware):Boolean.FALSE);
state.removeAttribute("menu"); //Menu not required in the permission view
}
/**
* Action doFrequency is requested when "set Frequency" button is clicked in new/revise page
*/
public void doEditfrequency(RunData rundata, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, rundata, CalendarActionState.class);
String peid = ((JetspeedRunData)rundata).getJs_peid();
SessionState sstate = ((JetspeedRunData)rundata).getPortletSessionState(peid);
String calId = "";
Calendar calendarObj = null;
String eventId = state.getCalendarEventId();
try
{
calId = state.getPrimaryCalendarReference();
calendarObj = CalendarService.getCalendar(calId);
String freq = (String) sstate.getAttribute(FREQUENCY_SELECT);
// conditions when the doEditfrequency is called:
// 1. new/existing event, in create-new/revise page first time: freq is null.
// It has been set to null in both doNew & doRevise.
// Make sure to re-set the freq in this step.
// 2. new/existing event, back from cancel/save-frequency-setting page: freq is sth, because when
// the first time doEditfrequency is called, there is a freq set up already
// condition 1 -
if ((freq == null)||(freq.equals("")))
{
// if a new event
if ((eventId == null)||(eventId.equals("")))
{
// set the frequency to be default "once", rule to be null
sstate.setAttribute(FREQUENCY_SELECT, DEFAULT_FREQ);
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
}
else
{ // exiting event
try
{
if(calendarObj.allowGetEvents())
{
CalendarEvent event = calendarObj.getEvent(eventId);
RecurrenceRule rule = event.getRecurrenceRule();
if (rule == null)
{
// not recurring, i.e., frequency is once
sstate.setAttribute(FREQUENCY_SELECT, DEFAULT_FREQ);
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
}
else
{
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, rule);
sstate.setAttribute(FREQUENCY_SELECT, rule.getFrequencyDescription());
} // if (rule==null)
} // if allowGetEvents
} // try
catch(IdUnusedException e)
{
M_log.debug(".doEditfrequency() + calendarObj.getEvent(): " + e);
} // try-cath
} // if ((eventId == null)||(eventId.equals(""))
}
else
{
// condition 2, state freq is set, and state rule is set already
}
} // try
catch(IdUnusedException e)
{
M_log.debug(".doEditfrequency() + CalendarService.getCalendar(): " + e);
}
catch (PermissionException e)
{
M_log.debug(".doEditfrequency() + CalendarService.getCalendar(): " + e);
}
int houri;
String hour = "";
hour = rundata.getParameters().getString("startHour");
String title ="";
title = rundata.getParameters().getString("activitytitle");
String minute = "";
minute = rundata.getParameters().getString("startMinute");
String dhour = "";
dhour = rundata.getParameters().getString("duHour");
String dminute = "";
dminute = rundata.getParameters().getString("duMinute");
String description = "";
description = rundata.getParameters().getString("description");
description = processFormattedTextFromBrowser(sstate, description);
String month = "";
month = rundata.getParameters().getString("month");
String day = "";
day = rundata.getParameters().getString("day");
String year = "";
year = rundata.getParameters().getString("yearSelect");
String timeType = "";
timeType = rundata.getParameters().getString("startAmpm");
String type = "";
type = rundata.getParameters().getString("eventType");
String location = "";
location = rundata.getParameters().getString("location");
readEventGroupForm(rundata, context);
// read the recurrence modification intention
String intentionStr = rundata.getParameters().getString("intention");
if (intentionStr == null) intentionStr = "";
try
{
calendarObj = CalendarService.getCalendar(calId);
Map addfieldsMap = new HashMap();
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsMapFromRunData(rundata, addfieldsMap, calendarObj);
if (timeType.equals("pm"))
{
if (Integer.parseInt(hour)>11)
houri = Integer.parseInt(hour);
else
houri = Integer.parseInt(hour)+12;
}
else if (timeType.equals("am") && Integer.parseInt(hour)==12)
{
houri = 24;
}
else
{
houri = Integer.parseInt(hour);
}
state.clearData();
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".doEditfrequency(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".doEditfrequency(): " + e);
}
sstate.setAttribute(STATE_BEFORE_SET_RECURRENCE, state.getState());
state.setState(STATE_SET_FREQUENCY);
} // doEditfrequency
/**
* Action doChangefrequency is requested when the user changes the selected frequency at the frequency setting page
*/
public void doChangefrequency(RunData rundata, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, rundata, CalendarActionState.class);
String freqSelect = rundata.getParameters().getString(FREQUENCY_SELECT);
String peid = ((JetspeedRunData)rundata).getJs_peid();
SessionState sstate = ((JetspeedRunData)rundata).getPortletSessionState(peid);
sstate.setAttribute(FREQUENCY_SELECT, freqSelect);
//TEMP_FREQ_SELECT only works for the onchange javascript function when user changes the frequency selection
// and will be discarded when buildFrequecyContext has caught its value
sstate.setAttribute(TEMP_FREQ_SELECT, freqSelect);
state.setState(STATE_SET_FREQUENCY);
} // doChangefrequency
/**
* Action doSavefrequency is requested when the user click on the "Save" button in the frequency setting page
*/
public void doSavefrequency(RunData rundata, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, rundata, CalendarActionState.class);
String peid = ((JetspeedRunData)rundata).getJs_peid();
SessionState sstate = ((JetspeedRunData)rundata).getPortletSessionState(peid);
String returnState = (String)sstate.getAttribute(STATE_BEFORE_SET_RECURRENCE);
// if by any chance, the returnState is not available,
// then reset it as either "new" or "revise".
// For new event, the id is null or empty string
if ((returnState == null)||(returnState.equals("")))
{
String eventId = state.getCalendarEventId();
if ((eventId == null) || (eventId.equals("")))
returnState = "new";
else
returnState = "revise";
}
state.setState(returnState);
// get the current frequency setting the user has selected - daily, weekly, or etc.
String freq = (String) rundata.getParameters().getString(FREQUENCY_SELECT);
if ((freq == null)||(freq.equals(FREQ_ONCE)))
{
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, FREQ_ONCE);
}
else
{
sstate.setAttribute(FREQUENCY_SELECT, freq);
String interval = rundata.getParameters().getString("interval");
int intInterval = Integer.parseInt(interval);
RecurrenceRule rule = null;
String CountOrTill = rundata.getParameters().getString("CountOrTill");
if (CountOrTill.equals("Never"))
{
rule = CalendarService.newRecurrence(freq, intInterval);
}
else if (CountOrTill.equals("Till"))
{
String endMonth = rundata.getParameters().getString("endMonth");
String endDay = rundata.getParameters().getString("endDay");
String endYear = rundata.getParameters().getString("endYear");
int intEndMonth = Integer.parseInt(endMonth);
int intEndDay = Integer.parseInt(endDay);
int intEndYear = Integer.parseInt(endYear);
//construct time object from individual ints, Local Time values
Time endTime = TimeService.newTimeLocal(intEndYear, intEndMonth, intEndDay, 23, 59, 59, 999);
rule = CalendarService.newRecurrence(freq, intInterval, endTime);
}
else if (CountOrTill.equals("Count"))
{
String count = rundata.getParameters().getString("count");
int intCount = Integer.parseInt(count);
rule = CalendarService.newRecurrence(freq, intInterval, intCount);
}
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, rule);
}
} // doSavefrequency
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata)
{
super.initState(state, portlet, rundata);
if (contentHostingService == null)
{
contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
}
if (entityBroker == null)
{
entityBroker = (EntityBroker) ComponentManager.get("org.sakaiproject.entitybroker.EntityBroker");
}
// retrieve the state from state object
CalendarActionState calState = (CalendarActionState)getState( portlet, rundata, CalendarActionState.class );
setPrimaryCalendarReferenceInState(portlet, calState);
// setup the observer to notify our main panel
if (state.getAttribute(STATE_INITED) == null)
{
state.setAttribute(STATE_INITED,STATE_INITED);
// load all calendar channels (either primary or merged calendars)
MergedList mergedCalendarList =
loadChannels( calState.getPrimaryCalendarReference(),
portlet.getPortletConfig().getInitParameter(PORTLET_CONFIG_PARM_MERGED_CALENDARS),
null );
}
// Initialize configuration properties
InputStream inConfig = null;
try
{
if ( configProps == null )
{
configProps = new Properties();
inConfig = this.getClass().getResourceAsStream("calendar.config");
configProps.load(inConfig);
}
}
catch ( IOException e )
{
M_log.warn("unable to load calendar.config: " + e);
}
finally {
if(inConfig != null)
{
try
{
inConfig.close();
}
catch(IOException e1)
{
M_log.warn("I(O error occurred while closing 'inConfig' inputstream", e1);
}
}
}
} // initState
/**
* Takes an array of tokens and converts into separator-separated string.
*
* @param String[] The array of strings input.
* @param String The string separator.
* @return String A string containing tokens separated by seperator.
*/
protected String arrayToString(String[] array, String separators)
{
StringBuilder sb = new StringBuilder("");
String empty = "";
if (array == null)
return empty;
if (separators == null)
separators = ",";
for (int ix=0; ix < array.length; ix++)
{
if (array[ix] != null && !array[ix].equals(""))
{
sb.append(array[ix] + separators);
}
}
String str = sb.toString();
if (!str.equals(""))
{
str = str.substring(0, (str.length() - separators.length()));
}
return str;
}
/**
* Processes formatted text that is coming back from the browser
* (from the formatted text editing widget).
* @param state Used to pass in any user-visible alerts or errors when processing the text
* @param strFromBrowser The string from the browser
* @return The formatted text
*/
private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser)
{
StringBuilder alertMsg = new StringBuilder();
try
{
String text = FormattedText.processFormattedText(strFromBrowser, alertMsg);
if (alertMsg.length() > 0) addAlert(state, alertMsg.toString());
return text;
}
catch (Exception e)
{
M_log.warn(" ", e);
return strFromBrowser;
}
}
/**
* Access the current month as a string.
* @return the current month as a string.
*/
public String calendarUtilGetMonth(int l_month)
{
// get the index for the month. Note, the index is increased by 1, u need to deduct 1 first
String[] months = new String [] { rb.getString("jan"),rb.getString("feb"),rb.getString("mar"),
rb.getString("apr"), rb.getString("may"), rb.getString("jun"),
rb.getString("jul"), rb.getString("aug"), rb.getString("sep"),
rb.getString("oct"), rb.getString("nov"), rb.getString("dec") };
if (l_month >12)
{
return rb.getString("java.thismonth");
}
return months[l_month-1];
} // getMonth
/**
* Get the name of the day.
* @return the name of the day.
*/
private String calendarUtilGetDay(int dayofweek)
{
String[] l_ndays = new String[] {rb.getString("day.sunday"),rb.getString("day.monday"),
rb.getString("day.tuesday"),rb.getString("day.wednesday"),rb.getString("day.thursday")
,rb.getString("day.friday"),rb.getString("day.saturday")};
if ( dayofweek > 7 )
{
dayofweek = 1;
}
else if ( dayofweek <=0 )
{
dayofweek = 7;
}
return l_ndays[dayofweek - 1];
} // calendarUtilGetDay
} // CalendarAction
| calendar/calendar-tool/tool/src/java/org/sakaiproject/calendar/tool/CalendarAction.java | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-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.sakaiproject.calendar.tool;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.Vector;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEdit;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarEventEdit;
import org.sakaiproject.calendar.api.CalendarEventVector;
import org.sakaiproject.calendar.api.ExternalSubscription;
import org.sakaiproject.calendar.api.RecurrenceRule;
import org.sakaiproject.calendar.cover.CalendarImporterService;
import org.sakaiproject.calendar.cover.CalendarService;
import org.sakaiproject.calendar.cover.ExternalCalendarSubscriptionService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.VelocityPortletStateAction;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.content.cover.ContentTypeImageService;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.entitybroker.EntityBroker;
import org.sakaiproject.entitybroker.entityprovider.extension.ActionReturn;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.ImportException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.api.TimeRange;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.CalendarChannelReferenceMaker;
import org.sakaiproject.util.CalendarReferenceToChannelConverter;
import org.sakaiproject.util.CalendarUtil;
import org.sakaiproject.util.EntryProvider;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.MergedList;
import org.sakaiproject.util.MergedListEntryProviderFixedListWrapper;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.Validator;
/**
* The schedule tool.
*/
public class CalendarAction
extends VelocityPortletStateAction
{
/**
*
*/
private static final long serialVersionUID = -8571818334710261359L;
/** Our logger. */
private static Log M_log = LogFactory.getLog(CalendarAction.class);
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("calendar");
// configuration properties (initialized in initState()
Properties configProps = null;
private static final String ALERT_MSG_KEY = "alertMessage";
private static final String CONFIRM_IMPORT_WIZARD_STATE = "CONFIRM_IMPORT";
private static final String WIZARD_IMPORT_FILE = "importFile";
private static final String GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE = "GENERIC_SELECT_FILE";
private static final String OTHER_SELECT_FILE_IMPORT_WIZARD_STATE = "OTHER_SELECT_FILE";
private static final String ICAL_SELECT_FILE_IMPORT_WIZARD_STATE = "ICAL_SELECT_FILE";
private static final String WIZARD_IMPORT_TYPE = "importType";
private static final String SELECT_TYPE_IMPORT_WIZARD_STATE = "SELECT_TYPE";
private static final String IMPORT_WIZARD_SELECT_TYPE_STATE = SELECT_TYPE_IMPORT_WIZARD_STATE;
private static final String STATE_SCHEDULE_IMPORT = "scheduleImport";
private static final String CALENDAR_INIT_PARAMETER = "calendar";
private static final int HOURS_PER_DAY = 24;
private static final int NUMBER_HOURS_PER_PAGE_FOR_WEEK_VIEW = 10;
private static final int FIRST_PAGE_START_HOUR = 0;
private static final int SECOND_PAGE_START_HOUR = 8;
private static final int THIRD_PAGE_START_HOUR = 14;
private static final String STATE_YEAR = "calYear";
private static final String STATE_MONTH = "calMonth";
private static final String STATE_DAY = "calDay";
private static final String STATE_REVISE = "revise";
private static final String STATE_SET_FREQUENCY = "setFrequency";
private static final String FREQUENCY_SELECT = "frequencySelect";
private static final String TEMP_FREQ_SELECT = "tempFrequencySelect";
private static final String FREQ_ONCE = "once";
private static final String DEFAULT_FREQ = FREQ_ONCE;
private static final String SSTATE__RECURRING_RULE = "rule";
private static final String STATE_BEFORE_SET_RECURRENCE = "state_before_set_recurrence";
private final static String TIME_FILTER_OPTION_VAR = "timeFilterOption";
private final static String TIME_FILTER_SETTING_CUSTOM_START_DATE_VAR = "customStartDate";
private final static String TIME_FILTER_SETTING_CUSTOM_END_DATE_VAR = "customEndDate";
private final static String TIME_FILTER_SETTING_CUSTOM_START_YEAR = "customStartYear";
private final static String TIME_FILTER_SETTING_CUSTOM_END_YEAR = "customEndYear";
private final static String TIME_FILTER_SETTING_CUSTOM_START_MONTH = "customStartMonth";
private final static String TIME_FILTER_SETTING_CUSTOM_END_MONTH = "customEndMonth";
private final static String TIME_FILTER_SETTING_CUSTOM_START_DAY = "customStartDay";
private final static String TIME_FILTER_SETTING_CUSTOM_END_DAY = "customEndDay";
private static final String FORM_ALIAS = "alias";
private static final String FORM_ICAL_ENABLE = "icalEnable";
/** The attachments from assignment */
private static final String ATTACHMENTS = "Assignment.attachments";
/** state selected view */
private static final String STATE_SELECTED_VIEW = "state_selected_view";
/** DELIMITER used to separate the list of custom fields for this calendar. */
private final static String ADDFIELDS_DELIMITER = "_,_";
protected final static String STATE_INITED = "calendar.state.inited";
/** for sorting in list view */
private static final String STATE_DATE_SORT_DSC = "dateSortedDsc";
// for group/section awareness
private final static String STATE_SCHEDULE_TO = "scheduleTo";
private final static String STATE_SCHEDULE_TO_GROUPS = "scheduleToGroups";
private static final String STATE_SELECTED_GROUPS_FILTER = "groups_filters";
private ContentHostingService contentHostingService;
private EntityBroker entityBroker;
// tbd fix shared definition from org.sakaiproject.assignment.api.AssignmentEntityProvider
private final static String ASSN_ENTITY_ID = "assignment";
private final static String ASSN_ENTITY_ACTION = "deepLink";
private final static String ASSN_ENTITY_PREFIX = File.separator+ASSN_ENTITY_ID+File.separator+ASSN_ENTITY_ACTION+File.separator;
private NumberFormat monthFormat = null;
/**
* Converts a string that is used to store additional attribute fields to an array of strings.
*/
private String[] fieldStringToArray(String addfields_str, String delimiter)
{
String [] fields = addfields_str.split(delimiter);
List destStringList = new ArrayList();
// Don't copy empty fields.
for ( int i=0; i < fields.length; i++)
{
if ( fields[i].length() > 0 )
{
destStringList.add(fields[i]);
}
}
return (String[]) destStringList.toArray(new String[destStringList.size()]);
}
/**
* Enable or disable the observer
* @param enable if true, the observer is enabled, if false, it is disabled
*/
protected void enableObserver(SessionState sstate, boolean enable)
{
if (enable)
{
enableObservers(sstate);
}
else
{
disableObservers(sstate);
}
}
// myYear class
public class MyYear
{
private MyMonth[][] yearArray;
private int year;
private MyMonth m;
public MyYear()
{
yearArray = new MyMonth[4][3];
m = null;
year = 0;
}
public void setMonth(MyMonth m, int x, int y)
{
yearArray[x][y] = m;
}
public MyMonth getMonth(int x, int y)
{
m = yearArray[x][y];
return (m);
}
public void setYear(int y)
{
year = y;
}
public int getYear()
{
return year;
}
}// myYear class
// my week
public class MyWeek
{
private MyDate[] week;
private int weekOfMonth;
public MyWeek()
{
week = new MyDate[7];
weekOfMonth = 0;
}
public void setWeek(int i, MyDate date)
{
week[i] = date;
}
public MyDate getWeek(int i)
{
return week[i];
}
public String getWeekRange()
{
String range = null;
range = week[0].getTodayDate() + " "+ "-" + " " + week[6].getTodayDate();
return range;
}
public void setWeekOfMonth(int w)
{
weekOfMonth = w;
}
public int getWeekOfMonth()
{
return weekOfMonth+1;
}
}
// myMonth class
public class MyMonth
{
private MyDate[][] monthArray;
private MyDate result;
private String monthName;
private int month;
private int row;
private int numberOfDaysInMonth;
public MyMonth()
{
result = null;
monthArray = new MyDate[6][7];
month = 0;
row = 0;
numberOfDaysInMonth=0;
}
public void setRow(int r)
{
row = r;
}
public int getRow()
{
return row;
}
public void setNumberOfDaysInMonth(int daysInMonth)
{
numberOfDaysInMonth = daysInMonth;
}
public int getNumberOfDaysInMonth()
{
return numberOfDaysInMonth;
}
public void setDay(MyDate d,int x, int y)
{
monthArray[x][y] = d;
}
public MyDate getDay(int x,int y)
{
result = monthArray[x][y];
return (result);
}
public void setMonthName(String name)
{
monthName = name;
}
public String getMonthName()
{
return monthName;
}
public void setMonth(int m)
{
month = m;
}
public int getMonth()
{
return month;
}
}// myMonth
// myDay class
public class MyDay
{
private String m_data; // data will have the days in the month
private String m_attachment_data; // data need to be displayed and attached, currently
// this si a string and it can be any structure in the future.
private int m_flag; // 0 if it is not a current date , 1 if it is a current date
private int day;
private int year;
private int month;
private String dayName; // name for each day
private String todayDate;
public MyDay()
{
m_data = "";
m_flag = 0;
m_attachment_data = "";
day = 0;
dayName = "";
todayDate = "";
}
public void setDay(int d)
{
day = d;
}
public int getDay()
{
return day;
}
public void setFlag(int flag)
{
m_flag = flag;
}
public void setData(String data)
{
m_data = data;
}
public int getFlag()
{
return m_flag;
}
public String getData()
{
return(m_data);
}
public void setAttachment(String data)
{
m_attachment_data = data;
}
public String getAttachment()
{
return(m_attachment_data);
}
public void setDayName(String dname)
{
dayName = dname;
}
public String getDayName()
{
return dayName;
}
public void setTodayDate(String date)
{
todayDate = date;
}
public String getTodayDate()
{
return todayDate;
}
public void setYear(int y)
{
year = y;
}
public int getYear()
{
return year;
}
public void setMonth(int m)
{
month = m;
}
public int getMonth()
{
return month;
}
}// myDay class
public class EventClass
{
private String displayName;
private long firstTime;
private String eventId;
public EventClass()
{
displayName = "";
firstTime = 0;
}
public void setDisplayName(String name)
{
displayName = name;
}
public void setFirstTime(long time)
{
firstTime = time;
}
public String getDisplayName()
{
return displayName;
}
public long getfirstTime()
{
return firstTime;
}
public void setId(String id)
{
eventId = id;
}
public String getId()
{
return eventId;
}
}
public class EventDisplayClass
{
private CalendarEvent calendareventobj;
private boolean eventConflict;
private int eventPosition;
public EventDisplayClass()
{
eventConflict = false;
calendareventobj = null;
eventPosition = 0;
}
public void setEvent(CalendarEvent ce, boolean eventconf, int pos)
{
eventConflict = eventconf;
calendareventobj = ce;
eventPosition = pos;
}
public void setFlag(boolean conflict)
{
eventConflict = conflict;
}
public void setPosition(int position)
{
eventPosition = position;
}
public int getPosition()
{
return eventPosition;
}
public CalendarEvent getEvent()
{
return calendareventobj;
}
public boolean getFlag()
{
return eventConflict;
}
}
public class MyDate
{
private MyDay day = null;
private MyMonth month = null;
private MyYear year = null;
private String dayName = "";
private Iterator iteratorObj = null;
private int flag = -1;
private Vector eVector;
public MyDate()
{
day = new MyDay();
month = new MyMonth();
year = new MyYear();
}
public void setTodayDate(int m, int d, int y)
{
day.setDay(d);
month.setMonth(m);
year.setYear(y);
}
public void setNumberOfDaysInMonth(int daysInMonth)
{
month.setNumberOfDaysInMonth(daysInMonth);
}
public int getNumberOfDaysInMonth()
{
return month.getNumberOfDaysInMonth();
}
public String getTodayDate()
{
DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT);
return f.format(new Date(year.getYear(), month.getMonth(), day.getDay()));
}
public void setFlag(int i)
{
flag = i;
}
public int getFlag()
{
return flag;
}
public void setDayName(String name)
{
dayName = name;
}
public void setNameOfMonth(String name)
{
month.setMonthName(name);
}
public String getDayName()
{
return dayName;
}
public int getDay()
{
return day.getDay();
}
public int getMonth()
{
return month.getMonth();
}
public String getNameOfMonth()
{
return month.getMonthName();
}
public int getYear()
{
return year.getYear();
}
public void setEventBerWeek(Vector eventVector)
{
eVector = eventVector;
}
public void setEventBerDay(Vector eventVector)
{
eVector = eventVector;
}
public Vector getEventsBerDay(int index)
{
Vector dayVector = new Vector();
if (eVector != null)
dayVector = (Vector)eVector.get(index);
if (dayVector == null)
dayVector = new Vector();
return dayVector;
}
public Vector getEventsBerWeek(int index)
{
Vector dayVector = new Vector();
if (eVector != null)
dayVector = (Vector)eVector.get(index);
if (dayVector == null)
dayVector = new Vector();
return dayVector;
}
public void setEvents(Iterator t)
{
iteratorObj = t;
}
public Vector getEvents()
{
Vector vectorObj = new Vector();
int i = 0;
if (iteratorObj!=null)
{
while(iteratorObj.hasNext())
{
vectorObj.add(i,iteratorObj.next());
i++;
}
}
return vectorObj;
}
}
public class Helper
{
private int numberOfActivity =0;
public int getduration(long x, int b)
{
Long l = Long.valueOf(x);
int v = l.intValue()/3600000;
return v;
}
public int getFractionIn(long x,int b)
{
Long ll = Long.valueOf(x);
int y = (ll.intValue()-(b*3600000));
int m = (y/60000);
return m;
}
public CalendarEvent getActivity(Vector mm)
{
int size = mm.size();
numberOfActivity = size;
CalendarEvent activityEvent,event=null;
if(size>0)
{
activityEvent = (CalendarEvent)mm.elementAt(0);
long temp = activityEvent.getRange().duration();
for(int i =0; i<size;i++)
{
activityEvent = (CalendarEvent)mm.elementAt(i);
if(temp<activityEvent.getRange().duration())
{
temp = activityEvent.getRange().duration();
event = activityEvent;
}
}
}
else
event = null;
return event;
}
public int getNumberOfActivity()
{
return numberOfActivity;
}
public int getInt(long x)
{
Long temp = Long.valueOf(x);
return(temp.intValue());
}
}
/**
* An inner class that can be initiated to perform text formatting
*/
public class CalendarFormattedText
{
// constructor
public CalendarFormattedText()
{
}
/**
* Use of FormattedText object's trimFormattedText function.
* @param formattedText The formatted text to trim
* @param maxNumOfChars The maximum number of displayed characters in the returned trimmed formatted text.
* @return String A String to hold the trimmed formatted text
*/
public String trimFormattedText(String formattedText, int maxNumOfChars)
{
StringBuilder sb = new StringBuilder();
FormattedText.trimFormattedText(formattedText, maxNumOfChars, sb);
return sb.toString();
}
}
/**
* Given a current date via the calendarUtil paramter, returns a TimeRange for the week.
*/
public TimeRange getWeekTimeRange(
CalendarUtil calendarUtil)
{
int dayofweek = 0;
dayofweek = calendarUtil.getDay_Of_Week(true)-1;
int tempCurrentYear = calendarUtil.getYear();
int tempCurrentMonth = calendarUtil.getMonthInteger();
int tempCurrentDay = calendarUtil.getDayOfMonth();
calendarUtil.setPrevDate(dayofweek);
Time startTime = TimeService.newTimeLocal(calendarUtil.getYear(),calendarUtil.getMonthInteger(),calendarUtil.getDayOfMonth(),00,00,00,000);
calendarUtil.setDay(tempCurrentYear,tempCurrentMonth,tempCurrentDay);
dayofweek = calendarUtil.getDay_Of_Week(true);
if (dayofweek< 7)
{
for(int i = dayofweek; i<=6;i++)
{
calendarUtil.nextDate();
}
}
Time endTime = TimeService.newTimeLocal(calendarUtil.getYear(),calendarUtil.getMonthInteger(),calendarUtil.getDayOfMonth(),23,59,59,000);
return TimeService.newTimeRange(startTime,endTime,true,true);
} // etWeekTimeRange
/**
* Given a current date via the calendarUtil paramter, returns a TimeRange for the month.
*/
public TimeRange getMonthTimeRange(CalendarUtil calendarUtil)
{
int dayofweek = 0;
calendarUtil.setDay(calendarUtil.getYear(), calendarUtil.getMonthInteger(), 1);
int numberOfCurrentDays = calendarUtil.getNumberOfDays();
int tempCurrentMonth = calendarUtil.getMonthInteger();
int tempCurrentYear = calendarUtil.getYear();
// get the index of the first day in the month
int firstDay_of_Month = calendarUtil.getDay_Of_Week(true) - 1;
// Construct the time range to get all the days in the current month plus the days in the first week in the previous month and
// the days in the last week from the last month
// get the days in the first week that exists in the prev month
calendarUtil.setPrevDate(firstDay_of_Month);
Time startTime = TimeService.newTimeLocal(calendarUtil.getYear(),calendarUtil.getMonthInteger(),calendarUtil.getDayOfMonth(),00,00,00,000);
// set the date object to the current month and last day in the current month
calendarUtil.setDay(tempCurrentYear,tempCurrentMonth,numberOfCurrentDays);
// get the index of the last day in the current month
dayofweek = calendarUtil.getDay_Of_Week(true);
// move the date object to the last day in the last week of the current month , this day will be one of those days in the
// following month
if (dayofweek < 7)
{
for(int i = dayofweek; i<=6;i++)
{
calendarUtil.nextDate();
}
}
Time endTime = TimeService.newTimeLocal(calendarUtil.getYear(),calendarUtil.getMonthInteger(),calendarUtil.getDayOfMonth(),23,59,59,000);
return TimeService.newTimeRange(startTime,endTime,true,true);
}
/**
* Given a current date in the year, month, and day parameters, returns a TimeRange for the day.
*/
public TimeRange getDayTimeRange(
int year,
int month,
int day)
{
Time startTime = TimeService.newTimeLocal(year,month,day,00,00,00,000);
Time endTime = TimeService.newTimeLocal(year,month,day,23,59,59,000);
return TimeService.newTimeRange(startTime,endTime,true,true);
}
/**
* This class controls the page that allows the user to customize which
* calendars will be merged with the current group.
*/
public class MergePage
{
private final String mergeScheduleButtonHandler = "doMerge";
// Name used in the velocity template for the list of merged/non-merged calendars
private final String mergedCalendarsCollection = "mergedCalendarsCollection";
public MergePage()
{
super();
}
/**
* Build the context for showing merged view
*/
public void buildContext(
VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state,
SessionState sstate)
{
// load all calendar channels (either primary or merged calendars)
MergedList calendarList =
loadChannels( state.getPrimaryCalendarReference(),
portlet.getPortletConfig().getInitParameter(PORTLET_CONFIG_PARM_MERGED_CALENDARS),
new EntryProvider() );
// Place this object in the context so that the velocity template
// can get at it.
context.put(mergedCalendarsCollection, calendarList);
context.put("tlang",rb);
context.put("config",configProps);
sstate.setAttribute(
CalendarAction.SSTATE_ATTRIBUTE_MERGED_CALENDARS,
calendarList);
}
/**
* Action is used when the docancel is requested when the user click on cancel in the new view
*/
public void doCancel(
RunData data,
Context context,
CalendarActionState state,
SessionState sstate)
{
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
// cancel the options, release the site lock, cleanup
cancelOptions();
// Clear the previous state so that we don't get confused elsewhere.
state.setPrevState("");
sstate.removeAttribute(STATE_MODE);
enableObserver(sstate, true);
} // doCancel
/**
* Handle the "Merge" button on the toolbar
*/
public void doMerge(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
// TODO: really?
// get a lock on the site and setup for options work
doOptions(runData, context);
// if we didn't end up in options mode, bail out
if (!MODE_OPTIONS.equals(sstate.getAttribute(STATE_MODE))) return;
// Disable the observer
enableObserver(sstate, false);
// Save the previous state so that we can get to it after we're done with the options mode.
// if the previous state is Description, we need to remember one more step back
// coz there is a back link in description view
if ((state.getState()).equalsIgnoreCase("description"))
{
state.setPrevState(state.getReturnState() + "!!!fromDescription");
}
else
{
state.setPrevState(state.getState());
}
state.setState(CalendarAction.STATE_MERGE_CALENDARS);
} // doMerge
/**
* Handles the user clicking on the save button on the page to specify which
* calendars will be merged into the present schedule.
*/
public void doUpdate(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
// Get the merged calendar list out of our session state
MergedList mergedCalendarList =
(MergedList) sstate.getAttribute(
CalendarAction.SSTATE_ATTRIBUTE_MERGED_CALENDARS);
if (mergedCalendarList != null)
{
// Get the information from the run data and load it into
// our calendar list that we have in the session state.
mergedCalendarList.loadFromRunData(runData.getParameters());
}
// update the tool config
Placement placement = ToolManager.getCurrentPlacement();
// myWorkspace is special (a null mergedCalendar list defaults to all channels),
// so we add the primary calendar here to indicate no other channels are wanted
if (mergedCalendarList != null && isOnWorkspaceTab())
{
String channelRef = mergedCalendarList.getDelimitedChannelReferenceString();
if (StringUtils.trimToNull(channelRef) == null )
channelRef = state.getPrimaryCalendarReference();
placement.getPlacementConfig().setProperty(
PORTLET_CONFIG_PARM_MERGED_CALENDARS, channelRef );
}
// Otherwise, just set the list as specified
else if (mergedCalendarList != null && !isOnWorkspaceTab())
{
placement.getPlacementConfig().setProperty(
PORTLET_CONFIG_PARM_MERGED_CALENDARS,
mergedCalendarList.getDelimitedChannelReferenceString());
}
// handle the case of no merge calendars
else
{
placement.getPlacementConfig().remove(PORTLET_CONFIG_PARM_MERGED_CALENDARS);
}
// commit the change
saveOptions();
// Turn the observer back on.
enableObserver(sstate, true);
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
// Clear the previous state so that we don't get confused elsewhere.
state.setPrevState("");
sstate.removeAttribute(STATE_MODE);
} // doUpdate
/* (non-Javadoc)
* @see org.chefproject.actions.schedulePages.SchedulePage#getMenuHandlerID()
*/
public String getButtonHandlerID()
{
return mergeScheduleButtonHandler;
}
/* (non-Javadoc)
* @see org.chefproject.actions.schedulePages.SchedulePage#getMenuText()
*/
public String getButtonText()
{
return rb.getString("java.merge");
}
}
/**
* This class controls the page that allows the user to add arbitrary
* attributes to the attribute list for the primary calendar that
* corresponds to the current group.
*/
public class CustomizeCalendarPage
{
//This is the session attribute name to store init and current addFields list
// Name used in the velocity template for the list of calendar addFields
private final static String ADDFIELDS_CALENDARS_COLLECTION = "addFieldsCalendarsCollection";
private final static String ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY = "addFieldsCalendarsCollectionIsEmpty";
private final static String OPTIONS_BUTTON_HANDLER = "doCustomize";
public CustomizeCalendarPage()
{
super();
}
/**
* Build the context for addfields calendar (Options menu)
*/
public void buildContext(
VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state,
SessionState sstate)
{
String[] addFieldsCalendarArray = null;
// Get a list of current calendar addFields. This is a comma-delimited list.
if (sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE).toString().equals(CalendarAction.PAGE_MAIN)) //when the 'Options' button click
{
//when the 'Options' button click
Calendar calendarObj = null;
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch (IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.warn(".buildCustomizeContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.warn(".buildCustomizeContext(): " + e);
return;
}
// Get a current list of add fields. This is a comma-delimited string.
String addfieldsCalendars = calendarObj.getEventFields();
if (addfieldsCalendars != null)
{
addFieldsCalendarArray =
fieldStringToArray(
addfieldsCalendars,
ADDFIELDS_DELIMITER);
}
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS_INIT, addfieldsCalendars);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, addfieldsCalendars);
context.put("delFields", (List)sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS));
sstate.removeAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS_CONFIRM, "N");
state.setDelfieldAlertOff(true);
}
else //after the 'Options' button click
{
String addFieldsCollection = (String) sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS);
if (addFieldsCollection != null)
addFieldsCalendarArray = fieldStringToArray(addFieldsCollection, ADDFIELDS_DELIMITER);
}
// Place this object in the context so that the velocity template
// can get at it.
context.put(ADDFIELDS_CALENDARS_COLLECTION, addFieldsCalendarArray);
context.put("tlang",rb);
context.put("config",configProps);
if (addFieldsCalendarArray == null)
context.put(ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY, Boolean.valueOf(true));
else
context.put(ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY, Boolean.valueOf(false));
} //buildCustomizeCalendarContext
/**
* Handles the click on the page to add a field to events that will
* be added to the calendar. Changes aren't complete until the user
* commits changes with a save.
*/
public void doAddfield(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
String addFields = (String) sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS);
String [] addFieldsCalendarList = null;
if (addFields != null)
addFieldsCalendarList = fieldStringToArray(addFields,ADDFIELDS_DELIMITER);
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
enableObserver(sstate, true);
String addField = "";
addField = runData.getParameters().getString("textfield").trim();
String dupAddfield = "N";
//prevent entry of some characters (can cause problem)
addField = addField.replaceAll(" "," ");
addField = addField.replaceAll("'","");
addField = addField.replaceAll("\"","");
if (addField.length()==0)
{
addAlert(sstate, rb.getString("java.alert.youneed"));
}
else
{
if (addFieldsCalendarList != null)
{
for (int i=0; i < addFieldsCalendarList.length; i++)
{
if (addField.toUpperCase().equals(addFieldsCalendarList[i].toUpperCase()))
{
addAlert(sstate, rb.getString("java.alert.theadd"));
dupAddfield = "Y";
i = addFieldsCalendarList.length + 1;
}
}
if (dupAddfield.equals("N"))
addFieldsCalendarList = fieldStringToArray(addFields+ADDFIELDS_DELIMITER+addField, ADDFIELDS_DELIMITER);
}
else
{
String [] initString = new String[1];
initString[0] = addField;
addFieldsCalendarList = initString;
}
if (dupAddfield.equals("N"))
{
if (addFields != null)
addFields = addFields + ADDFIELDS_DELIMITER + addField;
else
addFields = addField;
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, addFields);
}
}
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, CalendarAction.PAGE_ADDFIELDS);
}
/**
* Handles a click on the cancel button in the page that allows the
* user to add/remove events to/from events that will be added to
* the calendar.
*/
public void doCancel(
RunData data,
Context context,
CalendarActionState state,
SessionState sstate)
{
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS_INIT));
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, CalendarAction.PAGE_MAIN);
enableObserver(sstate, true);
} // doCancel
/**
* This initiates the page where the user can add/remove additional
* properties to/from events that will be added to the calendar.
*/
public void doCustomize(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
// Disable the observer
enableObserver(sstate, false);
// Save the previous state so that we can get to it after we're done with the options mode.
// if the previous state is Description, we need to remember one more step back
// coz there is a back link in description view
if ((state.getState()).equalsIgnoreCase("description"))
{
state.setPrevState(state.getReturnState() + "!!!fromDescription");
}
else
{
state.setPrevState(state.getState());
}
state.setState(CalendarAction.STATE_CUSTOMIZE_CALENDAR);
}
/**
* Handles the click on the page to remove a field from events in the
* calendar. Changes aren't complete until the user commits changes
* with a save.
*/
public void doDeletefield(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
ParameterParser params = runData.getParameters();
String addFields = (String) sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS);
String [] addFieldsCalendarList = null, newAddFieldsCalendarList = null;
List delFields = new Vector();
int nextNewFieldsIndex = 0;
if (addFields != null)
{
addFieldsCalendarList = fieldStringToArray(addFields,ADDFIELDS_DELIMITER);
// The longest the new array can possibly be is the current size of the list.
newAddFieldsCalendarList = new String[addFieldsCalendarList.length];
for (int i=0; i< addFieldsCalendarList.length; i++)
{
String fieldName = params.getString(addFieldsCalendarList[i]);
// If a value is present, then that means that the user has checked
// the box for the field to be removed. Don't add it to the
// new list of field names. If it is not present, then add it
// to the new list of field names.
if ( fieldName == null || fieldName.length() == 0 )
{
newAddFieldsCalendarList[nextNewFieldsIndex++] = addFieldsCalendarList[i];
}
else
{
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS_CONFIRM, "Y");
delFields.add(addFieldsCalendarList[i]);
}
}
addFields = arrayToString(newAddFieldsCalendarList, ADDFIELDS_DELIMITER);
}
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
enableObserver(sstate, true);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, addFields);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS, delFields);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, CalendarAction.PAGE_ADDFIELDS);
}
/**
* Handles the user clicking on the save button on the page to add or
* remove additional attributes for all calendar events.
*/
public void doUpdate(
RunData runData,
Context context,
CalendarActionState state,
SessionState sstate)
{
if (sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_DELFIELDS_CONFIRM).equals("Y") && state.getDelfieldAlertOff() )
{
String errorCode = rb.getString("java.alert.areyou");
List delFields = (List) sstate.getAttribute(SSTATE_ATTRIBUTE_DELFIELDS);
errorCode = errorCode.concat((String)(delFields.get(0)));
for(int i=1; i<delFields.size(); i++)
{
errorCode = errorCode.concat(", " + (String)(delFields.get(i)));
}
errorCode = errorCode.concat(rb.getString("java.alert.ifyes"));
addAlert(sstate, errorCode);
state.setDelfieldAlertOff(false);
}
else
{
state.setDelfieldAlertOff(true);
String addfields = (String) sstate.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS);
while (addfields.startsWith(ADDFIELDS_DELIMITER))
{
addfields = addfields.substring(ADDFIELDS_DELIMITER.length());
}
String calId = state.getPrimaryCalendarReference();
try
{
CalendarEdit edit = CalendarService.editCalendar(calId);
edit.setEventFields(addfields);
CalendarService.commitCalendar(edit);
}
catch (IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereisno"));
M_log.debug(".doUpdate customize calendar IdUnusedException"+e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdonthave"));
M_log.debug(".doUpdate customize calendar "+e);
return;
}
catch (InUseException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.someone"));
M_log.debug(".doUpdate() for CustomizeCalendar: " + e);
return;
}
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS, addfields);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, CalendarAction.PAGE_MAIN);
}
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
enableObserver(sstate, true);
} // doUpdate
/* (non-Javadoc)
* @see org.chefproject.actions.schedulePages.SchedulePage#getMenuHandlerID()
*/
public String getButtonHandlerID()
{
return OPTIONS_BUTTON_HANDLER;
}
/* (non-Javadoc)
* @see org.chefproject.actions.schedulePages.SchedulePage#getMenuText()
*/
public String getButtonText()
{
return rb.getString("java.fields");
}
/**
* Loads additional fields information from the calendar object passed
* as a parameter and loads them into the context object for the Velocity
* template.
*/
public void loadAdditionalFieldsIntoContextFromCalendar(
Calendar calendarObj,
Context context)
{
// Get a current list of add fields. This is a ADDFIELDS_DELIMITER string.
String addfieldsCalendars = calendarObj.getEventFields();
String[] addfieldsCalendarArray = null;
if (addfieldsCalendars != null)
{
addfieldsCalendarArray =
fieldStringToArray(
addfieldsCalendars,
ADDFIELDS_DELIMITER);
}
// Place this object in the context so that the velocity template
// can get at it.
context.put(ADDFIELDS_CALENDARS_COLLECTION, addfieldsCalendarArray);
context.put("tlang",rb);
context.put("config",configProps);
if (addfieldsCalendarArray == null)
context.put(ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY, Boolean.valueOf(true));
else
context.put(ADDFIELDS_CALENDARS_COLLECTION_ISEMPTY, Boolean.valueOf(false));
}
/**
* Loads additional fields from the run data into a provided map object.
*/
public void loadAdditionalFieldsMapFromRunData(
RunData rundata,
Map addfieldsMap,
Calendar calendarObj)
{
String addfields_str = calendarObj.getEventFields();
if ( addfields_str != null && addfields_str.trim().length() != 0)
{
String [] addfields = fieldStringToArray(addfields_str, ADDFIELDS_DELIMITER);
String eachfield;
for (int i=0; i < addfields.length; i++)
{
eachfield = addfields[i];
addfieldsMap.put(eachfield, rundata.getParameters().getString(eachfield));
}
}
}
}
/**
* This class controls the page that allows the user to configure
* external calendar subscriptions.
*/
public class CalendarSubscriptionsPage
{
private final String institutionalSubscriptionsCollection = "institutionalSubscriptionsCollection";
private final String institutionalSubscriptionsAvailable = "institutionalSubscriptionsAvailable";
private final String userSubscriptionsCollection = "userSubscriptionsCollection";
private final String REF_DELIMITER = ExternalCalendarSubscriptionService.SUBS_REF_DELIMITER;
private final String NAME_DELIMITER = ExternalCalendarSubscriptionService.SUBS_NAME_DELIMITER;
public CalendarSubscriptionsPage()
{
super();
}
/**
* Build the context
*/
public void buildContext(VelocityPortlet portlet, Context context,
RunData runData, CalendarActionState state, SessionState sstate)
{
String channel = state.getPrimaryCalendarReference();
Set<ExternalSubscription> availableSubscriptions = ExternalCalendarSubscriptionService
.getAvailableInstitutionalSubscriptionsForChannel(channel);
Set<ExternalSubscription> subscribedByUser = ExternalCalendarSubscriptionService
.getSubscriptionsForChannel(channel, false);
// Institutional subscriptions
List<SubscriptionWrapper> institutionalSubscriptions = new ArrayList<SubscriptionWrapper>();
for (ExternalSubscription available : availableSubscriptions)
{
boolean selected = false;
for (ExternalSubscription subscribed : subscribedByUser)
{
if (subscribed.getReference().equals(available.getReference()))
{
selected = true;
break;
}
}
if (available.isInstitutional())
institutionalSubscriptions.add(new SubscriptionWrapper(available,
selected));
}
// User subscriptions
List<SubscriptionWrapper> userSubscriptions = (List<SubscriptionWrapper>) sstate
.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
if (userSubscriptions == null)
{
userSubscriptions = new ArrayList<SubscriptionWrapper>();
for (ExternalSubscription subscribed : subscribedByUser)
{
if (!subscribed.isInstitutional())
{
userSubscriptions.add(new SubscriptionWrapper(subscribed, true));
}
}
}
// Sort collections by name
Collections.sort(institutionalSubscriptions);
Collections.sort(userSubscriptions);
// Place in context so that the velocity template can get at it.
context.put("tlang", rb);
context.put(institutionalSubscriptionsAvailable, !institutionalSubscriptions
.isEmpty());
context.put(institutionalSubscriptionsCollection, institutionalSubscriptions);
context.put(userSubscriptionsCollection, userSubscriptions);
sstate.setAttribute(SSTATE_ATTRIBUTE_SUBSCRIPTIONS,
institutionalSubscriptions);
sstate.setAttribute(SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS, userSubscriptions);
}
/**
* Action is used when the doCancel is requested when the user click on
* cancel
*/
public void doCancel(RunData data, Context context, CalendarActionState state,
SessionState sstate)
{
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
// cancel the options, release the site lock, cleanup
cancelOptions();
// Clear the previous state so that we don't get confused elsewhere.
state.setPrevState("");
sstate.removeAttribute(STATE_MODE);
sstate.removeAttribute(SSTATE_ATTRIBUTE_SUBSCRIPTIONS);
sstate.removeAttribute(SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
enableObserver(sstate, true);
} // doCancel
/**
* Action is used when the doAddSubscription is requested
*/
public void doAddSubscription(RunData runData, Context context,
CalendarActionState state, SessionState sstate)
{
List<SubscriptionWrapper> addSubscriptions = (List<SubscriptionWrapper>) sstate
.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
enableObserver(sstate, true);
String calendarName = runData.getParameters().getString("calendarName")
.trim();
String calendarUrl = runData.getParameters().getString("calendarUrl").trim();
calendarUrl = calendarUrl.replaceAll("webcals://", "https://");
calendarUrl = calendarUrl.replaceAll("webcal://", "http://");
if (calendarName.length() == 0)
{
addAlert(sstate, rb.getString("java.alert.subsnameempty"));
}
else if (calendarUrl.length() == 0)
{
addAlert(sstate, rb.getString("java.alert.subsurlempty"));
}
else
{
String contextId = EntityManager.newReference(
state.getPrimaryCalendarReference()).getContext();
String id = ExternalCalendarSubscriptionService
.getIdFromSubscriptionUrl(calendarUrl);
String ref = ExternalCalendarSubscriptionService
.calendarSubscriptionReference(contextId, id);
addSubscriptions.add(new SubscriptionWrapper(calendarName, ref, true));
// Sort collections by name
Collections.sort(addSubscriptions);
sstate.setAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS,
addSubscriptions);
}
} // doAddSubscription
/**
* Handle the "Subscriptions" button on the toolbar
*/
public void doSubscriptions(RunData runData, Context context,
CalendarActionState state, SessionState sstate)
{
doOptions(runData, context);
// if we didn't end up in options mode, bail out
if (!MODE_OPTIONS.equals(sstate.getAttribute(STATE_MODE))) return;
// Disable the observer
enableObserver(sstate, false);
// Save the previous state so that we can get to it after we're done
// with the options mode.
// state.setPrevState(state.getState());
// Save the previous state so that we can get to it after we're done
// with the options mode.
// if the previous state is Description, we need to remember one
// more step back
// coz there is a back link in description view
if ((state.getState()).equalsIgnoreCase("description"))
{
state.setPrevState(state.getReturnState() + "!!!fromDescription");
}
else
{
state.setPrevState(state.getState());
}
state.setState(CalendarAction.STATE_CALENDAR_SUBSCRIPTIONS);
} // doSubscriptions
/**
* Handles the user clicking on the save button on the page to specify
* which calendars will be merged into the present schedule.
*/
public void doUpdate(RunData runData, Context context, CalendarActionState state,
SessionState sstate)
{
List<SubscriptionWrapper> calendarSubscriptions = (List<SubscriptionWrapper>) sstate
.getAttribute(SSTATE_ATTRIBUTE_SUBSCRIPTIONS);
List<SubscriptionWrapper> addSubscriptions = (List<SubscriptionWrapper>) sstate
.getAttribute(CalendarAction.SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
List<String> subscriptionTC = new LinkedList<String>();
ParameterParser params = runData.getParameters();
// Institutional Calendars
if (calendarSubscriptions != null)
{
for (SubscriptionWrapper subs : calendarSubscriptions)
{
if (params.getString(subs.getReference()) != null)
{
String name = subs.getDisplayName();
if (name == null || name.equals("")) name = subs.getUrl();
subscriptionTC.add(subs.getReference());
}
}
}
// Other Calendars
if (addSubscriptions != null)
{
for (SubscriptionWrapper add : addSubscriptions)
{
if (params.getString(add.getReference()) != null)
{
String name = add.getDisplayName();
if (name == null || name.equals("")) name = add.getUrl();
subscriptionTC.add(add.getReference() + NAME_DELIMITER
+ add.getDisplayName());
}
}
}
// Update the tool config
Placement placement = ToolManager.getCurrentPlacement();
if (placement != null)
{
Properties config = placement.getPlacementConfig();
if (config != null)
{
boolean first = true;
StringBuffer propValue = new StringBuffer();
for (String ref : subscriptionTC)
{
if (!first) propValue.append(REF_DELIMITER);
first = false;
propValue.append(ref);
}
config.setProperty(
ExternalCalendarSubscriptionService.TC_PROP_SUBCRIPTIONS,
propValue.toString());
// commit the change
saveOptions();
}
}
// Turn the observer back on.
enableObserver(sstate, true);
// Go back to whatever state we were in beforehand.
state.setReturnState(state.getPrevState());
// Clear the previous state so that we don't get confused elsewhere.
state.setPrevState("");
sstate.removeAttribute(STATE_MODE);
sstate.removeAttribute(SSTATE_ATTRIBUTE_SUBSCRIPTIONS);
sstate.removeAttribute(SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS);
} // doUpdate
public class SubscriptionWrapper implements Comparable<SubscriptionWrapper>
{
private String reference;
private String url;
private String displayName;
private boolean isInstitutional;
private boolean isSelected;
public SubscriptionWrapper()
{
}
public SubscriptionWrapper(ExternalSubscription subscription, boolean selected)
{
this.reference = subscription.getReference();
this.url = subscription.getSubscriptionUrl();
this.displayName = subscription.getSubscriptionName();
this.isInstitutional = subscription.isInstitutional();
this.isSelected = selected;
}
public SubscriptionWrapper(String calendarName, String ref, boolean selected)
{
Reference _reference = EntityManager.newReference(ref);
this.reference = ref;
// this.id = _reference.getId();
this.url = ExternalCalendarSubscriptionService
.getSubscriptionUrlFromId(_reference.getId());
this.displayName = calendarName;
this.isInstitutional = ExternalCalendarSubscriptionService
.isInstitutionalCalendar(ref);
this.isSelected = selected;
}
public String getReference()
{
return reference;
}
public void setReference(String ref)
{
this.reference = ref;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public String getDisplayName()
{
return displayName;
}
public void setDisplayName(String displayName)
{
this.displayName = displayName;
}
public boolean isInstitutional()
{
return isInstitutional;
}
public void setInstitutional(boolean isInstitutional)
{
this.isInstitutional = isInstitutional;
}
public boolean isSelected()
{
return isSelected;
}
public void setSelected(boolean isSelected)
{
this.isSelected = isSelected;
}
public int compareTo(SubscriptionWrapper sub)
{
if(this.getDisplayName() == null || sub.getDisplayName() == null)
return this.getUrl().compareTo(sub.getUrl());
else
return this.getDisplayName().compareTo(sub.getDisplayName());
}
}
}
/**
* Utility class to figure out permissions for a calendar object.
*/
static public class CalendarPermissions
{
/**
* Priate constructor, doesn't allow instances of this object.
*/
private CalendarPermissions()
{
super();
}
/**
* Returns true if the primary and selected calendar are the same, but not null.
*/
static boolean verifyPrimarySelectedMatch(String primaryCalendarReference, String selectedCalendarReference)
{
//
// Both primary and secondary calendar ids must be specified.
// These must also match to be able to delete an event
//
if ( primaryCalendarReference == null ||
selectedCalendarReference == null ||
!primaryCalendarReference.equals(selectedCalendarReference) )
{
return false;
}
else
{
return true;
}
}
/**
* Utility routint to get the calendar for a given calendar id.
*/
static private Calendar getTheCalendar(String calendarReference)
{
Calendar calendarObj = null;
try
{
calendarObj = CalendarService.getCalendar(calendarReference);
if (calendarObj == null)
{
// If the calendar isn't there, try adding it.
CalendarService.commitCalendar(
CalendarService.addCalendar(calendarReference));
calendarObj = CalendarService.getCalendar(calendarReference);
}
}
catch (IdUnusedException e)
{
M_log.debug("CalendarPermissions.getTheCalendar(): ",e);
}
catch (PermissionException e)
{
M_log.debug("CalendarPermissions.getTheCalendar(): " + e);
}
catch (IdUsedException e)
{
M_log.debug("CalendarPermissions.getTheCalendar(): " + e);
}
catch (IdInvalidException e)
{
M_log.debug("CalendarPermissions.getTheCalendar(): " + e);
}
return calendarObj;
}
/**
* Returns true if the current user can see the events in a calendar.
*/
static public boolean allowViewEvents(String calendarReference)
{
Calendar calendarObj = getTheCalendar(calendarReference);
if (calendarObj == null)
{
return false;
}
else
{
return calendarObj.allowGetEvents();
}
}
/**
* Returns true if the current user is allowed to delete events on the calendar id
* passed in as the selectedCalendarReference parameter. The selected calendar must match
* the primary calendar for this function to return true.
* @param primaryCalendarReference calendar id for the default channel
* @param selectedCalendarReference calendar id for the event the user has just selected
*/
public static boolean allowDeleteEvent(String primaryCalendarReference, String selectedCalendarReference, String eventId)
{
//
// Both primary and secondary calendar ids must be specified.
// These must also match to be able to delete an event
//
if ( !verifyPrimarySelectedMatch(primaryCalendarReference, selectedCalendarReference) )
{
return false;
}
Calendar calendarObj = getTheCalendar(primaryCalendarReference);
if (calendarObj == null)
{
return false;
}
else
{
CalendarEvent event = null;
try
{
event = calendarObj.getEvent(eventId);
}
catch (IdUnusedException e)
{
M_log.debug("CalendarPermissions.canDeleteEvent(): " + e);
}
catch (PermissionException e)
{
M_log.debug("CalendarPermissions.canDeleteEvent(): " + e);
}
if (event == null)
{
return false;
}
else
{
return calendarObj.allowRemoveEvent(event);
}
}
}
/**
* Returns true if the current user is allowed to revise events on the calendar id
* passed in as the selectedCalendarReference parameter. The selected calendar must match
* the primary calendar for this function to return true.
* @param primaryCalendarReference calendar id for the default channel
* @param selectedCalendarReference calendar reference for the event the user has just selected
*/
static public boolean allowReviseEvents(String primaryCalendarReference, String selectedCalendarReference, String eventId)
{
//
// Both primary and secondary calendar ids must be specified.
// These must also match to be able to delete an event
//
if ( !verifyPrimarySelectedMatch(primaryCalendarReference, selectedCalendarReference) )
{
return false;
}
Calendar calendarObj = getTheCalendar(primaryCalendarReference);
if (calendarObj == null)
{
return false;
}
else
{
return calendarObj.allowEditEvent(eventId);
}
}
/**
* Returns true if the current user is allowed to create events on the calendar id
* passed in as the selectedCalendarReference parameter. The selected calendar must match
* the primary calendar for this function to return true.
* @param primaryCalendarReference calendar reference for the default channel
* @param selectedCalendarReference calendar reference for the event the user has just selected
*/
static public boolean allowCreateEvents(String primaryCalendarReference, String selectedCalendarReference)
{
// %%% Note: disabling this check as the allow create events should ONLY be on the primary,
// we don't care about the selected -ggolden
/*
//
// The primary and selected calendar ids must match, unless the selected calendar
// is null or empty.
//
if ( selectedCalendarReference != null &&
selectedCalendarReference.length() > 0 &&
!verifyPrimarySelectedMatch(primaryCalendarReference, selectedCalendarReference) )
{
return false;
}
*/
Calendar calendarObj = getTheCalendar(primaryCalendarReference);
if (calendarObj == null)
{
return false;
}
else
{
return calendarObj.allowAddEvent();
}
}
/**
* Returns true if the user is allowed to merge events from different calendars
* within the default channel.
*/
static public boolean allowMergeCalendars(String calendarReference)
{
return CalendarService.allowMergeCalendar(calendarReference);
}
/**
* Returns true if the use is allowed to modify properties of the calendar itself,
* and not just the events within the calendar.
*/
static public boolean allowModifyCalendarProperties(String calendarReference)
{
return CalendarService.allowEditCalendar(calendarReference);
}
/**
* Returns true if the use is allowed to import (and export) events
* into the calendar.
*/
static public boolean allowImport(String calendarReference)
{
return CalendarService.allowImportCalendar(calendarReference);
}
/**
* Returns true if the user is allowed to subscribe external calendars
* into the calendar.
*/
static public boolean allowSubscribe(String calendarReference)
{
return CalendarService.allowSubscribeCalendar(calendarReference);
}
}
private final static String SSTATE_ATTRIBUTE_ADDFIELDS_PAGE =
"addfieldsPage";
private final static String SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS_INIT =
"addfieldsInit";
private final static String SSTATE_ATTRIBUTE_ADDFIELDS_CALENDARS =
"addfields";
private final static String SSTATE_ATTRIBUTE_DELFIELDS = "delFields";
private final static String SSTATE_ATTRIBUTE_DELFIELDS_CONFIRM =
"delfieldsConfirm";
private final static String SSTATE_ATTRIBUTE_SUBSCRIPTIONS_SERVICE = "calendarSubscriptionsService";
private final static String SSTATE_ATTRIBUTE_SUBSCRIPTIONS = "calendarSubscriptions";
private final static String SSTATE_ATTRIBUTE_ADDSUBSCRIPTIONS = "addCalendarSubscriptions";
private final static String STATE_NEW = "new";
private static final String EVENT_REFERENCE_PARAMETER = "eventReference";
private static final String EVENT_CONTEXT_VAR = "event";
private static final String NO_EVENT_FLAG_CONTEXT_VAR = "noEvent";
//
// These are variables used in the context for communication between this
// action class and the Velocity template.
//
// False/true string values are used in the context variables in a number of places.
private static final String FALSE_STRING = "false";
private static final String TRUE_STRING = "true";
// This is the property name in the portlet config for the list of calendars
// that are not merged.
private final static String PORTLET_CONFIG_PARM_MERGED_CALENDARS = "mergedCalendarReferences";
// default calendar view property
private final static String PORTLET_CONFIG_DEFAULT_VIEW = "defaultCalendarView";
private final static String PAGE_MAIN = "main";
private final static String PAGE_ADDFIELDS = "addFields";
/** The flag name and value in state to indicate an update to the portlet is needed. */
private final static String SSTATE_ATTRIBUTE_MERGED_CALENDARS = "mergedCalendars";
// String constants for user interface states
private final static String STATE_MERGE_CALENDARS = "mergeCalendars";
private final static String STATE_CALENDAR_SUBSCRIPTIONS = "calendarSubscriptions";
private final static String STATE_CUSTOMIZE_CALENDAR = "customizeCalendar";
// for detailed event view navigator
private final static String STATE_PREV_ACT = "toPrevActivity";
private final static String STATE_NEXT_ACT = "toNextActivity";
private final static String STATE_CURRENT_ACT = "toCurrentActivity";
private final static String STATE_EVENTS_LIST ="eventIds";
private final static String STATE_NAV_DIRECTION = "navigationDirection";
private MergePage mergedCalendarPage = new MergePage();
private CustomizeCalendarPage customizeCalendarPage = new CustomizeCalendarPage();
private CalendarSubscriptionsPage calendarSubscriptionsPage = new CalendarSubscriptionsPage();
/**
* See if the current tab is the workspace tab (i.e. user site)
* @return true if we are currently on the "My Workspace" tab.
*/
private static boolean isOnWorkspaceTab()
{
return SiteService.isUserSite(ToolManager.getCurrentPlacement().getContext());
}
protected Class getStateClass()
{
return CalendarActionState.class;
} // getStateClass
/**
** loadChannels -- load specified primaryCalendarReference
** or merged calendars if initMergeList is defined
**/
private MergedList loadChannels( String primaryCalendarReference,
String initMergeList,
MergedList.EntryProvider entryProvider )
{
MergedList mergedCalendarList = new MergedList();
String[] channelArray = null;
// Figure out the list of channel references that we'll be using.
// MyWorkspace is special: if not superuser, and not otherwise defined, get all channels
if ( isOnWorkspaceTab() && !SecurityService.isSuperUser() && initMergeList == null )
channelArray = mergedCalendarList.getAllPermittedChannels(new CalendarChannelReferenceMaker());
else
channelArray = mergedCalendarList.getChannelReferenceArrayFromDelimitedString(
primaryCalendarReference, initMergeList );
if (entryProvider == null )
{
entryProvider = new MergedListEntryProviderFixedListWrapper(
new EntryProvider(),
primaryCalendarReference,
channelArray,
new CalendarReferenceToChannelConverter());
}
mergedCalendarList.loadChannelsFromDelimitedString(
isOnWorkspaceTab(),
false,
entryProvider,
StringUtils.trimToEmpty(SessionManager.getCurrentSessionUserId()),
channelArray,
SecurityService.isSuperUser(),
ToolManager.getCurrentPlacement().getContext());
return mergedCalendarList;
}
/**
* Gets an array of all the calendars whose events we can access.
*/
private List getCalendarReferenceList(VelocityPortlet portlet, String primaryCalendarReference, boolean isOnWorkspaceTab)
{
// load all calendar channels (either primary or merged calendars)
MergedList mergedCalendarList =
loadChannels( primaryCalendarReference,
portlet.getPortletConfig().getInitParameter(PORTLET_CONFIG_PARM_MERGED_CALENDARS),
null );
// add external calendar subscriptions
List referenceList = mergedCalendarList.getReferenceList();
Set subscriptionRefList = ExternalCalendarSubscriptionService.getCalendarSubscriptionChannelsForChannels(
primaryCalendarReference,
referenceList);
referenceList.addAll(subscriptionRefList);
return referenceList;
}
/**
* Gets the session state from the Jetspeed RunData
*/
static private SessionState getSessionState(RunData runData)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData)runData).getJs_peid();
return ((JetspeedRunData)runData).getPortletSessionState(peid);
}
public String buildMainPanelContext( VelocityPortlet portlet,
Context context,
RunData runData,
SessionState sstate)
{
CalendarActionState state = (CalendarActionState)getState(portlet, runData, CalendarActionState.class);
String template = (String)getContext(runData).get("template");
// get current state (view); if not set use tool default or default to week view
String stateName = state.getState();
if (stateName == null)
{
stateName = portlet.getPortletConfig().getInitParameter(PORTLET_CONFIG_DEFAULT_VIEW);
if (stateName == null)
stateName = ServerConfigurationService.getString("calendar.default.view", "week");
state.setState(stateName);
}
if ( stateName.equals(STATE_SCHEDULE_IMPORT) )
{
buildImportContext(portlet, context, runData, state, getSessionState(runData));
}
else if ( stateName.equals(STATE_MERGE_CALENDARS) )
{
// build the context to display the options panel
mergedCalendarPage.buildContext(portlet, context, runData, state, getSessionState(runData));
}
else if ( stateName.equals(STATE_CALENDAR_SUBSCRIPTIONS) )
{
// build the context to display the options panel
calendarSubscriptionsPage.buildContext(portlet, context, runData, state, getSessionState(runData));
}
else if ( stateName.equals(STATE_CUSTOMIZE_CALENDAR) )
{
// build the context to display the options panel
//needed to track when user clicks 'Save' or 'Cancel'
String sstatepage = "";
Object statepageAttribute = sstate.getAttribute(SSTATE_ATTRIBUTE_ADDFIELDS_PAGE);
if ( statepageAttribute != null )
{
sstatepage = statepageAttribute.toString();
}
if (!sstatepage.equals(PAGE_ADDFIELDS))
{
sstate.setAttribute(SSTATE_ATTRIBUTE_ADDFIELDS_PAGE, PAGE_MAIN);
}
customizeCalendarPage.buildContext(portlet, context, runData, state, getSessionState(runData));
}
else if ((stateName.equals("revise"))|| (stateName.equals("goToReviseCalendar")))
{
// build the context for the normal view show
buildReviseContext(portlet, context, runData, state);
}
else if (stateName.equals("description"))
{
// build the context for the basic step of adding file
buildDescriptionContext(portlet, context, runData, state);
}
else if (stateName.equals("year"))
{
// build the context for the advanced step of adding file
buildYearContext(portlet, context, runData, state);
}
else if (stateName.equals("month"))
{
// build the context for the basic step of adding folder
buildMonthContext(portlet, context, runData, state);
}
else if (stateName.equals("day"))
{
// build the context for the basic step of adding simple text
buildDayContext(portlet, context, runData, state);
}
else if (stateName.equals("week"))
{
// build the context for the basic step of delete confirm page
buildWeekContext(portlet, context, runData, state);
}
else if (stateName.equals("new"))
{
// build the context to display the property list
buildNewContext(portlet, context, runData, state);
}
else if (stateName.equals("icalEx"))
{
buildIcalExportPanelContext(portlet, context, runData, state);
}
else if (stateName.equals("delete"))
{
// build the context to display the property list
buildDeleteContext(portlet, context, runData, state);
}
else if (stateName.equals("list"))
{
// build the context to display the list view
buildListContext(portlet, context, runData, state);
}
else if (stateName.equals(STATE_SET_FREQUENCY))
{
buildFrequencyContext(portlet, context, runData, state);
}
TimeZone timeZone = TimeService.getLocalTimeZone();
context.put("timezone", timeZone.getDisplayName(timeZone.inDaylightTime(new Date()), TimeZone.SHORT) );
//the AM/PM strings
context.put("amString", CalendarUtil.getLocalAMString());
context.put("pmString", CalendarUtil.getLocalPMString());
// group realted variables
context.put("siteAccess", CalendarEvent.EventAccess.SITE);
context.put("groupAccess", CalendarEvent.EventAccess.GROUPED);
context.put("message", state.getState());
context.put("state", state.getKey());
context.put("tlang",rb);
context.put("config",configProps);
context.put("dateFormat", getDateFormatString());
return template;
} // buildMainPanelContext
private void buildImportContext(VelocityPortlet portlet, Context context, RunData runData, CalendarActionState state, SessionState state2)
{
// Place this object in the context so that the velocity template
// can get at it.
// Start at the beginning if nothing is set yet.
if ( state.getImportWizardState() == null )
{
state.setImportWizardState(IMPORT_WIZARD_SELECT_TYPE_STATE);
}
// (optional) ical.experimental import
context.put("icalEnable",
ServerConfigurationService.getString("ical.experimental"));
// Set whatever the current wizard state is.
context.put("importWizardState", state.getImportWizardState());
context.put("tlang",rb);
context.put("config",configProps);
// Set the imported events into the context.
context.put("wizardImportedEvents", state.getWizardImportedEvents());
String calId = state.getPrimaryCalendarReference();
try
{
Calendar calendarObj = CalendarService.getCalendar(calId);
String scheduleTo = (String)state2.getAttribute(STATE_SCHEDULE_TO);
if (scheduleTo != null && scheduleTo.length() != 0)
{
context.put("scheduleTo", scheduleTo);
}
else
{
if (calendarObj.allowAddEvent())
{
// default to make site selection
context.put("scheduleTo", "site");
}
else if (calendarObj.getGroupsAllowAddEvent().size() > 0)
{
// to group otherwise
context.put("scheduleTo", "groups");
}
}
Collection groups = calendarObj.getGroupsAllowAddEvent();
if (groups.size() > 0)
{
context.put("groups", groups);
}
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".buildImportContext(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".buildImportContext(): " + e);
}
}
/**
* Addes the primary calendar reference (this site's default calendar)
* to the calendar action state object.
*/
private void setPrimaryCalendarReferenceInState(VelocityPortlet portlet, CalendarActionState state)
{
String calendarReference = state.getPrimaryCalendarReference();
if (calendarReference == null)
{
calendarReference = StringUtils.trimToNull(portlet.getPortletConfig().getInitParameter(CALENDAR_INIT_PARAMETER));
if (calendarReference == null)
{
// form a reference to the default calendar for this request's site
calendarReference = CalendarService.calendarReference(ToolManager.getCurrentPlacement().getContext(), SiteService.MAIN_CONTAINER);
state.setPrimaryCalendarReference(calendarReference);
}
}
}
/**
* Build the context for editing the frequency
*/
protected void buildFrequencyContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
// under 3 conditions, we get into this page
// 1st, brand new event, no freq or rule set up, coming from revise page
// 2nd, exisitng event, coming from revise page
// 3rd, new event, stay in this page after changing frequency by calling js function onchange()
// 4th, existing event, stay in this page after changing frequency by calling js function onchange()
// sstate attribute TEMP_FREQ_SELECT is one of the flags
// if this attribute is not null, means changeFrequency() is called thru onchange().
// Then rule is another flag, if rule is null, means new event
// Combination of these 2 flags should cover all the conditions
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
// defaultly set frequency to be once
// if there is a saved state frequency attribute, replace the default one
String freq = CalendarAction.DEFAULT_FREQ;
if (sstate.getAttribute(TEMP_FREQ_SELECT) != null)
{
freq = (String)sstate.getAttribute(TEMP_FREQ_SELECT);
if (rule != null)
context.put("rule", rule);
sstate.removeAttribute(TEMP_FREQ_SELECT);
}
else
{
if (rule != null)
{
freq = rule.getFrequency();
context.put("rule", rule);
}
}
context.put("freq", freq);
context.put("tlang",rb);
context.put("config",configProps);
// get the data the user just input in the preview new/revise page
context.put("savedData",state.getNewData());
context.put("realDate", TimeService.newTime());
} // buildFrequencyContext
/**
* Build the context for showing revise view
*/
protected void buildReviseContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
context.put("tlang",rb);
context.put("config",configProps);
Calendar calendarObj = null;
CalendarEvent calEvent = null;
CalendarUtil calObj= new CalendarUtil(); //null;
MyDate dateObj1 = null;
dateObj1 = new MyDate();
boolean getEventsFlag = false;
List attachments = state.getAttachments();
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
calObj.setDay(stateYear, stateMonth, stateDay);
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
String calId = state.getPrimaryCalendarReference();
if( state.getIsNewCalendar() == false)
{
if (CalendarService.allowGetCalendar(calId)== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
return;
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
if(calendarObj.allowGetEvent(state.getCalendarEventId()))
{
calEvent = calendarObj.getEvent(state.getCalendarEventId());
getEventsFlag = true;
context.put("selectedGroupRefsCollection", calEvent.getGroups());
// all the groups the user is allowed to do remove from
context.put("allowedRemoveGroups", calendarObj.getGroupsAllowRemoveEvent(calEvent.isUserOwner()));
}
else
getEventsFlag = false;
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsIntoContextFromCalendar( calendarObj, context);
context.put("tlang",rb);
context.put("config",configProps);
context.put("calEventFlag","true");
context.put("new", "false");
// if from the metadata view of announcement, the message is already the system resource
if ( state.getState().equals("goToReviseCalendar") )
{
context.put("backToRevise", "false");
}
// if from the attachments editing view or preview view of announcement
else if (state.getState().equals("revise"))
{
context.put("backToRevise", "true");
}
//Vector attachments = state.getAttachments();
if ( attachments != null )
{
context.put("attachments", attachments);
}
else
{
context.put("attachNull", "true");
}
context.put("fromAttachmentFlag",state.getfromAttachmentFlag());
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY, rb.getString("java.alert.therenoactv"));
M_log.debug(".buildReviseContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildReviseContext(): " + e);
return;
}
}
}
else
{
// if this a new annoucement, get the subject and body from temparory record
context.put("new", "true");
context.put("tlang",rb);
context.put("config",configProps);
context.put("attachments", attachments);
context.put("fromAttachmentFlag",state.getfromAttachmentFlag());
}
// Output for recurring events
// for an existing event
// if the saved recurring rule equals to string FREQ_ONCE, set it as not recurring
// if there is a saved recurring rule in sstate, display it
// otherwise, output the event's rule instead
if ((((String) sstate.getAttribute(FREQUENCY_SELECT)) != null)
&& (((String) sstate.getAttribute(FREQUENCY_SELECT)).equals(FREQ_ONCE)))
{
context.put("rule", null);
}
else
{
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
if (rule == null)
{
rule = calEvent.getRecurrenceRule();
}
else
context.put("rule", rule);
if (rule != null)
{
context.put("freq", rule.getFrequencyDescription());
} // if (rule != null)
} //if ((String) sstate.getAttribute(FREQUENCY_SELECT).equals(FREQ_ONCE))
try
{
calendarObj = CalendarService.getCalendar(calId);
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
if (scheduleTo != null && scheduleTo.length() != 0)
{
context.put("scheduleTo", scheduleTo);
}
else
{
if (calendarObj.allowAddCalendarEvent())
{
// default to make site selection
context.put("scheduleTo", "site");
}
else if (calendarObj.getGroupsAllowAddEvent().size() > 0)
{
// to group otherwise
context.put("scheduleTo", "groups");
}
}
Collection groups = calendarObj.getGroupsAllowAddEvent();
// add to these any groups that the message already has
calEvent = calendarObj.getEvent(state.getCalendarEventId());
if (calEvent != null)
{
Collection otherGroups = calEvent.getGroupObjects();
for (Iterator i = otherGroups.iterator(); i.hasNext();)
{
Group g = (Group) i.next();
if (!groups.contains(g))
{
groups.add(g);
}
}
}
if (groups.size() > 0)
{
context.put("groups", groups);
}
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".buildNewContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".buildNewContext(): " + e);
return;
}
context.put("tlang",rb);
context.put("config",configProps);
context.put("event", calEvent);
context.put("helper",new Helper());
context.put("message","revise");
context.put("savedData",state.getNewData());
context.put("getEventsFlag", Boolean.valueOf(getEventsFlag));
if(state.getIsNewCalendar()==true)
context.put("vmtype","new");
else
context.put("vmtype","revise");
context.put("service", contentHostingService);
// output the real time
context.put("realDate", TimeService.newTime());
} // buildReviseContext
/**
* Build the context for showing description for events
*/
protected void buildDescriptionContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
context.put("tlang",rb);
context.put("config",configProps);
context.put("Context", ToolManager.getCurrentPlacement().getContext());
context.put("CalendarService", CalendarService.getInstance());
context.put("SiteService", SiteService.getInstance());
Calendar calendarObj = null;
CalendarEvent calEvent = null;
MyDate dateObj1 = null;
dateObj1 = new MyDate();
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
navigatorContextControl(portlet, context, runData, (String)sstate.getAttribute(STATE_NAV_DIRECTION));
boolean prevAct = sstate.getAttribute(STATE_PREV_ACT) != null;
boolean nextAct = sstate.getAttribute(STATE_NEXT_ACT) != null;
context.put("prevAct", Boolean.valueOf(prevAct));
context.put("nextAct", Boolean.valueOf(nextAct));
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj= new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
// get the today date in month/day/year format
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
// get the event id from the CalendarService.
// send the event to the vm
String ce = state.getCalendarEventId();
String selectedCalendarReference = state.getSelectedCalendarReference();
if ( !CalendarPermissions.allowViewEvents(selectedCalendarReference) )
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
M_log.debug("here in buildDescription not showing event");
return;
}
else
{
try
{
calendarObj = CalendarService.getCalendar(selectedCalendarReference);
calEvent = calendarObj.getEvent(ce);
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsIntoContextFromCalendar( calendarObj, context);
context.put(EVENT_CONTEXT_VAR, calEvent);
context.put("tlang",rb);
context.put("config",configProps);
// Get the attachments from assignment tool for viewing
String assignmentId = calEvent.getField(CalendarUtil.NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID);
if (assignmentId != null && assignmentId.length() > 0)
{
// pass in the assignment reference to get the assignment data we need
Map<String, Object> assignData = new HashMap<String, Object>();
StringBuilder entityId = new StringBuilder( ASSN_ENTITY_PREFIX );
entityId.append( (CalendarService.getCalendar(calEvent.getCalendarReference())).getContext() );
entityId.append( File.separator );
entityId.append( assignmentId );
ActionReturn ret = entityBroker.executeCustomAction(entityId.toString(), ASSN_ENTITY_ACTION, null, null);
if (ret != null && ret.getEntityData() != null) {
Object returnData = ret.getEntityData().getData();
assignData = (Map<String, Object>)returnData;
}
context.put("assignmenturl", (String) assignData.get("assignmentUrl"));
context.put("assignmentTitle", (String) assignData.get("assignmentTitle"));
}
String ownerId = calEvent.getCreator();
if ( ownerId != null && ! ownerId.equals("") )
{
String ownerName =
UserDirectoryService.getUser( ownerId ).getDisplayName();
context.put("owner_name", ownerName);
}
String siteName = calEvent.getSiteName();
if ( siteName != null )
context.put("site_name", siteName );
RecurrenceRule rule = calEvent.getRecurrenceRule();
// for a brand new event, there is no saved recurring rule
if (rule != null)
{
context.put("freq", rule.getFrequencyDescription());
context.put("rule", rule);
}
// show all the groups in this calendar that user has get event in
Collection groups = calendarObj.getGroupsAllowGetEvent();
if (groups != null)
{
context.put("groupRange", calEvent.getGroupRangeForDisplay(calendarObj));
}
}
catch (IdUnusedException e)
{
M_log.debug(".buildDescriptionContext(): " + e);
context.put(NO_EVENT_FLAG_CONTEXT_VAR, TRUE_STRING);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotpermadd"));
M_log.debug(".buildDescriptionContext(): " + e);
return;
}
catch (UserNotDefinedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotpermadd"));
M_log.debug(".buildDescriptionContext(): " + e);
return;
}
}
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
context.put(
"allowDelete",
Boolean.valueOf(CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId())));
context.put(
"allowRevise",
Boolean.valueOf(CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId())));
} // buildDescriptionContext
/**
* Build the context for showing Year view
*/
protected void buildYearContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
CalendarUtil calObj= new CalendarUtil();
MyYear yearObj = null;
MyMonth monthObj1, monthObj2 = null;
MyDay dayObj = null;
MyDate dateObj1 = null;
boolean allowed = false;
CalendarEventVector CalendarEventVectorObj = null;
// new objects of myYear, myMonth, myDay, myWeek classes
yearObj = new MyYear();
monthObj1 = new MyMonth();
dayObj = new MyDay();
dateObj1 = new MyDate();
int month = 1;
int col = 3;
int row = 4;
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
calObj.setDay(stateYear, stateMonth, stateDay);
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
yearObj.setYear(calObj.getYear());
monthObj1.setMonth(calObj.getMonthInteger());
dayObj.setDay(calObj.getDayOfMonth());
if (CalendarService.allowGetCalendar(state.getPrimaryCalendarReference())== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallowsee"));
}
else
{
try
{
allowed = CalendarService.getCalendar(state.getPrimaryCalendarReference()).allowAddEvent();
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.therenoactv"));
M_log.debug(".buildYearContext(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildYearContext(): " + e);
}
}
for(int r = 0; r<row; r++)
{
for (int c = 0; c<col;c++)
{
monthObj2 = new MyMonth();
calObj.setDay(dateObj1.getYear(),month,1);
CalendarEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
getMonthTimeRange(calObj));
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
monthObj2 = calMonth(month, calObj,state,CalendarEventVectorObj);
month++;
yearObj.setMonth(monthObj2,r,c);
}
}
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
context.put("tlang",rb);
context.put("config",configProps);
context.put("yearArray",yearObj);
context.put("year",Integer.valueOf(calObj.getYear()));
context.put("date",dateObj1);
state.setState("year");
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
// added by zqian for toolbar
context.put("allow_new", Boolean.valueOf(allowed));
context.put("allow_delete", Boolean.valueOf(false));
context.put("allow_revise", Boolean.valueOf(false));
context.put("tlang",rb);
context.put("config",configProps);
context.put(Menu.CONTEXT_ACTION, "CalendarAction");
context.put("selectedView", rb.getString("java.byyear"));
context.put("dayOfWeekNames", calObj.getCalendarDaysOfWeekNames(false));
} // buildYearContext
/**
* Build the context for showing month view
*/
protected void buildMonthContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
MyMonth monthObj2 = null;
MyDate dateObj1 = null;
CalendarEventVector CalendarEventVectorObj = null;
dateObj1 = new MyDate();
// read calendar object saved in state object
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
// fill this month object with all days avilable for this month
if (CalendarService.allowGetCalendar(state.getPrimaryCalendarReference())== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
return;
}
CalendarEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
getMonthTimeRange(calObj));
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
monthObj2 = calMonth(calObj.getMonthInteger(), calObj,state, CalendarEventVectorObj);
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
// retrieve the information from day, month and year to calObj again since calObj changed during the process of CalMonth().
context.put("nameOfMonth",calendarUtilGetMonth(calObj.getMonthInteger()));
context.put("year", Integer.valueOf(calObj.getYear()));
context.put("monthArray",monthObj2);
context.put("tlang",rb);
context.put("config",configProps);
int row = 5;
context.put("row",Integer.valueOf(row));
context.put("date",dateObj1);
context.put("realDate", TimeService.newTime());
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
state.setState("month");
context.put("selectedView", rb.getString("java.bymonth"));
context.put("dayOfWeekNames", calObj.getCalendarDaysOfWeekNames(false));
} // buildMonthContext
protected Vector getNewEvents(int year, int month, int day, CalendarActionState state, RunData rundata, int time, int numberofcycles,Context context,CalendarEventVector CalendarEventVectorObj)
{
boolean firstTime = true;
Vector events = new Vector();
Time timeObj = TimeService.newTimeLocal(year,month,day,time,00,00,000);
long duration = ((30*60)*(1000));
Time updatedTime = TimeService.newTime(timeObj.getTime()+ duration);
/*** include the start time ***/
TimeRange timeRangeObj = TimeService.newTimeRange(timeObj,updatedTime,true,false);
for (int range = 0; range <=numberofcycles;range++)
{
Iterator calEvent = null;
calEvent = CalendarEventVectorObj.getEvents(timeRangeObj);
Vector vectorObj = new Vector();
EventDisplayClass eventDisplayObj;
Vector newVectorObj = null;
boolean swapflag=true;
EventDisplayClass eventdisplayobj = null;
if (calEvent.hasNext())
{
int i = 0;
while (calEvent.hasNext())
{
eventdisplayobj = new EventDisplayClass();
eventdisplayobj.setEvent((CalendarEvent)calEvent.next(),false,i);
vectorObj.add(i,eventdisplayobj);
i++;
} // while
if(firstTime)
{
events.add(range,vectorObj);
firstTime = false;
}
else
{
while(swapflag == true)
{
swapflag=false;
for(int mm = 0; mm<events.size();mm++)
{
int eom, mv =0;
Vector evectorObj = (Vector)events.elementAt(mm);
if(evectorObj.isEmpty()==false)
{
for(eom = 0; eom<evectorObj.size();eom++)
{
if(!"".equals(evectorObj.elementAt(eom)))
{
String eomId = (((EventDisplayClass)evectorObj.elementAt(eom)).getEvent()).getId();
newVectorObj = new Vector();
for(mv = 0; mv<vectorObj.size();mv++)
{
if(!"".equals(vectorObj.elementAt(mv)))
{
String vectorId = (((EventDisplayClass)vectorObj.elementAt(mv)).getEvent()).getId();
if (vectorId.equals(eomId))
{
eventDisplayObj = (EventDisplayClass)vectorObj.elementAt(mv);
eventDisplayObj.setFlag(true);
if (mv != eom)
{
swapflag = true;
vectorObj.removeElementAt(mv);
for(int x = 0 ; x<eom;x++)
{
if(vectorObj.isEmpty()==false)
{
newVectorObj.add(x,vectorObj.elementAt(0));
vectorObj.removeElementAt(0);
}
else
{
newVectorObj.add(x,"");
}
}// for
newVectorObj.add(eom, eventDisplayObj);
int neweom = eom;
neweom = neweom+1;
while(vectorObj.isEmpty()==false)
{
newVectorObj.add(neweom,vectorObj.elementAt(0));
vectorObj.removeElementAt(0);
neweom++;
}
for(int vv =0;vv<newVectorObj.size();vv++)
{
vectorObj.add(vv,newVectorObj.elementAt(vv));
}
} // if
} // if
} // if
} //for
} // if
} // for
} // if
} // for
} // while
events.add(range,vectorObj);
} // if - else firstTime
timeRangeObj.shiftForward(1800000);
}
else
{
events.add(range,vectorObj);
timeRangeObj.shiftForward(1800000);
}
} // for
return events;
} // getNewEvents
/**
* Build the context for showing day view
*/
protected void buildDayContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
Calendar calendarObj = null;
boolean allowed = false;
MyDate dateObj1 = null;
CalendarEventVector CalendarEventVectorObj = null;
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
context.put("todayYear", Integer.valueOf(stateYear));
context.put("todayMonth", Integer.valueOf(stateMonth));
context.put("todayDay", Integer.valueOf(stateDay));
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
// new objects of myYear, myMonth, myDay, myWeek classes
dateObj1 = new MyDate();
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
int year = dateObj1.getYear();
int month = dateObj1.getMonth();
int day = dateObj1.getDay();
Vector eventVector = new Vector();
String calId = state.getPrimaryCalendarReference();
if (CalendarService.allowGetCalendar(calId)== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
return;
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
allowed = calendarObj.allowAddEvent();
CalendarEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
getDayTimeRange(year, month, day));
String currentPage = state.getCurrentPage();
// if coming from clicking the the day number in month view, year view or list view
// select the time slot first, go to the slot containing earliest event on that day
if (state.getPrevState() != null)
{
if ( (state.getPrevState()).equalsIgnoreCase("list")
|| (state.getPrevState()).equalsIgnoreCase("month")
|| (state.getPrevState()).equalsIgnoreCase("year"))
{
CalendarEventVector vec = null;
Time timeObj = TimeService.newTimeLocal(year,month,day,FIRST_PAGE_START_HOUR,00,00,000);
Time timeObj2 = TimeService.newTimeLocal(year,month,day,7,59,59,000);
TimeRange timeRangeObj = TimeService.newTimeRange(timeObj,timeObj2);
vec = CalendarService.getEvents(getCalendarReferenceList(portlet, state.getPrimaryCalendarReference(),isOnWorkspaceTab()), timeRangeObj);
if (vec.size() > 0)
currentPage = "first";
else
{
timeObj = TimeService.newTimeLocal(year,month,day,SECOND_PAGE_START_HOUR,00,00,000);
timeObj2 = TimeService.newTimeLocal(year,month,day,17,59,59,000);
timeRangeObj = TimeService.newTimeRange(timeObj,timeObj2);
vec = CalendarService.getEvents(getCalendarReferenceList(portlet, state.getPrimaryCalendarReference(),isOnWorkspaceTab()), timeRangeObj);
if (vec.size() > 0)
currentPage = "second";
else
{
timeObj = TimeService.newTimeLocal(year,month,day,THIRD_PAGE_START_HOUR,00,00,000);
timeObj2 = TimeService.newTimeLocal(year,month,day,23,59,59,000);
timeRangeObj = TimeService.newTimeRange(timeObj,timeObj2);
vec = CalendarService.getEvents(getCalendarReferenceList(portlet, state.getPrimaryCalendarReference(),isOnWorkspaceTab()), timeRangeObj);
if (vec.size() > 0)
currentPage = "third";
else
currentPage = "second";
}
}
state.setCurrentPage(currentPage);
}
}
if(currentPage.equals("third"))
{
eventVector = getNewEvents(year,month,day, state, runData,THIRD_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
}
else if (currentPage.equals("second"))
{
eventVector = getNewEvents(year,month,day, state, runData,SECOND_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
}
else
{
eventVector = getNewEvents(year,month,day, state, runData,FIRST_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
}
dateObj1.setEventBerDay(eventVector);
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.therenoactv"));
M_log.debug(".buildDayContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildDayContext(): " + e);
return;
}
}
context.put("nameOfMonth",calendarUtilGetMonth(calObj.getMonthInteger()));
context.put("monthInt", Integer.valueOf(calObj.getMonthInteger()));
context.put("firstpage","true");
context.put("secondpage","false");
context.put("page",state.getCurrentPage());
context.put("date",dateObj1);
context.put("helper",new Helper());
context.put("calObj", calObj);
context.put("tlang",rb);
context.put("config",configProps);
state.setState("day");
context.put("message", state.getState());
DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL, new ResourceLoader().getLocale());
try{
context.put("today",formatter.format(calObj.getTime()));
}catch(Exception e){
context.put("today", calObj.getTodayDate());
}
state.setPrevState("");
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
context.put("permissionallowed",Boolean.valueOf(allowed));
context.put("tlang",rb);
context.put("config",configProps);
context.put("selectedView", rb.getString("java.byday"));
context.put("dayName", calendarUtilGetDay(calObj.getDay_Of_Week(false)));
} // buildDayContext
/**
* Build the context for showing week view
*/
protected void buildWeekContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
Calendar calendarObj = null;
//Time st,et = null;
//CalendarUtil calObj= null;
MyYear yearObj = null;
MyMonth monthObj1 = null;
MyWeek weekObj =null;
MyDay dayObj = null;
MyDate dateObj1, dateObj2 = null;
int dayofweek = 0;
// new objects of myYear, myMonth, myDay, myWeek classes
yearObj = new MyYear();
monthObj1 = new MyMonth();
weekObj = new MyWeek();
dayObj = new MyDay();
dateObj1 = new MyDate();
CalendarEventVector CalendarEventVectorObj = null;
//calObj = state.getCalObj();
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
int iii =0;
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
yearObj.setYear(calObj.getYear());
monthObj1.setMonth(calObj.getMonthInteger());
dayObj.setDay(calObj.getDayOfMonth());
String calId = state.getPrimaryCalendarReference();
// this loop will move the calendar to the begining of the week
if (CalendarService.allowGetCalendar(calId)== false)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
return;
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch(IdUnusedException e)
{
try
{
CalendarService.commitCalendar(CalendarService.addCalendar(calId));
calendarObj = CalendarService.getCalendar(calId);
}
catch (Exception err)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.therenoactv"));
M_log.debug(".buildWeekContext(): " + err);
return;
}
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildWeekContext(): " + e);
return;
}
}
if (calendarObj.allowGetEvents() == true)
{
CalendarEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
getWeekTimeRange(calObj));
}
else
{
CalendarEventVectorObj = new CalendarEventVector();
}
calObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
dayofweek = calObj.getDay_Of_Week(true);
calObj.setPrevDate(dayofweek-1);
dayofweek = calObj.getDay_Of_Week(true);
Time[] pageStartTime = new Time[7];
Time[] pageEndTime = new Time[7];
for(int i = 7; i>=dayofweek; i--)
{
Vector eventVector = new Vector();
Vector eventVector1;
dateObj2 = new MyDate();
dateObj2.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
dateObj2.setDayName(calendarUtilGetDay(calObj.getDay_Of_Week(false)));
dateObj2.setNameOfMonth(calendarUtilGetMonth(calObj.getMonthInteger()));
if (calObj.getDayOfMonth() == dayObj.getDay())
dateObj2.setFlag(1);
if(state.getCurrentPage().equals("third"))
{
eventVector1 = new Vector();
// JS -- the third page starts at 2PM(14 o'clock), and lasts 20 half-hour
eventVector = getNewEvents(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), state, runData,THIRD_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
for(int index = 0;index<eventVector1.size();index++)
{
eventVector.add(eventVector.size(),eventVector1.get(index));
}
// Reminder: weekview vm is using 0..6
pageStartTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), THIRD_PAGE_START_HOUR, 0, 0, 0);
pageEndTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), 23, 59, 0, 0);
}
else if (state.getCurrentPage().equals("second"))
{
eventVector = getNewEvents(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), state, runData,SECOND_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
// Reminder: weekview vm is using 0..6
pageStartTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), SECOND_PAGE_START_HOUR, 0, 0, 0);
pageEndTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), 17, 59, 0, 0);
}
else
{
eventVector1 = new Vector();
// JS -- the first page starts at 12AM(0 o'clock), and lasts 20 half-hour
eventVector1 = getNewEvents(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), state, runData, FIRST_PAGE_START_HOUR,19,context,CalendarEventVectorObj);
for(int index = 0;index<eventVector1.size();index++)
{
eventVector.insertElementAt(eventVector1.get(index),index);
}
// Reminder: weekview vm is using 0..6
pageStartTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), 0, 0, 0, 0);
pageEndTime[i-1] = TimeService.newTimeLocal(calObj.getYear(),calObj.getMonthInteger(),calObj.getDayOfMonth(), 9, 59, 0, 0);
}
dateObj2.setEventBerWeek(eventVector);
weekObj.setWeek(7-i,dateObj2);
// the purpose of this if condition is to check if we reached day 7 if yes do not
// call next day.
if (i > dayofweek)
calObj.nextDate();
}
calObj.setDay(yearObj.getYear(),monthObj1.getMonth(),dayObj.getDay());
context.put("week", weekObj);
context.put("helper",new Helper());
context.put("date",dateObj1);
context.put("page",state.getCurrentPage());
state.setState("week");
context.put("tlang",rb);
context.put("config",configProps);
context.put("message",state.getState());
DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL, new ResourceLoader().getLocale());
formatter.setTimeZone(TimeService.getLocalTimeZone());
try{
context.put("beginWeek", formatter.format(calObj.getPrevTime(calObj.getDay_Of_Week(true)-1)));
}catch(Exception e){
context.put("beginWeek", calObj.getTodayDate());
}
try{
calObj.setNextWeek();
context.put("endWeek",formatter.format(calObj.getPrevTime(1)));
}catch(Exception e){
context.put("endWeek", calObj.getTodayDate());
}
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
calObj.setDay(yearObj.getYear(),monthObj1.getMonth(),dayObj.getDay());
context.put("realDate", TimeService.newTime());
context.put("tlang",rb);
context.put("config",configProps);
Vector vec = new Vector();
context.put("vec", vec);
Vector conflictVec = new Vector();
context.put("conflictVec", conflictVec);
Vector calVec = new Vector();
context.put("calVec", calVec);
HashMap hm = new HashMap();
context.put("hm", hm);
Integer intObj = Integer.valueOf(0);
context.put("intObj", intObj);
context.put("pageStartTime", pageStartTime);
context.put("pageEndTime", pageEndTime);
context.put("selectedView", rb.getString("java.byweek"));
context.put("dayOfWeekNames", calObj.getCalendarDaysOfWeekNames(false));
} // buildWeekContext
/**
* Build the context for showing New view
*/
protected void buildNewContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
context.put("tlang",rb);
context.put("config",configProps);
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
MyDate dateObj1 = new MyDate();
CalendarUtil calObj= new CalendarUtil();
// set real today's date as default
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
calObj.setDay(b.getYear(), b.getMonth(), b.getDay());
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
// get the event id from the CalendarService.
// send the event to the vm
dateObj1.setNumberOfDaysInMonth(calObj.getNumberOfDays());
List attachments = state.getAttachments();
context.put("attachments",attachments);
String calId = state.getPrimaryCalendarReference();
Calendar calendarObj = null;
try
{
calendarObj = CalendarService.getCalendar(calId);
Collection groups = calendarObj.getGroupsAllowAddEvent();
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
if (scheduleTo != null && scheduleTo.length() != 0)
{
context.put("scheduleTo", scheduleTo);
}
else
{
if (calendarObj.allowAddCalendarEvent())
{
// default to make site selection
context.put("scheduleTo", "site");
}
else if (groups.size() > 0)
{
// to group otherwise
context.put("scheduleTo", "groups");
}
}
if (groups.size() > 0)
{
List schToGroups = (List)(sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS));
context.put("scheduleToGroups", schToGroups);
context.put("groups", groups);
}
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".buildNewContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".buildNewContext(): " + e);
return;
}
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsIntoContextFromCalendar( calendarObj, context);
// Output for recurring events
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
// if the saved recurring rule equals to string FREQ_ONCE, set it as not recurring
// if there is a saved recurring rule in sstate, display it
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
if (rule != null)
{
context.put("freq", rule.getFrequencyDescription());
context.put("rule", rule);
}
context.put("date",dateObj1);
context.put("savedData",state.getNewData());
context.put("helper",new Helper());
context.put("realDate", TimeService.newTime());
} // buildNewContext
/**
* Setup for iCal Export.
*/
public String buildIcalExportPanelContext(VelocityPortlet portlet, Context context, RunData rundata, CalendarActionState state)
{
String calId = state.getPrimaryCalendarReference();
Calendar calendarObj = null;
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch ( Exception e )
{
M_log.debug(".buildIcalExportPanelContext: " + e);
}
context.put("tlang", rb);
context.put("config",configProps);
// provide form names
context.put("form-alias", FORM_ALIAS);
context.put("form-ical-enable", FORM_ICAL_ENABLE);
context.put("form-submit", BUTTON + "doIcalExport");
context.put("form-cancel", BUTTON + "doCancel");
if ( calendarObj != null )
{
List aliasList = AliasService.getAliases( calendarObj.getReference() );
if ( ! aliasList.isEmpty() )
{
String alias[] = ((Alias)aliasList.get(0)).getId().split("\\.");
context.put("alias", alias[0] );
}
}
context.put("serverName", ServerConfigurationService.getServerName());
// Add iCal Export URL
Reference calendarRef = EntityManager.newReference(calId);
String icalUrl = ServerConfigurationService.getAccessUrl()
+ CalendarService.calendarICalReference(calendarRef);
context.put("icalUrl", icalUrl );
boolean exportAllowed = CalendarPermissions.allowImport( calId );
context.put("allow_export", String.valueOf(exportAllowed) );
boolean exportEnabled = CalendarService.getExportEnabled(calId);
context.put("enable_export", String.valueOf(exportEnabled) );
// pick the "export" template based on the standard template name
String template = (String) getContext(rundata).get("template");
return template + "_icalexport";
} // buildIcalExportPanelContext
/**
* Build the context for showing delete view
*/
protected void buildDeleteContext(VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state)
{
context.put("tlang",rb);
context.put("config",configProps);
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
Calendar calendarObj = null;
CalendarEvent calEvent = null;
// get the event id from the CalendarService.
// send the event to the vm
String calId = state.getPrimaryCalendarReference();
String calendarEventObj = state.getCalendarEventId();
try
{
calendarObj = CalendarService.getCalendar(calId);
calEvent = calendarObj.getEvent(calendarEventObj);
RecurrenceRule rule = calEvent.getRecurrenceRule();
// for a brand new event, there is no saved recurring rule
if (rule != null)
{
context.put("freq", rule.getFrequencyDescription());
context.put("rule", rule);
}
context.put("message","delete");
context.put("event",calEvent);
// show all the groups in this calendar that user has get event in
Collection groups = calendarObj.getGroupsAllowGetEvent();
if (groups != null)
{
context.put("groupRange", calEvent.getGroupRangeForDisplay(calendarObj));
}
}
catch (IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.noexist"));
M_log.debug(".buildDeleteContext(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youcreate"));
M_log.debug(".buildDeleteContext(): " + e);
}
} // buildDeleteContext
/**
* calculate the days in the month and there events if any
* @param month is int
* @param m_calObj is object of calendar
*/
public MyMonth calMonth(int month, CalendarUtil m_calObj, CalendarActionState state, CalendarEventVector CalendarEventVectorObj)
{
int numberOfDays = 0;
int firstDay_of_Month = 0;
boolean start = true;
MyMonth monthObj = null;
MyDate dateObj = null;
Iterator eventList = null;
Time startTime = null;
Time endTime = null;
TimeRange timeRange = null;
// new objects of myYear, myMonth, myDay, myWeek classes.
monthObj = new MyMonth();
// set the calendar to the begining of the month
m_calObj.setDay(m_calObj.getYear(), month, 1);
numberOfDays = m_calObj.getNumberOfDays();
// get the index of the first day in the month
firstDay_of_Month = m_calObj.getDay_Of_Week(true) - 1;
// get the index of the day
monthObj.setMonthName(calendarUtilGetMonth(m_calObj.getMonthInteger()));
// get the index of first day (-1) to display (may be in previous month)
m_calObj.setPrevDate(firstDay_of_Month+1);
for(int weekInMonth = 0; weekInMonth < 1; weekInMonth++)
{
// got the seven days in the first week of the month do..
for(int dayInWeek = 0; dayInWeek < 7; dayInWeek++)
{
dateObj = new MyDate();
m_calObj.nextDate();
// check if reach the first day of the month.
if ((dayInWeek == firstDay_of_Month) || (start == false))
{
// check if the current day of the month has been match, if yes set the flag to highlight the day in the
// user interface.
if ((m_calObj.getDayOfMonth() == state.getcurrentDay()) && (state.getcurrentMonth()== m_calObj.getMonthInteger()) && (state.getcurrentYear() == m_calObj.getYear()))
{
dateObj.setFlag(1);
}
// Each monthObj contains dayObjs for the number of the days in the month.
dateObj.setTodayDate(m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),m_calObj.getYear());
startTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),00,00,00,001);
endTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),23,59,00,000);
eventList = CalendarEventVectorObj.getEvents(TimeService.newTimeRange(startTime,endTime,true,true));
dateObj.setEvents(eventList);
// keep iterator of events in the dateObj
numberOfDays--;
monthObj.setDay(dateObj,weekInMonth,dayInWeek);
start = false;
}
else if (start == true)
{
// fill empty spaces for the first days in the first week in the month before reach the first day of the month
dateObj.setTodayDate(m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),m_calObj.getYear());
startTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),00,00,00,001);
endTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),23,59,00,000);
timeRange = TimeService.newTimeRange(startTime,endTime,true,true);
eventList = CalendarEventVectorObj.getEvents(timeRange);
dateObj.setEvents(eventList);
monthObj.setDay(dateObj,weekInMonth,dayInWeek);
dateObj.setFlag(0);
}// end else
}// end for m
}// end for i
// Construct the weeks left in the month and save it in the monthObj.
// row is the max number of rows in the month., Col is equal to 7 which is the max number of col in the month.
for(int row = 1; row<6; row++)
{
// Col is equal to 7 which is the max number of col in tin he month.
for(int col = 0; col<7; col++)
{
if (numberOfDays != 0)
{
dateObj = new MyDate();
m_calObj.nextDate();
if ((m_calObj.getDayOfMonth() == state.getcurrentDay()) && (state.getcurrentMonth()== m_calObj.getMonthInteger()) && (state.getcurrentYear() == m_calObj.getYear()))
dateObj.setFlag(1);
dateObj.setTodayDate(m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),m_calObj.getYear());
startTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),00,00,00,001);
endTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),23,59,00,000);
timeRange = TimeService.newTimeRange(startTime,endTime,true,true);
eventList = CalendarEventVectorObj.getEvents(timeRange);
dateObj.setEvents(eventList);
numberOfDays--;
monthObj.setDay(dateObj,row,col);
monthObj.setRow(row);
}
else // if it is not the end of week , complete the week wih days from next month.
{
if ((m_calObj.getDay_Of_Week(true))== 7) // if end of week, exit the loop
{
row = 7;
col = SECOND_PAGE_START_HOUR;
}
else // if it is not the end of week, complete with days from next month
{
dateObj = new MyDate();
m_calObj.nextDate();
dateObj.setTodayDate(m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),m_calObj.getYear());
startTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),00,00,00,001);
endTime = TimeService.newTimeLocal(m_calObj.getYear(),m_calObj.getMonthInteger(),m_calObj.getDayOfMonth(),23,59,00,000);
timeRange = TimeService.newTimeRange(startTime,endTime,true,true);
eventList = CalendarEventVectorObj.getEvents(timeRange);
dateObj.setEvents(eventList);
monthObj.setDay(dateObj,row,col);
monthObj.setRow(row);
dateObj.setFlag(0);
}
}
}// end for
}// end for
return monthObj;
}
public void doAttachments(RunData rundata, Context context)
{
// get into helper mode with this helper tool
startHelper(rundata.getRequest(), "sakai.filepicker");
// setup the parameters for the helper
SessionState state = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid());
CalendarActionState State = (CalendarActionState)getState( context, rundata, CalendarActionState.class );
int houri;
// put a the real attachments into the stats - let the helper update it directly if the user chooses to save their attachment editing.
List attachments = State.getAttachments();
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, attachments);
String hour = "";
hour = rundata.getParameters().getString("startHour");
String title ="";
title = rundata.getParameters().getString("activitytitle");
String minute = "";
minute = rundata.getParameters().getString("startMinute");
String dhour = "";
dhour = rundata.getParameters().getString("duHour");
String dminute = "";
dminute = rundata.getParameters().getString("duMinute");
String description = "";
description = rundata.getParameters().getString("description");
description = processFormattedTextFromBrowser(state, description);
String month = "";
month = rundata.getParameters().getString("month");
String day = "";
day = rundata.getParameters().getString("day");
String year = "";
year = rundata.getParameters().getString("yearSelect");
String timeType = "";
timeType = rundata.getParameters().getString("startAmpm");
String type = "";
type = rundata.getParameters().getString("eventType");
String location = "";
location = rundata.getParameters().getString("location");
readEventGroupForm(rundata, context);
// read the recurrence modification intention
String intentionStr = rundata.getParameters().getString("intention");
if (intentionStr == null) intentionStr = "";
Calendar calendarObj = null;
String calId = State.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".buildCustomizeContext(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".buildCustomizeContext(): " + e);
return;
}
Map addfieldsMap = new HashMap();
// Add any additional fields in the calendar.
customizeCalendarPage. loadAdditionalFieldsMapFromRunData(rundata, addfieldsMap, calendarObj);
if (timeType.equals("pm"))
{
if (Integer.parseInt(hour)>11)
houri = Integer.parseInt(hour);
else
houri = Integer.parseInt(hour)+12;
}
else if (timeType.equals("am") && Integer.parseInt(hour)==12)
{
houri = 24;
}
else
{
houri = Integer.parseInt(hour);
}
State.clearData();
State.setNewData(State.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
// **************** changed for the new attachment editor **************************
} // doAttachments
/**
* Action is used when doMonth requested in the menu
*/
public void doMonth(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
state.setState("month");
} // doMonth
/**
* Action is used when doDescription is requested when the user click on an event
*/
public void doDescription(RunData data, Context context)
{
CalendarEvent calendarEventObj = null;
Calendar calendarObj = null;
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
// "crack" the reference (a.k.a dereference, i.e. make a Reference)
// and get the event id and calendar reference
Reference ref = EntityManager.newReference(data.getParameters().getString(EVENT_REFERENCE_PARAMETER));
String eventId = ref.getId();
String calId = null;
if(CalendarService.REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
calId = CalendarService.calendarSubscriptionReference(ref.getContext(), ref.getContainer());
else
calId = CalendarService.calendarReference(ref.getContext(), ref.getContainer());
// %%% get the event object from the reference new Reference(data.getParameters().getString(EVENT_REFERENCE_PARAMETER)).getResource() -ggolden
try
{
calendarObj = CalendarService.getCalendar(calId);
try
{
calendarEventObj = calendarObj.getEvent(eventId);
TimeBreakdown b = calendarEventObj.getRange().firstTime().breakdownLocal();
sstate.setAttribute(STATE_YEAR, Integer.valueOf(b.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(b.getMonth()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(b.getDay()));
sstate.setAttribute(STATE_NAV_DIRECTION, STATE_CURRENT_ACT);
}
catch (IdUnusedException err)
{
// if this event doesn't exist, let user not go to the detail view
// set the state recorded ID as null
// show the alert message
M_log.debug(".IdUnusedException " + err);
state.setCalendarEventId("", "");
String errorCode = rb.getString("java.error");
addAlert(sstate, errorCode);
return;
}
catch (PermissionException err)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.debug(".PermissionException " + err);
return;
}
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
return;
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
return;
}
// store the state coming from, like day view, week view, month view or list view
String returnState = state.getState();
state.setPrevState(returnState);
state.setReturnState(returnState);
state.setState("description");
state.setAttachments(null);
state.setCalendarEventId(calId, eventId);
} // doDescription
/**
* Action is used when doGomonth requested in the year/list view
*/
public void doGomonth(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil();
m_calObj.setDay(stateYear, stateMonth, stateDay);
String month = "";
month = data.getParameters().getString("month");
m_calObj.setMonth(Integer.parseInt(month));
// if this function is called from list view
// the value of year must be caught also
int yearInt = m_calObj.getYear();
String currentState = state.getState();
if (currentState.equalsIgnoreCase("list"))
{
String year = "";
year = data.getParameters().getString("year");
yearInt = Integer.parseInt(year);
}
m_calObj.setDay(yearInt, m_calObj.getMonthInteger(), m_calObj.getDayOfMonth());
sstate.setAttribute(STATE_YEAR, Integer.valueOf(yearInt));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
state.setState("month");
} // doGomonth
/**
* Action is used when doGoyear requested in the list view
*/
public void doGoyear(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil();
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
m_calObj.setDay(stateYear, stateMonth, stateDay);
// catch the year value from the list view
int yearInt = m_calObj.getYear();
String currentState = state.getState();
if (currentState.equalsIgnoreCase("list"))
{
String year = "";
year = data.getParameters().getString("year");
yearInt = Integer.parseInt(year);
}
m_calObj.setDay(yearInt, m_calObj.getMonthInteger(), m_calObj.getDayOfMonth());
sstate.setAttribute(STATE_YEAR, Integer.valueOf(yearInt));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
state.setState("year");
} // doGoyear
/**
* Action is used when doOk is requested when user click on Back button
*/
public void doOk(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
// return to the state coming from
String returnState = state.getReturnState();
state.setState(returnState);
}
/**
* Action is used when the user click on the doRevise in the menu
*/
public void doRevise(RunData data, Context context)
{
CalendarEvent calendarEventObj = null;
Calendar calendarObj = null;
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String calId = state.getPrimaryCalendarReference();
state.setPrevState(state.getState());
state.setState("goToReviseCalendar");
state.setIsNewCalendar(false);
state.setfromAttachmentFlag("false");
sstate.setAttribute(FREQUENCY_SELECT, null);
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
state.clearData();
try
{
calendarObj = CalendarService.getCalendar(calId);
try
{
String eventId = state.getCalendarEventId();
// get the edit object, and lock the event for the furthur revise
CalendarEventEdit edit = calendarObj.getEditEvent(eventId, org.sakaiproject.calendar.api.CalendarService.EVENT_MODIFY_CALENDAR);
state.setEdit(edit);
state.setPrimaryCalendarEdit(edit);
calendarEventObj = calendarObj.getEvent(eventId);
state.setAttachments(calendarEventObj.getAttachments());
}
catch (IdUnusedException err)
{
// if this event doesn't exist, let user stay in activity view
// set the state recorded ID as null
// show the alert message
// reset the menu button display, no revise/delete
M_log.debug(".IdUnusedException " + err);
state.setState("description");
state.setCalendarEventId("", "");
String errorCode = rb.getString("java.alert.event");
addAlert(sstate, errorCode);
}
catch (PermissionException err)
{
M_log.debug(".PermissionException " + err);
}
catch (InUseException err)
{
M_log.debug(".InUseException " + err);
state.setState("description");
String errorCode = rb.getString("java.alert.eventbeing");
addAlert(sstate, errorCode);
}
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
}
} // doRevise
/**
* Handle the "continue" button on the schedule import wizard.
*/
public void doScheduleContinue(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
if ( SELECT_TYPE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) )
{
// If the type is Outlook or MeetingMaker, the next state is
// the "other" file select mode where we just select a file without
// all of the extra info on the generic import page.
String importType = data.getParameters ().getString(WIZARD_IMPORT_TYPE);
if ( CalendarImporterService.OUTLOOK_IMPORT.equals(importType) || CalendarImporterService.MEETINGMAKER_IMPORT.equals(importType) || CalendarImporterService.ICALENDAR_IMPORT.equals(importType))
{
if (CalendarImporterService.OUTLOOK_IMPORT.equals(importType))
{
state.setImportWizardType(CalendarImporterService.OUTLOOK_IMPORT);
state.setImportWizardState(OTHER_SELECT_FILE_IMPORT_WIZARD_STATE);
}
else if (CalendarImporterService.MEETINGMAKER_IMPORT.equals(importType))
{
state.setImportWizardType(CalendarImporterService.MEETINGMAKER_IMPORT);
state.setImportWizardState(OTHER_SELECT_FILE_IMPORT_WIZARD_STATE);
}
else
{
state.setImportWizardType(CalendarImporterService.ICALENDAR_IMPORT);
state.setImportWizardState(ICAL_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
else
{
// Remember the type we're importing
state.setImportWizardType(CalendarImporterService.CSV_IMPORT);
state.setImportWizardState(GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
else if ( GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) )
{
boolean importSucceeded = false;
// Do the import and send us to the confirm page
FileItem importFile = data.getParameters().getFileItem(WIZARD_IMPORT_FILE);
try
{
Map columnMap = CalendarImporterService.getDefaultColumnMap(CalendarImporterService.CSV_IMPORT);
String [] addFieldsCalendarArray = getCustomFieldsArray(state, sstate);
if ( addFieldsCalendarArray != null )
{
// Add all custom columns. Assume that there will be no
// name collisions. (Maybe a marginal assumption.)
for ( int i=0; i < addFieldsCalendarArray.length; i++)
{
columnMap.put(
addFieldsCalendarArray[i],
addFieldsCalendarArray[i]);
}
}
state.setWizardImportedEvents(
CalendarImporterService.doImport(
CalendarImporterService.CSV_IMPORT,
new ByteArrayInputStream(importFile.get()),
columnMap,
addFieldsCalendarArray));
importSucceeded = true;
}
catch (ImportException e)
{
addAlert(sstate, e.getMessage());
}
if ( importSucceeded )
{
// If all is well, go on to the confirmation page.
state.setImportWizardState(CONFIRM_IMPORT_WIZARD_STATE);
}
else
{
// If there are errors, send us back to the file selection page.
state.setImportWizardState(GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
else if ( OTHER_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) ||
ICAL_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) )
{
boolean importSucceeded = false;
// Do the import and send us to the confirm page
FileItem importFile = data.getParameters().getFileItem(WIZARD_IMPORT_FILE);
String [] addFieldsCalendarArray = getCustomFieldsArray(state, sstate);
try
{
state.setWizardImportedEvents(
CalendarImporterService.doImport(
state.getImportWizardType(),
new ByteArrayInputStream(importFile.get()),
null,
addFieldsCalendarArray));
importSucceeded = true;
}
catch (ImportException e)
{
addAlert(sstate, e.getMessage());
}
if ( importSucceeded )
{
// If all is well, go on to the confirmation page.
state.setImportWizardState(CONFIRM_IMPORT_WIZARD_STATE);
}
else
{
// If there are errors, send us back to the file selection page.
state.setImportWizardState(OTHER_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
else if ( CONFIRM_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()) )
{
// If there are errors, send us back to Either
// the OTHER_SELECT_FILE or GENERIC_SELECT_FILE states.
// Otherwise, we're done.
List wizardCandidateEventList = state.getWizardImportedEvents();
// for group awareness - read user selection
readEventGroupForm(data, context);
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
Collection groupChoice = (Collection) sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS);
if ( scheduleTo != null &&
( scheduleTo.equals("site") ||
(scheduleTo.equals("groups") && groupChoice!=null && groupChoice.size()>0) ) )
{
for ( int i =0; i < wizardCandidateEventList.size(); i++ )
{
// The line numbers are one-based.
String selectionName = "eventSelected" + (i+1);
String selectdValue = data.getParameters().getString(selectionName);
if ( TRUE_STRING.equals(selectdValue) )
{
// Add the events
String calId = state.getPrimaryCalendarReference();
try
{
Calendar calendarObj = CalendarService.getCalendar(calId);
CalendarEvent event = (CalendarEvent) wizardCandidateEventList.get(i);
CalendarEventEdit newEvent = calendarObj.addEvent();
state.setEdit(newEvent);
if ( event.getDescriptionFormatted() != null )
{
newEvent.setDescriptionFormatted( event.getDescriptionFormatted() );
}
// Range must be present at this point, so don't check for null.
newEvent.setRange(event.getRange());
if ( event.getDisplayName() != null )
{
newEvent.setDisplayName(event.getDisplayName());
}
// The type must have either been set or defaulted by this point.
newEvent.setType(event.getType());
if ( event.getLocation() != null )
{
newEvent.setLocation(event.getLocation());
}
if ( event.getRecurrenceRule() != null )
{
newEvent.setRecurrenceRule(event.getRecurrenceRule());
}
String [] customFields = getCustomFieldsArray(state, sstate);
// Set the creator
newEvent.setCreator();
// Copy any custom fields.
if ( customFields != null )
{
for ( int j = 0; j < customFields.length; j++ )
{
newEvent.setField(customFields[j], event.getField(customFields[j]));
}
}
// group awareness
try
{
// for site event
if (scheduleTo.equals("site"))
{
newEvent.clearGroupAccess();
}
// for grouped event
else if (scheduleTo.equals("groups"))
{
Site site = SiteService.getSite(calendarObj.getContext());
// make a collection of Group objects from the collection of group ref strings
Collection groups = new Vector();
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupRef = (String) iGroups.next();
groups.add(site.getGroup(groupRef));
}
newEvent.setGroupAccess(groups, true);
}
}
catch (Exception e)
{
M_log.warn("doScheduleContinue: " + e);
}
calendarObj.commitEvent(newEvent);
state.setEdit(null);
}
catch (IdUnusedException e)
{
addAlert(sstate, e.getMessage());
M_log.debug(".doScheduleContinue(): " + e);
break;
}
catch (PermissionException e)
{
addAlert(sstate, e.getMessage());
M_log.debug(".doScheduleContinue(): " + e);
break;
}
}
}
// Cancel wizard mode.
doCancelImportWizard(data, context);
}
else
{
addAlert(sstate, rb.getString("java.alert.youchoosegroup"));
}
}
}
/**
* Get an array of custom field names (if any)
*/
private String[] getCustomFieldsArray(
CalendarActionState state,
SessionState sstate)
{
Calendar calendarObj = null;
try
{
calendarObj =
CalendarService.getCalendar(
state.getPrimaryCalendarReference());
}
catch (IdUnusedException e1)
{
// Ignore
}
catch (PermissionException e)
{
addAlert(sstate, e.getMessage());
}
// Get a current list of add fields. This is a comma-delimited string.
String[] addFieldsCalendarArray = null;
if ( calendarObj != null )
{
String addfieldsCalendars = calendarObj.getEventFields();
if (addfieldsCalendars != null)
{
addFieldsCalendarArray =
fieldStringToArray(
addfieldsCalendars,
ADDFIELDS_DELIMITER);
}
}
return addFieldsCalendarArray;
}
/**
* Handle the back button on the schedule import wizard
*/
public void doScheduleBack(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
if (GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState())
|| OTHER_SELECT_FILE_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()))
{
state.setImportWizardState(SELECT_TYPE_IMPORT_WIZARD_STATE);
}
else
if (CONFIRM_IMPORT_WIZARD_STATE.equals(state.getImportWizardState()))
{
if (CalendarImporterService.OUTLOOK_IMPORT.equals(state.getImportWizardType())
|| CalendarImporterService.MEETINGMAKER_IMPORT.equals(state.getImportWizardType()))
{
state.setImportWizardState(OTHER_SELECT_FILE_IMPORT_WIZARD_STATE);
}
else if (CalendarImporterService.ICALENDAR_IMPORT.equals(state.getImportWizardType()))
{
state.setImportWizardState(ICAL_SELECT_FILE_IMPORT_WIZARD_STATE);
}
else
{
state.setImportWizardState(GENERIC_SELECT_FILE_IMPORT_WIZARD_STATE);
}
}
}
/**
* Called when the user cancels the import wizard.
*/
public void doCancelImportWizard(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
// Get rid of any events
state.setWizardImportedEvents(null);
// Make sure that we start the wizard at the beginning.
state.setImportWizardState(null);
// Return to the previous state.
state.setState(state.getPrevState());
}
/**
* Action is used when the docancel is requested when the user click on cancel in the new view
*/
public void doCancel(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Calendar calendarObj = null;
String currentState = state.getState();
String returnState = state.getReturnState();
if (currentState.equals(STATE_NEW))
{
// no need to release the lock.
// clear the saved recurring rule and the selected frequency
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, null);
}
else
if (currentState.equals(STATE_CUSTOMIZE_CALENDAR))
{
customizeCalendarPage.doCancel(data, context, state, getSessionState(data));
returnState=state.getPrevState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
returnState = "description";
}
}
else
if (currentState.equals(STATE_CALENDAR_SUBSCRIPTIONS))
{
calendarSubscriptionsPage.doCancel(data, context, state, getSessionState(data));
//returnState=state.getPrevState();
returnState=state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
returnState = "description";
}
}
else
if (currentState.equals(STATE_MERGE_CALENDARS))
{
mergedCalendarPage.doCancel(data, context, state, getSessionState(data));
returnState=state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
returnState = "description";
}
}
else // in revise view, state name varies
if ((currentState.equals("revise"))|| (currentState.equals("goToReviseCalendar")))
{
String calId = state.getPrimaryCalendarReference();
if (state.getPrimaryCalendarEdit() != null)
{
try
{
calendarObj = CalendarService.getCalendar(calId);
// the event is locked, now we need to release the lock
calendarObj.cancelEvent(state.getPrimaryCalendarEdit());
state.setPrimaryCalendarEdit(null);
state.setEdit(null);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
}
}
// clear the saved recurring rule and the selected frequency
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, null);
}
else if (currentState.equals(STATE_SET_FREQUENCY))// cancel at frequency editing page
{
returnState = (String)sstate.getAttribute(STATE_BEFORE_SET_RECURRENCE);
}
state.setState(returnState);
state.setAttachments(null);
} // doCancel
/**
* Action is used when the doBack is called when the user click on the back on the EventActivity view
*/
public void doBack(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Calendar calendarObj = null;
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
// the event is locked, now we need to release the lock
calendarObj.cancelEvent(state.getPrimaryCalendarEdit());
state.setPrimaryCalendarEdit(null);
state.setEdit(null);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
}
String returnState = state.getReturnState();
state.setState(returnState);
} // doBack
/**
* Action is used when the doDelete is called when the user click on delete in menu
*/
public void doDelete(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
CalendarEvent calendarEventObj = null;
Calendar calendarObj = null;
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
try
{
String eventId = state.getCalendarEventId();
// get the edit object, and lock the event for the furthur revise
CalendarEventEdit edit = calendarObj.getEditEvent(eventId,
org.sakaiproject.calendar.api.CalendarService.EVENT_REMOVE_CALENDAR);
state.setEdit(edit);
state.setPrimaryCalendarEdit(edit);
calendarEventObj = calendarObj.getEvent(eventId);
state.setAttachments(calendarEventObj.getAttachments());
// after deletion, it needs to go back to previous page
// if coming from description, it won't go back to description
// but the state one step ealier
String returnState = state.getState();
if (!returnState.equals("description"))
{
state.setReturnState(returnState);
}
state.setState("delete");
}
catch (IdUnusedException err)
{
// if this event doesn't exist, let user stay in activity view
// set the state recorded ID as null
// show the alert message
// reset the menu button display, no revise/delete
M_log.debug(".IdUnusedException " + err);
state.setState("description");
state.setCalendarEventId("", "");
String errorCode = rb.getString("java.alert.event");
addAlert(sstate, errorCode);
}
catch (PermissionException err)
{
M_log.debug(".PermissionException " + err);
}
catch (InUseException err)
{
M_log.debug(".InUseException delete" + err);
state.setState("description");
String errorCode = rb.getString("java.alert.eventbeing");
addAlert(sstate, errorCode);
}
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
}
} // doDelete
/**
* Action is used when the doConfirm is called when the user click on confirm to delete event in the delete view.
*/
public void doConfirm(RunData data, Context context)
{
Calendar calendarObj = null;
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
// read the intention field
String intentionStr = data.getParameters().getString("intention");
int intention = CalendarService.MOD_NA;
if ("t".equals(intentionStr)) intention = CalendarService.MOD_THIS;
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
CalendarEventEdit edit = state.getPrimaryCalendarEdit();
calendarObj.removeEvent(edit, intention);
state.setPrimaryCalendarEdit(null);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doConfirm(): " + e);
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.debug(".doConfirm(): " + e);
}
String returnState = state.getReturnState();
state.setState(returnState);
} // doConfirm
public void doView (RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String viewMode = data.getParameters ().getString("view");
if (viewMode.equalsIgnoreCase(rb.getString("java.byday")))
{
doMenueday(data, context);
}
else if (viewMode.equalsIgnoreCase(rb.getString("java.byweek")))
{
doWeek(data, context);
}
else if (viewMode.equalsIgnoreCase(rb.getString("java.bymonth")))
{
doMonth(data, context);
}
else if (viewMode.equalsIgnoreCase(rb.getString("java.byyear")))
{
doYear(data, context);
}
else if (viewMode.equalsIgnoreCase(rb.getString("java.listeve")))
{
doList(data, context);
}
state.setAttribute(STATE_SELECTED_VIEW, viewMode);
} // doView
/**
* Action doYear is requested when the user click on Year on menu
*/
public void doYear(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
state.setState("year");
} // doYear
/**
* Action doWeek is requested when the user click on the week item in then menu
*/
public void doWeek(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
state.setState("week");
} // doWeek
/**
* Action doDay is requested when the user click on the day item in the menue
*/
public void doDay(RunData data, Context context)
{
String year = null;
year = data.getParameters().getString("year");
String month = null;
month = data.getParameters().getString("month");
String day = null;
day = data.getParameters().getString("day");
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
sstate.setAttribute(STATE_YEAR, Integer.valueOf(Integer.parseInt(year)));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(Integer.parseInt(month)));
sstate.setAttribute(STATE_DAY, Integer.valueOf(Integer.parseInt(day)));
state.setPrevState(state.getState()); // remember the coming state from Month, Year or List
state.setState("day");
} // doDay
/**
* Action doToday is requested when the user click on "Go to today" button
*/
public void doToday(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
CalendarUtil m_calObj = new CalendarUtil();
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
m_calObj.setDay(b.getYear(), b.getMonth(), b.getDay());
sstate.setAttribute(STATE_YEAR, Integer.valueOf(b.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(b.getMonth()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(b.getDay()));
state.setState("day");
//for dropdown menu display purpose
sstate.setAttribute(STATE_SELECTED_VIEW, rb.getString("java.byday"));
} // doToday
/**
* Action doCustomDate is requested when the user specifies a start/end date
* to filter the list view.
*/
public void doCustomdate(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String sY = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_START_YEAR);
String sM = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_START_MONTH);
String sD = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_START_DAY);
String eY = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_END_YEAR);
String eM = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_END_MONTH);
String eD = data.getParameters().getString(TIME_FILTER_SETTING_CUSTOM_END_DAY);
if (sM.length() == 1) sM = "0"+sM;
if (eM.length() == 1) eM = "0"+eM;
if (sD.length() == 1) sD = "0"+sD;
if (eD.length() == 1) eD = "0"+eD;
sY = sY.substring(2);
eY = eY.substring(2);
String startingDateStr = sM + "/" + sD + "/" + sY;
String endingDateStr = eM + "/" + eD + "/" + eY;
// Pass in a buffer for a possible error message.
StringBuilder errorMessage = new StringBuilder();
// Try to simultaneously set the start/end dates.
// If that doesn't work, add an error message.
if ( !state.getCalendarFilter().setStartAndEndListViewDates(startingDateStr, endingDateStr, errorMessage) )
{
addAlert(sstate, errorMessage.toString());
}
} // doCustomdate
/**
* Action doFilter is requested when the user clicks on the list box
* to select a filtering mode for the list view.
*/
public void doFilter(RunData data, Context context)
{
CalendarActionState state =
(CalendarActionState) getState(context,
data,
CalendarActionState.class);
state.getCalendarFilter().setListViewFilterMode(
data.getParameters().getString(TIME_FILTER_OPTION_VAR));
} // doFilter
/**
* Action is requestd when the user select day from the menu avilable in some views.
*/
public void doMenueday(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
state.setState("day");
} // doMenueday
/**
* Action is requsted when the user select day from menu in Activityevent view.
*/
public void doActivityday(RunData data, Context context)
{
CalendarEvent ce = null;
Calendar calendarObj = null;
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
CalendarUtil m_calObj = new CalendarUtil();
String id = state.getCalendarEventId();
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
ce = calendarObj.getEvent(id);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.warn(".doActivityday(): " + e);
return;
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.warn(".doActivityday(): " + e);
return;
}
TimeRange tr = ce.getRange();
Time t = tr.firstTime();
TimeBreakdown b = t.breakdownLocal();
m_calObj.setDay(b.getYear(),b.getMonth(),b.getDay()) ;
sstate.setAttribute(STATE_YEAR, Integer.valueOf(b.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(b.getMonth()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(b.getDay()));
state.setState("day");
} // doActivityDay
/**
* Action doNext is called when the user click on next button to move to next day, next week, next month or next year.
*/
public void doNext(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String currentstate = state.getState();
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil();
m_calObj.setDay(stateYear, stateMonth, stateDay);
if (currentstate.equals("month"))
{
m_calObj.getNextMonth();
}
if (currentstate.equals("year"))
{
m_calObj.setNextYear();
}
if (currentstate.equals("day"))
{
String date = m_calObj.getNextDate();
state.setnextDate(date);
}
if (currentstate.equals("week"))
{
m_calObj.setNextWeek();
}
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
} // doNext
/**
* Action doNextday is called when the user click on "Tomorrow" link in day view
*/
public void doNextday(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String currentstate = state.getState();
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil(); //null;
m_calObj.setDay(stateYear, stateMonth, stateDay);
if (currentstate.equals("day"))
{
String date = m_calObj.getNextDate();
state.setnextDate(date);
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
// if this function is called thru "tomorrow" link
// the default page has to be changed to "first"
state.setCurrentPage("first");
}
} // doNextday
/**
* Action doPrev is requested when the user click on the prev button to move into pre day, month, year, or week.
*/
public void doPrev(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil();
m_calObj.setDay(stateYear, stateMonth, stateDay);
String currentstate = state.getState();
if (currentstate.equals("month"))
{
m_calObj.getPrevMonth();
}
if (currentstate.equals("year"))
{
m_calObj.setPrevYear();
}
if (currentstate.equals("day"))
{
String date = m_calObj.getPrevDate();
state.setprevDate(date);
}
if (currentstate.equals("week"))
{
m_calObj.setPrevWeek();
}
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
} // doPrev
/**
* Action doPreday is called when the user click on "Yesterday" link in day view
*/
public void doPreday(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String currentstate = state.getState();
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil m_calObj = new CalendarUtil(); //null;
m_calObj.setDay(stateYear, stateMonth, stateDay);
if (currentstate.equals("day"))
{
String date = m_calObj.getPrevDate();
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
state.setprevDate(date);
// if this function is called thru "Yesterday" link, it goes the last page of yesterday
// the default page has to be changed to "third"
state.setCurrentPage("third");
}
} // doPreday
/**
* Enter the schedule import wizard
*/
public void doImport(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
// Remember the state prior to entering the wizard.
state.setPrevState(state.getState());
// Enter wizard mode.
state.setState(STATE_SCHEDULE_IMPORT);
} // doImport
/**
* Action doIcalExportName acts on a "Export" request
*/
public void doIcalExportName(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
// store the state coming from
String returnState = state.getState();
if ( ! returnState.equals("description") )
{
state.setReturnState(returnState);
}
state.clearData();
state.setAttachments(null);
state.setPrevState(state.getState());
state.setState("icalEx");
} // doIcalExportName
/**
* Action doIcalExport acts on a "Submit" request in the icalexport form
*/
public void doIcalExport(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
String enable = StringUtils.trimToNull(data.getParameters().getString(FORM_ICAL_ENABLE));
String alias = StringUtils.trimToNull(data.getParameters().getString(FORM_ALIAS));
// this will verify that no invalid characters are used
if ( ! Validator.escapeResourceName(alias).equals(alias) )
{
addAlert(sstate, rb.getString("java.alert.invalidname"));
return;
}
String calId = state.getPrimaryCalendarReference();
Calendar calendarObj = null;
boolean oldExportEnabled = CalendarService.getExportEnabled(calId);
try
{
calendarObj = CalendarService.getCalendar(calId);
List aliasList = AliasService.getAliases( calendarObj.getReference() );
String oldAlias = null;
if ( ! aliasList.isEmpty() )
{
String aliasSplit[] = ((Alias)aliasList.get(0)).getId().split("\\.");
oldAlias = aliasSplit[0];
}
// Add the desired alias (if changed)
if ( alias != null && (oldAlias == null || !oldAlias.equals(alias)) )
{
// first, clear any alias set to this calendar
AliasService.removeTargetAliases(calendarObj.getReference());
alias += ".ics";
AliasService.setAlias(alias, calendarObj.getReference());
}
}
catch (IdUnusedException ie)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doIcalExport() Other: " + ie);
return;
}
catch (IdUsedException ue)
{
addAlert(sstate, rb.getString("java.alert.dupalias"));
return;
}
catch (PermissionException pe)
{
addAlert(sstate, rb.getString("java.alert.youdont"));
return;
}
catch (IdInvalidException e)
{
addAlert(sstate, rb.getString("java.alert.unknown"));
M_log.debug(".doIcalExport() Other: " + e);
return;
}
// enable/disable export (if changed)
if ( enable != null && !oldExportEnabled )
CalendarService.setExportEnabled( calId, true );
else if ( enable == null && oldExportEnabled )
CalendarService.setExportEnabled( calId, false );
String returnState = state.getReturnState();
state.setState(returnState);
} // doIcalExport
public void doNew(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
//clean group awareness state info
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
// store the state coming from
String returnState = state.getState();
if ( ! returnState.equals("description") )
{
state.setReturnState(returnState);
}
state.clearData();
state.setAttachments(null);
state.setPrevState(state.getState());
state.setState("new");
state.setCalendarEventId("", "");
state.setIsNewCalendar(true);
state.setIsPastAlertOff(true);
sstate.setAttribute(FREQUENCY_SELECT, null);
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
} // doNew
/**
* Read user inputs in announcement form
* @param data
* @param checkForm need to check form data or not
*/
protected void readEventGroupForm(RunData rundata, Context context)
{
String peid = ((JetspeedRunData) rundata).getJs_peid();
SessionState state =
((JetspeedRunData) rundata).getPortletSessionState(peid);
String scheduleTo = rundata.getParameters().getString("scheduleTo");
state.setAttribute(STATE_SCHEDULE_TO, scheduleTo);
if (scheduleTo.equals("groups"))
{
String[] groupChoice = rundata.getParameters().getStrings("selectedGroups");
if (groupChoice != null)
{
state.setAttribute(STATE_SCHEDULE_TO_GROUPS, new ArrayList(Arrays.asList(groupChoice)));
}
if (groupChoice== null || groupChoice.length == 0)
{
state.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
}
}
else
{
state.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
}
} // readEventGroupForm
/**
* Action doAdd is requested when the user click on the add in the new view to add an event into a calendar.
*/
public void doAdd(RunData runData, Context context)
{
CalendarUtil m_calObj = new CalendarUtil();// null;
Calendar calendarObj = null;
int houri;
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
m_calObj.setDay(stateYear, stateMonth, stateDay);
String hour = "";
hour = runData.getParameters().getString("startHour");
String title ="";
title = runData.getParameters().getString("activitytitle");
String minute = "";
minute = runData.getParameters().getString("startMinute");
String dhour = "";
dhour = runData.getParameters().getString("duHour");
String dminute = "";
dminute = runData.getParameters().getString("duMinute");
String description = "";
description = runData.getParameters().getString("description");
description = processFormattedTextFromBrowser(sstate, description);
String month = "";
month = runData.getParameters().getString("month");
String day = "";
day = runData.getParameters().getString("day");
String year = "";
year = runData.getParameters().getString("yearSelect");
String timeType = "";
timeType = runData.getParameters().getString("startAmpm");
String type = "";
type = runData.getParameters().getString("eventType");
String location = "";
location = runData.getParameters().getString("location");
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereisno"));
M_log.debug(".doAdd(): " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".doAdd(): " + e);
return;
}
// for section awareness - read user selection
readEventGroupForm(runData, context);
Map addfieldsMap = new HashMap();
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsMapFromRunData(runData, addfieldsMap, calendarObj);
if (timeType.equals("pm"))
{
if (Integer.parseInt(hour)>11)
houri = Integer.parseInt(hour);
else
houri = Integer.parseInt(hour)+12;
}
else if (timeType.equals("am") && Integer.parseInt(hour)==12)
{
// set 12 AM as the beginning of one day
houri = 0;
}
else
{
houri = Integer.parseInt(hour);
}
Time now_time = TimeService.newTime();
Time event_startTime = TimeService.newTimeLocal(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day), houri, Integer.parseInt(minute), 0, 0);
// conditions for an new event:
// 1st, frequency not touched, no save state rule or state freq (0, 0)
// --> non-recurring, no alert needed (0)
// 2st, frequency revised, there is a state-saved rule, and state-saved freq exists (1, 1)
// --> no matter if the start has been modified, compare the ending and starting date, show alert if needed (1)
// 3th, frequency revised, the state saved rule is null, but state-saved freq exists (0, 1)
// --> non-recurring, no alert needed (0)
// so the only possiblityto show the alert is under condistion 2.
boolean earlierEnding = false;
String freq = "";
if ((( freq = (String) sstate.getAttribute(FREQUENCY_SELECT))!= null)
&& (!(freq.equals(FREQ_ONCE))))
{
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
if (rule != null)
{
Time startingTime = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),houri,Integer.parseInt(minute),00,000);
Time endingTime = rule.getUntil();
if ((endingTime != null) && endingTime.before(startingTime))
earlierEnding = true;
} // if (rule != null)
} // if state saved freq is not null, and it not equals "once"
String intentionStr = ""; // there is no recurrence modification intention for new event
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
Collection groupChoice = (Collection) sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS);
if(title.length()==0)
{
String errorCode = rb.getString("java.pleasetitle");
addAlert(sstate, errorCode);
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
}
else if(hour.equals("100") || minute.equals("100"))
{
String errorCode = rb.getString("java.pleasetime");
addAlert(sstate, errorCode);
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
}
else if( earlierEnding ) // if ending date is earlier than the starting date, show alert
{
addAlert(sstate, rb.getString("java.theend") );
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
}
else if( event_startTime.before(now_time) && state.getIsPastAlertOff() )
{
// IsPastAlertOff
// true: no alert shown -> then show the alert, set false;
// false: Alert shown, if user click ADD - doAdd again -> accept it, set true, set alert empty;
String errorCode = rb.getString("java.alert.past");
addAlert(sstate, errorCode);
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
state.setIsPastAlertOff(false);
}
else if (!Validator.checkDate(Integer.parseInt(day), Integer.parseInt(month), Integer.parseInt(year)))
{
addAlert(sstate, rb.getString("date.invalid"));
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
}
else if (scheduleTo.equals("groups") && ((groupChoice == null) || (groupChoice.size() == 0)))
{
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("new");
addAlert(sstate, rb.getString("java.alert.youchoosegroup"));
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
Time timeObj = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),houri,Integer.parseInt(minute),00,000);
long du = (((Integer.parseInt(dhour) * 60)*60)*1000) + ((Integer.parseInt(dminute)*60)*(1000));
Time endTime = TimeService.newTime(timeObj.getTime() + du);
boolean includeEndTime = false;
if (du==0)
{
includeEndTime = true;
}
TimeRange range = TimeService.newTimeRange(timeObj, endTime, true, includeEndTime);
List attachments = state.getAttachments();
// prepare to create the event
Collection groups = new Vector();
CalendarEvent.EventAccess access = CalendarEvent.EventAccess.GROUPED;
if (scheduleTo.equals("site")) access = CalendarEvent.EventAccess.SITE;
if (access == CalendarEvent.EventAccess.GROUPED)
{
// make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite(calendarObj.getContext());
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupRef = (String) iGroups.next();
groups.add(site.getGroup(groupRef));
}
}
// create the event = must create it with grouping / access to start with
CalendarEvent event = calendarObj.addEvent(range, title, "", type, location, access, groups, attachments);
// edit it further
CalendarEventEdit edit = calendarObj.getEditEvent(event.getId(),
org.sakaiproject.calendar.api.CalendarService.EVENT_ADD_CALENDAR);
edit.setDescriptionFormatted(description);
edit.setCreator();
String timeZone = TimeService.getLocalTimeZone().getID();
// we obtain the time zone where the event is created
// and save it as an event's property
// it is necessary to generate re-occurring events correctly
edit.setField("createdInTimeZone",timeZone);
setFields(edit, addfieldsMap);
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
// for a brand new event, there is no saved recurring rule
if (rule != null)
edit.setRecurrenceRule(rule);
else
edit.setRecurrenceRule(null);
// save it
calendarObj.commitEvent(edit);
state.setEdit(null);
state.setIsNewCalendar(false);
m_calObj.setDay(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day));
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
// clear the saved recurring rule and the selected frequency
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, null);
// set the return state to be the state before new/revise
String returnState = state.getReturnState();
if (returnState != null)
{
state.setState(returnState);
}
else
{
state.setState("week");
}
// if going back to week/day view, we need to know which slot to go
// -- the slot containing the starting time of the new added event
if (state.getState().equals("week")||state.getState().equals("day"))
{
Time timeObj_p1 = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),FIRST_PAGE_START_HOUR,00,00,000);
Time timeObj_p2 = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),SECOND_PAGE_START_HOUR,00,00,000);
Time timeObj_p3 = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),THIRD_PAGE_START_HOUR,00,00,000);
if (timeObj.after(timeObj_p2) && timeObj.before(timeObj_p3))
state.setCurrentPage("second");
else if (timeObj.before(timeObj_p2))
state.setCurrentPage("first");
else if (timeObj.after(timeObj_p3))
state.setCurrentPage("third");
}
// clean state
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doAdd(): " + e);
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.debug(".doAdd(): " + e);
}
catch (InUseException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doAdd(): " + e);
}
} // elseif
} // doAdd
/**
* Action doUpdateGroupView is requested when the user click on the Update button on the list view.
*/
public void doUpdateGroupView(RunData runData, Context context)
{
readEventGroupForm(runData, context);
//stay at the list view
}
/**
* Action doUpdate is requested when the user click on the save button on the revise screen.
*/
public void doUpdate(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
CalendarUtil m_calObj= new CalendarUtil();
// read the intention field
String intentionStr = runData.getParameters().getString("intention");
int intention = CalendarService.MOD_NA;
if ("t".equals(intentionStr)) intention = CalendarService.MOD_THIS;
// See if we're in the "options" state.
if (state.getState().equalsIgnoreCase(STATE_MERGE_CALENDARS))
{
mergedCalendarPage.doUpdate(runData, context, state, getSessionState(runData));
// ReturnState was set up above. Switch states now.
String returnState = state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
state.setState("description");
}
else
{
state.setReturnState("");
state.setState(returnState);
}
}
else
if (state.getState().equalsIgnoreCase(STATE_CALENDAR_SUBSCRIPTIONS))
{
calendarSubscriptionsPage.doUpdate(runData, context, state, getSessionState(runData));
// ReturnState was set up above. Switch states now.
String returnState = state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
state.setState("description");
}
else
{
state.setReturnState("");
state.setState(returnState);
}
}
else
if (state.getState().equalsIgnoreCase(STATE_CUSTOMIZE_CALENDAR))
{
customizeCalendarPage.doDeletefield( runData, context, state, getSessionState(runData));
customizeCalendarPage.doUpdate(runData, context, state, getSessionState(runData));
if (!state.getDelfieldAlertOff())
{
state.setState(CalendarAction.STATE_CUSTOMIZE_CALENDAR);
}
else
{
// ReturnState was set up above. Switch states now.
String returnState = state.getReturnState();
if (returnState.endsWith("!!!fromDescription"))
{
state.setReturnState(returnState.substring(0, returnState.indexOf("!!!fromDescription")));
state.setState("description");
}
else
{
state.setReturnState("");
state.setState(returnState);
}
} // if (!state.getDelfieldAlertOff())
}
else
{
int houri;
Calendar calendarObj = null;
String hour = "";
hour = runData.getParameters().getString("startHour");
String title = "";
title = runData.getParameters().getString("activitytitle");
String minute = "";
minute = runData.getParameters().getString("startMinute");
String dhour = "";
dhour = runData.getParameters().getString("duHour");
String dminute = "";
dminute = runData.getParameters().getString("duMinute");
String description = "";
description = runData.getParameters().getString("description");
description = processFormattedTextFromBrowser(sstate, description);
String month = "";
month = runData.getParameters().getString("month");
String day = "";
day = runData.getParameters().getString("day");
String year = "";
year = runData.getParameters().getString("yearSelect");
String timeType = "";
timeType = runData.getParameters().getString("startAmpm");
String type = "";
type = runData.getParameters().getString("eventType");
String location = "";
location = runData.getParameters().getString("location");
String calId = state.getPrimaryCalendarReference();
try
{
calendarObj = CalendarService.getCalendar(calId);
}
catch (IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.theresisno"));
M_log.debug(".doUpdate() Other: " + e);
return;
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".doUpdate() Other: " + e);
return;
}
// for group/section awareness
readEventGroupForm(runData, context);
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
Collection groupChoice = (Collection) sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS);
Map addfieldsMap = new HashMap();
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsMapFromRunData(runData, addfieldsMap, calendarObj);
if (timeType.equals("pm"))
{
if (Integer.parseInt(hour)>11)
houri = Integer.parseInt(hour);
else
houri = Integer.parseInt(hour)+12;
}
else if (timeType.equals("am") && Integer.parseInt(hour)==12)
{
houri = 0;
}
else
{
houri = Integer.parseInt(hour);
}
// conditions for an existing event: (if recurring event, if state-saved-rule exists, if state-saved-freq exists)
// 1st, an existing recurring one, just revised without frequency change, no save state rule or state freq (1, 0, 0)
// --> the starting time might has been modified, compare the ending and starting date, show alert if needed (1)
// 2st, and existing non-recurring one, just revised, no save state rule or state freq (0, 0, 0)
// --> non-recurring, no alert needed (0)
// 3rd, an existing recurring one, frequency revised, there is a state-saved rule, and state-saved freq exists (1, 1, 1)
// --> no matter if the start has been modified, compare the ending and starting date, show alert if needed (1)
// 4th, an existing recurring one, changed to non-recurring, the state saved rule is null, but state-saved freq exists (1, 0, 1)
// --> non-recurring, no alert needed (0)
// 5th, an existing non-recurring one, changed but kept as non-recurring, the state-saved rule is null, but state-saved freq exists (1, 0, 1)
// --> non-recurring, no alert needed (0)
// 6th, an existing recurring one, changed only the starting time, showed alert for ealier ending time,
// so the only possiblity to show the alert is under condistion 1 & 3: recurring one stays as recurring
boolean earlierEnding = false;
CalendarEventEdit edit = state.getPrimaryCalendarEdit();
if (edit != null)
{
RecurrenceRule editRule = edit.getRecurrenceRule();
if ( editRule != null)
{
String freq = (String) sstate.getAttribute(FREQUENCY_SELECT);
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
boolean comparisonNeeded = false;
if ((freq == null) && (rule == null))
{
// condition 1: recurring without frequency touched, but the starting might change
rule = editRule;
comparisonNeeded = true;
}
else if ((freq != null) && (!(freq.equals(FREQ_ONCE))))
{
// condition 3: recurring with frequency changed, and stays at recurring
comparisonNeeded = true;
}
if (comparisonNeeded) // if under condition 1 or 3
{
if (rule != null)
{
Time startingTime = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),houri,Integer.parseInt(minute),00,000);
Time endingTime = rule.getUntil();
if ((endingTime != null) && endingTime.before(startingTime))
earlierEnding = true;
} // if (editRule != null)
} // if (comparisonNeeded) // if under condition 1 or 3
} // if (calEvent.getRecurrenceRule() != null)
} // if (edit != null)
if(title.length()==0)
{
String errorCode = rb.getString("java.pleasetitle");
addAlert(sstate, errorCode);
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("revise");
}
/*
else if(hour.equals("0") && minute.equals("0"))
{
String errorCode = "Please enter a time";
addAlert(sstate, errorCode);
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap);
state.setState("revise");
}
*/
else if( earlierEnding ) // if ending date is earlier than the starting date, show alert
{
addAlert(sstate, rb.getString("java.theend") );
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("revise");
}
else if (!Validator.checkDate(Integer.parseInt(day), Integer.parseInt(month), Integer.parseInt(year)))
{
addAlert(sstate, rb.getString("date.invalid"));
state.setNewData(calId, title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("revise");
}
else if (scheduleTo.equals("groups") && ((groupChoice == null) || (groupChoice.size() == 0)))
{
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
state.setState("revise");
addAlert(sstate, rb.getString("java.alert.youchoosegroup"));
}
else
{
try
{
calendarObj = CalendarService.getCalendar(calId);
Time timeObj = TimeService.newTimeLocal(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day),houri,Integer.parseInt(minute),00,000);
long du = (((Integer.parseInt(dhour) * 60)*60)*1000) + ((Integer.parseInt(dminute)*60)*(1000));
Time endTime = TimeService.newTime(timeObj.getTime() + du);
boolean includeEndTime = false;
TimeRange range = null;
if (du==0)
{
range = TimeService.newTimeRange(timeObj);
}
else
{
range = TimeService.newTimeRange(timeObj, endTime, true, includeEndTime);
}
List attachments = state.getAttachments();
if (edit != null)
{
edit.setRange(range);
edit.setDescriptionFormatted(description);
edit.setDisplayName(title);
edit.setType(type);
edit.setLocation(location);
setFields(edit, addfieldsMap);
edit.replaceAttachments(attachments);
RecurrenceRule rule = (RecurrenceRule) sstate.getAttribute(CalendarAction.SSTATE__RECURRING_RULE);
// conditions:
// 1st, an existing recurring one, just revised, no save state rule or state freq (0, 0)
// --> let edit rule untouched
// 2st, and existing non-recurring one, just revised, no save state rule or state freq (0, 0)
// --> let edit rule untouched
// 3rd, an existing recurring one, frequency revised, there is a state-saved rule, and state-saved freq exists (1, 1)
// --> replace the edit rule with state-saved rule
// 4th, and existing recurring one, changed to non-recurring, the state saved rule is null, but state-saved freq exists (0, 1)
// --> replace the edit rule with state-saved rule
// 5th, and existing non-recurring one, changed but kept as non-recurring, the state-saved rule is null, but state-saved freq exists (0, 1)
// --> replace the edit rule with state-saved rule
// so if the state-saved freq exists, replace the event rule
String freq = (String) sstate.getAttribute(FREQUENCY_SELECT);
if (sstate.getAttribute(FREQUENCY_SELECT) != null)
{
edit.setRecurrenceRule(rule);
}
// section awareness
try
{
// for site event
if (scheduleTo.equals("site"))
{
edit.clearGroupAccess();
}
// for grouped event
else if (scheduleTo.equals("groups"))
{
Site site = SiteService.getSite(calendarObj.getContext());
// make a collection of Group objects from the collection of group ref strings
Collection groups = new Vector();
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupRef = (String) iGroups.next();
groups.add(site.getGroup(groupRef));
}
edit.setGroupAccess(groups, edit.isUserOwner());
}
}
catch (Exception e)
{
M_log.warn("doUpdate", e);
}
calendarObj.commitEvent(edit, intention);
state.setPrimaryCalendarEdit(null);
state.setEdit(null);
state.setIsNewCalendar(false);
} // if (edit != null)
m_calObj.setDay(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day));
sstate.setAttribute(STATE_YEAR, Integer.valueOf(m_calObj.getYear()));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(m_calObj.getMonthInteger()));
sstate.setAttribute(STATE_DAY, Integer.valueOf(m_calObj.getDayOfMonth()));
// clear the saved recurring rule and the selected frequency
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, null);
// set the return state as the one before new/revise
String returnState = state.getReturnState();
if (returnState != null)
{
state.setState(returnState);
}
else
{
state.setState("week");
}
// clean state
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
}
catch (IdUnusedException e)
{
addAlert(sstate, rb.getString("java.alert.noexist"));
M_log.debug(".doUpdate(): " + e);
}
catch (PermissionException e)
{
addAlert(sstate, rb.getString("java.alert.youcreate"));
M_log.debug(".doUpdate(): " + e);
} // try-catch
} // if(title.length()==0)
} // if (state.getState().equalsIgnoreCase(STATE_CUSTOMIZE_CALENDAR))
} // doUpdate
public void doDeletefield(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
customizeCalendarPage.doDeletefield( runData, context, state, getSessionState(runData));
}
/**
* Handle the button click to add a field to the list of optional attributes.
*/
public void doAddfield(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
customizeCalendarPage.doAddfield( runData, context, state, getSessionState(runData));
}
public void doAddSubscription(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
calendarSubscriptionsPage.doAddSubscription( runData, context, state, getSessionState(runData));
}
/**
* Action doNpagew is requested when the user click on the next arrow to move to the next page in the week view.
*/
public void doNpagew(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
if(state.getCurrentPage().equals("third"))
state.setCurrentPage("first");
else if(state.getCurrentPage().equals("second"))
state.setCurrentPage("third");
else if(state.getCurrentPage().equals("first"))
state.setCurrentPage("second");
state.setState("week");
}
/**
* Action doPpagew is requested when the user click on the previous arrow to move to the previous page in week view.
*/
public void doPpagew(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
if(state.getCurrentPage().equals("first"))
state.setCurrentPage("third");
else if (state.getCurrentPage().equals("third"))
state.setCurrentPage("second");
else if (state.getCurrentPage().equals("second"))
state.setCurrentPage("first");
state.setState("week");
}
/**
* Action doDpagen is requested when the user click on the next arrow to move to the next page in day view.
*/
public void doDpagen(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
if(state.getCurrentPage().equals("third"))
state.setCurrentPage("first");
else if(state.getCurrentPage().equals("second"))
state.setCurrentPage("third");
else if(state.getCurrentPage().equals("first"))
state.setCurrentPage("second");
state.setState("day");
}
/**
* Action doDpagep is requested when the user click on the upper arrow to move to the previous page in day view.
*/
public void doDpagep(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
if(state.getCurrentPage().equals("first"))
state.setCurrentPage("third");
else if (state.getCurrentPage().equals("third"))
state.setCurrentPage("second");
else if (state.getCurrentPage().equals("second"))
state.setCurrentPage("first");
state.setState("day");
} // doDpagep
/**
* Action doPrev_activity is requested when the user navigates to the previous message in the detailed view.
*/
public void doPrev_activity(RunData runData, Context context)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
sstate.setAttribute(STATE_NAV_DIRECTION, STATE_PREV_ACT);
} //doPrev_activity
/**
* Action doNext_activity is requested when the user navigates to the previous message in the detailed view.
*/
public void doNext_activity(RunData runData, Context context)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
sstate.setAttribute(STATE_NAV_DIRECTION, STATE_NEXT_ACT);
} // doNext_activity
/*
* detailNavigatorControl will handle the goNext/goPrev buttons in detailed view,
* as well as figure out the prev/next message if available
*/
private void navigatorContextControl(VelocityPortlet portlet, Context context, RunData runData, String direction)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
String eventId = state.getCalendarEventId();
List events = prepEventList(portlet, context, runData);
int index = -1;
int size = events.size();
for (int i=0; i<size; i++)
{
CalendarEvent e = (CalendarEvent) events.get(i);
if (e.getId().equals(eventId))
index = i;
}
// navigate to the previous activity
if (STATE_PREV_ACT.equals(direction) && index > 0)
{
CalendarEvent ce = (CalendarEvent) events.get(--index);
Reference ref = EntityManager.newReference(ce.getReference());
eventId = ref.getId();
String calId = null;
if(CalendarService.REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
calId = CalendarService.calendarSubscriptionReference(ref.getContext(), ref.getContainer());
else
calId = CalendarService.calendarReference(ref.getContext(), ref.getContainer());
state.setCalendarEventId(calId, eventId);
state.setAttachments(null);
}
// navigate to the next activity
else if (STATE_NEXT_ACT.equals(direction) && index < size-1)
{
CalendarEvent ce = (CalendarEvent) events.get(++index);
Reference ref = EntityManager.newReference(ce.getReference());
eventId = ref.getId();
String calId = null;
if(CalendarService.REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
calId = CalendarService.calendarSubscriptionReference(ref.getContext(), ref.getContainer());
else
calId = CalendarService.calendarReference(ref.getContext(), ref.getContainer());
state.setCalendarEventId(calId, eventId);
state.setAttachments(null);
}
if (index > 0)
sstate.setAttribute(STATE_PREV_ACT, "");
else
sstate.removeAttribute(STATE_PREV_ACT);
if(index < size-1)
sstate.setAttribute(STATE_NEXT_ACT, "");
else
sstate.removeAttribute(STATE_NEXT_ACT);
sstate.setAttribute(STATE_NAV_DIRECTION, STATE_CURRENT_ACT);
} // navigatorControl
private CalendarEventVector prepEventList(VelocityPortlet portlet,
Context context,
RunData runData)
{
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
TimeRange fullTimeRange =
TimeService.newTimeRange(
TimeService.newTimeLocal(
CalendarFilter.LIST_VIEW_STARTING_YEAR,
1,
1,
0,
0,
0,
0),
TimeService.newTimeLocal(
CalendarFilter.LIST_VIEW_ENDING_YEAR,
12,
31,
23,
59,
59,
999));
// We need to get events from all calendars for the full time range.
CalendarEventVector masterEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
fullTimeRange);
sstate.setAttribute(STATE_EVENTS_LIST, masterEventVectorObj);
return masterEventVectorObj;
} // eventList
/**
* Action is to parse the function calls
**/
public void doParse(RunData data, Context context)
{
ParameterParser params = data.getParameters();
String source = params.getString("source");
if (source.equalsIgnoreCase("new"))
{
// create new event
doNew(data, context);
}
else if (source.equalsIgnoreCase("revise"))
{
// revise an event
doRevise(data, context);
}
else if (source.equalsIgnoreCase("delete"))
{
// delete event
doDelete(data, context);
}
else if (source.equalsIgnoreCase("byday"))
{
// view by day
doMenueday(data, context);
}
else if (source.equalsIgnoreCase("byweek"))
{
// view by week
doWeek(data, context);
}
else if (source.equalsIgnoreCase("bymonth"))
{
// view by month
doMonth(data, context);
}
else if (source.equalsIgnoreCase("byyear"))
{
// view by year
doYear(data, context);
}
else if (source.equalsIgnoreCase("prev"))
{
// go previous
doPrev(data, context);
}
else if (source.equalsIgnoreCase("next"))
{
// go next
doNext(data, context);
}
else if (source.equalsIgnoreCase("bylist"))
{
// view by list
doList(data, context);
}
} // doParse
/**
* Action doList is requested when the user click on the list in the toolbar
*/
public void doList(RunData data, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, data, CalendarActionState.class);
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
String sM;
String eM;
String sD;
String eD;
String sY;
String eY;
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
String prevState = state.getState().toString();
if (prevState.equals("day"))
{
sY = Integer.valueOf(calObj.getYear()).toString();
sM = Integer.valueOf(calObj.getMonthInteger()).toString();
sD = Integer.valueOf(calObj.getDayOfMonth()).toString();
eY = Integer.valueOf(calObj.getYear()).toString();
eM = Integer.valueOf(calObj.getMonthInteger()).toString();
eD = Integer.valueOf(calObj.getDayOfMonth()).toString();
}
else if (prevState.equals("week"))
{
int dayofweek = calObj.getDay_Of_Week(true);
calObj.setPrevDate(dayofweek-1);
sY = Integer.valueOf(calObj.getYear()).toString();
sM = Integer.valueOf(calObj.getMonthInteger()).toString();
sD = Integer.valueOf(calObj.getDayOfMonth()).toString();
for(int i = 0; i<6; i++)
{
calObj.getNextDate();
}
eY = Integer.valueOf(calObj.getYear()).toString();
eM = Integer.valueOf(calObj.getMonthInteger()).toString();
eD = Integer.valueOf(calObj.getDayOfMonth()).toString();
}
else if (prevState.equals("month"))
{
sY = Integer.valueOf(calObj.getYear()).toString();
sM = Integer.valueOf(calObj.getMonthInteger()).toString();
sD = String.valueOf("1");
calObj.setDay(stateYear, stateMonth, 1);
GregorianCalendar cal = new GregorianCalendar(calObj.getYear(), calObj.getMonthInteger()-1, 1);
int daysInMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
for (int i=1; i<daysInMonth; i++)
calObj.getNextDate();
eY = Integer.valueOf(calObj.getYear()).toString();
eM = Integer.valueOf(calObj.getMonthInteger()).toString();
eD = Integer.valueOf(calObj.getDayOfMonth()).toString();
}
else
{
// for other conditions: show the current year
sY = Integer.valueOf(stateYear).toString();
sM = "1";
sD = "1";
eY = Integer.valueOf(stateYear).toString();
eM = "12";
eD = "31";
}
if (sM.length() == 1) sM = "0"+sM;
if (eM.length() == 1) eM = "0"+eM;
if (sD.length() == 1) sD = "0"+sD;
if (eD.length() == 1) eD = "0"+eD;
sY = sY.substring(2);
eY = eY.substring(2);
String startingDateStr = sM + "/" + sD + "/" + sY;
String endingDateStr = eM + "/" + eD + "/" + eY;
state.getCalendarFilter().setListViewFilterMode(CalendarFilter.SHOW_CUSTOM_RANGE);
sstate.removeAttribute(STATE_SCHEDULE_TO);
sstate.removeAttribute(STATE_SCHEDULE_TO_GROUPS);
// Pass in a buffer for a possible error message.
StringBuilder errorMessage = new StringBuilder();
// Try to simultaneously set the start/end dates.
// If that doesn't work, add an error message.
if ( !state.getCalendarFilter().setStartAndEndListViewDates(startingDateStr, endingDateStr, errorMessage) )
{
addAlert(sstate, errorMessage.toString());
}
state.setState("list");
} // doList
/**
* Action doSort_by_date_toggle is requested when the user click on the sorting icon in the list view
*/
public void doSort_by_date_toggle(RunData data, Context context)
{
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState sstate = ((JetspeedRunData)data).getPortletSessionState(peid);
boolean dateDsc = sstate.getAttribute(STATE_DATE_SORT_DSC) != null;
if (dateDsc)
sstate.removeAttribute(STATE_DATE_SORT_DSC);
else
sstate.setAttribute(STATE_DATE_SORT_DSC, "");
} // doSort_by_date_toggle
/**
* Handle a request from the "merge" page to merge calendars from other groups into this group's Schedule display.
*/
public void doMerge(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
mergedCalendarPage.doMerge( runData, context, state, getSessionState(runData));
} // doMerge
/**
* Handle a request from the "subscriptions" page to subscribe calendars.
*/
public void doSubscriptions(RunData runData, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, runData, CalendarActionState.class);
calendarSubscriptionsPage.doSubscriptions( runData, context, state, getSessionState(runData));
} // doMerge
/**
* Handle a request to set options.
*/
public void doCustomize(RunData runData, Context context)
{
CalendarActionState state =
(CalendarActionState) getState(context,
runData,
CalendarActionState.class);
customizeCalendarPage.doCustomize(
runData,
context,
state,
getSessionState(runData));
}
/**
* Build the context for showing list view
*/
protected void buildListContext(VelocityPortlet portlet, Context context, RunData runData, CalendarActionState state)
{
// to get the content Type Image Service
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
context.put("tlang",rb);
context.put("config",configProps);
MyMonth monthObj2 = null;
MyDate dateObj1 = new MyDate();
CalendarEventVector calendarEventVectorObj = null;
boolean allowed = false;
LinkedHashMap yearMap = new LinkedHashMap();
// Initialize month format object
if ( monthFormat == null )
{
monthFormat = NumberFormat.getInstance(new ResourceLoader().getLocale());
monthFormat.setMinimumIntegerDigits(2);
}
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
// Set up list filtering information in the context.
context.put(TIME_FILTER_OPTION_VAR, state.getCalendarFilter().getListViewFilterMode());
//
// Fill in the custom dates
//
String sDate; // starting date
String eDate; // ending date
java.util.Calendar userCal = java.util.Calendar.getInstance();
context.put("ddStartYear", Integer.valueOf(userCal.get(java.util.Calendar.YEAR) - 3));
context.put("ddEndYear", Integer.valueOf(userCal.get(java.util.Calendar.YEAR) + 4));
String sM;
String eM;
String sD;
String eD;
String sY;
String eY;
if (state.getCalendarFilter().isCustomListViewDates() )
{
sDate = state.getCalendarFilter().getStartingListViewDateString();
eDate = state.getCalendarFilter().getEndingListViewDateString();
sM = sDate.substring(0, 2);
eM = eDate.substring(0, 2);
sD = sDate.substring(3, 5);
eD = eDate.substring(3, 5);
sY = "20" + sDate.substring(6);
eY = "20" + eDate.substring(6);
}
else
{
//default to current week
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
TimeRange weekRange = getWeekTimeRange( calObj );
sD = String.valueOf( weekRange.firstTime().breakdownLocal().getDay() );
sY = String.valueOf( weekRange.firstTime().breakdownLocal().getYear() );
sM = monthFormat.format( weekRange.firstTime().breakdownLocal().getMonth() );
eD = String.valueOf( weekRange.lastTime().breakdownLocal().getDay() );
eY = String.valueOf( weekRange.lastTime().breakdownLocal().getYear() );
eM = monthFormat.format( weekRange.lastTime().breakdownLocal().getMonth() );
}
context.put(TIME_FILTER_SETTING_CUSTOM_START_YEAR, Integer.valueOf(sY));
context.put(TIME_FILTER_SETTING_CUSTOM_END_YEAR, Integer.valueOf(eY));
context.put(TIME_FILTER_SETTING_CUSTOM_START_MONTH, Integer.valueOf(sM));
context.put(TIME_FILTER_SETTING_CUSTOM_END_MONTH, Integer.valueOf(eM));
context.put(TIME_FILTER_SETTING_CUSTOM_START_DAY, Integer.valueOf(sD));
context.put(TIME_FILTER_SETTING_CUSTOM_END_DAY, Integer.valueOf(eD));
CalendarUtil calObj= new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
dateObj1.setTodayDate(calObj.getMonthInteger(),calObj.getDayOfMonth(),calObj.getYear());
// fill this month object with all days avilable for this month
if (CalendarService.allowGetCalendar(state.getPrimaryCalendarReference())== false)
{
allowed = false;
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotallow"));
calendarEventVectorObj = new CalendarEventVector();
}
else
{
try
{
allowed = CalendarService.getCalendar(state.getPrimaryCalendarReference()).allowAddEvent();
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.therenoactv"));
M_log.debug(".buildMonthContext(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.younotperm"));
M_log.debug(".buildMonthContext(): " + e);
}
}
int yearInt, monthInt, dayInt=1;
TimeRange fullTimeRange =
TimeService.newTimeRange(
TimeService.newTimeLocal(
CalendarFilter.LIST_VIEW_STARTING_YEAR,
1,
1,
0,
0,
0,
0),
TimeService.newTimeLocal(
CalendarFilter.LIST_VIEW_ENDING_YEAR,
12,
31,
23,
59,
59,
999));
// We need to get events from all calendars for the full time range.
CalendarEventVector masterEventVectorObj =
CalendarService.getEvents(
getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab()),
fullTimeRange);
// groups awareness - filtering
String calId = state.getPrimaryCalendarReference();
String scheduleTo = (String)sstate.getAttribute(STATE_SCHEDULE_TO);
try
{
Calendar calendarObj = CalendarService.getCalendar(calId);
context.put("cal", calendarObj);
if (scheduleTo != null && scheduleTo.length() != 0)
{
context.put("scheduleTo", scheduleTo);
}
else
{
if (calendarObj.allowGetEvents())
{
// default to make site selection
context.put("scheduleTo", "site");
}
else if (calendarObj.getGroupsAllowGetEvent().size() > 0)
{
// to group otherwise
context.put("scheduleTo", "groups");
}
}
Collection groups = calendarObj.getGroupsAllowGetEvent();
if (groups.size() > 0)
{
context.put("groups", groups);
}
List schToGroups = (List)(sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS));
context.put("scheduleToGroups", schToGroups);
CalendarEventVector newEventVectorObj = new CalendarEventVector();
newEventVectorObj.addAll(masterEventVectorObj);
for (Iterator i = masterEventVectorObj.iterator(); i.hasNext();)
{
CalendarEvent e = (CalendarEvent)(i.next());
String origSiteId = (CalendarService.getCalendar(e.getCalendarReference())).getContext();
if (!origSiteId.equals(ToolManager.getCurrentPlacement().getContext()))
{
context.put("fromColExist", Boolean.TRUE);
}
if ((schToGroups != null) && (schToGroups.size()>0))
{
boolean eventInGroup = false;
for (Iterator j = schToGroups.iterator(); j.hasNext();)
{
String groupRangeForDisplay = e.getGroupRangeForDisplay(calendarObj);
String groupId = j.next().toString();
Site site = SiteService.getSite(calendarObj.getContext());
Group group = site.getGroup(groupId);
if (groupRangeForDisplay.equals("")||groupRangeForDisplay.equals("site"))
eventInGroup = true;
if (groupRangeForDisplay.indexOf(group.getTitle()) != -1)
eventInGroup = true;
}
if ( ! eventInGroup )
newEventVectorObj.remove(e);
}
}
if ((schToGroups != null) && (schToGroups.size()>0))
{
masterEventVectorObj.clear();
masterEventVectorObj.addAll(newEventVectorObj);
}
}
catch(IdUnusedException e)
{
M_log.debug(".buildListContext(): " + e);
}
catch (PermissionException e)
{
M_log.debug(".buildListContext(): " + e);
}
boolean dateDsc = sstate.getAttribute(STATE_DATE_SORT_DSC) != null;
context.put("currentDateSortAsc", Boolean.valueOf(!dateDsc));
if (!dateDsc)
{
for (yearInt = CalendarFilter.LIST_VIEW_STARTING_YEAR;
yearInt <= CalendarFilter.LIST_VIEW_ENDING_YEAR;
yearInt++)
{
Vector arrayOfMonths = new Vector(20);
for(monthInt = 1; monthInt <13; monthInt++)
{
CalendarUtil AcalObj = new CalendarUtil();
monthObj2 = new MyMonth();
AcalObj.setDay(yearInt, monthInt, dayInt);
dateObj1.setTodayDate(AcalObj.getMonthInteger(),AcalObj.getDayOfMonth(),AcalObj.getYear());
// Get the events for the particular month from the
// master list of events.
calendarEventVectorObj =
new CalendarEventVector(
state.getCalendarFilter().filterEvents(
masterEventVectorObj.getEvents(
getMonthTimeRange((CalendarUtil) AcalObj))));
if (!calendarEventVectorObj.isEmpty())
{
AcalObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
monthObj2 = calMonth(monthInt, (CalendarUtil)AcalObj, state, calendarEventVectorObj);
AcalObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
if (!calendarEventVectorObj.isEmpty())
arrayOfMonths.addElement(monthObj2);
}
}
if (!arrayOfMonths.isEmpty())
yearMap.put(Integer.valueOf(yearInt), arrayOfMonths.iterator());
}
}
else
{
for (yearInt = CalendarFilter.LIST_VIEW_ENDING_YEAR;
yearInt >= CalendarFilter.LIST_VIEW_STARTING_YEAR;
yearInt--)
{
Vector arrayOfMonths = new Vector(20);
for(monthInt = 12; monthInt >=1; monthInt--)
{
CalendarUtil AcalObj = new CalendarUtil();
monthObj2 = new MyMonth();
AcalObj.setDay(yearInt, monthInt, dayInt);
dateObj1.setTodayDate(AcalObj.getMonthInteger(),AcalObj.getDayOfMonth(),AcalObj.getYear());
// Get the events for the particular month from the
// master list of events.
calendarEventVectorObj =
new CalendarEventVector(
state.getCalendarFilter().filterEvents(
masterEventVectorObj.getEvents(
getMonthTimeRange((CalendarUtil) AcalObj))));
if (!calendarEventVectorObj.isEmpty())
{
AcalObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
monthObj2 = calMonth(monthInt, (CalendarUtil)AcalObj, state, calendarEventVectorObj);
AcalObj.setDay(dateObj1.getYear(),dateObj1.getMonth(),dateObj1.getDay());
if (!calendarEventVectorObj.isEmpty())
arrayOfMonths.addElement(monthObj2);
}
}
if (!arrayOfMonths.isEmpty())
yearMap.put(Integer.valueOf(yearInt), arrayOfMonths.iterator());
}
}
context.put("yearMap", yearMap);
int row = 5;
context.put("row",Integer.valueOf(row));
calObj.setDay(stateYear, stateMonth, stateDay);
// using session state stored year-month-day to replace saving calObj
sstate.setAttribute(STATE_YEAR, Integer.valueOf(stateYear));
sstate.setAttribute(STATE_MONTH, Integer.valueOf(stateMonth));
sstate.setAttribute(STATE_DAY, Integer.valueOf(stateDay));
state.setState("list");
context.put("date",dateObj1);
// output CalendarService and SiteService
context.put("CalendarService", CalendarService.getInstance());
context.put("SiteService", SiteService.getInstance());
context.put("Context", ToolManager.getCurrentPlacement().getContext());
buildMenu(
portlet,
context,
runData,
state,
CalendarPermissions.allowCreateEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference()),
CalendarPermissions.allowDeleteEvent(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowReviseEvents(
state.getPrimaryCalendarReference(),
state.getSelectedCalendarReference(),
state.getCalendarEventId()),
CalendarPermissions.allowMergeCalendars(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowModifyCalendarProperties(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowImport(
state.getPrimaryCalendarReference()),
CalendarPermissions.allowSubscribe(
state.getPrimaryCalendarReference()));
// added by zqian for toolbar
context.put("allow_new", Boolean.valueOf(allowed));
context.put("allow_delete", Boolean.valueOf(false));
context.put("allow_revise", Boolean.valueOf(false));
context.put("realDate", TimeService.newTime());
context.put("selectedView", rb.getString("java.listeve"));
context.put("tlang",rb);
context.put("config",configProps);
context.put("calendarFormattedText", new CalendarFormattedText());
} // buildListContext
private void buildPrintMenu( VelocityPortlet portlet,
RunData runData,
CalendarActionState state,
Menu bar_print )
{
String stateName = state.getState();
if (stateName.equals("month")
|| stateName.equals("day")
|| stateName.equals("week")
|| stateName.equals("list"))
{
int printType = CalendarService.UNKNOWN_VIEW;
String timeRangeString = "";
TimeRange dailyStartTime = null;
int startHour = 0, startMinute = 0;
int endHour = 0, endMinute = 0;
int endSeconds = 0, endMSeconds = 0;
//
// Depending what page we are on, there will be
// a different time of the day on which we start.
//
if (state.getCurrentPage().equals("first"))
{
startHour = FIRST_PAGE_START_HOUR;
endHour = startHour + NUMBER_HOURS_PER_PAGE_FOR_WEEK_VIEW;
}
else
if (state.getCurrentPage().equals("second"))
{
startHour = SECOND_PAGE_START_HOUR;
endHour = startHour + NUMBER_HOURS_PER_PAGE_FOR_WEEK_VIEW;
}
else
if (state.getCurrentPage().equals("third"))
{
startHour = THIRD_PAGE_START_HOUR;
endHour = startHour + NUMBER_HOURS_PER_PAGE_FOR_WEEK_VIEW;
}
else
{
startHour = 0;
endHour = startHour + HOURS_PER_DAY;
}
// If we go over twenty-four hours, stop at the end of the day.
if ( endHour >= HOURS_PER_DAY )
{
endHour = 23;
endMinute = 59;
endSeconds = 59;
endMSeconds = 999;
}
dailyStartTime =
TimeService.newTimeRange(
TimeService.newTimeLocal(
state.getcurrentYear(),
state.getcurrentMonth(),
state.getcurrentDay(),
startHour,
startMinute,
00,
000),
TimeService.newTimeLocal(
state.getcurrentYear(),
state.getcurrentMonth(),
state.getcurrentDay(),
endHour,
endMinute,
endSeconds,
endMSeconds));
String peid = ((JetspeedRunData)runData).getJs_peid();
SessionState sstate = ((JetspeedRunData)runData).getPortletSessionState(peid);
Time m_time = TimeService.newTime();
TimeBreakdown b = m_time.breakdownLocal();
int stateYear = b.getYear();
int stateMonth = b.getMonth();
int stateDay = b.getDay();
if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null))
{
stateYear = ((Integer)sstate.getAttribute(STATE_YEAR)).intValue();
stateMonth = ((Integer)sstate.getAttribute(STATE_MONTH)).intValue();
stateDay = ((Integer)sstate.getAttribute(STATE_DAY)).intValue();
}
CalendarUtil calObj = new CalendarUtil();
calObj.setDay(stateYear, stateMonth, stateDay);
if (stateName.equals("month"))
{
printType = CalendarService.MONTH_VIEW;
timeRangeString = getMonthTimeRange(calObj).toString();
}
else
if (stateName.equals("day"))
{
printType = CalendarService.DAY_VIEW;
timeRangeString =
getDayTimeRange(
calObj.getYear(),
calObj.getMonthInteger(),
calObj.getDayOfMonth())
.toString();
}
else
if (stateName.equals("week"))
{
printType = CalendarService.WEEK_VIEW;
timeRangeString = getWeekTimeRange(calObj).toString();
}
else
if (stateName.equals("list"))
{
printType = CalendarService.LIST_VIEW;
timeRangeString =
TimeService
.newTimeRange(
state.getCalendarFilter().getListViewStartingTime(),
state.getCalendarFilter().getListViewEndingTime())
.toString();
}
// set the actual list of calendars into the user's session:
List calRefList = getCalendarReferenceList(
portlet,
state.getPrimaryCalendarReference(),
isOnWorkspaceTab());
SessionManager.getCurrentSession().setAttribute(CalendarService.SESSION_CALENDAR_LIST,calRefList);
Reference calendarRef = EntityManager.newReference(state.getPrimaryCalendarReference());
// Add PDF print menu option
String accessPointUrl = ServerConfigurationService.getAccessUrl()
+ CalendarService.calendarPdfReference(calendarRef.getContext(),
calendarRef.getId(),
printType,
timeRangeString,
UserDirectoryService.getCurrentUser().getDisplayName(),
dailyStartTime);
bar_print.add(new MenuEntry(rb.getString("java.print"), "").setUrl(accessPointUrl));
}
}
/**
* Build the menu.
*/
private void buildMenu( VelocityPortlet portlet,
Context context,
RunData runData,
CalendarActionState state,
boolean allow_new,
boolean allow_delete,
boolean allow_revise,
boolean allow_merge_calendars,
boolean allow_modify_calendar_properties,
boolean allow_import_export,
boolean allow_subscribe)
{
Menu bar = new MenuImpl(portlet, runData, "CalendarAction");
String status = state.getState();
if ((status.equals("day"))
||(status.equals("week"))
||(status.equals("month"))
||(status.equals("year"))
||(status.equals("list")))
{
allow_revise = false;
allow_delete = false;
}
bar.add( new MenuEntry(rb.getString("java.new"), null, allow_new, MenuItem.CHECKED_NA, "doNew") );
//
// See if we are allowed to merge items.
//
bar.add( new MenuEntry(mergedCalendarPage.getButtonText(), null, allow_merge_calendars, MenuItem.CHECKED_NA, mergedCalendarPage.getButtonHandlerID()) );
// See if we are allowed to import items.
if ( allow_import_export )
{
bar.add( new MenuEntry(rb.getString("java.import"), null, allow_new, MenuItem.CHECKED_NA, "doImport") );
}
// See if we are allowed to export items.
String calId = state.getPrimaryCalendarReference();
if ( (allow_import_export || CalendarService.getExportEnabled(calId)) &&
ServerConfigurationService.getBoolean("ical.experimental",false))
{
bar.add( new MenuEntry(rb.getString("java.export"), null, allow_new, MenuItem.CHECKED_NA, "doIcalExportName") );
}
// See if we are allowed to configure external calendar subscriptions
if ( allow_subscribe && ServerConfigurationService.getBoolean(ExternalCalendarSubscriptionService.SAK_PROP_EXTSUBSCRIPTIONS_ENABLED,false))
{
bar.add( new MenuEntry(rb.getString("java.subscriptions"), null, allow_subscribe, MenuItem.CHECKED_NA, "doSubscriptions") );
}
//2nd menu bar for the PDF print only
Menu bar_print = new MenuImpl(portlet, runData, "CalendarAction");
buildPrintMenu( portlet, runData, state, bar_print );
if (SiteService.allowUpdateSite(ToolManager.getCurrentPlacement().getContext()))
{
bar_print.add( new MenuEntry(rb.getString("java.default_view"), "doDefaultview") );
}
bar.add( new MenuEntry(customizeCalendarPage.getButtonText(), null, allow_modify_calendar_properties, MenuItem.CHECKED_NA, customizeCalendarPage.getButtonHandlerID()) );
// add permissions, if allowed
//SAK-21684 don't show in myworkspace site unless super user.
String currentSiteId = ToolManager.getCurrentPlacement().getContext();
if (SecurityService.isSuperUser() || (SiteService.allowUpdateSite(currentSiteId) && !SiteService.isUserSite(currentSiteId)))
{
bar.add( new MenuEntry(rb.getString("java.permissions"), "doPermissions") );
}
// Set menu state attribute
SessionState stateForMenus = ((JetspeedRunData)runData).getPortletSessionState(portlet.getID());
stateForMenus.setAttribute(MenuItem.STATE_MENU, bar);
context.put("tlang",rb);
context.put("config",configProps);
context.put(Menu.CONTEXT_MENU, bar);
context.put("menu_PDF", bar_print);
context.put(Menu.CONTEXT_ACTION, "CalendarAction");
} // buildMenu
/**
* Align the edit's fields with these values.
* @param edit The CalendarEventEdit.
* @param values The map of name-value pairs.
*/
private void setFields(CalendarEventEdit edit, Map values)
{
Set<Entry<String, String>> keys = values.entrySet();
for (Iterator<Entry<String, String>> it = keys.iterator(); it.hasNext(); )
{
Entry entry = it.next();
String name = (String)entry.getKey() ;
String value = (String) entry.getValue();
edit.setField(name, value);
}
} // setFields
/** Set current calendar view as tool default
**/
public void doDefaultview( RunData rundata, Context context )
{
CalendarActionState state = (CalendarActionState)getState(context, rundata, CalendarActionState.class);
SessionState sstate = ((JetspeedRunData) rundata).getPortletSessionState(((JetspeedRunData) rundata).getJs_peid());
String view = state.getState();
Placement placement = ToolManager.getCurrentPlacement();
placement.getPlacementConfig().setProperty(
PORTLET_CONFIG_DEFAULT_VIEW, view );
saveOptions();
addAlert(sstate, rb.getString("java.alert.default_view"));
}
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context)
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
// setup the parameters for the helper
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
CalendarActionState cstate = (CalendarActionState) getState(context, data, CalendarActionState.class);
String calendarRefStr = cstate.getPrimaryCalendarReference();
Reference calendarRef = EntityManager.newReference(calendarRefStr);
String siteRef = SiteService.siteReference(calendarRef.getContext());
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("java.set")
+ SiteService.getSiteDisplay(calendarRef.getContext()));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "calendar.");
// ... pass the resource loader object
ResourceLoader pRb = new ResourceLoader("permissions");
HashMap<String, String> pRbValues = new HashMap<String, String>();
for (Iterator<Entry<String, String>> iKeys = pRb.entrySet().iterator();iKeys.hasNext();)
{
Entry entry = iKeys.next();
String key = (String)entry.getKey();
pRbValues.put(key, (String)entry.getValue());
}
state.setAttribute("permissionDescriptions", pRbValues);
String groupAware = ToolManager.getCurrentTool().getRegisteredConfig().getProperty("groupAware");
state.setAttribute("groupAware", groupAware != null?Boolean.valueOf(groupAware):Boolean.FALSE);
state.removeAttribute("menu"); //Menu not required in the permission view
}
/**
* Action doFrequency is requested when "set Frequency" button is clicked in new/revise page
*/
public void doEditfrequency(RunData rundata, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, rundata, CalendarActionState.class);
String peid = ((JetspeedRunData)rundata).getJs_peid();
SessionState sstate = ((JetspeedRunData)rundata).getPortletSessionState(peid);
String calId = "";
Calendar calendarObj = null;
String eventId = state.getCalendarEventId();
try
{
calId = state.getPrimaryCalendarReference();
calendarObj = CalendarService.getCalendar(calId);
String freq = (String) sstate.getAttribute(FREQUENCY_SELECT);
// conditions when the doEditfrequency is called:
// 1. new/existing event, in create-new/revise page first time: freq is null.
// It has been set to null in both doNew & doRevise.
// Make sure to re-set the freq in this step.
// 2. new/existing event, back from cancel/save-frequency-setting page: freq is sth, because when
// the first time doEditfrequency is called, there is a freq set up already
// condition 1 -
if ((freq == null)||(freq.equals("")))
{
// if a new event
if ((eventId == null)||(eventId.equals("")))
{
// set the frequency to be default "once", rule to be null
sstate.setAttribute(FREQUENCY_SELECT, DEFAULT_FREQ);
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
}
else
{ // exiting event
try
{
if(calendarObj.allowGetEvents())
{
CalendarEvent event = calendarObj.getEvent(eventId);
RecurrenceRule rule = event.getRecurrenceRule();
if (rule == null)
{
// not recurring, i.e., frequency is once
sstate.setAttribute(FREQUENCY_SELECT, DEFAULT_FREQ);
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
}
else
{
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, rule);
sstate.setAttribute(FREQUENCY_SELECT, rule.getFrequencyDescription());
} // if (rule==null)
} // if allowGetEvents
} // try
catch(IdUnusedException e)
{
M_log.debug(".doEditfrequency() + calendarObj.getEvent(): " + e);
} // try-cath
} // if ((eventId == null)||(eventId.equals(""))
}
else
{
// condition 2, state freq is set, and state rule is set already
}
} // try
catch(IdUnusedException e)
{
M_log.debug(".doEditfrequency() + CalendarService.getCalendar(): " + e);
}
catch (PermissionException e)
{
M_log.debug(".doEditfrequency() + CalendarService.getCalendar(): " + e);
}
int houri;
String hour = "";
hour = rundata.getParameters().getString("startHour");
String title ="";
title = rundata.getParameters().getString("activitytitle");
String minute = "";
minute = rundata.getParameters().getString("startMinute");
String dhour = "";
dhour = rundata.getParameters().getString("duHour");
String dminute = "";
dminute = rundata.getParameters().getString("duMinute");
String description = "";
description = rundata.getParameters().getString("description");
description = processFormattedTextFromBrowser(sstate, description);
String month = "";
month = rundata.getParameters().getString("month");
String day = "";
day = rundata.getParameters().getString("day");
String year = "";
year = rundata.getParameters().getString("yearSelect");
String timeType = "";
timeType = rundata.getParameters().getString("startAmpm");
String type = "";
type = rundata.getParameters().getString("eventType");
String location = "";
location = rundata.getParameters().getString("location");
readEventGroupForm(rundata, context);
// read the recurrence modification intention
String intentionStr = rundata.getParameters().getString("intention");
if (intentionStr == null) intentionStr = "";
try
{
calendarObj = CalendarService.getCalendar(calId);
Map addfieldsMap = new HashMap();
// Add any additional fields in the calendar.
customizeCalendarPage.loadAdditionalFieldsMapFromRunData(rundata, addfieldsMap, calendarObj);
if (timeType.equals("pm"))
{
if (Integer.parseInt(hour)>11)
houri = Integer.parseInt(hour);
else
houri = Integer.parseInt(hour)+12;
}
else if (timeType.equals("am") && Integer.parseInt(hour)==12)
{
houri = 24;
}
else
{
houri = Integer.parseInt(hour);
}
state.clearData();
state.setNewData(state.getPrimaryCalendarReference(), title,description,Integer.parseInt(month),Integer.parseInt(day),year,houri,Integer.parseInt(minute),Integer.parseInt(dhour),Integer.parseInt(dminute),type,timeType,location, addfieldsMap, intentionStr);
}
catch(IdUnusedException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.thereis"));
M_log.debug(".doEditfrequency(): " + e);
}
catch (PermissionException e)
{
context.put(ALERT_MSG_KEY,rb.getString("java.alert.youdont"));
M_log.debug(".doEditfrequency(): " + e);
}
sstate.setAttribute(STATE_BEFORE_SET_RECURRENCE, state.getState());
state.setState(STATE_SET_FREQUENCY);
} // doEditfrequency
/**
* Action doChangefrequency is requested when the user changes the selected frequency at the frequency setting page
*/
public void doChangefrequency(RunData rundata, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, rundata, CalendarActionState.class);
String freqSelect = rundata.getParameters().getString(FREQUENCY_SELECT);
String peid = ((JetspeedRunData)rundata).getJs_peid();
SessionState sstate = ((JetspeedRunData)rundata).getPortletSessionState(peid);
sstate.setAttribute(FREQUENCY_SELECT, freqSelect);
//TEMP_FREQ_SELECT only works for the onchange javascript function when user changes the frequency selection
// and will be discarded when buildFrequecyContext has caught its value
sstate.setAttribute(TEMP_FREQ_SELECT, freqSelect);
state.setState(STATE_SET_FREQUENCY);
} // doChangefrequency
/**
* Action doSavefrequency is requested when the user click on the "Save" button in the frequency setting page
*/
public void doSavefrequency(RunData rundata, Context context)
{
CalendarActionState state = (CalendarActionState)getState(context, rundata, CalendarActionState.class);
String peid = ((JetspeedRunData)rundata).getJs_peid();
SessionState sstate = ((JetspeedRunData)rundata).getPortletSessionState(peid);
String returnState = (String)sstate.getAttribute(STATE_BEFORE_SET_RECURRENCE);
// if by any chance, the returnState is not available,
// then reset it as either "new" or "revise".
// For new event, the id is null or empty string
if ((returnState == null)||(returnState.equals("")))
{
String eventId = state.getCalendarEventId();
if ((eventId == null) || (eventId.equals("")))
returnState = "new";
else
returnState = "revise";
}
state.setState(returnState);
// get the current frequency setting the user has selected - daily, weekly, or etc.
String freq = (String) rundata.getParameters().getString(FREQUENCY_SELECT);
if ((freq == null)||(freq.equals(FREQ_ONCE)))
{
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, null);
sstate.setAttribute(FREQUENCY_SELECT, FREQ_ONCE);
}
else
{
sstate.setAttribute(FREQUENCY_SELECT, freq);
String interval = rundata.getParameters().getString("interval");
int intInterval = Integer.parseInt(interval);
RecurrenceRule rule = null;
String CountOrTill = rundata.getParameters().getString("CountOrTill");
if (CountOrTill.equals("Never"))
{
rule = CalendarService.newRecurrence(freq, intInterval);
}
else if (CountOrTill.equals("Till"))
{
String endMonth = rundata.getParameters().getString("endMonth");
String endDay = rundata.getParameters().getString("endDay");
String endYear = rundata.getParameters().getString("endYear");
int intEndMonth = Integer.parseInt(endMonth);
int intEndDay = Integer.parseInt(endDay);
int intEndYear = Integer.parseInt(endYear);
//construct time object from individual ints, Local Time values
Time endTime = TimeService.newTimeLocal(intEndYear, intEndMonth, intEndDay, 23, 59, 59, 999);
rule = CalendarService.newRecurrence(freq, intInterval, endTime);
}
else if (CountOrTill.equals("Count"))
{
String count = rundata.getParameters().getString("count");
int intCount = Integer.parseInt(count);
rule = CalendarService.newRecurrence(freq, intInterval, intCount);
}
sstate.setAttribute(CalendarAction.SSTATE__RECURRING_RULE, rule);
}
} // doSavefrequency
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata)
{
super.initState(state, portlet, rundata);
if (contentHostingService == null)
{
contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
}
if (entityBroker == null)
{
entityBroker = (EntityBroker) ComponentManager.get("org.sakaiproject.entitybroker.EntityBroker");
}
// retrieve the state from state object
CalendarActionState calState = (CalendarActionState)getState( portlet, rundata, CalendarActionState.class );
setPrimaryCalendarReferenceInState(portlet, calState);
// setup the observer to notify our main panel
if (state.getAttribute(STATE_INITED) == null)
{
state.setAttribute(STATE_INITED,STATE_INITED);
// load all calendar channels (either primary or merged calendars)
MergedList mergedCalendarList =
loadChannels( calState.getPrimaryCalendarReference(),
portlet.getPortletConfig().getInitParameter(PORTLET_CONFIG_PARM_MERGED_CALENDARS),
null );
}
// Initialize configuration properties
InputStream inConfig = null;
try
{
if ( configProps == null )
{
configProps = new Properties();
inConfig = this.getClass().getResourceAsStream("calendar.config");
configProps.load(inConfig);
}
}
catch ( IOException e )
{
M_log.warn("unable to load calendar.config: " + e);
}
finally {
if(inConfig != null)
{
try
{
inConfig.close();
}
catch(IOException e1)
{
M_log.warn("I(O error occurred while closing 'inConfig' inputstream", e1);
}
}
}
} // initState
/**
* Takes an array of tokens and converts into separator-separated string.
*
* @param String[] The array of strings input.
* @param String The string separator.
* @return String A string containing tokens separated by seperator.
*/
protected String arrayToString(String[] array, String separators)
{
StringBuilder sb = new StringBuilder("");
String empty = "";
if (array == null)
return empty;
if (separators == null)
separators = ",";
for (int ix=0; ix < array.length; ix++)
{
if (array[ix] != null && !array[ix].equals(""))
{
sb.append(array[ix] + separators);
}
}
String str = sb.toString();
if (!str.equals(""))
{
str = str.substring(0, (str.length() - separators.length()));
}
return str;
}
/**
* Processes formatted text that is coming back from the browser
* (from the formatted text editing widget).
* @param state Used to pass in any user-visible alerts or errors when processing the text
* @param strFromBrowser The string from the browser
* @return The formatted text
*/
private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser)
{
StringBuilder alertMsg = new StringBuilder();
try
{
String text = FormattedText.processFormattedText(strFromBrowser, alertMsg);
if (alertMsg.length() > 0) addAlert(state, alertMsg.toString());
return text;
}
catch (Exception e)
{
M_log.warn(" ", e);
return strFromBrowser;
}
}
/**
* Access the current month as a string.
* @return the current month as a string.
*/
public String calendarUtilGetMonth(int l_month)
{
// get the index for the month. Note, the index is increased by 1, u need to deduct 1 first
String[] months = new String [] { rb.getString("jan"),rb.getString("feb"),rb.getString("mar"),
rb.getString("apr"), rb.getString("may"), rb.getString("jun"),
rb.getString("jul"), rb.getString("aug"), rb.getString("sep"),
rb.getString("oct"), rb.getString("nov"), rb.getString("dec") };
if (l_month >12)
{
return rb.getString("java.thismonth");
}
return months[l_month-1];
} // getMonth
/**
* Get the name of the day.
* @return the name of the day.
*/
private String calendarUtilGetDay(int dayofweek)
{
String[] l_ndays = new String[] {rb.getString("day.sunday"),rb.getString("day.monday"),
rb.getString("day.tuesday"),rb.getString("day.wednesday"),rb.getString("day.thursday")
,rb.getString("day.friday"),rb.getString("day.saturday")};
if ( dayofweek > 7 )
{
dayofweek = 1;
}
else if ( dayofweek <=0 )
{
dayofweek = 7;
}
return l_ndays[dayofweek - 1];
} // calendarUtilGetDay
} // CalendarAction
| SAK-22636 - Calendar uses file separator instead of entity separator, contributed patch.
git-svn-id: 04d4787a8f5c2a5245f79294070475605a4425d0@113742 66ffb92e-73f9-0310-93c1-f5514f145a0a
| calendar/calendar-tool/tool/src/java/org/sakaiproject/calendar/tool/CalendarAction.java | SAK-22636 - Calendar uses file separator instead of entity separator, contributed patch. | <ide><path>alendar/calendar-tool/tool/src/java/org/sakaiproject/calendar/tool/CalendarAction.java
<ide> import java.io.ByteArrayInputStream;
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<del>import java.io.File;
<ide> import java.text.DateFormat;
<ide> import java.text.NumberFormat;
<ide> import java.util.ArrayList;
<ide> import org.sakaiproject.entity.cover.EntityManager;
<ide> import org.sakaiproject.entitybroker.EntityBroker;
<ide> import org.sakaiproject.entitybroker.entityprovider.extension.ActionReturn;
<add>import org.sakaiproject.entitybroker.EntityReference;
<ide> import org.sakaiproject.event.api.SessionState;
<ide> import org.sakaiproject.exception.IdInvalidException;
<ide> import org.sakaiproject.exception.IdUnusedException;
<ide> // tbd fix shared definition from org.sakaiproject.assignment.api.AssignmentEntityProvider
<ide> private final static String ASSN_ENTITY_ID = "assignment";
<ide> private final static String ASSN_ENTITY_ACTION = "deepLink";
<del> private final static String ASSN_ENTITY_PREFIX = File.separator+ASSN_ENTITY_ID+File.separator+ASSN_ENTITY_ACTION+File.separator;
<add> private final static String ASSN_ENTITY_PREFIX = EntityReference.SEPARATOR+ASSN_ENTITY_ID+EntityReference.SEPARATOR+ASSN_ENTITY_ACTION+EntityReference.SEPARATOR;
<ide>
<ide> private NumberFormat monthFormat = null;
<ide>
<ide> Map<String, Object> assignData = new HashMap<String, Object>();
<ide> StringBuilder entityId = new StringBuilder( ASSN_ENTITY_PREFIX );
<ide> entityId.append( (CalendarService.getCalendar(calEvent.getCalendarReference())).getContext() );
<del> entityId.append( File.separator );
<add> entityId.append( EntityReference.SEPARATOR );
<ide> entityId.append( assignmentId );
<ide> ActionReturn ret = entityBroker.executeCustomAction(entityId.toString(), ASSN_ENTITY_ACTION, null, null);
<ide> if (ret != null && ret.getEntityData() != null) { |
|
Java | mit | e873db38c77606b98a4d5d9ad291c413bbb4aee4 | 0 | conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5 | package com.conveyal.r5.analyst.cluster;
import com.conveyal.r5.analyst.GridCache;
import com.conveyal.r5.analyst.PointSet;
import com.conveyal.r5.analyst.WebMercatorGridPointSetCache;
import com.conveyal.r5.analyst.WorkerCategory;
import com.conveyal.r5.profile.ProfileRequest;
import com.conveyal.r5.transit.TransportNetwork;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.List;
/**
* Describes an analysis task to be performed.
*
* By default, the task will be a travelTimeSurfaceTask for one origin.
* This task is completed by returning a grid of total travel times from that origin to all destinations.
*/
@JsonTypeInfo(use= JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
// these match the enum values in AnalysisTask.Type
@JsonSubTypes.Type(name = "TRAVEL_TIME_SURFACE", value = TravelTimeSurfaceTask.class),
@JsonSubTypes.Type(name = "REGIONAL_ANALYSIS", value = RegionalTask.class)
})
public abstract class AnalysisTask extends ProfileRequest {
/**
* A loading cache of gridded pointSets (not opportunity data grids), shared statically among all single point and
* multi-point (regional) requests. TODO make this non-static yet shared.
*/
public static final WebMercatorGridPointSetCache gridPointSetCache = new WebMercatorGridPointSetCache();
public int zoom;
public int west;
public int north;
public int width;
public int height;
/** The ID of the graph against which to calculate this task. */
public String graphId;
/** The commit of r5 the worker should be running when it processes this task. */
public String workerVersion;
/** The job ID this is associated with. */
public String jobId;
/** The id of this particular origin. */
public String id;
/** A unique identifier for this task assigned by the queue/broker system. */
public int taskId;
/**
* Whether to save results on S3.
* If false, the results will only be sent back to the broker or UI.
* If true, travel time surfaces will be saved to S3
* Currently this only works on regional requests, and causes them to produce travel time surfaces instead of
* accessibility indicator values.
* FIXME in practice this always implies travelTimeBreakdown and returnPaths, so we've got redundant and potentially incoherent information in the request.
* The intent is in the future to make all these options separate - we can make either travel time surfaces or
* accessibility indicators or both, and they may or may not be saved to S3.
*/
public boolean makeStaticSite = false;
/** Whether to break travel time down into in-vehicle, wait, and access/egress time. */
public boolean travelTimeBreakdown = false;
/** Whether to include paths in results. This allows rendering transitive-style schematic maps. */
public boolean returnPaths = false;
/** Which percentiles of travel time to calculate. */
public double[] percentiles = new double[] { 50 };
/**
* When recording paths as in a static site, how many distinct paths should be saved to each destination?
* Currently this only makes sense in regional tasks, but it could also become relevant for travel time surfaces
* so it's in this superclass.
*/
public int nPathsPerTarget = 3;
/**
* Whether the R5 worker should log an analysis request it receives from the broker. analysis-backend translates
* front-end requests to the format expected by R5. To debug this translation process, set logRequest = true in
* the front-end profile request, then look for the full request received by the worker in its Cloudwatch log.
*/
public boolean logRequest = false;
/**
* Is this a task that should return a binary travel time surface or compute accessibility and return it via SQS
* to be saved in a regional analysis grid file?
*/
public abstract Type getType();
/** Ensure that type is perceived as a field by serialization libs, no-op */
public void setType (Type type) {};
public void setTypes (String type) {};
/**
* Whether this task is high priority and should jump in front of other work.
* TODO eliminate and use polymorphism, this is only used in one place.
*/
@JsonIgnore
public abstract boolean isHighPriority();
@JsonIgnore
public WorkerCategory getWorkerCategory () {
return new WorkerCategory(graphId, workerVersion);
}
public enum Type {
/* TODO these could be changed, to SINGLE_POINT and MULTI_POINT. The type of results requested (i.e. a grid of
travel times per origin vs. an accessibility value per origin) can be inferred based on whether grids are
specified in the profile request. If travel time results are requested, flags can specify whether components
of travel time (e.g. waiting) and paths should also be returned.
*/
/** Binary grid of travel times from a single origin, for multiple percentiles, returned via broker by default */
TRAVEL_TIME_SURFACE,
/** Bootstrapped accessibility results for multiple origins, returned over SQS by default. */
REGIONAL_ANALYSIS
}
public AnalysisTask clone () {
// no need to catch CloneNotSupportedException, it's caught in ProfileRequest::clone
return (AnalysisTask) super.clone();
}
}
| src/main/java/com/conveyal/r5/analyst/cluster/AnalysisTask.java | package com.conveyal.r5.analyst.cluster;
import com.conveyal.r5.analyst.GridCache;
import com.conveyal.r5.analyst.PointSet;
import com.conveyal.r5.analyst.WebMercatorGridPointSetCache;
import com.conveyal.r5.analyst.WorkerCategory;
import com.conveyal.r5.profile.ProfileRequest;
import com.conveyal.r5.transit.TransportNetwork;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.List;
/**
* Describes an analysis task to be performed.
*
* By default, the task will be a travelTimeSurfaceTask for one origin.
* This task is completed by returning a grid of total travel times from that origin to all destinations.
*/
@JsonTypeInfo(use= JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
// these match the enum values in AnalysisTask.Type
@JsonSubTypes.Type(name = "TRAVEL_TIME_SURFACE", value = TravelTimeSurfaceTask.class),
@JsonSubTypes.Type(name = "REGIONAL_ANALYSIS", value = RegionalTask.class)
})
public abstract class AnalysisTask extends ProfileRequest {
/**
* A loading cache of gridded pointSets (not opportunity data grids), shared statically among all single point and
* multi-point (regional) requests. TODO make this non-static yet shared.
*/
public static final WebMercatorGridPointSetCache gridPointSetCache = new WebMercatorGridPointSetCache();
public int zoom;
public int west;
public int north;
public int width;
public int height;
/** The ID of the graph against which to calculate this task. */
public String graphId;
/** The commit of r5 the worker should be running when it processes this task. */
public String workerVersion;
/** The job ID this is associated with. */
public String jobId;
/** The id of this particular origin. */
public String id;
/** A unique identifier for this task assigned by the queue/broker system. */
public int taskId;
/**
* Whether to save results on S3.
* If false, the results will only be sent back to the broker or UI.
* If true, travel time surfaces will be saved to S3
* Currently this only works on regional requests, and causes them to produce travel time surfaces instead of
* accessibility indicator values.
* FIXME in practice this always implies travelTimeBreakdown and returnPaths, so we've got redundant and potentially incoherent information in the request.
* The intent is in the future to make all these options separate - we can make either travel time surfaces or
* accessibility indicators or both, and they may or may not be saved to S3.
*/
public boolean makeStaticSite = false;
/** Whether to break travel time down into in-vehicle, wait, and access/egress time. */
public boolean travelTimeBreakdown = false;
/** Whether to include paths in results. This allows rendering transitive-style schematic maps. */
public boolean returnPaths = false;
/** Which percentiles of travel time to calculate. */
public double[] percentiles = new double[] { 50 };
/**
* When recording paths as in a static site, how many distinct paths should be saved to each destination?
* Currently this only makes sense in regional tasks, but it could also become relevant for travel time surfaces
* so it's in this superclass.
*/
public int nPathsPerTarget = 3;
public boolean logRequest = false;
/**
* Is this a task that should return a binary travel time surface or compute accessibility and return it via SQS
* to be saved in a regional analysis grid file?
*/
public abstract Type getType();
/** Ensure that type is perceived as a field by serialization libs, no-op */
public void setType (Type type) {};
public void setTypes (String type) {};
/**
* Whether this task is high priority and should jump in front of other work.
* TODO eliminate and use polymorphism, this is only used in one place.
*/
@JsonIgnore
public abstract boolean isHighPriority();
@JsonIgnore
public WorkerCategory getWorkerCategory () {
return new WorkerCategory(graphId, workerVersion);
}
public enum Type {
/* TODO these could be changed, to SINGLE_POINT and MULTI_POINT. The type of results requested (i.e. a grid of
travel times per origin vs. an accessibility value per origin) can be inferred based on whether grids are
specified in the profile request. If travel time results are requested, flags can specify whether components
of travel time (e.g. waiting) and paths should also be returned.
*/
/** Binary grid of travel times from a single origin, for multiple percentiles, returned via broker by default */
TRAVEL_TIME_SURFACE,
/** Bootstrapped accessibility results for multiple origins, returned over SQS by default. */
REGIONAL_ANALYSIS
}
public AnalysisTask clone () {
// no need to catch CloneNotSupportedException, it's caught in ProfileRequest::clone
return (AnalysisTask) super.clone();
}
}
| docs(request): add javadoc
| src/main/java/com/conveyal/r5/analyst/cluster/AnalysisTask.java | docs(request): add javadoc | <ide><path>rc/main/java/com/conveyal/r5/analyst/cluster/AnalysisTask.java
<ide> */
<ide> public int nPathsPerTarget = 3;
<ide>
<add> /**
<add> * Whether the R5 worker should log an analysis request it receives from the broker. analysis-backend translates
<add> * front-end requests to the format expected by R5. To debug this translation process, set logRequest = true in
<add> * the front-end profile request, then look for the full request received by the worker in its Cloudwatch log.
<add> */
<ide> public boolean logRequest = false;
<ide>
<ide> /** |
|
Java | epl-1.0 | 7e280014877bdcb7c1548efc3daf3cf564dd1dbd | 0 | miklossy/xtext-core,miklossy/xtext-core | /*******************************************************************************
* Copyright (c) 2012 itemis AG (http://www.itemis.eu) and others.
* 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.eclipse.xtext.generator;
import java.io.CharArrayWriter;
import org.eclipse.emf.common.util.URI;
import org.eclipse.xtext.formatting.IWhitespaceInformationProvider;
import com.google.inject.Inject;
/**
* Replaces all line breaks with the configured line separator.
*
* @author Jan Koehnlein - Initial contribution and API
* @since 2.3
*/
public class LineSeparatorHarmonizer implements IFilePostProcessor {
@Inject
private IWhitespaceInformationProvider whitespaceInformationProvider;
public CharSequence postProcess(URI fileURI, CharSequence content) {
String lineSeparator = whitespaceInformationProvider.getLineSeparatorInformation(fileURI).getLineSeparator();
return replaceLineSeparators(content, lineSeparator);
}
protected String replaceLineSeparators(CharSequence content, String newLineSeparator) {
CharArrayWriter writer = new CharArrayWriter(content.length());
boolean isLookahead = false;
char ignoreNext = '\u0000';
for(int i=0; i<content.length(); ++i) {
char c = content.charAt(i);
if (isLookahead) {
isLookahead = false;
if (c == ignoreNext)
continue;
}
switch (c) {
case '\n':
writer.append(newLineSeparator);
isLookahead = true;
ignoreNext = '\r';
break;
case '\r':
writer.append(newLineSeparator);
isLookahead = true;
ignoreNext = '\n';
break;
default:
writer.append(c);
}
}
return writer.toString();
}
protected IWhitespaceInformationProvider getWhitespaceInformationProvider() {
return whitespaceInformationProvider;
}
}
| plugins/org.eclipse.xtext/src/org/eclipse/xtext/generator/LineSeparatorHarmonizer.java | /*******************************************************************************
* Copyright (c) 2012 itemis AG (http://www.itemis.eu) and others.
* 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.eclipse.xtext.generator;
import java.io.CharArrayWriter;
import org.eclipse.emf.common.util.URI;
import org.eclipse.xtext.formatting.IWhitespaceInformationProvider;
import com.google.inject.Inject;
/**
* Replaces all line breaks with the configured line separator.
*
* @author Jan Koehnlein - Initial contribution and API
* @since 2.3
*/
public class LineSeparatorHarmonizer implements IFilePostProcessor {
@Inject
private IWhitespaceInformationProvider whitespaceInformationProvider;
public String postProcess(URI fileURI, CharSequence content) {
String lineSeparator = whitespaceInformationProvider.getLineSeparatorInformation(fileURI).getLineSeparator();
CharArrayWriter writer = new CharArrayWriter(content.length());
boolean isLookahead = false;
char ignoreNext = '\u0000';
for(int i=0; i<content.length(); ++i) {
char c = content.charAt(i);
if (isLookahead) {
isLookahead = false;
if (c == ignoreNext)
continue;
}
switch (c) {
case '\n':
writer.append(lineSeparator);
isLookahead = true;
ignoreNext = '\r';
break;
case '\r':
writer.append(lineSeparator);
isLookahead = true;
ignoreNext = '\n';
break;
default:
writer.append(c);
}
}
return new String(writer.toCharArray());
}
}
| [trace] Replaced TracingAppendable by TreeAppendable which can be post processed | plugins/org.eclipse.xtext/src/org/eclipse/xtext/generator/LineSeparatorHarmonizer.java | [trace] Replaced TracingAppendable by TreeAppendable which can be post processed | <ide><path>lugins/org.eclipse.xtext/src/org/eclipse/xtext/generator/LineSeparatorHarmonizer.java
<ide> @Inject
<ide> private IWhitespaceInformationProvider whitespaceInformationProvider;
<ide>
<del> public String postProcess(URI fileURI, CharSequence content) {
<add> public CharSequence postProcess(URI fileURI, CharSequence content) {
<ide> String lineSeparator = whitespaceInformationProvider.getLineSeparatorInformation(fileURI).getLineSeparator();
<add> return replaceLineSeparators(content, lineSeparator);
<add> }
<add>
<add> protected String replaceLineSeparators(CharSequence content, String newLineSeparator) {
<ide> CharArrayWriter writer = new CharArrayWriter(content.length());
<ide> boolean isLookahead = false;
<ide> char ignoreNext = '\u0000';
<ide> }
<ide> switch (c) {
<ide> case '\n':
<del> writer.append(lineSeparator);
<add> writer.append(newLineSeparator);
<ide> isLookahead = true;
<ide> ignoreNext = '\r';
<ide> break;
<ide> case '\r':
<del> writer.append(lineSeparator);
<add> writer.append(newLineSeparator);
<ide> isLookahead = true;
<ide> ignoreNext = '\n';
<ide> break;
<ide> writer.append(c);
<ide> }
<ide> }
<del> return new String(writer.toCharArray());
<add> return writer.toString();
<add> }
<add>
<add> protected IWhitespaceInformationProvider getWhitespaceInformationProvider() {
<add> return whitespaceInformationProvider;
<ide> }
<ide> } |
|
JavaScript | agpl-3.0 | 40f1c2dfe5fa6811257bdc6a3da28cd388d90894 | 0 | Memba/Memba-Widgets,Memba/Memba-Widgets,Memba/Memba-Widgets | /**
* Copyright (c) 2013-2017 Memba Sarl. All rights reserved.
* Sources at https://github.com/Memba
*/
/* jshint browser: true, jquery: true */
/* globals define: false */
(function (f, define) {
'use strict';
define([
'./window.assert',
'./window.logger',
'./vendor/kendo/kendo.binder',
'./vendor/kendo/kendo.color',
'./vendor/kendo/kendo.drawing',
'./vendor/kendo/kendo.toolbar'
], f);
})(function () {
'use strict';
/* This function has too many statements. */
/* jshint -W071 */
(function ($, undefined) {
var kendo = window.kendo;
var data = kendo.data;
var drawing = kendo.drawing;
var geometry = kendo.geometry;
var Color = kendo.Color;
var DataSource = data.DataSource;
var Surface = drawing.Surface;
var Widget = kendo.ui.Widget;
var ToolBar = kendo.ui.ToolBar;
var assert = window.assert;
var logger = new window.Logger('kidoju.widgets.selection');
var NUMBER = 'number';
var STRING = 'string';
// var NULL = 'null';
var UNDEFINED = 'undefined';
var DOT = '.';
var HASH = '#';
var WIDGET = 'kendoSelector';
var NS = DOT + WIDGET;
var CHANGE = 'change';
var MOUSEDOWN = 'mousedown' + NS + ' ' + 'touchstart' + NS;
var MOUSEMOVE = 'mousemove' + NS + ' ' + 'touchmove' + NS;
var MOUSEUP = 'mouseup' + NS + ' ' + 'touchend' + NS;
var TOGGLE = 'toggle';
var DIV = '<div/>';
var ROLE = 'selector';
var ID = 'id';
var WIDGET_CLASS = 'kj-selector';
var SURFACE_CLASS = WIDGET_CLASS + '-surface';
var INTERACTIVE_CLASS = 'kj-interactive';
var DATA_TYPE = 'selection';
var MIN_DIAGONAL = 30;
var LINE_HW_PROPORTION = 0.2;
var SHAPE_HIT_DISTANCE = 10;
var CROSS_CURVE = 0.5;
/*********************************************************************************
* Helpers
*********************************************************************************/
var util = {
/**
* Build a random hex string of length characters
* @param length
* @returns {string}
*/
randomString: function (length) {
var s = new Array(length + 1).join('x');
return s.replace(/x/g, function (c) {
/* jshint -W016 */
return (Math.random() * 16|0).toString(16);
/* jshint +W016 */
});
},
/**
* Get the mouse (or touch) position
* @param e
* @param stage
* @returns {{x: *, y: *}}
*/
getMousePosition: function (e, stage) {
assert.instanceof($.Event, e, kendo.format(assert.messages.instanceof.default, 'e', 'jQuery.Event'));
assert.instanceof($, stage, kendo.format(assert.messages.instanceof.default, 'stage', 'jQuery'));
// See http://www.jacklmoore.com/notes/mouse-position/
// See http://www.jqwidgets.com/community/topic/dragend-event-properties-clientx-and-clienty-are-undefined-on-ios/
// See http://www.devinrolsen.com/basic-jquery-touchmove-event-setup/
// ATTENTION: e.originalEvent.changedTouches instanceof TouchList, not Array
var originalEvent = e.originalEvent;
var clientX = originalEvent && originalEvent.changedTouches ? originalEvent.changedTouches[0].clientX : e.clientX;
var clientY = originalEvent && originalEvent.changedTouches ? originalEvent.changedTouches[0].clientY : e.clientY;
// IMPORTANT: Position is relative to the stage and e.offsetX / e.offsetY do not work in Firefox
// var stage = $(e.target).closest('.kj-stage').find(kendo.roleSelector('stage'));
var ownerDocument = $(stage.get(0).ownerDocument);
var stageOffset = stage.offset();
var mouse = {
x: clientX - stageOffset.left + ownerDocument.scrollLeft(),
y: clientY - stageOffset.top + ownerDocument.scrollTop()
};
return mouse;
},
/**
* Get the position of the center of an element
* @param element
* @param stage
* @param scale
*/
getElementCenter: function (element, stage, scale) {
assert.instanceof($, element, kendo.format(assert.messages.instanceof.default, 'element', 'jQuery'));
assert.instanceof($, stage, kendo.format(assert.messages.instanceof.default, 'stage', 'jQuery'));
assert.type(NUMBER, scale, kendo.format(assert.messages.type.default, 'scale', NUMBER));
// We need getBoundingClientRect to especially account for rotation
var rect = element[0].getBoundingClientRect();
var ownerDocument = $(stage.get(0).ownerDocument);
var stageOffset = stage.offset();
return {
left: (rect.left - stageOffset.left + rect.width / 2 + ownerDocument.scrollLeft()) / scale,
top: (rect.top - stageOffset.top + rect.height / 2 + ownerDocument.scrollTop()) / scale
};
},
/**
* Get the scale of an element's CSS transformation
* Note: the same function is used in kidoju.widgets.stage
* @param element
* @returns {Number|number}
*/
getTransformScale: function (element) {
assert.instanceof($, element, kendo.format(assert.messages.instanceof.default, 'element', 'jQuery'));
// element.css('transform') returns a matrix, so we have to read the style attribute
var match = (element.attr('style') || '').match(/scale\([\s]*([0-9\.]+)[\s]*\)/);
return $.isArray(match) && match.length > 1 ? parseFloat(match[1]) || 1 : 1;
},
/* This function's cyclomatic complexity is too high. */
/* jshint -W074 */
/**
* Detect the shape of a path (circle, cross, line) among a list of shapes
* @param path
* @param shapes
*/
detectShape: function (path, shapes) {
assert.instanceof(drawing.Path, path, kendo.format(assert.messages.instanceof.default, 'path', 'kendo.drawing.Path'));
assert.isArray(shapes, kendo.format(assert.messages.isArray.default, 'shapes'));
assert.hasLength(shapes, kendo.format(assert.messages.hasLength.default, 'shapes'));
if (shapes.length === 1) {
return shapes[0];
}
var bbox = path.bbox();
var x = Math.floor(bbox.origin.x);
var y = Math.floor(bbox.origin.y);
var height = Math.floor(bbox.size.height);
var width = Math.floor(bbox.size.width);
// Detect a line (height / width ratio)
if (height / width < LINE_HW_PROPORTION && shapes.indexOf(SelectorSurface.fn.shapes.line) > -1) {
return SelectorSurface.fn.shapes.line;
}
if (shapes.indexOf(SelectorSurface.fn.shapes.circle) === -1 && shapes.indexOf(SelectorSurface.fn.shapes.cross) > -1) {
return SelectorSurface.fn.shapes.cross;
} else if (shapes.indexOf(SelectorSurface.fn.shapes.circle) > -1 && shapes.indexOf(SelectorSurface.fn.shapes.cross) === -1) {
return SelectorSurface.fn.shapes.circle;
} else if (shapes.indexOf(SelectorSurface.fn.shapes.circle) > -1 && shapes.indexOf(SelectorSurface.fn.shapes.cross) > -1) {
// Detect a circle (shape nears top, right, bottom and left)
var topPoint = new geometry.Point(x + width / 2, y);
var rightPoint = new geometry.Point(x + width, y + height / 2);
var bottomPoint = new geometry.Point(x + width / 2, y + height);
var leftPoint = new geometry.Point(x, y + height / 2);
var hitTop = false;
var hitRight = false;
var hitBottom = false;
var hitLeft = false;
for (var i = 0, length = path.segments.length; i < length; i++) {
var segment = path.segments[i];
if (!hitTop) {
hitTop = segment.anchor().distanceTo(topPoint) < SHAPE_HIT_DISTANCE;
}
if (!hitRight) {
hitRight = segment.anchor().distanceTo(rightPoint) < SHAPE_HIT_DISTANCE;
}
if (!hitBottom) {
hitBottom = segment.anchor().distanceTo(bottomPoint) < SHAPE_HIT_DISTANCE;
}
if (!hitLeft) {
hitLeft = segment.anchor().distanceTo(leftPoint) < SHAPE_HIT_DISTANCE;
}
if (hitTop && hitRight && hitBottom && hitLeft) {
break;
}
}
if (hitTop && hitRight && hitBottom && hitLeft) {
return SelectorSurface.fn.shapes.circle;
} else {
// Otherwise let's assume it is a cross
return SelectorSurface.fn.shapes.cross;
}
}
},
/* jshint +W074 */
/**
* Get a selection data item for dataSource from a user-drawn path
* @param path
* @param color
* @param shapes
*/
getDataItem: function (path, color, shapes) {
assert.instanceof(drawing.Path, path, kendo.format(assert.messages.instanceof.default, 'path', 'kendo.drawing.Path'));
assert.type(STRING, color, kendo.format(assert.messages.type.default, 'color', STRING));
assert.isArray(shapes, kendo.format(assert.messages.isArray.default, 'shapes'));
assert.hasLength(shapes, kendo.format(assert.messages.hasLength.default, 'shapes'));
var bbox = path.bbox();
var height = Math.floor(bbox.size.height);
var width = Math.floor(bbox.size.width);
// If the user-drawn path is too small, discard
if (Math.sqrt(Math.pow(height, 2) + Math.pow(width, 2)) > MIN_DIAGONAL) {
return {
type: DATA_TYPE,
data: {
color: color,
origin: { x: Math.floor(bbox.origin.x), y: Math.floor(bbox.origin.y) },
shape: util.detectShape(path, shapes),
size: { height: height, width: width }
}
};
}
},
/**
* Get an horizontal line path within rect
* @param rect
* @param options
*/
getHorizontalLineDrawing: function (rect, options) {
assert.instanceof(geometry.Rect, rect, kendo.format(assert.messages.instanceof.default, 'rect', 'kendo.geometry.Rect'));
var path = new drawing.Path(options);
path.moveTo(rect.origin.x, rect.origin.y + rect.size.height / 2);
path.lineTo(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height / 2);
return path;
},
/**
* Get the arc of an ellipsis within rect
* @param rect
* @param options
*/
getCircleDrawing: function (rect, options) {
assert.instanceof(geometry.Rect, rect, kendo.format(assert.messages.instanceof.default, 'rect', 'kendo.geometry.Rect'));
var arcGeometry = new geometry.Arc(
[rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height / 2], // center
{
radiusX: rect.size.width / 2,
radiusY: rect.size.height / 2,
startAngle: 0,
endAngle: 360,
anticlockwise: false
}
);
return new drawing.Arc(arcGeometry, options);
},
/**
* Get a cross path within rect
* @param rect
* @param options
*/
getCrossDrawing: function (rect, options) {
assert.instanceof(geometry.Rect, rect, kendo.format(assert.messages.instanceof.default, 'rect', 'kendo.geometry.Rect'));
var path = new drawing.Path(options);
var x = rect.origin.x;
var y = rect.origin.y;
var height = rect.size.height;
var width = rect.size.width;
path.moveTo(x + width, y);
path.lineTo(x + CROSS_CURVE * width, y + (1 - CROSS_CURVE) * height);
path.curveTo(
[x, y + height],
[x, y + height],
[x, y + (1 - CROSS_CURVE) * height]
);
path.lineTo(x, y + CROSS_CURVE * height);
path.curveTo(
[x, y],
[x, y],
[x + CROSS_CURVE * width, y + CROSS_CURVE * height]
);
path.lineTo(x + width, y + height);
return path;
},
/**
* Draw a shape from a dataSource dataItem
* @param dataItem
* @param strokeOptions
*/
getSelectionDrawing: function (dataItem, strokeOptions) {
assert.instanceof(kendo.data.ObservableObject, dataItem, kendo.format(assert.messages.instanceof.default, 'dataItem', 'kendo.data.ObservableObject'));
var shape = dataItem.data.shape;
var rect = new geometry.Rect([dataItem.data.origin.x, dataItem.data.origin.y], [dataItem.data.size.width, dataItem.data.size.height]);
var options = { stroke: $.extend(strokeOptions, { color: dataItem.data.color }) };
if (shape === SelectorSurface.fn.shapes.line) {
return util.getHorizontalLineDrawing(rect, options);
} else if (shape === SelectorSurface.fn.shapes.circle) {
return util.getCircleDrawing(rect, options);
} else {
return util.getCrossDrawing(rect, options);
}
}
};
/*********************************************************************************
* SelectorToolBar Widget
*********************************************************************************/
var SelectorToolBar = ToolBar.extend({
/**
* Initializes the widget
* @param element
* @param options
*/
init: function (element, options) {
var that = this;
options = options || {};
ToolBar.fn.init.call(that, element, options);
logger.debug({ method: 'init', message: 'toolbar initialized' });
that.bind(TOGGLE, that._onToggle);
kendo.notify(that);
},
/**
* Widget options
*/
options: {
name: 'SelectorToolBar',
iconSize: 16,
resizable: false
},
/**
* Add a color to the toolbar
* @param color
*/
addColor: function (color) {
var that = this;
// k-button-group in kendo.ui & km-buttongroup (wo second -) in kendo.mobile.ui
var buttonGroup = this.element.children('.k-button-group, .km-buttongroup');
var toolBarColors = buttonGroup.children('.k-toggle-button').map(function () {
return HASH + $(this).attr('id');
});
var buttons = [];
// Rebuild previous buttons;
for (var i = 0, length = toolBarColors.length; i < length; i++) {
buttons.push({
type: 'button',
group: 'selectorColors',
id: toolBarColors[i].substr(1), // removes the hashtag
imageUrl: that._createImageUrl(toolBarColors[i]),
showText: 'overflow',
text: toolBarColors[i],
togglable: true
});
}
// Parse color for what is actually a color
color = kendo.parseColor(color).toCss(); // might raise an exception
// Do not add a color that already exists
var found = buttons.find(function (button) {
return button.text === color;
});
// Create button
if ($.type(found) === UNDEFINED) {
buttons.push({
type: 'button',
group: 'selectorColors',
id: color.substr(1), // removes the hashtag
imageUrl: that._createImageUrl(color),
showText: 'overflow',
text: color,
togglable: true
});
}
if (buttonGroup.length) {
that.remove(buttonGroup);
}
that.add({ type: 'buttonGroup', buttons: buttons });
if (buttons.length) {
that.toggle(HASH + buttons[0].id, true);
that._onToggle({ id: buttons[0].id });
}
that.wrapper.toggle(buttons.length > 1);
},
/**
* Create toolbar icon
* @param: color
* @private
*/
_createImageUrl: function (color) {
var canvas = document.createElement('canvas');
canvas.height = this.options.iconSize;
canvas.width = this.options.iconSize;
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(
this.options.iconSize / 2, // center.x
this.options.iconSize / 2, // center.y
this.options.iconSize / 2, // radius
0, // start angle
2 * Math.PI // end angle
);
ctx.strokeStyle = 'black';
ctx.fillStyle = color;
ctx.stroke();
ctx.fill();
return canvas.toDataURL();
},
/**
* Register corresponding selector surface, the surface the selected color applies to
*/
registerSelectorSurface: function (selectorSurface) {
assert.instanceof(SelectorSurface, selectorSurface, kendo.format(assert.messages.instanceof.default, 'selectorSurface', 'kendo.ui.SelectorSurface'));
this.selectorSurface = selectorSurface;
},
/**
* Button toggle event handler
* @private
*/
_onToggle: function (e) {
assert.isPlainObject(e, kendo.format(assert.messages.isPlainObject.default, 'e'));
assert.instanceof(SelectorSurface, this.selectorSurface, kendo.format(assert.messages.instanceof.default, 'this.selectorSurface', 'kendo.ui.SelectorSurface'));
this.selectorSurface.color(HASH + e.id);
},
/**
* Destroy widget
*/
destroy: function () {
var that = this;
var element = that.element;
ToolBar.fn.destroy.call(that);
kendo.destroy(element);
}
});
kendo.ui.plugin(SelectorToolBar);
/*********************************************************************************
* SelectorSurface Widget
*********************************************************************************/
var SelectorSurface = Widget.extend({
/**
* Initializes the widget
* @param element
* @param options
*/
init: function (element, options) {
var that = this;
options = options || {};
Widget.fn.init.call(that, element, options);
logger.debug('surface initialized');
that._layout();
that._createToolBar();
that._dataSource();
kendo.notify(that);
},
/**
* Options
*/
options: {
name: 'SelectorSurface',
container: 'div.kj-stage>div[data-' + kendo.ns + 'role="stage"]', // TODO: container might not be necessary??? - replace with that.element / https://github.com/kidoju/Kidoju-Widgets/issues/167
scaler: 'div.kj-stage',
penStroke: {
width: 8
},
toolbar: '#toolbar'
},
/**
* Enumeration of possible shapes
*/
shapes: {
circle: 'circle',
cross: 'cross',
line: 'line'
},
/**
* Layout
* @private
*/
_layout: function () {
var that = this;
var element = that.element;
that.wrapper = element;
element
.addClass(SURFACE_CLASS);
that.surface = drawing.Surface.create(element);
},
/**
* Create toolbar
* @private
*/
_createToolBar: function () {
var that = this;
var toolbarContainer = $(that.options.toolbar);
if (toolbarContainer.length) {
var toolbarElement = $(DIV).appendTo(toolbarContainer);
that.toolbar = toolbarElement.kendoSelectorToolBar().data('kendoSelectorToolBar');
that.toolbar.registerSelectorSurface(this);
}
},
/**
* Register a selector
* @param selector
* @private
*/
registerSelector: function (selector) {
var that = this;
var options = that.options;
assert.instanceof(Selector, selector, kendo.format(assert.messages.instanceof.default, 'selector', 'Selector'));
assert.equal(options.container, selector.options.container, kendo.format(assert.messages.equal.default, 'selector.options.container', 'this.options.container'));
assert.equal(options.scaler, selector.options.scaler, kendo.format(assert.messages.equal.default, 'selector.options.scaler', 'this.options.scaler'));
// assert.equal(options.dataSource, selector.options.dataSource, kendo.format(assert.messages.equal.default, 'selector.options.dataSource', 'this.options.dataSource'));
if (!$.isArray(that.selectors)) {
that.selectors = [];
}
if (that.selectors.indexOf(selector) === -1) {
that.selectors.push(selector);
// Set the prefix for dataSource ids (so as to only draw selections for the current page when played)
var selectorId = selector.element.attr(kendo.attr(ID)) || '';
if ($.type(that._selectorId) === UNDEFINED) {
that._selectorId = selectorId;
} else if (that._selectorId > selectorId) {
that._selectorId = selectorId;
}
// Add enabled selector color to toolbar
if (that.toolbar instanceof SelectorToolBar && selector._enabled) {
that.toolbar.addColor(selector.options.shapeStroke.color);
}
// Reset mouse handlers
that._initMouseEvents();
}
},
/**
* Gets/Sets color
* @private
*/
color: function (color) {
if ($.type(color) === UNDEFINED) {
return this._color;
} else {
this._color = kendo.parseColor(color).toCss(); // This might raise an exception
}
},
/**
* Init mouse event handlers to draw on surface
* @private
*/
_initMouseEvents: function () {
// IMPORTANT
// We can have several widgets for selections on a page
// But we only have one set of event handlers shared across all selections
// So we cannot use `this` within handlers, which is specific to this selector surface
var options = this.options;
var data = {}; // We need an object so that data is passed by reference between handlers
// ATTENTION! There might be several options.container on the page as in Kidoju-Mobile
// So we need to make sure we unbind/bind events to the parent container
// https://github.com/kidoju/Kidoju-Widgets/issues/162
var container = this.element.closest(options.container);
var containers = $(document).find(options.container);
container = options.container + ':eq(' + containers.index(container) + ')';
$(document)
.off(NS, container);
if (this.enable()) {
$(document)
.on(MOUSEDOWN, container, data, this._onMouseDown)
.on(MOUSEMOVE, container, data, this._onMouseMove)
.on(MOUSEUP, container, data, this._onMouseUp);
}
},
/**
* Mouse down event handler
* @param e
* @private
*/
_onMouseDown: function (e) {
assert.instanceof($.Event, e, kendo.format(assert.messages.instanceof.default, 'e', 'jQuery.Event'));
e.preventDefault(); // prevents from selecting the div
if ($(e.target).hasClass(INTERACTIVE_CLASS)) {
return;
}
var container = $(e.currentTarget);
// Although `this` is unavailable, surfaceElement and surfaceWidget give us the drawing surface and dataSource
var surfaceElement = container.find(DOT + SURFACE_CLASS);
assert.hasLength(surfaceElement, kendo.format(assert.messages.hasLength.default, surfaceElement));
var surfaceWidget = surfaceElement.data('kendoSelectorSurface');
assert.instanceof(SelectorSurface, surfaceWidget, kendo.format(assert.messages.instanceof.default, 'surfaceWidget', 'kendo.ui.SelectorSurface'));
var scaler = container.closest(surfaceWidget.options.scaler);
var scale = scaler.length ? util.getTransformScale(scaler) : 1;
var mouse = util.getMousePosition(e, container);
var mousePoint = new geometry.Point(mouse.x / scale, mouse.y / scale);
var surface = surfaceWidget.surface;
assert.instanceof(Surface, surface, kendo.format(assert.messages.instanceof.default, 'surface', 'kendo.drawing.Surface'));
var dataSource = surfaceWidget.dataSource;
assert.instanceof(DataSource, dataSource, kendo.format(assert.messages.instanceof.default, 'dataSource', 'kendo.data.DataSource'));
var dataItems2Delete = dataSource.view().filter(function (dataItem) {
var selectionBox = dataItem.data;
return (mousePoint.x >= selectionBox.origin.x &&
mousePoint.x <= selectionBox.origin.x + selectionBox.size.width &&
mousePoint.y >= selectionBox.origin.y &&
mousePoint.y <= selectionBox.origin.y + selectionBox.size.height);
});
if ($.isArray(dataItems2Delete) && dataItems2Delete.length) {
dataItems2Delete.forEach(function (dataItem) {
dataSource.remove(dataItem);
});
} else {
var strokeOptions = $.extend({}, surfaceWidget.options.penStroke, { color: surfaceWidget.color() });
var path = new drawing.Path({ stroke: strokeOptions });
path.moveTo(mousePoint);
surface.draw(path);
e.data.path = path;
logger.debug({
method: '_onMouseDown',
message: 'Added new path',
data: strokeOptions
});
}
},
/**
* Mouse move event handler
* @param e
* @private
*/
_onMouseMove: function (e) {
assert.instanceof($.Event, e, kendo.format(assert.messages.instanceof.default, 'e', 'jQuery.Event'));
var path = e.data.path;
if (path instanceof kendo.drawing.Path) {
var container = $(e.currentTarget);
// Although `this` is unavailable, surfaceElement and surfaceWidget give us the drawing surface and dataSource
var surfaceElement = container.find(DOT + SURFACE_CLASS);
assert.hasLength(surfaceElement, kendo.format(assert.messages.hasLength.default, surfaceElement));
var surfaceWidget = surfaceElement.data('kendoSelectorSurface');
assert.instanceof(SelectorSurface, surfaceWidget, kendo.format(assert.messages.instanceof.default, 'surfaceWidget', 'kendo.ui.SelectorSurface'));
var scaler = container.closest(surfaceWidget.options.scaler);
var scale = scaler.length ? util.getTransformScale(scaler) : 1;
var mouse = util.getMousePosition(e, container);
path.lineTo(mouse.x / scale, mouse.y / scale);
}
},
/**
* Mouse up event handler
* @param e
* @private
*/
_onMouseUp: function (e) {
assert.instanceof($.Event, e, kendo.format(assert.messages.instanceof.default, 'e', 'jQuery.Event'));
var path = e.data.path;
if (path instanceof drawing.Path) {
var container = $(e.currentTarget);
// Although `this` is unavailable, surfaceElement and surfaceWidget give us the drawing surface and dataSouce
var surfaceElement = container.find(DOT + SURFACE_CLASS);
assert.hasLength(surfaceElement, kendo.format(assert.messages.hasLength.default, surfaceElement));
var surfaceWidget = surfaceElement.data('kendoSelectorSurface');
assert.instanceof(SelectorSurface, surfaceWidget, kendo.format(assert.messages.instanceof.default, 'surfaceWidget', 'kendo.ui.SelectorSurface'));
var dataSource = surfaceWidget.dataSource;
if (dataSource instanceof kendo.data.DataSource) {
var dataItem = util.getDataItem(path, surfaceWidget.color(), surfaceWidget.getSelectorShapes());
if ($.isPlainObject(dataItem)) {
// Add random Object Id
dataItem.id = util.randomString(24);
// Designate a selector to identify the page
dataItem.data.selector = surfaceWidget._selectorId;
dataSource.add(dataItem);
} else {
// Refresh (to remove the failed attempt at drawing a selection)
dataSource.trigger(CHANGE);
}
}
}
e.data.path = undefined;
},
/**
* _dataSource function to bind the refresh handler to the change event
* @private
*/
_dataSource: function () {
var that = this;
// returns the datasource OR creates one if using array or configuration
that.dataSource = DataSource.create(that.options.dataSource);
// bind to the change event to refresh the widget
if (that._refreshHandler) {
that.dataSource.unbind(CHANGE, that._refreshHandler);
}
that._refreshHandler = $.proxy(that.refresh, that);
that.dataSource.bind(CHANGE, that._refreshHandler);
// Filter dataSource
that.dataSource.filter({ field: 'type', operator: 'eq', value: DATA_TYPE });
// trigger a read on the dataSource if one hasn't happened yet
if (that.options.autoBind) {
that.dataSource.fetch();
}
var selectors = that.selectors;
if ($.isArray(selectors)) {
for (var i = 0, length = selectors.length; i < length; i++) {
if (selectors[i].dataSource !== that.dataSource) {
selectors[i].setDataSource(that.dataSource);
}
}
}
},
/**
* Sets the dataSource for source binding
* @param dataSource
*/
setDataSource: function (dataSource) {
var that = this;
// set the internal datasource equal to the one passed in by MVVM
that.options.dataSource = dataSource;
// rebuild the datasource if necessary, or just reassign
that._dataSource();
},
/**
* Refresh handler to redraw all selections from dataSource
*/
refresh: function () {
var that = this;
var options = that.options;
var dataSource = that.dataSource;
var surface = that.surface;
var selectors = that.selectors;
assert.instanceof(DataSource, dataSource, kendo.format(assert.messages.instanceof.default, 'this.dataSource', 'kendo.data.DataSource'));
assert.instanceof(Surface, surface, kendo.format(assert.messages.instanceof.default, 'this.surface', 'kendo.data.Surface'));
var dataView = dataSource.view(); // This is filtered
if (surface instanceof kendo.drawing.Surface) {
// Clear surface
surface.clear();
// Draw
for (var i = 0, total = dataView.length; i < total; i++) {
var dataItem = dataView[i];
// Draw the item only if it relates to the prefix
if (dataItem.type === DATA_TYPE && dataItem.data.selector === that._selectorId) {
surface.draw(util.getSelectionDrawing(dataItem, $.extend({}, options.penStroke)));
}
}
}
// Trigger a change on all selector widgets to recalculate databound values
if ($.isArray(selectors)) {
for (var j = 0, length = selectors.length; j < length; j++) {
var selector = selectors[j];
assert.instanceof(Selector, selector, kendo.format(assert.messages.instanceof.default, 'selector', 'kendo.ui.Selector'));
try {
// We might get `Uncaught TypeError: Cannot read property 'value' of undefined`
// because a refresh is triggered before test is added to the viewModel in play mode
selector.trigger(CHANGE);
} catch (ex) {}
}
}
},
/**
* Scan registered selectors for all shapes
*/
getSelectorShapes: function () {
var selectors = this.selectors;
var shapes = [];
if ($.isArray(selectors)) {
for (var i = 0, length = selectors.length; i < length; i++) {
var shape = selectors[i].options.shape;
if (shapes.indexOf(shape) === -1) {
shapes.push(shape); // test a dummy shape
}
}
}
return shapes;
},
/**
* Scan registered selectors for all colors
*/
getSelectorColors: function () {
var selectors = this.selectors;
var colors = [];
if ($.isArray(colors)) {
for (var i = 0, length = selectors.length; i < length; i++) {
var color = selectors[i].options.color;
if (colors.indexOf(color) === -1) {
colors.push(color);
}
}
}
return colors;
},
/**
* Return true if any selector is enabled, false if all selectors are disabled
*/
enable: function () {
var selectors = this.selectors;
var enabled = false;
if ($.isArray(selectors)) {
for (var i = 0, length = selectors.length; i < length; i++) {
enabled = enabled || selectors[i]._enabled;
}
}
return enabled;
},
/**
* Destroy the widget
* @method destroy
*/
destroy: function () {
var that = this;
var element = that.element;
// unbind document events
that._initMouseEvents();
// unbind dataSource
if ($.isFunction(that._refreshHandler)) {
that.dataSource.unbind(CHANGE, that._refreshHandler);
}
// destroy toolbar
if (that.toolbar instanceof SelectorToolBar) {
that.toolbar.destroy();
that.toolbar.wrapper.remove();
that.toolbar = undefined;
}
// Release references
that.surface = undefined;
that.selectors = undefined;
// Destroy kendo
Widget.fn.destroy.call(that);
kendo.destroy(element);
// Remove widget class
element.removeClass(WIDGET_CLASS);
}
});
kendo.ui.plugin(SelectorSurface);
/*********************************************************************************
* Selector Widget
*********************************************************************************/
/**
* Selector
* @class Selector Widget (kendoSelector)
*/
var Selector = Widget.extend({
/**
* Initializes the widget
* @param element
* @param options
*/
init: function (element, options) {
var that = this;
options = options || {};
Widget.fn.init.call(that, element, options);
logger.debug({ method: 'init', message: 'widget initialized' });
that._enabled = that.element.prop('disabled') ? false : that.options.enable;
that._layout();
that._ensureSurface();
that._dataSource();
that._drawPlaceholder();
kendo.notify(that);
},
/**
* Widget options
* @property options
*/
options: {
name: 'Selector',
id: null,
autoBind: true,
dataSource: null,
scaler: 'div.kj-stage',
container: 'div.kj-stage>div[data-' + kendo.ns + 'role="stage"]',
toolbar: '', // This points to a container div for including the toolbar
shape: 'circle',
color: '#FF0000',
frameStroke: { // strokeOptions
color: '#8a8a8a',
dashType: 'dot',
opacity: 0.6,
width: 2
},
shapeStroke: { // strokeOptions
color: '#FF0000',
dashType: 'dot',
opacity: 0.6,
width: 8
},
// in design mode: drawPlaceholder = true, createSurface = false, enable = false
// in play mode: drawPlaceholder = false, createSurface = true, enabled = true
// in review mode: drawPlaceholder = true, createSurface = true, enable = false
drawPlaceholder: true,
createSurface: true,
// showToolBar === enable
enable: true
},
/**
* Widget events
* @property events
*/
events: [
CHANGE
],
/**
* Value for MVVM binding
* - If there is no selection of the corresponding options.shapeStroke.color, value returns undefined
* - If there are more selections than the number of widgets of the same shape and color, value returns 0
* - If there is no selection of corresponding shape and color within the widget placeholder, value returns 0
* - If there is a selection of corresponding shape and color within the widget placeholder, value returns 1
* @param value
*/
value: function () {
var element = this.element;
var options = this.options;
var container = element.closest(options.container);
var scaler = container.closest(options.scaler);
var scale = scaler.length ? util.getTransformScale(scaler) : 1;
var boundingRect = element.get(0).getBoundingClientRect(); // boundingRect includes transformations, meaning it is scaled
var ownerDocument = $(container.get(0).ownerDocument);
var stageOffset = container.offset();
var elementRect = new geometry.Rect(
[(boundingRect.left - stageOffset.left + ownerDocument.scrollLeft()) / scale, (boundingRect.top - stageOffset.top + ownerDocument.scrollTop()) / scale],
[boundingRect.width / scale, boundingRect.height / scale] // getBoundingClientRect includes borders
);
var dataSource = this.dataSource;
var matchingSelections = dataSource.view().filter(function (selection) {
return selection.type === DATA_TYPE && // This one might not be useful considering dataSource should already be filtered
selection.data.shape === options.shape &&
kendo.parseColor(selection.data.color).equals(options.shapeStroke.color);
});
if ($.isArray(matchingSelections) && matchingSelections.length) {
var similarSelectorElements = container.find(kendo.roleSelector(ROLE)).filter(function (index, element) {
var selectorWidget = $(element).data('kendoSelector');
if (selectorWidget instanceof kendo.ui.Selector) {
return selectorWidget.options.shape === options.shape &&
selectorWidget.options.shapeStroke.color === options.shapeStroke.color;
}
return false;
});
// If we have more matching selections (same shape, same color) than similar widgets (same shape, same color)
// We cannot consider we have a match and the widget value is 0 (it would be too easy to multiply selections in hope of getting a match by mere luck)
if (matchingSelections.length > similarSelectorElements.length) {
return 0;
}
// If we have less matching selections than similar widgets, we are good to test
// all selections to check whether one fits within the current widget
var found = 0;
for (var i = 0, length = matchingSelections.length; i < length; i++) {
var selectionRect = new geometry.Rect(
[matchingSelections[i].data.origin.x, matchingSelections[i].data.origin.y],
[matchingSelections[i].data.size.width, matchingSelections[i].data.size.height]
);
if (
// Check that the selection rect fits within the element bounding box
selectionRect.origin.x >= elementRect.origin.x &&
selectionRect.origin.x <= elementRect.origin.x + elementRect.size.width &&
selectionRect.origin.y >= elementRect.origin.y &&
selectionRect.origin.y <= elementRect.origin.y + elementRect.size.height &&
// Also check the distance from center to center
new geometry.Point(selectionRect.origin.x + selectionRect.size.width / 2, selectionRect.origin.y + selectionRect.size.height / 2)
.distanceTo(new geometry.Point(elementRect.origin.x + elementRect.size.width / 2, elementRect.origin.y + elementRect.size.height / 2)) < MIN_DIAGONAL
) {
found++;
}
}
// Two or more selections within the widgets boundaries count as 1
return found ? 1 : 0;
}
},
/**
* Builds the widget layout
* @private
*/
_layout: function () {
var that = this;
var element = that.element;
that.wrapper = element;
// touch-action: 'none' is for Internet Explorer - https://github.com/jquery/jquery/issues/2987
// INTERACTIVE_CLASS (which might be shared with other widgets) is used to position any drawing surface underneath interactive widgets
element
.addClass(WIDGET_CLASS)
.addClass(INTERACTIVE_CLASS)
.css({ touchAction: 'none' });
that.surface = drawing.Surface.create(element);
},
/**
* Draw the selector placeholder according to options.shape
* @private
*/
_drawPlaceholder: function () {
assert.instanceof(Surface, this.surface, kendo.format(assert.messages.instanceof.default, 'this.surface', 'kendo.drawing.Surface'));
var that = this; // this is the selection widget
var options = that.options;
if (options.drawPlaceholder) {
var element = that.element;
var shape = options.shape;
var frameOptions = { stroke: options.frameStroke };
var shapeOptions = { stroke: options.shapeStroke };
var group = new drawing.Group();
var bbox = new geometry.Rect(
[
options.shapeStroke.width / 2,
options.shapeStroke.width / 2
],
[
// We cannot have a negative value here, esepcailly when element.width() === 0
// https://github.com/kidoju/Kidoju-Widgets/issues/160
Math.max(element.width(), options.shapeStroke.width) - options.shapeStroke.width,
Math.max(element.height(), options.shapeStroke.width) - options.shapeStroke.width
]
);
var outerRect = new drawing.Rect(bbox, frameOptions);
group.append(outerRect);
if (shape === SelectorSurface.fn.shapes.line) {
group.append(util.getHorizontalLineDrawing(bbox, shapeOptions));
} else if (shape === SelectorSurface.fn.shapes.circle) {
group.append(util.getCircleDrawing(bbox, shapeOptions));
} else {
group.append(util.getCrossDrawing(bbox, shapeOptions));
}
var center = new geometry.Point(bbox.origin.x + bbox.size.width / 2, bbox.origin.y + bbox.size.height / 2);
var centerShapeOptions = $.extend(true, {}, shapeOptions, { stroke: { dashType: 'solid', width: 2 } });
// Add vertical ligne
var verticalLine = new drawing.Path(centerShapeOptions)
.moveTo(center.x, center.y - MIN_DIAGONAL / 2)
.lineTo(center.x, center.y + MIN_DIAGONAL / 2);
group.append(verticalLine);
// Add horixontal line
var horizontalLine = new drawing.Path(centerShapeOptions)
.moveTo(center.x - MIN_DIAGONAL / 2, center.y)
.lineTo(center.x + MIN_DIAGONAL / 2, center.y);
group.append(horizontalLine);
// Add inner circle
// var innerCircleGeometry = new geometry.Circle(center, MIN_DIAGONAL / 2);
// var innerCircle = new drawing.Circle(innerCircleGeometry, centerShapeOptions);
// group.append(innerCircle);
that.surface.clear();
that.surface.draw(group);
}
},
/**
* Ensure drawing surface for all selections
* @private
*/
_ensureSurface: function () {
var that = this;
var options = that.options;
if (options.createSurface) {
var element = that.element;
var container = element.closest(options.container);
assert.hasLength(container, kendo.format(assert.messages.hasLength.default, options.container));
var surfaceElement = container.find(DOT + SURFACE_CLASS);
if (!surfaceElement.length) {
assert.isUndefined(that.selectorSurface, kendo.format(assert.messages.isUndefined.default, 'this.selectorSurface'));
var firstInteractiveElement = container.children().has(DOT + INTERACTIVE_CLASS).first();
surfaceElement = $(DIV)
.addClass(SURFACE_CLASS)
.css({ position: 'absolute', top: 0, left: 0 })
.height(container.height())
.width(container.width());
// Selections are not draggables so we have to consider that there might be no firstInteractiveElement
if (firstInteractiveElement.length) {
surfaceElement.insertBefore(firstInteractiveElement);
} else {
surfaceElement.appendTo(container);
}
surfaceElement.kendoSelectorSurface({
container: options.container,
dataSource: options.dataSource,
scaler: options.scaler,
toolbar: options.toolbar
});
}
var surfaceWidget = surfaceElement.data('kendoSelectorSurface');
assert.instanceof(SelectorSurface, surfaceWidget, kendo.format(assert.messages.instanceof.default, 'surfaceWidget', 'kendo.ui.SelectorSurface'));
surfaceWidget.registerSelector(that);
that.selectorSurface = surfaceWidget;
}
},
/**
* _dataSource function to bind the refresh handler to the change event
* @private
*/
_dataSource: function () {
var that = this;
// returns the datasource OR creates one if using array or configuration
that.dataSource = DataSource.create(that.options.dataSource);
// Note: without that.dataSource, source bindings won't work
// bind to the reset event to reset the dataSource
if (that._refreshHandler) {
that.dataSource.unbind(CHANGE, that._refreshHandler);
}
that._refreshHandler = $.proxy(that.refresh, that);
that.dataSource.bind(CHANGE, that._refreshHandler);
// trigger a read on the dataSource if one hasn't happened yet
if (that.options.autoBind) {
that.dataSource.fetch();
}
},
/**
* Sets the dataSource for source binding
* @param dataSource
*/
setDataSource: function (dataSource) {
var that = this;
// set the internal datasource equal to the one passed in by MVVM
that.options.dataSource = dataSource;
// rebuild the datasource if necessary, or just reassign
that._dataSource();
},
/**
* Refresh event handler for the dataSource
* @param e
*/
refresh: function (e) {
if (e && $.type(e.action) === UNDEFINED) {
// When resetting the dataSource, set the new dataSource on the selectorSurface widget
var surfaceWidget = this.selectorSurface;
if (surfaceWidget instanceof SelectorSurface && surfaceWidget.dataSource !== e.sender) {
surfaceWidget.setDataSource(e.sender);
logger.debug({
method: 'refresh',
message: 'reset the surfaceWidget dataSource (if infinite loop, make sure all selectors are bound to the same source)'
});
}
}
},
/**
* Enable/disable user interactivity on container
*/
enable: function (enabled) {
this._enabled = !!enabled;
var selectorSurface = this.selectorSurface;
if (selectorSurface instanceof SelectorSurface) {
selectorSurface._initMouseEvents();
}
},
/**
* Destroys the widget
* @method destroy
*/
destroy: function () {
var that = this;
var options = that.options;
// unbind dataSource
that.dataSource.unbind(CHANGE, that._refreshHandler);
// dereference selectors
if (that.selectorSurface instanceof SelectorSurface && $.isArray(that.selectorSurface.selectors)) {
// unregister this selector
if (that.selectorSurface.selectors.length > 0) {
var index = that.selectorSurface.selectors.indexOf(that);
that.selectorSurface.selectors.splice(index, 1);
}
// if all selectors are unregistered, destroy selector surface (which should destroy the toolbar)
if (that.selectorSurface.selectors.length === 0) {
that.selectorSurface.destroy();
that.selectorSurface.wrapper.remove();
}
that.selectorSurface = undefined;
}
// Destroy kendo
Widget.fn.destroy.call(that);
kendo.destroy(that.element);
}
});
kendo.ui.plugin(Selector);
}(window.jQuery));
/* jshint +W071 */
return window.kendo;
}, typeof define === 'function' && define.amd ? define : function (_, f) { 'use strict'; f(); });
| src/js/kidoju.widgets.selector.js | /**
* Copyright (c) 2013-2017 Memba Sarl. All rights reserved.
* Sources at https://github.com/Memba
*/
/* jshint browser: true, jquery: true */
/* globals define: false */
(function (f, define) {
'use strict';
define([
'./window.assert',
'./window.logger',
'./vendor/kendo/kendo.binder',
'./vendor/kendo/kendo.color',
'./vendor/kendo/kendo.drawing',
'./vendor/kendo/kendo.toolbar'
], f);
})(function () {
'use strict';
/* This function has too many statements. */
/* jshint -W071 */
(function ($, undefined) {
var kendo = window.kendo;
var data = kendo.data;
var drawing = kendo.drawing;
var geometry = kendo.geometry;
var Color = kendo.Color;
var DataSource = data.DataSource;
var Surface = drawing.Surface;
var Widget = kendo.ui.Widget;
var ToolBar = kendo.ui.ToolBar;
var assert = window.assert;
var logger = new window.Logger('kidoju.widgets.selection');
var NUMBER = 'number';
var STRING = 'string';
// var NULL = 'null';
var UNDEFINED = 'undefined';
var DOT = '.';
var HASH = '#';
var WIDGET = 'kendoSelector';
var NS = DOT + WIDGET;
var CHANGE = 'change';
var MOUSEDOWN = 'mousedown' + NS + ' ' + 'touchstart' + NS;
var MOUSEMOVE = 'mousemove' + NS + ' ' + 'touchmove' + NS;
var MOUSEUP = 'mouseup' + NS + ' ' + 'touchend' + NS;
var TOGGLE = 'toggle';
var DIV = '<div/>';
var ROLE = 'selector';
var ID = 'id';
var WIDGET_CLASS = 'kj-selector';
var SURFACE_CLASS = WIDGET_CLASS + '-surface';
var INTERACTIVE_CLASS = 'kj-interactive';
var DATA_TYPE = 'selection';
var MIN_DIAGONAL = 30;
var LINE_HW_PROPORTION = 0.2;
var SHAPE_HIT_DISTANCE = 10;
var CROSS_CURVE = 0.5;
/*********************************************************************************
* Helpers
*********************************************************************************/
var util = {
/**
* Build a random hex string of length characters
* @param length
* @returns {string}
*/
randomString: function (length) {
var s = new Array(length + 1).join('x');
return s.replace(/x/g, function (c) {
/* jshint -W016 */
return (Math.random() * 16|0).toString(16);
/* jshint +W016 */
});
},
/**
* Get the mouse (or touch) position
* @param e
* @param stage
* @returns {{x: *, y: *}}
*/
getMousePosition: function (e, stage) {
assert.instanceof($.Event, e, kendo.format(assert.messages.instanceof.default, 'e', 'jQuery.Event'));
assert.instanceof($, stage, kendo.format(assert.messages.instanceof.default, 'stage', 'jQuery'));
// See http://www.jacklmoore.com/notes/mouse-position/
// See http://www.jqwidgets.com/community/topic/dragend-event-properties-clientx-and-clienty-are-undefined-on-ios/
// See http://www.devinrolsen.com/basic-jquery-touchmove-event-setup/
// ATTENTION: e.originalEvent.changedTouches instanceof TouchList, not Array
var originalEvent = e.originalEvent;
var clientX = originalEvent && originalEvent.changedTouches ? originalEvent.changedTouches[0].clientX : e.clientX;
var clientY = originalEvent && originalEvent.changedTouches ? originalEvent.changedTouches[0].clientY : e.clientY;
// IMPORTANT: Position is relative to the stage and e.offsetX / e.offsetY do not work in Firefox
// var stage = $(e.target).closest('.kj-stage').find(kendo.roleSelector('stage'));
var ownerDocument = $(stage.get(0).ownerDocument);
var stageOffset = stage.offset();
var mouse = {
x: clientX - stageOffset.left + ownerDocument.scrollLeft(),
y: clientY - stageOffset.top + ownerDocument.scrollTop()
};
return mouse;
},
/**
* Get the position of the center of an element
* @param element
* @param stage
* @param scale
*/
getElementCenter: function (element, stage, scale) {
assert.instanceof($, element, kendo.format(assert.messages.instanceof.default, 'element', 'jQuery'));
assert.instanceof($, stage, kendo.format(assert.messages.instanceof.default, 'stage', 'jQuery'));
assert.type(NUMBER, scale, kendo.format(assert.messages.type.default, 'scale', NUMBER));
// We need getBoundingClientRect to especially account for rotation
var rect = element[0].getBoundingClientRect();
var ownerDocument = $(stage.get(0).ownerDocument);
var stageOffset = stage.offset();
return {
left: (rect.left - stageOffset.left + rect.width / 2 + ownerDocument.scrollLeft()) / scale,
top: (rect.top - stageOffset.top + rect.height / 2 + ownerDocument.scrollTop()) / scale
};
},
/**
* Get the scale of an element's CSS transformation
* Note: the same function is used in kidoju.widgets.stage
* @param element
* @returns {Number|number}
*/
getTransformScale: function (element) {
assert.instanceof($, element, kendo.format(assert.messages.instanceof.default, 'element', 'jQuery'));
// element.css('transform') returns a matrix, so we have to read the style attribute
var match = (element.attr('style') || '').match(/scale\([\s]*([0-9\.]+)[\s]*\)/);
return $.isArray(match) && match.length > 1 ? parseFloat(match[1]) || 1 : 1;
},
/* This function's cyclomatic complexity is too high. */
/* jshint -W074 */
/**
* Detect the shape of a path (circle, cross, line) among a list of shapes
* @param path
* @param shapes
*/
detectShape: function (path, shapes) {
assert.instanceof(drawing.Path, path, kendo.format(assert.messages.instanceof.default, 'path', 'kendo.drawing.Path'));
assert.isArray(shapes, kendo.format(assert.messages.isArray.default, 'shapes'));
assert.hasLength(shapes, kendo.format(assert.messages.hasLength.default, 'shapes'));
if (shapes.length === 1) {
return shapes[0];
}
var bbox = path.bbox();
var x = Math.floor(bbox.origin.x);
var y = Math.floor(bbox.origin.y);
var height = Math.floor(bbox.size.height);
var width = Math.floor(bbox.size.width);
// Detect a line (height / width ratio)
if (height / width < LINE_HW_PROPORTION && shapes.indexOf(SelectorSurface.fn.shapes.line) > -1) {
return SelectorSurface.fn.shapes.line;
}
if (shapes.indexOf(SelectorSurface.fn.shapes.circle) === -1 && shapes.indexOf(SelectorSurface.fn.shapes.cross) > -1) {
return SelectorSurface.fn.shapes.cross;
} else if (shapes.indexOf(SelectorSurface.fn.shapes.circle) > -1 && shapes.indexOf(SelectorSurface.fn.shapes.cross) === -1) {
return SelectorSurface.fn.shapes.circle;
} else if (shapes.indexOf(SelectorSurface.fn.shapes.circle) > -1 && shapes.indexOf(SelectorSurface.fn.shapes.cross) > -1) {
// Detect a circle (shape nears top, right, bottom and left)
var topPoint = new geometry.Point(x + width / 2, y);
var rightPoint = new geometry.Point(x + width, y + height / 2);
var bottomPoint = new geometry.Point(x + width / 2, y + height);
var leftPoint = new geometry.Point(x, y + height / 2);
var hitTop = false;
var hitRight = false;
var hitBottom = false;
var hitLeft = false;
for (var i = 0, length = path.segments.length; i < length; i++) {
var segment = path.segments[i];
if (!hitTop) {
hitTop = segment.anchor().distanceTo(topPoint) < SHAPE_HIT_DISTANCE;
}
if (!hitRight) {
hitRight = segment.anchor().distanceTo(rightPoint) < SHAPE_HIT_DISTANCE;
}
if (!hitBottom) {
hitBottom = segment.anchor().distanceTo(bottomPoint) < SHAPE_HIT_DISTANCE;
}
if (!hitLeft) {
hitLeft = segment.anchor().distanceTo(leftPoint) < SHAPE_HIT_DISTANCE;
}
if (hitTop && hitRight && hitBottom && hitLeft) {
break;
}
}
if (hitTop && hitRight && hitBottom && hitLeft) {
return SelectorSurface.fn.shapes.circle;
} else {
// Otherwise let's assume it is a cross
return SelectorSurface.fn.shapes.cross;
}
}
},
/* jshint +W074 */
/**
* Get a selection data item for dataSource from a user-drawn path
* @param path
* @param color
* @param shapes
*/
getDataItem: function (path, color, shapes) {
assert.instanceof(drawing.Path, path, kendo.format(assert.messages.instanceof.default, 'path', 'kendo.drawing.Path'));
assert.type(STRING, color, kendo.format(assert.messages.type.default, 'color', STRING));
assert.isArray(shapes, kendo.format(assert.messages.isArray.default, 'shapes'));
assert.hasLength(shapes, kendo.format(assert.messages.hasLength.default, 'shapes'));
var bbox = path.bbox();
var height = Math.floor(bbox.size.height);
var width = Math.floor(bbox.size.width);
// If the user-drawn path is too small, discard
if (Math.sqrt(Math.pow(height, 2) + Math.pow(width, 2)) > MIN_DIAGONAL) {
return {
type: DATA_TYPE,
data: {
color: color,
origin: { x: Math.floor(bbox.origin.x), y: Math.floor(bbox.origin.y) },
shape: util.detectShape(path, shapes),
size: { height: height, width: width }
}
};
}
},
/**
* Get an horizontal line path within rect
* @param rect
* @param options
*/
getHorizontalLineDrawing: function (rect, options) {
assert.instanceof(geometry.Rect, rect, kendo.format(assert.messages.instanceof.default, 'rect', 'kendo.geometry.Rect'));
var path = new drawing.Path(options);
path.moveTo(rect.origin.x, rect.origin.y + rect.size.height / 2);
path.lineTo(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height / 2);
return path;
},
/**
* Get the arc of an ellipsis within rect
* @param rect
* @param options
*/
getCircleDrawing: function (rect, options) {
assert.instanceof(geometry.Rect, rect, kendo.format(assert.messages.instanceof.default, 'rect', 'kendo.geometry.Rect'));
var arcGeometry = new geometry.Arc(
[rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height / 2], // center
{
radiusX: rect.size.width / 2,
radiusY: rect.size.height / 2,
startAngle: 0,
endAngle: 360,
anticlockwise: false
}
);
return new drawing.Arc(arcGeometry, options);
},
/**
* Get a cross path within rect
* @param rect
* @param options
*/
getCrossDrawing: function (rect, options) {
assert.instanceof(geometry.Rect, rect, kendo.format(assert.messages.instanceof.default, 'rect', 'kendo.geometry.Rect'));
var path = new drawing.Path(options);
var x = rect.origin.x;
var y = rect.origin.y;
var height = rect.size.height;
var width = rect.size.width;
path.moveTo(x + width, y);
path.lineTo(x + CROSS_CURVE * width, y + (1 - CROSS_CURVE) * height);
path.curveTo(
[x, y + height],
[x, y + height],
[x, y + (1 - CROSS_CURVE) * height]
);
path.lineTo(x, y + CROSS_CURVE * height);
path.curveTo(
[x, y],
[x, y],
[x + CROSS_CURVE * width, y + CROSS_CURVE * height]
);
path.lineTo(x + width, y + height);
return path;
},
/**
* Draw a shape from a dataSource dataItem
* @param dataItem
* @param strokeOptions
*/
getSelectionDrawing: function (dataItem, strokeOptions) {
assert.instanceof(kendo.data.ObservableObject, dataItem, kendo.format(assert.messages.instanceof.default, 'dataItem', 'kendo.data.ObservableObject'));
var shape = dataItem.data.shape;
var rect = new geometry.Rect([dataItem.data.origin.x, dataItem.data.origin.y], [dataItem.data.size.width, dataItem.data.size.height]);
var options = { stroke: $.extend(strokeOptions, { color: dataItem.data.color }) };
if (shape === SelectorSurface.fn.shapes.line) {
return util.getHorizontalLineDrawing(rect, options);
} else if (shape === SelectorSurface.fn.shapes.circle) {
return util.getCircleDrawing(rect, options);
} else {
return util.getCrossDrawing(rect, options);
}
}
};
/*********************************************************************************
* SelectorToolBar Widget
*********************************************************************************/
var SelectorToolBar = ToolBar.extend({
/**
* Initializes the widget
* @param element
* @param options
*/
init: function (element, options) {
var that = this;
options = options || {};
ToolBar.fn.init.call(that, element, options);
logger.debug({ method: 'init', message: 'toolbar initialized' });
that.bind(TOGGLE, that._onToggle);
kendo.notify(that);
},
/**
* Widget options
*/
options: {
name: 'SelectorToolBar',
iconSize: 16,
resizable: false
},
/**
* Add a color to the toolbar
* @param color
*/
addColor: function (color) {
var that = this;
// k-button-group in kendo.ui & km-buttongroup (wo second -) in kendo.mobile.ui
var buttonGroup = this.element.children('.k-button-group, .km-buttongroup');
var toolBarColors = buttonGroup.children('.k-toggle-button').map(function () {
return HASH + $(this).attr('id');
});
var buttons = [];
// Rebuild previous buttons;
for (var i = 0, length = toolBarColors.length; i < length; i++) {
buttons.push({
type: 'button',
group: 'selectorColors',
id: toolBarColors[i].substr(1), // removes the hashtag
imageUrl: that._createImageUrl(toolBarColors[i]),
showText: 'overflow',
text: toolBarColors[i],
togglable: true
});
}
// Parse color for what is actually a color
color = kendo.parseColor(color).toCss(); // might raise an exception
// Do not add a color that already exists
var found = buttons.find(function (button) {
return button.text === color;
});
// Create button
if ($.type(found) === UNDEFINED) {
buttons.push({
type: 'button',
group: 'selectorColors',
id: color.substr(1), // removes the hashtag
imageUrl: that._createImageUrl(color),
showText: 'overflow',
text: color,
togglable: true
});
}
if (buttonGroup.length) {
that.remove(buttonGroup);
}
that.add({ type: 'buttonGroup', buttons: buttons });
if (buttons.length) {
that.toggle(HASH + buttons[0].id, true);
that._onToggle({ id: buttons[0].id });
}
that.wrapper.toggle(buttons.length > 1);
},
/**
* Create toolbar icon
* @param: color
* @private
*/
_createImageUrl: function (color) {
var canvas = document.createElement('canvas');
canvas.height = this.options.iconSize;
canvas.width = this.options.iconSize;
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(
this.options.iconSize / 2, // center.x
this.options.iconSize / 2, // center.y
this.options.iconSize / 2, // radius
0, // start angle
2 * Math.PI // end angle
);
ctx.strokeStyle = 'black';
ctx.fillStyle = color;
ctx.stroke();
ctx.fill();
return canvas.toDataURL();
},
/**
* Register corresponding selector surface, the surface the selected color applies to
*/
registerSelectorSurface: function (selectorSurface) {
assert.instanceof(SelectorSurface, selectorSurface, kendo.format(assert.messages.instanceof.default, 'selectorSurface', 'kendo.ui.SelectorSurface'));
this.selectorSurface = selectorSurface;
},
/**
* Button toggle event handler
* @private
*/
_onToggle: function (e) {
assert.isPlainObject(e, kendo.format(assert.messages.isPlainObject.default, 'e'));
assert.instanceof(SelectorSurface, this.selectorSurface, kendo.format(assert.messages.instanceof.default, 'this.selectorSurface', 'kendo.ui.SelectorSurface'));
this.selectorSurface.color(HASH + e.id);
},
/**
* Destroy widget
*/
destroy: function () {
var that = this;
var element = that.element;
ToolBar.fn.destroy.call(that);
kendo.destroy(element);
}
});
kendo.ui.plugin(SelectorToolBar);
/*********************************************************************************
* SelectorSurface Widget
*********************************************************************************/
var SelectorSurface = Widget.extend({
/**
* Initializes the widget
* @param element
* @param options
*/
init: function (element, options) {
var that = this;
options = options || {};
Widget.fn.init.call(that, element, options);
logger.debug('surface initialized');
that._layout();
that._createToolBar();
that._dataSource();
kendo.notify(that);
},
/**
* Options
*/
options: {
name: 'SelectorSurface',
container: 'div.kj-stage>div[data-' + kendo.ns + 'role="stage"]', // TODO: container might not be necessary??? - replace with that.element / https://github.com/kidoju/Kidoju-Widgets/issues/167
scaler: 'div.kj-stage',
penStroke: {
width: 8
},
toolbar: '#toolbar'
},
/**
* Enumeration of possible shapes
*/
shapes: {
circle: 'circle',
cross: 'cross',
line: 'line'
},
/**
* Layout
* @private
*/
_layout: function () {
var that = this;
var element = that.element;
that.wrapper = element;
element
.addClass(SURFACE_CLASS);
that.surface = drawing.Surface.create(element);
},
/**
* Create toolbar
* @private
*/
_createToolBar: function () {
var that = this;
var toolbarContainer = $(that.options.toolbar);
if (toolbarContainer.length) {
var toolbarElement = $(DIV).appendTo(toolbarContainer);
that.toolbar = toolbarElement.kendoSelectorToolBar().data('kendoSelectorToolBar');
that.toolbar.registerSelectorSurface(this);
}
},
/**
* Register a selector
* @param selector
* @private
*/
registerSelector: function (selector) {
var that = this;
var options = that.options;
assert.instanceof(Selector, selector, kendo.format(assert.messages.instanceof.default, 'selector', 'Selector'));
assert.equal(options.container, selector.options.container, kendo.format(assert.messages.equal.default, 'selector.options.container', 'this.options.container'));
assert.equal(options.scaler, selector.options.scaler, kendo.format(assert.messages.equal.default, 'selector.options.scaler', 'this.options.scaler'));
// assert.equal(options.dataSource, selector.options.dataSource, kendo.format(assert.messages.equal.default, 'selector.options.dataSource', 'this.options.dataSource'));
if (!$.isArray(that.selectors)) {
that.selectors = [];
}
if (that.selectors.indexOf(selector) === -1) {
that.selectors.push(selector);
// Set the prefix for dataSource ids (so as to only draw selections for the current page when played)
var selectorId = selector.element.attr(kendo.attr(ID)) || '';
if ($.type(that._selectorId) === UNDEFINED) {
that._selectorId = selectorId;
} else if (that._selectorId > selectorId) {
that._selectorId = selectorId;
}
// Add enabled selector color to toolbar
if (that.toolbar instanceof SelectorToolBar && selector._enabled) {
that.toolbar.addColor(selector.options.shapeStroke.color);
}
// Reset mouse handlers
that._initMouseEvents();
}
},
/**
* Gets/Sets color
* @private
*/
color: function (color) {
if ($.type(color) === UNDEFINED) {
return this._color;
} else {
this._color = kendo.parseColor(color).toCss(); // This might raise an exception
}
},
/**
* Init mouse event handlers to draw on surface
* @private
*/
_initMouseEvents: function () {
// IMPORTANT
// We can have several widgets for selections on a page
// But we only have one set of event handlers shared across all selections
// So we cannot use `this` within handlers, which is specific to this selector surface
var options = this.options;
var data = {}; // We need an object so that data is passed by reference between handlers
// ATTENTION! There might be several options.container on the page as in Kidoju-Mobile
// So we need to make sure we unbind/bind events to the parent container
// https://github.com/kidoju/Kidoju-Widgets/issues/162
var container = this.element.closest(options.container);
var containers = $(document).find(options.container);
container = options.container + ':eq(' + containers.index(container) + ')';
$(document)
.off(NS, container);
if (this.enable()) {
$(document)
.on(MOUSEDOWN, container, data, this._onMouseDown)
.on(MOUSEMOVE, container, data, this._onMouseMove)
.on(MOUSEUP, container, data, this._onMouseUp);
}
},
/**
* Mouse down event handler
* @param e
* @private
*/
_onMouseDown: function (e) {
assert.instanceof($.Event, e, kendo.format(assert.messages.instanceof.default, 'e', 'jQuery.Event'));
e.preventDefault(); // prevents from selecting the div
var container = $(e.currentTarget);
// Although `this` is unavailable, surfaceElement and surfaceWidget give us the drawing surface and dataSource
var surfaceElement = container.find(DOT + SURFACE_CLASS);
assert.hasLength(surfaceElement, kendo.format(assert.messages.hasLength.default, surfaceElement));
var surfaceWidget = surfaceElement.data('kendoSelectorSurface');
assert.instanceof(SelectorSurface, surfaceWidget, kendo.format(assert.messages.instanceof.default, 'surfaceWidget', 'kendo.ui.SelectorSurface'));
var scaler = container.closest(surfaceWidget.options.scaler);
var scale = scaler.length ? util.getTransformScale(scaler) : 1;
var mouse = util.getMousePosition(e, container);
var mousePoint = new geometry.Point(mouse.x / scale, mouse.y / scale);
var surface = surfaceWidget.surface;
assert.instanceof(Surface, surface, kendo.format(assert.messages.instanceof.default, 'surface', 'kendo.drawing.Surface'));
var dataSource = surfaceWidget.dataSource;
assert.instanceof(DataSource, dataSource, kendo.format(assert.messages.instanceof.default, 'dataSource', 'kendo.data.DataSource'));
var dataItems2Delete = dataSource.view().filter(function (dataItem) {
var selectionBox = dataItem.data;
return (mousePoint.x >= selectionBox.origin.x &&
mousePoint.x <= selectionBox.origin.x + selectionBox.size.width &&
mousePoint.y >= selectionBox.origin.y &&
mousePoint.y <= selectionBox.origin.y + selectionBox.size.height);
});
if ($.isArray(dataItems2Delete) && dataItems2Delete.length) {
dataItems2Delete.forEach(function (dataItem) {
dataSource.remove(dataItem);
});
} else {
var strokeOptions = $.extend({}, surfaceWidget.options.penStroke, { color: surfaceWidget.color() });
var path = new drawing.Path({ stroke: strokeOptions });
path.moveTo(mousePoint);
surface.draw(path);
e.data.path = path;
logger.debug({
method: '_onMouseDown',
message: 'Added new path',
data: strokeOptions
});
}
},
/**
* Mouse move event handler
* @param e
* @private
*/
_onMouseMove: function (e) {
assert.instanceof($.Event, e, kendo.format(assert.messages.instanceof.default, 'e', 'jQuery.Event'));
var path = e.data.path;
if (path instanceof kendo.drawing.Path) {
var container = $(e.currentTarget);
// Although `this` is unavailable, surfaceElement and surfaceWidget give us the drawing surface and dataSource
var surfaceElement = container.find(DOT + SURFACE_CLASS);
assert.hasLength(surfaceElement, kendo.format(assert.messages.hasLength.default, surfaceElement));
var surfaceWidget = surfaceElement.data('kendoSelectorSurface');
assert.instanceof(SelectorSurface, surfaceWidget, kendo.format(assert.messages.instanceof.default, 'surfaceWidget', 'kendo.ui.SelectorSurface'));
var scaler = container.closest(surfaceWidget.options.scaler);
var scale = scaler.length ? util.getTransformScale(scaler) : 1;
var mouse = util.getMousePosition(e, container);
path.lineTo(mouse.x / scale, mouse.y / scale);
}
},
/**
* Mouse up event handler
* @param e
* @private
*/
_onMouseUp: function (e) {
assert.instanceof($.Event, e, kendo.format(assert.messages.instanceof.default, 'e', 'jQuery.Event'));
var path = e.data.path;
if (path instanceof drawing.Path) {
var container = $(e.currentTarget);
// Although `this` is unavailable, surfaceElement and surfaceWidget give us the drawing surface and dataSouce
var surfaceElement = container.find(DOT + SURFACE_CLASS);
assert.hasLength(surfaceElement, kendo.format(assert.messages.hasLength.default, surfaceElement));
var surfaceWidget = surfaceElement.data('kendoSelectorSurface');
assert.instanceof(SelectorSurface, surfaceWidget, kendo.format(assert.messages.instanceof.default, 'surfaceWidget', 'kendo.ui.SelectorSurface'));
var dataSource = surfaceWidget.dataSource;
if (dataSource instanceof kendo.data.DataSource) {
var dataItem = util.getDataItem(path, surfaceWidget.color(), surfaceWidget.getSelectorShapes());
if ($.isPlainObject(dataItem)) {
// Add random Object Id
dataItem.id = util.randomString(24);
// Designate a selector to identify the page
dataItem.data.selector = surfaceWidget._selectorId;
dataSource.add(dataItem);
} else {
// Refresh (to remove the failed attempt at drawing a selection)
dataSource.trigger(CHANGE);
}
}
}
e.data.path = undefined;
},
/**
* _dataSource function to bind the refresh handler to the change event
* @private
*/
_dataSource: function () {
var that = this;
// returns the datasource OR creates one if using array or configuration
that.dataSource = DataSource.create(that.options.dataSource);
// bind to the change event to refresh the widget
if (that._refreshHandler) {
that.dataSource.unbind(CHANGE, that._refreshHandler);
}
that._refreshHandler = $.proxy(that.refresh, that);
that.dataSource.bind(CHANGE, that._refreshHandler);
// Filter dataSource
that.dataSource.filter({ field: 'type', operator: 'eq', value: DATA_TYPE });
// trigger a read on the dataSource if one hasn't happened yet
if (that.options.autoBind) {
that.dataSource.fetch();
}
var selectors = that.selectors;
if ($.isArray(selectors)) {
for (var i = 0, length = selectors.length; i < length; i++) {
if (selectors[i].dataSource !== that.dataSource) {
selectors[i].setDataSource(that.dataSource);
}
}
}
},
/**
* Sets the dataSource for source binding
* @param dataSource
*/
setDataSource: function (dataSource) {
var that = this;
// set the internal datasource equal to the one passed in by MVVM
that.options.dataSource = dataSource;
// rebuild the datasource if necessary, or just reassign
that._dataSource();
},
/**
* Refresh handler to redraw all selections from dataSource
*/
refresh: function () {
var that = this;
var options = that.options;
var dataSource = that.dataSource;
var surface = that.surface;
var selectors = that.selectors;
assert.instanceof(DataSource, dataSource, kendo.format(assert.messages.instanceof.default, 'this.dataSource', 'kendo.data.DataSource'));
assert.instanceof(Surface, surface, kendo.format(assert.messages.instanceof.default, 'this.surface', 'kendo.data.Surface'));
var dataView = dataSource.view(); // This is filtered
if (surface instanceof kendo.drawing.Surface) {
// Clear surface
surface.clear();
// Draw
for (var i = 0, total = dataView.length; i < total; i++) {
var dataItem = dataView[i];
// Draw the item only if it relates to the prefix
if (dataItem.type === DATA_TYPE && dataItem.data.selector === that._selectorId) {
surface.draw(util.getSelectionDrawing(dataItem, $.extend({}, options.penStroke)));
}
}
}
// Trigger a change on all selector widgets to recalculate databound values
if ($.isArray(selectors)) {
for (var j = 0, length = selectors.length; j < length; j++) {
var selector = selectors[j];
assert.instanceof(Selector, selector, kendo.format(assert.messages.instanceof.default, 'selector', 'kendo.ui.Selector'));
try {
// We might get `Uncaught TypeError: Cannot read property 'value' of undefined`
// because a refresh is triggered before test is added to the viewModel in play mode
selector.trigger(CHANGE);
} catch (ex) {}
}
}
},
/**
* Scan registered selectors for all shapes
*/
getSelectorShapes: function () {
var selectors = this.selectors;
var shapes = [];
if ($.isArray(selectors)) {
for (var i = 0, length = selectors.length; i < length; i++) {
var shape = selectors[i].options.shape;
if (shapes.indexOf(shape) === -1) {
shapes.push(shape); // test a dummy shape
}
}
}
return shapes;
},
/**
* Scan registered selectors for all colors
*/
getSelectorColors: function () {
var selectors = this.selectors;
var colors = [];
if ($.isArray(colors)) {
for (var i = 0, length = selectors.length; i < length; i++) {
var color = selectors[i].options.color;
if (colors.indexOf(color) === -1) {
colors.push(color);
}
}
}
return colors;
},
/**
* Return true if any selector is enabled, false if all selectors are disabled
*/
enable: function () {
var selectors = this.selectors;
var enabled = false;
if ($.isArray(selectors)) {
for (var i = 0, length = selectors.length; i < length; i++) {
enabled = enabled || selectors[i]._enabled;
}
}
return enabled;
},
/**
* Destroy the widget
* @method destroy
*/
destroy: function () {
var that = this;
var element = that.element;
// unbind document events
that._initMouseEvents();
// unbind dataSource
if ($.isFunction(that._refreshHandler)) {
that.dataSource.unbind(CHANGE, that._refreshHandler);
}
// destroy toolbar
if (that.toolbar instanceof SelectorToolBar) {
that.toolbar.destroy();
that.toolbar.wrapper.remove();
that.toolbar = undefined;
}
// Release references
that.surface = undefined;
that.selectors = undefined;
// Destroy kendo
Widget.fn.destroy.call(that);
kendo.destroy(element);
// Remove widget class
element.removeClass(WIDGET_CLASS);
}
});
kendo.ui.plugin(SelectorSurface);
/*********************************************************************************
* Selector Widget
*********************************************************************************/
/**
* Selector
* @class Selector Widget (kendoSelector)
*/
var Selector = Widget.extend({
/**
* Initializes the widget
* @param element
* @param options
*/
init: function (element, options) {
var that = this;
options = options || {};
Widget.fn.init.call(that, element, options);
logger.debug({ method: 'init', message: 'widget initialized' });
that._enabled = that.element.prop('disabled') ? false : that.options.enable;
that._layout();
that._ensureSurface();
that._dataSource();
that._drawPlaceholder();
kendo.notify(that);
},
/**
* Widget options
* @property options
*/
options: {
name: 'Selector',
id: null,
autoBind: true,
dataSource: null,
scaler: 'div.kj-stage',
container: 'div.kj-stage>div[data-' + kendo.ns + 'role="stage"]',
toolbar: '', // This points to a container div for including the toolbar
shape: 'circle',
color: '#FF0000',
frameStroke: { // strokeOptions
color: '#8a8a8a',
dashType: 'dot',
opacity: 0.6,
width: 2
},
shapeStroke: { // strokeOptions
color: '#FF0000',
dashType: 'dot',
opacity: 0.6,
width: 8
},
// in design mode: drawPlaceholder = true, createSurface = false, enable = false
// in play mode: drawPlaceholder = false, createSurface = true, enabled = true
// in review mode: drawPlaceholder = true, createSurface = true, enable = false
drawPlaceholder: true,
createSurface: true,
// showToolBar === enable
enable: true
},
/**
* Widget events
* @property events
*/
events: [
CHANGE
],
/**
* Value for MVVM binding
* - If there is no selection of the corresponding options.shapeStroke.color, value returns undefined
* - If there are more selections than the number of widgets of the same shape and color, value returns 0
* - If there is no selection of corresponding shape and color within the widget placeholder, value returns 0
* - If there is a selection of corresponding shape and color within the widget placeholder, value returns 1
* @param value
*/
value: function () {
var element = this.element;
var options = this.options;
var container = element.closest(options.container);
var scaler = container.closest(options.scaler);
var scale = scaler.length ? util.getTransformScale(scaler) : 1;
var boundingRect = element.get(0).getBoundingClientRect(); // boundingRect includes transformations, meaning it is scaled
var ownerDocument = $(container.get(0).ownerDocument);
var stageOffset = container.offset();
var elementRect = new geometry.Rect(
[(boundingRect.left - stageOffset.left + ownerDocument.scrollLeft()) / scale, (boundingRect.top - stageOffset.top + ownerDocument.scrollTop()) / scale],
[boundingRect.width / scale, boundingRect.height / scale] // getBoundingClientRect includes borders
);
var dataSource = this.dataSource;
var matchingSelections = dataSource.view().filter(function (selection) {
return selection.type === DATA_TYPE && // This one might not be useful considering dataSource should already be filtered
selection.data.shape === options.shape &&
kendo.parseColor(selection.data.color).equals(options.shapeStroke.color);
});
if ($.isArray(matchingSelections) && matchingSelections.length) {
var similarSelectorElements = container.find(kendo.roleSelector(ROLE)).filter(function (index, element) {
var selectorWidget = $(element).data('kendoSelector');
if (selectorWidget instanceof kendo.ui.Selector) {
return selectorWidget.options.shape === options.shape &&
selectorWidget.options.shapeStroke.color === options.shapeStroke.color;
}
return false;
});
// If we have more matching selections (same shape, same color) than similar widgets (same shape, same color)
// We cannot consider we have a match and the widget value is 0 (it would be too easy to multiply selections in hope of getting a match by mere luck)
if (matchingSelections.length > similarSelectorElements.length) {
return 0;
}
// If we have less matching selections than similar widgets, we are good to test
// all selections to check whether one fits within the current widget
var found = 0;
for (var i = 0, length = matchingSelections.length; i < length; i++) {
var selectionRect = new geometry.Rect(
[matchingSelections[i].data.origin.x, matchingSelections[i].data.origin.y],
[matchingSelections[i].data.size.width, matchingSelections[i].data.size.height]
);
if (
// Check that the selection rect fits within the element bounding box
selectionRect.origin.x >= elementRect.origin.x &&
selectionRect.origin.x <= elementRect.origin.x + elementRect.size.width &&
selectionRect.origin.y >= elementRect.origin.y &&
selectionRect.origin.y <= elementRect.origin.y + elementRect.size.height &&
// Also check the distance from center to center
new geometry.Point(selectionRect.origin.x + selectionRect.size.width / 2, selectionRect.origin.y + selectionRect.size.height / 2)
.distanceTo(new geometry.Point(elementRect.origin.x + elementRect.size.width / 2, elementRect.origin.y + elementRect.size.height / 2)) < MIN_DIAGONAL
) {
found++;
}
}
// Two or more selections within the widgets boundaries count as 1
return found ? 1 : 0;
}
},
/**
* Builds the widget layout
* @private
*/
_layout: function () {
var that = this;
var element = that.element;
that.wrapper = element;
// touch-action: 'none' is for Internet Explorer - https://github.com/jquery/jquery/issues/2987
// INTERACTIVE_CLASS (which might be shared with other widgets) is used to position any drawing surface underneath interactive widgets
element
.addClass(WIDGET_CLASS)
.addClass(INTERACTIVE_CLASS)
.css({ touchAction: 'none' });
that.surface = drawing.Surface.create(element);
},
/**
* Draw the selector placeholder according to options.shape
* @private
*/
_drawPlaceholder: function () {
assert.instanceof(Surface, this.surface, kendo.format(assert.messages.instanceof.default, 'this.surface', 'kendo.drawing.Surface'));
var that = this; // this is the selection widget
var options = that.options;
if (options.drawPlaceholder) {
var element = that.element;
var shape = options.shape;
var frameOptions = { stroke: options.frameStroke };
var shapeOptions = { stroke: options.shapeStroke };
var group = new drawing.Group();
var bbox = new geometry.Rect(
[
options.shapeStroke.width / 2,
options.shapeStroke.width / 2
],
[
// We cannot have a negative value here, esepcailly when element.width() === 0
// https://github.com/kidoju/Kidoju-Widgets/issues/160
Math.max(element.width(), options.shapeStroke.width) - options.shapeStroke.width,
Math.max(element.height(), options.shapeStroke.width) - options.shapeStroke.width
]
);
var outerRect = new drawing.Rect(bbox, frameOptions);
group.append(outerRect);
if (shape === SelectorSurface.fn.shapes.line) {
group.append(util.getHorizontalLineDrawing(bbox, shapeOptions));
} else if (shape === SelectorSurface.fn.shapes.circle) {
group.append(util.getCircleDrawing(bbox, shapeOptions));
} else {
group.append(util.getCrossDrawing(bbox, shapeOptions));
}
var center = new geometry.Point(bbox.origin.x + bbox.size.width / 2, bbox.origin.y + bbox.size.height / 2);
var centerShapeOptions = $.extend(true, {}, shapeOptions, { stroke: { dashType: 'solid', width: 2 } });
// Add vertical ligne
var verticalLine = new drawing.Path(centerShapeOptions)
.moveTo(center.x, center.y - MIN_DIAGONAL / 2)
.lineTo(center.x, center.y + MIN_DIAGONAL / 2);
group.append(verticalLine);
// Add horixontal line
var horizontalLine = new drawing.Path(centerShapeOptions)
.moveTo(center.x - MIN_DIAGONAL / 2, center.y)
.lineTo(center.x + MIN_DIAGONAL / 2, center.y);
group.append(horizontalLine);
// Add inner circle
// var innerCircleGeometry = new geometry.Circle(center, MIN_DIAGONAL / 2);
// var innerCircle = new drawing.Circle(innerCircleGeometry, centerShapeOptions);
// group.append(innerCircle);
that.surface.clear();
that.surface.draw(group);
}
},
/**
* Ensure drawing surface for all selections
* @private
*/
_ensureSurface: function () {
var that = this;
var options = that.options;
if (options.createSurface) {
var element = that.element;
var container = element.closest(options.container);
assert.hasLength(container, kendo.format(assert.messages.hasLength.default, options.container));
var surfaceElement = container.find(DOT + SURFACE_CLASS);
if (!surfaceElement.length) {
assert.isUndefined(that.selectorSurface, kendo.format(assert.messages.isUndefined.default, 'this.selectorSurface'));
var firstInteractiveElement = container.children().has(DOT + INTERACTIVE_CLASS).first();
surfaceElement = $(DIV)
.addClass(SURFACE_CLASS)
.css({ position: 'absolute', top: 0, left: 0 })
.height(container.height())
.width(container.width());
// Selections are not draggables so we have to consider that there might be no firstInteractiveElement
if (firstInteractiveElement.length) {
surfaceElement.insertBefore(firstInteractiveElement);
} else {
surfaceElement.appendTo(container);
}
surfaceElement.kendoSelectorSurface({
container: options.container,
dataSource: options.dataSource,
scaler: options.scaler,
toolbar: options.toolbar
});
}
var surfaceWidget = surfaceElement.data('kendoSelectorSurface');
assert.instanceof(SelectorSurface, surfaceWidget, kendo.format(assert.messages.instanceof.default, 'surfaceWidget', 'kendo.ui.SelectorSurface'));
surfaceWidget.registerSelector(that);
that.selectorSurface = surfaceWidget;
}
},
/**
* _dataSource function to bind the refresh handler to the change event
* @private
*/
_dataSource: function () {
var that = this;
// returns the datasource OR creates one if using array or configuration
that.dataSource = DataSource.create(that.options.dataSource);
// Note: without that.dataSource, source bindings won't work
// bind to the reset event to reset the dataSource
if (that._refreshHandler) {
that.dataSource.unbind(CHANGE, that._refreshHandler);
}
that._refreshHandler = $.proxy(that.refresh, that);
that.dataSource.bind(CHANGE, that._refreshHandler);
// trigger a read on the dataSource if one hasn't happened yet
if (that.options.autoBind) {
that.dataSource.fetch();
}
},
/**
* Sets the dataSource for source binding
* @param dataSource
*/
setDataSource: function (dataSource) {
var that = this;
// set the internal datasource equal to the one passed in by MVVM
that.options.dataSource = dataSource;
// rebuild the datasource if necessary, or just reassign
that._dataSource();
},
/**
* Refresh event handler for the dataSource
* @param e
*/
refresh: function (e) {
if (e && $.type(e.action) === UNDEFINED) {
// When resetting the dataSource, set the new dataSource on the selectorSurface widget
var surfaceWidget = this.selectorSurface;
if (surfaceWidget instanceof SelectorSurface && surfaceWidget.dataSource !== e.sender) {
surfaceWidget.setDataSource(e.sender);
logger.debug({
method: 'refresh',
message: 'reset the surfaceWidget dataSource (if infinite loop, make sure all selectors are bound to the same source)'
});
}
}
},
/**
* Enable/disable user interactivity on container
*/
enable: function (enabled) {
this._enabled = !!enabled;
var selectorSurface = this.selectorSurface;
if (selectorSurface instanceof SelectorSurface) {
selectorSurface._initMouseEvents();
}
},
/**
* Destroys the widget
* @method destroy
*/
destroy: function () {
var that = this;
var options = that.options;
// unbind dataSource
that.dataSource.unbind(CHANGE, that._refreshHandler);
// dereference selectors
if (that.selectorSurface instanceof SelectorSurface && $.isArray(that.selectorSurface.selectors)) {
// unregister this selector
if (that.selectorSurface.selectors.length > 0) {
var index = that.selectorSurface.selectors.indexOf(that);
that.selectorSurface.selectors.splice(index, 1);
}
// if all selectors are unregistered, destroy selector surface (which should destroy the toolbar)
if (that.selectorSurface.selectors.length === 0) {
that.selectorSurface.destroy();
that.selectorSurface.wrapper.remove();
}
that.selectorSurface = undefined;
}
// Destroy kendo
Widget.fn.destroy.call(that);
kendo.destroy(that.element);
}
});
kendo.ui.plugin(Selector);
}(window.jQuery));
/* jshint +W071 */
return window.kendo;
}, typeof define === 'function' && define.amd ? define : function (_, f) { 'use strict'; f(); });
| Prevent drawing a selection when interacting with a kj-interactive element
| src/js/kidoju.widgets.selector.js | Prevent drawing a selection when interacting with a kj-interactive element | <ide><path>rc/js/kidoju.widgets.selector.js
<ide> _onMouseDown: function (e) {
<ide> assert.instanceof($.Event, e, kendo.format(assert.messages.instanceof.default, 'e', 'jQuery.Event'));
<ide> e.preventDefault(); // prevents from selecting the div
<add> if ($(e.target).hasClass(INTERACTIVE_CLASS)) {
<add> return;
<add> }
<ide> var container = $(e.currentTarget);
<ide> // Although `this` is unavailable, surfaceElement and surfaceWidget give us the drawing surface and dataSource
<ide> var surfaceElement = container.find(DOT + SURFACE_CLASS); |
|
JavaScript | mit | 696a46232bbc4747970008516a495d9764fa378d | 0 | SporkList/sporklist.github.io,SporkList/sporklist.github.io | var parseUser = null;
var position = null;
var service = null;
var autocomplete = null;
var searchResults = null;
var count = 0;
/* In the case of no location name, we use the user's current location */
function retrieveSearchResults() {
var loc;
var place = autocomplete.getPlace();
if(place == undefined || $("#location-bar").val().replace(" ", "") == "")
loc = new google.maps.LatLng(position.latitude, position.longitude);
else
loc = new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng());
var request = {
location: loc,
radius: '8000',
types: ['restaurant', 'meal_delivery', 'meal_takeaway', 'cafe'],
key: 'AIzaSyCnk5Oo0joyYzlR4BVBZsDR2aUteESG0MY',
keyword: $("#search-bar").val()
};
service.nearbySearch(request, displaySearchResults);
}
/* Callback that FINALLY has our search results */
function displaySearchResults(results, status) {
if(status != google.maps.places.PlacesServiceStatus.OK) {
alert("Failed to perform search because: " + status);
return;
}
count = results.length;
searchResults = [];
for(var i = 0; i < results.length; i += 1) {
var request2 = {
placeId: results[i].place_id
};
service.getDetails(request2, addDetails);
}
}
function addDetails(result, status) {
if(status == google.maps.places.PlacesServiceStatus.OK) searchResults.push(result);
count -= 1;
if(count <= 0) updateSearchResults(searchResults);
}
/* Hack for having a perfect playlist height */
function setPlaylistHeight() {
var sum = 0;
$("#playlists-pane").children().each(function() {
$this = $(this);
if($this.attr('id') != "playlists") {
sum += $this.height();
sum += parseInt($this.css("borderTopWidth"));
sum += parseInt($this.css("borderBottomWidth"));
sum += parseInt($this.css("paddingTop"));
sum += parseInt($this.css("paddingBottom"));
}
});
$("#playlists").css('height', window.innerHeight - sum);
}
function dragstartAdd(e) {
e.dataTransfer.effectAllowed = 'copy';
e.dataTransfer.setData('pid', e.target.getAttribute('data-uid'));
}
function dragoverAdd(e) {
if (e.preventDefault) e.preventDefault(); // allows us to drop
e.dataTransfer.dropEffect = 'copy';
return false;
}
function dragenterAdd(e) { $(e.target).addClass('over'); }
function dragleaveAdd(e) { $(e.target).removeClass('over'); }
function dropAdd(e) {
if (e.stopPropagation) e.stopPropagation();
var pid = e.dataTransfer.getData('pid');
var uid = e.target.getAttribute('data-uid');
$(e.target).removeClass("over");
var choice;
for(var i = 0; i < searchResults.length; i += 1) {
if(searchResults[i].place_id == pid) {
choice = searchResults[i];
break;
}
}
/* Integrate with shit here */
var name = choice.name;
var loc = new Parse.GeoPoint({latitude: choice.geometry.location.lat(), longitude: choice.geometry.location.lng()});
var restaurant = Parse.Object.extend("Restaurant");
var query = new Parse.Query(restaurant);
query.equalTo("place_id", pid);
query.find({
success: function(results) {
var target;
if (results.length == 0) {
target = new restaurant();
target.set("place_id", pid);
target.set("name", name);
target.set("locaiton", loc);
target.set("sporklists", []);
} else {
target = results[0];
}
var list = target.get("sporklists");
list.push(uid);
target.set("sporklists", list);
console.log(target);
target.save();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
function main(loc) {
service = new google.maps.places.PlacesService(/** @type {HTMLInputElement} */(document.getElementById('attributions')));
autocomplete = new google.maps.places.Autocomplete(/** @type {HTMLInputElement} */(document.getElementById('location-bar')), { types: ['geocode'] });
position = loc.coords;
$("#loading-cover").fadeOut(300);
/* Add functionality to search bar */
$("#restaurant-search").submit(function(e) {
e.preventDefault();
retrieveSearchResults();
});
}
function locError(locErr) {
alert("You cannot use this site because we could not get your geolocation. The error we got was: " + locErr.code);
}
$(document).ready(function() {
setPlaylistHeight();
setTimeout(function() {
navigator.geolocation.getCurrentPosition(main, locError);
}, 600);
});
$(window).resize(function() {
setPlaylistHeight();
});
| scripts/main.js | var parseUser = null;
var position = null;
var service = null;
var autocomplete = null;
var searchResults = null;
var count = 0;
/* In the case of no location name, we use the user's current location */
function retrieveSearchResults() {
var loc;
var place = autocomplete.getPlace();
if(place == undefined || $("#location-bar").val().replace(" ", "") == "")
loc = new google.maps.LatLng(position.latitude, position.longitude);
else
loc = new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng());
var request = {
location: loc,
radius: '8000',
types: ['restaurant', 'meal_delivery', 'meal_takeaway', 'cafe'],
key: 'AIzaSyCnk5Oo0joyYzlR4BVBZsDR2aUteESG0MY',
keyword: $("#search-bar").val()
};
service.nearbySearch(request, displaySearchResults);
}
/* Callback that FINALLY has our search results */
function displaySearchResults(results, status) {
if(status != google.maps.places.PlacesServiceStatus.OK) {
alert("Failed to perform search because: " + status);
return;
}
count = results.length;
searchResults = [];
for(var i = 0; i < results.length; i += 1) {
var request2 = {
placeId: results[i].place_id
};
service.getDetails(request2, addDetails);
}
}
function addDetails(result, status) {
if(status == google.maps.places.PlacesServiceStatus.OK) searchResults.push(result);
count -= 1;
if(count <= 0) updateSearchResults(searchResults);
}
/* Hack for having a perfect playlist height */
function setPlaylistHeight() {
var sum = 0;
$("#playlists-pane").children().each(function() {
$this = $(this);
if($this.attr('id') != "playlists") {
sum += $this.height();
sum += parseInt($this.css("borderTopWidth"));
sum += parseInt($this.css("borderBottomWidth"));
sum += parseInt($this.css("paddingTop"));
sum += parseInt($this.css("paddingBottom"));
}
});
$("#playlists").css('height', window.innerHeight - sum);
}
function dragstartAdd(e) {
e.dataTransfer.effectAllowed = 'copy';
e.dataTransfer.setData('pid', e.target.getAttribute('data-uid'));
}
function dragoverAdd(e) {
if (e.preventDefault) e.preventDefault(); // allows us to drop
e.dataTransfer.dropEffect = 'copy';
return false;
}
function dragenterAdd(e) { $(e.target).addClass('over'); }
function dragleaveAdd(e) { $(e.target).removeClass('over'); }
function dropAdd(e) {
if (e.stopPropagation) e.stopPropagation();
var pid = e.dataTransfer.getData('pid');
var uid = e.target.getAttribute('data-uid');
$(e.target).removeClass("over");
var choice;
for(var i = 0; i < searchResults.length; i += 1) {
if(searchResults[i].place_id == pid) {
choice = searchResults[i];
break;
}
}
/* Integrate with shit here */
var name = choice.name;
var location = new Parse.GeoPoint({latitude: choice.geometry.location.lat(), longitude: choice.geometry.location.lng()});
var restaurant = Parse.Object.extend("Restaurant");
var query = new Parse.Query(restaurant);
query.equalTo("place_id", pid);
query.find({
success: function(results) {
var target;
if (results.length == 0) {
target = new restaurant();
target.set("place_id", pid);
target.set("name", name);
target.set("locaiton", location);
target.set("sporklists", []);
} else {
target = results[0];
}
var list = target.get("sporklists");
list.push(uid);
target.set("sporklists", list);
target.save();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
function main(loc) {
service = new google.maps.places.PlacesService(/** @type {HTMLInputElement} */(document.getElementById('attributions')));
autocomplete = new google.maps.places.Autocomplete(/** @type {HTMLInputElement} */(document.getElementById('location-bar')), { types: ['geocode'] });
position = loc.coords;
$("#loading-cover").fadeOut(300);
/* Add functionality to search bar */
$("#restaurant-search").submit(function(e) {
e.preventDefault();
retrieveSearchResults();
});
}
function locError(locErr) {
alert("You cannot use this site because we could not get your geolocation. The error we got was: " + locErr.code);
}
$(document).ready(function() {
setPlaylistHeight();
setTimeout(function() {
navigator.geolocation.getCurrentPosition(main, locError);
}, 600);
});
$(window).resize(function() {
setPlaylistHeight();
});
| GAAHHH
| scripts/main.js | GAAHHH | <ide><path>cripts/main.js
<ide>
<ide> /* Integrate with shit here */
<ide> var name = choice.name;
<del> var location = new Parse.GeoPoint({latitude: choice.geometry.location.lat(), longitude: choice.geometry.location.lng()});
<add> var loc = new Parse.GeoPoint({latitude: choice.geometry.location.lat(), longitude: choice.geometry.location.lng()});
<ide>
<ide> var restaurant = Parse.Object.extend("Restaurant");
<ide> var query = new Parse.Query(restaurant);
<ide> target = new restaurant();
<ide> target.set("place_id", pid);
<ide> target.set("name", name);
<del> target.set("locaiton", location);
<add> target.set("locaiton", loc);
<ide> target.set("sporklists", []);
<ide> } else {
<ide> target = results[0];
<ide> list.push(uid);
<ide> target.set("sporklists", list);
<ide>
<add> console.log(target);
<ide> target.save();
<ide> },
<ide> error: function(error) { |
|
Java | apache-2.0 | 18c8ec0fa870b8764b98f128859f25a70c17ce22 | 0 | yarrr-ru/stash2slack | package com.pragbits.stash.components;
import com.atlassian.event.api.EventListener;
import com.atlassian.stash.commit.CommitService;
import com.atlassian.stash.content.Changeset;
import com.atlassian.stash.content.ChangesetsBetweenRequest;
import com.atlassian.stash.event.RepositoryPushEvent;
import com.atlassian.stash.nav.NavBuilder;
import com.atlassian.stash.repository.RefChange;
import com.atlassian.stash.repository.RefChangeType;
import com.atlassian.stash.repository.Repository;
import com.atlassian.stash.util.Page;
import com.atlassian.stash.util.PageRequest;
import com.atlassian.stash.util.PageUtils;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.pragbits.stash.ColorCode;
import com.pragbits.stash.SlackGlobalSettingsService;
import com.pragbits.stash.SlackSettings;
import com.pragbits.stash.SlackSettingsService;
import com.pragbits.stash.tools.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class RepositoryPushActivityListener {
static final String KEY_GLOBAL_SETTING_HOOK_URL = "stash2slack.globalsettings.hookurl";
static final String KEY_GLOBAL_SLACK_CHANNEL_NAME = "stash2slack.globalsettings.channelname";
private static final Logger log = LoggerFactory.getLogger(RepositoryPushActivityListener.class);
private final SlackGlobalSettingsService slackGlobalSettingsService;
private final SlackSettingsService slackSettingsService;
private final CommitService commitService;
private final NavBuilder navBuilder;
private final SlackNotifier slackNotifier;
private final Gson gson = new Gson();
public RepositoryPushActivityListener(SlackGlobalSettingsService slackGlobalSettingsService,
SlackSettingsService slackSettingsService,
CommitService commitService,
NavBuilder navBuilder,
SlackNotifier slackNotifier) {
this.slackGlobalSettingsService = slackGlobalSettingsService;
this.slackSettingsService = slackSettingsService;
this.commitService = commitService;
this.navBuilder = navBuilder;
this.slackNotifier = slackNotifier;
}
@EventListener
public void NotifySlackChannel(RepositoryPushEvent event) {
// find out if notification is enabled for this repo
Repository repository = event.getRepository();
SlackSettings slackSettings = slackSettingsService.getSlackSettings(repository);
String globalHookUrl = slackGlobalSettingsService.getWebHookUrl(KEY_GLOBAL_SETTING_HOOK_URL);
SettingsSelector settingsSelector = new SettingsSelector(slackSettingsService, slackGlobalSettingsService, repository);
SlackSettings resolvedSlackSettings = settingsSelector.getResolvedSlackSettings();
if (resolvedSlackSettings.isSlackNotificationsEnabledForPush()) {
String localHookUrl = slackSettings.getSlackWebHookUrl();
WebHookSelector hookSelector = new WebHookSelector(globalHookUrl, localHookUrl);
ChannelSelector channelSelector = new ChannelSelector(slackGlobalSettingsService.getChannelName(KEY_GLOBAL_SLACK_CHANNEL_NAME), slackSettings.getSlackChannelName());
if (!hookSelector.isHookValid()) {
log.error("There is no valid configured Web hook url! Reason: " + hookSelector.getProblem());
return;
}
if (repository.isFork() && !resolvedSlackSettings.isSlackNotificationsEnabledForPersonal()) {
// simply return silently when we don't want forks to get notifications unless they're explicitly enabled
return;
}
String repoName = repository.getSlug();
String projectName = repository.getProject().getKey();
String repoPath = projectName + "/" + event.getRepository().getName();
for (RefChange refChange : event.getRefChanges()) {
String text;
String ref = refChange.getRefId();
NavBuilder.Repo repoUrlBuilder = navBuilder
.project(projectName)
.repo(repoName);
String url = repoUrlBuilder
.commits()
.until(refChange.getRefId())
.buildAbsolute();
List<Changeset> myChanges = new LinkedList<Changeset>();
boolean isNewRef = refChange.getFromHash().equalsIgnoreCase("0000000000000000000000000000000000000000");
boolean isDeleted = refChange.getToHash().equalsIgnoreCase("0000000000000000000000000000000000000000")
&& refChange.getType() == RefChangeType.DELETE;
if (isDeleted || isNewRef) {
return;
}
if (isDeleted) {
// issue#4: if type is "DELETE" and toHash is all zero then this is a branch delete
if (ref.indexOf("refs/tags") >= 0) {
text = String.format("Tag `%s` deleted from repository <%s|`%s`>.",
ref.replace("refs/tags/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath);
} else {
text = String.format("Branch `%s` deleted from repository <%s|`%s`>.",
ref.replace("refs/heads/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath);
}
} else if (isNewRef) {
// issue#3 if fromHash is all zero (meaning the beginning of everything, probably), then this push is probably
// a new branch or tag, and we want only to display the latest commit, not the entire history
Changeset latestChangeSet = commitService.getChangeset(repository, refChange.getToHash());
myChanges.add(latestChangeSet);
if (ref.indexOf("refs/tags") >= 0) {
text = String.format("Tag <%s|`%s`> pushed on <%s|`%s`>. See <%s|commit list>.",
url,
ref.replace("refs/tags/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath,
url
);
} else {
text = String.format("Branch <%s|`%s`> pushed on <%s|`%s`>. See <%s|commit list>.",
url,
ref.replace("refs/heads/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath,
url);
}
} else {
ChangesetsBetweenRequest request = new ChangesetsBetweenRequest.Builder(repository)
.exclude(refChange.getFromHash())
.include(refChange.getToHash())
.build();
Page<Changeset> changeSets = commitService.getChangesetsBetween(
request, PageUtils.newRequest(0, PageRequest.MAX_PAGE_LIMIT));
myChanges.addAll(Lists.newArrayList(changeSets.getValues()));
int commitCount = myChanges.size();
String commitStr = commitCount == 1 ? "commit" : "commits";
String branch = ref.replace("refs/heads/", "");
if (!branch.equals("master")) {
continue;
}
text = String.format("Push on <%s|`%s`> branch <%s|`%s`> by `%s <%s>` (%d %s). See <%s|commit list>.",
repoUrlBuilder.buildAbsolute(),
repoPath,
url,
branch,
event.getUser() != null ? event.getUser().getDisplayName() : "unknown user",
event.getUser() != null ? event.getUser().getEmailAddress() : "unknown email",
commitCount, commitStr,
url);
}
// Figure out what type of change this is:
SlackPayload payload = new SlackPayload();
payload.setText(text);
payload.setMrkdwn(true);
switch (resolvedSlackSettings.getNotificationLevel()) {
case COMPACT:
compactCommitLog(event, refChange, payload, repoUrlBuilder, myChanges);
break;
case VERBOSE:
verboseCommitLog(event, refChange, payload, repoUrlBuilder, text, myChanges);
break;
case MINIMAL:
default:
break;
}
// slackSettings.getSlackChannelName might be:
// - empty
// - comma separated list of channel names, eg: #mych1, #mych2, #mych3
if (channelSelector.getSelectedChannel().isEmpty()) {
slackNotifier.SendSlackNotification(hookSelector.getSelectedHook(), gson.toJson(payload));
} else {
// send message to multiple channels
List<String> channels = Arrays.asList(channelSelector.getSelectedChannel().split("\\s*,\\s*"));
for (String channel: channels) {
payload.setChannel(channel.trim());
slackNotifier.SendSlackNotification(hookSelector.getSelectedHook(), gson.toJson(payload));
}
}
}
}
}
private void compactCommitLog(RepositoryPushEvent event, RefChange refChange, SlackPayload payload, NavBuilder.Repo urlBuilder, List<Changeset> myChanges) {
if (myChanges.size() == 0) {
// If there are no commits, no reason to add anything
}
SlackAttachment commits = new SlackAttachment();
commits.setColor(ColorCode.GRAY.getCode());
// Since the branch is now in the main commit line, title is not needed
//commits.setTitle(String.format("[%s:%s]", event.getRepository().getName(), refChange.getRefId().replace("refs/heads", "")));
StringBuilder attachmentFallback = new StringBuilder();
StringBuilder commitListBlock = new StringBuilder();
for (Changeset ch : myChanges) {
String commitUrl = urlBuilder.changeset(ch.getId()).buildAbsolute();
String firstCommitMessageLine = ch.getMessage().split("\n")[0];
// Note that we changed this to put everything in one attachment because otherwise it
// doesn't get collapsed in slack (the see more... doesn't appear)
commitListBlock.append(String.format("<%s|`%s`>: %s - _%s_\n",
commitUrl, ch.getDisplayId(), firstCommitMessageLine, ch.getAuthor().getName()));
attachmentFallback.append(String.format("%s: %s\n", ch.getDisplayId(), firstCommitMessageLine));
}
commits.setText(commitListBlock.toString());
commits.setFallback(attachmentFallback.toString());
payload.addAttachment(commits);
}
private void verboseCommitLog(RepositoryPushEvent event, RefChange refChange, SlackPayload payload, NavBuilder.Repo urlBuilder, String text, List<Changeset> myChanges) {
for (Changeset ch : myChanges) {
SlackAttachment attachment = new SlackAttachment();
attachment.setFallback(text);
attachment.setColor(ColorCode.GRAY.getCode());
SlackAttachmentField field = new SlackAttachmentField();
attachment.setTitle(String.format("[%s:%s] - %s", event.getRepository().getName(), refChange.getRefId().replace("refs/heads", ""), ch.getId()));
attachment.setTitle_link(urlBuilder.changeset(ch.getId()).buildAbsolute());
field.setTitle("comment");
field.setValue(ch.getMessage());
field.setShort(false);
attachment.addField(field);
payload.addAttachment(attachment);
}
}
}
| src/main/java/com/pragbits/stash/components/RepositoryPushActivityListener.java | package com.pragbits.stash.components;
import com.atlassian.event.api.EventListener;
import com.atlassian.stash.commit.CommitService;
import com.atlassian.stash.content.Changeset;
import com.atlassian.stash.content.ChangesetsBetweenRequest;
import com.atlassian.stash.event.RepositoryPushEvent;
import com.atlassian.stash.nav.NavBuilder;
import com.atlassian.stash.repository.RefChange;
import com.atlassian.stash.repository.RefChangeType;
import com.atlassian.stash.repository.Repository;
import com.atlassian.stash.util.Page;
import com.atlassian.stash.util.PageRequest;
import com.atlassian.stash.util.PageUtils;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.pragbits.stash.ColorCode;
import com.pragbits.stash.SlackGlobalSettingsService;
import com.pragbits.stash.SlackSettings;
import com.pragbits.stash.SlackSettingsService;
import com.pragbits.stash.tools.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class RepositoryPushActivityListener {
static final String KEY_GLOBAL_SETTING_HOOK_URL = "stash2slack.globalsettings.hookurl";
static final String KEY_GLOBAL_SLACK_CHANNEL_NAME = "stash2slack.globalsettings.channelname";
private static final Logger log = LoggerFactory.getLogger(RepositoryPushActivityListener.class);
private final SlackGlobalSettingsService slackGlobalSettingsService;
private final SlackSettingsService slackSettingsService;
private final CommitService commitService;
private final NavBuilder navBuilder;
private final SlackNotifier slackNotifier;
private final Gson gson = new Gson();
public RepositoryPushActivityListener(SlackGlobalSettingsService slackGlobalSettingsService,
SlackSettingsService slackSettingsService,
CommitService commitService,
NavBuilder navBuilder,
SlackNotifier slackNotifier) {
this.slackGlobalSettingsService = slackGlobalSettingsService;
this.slackSettingsService = slackSettingsService;
this.commitService = commitService;
this.navBuilder = navBuilder;
this.slackNotifier = slackNotifier;
}
@EventListener
public void NotifySlackChannel(RepositoryPushEvent event) {
// find out if notification is enabled for this repo
Repository repository = event.getRepository();
SlackSettings slackSettings = slackSettingsService.getSlackSettings(repository);
String globalHookUrl = slackGlobalSettingsService.getWebHookUrl(KEY_GLOBAL_SETTING_HOOK_URL);
SettingsSelector settingsSelector = new SettingsSelector(slackSettingsService, slackGlobalSettingsService, repository);
SlackSettings resolvedSlackSettings = settingsSelector.getResolvedSlackSettings();
if (resolvedSlackSettings.isSlackNotificationsEnabledForPush()) {
String localHookUrl = slackSettings.getSlackWebHookUrl();
WebHookSelector hookSelector = new WebHookSelector(globalHookUrl, localHookUrl);
ChannelSelector channelSelector = new ChannelSelector(slackGlobalSettingsService.getChannelName(KEY_GLOBAL_SLACK_CHANNEL_NAME), slackSettings.getSlackChannelName());
if (!hookSelector.isHookValid()) {
log.error("There is no valid configured Web hook url! Reason: " + hookSelector.getProblem());
return;
}
if (repository.isFork() && !resolvedSlackSettings.isSlackNotificationsEnabledForPersonal()) {
// simply return silently when we don't want forks to get notifications unless they're explicitly enabled
return;
}
String repoName = repository.getSlug();
String projectName = repository.getProject().getKey();
String repoPath = projectName + "/" + event.getRepository().getName();
for (RefChange refChange : event.getRefChanges()) {
String text;
String ref = refChange.getRefId();
NavBuilder.Repo repoUrlBuilder = navBuilder
.project(projectName)
.repo(repoName);
String url = repoUrlBuilder
.commits()
.until(refChange.getRefId())
.buildAbsolute();
List<Changeset> myChanges = new LinkedList<Changeset>();
boolean isNewRef = refChange.getFromHash().equalsIgnoreCase("0000000000000000000000000000000000000000");
boolean isDeleted = refChange.getToHash().equalsIgnoreCase("0000000000000000000000000000000000000000")
&& refChange.getType() == RefChangeType.DELETE;
if (isDeleted) {
// issue#4: if type is "DELETE" and toHash is all zero then this is a branch delete
if (ref.indexOf("refs/tags") >= 0) {
text = String.format("Tag `%s` deleted from repository <%s|`%s`>.",
ref.replace("refs/tags/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath);
} else {
text = String.format("Branch `%s` deleted from repository <%s|`%s`>.",
ref.replace("refs/heads/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath);
}
} else if (isNewRef) {
// issue#3 if fromHash is all zero (meaning the beginning of everything, probably), then this push is probably
// a new branch or tag, and we want only to display the latest commit, not the entire history
Changeset latestChangeSet = commitService.getChangeset(repository, refChange.getToHash());
myChanges.add(latestChangeSet);
if (ref.indexOf("refs/tags") >= 0) {
text = String.format("Tag <%s|`%s`> pushed on <%s|`%s`>. See <%s|commit list>.",
url,
ref.replace("refs/tags/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath,
url
);
} else {
text = String.format("Branch <%s|`%s`> pushed on <%s|`%s`>. See <%s|commit list>.",
url,
ref.replace("refs/heads/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath,
url);
}
} else {
ChangesetsBetweenRequest request = new ChangesetsBetweenRequest.Builder(repository)
.exclude(refChange.getFromHash())
.include(refChange.getToHash())
.build();
Page<Changeset> changeSets = commitService.getChangesetsBetween(
request, PageUtils.newRequest(0, PageRequest.MAX_PAGE_LIMIT));
myChanges.addAll(Lists.newArrayList(changeSets.getValues()));
int commitCount = myChanges.size();
String commitStr = commitCount == 1 ? "commit" : "commits";
String branch = ref.replace("refs/heads/", "");
if (!branch.equals("master")) {
continue;
}
text = String.format("Push on <%s|`%s`> branch <%s|`%s`> by `%s <%s>` (%d %s). See <%s|commit list>.",
repoUrlBuilder.buildAbsolute(),
repoPath,
url,
branch,
event.getUser() != null ? event.getUser().getDisplayName() : "unknown user",
event.getUser() != null ? event.getUser().getEmailAddress() : "unknown email",
commitCount, commitStr,
url);
}
// Figure out what type of change this is:
SlackPayload payload = new SlackPayload();
payload.setText(text);
payload.setMrkdwn(true);
switch (resolvedSlackSettings.getNotificationLevel()) {
case COMPACT:
compactCommitLog(event, refChange, payload, repoUrlBuilder, myChanges);
break;
case VERBOSE:
verboseCommitLog(event, refChange, payload, repoUrlBuilder, text, myChanges);
break;
case MINIMAL:
default:
break;
}
// slackSettings.getSlackChannelName might be:
// - empty
// - comma separated list of channel names, eg: #mych1, #mych2, #mych3
if (channelSelector.getSelectedChannel().isEmpty()) {
slackNotifier.SendSlackNotification(hookSelector.getSelectedHook(), gson.toJson(payload));
} else {
// send message to multiple channels
List<String> channels = Arrays.asList(channelSelector.getSelectedChannel().split("\\s*,\\s*"));
for (String channel: channels) {
payload.setChannel(channel.trim());
slackNotifier.SendSlackNotification(hookSelector.getSelectedHook(), gson.toJson(payload));
}
}
}
}
}
private void compactCommitLog(RepositoryPushEvent event, RefChange refChange, SlackPayload payload, NavBuilder.Repo urlBuilder, List<Changeset> myChanges) {
if (myChanges.size() == 0) {
// If there are no commits, no reason to add anything
}
SlackAttachment commits = new SlackAttachment();
commits.setColor(ColorCode.GRAY.getCode());
// Since the branch is now in the main commit line, title is not needed
//commits.setTitle(String.format("[%s:%s]", event.getRepository().getName(), refChange.getRefId().replace("refs/heads", "")));
StringBuilder attachmentFallback = new StringBuilder();
StringBuilder commitListBlock = new StringBuilder();
for (Changeset ch : myChanges) {
String commitUrl = urlBuilder.changeset(ch.getId()).buildAbsolute();
String firstCommitMessageLine = ch.getMessage().split("\n")[0];
// Note that we changed this to put everything in one attachment because otherwise it
// doesn't get collapsed in slack (the see more... doesn't appear)
commitListBlock.append(String.format("<%s|`%s`>: %s - _%s_\n",
commitUrl, ch.getDisplayId(), firstCommitMessageLine, ch.getAuthor().getName()));
attachmentFallback.append(String.format("%s: %s\n", ch.getDisplayId(), firstCommitMessageLine));
}
commits.setText(commitListBlock.toString());
commits.setFallback(attachmentFallback.toString());
payload.addAttachment(commits);
}
private void verboseCommitLog(RepositoryPushEvent event, RefChange refChange, SlackPayload payload, NavBuilder.Repo urlBuilder, String text, List<Changeset> myChanges) {
for (Changeset ch : myChanges) {
SlackAttachment attachment = new SlackAttachment();
attachment.setFallback(text);
attachment.setColor(ColorCode.GRAY.getCode());
SlackAttachmentField field = new SlackAttachmentField();
attachment.setTitle(String.format("[%s:%s] - %s", event.getRepository().getName(), refChange.getRefId().replace("refs/heads", ""), ch.getId()));
attachment.setTitle_link(urlBuilder.changeset(ch.getId()).buildAbsolute());
field.setTitle("comment");
field.setValue(ch.getMessage());
field.setShort(false);
attachment.addField(field);
payload.addAttachment(attachment);
}
}
}
| Update RepositoryPushActivityListener.java
Remove messages about new branches | src/main/java/com/pragbits/stash/components/RepositoryPushActivityListener.java | Update RepositoryPushActivityListener.java | <ide><path>rc/main/java/com/pragbits/stash/components/RepositoryPushActivityListener.java
<ide> boolean isNewRef = refChange.getFromHash().equalsIgnoreCase("0000000000000000000000000000000000000000");
<ide> boolean isDeleted = refChange.getToHash().equalsIgnoreCase("0000000000000000000000000000000000000000")
<ide> && refChange.getType() == RefChangeType.DELETE;
<add> if (isDeleted || isNewRef) {
<add> return;
<add> }
<ide> if (isDeleted) {
<ide> // issue#4: if type is "DELETE" and toHash is all zero then this is a branch delete
<ide> if (ref.indexOf("refs/tags") >= 0) { |
|
Java | apache-2.0 | 5da51cbb74cdb7c38f3838a9e1c09d0d48668335 | 0 | playfellas/superapp | package it.playfellas.superapp.ui.master;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import it.playfellas.superapp.R;
public class GameFragment extends Fragment implements
MasterDialogFragment.DialogConfirmListener {
private static final String TAG = GameFragment.class.getSimpleName();
protected GamePresenter presenter;
@Bind(R.id.scoreTextView)
TextView scoreTextView;
@Bind(R.id.globalScoreTextView)
TextView globalScoreTextView;
//Photos taken on slave devices.
// @Bind(R.id.photo1ImageView)
// protected ImageView photo1ImageView;
@Bind(R.id.photo2ImageView)
protected ImageView photo2ImageView;
@Bind(R.id.photo3ImageView)
protected ImageView photo3ImageView;
@Bind(R.id.photo4ImageView)
protected ImageView photo4ImageView;
//The central image, that represent the progress (in number of completed stages) of the current game.
@Bind(R.id.central_img)
ImageView centralImageView;
private List<Bitmap> piecesList;
protected Bitmap photoBitmap;
/**
* Method to init central image, creating a grayscale version of {@code photoBitmap}.
*
* @param numStages the maximum number of stages used to split the original bitmap.
*/
public void initCentralImage(int numStages) {
//split the original bitmap and store its pieces in a List
piecesList = BitmapUtils.splitImage(photoBitmap, numStages);
//create a gray scale version of the original bitmap
Bitmap gray = BitmapUtils.toGrayscale(photoBitmap);
//update the gui with the gray scale version
centralImageView.setImageBitmap(gray);
}
/**
* Method to update the central image coloring {@code currentStages} pieces,
* and leaving {@code numStages-currentStages} pieces in gray scale.
*
* @param currentStage starts from 0 to numStages-1
* @param numStages the maximum number of stages
*/
protected void updateStageImage(int currentStage, int numStages) {
if (currentStage > numStages) {
return;
}
Log.d("GameFragment", "currentStage: " + currentStage + " , maxStages: " + numStages);
//Copy the arrayList of the photoBitmap's pieces
List<Bitmap> bitmapListCopy = new ArrayList<>(piecesList);
//update the pieces by the value of currentStages
for (int i = 0; i < numStages; i++) {
if (i <= currentStage) {
bitmapListCopy.set(i, bitmapListCopy.get(i));
} else {
bitmapListCopy.set(i, BitmapUtils.toGrayscale(bitmapListCopy.get(i)));
}
}
//get the combined image
Bitmap finalBitmap = BitmapUtils.getCombinedBitmapByPieces(bitmapListCopy, numStages);
//set the combined image in the gui
centralImageView.setImageBitmap(finalBitmap);
}
/**
* Method to update the current stage's score. This is not the global score.
*
* @param currentStageScore The total score.
*/
protected void setCurrentStageScore(int currentStageScore) {
this.scoreTextView.setText(currentStageScore + "");
}
/**
* Method to update the global score, non only of the current stage, but it's the sum of all stages scores.
*
* @param currentStageScore The score of the current stage.
* @param maxScorePerStage The max score that you must obtain to complete the current stage.
* @param currentStageNum The current stage number (0 to maxNumStages - 1).
*/
protected void setGlobalScore(int currentStageScore, int maxScorePerStage, int currentStageNum) {
int globalScore = (maxScorePerStage * currentStageNum) + currentStageScore;
Log.d(TAG, "globalscore: " + globalScore);
this.globalScoreTextView.setText(globalScore + "");
}
public void showDialogToProceed() {
//show a dialog with this title and string, but this isn't a dialog to ask confirmation
showDialogFragment("Stage completato", "Pronto per lo stage successivo?", false, "masterDialogFragment");
}
@Override
public void yesButtonPressed() {
//if you press YES on a dialog
presenter.beginNextStage();
}
@Override
public void noButtonPressed() {
//show a dialog with this title and string, but this time displays a dialog to ask
//if you are really sure to confirm the previous action
this.hideDialogFragment("masterDialogFragment");
//now i'll show a new dialog fragment
showDialogFragment("Terminare la partita?", "Sei sicuro di voler terminare la partita?", true, "areYourSureDialogFragment");
}
@Override
public void yesButtonAreYouSurePressed() {
//TODO cancel the game an go back to the main activity or the gameactivity.
}
@Override
public void noButtonAreYouSurePressed() {
//do nothing, because i dismiss the "Are you sure dialog"
}
private void showDialogFragment(String title, String message, boolean areYouSureDialog, String tag) {
MasterDialogFragment masterDialogFragment = (MasterDialogFragment) getFragmentManager().findFragmentByTag(tag);
if (masterDialogFragment == null) {
masterDialogFragment = MasterDialogFragment.newInstance(title, message, areYouSureDialog);
masterDialogFragment.setTargetFragment(this, 0);
masterDialogFragment.show(getFragmentManager(), tag);
getFragmentManager().executePendingTransactions();
}
}
private void hideDialogFragment(String tag) {
MasterDialogFragment masterDialogFragment = (MasterDialogFragment) getFragmentManager().findFragmentByTag(tag);
if (masterDialogFragment != null) {
masterDialogFragment.dismiss();
getFragmentManager().executePendingTransactions();
}
}
}
| app/src/main/java/it/playfellas/superapp/ui/master/GameFragment.java | package it.playfellas.superapp.ui.master;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import it.playfellas.superapp.R;
import lombok.Getter;
public class GameFragment extends Fragment implements
MasterDialogFragment.DialogConfirmListener {
private static final String TAG = GameFragment.class.getSimpleName();
protected GamePresenter presenter;
@Bind(R.id.scoreTextView)
TextView scoreTextView;
@Bind(R.id.globalScoreTextView)
TextView globalScoreTextView;
//Photos taken on slave devices.
// @Bind(R.id.photo1ImageView)
// protected ImageView photo1ImageView;
@Bind(R.id.photo2ImageView)
protected ImageView photo2ImageView;
@Bind(R.id.photo3ImageView)
protected ImageView photo3ImageView;
@Bind(R.id.photo4ImageView)
protected ImageView photo4ImageView;
//The central image, that represent the progress (in number of completed stages) of the current game.
@Bind(R.id.central_img)
ImageView centralImageView;
private List<Bitmap> piecesList;
protected Bitmap photoBitmap;
/**
* Method to init central image, creating a grayscale version of {@code photoBitmap}.
*
* @param numStages the maximum number of stages used to split the original bitmap.
*/
public void initCentralImage(int numStages) {
//split the original bitmap and store its pieces in a List
piecesList = BitmapUtils.splitImage(photoBitmap, numStages);
//create a gray scale version of the original bitmap
Bitmap gray = BitmapUtils.toGrayscale(photoBitmap);
//update the gui with the gray scale version
centralImageView.setImageBitmap(gray);
}
/**
* Method to update the central image coloring {@code currentStages} pieces,
* and leaving {@code numStages-currentStages} pieces in gray scale.
*
* @param currentStage starts from 0 to numStages-1
* @param numStages the maximum number of stages
*/
protected void updateStageImage(int currentStage, int numStages) {
if (currentStage > numStages) {
return;
}
Log.d("GameFragment", "currentStage: " + currentStage + " , maxStages: " + numStages);
//Copy the arrayList of the photoBitmap's pieces
List<Bitmap> bitmapListCopy = new ArrayList<>(piecesList);
//update the pieces by the value of currentStages
for (int i = 0; i < numStages; i++) {
if (i <= currentStage) {
bitmapListCopy.set(i, bitmapListCopy.get(i));
} else {
bitmapListCopy.set(i, BitmapUtils.toGrayscale(bitmapListCopy.get(i)));
}
}
//get the combined image
Bitmap finalBitmap = BitmapUtils.getCombinedBitmapByPieces(bitmapListCopy, numStages);
//set the combined image in the gui
centralImageView.setImageBitmap(finalBitmap);
}
/**
* Method to update the current stage's score. This is not the global score.
*
* @param currentStageScore The total score.
*/
protected void setCurrentStageScore(int currentStageScore) {
this.scoreTextView.setText(currentStageScore + "");
}
/**
* Method to update the global score, non only of the current stage, but it's the sum of all stages scores.
*
* @param currentStageScore The score of the current stage.
* @param maxScorePerStage The max score that you must obtain to complete the current stage.
* @param currentStageNum The current stage number (0 to maxNumStages - 1).
*/
protected void setGlobalScore(int currentStageScore, int maxScorePerStage, int currentStageNum) {
int globalScore = (maxScorePerStage * currentStageNum) + currentStageScore;
Log.d(TAG, "globalscore: " + globalScore);
this.globalScoreTextView.setText(globalScore + "");
}
public void showDialogToProceed() {
//show a dialog with this title and string, but this isn't a dialog to ask confirmation
showDialogFragment("Stage completato", "Pronto per lo stage successivo?", false);
}
@Override
public void yesButtonPressed() {
//if you press YES on a dialog
presenter.beginNextStage();
}
@Override
public void noButtonPressed() {
//show a dialog with this title and string, but this time displays a dialog to ask
//if you are really sure to confirm the previous action
showDialogFragment("Terminare la partita?", "Sei sicuro di voler terminare la partita?", true);
}
@Override
public void yesButtonAreYouSurePressed() {
//TODO cancel the game an go back to the main activity or the gameactivity.
}
@Override
public void noButtonAreYouSurePressed() {
//do nothing, because i cancel the Are you sure dialog
}
private void showDialogFragment(String title, String message, boolean areYouSureDialog) {
MasterDialogFragment masterDialogFragment = (MasterDialogFragment) getFragmentManager()
.findFragmentByTag("masterDialogFragment");
if (masterDialogFragment == null) {
masterDialogFragment = MasterDialogFragment.newInstance(title, message, areYouSureDialog);
masterDialogFragment.setTargetFragment(this, 0);
masterDialogFragment.show(getFragmentManager(), "masterDialogFragment");
getFragmentManager().executePendingTransactions();
}
}
}
| Fix for "are you really sure" dialog fragment Master
| app/src/main/java/it/playfellas/superapp/ui/master/GameFragment.java | Fix for "are you really sure" dialog fragment Master | <ide><path>pp/src/main/java/it/playfellas/superapp/ui/master/GameFragment.java
<ide>
<ide> import butterknife.Bind;
<ide> import it.playfellas.superapp.R;
<del>import lombok.Getter;
<ide>
<ide> public class GameFragment extends Fragment implements
<ide> MasterDialogFragment.DialogConfirmListener {
<ide>
<ide> public void showDialogToProceed() {
<ide> //show a dialog with this title and string, but this isn't a dialog to ask confirmation
<del> showDialogFragment("Stage completato", "Pronto per lo stage successivo?", false);
<add> showDialogFragment("Stage completato", "Pronto per lo stage successivo?", false, "masterDialogFragment");
<ide> }
<ide>
<ide> @Override
<ide> public void noButtonPressed() {
<ide> //show a dialog with this title and string, but this time displays a dialog to ask
<ide> //if you are really sure to confirm the previous action
<del> showDialogFragment("Terminare la partita?", "Sei sicuro di voler terminare la partita?", true);
<add> this.hideDialogFragment("masterDialogFragment");
<ide>
<add> //now i'll show a new dialog fragment
<add> showDialogFragment("Terminare la partita?", "Sei sicuro di voler terminare la partita?", true, "areYourSureDialogFragment");
<ide> }
<ide>
<ide> @Override
<ide>
<ide> @Override
<ide> public void noButtonAreYouSurePressed() {
<del> //do nothing, because i cancel the Are you sure dialog
<add> //do nothing, because i dismiss the "Are you sure dialog"
<ide> }
<ide>
<del> private void showDialogFragment(String title, String message, boolean areYouSureDialog) {
<del> MasterDialogFragment masterDialogFragment = (MasterDialogFragment) getFragmentManager()
<del> .findFragmentByTag("masterDialogFragment");
<add> private void showDialogFragment(String title, String message, boolean areYouSureDialog, String tag) {
<add> MasterDialogFragment masterDialogFragment = (MasterDialogFragment) getFragmentManager().findFragmentByTag(tag);
<ide>
<ide> if (masterDialogFragment == null) {
<ide> masterDialogFragment = MasterDialogFragment.newInstance(title, message, areYouSureDialog);
<ide> masterDialogFragment.setTargetFragment(this, 0);
<ide>
<del> masterDialogFragment.show(getFragmentManager(), "masterDialogFragment");
<add> masterDialogFragment.show(getFragmentManager(), tag);
<add> getFragmentManager().executePendingTransactions();
<add> }
<add> }
<add>
<add> private void hideDialogFragment(String tag) {
<add> MasterDialogFragment masterDialogFragment = (MasterDialogFragment) getFragmentManager().findFragmentByTag(tag);
<add> if (masterDialogFragment != null) {
<add> masterDialogFragment.dismiss();
<ide> getFragmentManager().executePendingTransactions();
<ide> }
<ide> } |
|
JavaScript | mit | 2fa0dbbb850cf8a29ee4e912382649b5a0669d5c | 0 | mavoweb/mavo | (function($, $$) {
var _ = Mavo.Expression = $.Class({
constructor: function(expression) {
this.expression = expression;
},
eval: function(data = Mavo.Data.stub, o) {
Mavo.hooks.run("expression-eval-beforeeval", this);
if (!this.function) {
try {
this.function = Mavo.Script.compile(this.expression, o);
}
catch (error) {
// Compilation error
this.error(`There is something wrong with the expression ${this.expression}`,
error.message,
'Not an expression? See https://mavo.io/docs/expressions/#disabling-expressions for information on how to disable expressions.'
);
Mavo.hooks.run("expression-compile-error", {context: this, error});
return this.function = error;
}
}
else if (this.function instanceof Error) {
// Previous compilation error
return this.function;
}
try {
return this.function(data);
}
catch (error) {
// Runtime error
this.error(`Something went wrong with the expression ${this.expression}`,
error.message,
`Data was: ${JSON.stringify(data)}`
);
Mavo.hooks.run("expression-eval-error", {context: this, error});
return error;
}
},
error(title, ...message) {
message = message.join("\n");
console.info(`%cOops! �� ${title}:`, "color: #c04; font-weight: bold;", message);
},
toString() {
return this.expression;
},
changedBy: function(evt) {
return _.changedBy(this.identifiers, evt);
},
live: {
expression: function(value) {
this.function = null;
this.identifiers = value.match(/[$a-z][$\w]*/ig) || [];
}
},
});
_.Syntax = $.Class({
constructor: function(start, end) {
this.start = start;
this.end = end;
this.regex = RegExp(`${Mavo.escapeRegExp(start)}([\\S\\s]+?)${Mavo.escapeRegExp(end)}`, "gi");
},
test: function(str) {
this.regex.lastIndex = 0;
return this.regex.test(str);
},
tokenize: function(str) {
var match, ret = [], lastIndex = 0;
this.regex.lastIndex = 0;
while ((match = this.regex.exec(str)) !== null) {
// Literal before the expression
if (match.index > lastIndex) {
ret.push(str.substring(lastIndex, match.index));
}
lastIndex = this.regex.lastIndex;
ret.push(new Mavo.Expression(match[1]));
}
// Literal at the end
if (lastIndex < str.length) {
ret.push(str.substring(lastIndex));
}
return ret;
},
static: {
create: function(element) {
if (element) {
var syntax = element.getAttribute("mv-expressions");
if (syntax) {
syntax = syntax.trim();
return /\s/.test(syntax)? new _.Syntax(...syntax.split(/\s+/)) : _.Syntax.ESCAPE;
}
}
},
ESCAPE: -1
}
});
_.Syntax.default = new _.Syntax("[", "]");
})(Bliss, Bliss.$);
| src/expression.js | (function($, $$) {
var _ = Mavo.Expression = $.Class({
constructor: function(expression) {
this.expression = expression;
},
eval: function(data = Mavo.Data.stub, o) {
Mavo.hooks.run("expression-eval-beforeeval", this);
try {
if (!this.function) {
this.function = Mavo.Script.compile(this.expression, o);
}
return this.function(data);
}
catch (exception) {
console.info("%cExpression error!", "color: red; font-weight: bold", `${exception.message} in expression ${this.expression}`, `
Not an expression? Use mv-expressions="none" to disable expressions on an element and its descendants.`);
Mavo.hooks.run("expression-eval-error", {context: this, exception});
return exception;
}
},
toString() {
return this.expression;
},
changedBy: function(evt) {
return _.changedBy(this.identifiers, evt);
},
live: {
expression: function(value) {
this.function = null;
this.identifiers = value.match(/[$a-z][$\w]*/ig) || [];
}
},
});
_.Syntax = $.Class({
constructor: function(start, end) {
this.start = start;
this.end = end;
this.regex = RegExp(`${Mavo.escapeRegExp(start)}([\\S\\s]+?)${Mavo.escapeRegExp(end)}`, "gi");
},
test: function(str) {
this.regex.lastIndex = 0;
return this.regex.test(str);
},
tokenize: function(str) {
var match, ret = [], lastIndex = 0;
this.regex.lastIndex = 0;
while ((match = this.regex.exec(str)) !== null) {
// Literal before the expression
if (match.index > lastIndex) {
ret.push(str.substring(lastIndex, match.index));
}
lastIndex = this.regex.lastIndex;
ret.push(new Mavo.Expression(match[1]));
}
// Literal at the end
if (lastIndex < str.length) {
ret.push(str.substring(lastIndex));
}
return ret;
},
static: {
create: function(element) {
if (element) {
var syntax = element.getAttribute("mv-expressions");
if (syntax) {
syntax = syntax.trim();
return /\s/.test(syntax)? new _.Syntax(...syntax.split(/\s+/)) : _.Syntax.ESCAPE;
}
}
},
ESCAPE: -1
}
});
_.Syntax.default = new _.Syntax("[", "]");
})(Bliss, Bliss.$);
| Better error display for expressions
Separate compilation errors from runtime errors, show the former only
once.
More useful error display overall.
Link to docs for disabling expressions.
| src/expression.js | Better error display for expressions | <ide><path>rc/expression.js
<ide> eval: function(data = Mavo.Data.stub, o) {
<ide> Mavo.hooks.run("expression-eval-beforeeval", this);
<ide>
<del> try {
<del> if (!this.function) {
<add> if (!this.function) {
<add> try {
<ide> this.function = Mavo.Script.compile(this.expression, o);
<ide> }
<add> catch (error) {
<add> // Compilation error
<add> this.error(`There is something wrong with the expression ${this.expression}`,
<add> error.message,
<add> 'Not an expression? See https://mavo.io/docs/expressions/#disabling-expressions for information on how to disable expressions.'
<add> );
<ide>
<add> Mavo.hooks.run("expression-compile-error", {context: this, error});
<add>
<add> return this.function = error;
<add> }
<add> }
<add> else if (this.function instanceof Error) {
<add> // Previous compilation error
<add> return this.function;
<add> }
<add>
<add> try {
<ide> return this.function(data);
<ide> }
<del> catch (exception) {
<del> console.info("%cExpression error!", "color: red; font-weight: bold", `${exception.message} in expression ${this.expression}`, `
<del>Not an expression? Use mv-expressions="none" to disable expressions on an element and its descendants.`);
<add> catch (error) {
<add> // Runtime error
<add> this.error(`Something went wrong with the expression ${this.expression}`,
<add> error.message,
<add> `Data was: ${JSON.stringify(data)}`
<add> );
<ide>
<del> Mavo.hooks.run("expression-eval-error", {context: this, exception});
<add> Mavo.hooks.run("expression-eval-error", {context: this, error});
<ide>
<del> return exception;
<add> return error;
<ide> }
<add> },
<add>
<add> error(title, ...message) {
<add> message = message.join("\n");
<add> console.info(`%cOops! �� ${title}:`, "color: #c04; font-weight: bold;", message);
<ide> },
<ide>
<ide> toString() { |
|
Java | apache-2.0 | 7617d3917e9de8785ba1db99934ee5e1648b5db5 | 0 | atomfrede/generator-jhipster,PierreBesson/generator-jhipster,PierreBesson/generator-jhipster,robertmilowski/generator-jhipster,liseri/generator-jhipster,nkolosnjaji/generator-jhipster,gmarziou/generator-jhipster,robertmilowski/generator-jhipster,dynamicguy/generator-jhipster,dynamicguy/generator-jhipster,robertmilowski/generator-jhipster,jkutner/generator-jhipster,ruddell/generator-jhipster,ramzimaalej/generator-jhipster,ruddell/generator-jhipster,duderoot/generator-jhipster,vivekmore/generator-jhipster,sohibegit/generator-jhipster,erikkemperman/generator-jhipster,sohibegit/generator-jhipster,vivekmore/generator-jhipster,Tcharl/generator-jhipster,mraible/generator-jhipster,mraible/generator-jhipster,danielpetisme/generator-jhipster,mosoft521/generator-jhipster,nkolosnjaji/generator-jhipster,dimeros/generator-jhipster,jhipster/generator-jhipster,PierreBesson/generator-jhipster,sendilkumarn/generator-jhipster,danielpetisme/generator-jhipster,sohibegit/generator-jhipster,hdurix/generator-jhipster,Tcharl/generator-jhipster,wmarques/generator-jhipster,robertmilowski/generator-jhipster,ruddell/generator-jhipster,mraible/generator-jhipster,erikkemperman/generator-jhipster,eosimosu/generator-jhipster,gzsombor/generator-jhipster,pascalgrimaud/generator-jhipster,ctamisier/generator-jhipster,gmarziou/generator-jhipster,jkutner/generator-jhipster,robertmilowski/generator-jhipster,ziogiugno/generator-jhipster,gmarziou/generator-jhipster,jhipster/generator-jhipster,rifatdover/generator-jhipster,danielpetisme/generator-jhipster,PierreBesson/generator-jhipster,mosoft521/generator-jhipster,mosoft521/generator-jhipster,dynamicguy/generator-jhipster,eosimosu/generator-jhipster,erikkemperman/generator-jhipster,sendilkumarn/generator-jhipster,jkutner/generator-jhipster,atomfrede/generator-jhipster,pascalgrimaud/generator-jhipster,danielpetisme/generator-jhipster,eosimosu/generator-jhipster,nkolosnjaji/generator-jhipster,liseri/generator-jhipster,cbornet/generator-jhipster,cbornet/generator-jhipster,pascalgrimaud/generator-jhipster,ziogiugno/generator-jhipster,gmarziou/generator-jhipster,duderoot/generator-jhipster,gzsombor/generator-jhipster,liseri/generator-jhipster,jkutner/generator-jhipster,wmarques/generator-jhipster,cbornet/generator-jhipster,ruddell/generator-jhipster,mosoft521/generator-jhipster,pascalgrimaud/generator-jhipster,wmarques/generator-jhipster,atomfrede/generator-jhipster,atomfrede/generator-jhipster,sendilkumarn/generator-jhipster,sohibegit/generator-jhipster,sendilkumarn/generator-jhipster,cbornet/generator-jhipster,jhipster/generator-jhipster,Tcharl/generator-jhipster,hdurix/generator-jhipster,jhipster/generator-jhipster,sohibegit/generator-jhipster,atomfrede/generator-jhipster,wmarques/generator-jhipster,mraible/generator-jhipster,danielpetisme/generator-jhipster,mosoft521/generator-jhipster,ziogiugno/generator-jhipster,pascalgrimaud/generator-jhipster,gmarziou/generator-jhipster,dimeros/generator-jhipster,ctamisier/generator-jhipster,wmarques/generator-jhipster,dimeros/generator-jhipster,ctamisier/generator-jhipster,ruddell/generator-jhipster,vivekmore/generator-jhipster,ctamisier/generator-jhipster,jhipster/generator-jhipster,liseri/generator-jhipster,nkolosnjaji/generator-jhipster,hdurix/generator-jhipster,sendilkumarn/generator-jhipster,vivekmore/generator-jhipster,dimeros/generator-jhipster,ramzimaalej/generator-jhipster,duderoot/generator-jhipster,eosimosu/generator-jhipster,rifatdover/generator-jhipster,Tcharl/generator-jhipster,rifatdover/generator-jhipster,hdurix/generator-jhipster,erikkemperman/generator-jhipster,gzsombor/generator-jhipster,ziogiugno/generator-jhipster,mraible/generator-jhipster,dynamicguy/generator-jhipster,erikkemperman/generator-jhipster,liseri/generator-jhipster,cbornet/generator-jhipster,dimeros/generator-jhipster,vivekmore/generator-jhipster,duderoot/generator-jhipster,eosimosu/generator-jhipster,Tcharl/generator-jhipster,hdurix/generator-jhipster,gzsombor/generator-jhipster,PierreBesson/generator-jhipster,ctamisier/generator-jhipster,duderoot/generator-jhipster,ziogiugno/generator-jhipster,ramzimaalej/generator-jhipster,nkolosnjaji/generator-jhipster,gzsombor/generator-jhipster,jkutner/generator-jhipster | <%#
Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
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 <%=packageName%>.config;
<%_ if (cacheProvider === 'ehcache') { _%>
import io.github.jhipster.config.JHipsterProperties;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
import java.util.concurrent.TimeUnit;
<%_ } _%>
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import com.hazelcast.config.*;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.Hazelcast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
import org.springframework.beans.factory.annotation.Autowired;
<%_ } _%>
<%_ } _%>
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
<%_ if (cacheProvider === 'ehcache') { _%>
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
<%_ } _%>
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
<%_ if (serviceDiscoveryType === 'eureka') { _%>
import org.springframework.boot.autoconfigure.web.ServerProperties;
<%_ } _%>
import org.springframework.cache.CacheManager;
<%_ } _%>
import org.springframework.cache.annotation.EnableCaching;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
<%_ } _%>
import org.springframework.context.annotation.*;
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
import org.springframework.core.env.Environment;
<%_ } _%>
<%_ if (clusteredHttpSession === 'hazelcast') { _%>
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
<%_ } _%>
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
import javax.annotation.PreDestroy;
<%_ } _%>
<%_ if (cacheProvider === 'infinispan') { _%>
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import infinispan.autoconfigure.embedded.InfinispanCacheConfigurer;
import infinispan.autoconfigure.embedded.InfinispanGlobalConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.jhipster.config.JHipsterProperties;
import java.util.concurrent.TimeUnit;
import org.infinispan.eviction.EvictionType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.transaction.TransactionMode;
import infinispan.autoconfigure.embedded.InfinispanEmbeddedCacheManagerAutoConfiguration;
import org.infinispan.jcache.embedded.ConfigurationAdapter;
import org.infinispan.jcache.embedded.JCache;
import org.infinispan.jcache.embedded.JCacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
import java.net.URI;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
import org.springframework.beans.factory.annotation.Autowired;
import org.infinispan.remoting.transport.jgroups.JGroupsTransport;
import org.jgroups.Channel;
import org.jgroups.JChannel;
import org.jgroups.PhysicalAddress;
import org.jgroups.protocols.*;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.protocols.pbcast.NAKACK2;
import org.jgroups.protocols.pbcast.STABLE;
import org.jgroups.stack.IpAddress;
import org.jgroups.stack.ProtocolStack;
import java.net.InetAddress;
import org.springframework.beans.factory.BeanInitializationException;
import java.util.ArrayList;
import java.util.List;
<%_ } _%>
<%_ } _%>
@Configuration
@EnableCaching
@AutoConfigureAfter(value = { MetricsConfiguration.class })
@AutoConfigureBefore(value = { WebConfigurer.class<% if (databaseType === 'sql' || databaseType === 'mongodb') { %>, DatabaseConfiguration.class<% } %> })
<%_ if (cacheProvider === 'infinispan') { _%>
@Import(InfinispanEmbeddedCacheManagerAutoConfiguration.class)
<%_ } _%>
public class CacheConfiguration {
<%_ if (cacheProvider === 'ehcache') { _%>
private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;
public CacheConfiguration(JHipsterProperties jHipsterProperties) {
JHipsterProperties.Cache.Ehcache ehcache =
jHipsterProperties.getCache().getEhcache();
jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
ResourcePoolsBuilder.heap(ehcache.getMaxEntries()))
.withExpiry(Expirations.timeToLiveExpiration(Duration.of(ehcache.getTimeToLiveSeconds(), TimeUnit.SECONDS)))
.build());
}
@Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
return cm -> {
<%_ if (authenticationType === 'oauth2' && applicationType === 'microservice') { _%>
cm.createCache("oAuth2Authentication", jcacheConfiguration);
<%_ } _%>
<%_ if (!skipUserManagement || (authenticationType === 'oauth2' && applicationType === 'monolith')) { _%>
cm.createCache("users", jcacheConfiguration);
cm.createCache(<%=packageName%>.domain.User.class.getName(), jcacheConfiguration);
cm.createCache(<%=packageName%>.domain.Authority.class.getName(), jcacheConfiguration);
cm.createCache(<%=packageName%>.domain.User.class.getName() + ".authorities", jcacheConfiguration);
<%_ if (authenticationType === 'session') { _%>
cm.createCache(<%=packageName%>.domain.PersistentToken.class.getName(), jcacheConfiguration);
cm.createCache(<%=packageName%>.domain.User.class.getName() + ".persistentTokens", jcacheConfiguration);
<%_ } _%>
<%_ if (enableSocialSignIn) { _%>
cm.createCache(<%=packageName%>.domain.SocialUserConnection.class.getName(), jcacheConfiguration);
<%_ } _%>
<%_ } _%>
// jhipster-needle-ehcache-add-entry
};
}
<%_ } _%>
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
private final Environment env;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
private final ServerProperties serverProperties;
private final DiscoveryClient discoveryClient;
private Registration registration;
<%_ } _%>
public CacheConfiguration(<% if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { %>Environment env<% if (serviceDiscoveryType === 'eureka') { %>, ServerProperties serverProperties, DiscoveryClient discoveryClient<% } } %>) {
this.env = env;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
this.serverProperties = serverProperties;
this.discoveryClient = discoveryClient;
<%_ } _%>
}
<%_ if (serviceDiscoveryType === 'eureka') { _%>
@Autowired(required = false)
public void setRegistration(Registration registration) {
this.registration = registration;
}
<%_ } _%>
@PreDestroy
public void destroy() {
log.info("Closing Cache Manager");
Hazelcast.shutdownAll();
}
@Bean
public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
log.debug("Starting HazelcastCacheManager");
CacheManager cacheManager = new com.hazelcast.spring.cache.HazelcastCacheManager(hazelcastInstance);
return cacheManager;
}
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
log.debug("Configuring Hazelcast");
HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("<%=baseName%>");
if (hazelCastInstance != null) {
log.debug("Hazelcast already initialized");
return hazelCastInstance;
}
Config config = new Config();
config.setInstanceName("<%=baseName%>");
<%_ if (serviceDiscoveryType === 'eureka') { _%>
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
if (this.registration == null) {
log.warn("No discovery service is set up, Hazelcast cannot create a cluster.");
} else {
// The serviceId is by default the application's name, see Spring Boot's eureka.instance.appname property
String serviceId = registration.getServiceId();
log.debug("Configuring Hazelcast clustering for instanceId: {}", serviceId);
// In development, everything goes through 127.0.0.1, with a different port
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
log.debug("Application is running with the \"dev\" profile, Hazelcast " +
"cluster will only work with localhost instances");
System.setProperty("hazelcast.local.localAddress", "127.0.0.1");
config.getNetworkConfig().setPort(serverProperties.getPort() + 5701);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) {
String clusterMember = "127.0.0.1:" + (instance.getPort() + 5701);
log.debug("Adding Hazelcast (dev) cluster member " + clusterMember);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember);
}
} else { // Production configuration, one host per instance all using port 5701
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) {
String clusterMember = instance.getHost() + ":5701";
log.debug("Adding Hazelcast (prod) cluster member " + clusterMember);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember);
}
}
}
<%_ } else { _%>
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().setPortAutoIncrement(true);
// In development, remove multicast auto-configuration
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
System.setProperty("hazelcast.local.localAddress", "127.0.0.1");
config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
}
<%_ } _%>
config.getMapConfigs().put("default", initializeDefaultMapConfig());
// Full reference is available at: http://docs.hazelcast.org/docs/management-center/3.9/manual/html/Deploying_and_Starting.html
config.setManagementCenterConfig(initializeDefaultManagementCenterConfig(jHipsterProperties));
<%_ if (cacheProvider === 'hazelcast') { _%>
config.getMapConfigs().put("<%=packageName%>.domain.*", initializeDomainMapConfig(jHipsterProperties));
<%_ } _%>
<%_ if (clusteredHttpSession === 'hazelcast') { _%>
config.getMapConfigs().put("clustered-http-sessions", initializeClusteredSession(jHipsterProperties));
<%_ } _%>
return Hazelcast.newHazelcastInstance(config);
}
private ManagementCenterConfig initializeDefaultManagementCenterConfig(JHipsterProperties jHipsterProperties) {
ManagementCenterConfig managementCenterConfig = new ManagementCenterConfig();
managementCenterConfig.setEnabled(jHipsterProperties.getCache().getHazelcast().getManagementCenter().isEnabled());
managementCenterConfig.setUrl(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUrl());
managementCenterConfig.setUpdateInterval(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUpdateInterval());
return managementCenterConfig;
}
private MapConfig initializeDefaultMapConfig() {
MapConfig mapConfig = new MapConfig();
/*
Number of backups. If 1 is set as the backup-count for example,
then all entries of the map will be copied to another JVM for
fail-safety. Valid numbers are 0 (no backup), 1, 2, 3.
*/
mapConfig.setBackupCount(0);
/*
Valid values are:
NONE (no eviction),
LRU (Least Recently Used),
LFU (Least Frequently Used).
NONE is the default.
*/
mapConfig.setEvictionPolicy(EvictionPolicy.LRU);
/*
Maximum size of the map. When max size is reached,
map is evicted based on the policy defined.
Any integer between 0 and Integer.MAX_VALUE. 0 means
Integer.MAX_VALUE. Default is 0.
*/
mapConfig.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE));
return mapConfig;
}
<%_ if (cacheProvider === 'hazelcast') { _%>
private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds());
return mapConfig;
}
<%_ } _%>
<%_ if (clusteredHttpSession === 'hazelcast') { _%>
private MapConfig initializeClusteredSession(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
mapConfig.setBackupCount(jHipsterProperties.getCache().getHazelcast().getBackupCount());
mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds());
return mapConfig;
}
/**
* Used by Spring Security, to get events from Hazelcast.
*
* @return the session registry
*/
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
<%_ } _%>
<%_ } _%>
<%_ if (cacheProvider === 'infinispan') { _%>
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
// Initialize the cache in a non Spring-managed bean
private static EmbeddedCacheManager cacheManager;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
private DiscoveryClient discoveryClient;
private Registration registration;
@Autowired(required = false)
public void setRegistration(Registration registration) {
this.registration = registration;
}
@Autowired(required = false)
public void setDiscoveryClient(DiscoveryClient discoveryClient) {
this.discoveryClient = discoveryClient;
}
<%_ } _%>
public static EmbeddedCacheManager getCacheManager(){
return cacheManager;
}
public static void setCacheManager(EmbeddedCacheManager cacheManager) {
CacheConfiguration.cacheManager = cacheManager;
}
/**
* Inject a {@link org.infinispan.configuration.global.GlobalConfiguration GlobalConfiguration} for Infinispan cache.
* <p>
* If the JHipster Registry is enabled, then the host list will be populated
* from Eureka.
*
* <p>
* If the JHipster Registry is not enabled, host discovery will be based on
* the default transport settings defined in the 'config-file' packaged within
* the Jar. The 'config-file' can be overridden using the application property
* <i>jhipster.cache.inifnispan.config-file</i>
*
* <p>
* If the JHipster Registry is not defined, you have the choice of 'config-file'
* based on the underlying platform for hosts discovery. Infinispan
* supports discovery natively for most of the platforms like Kubernets/OpenShift,
* AWS, Azure and Google.
*
*/
@Bean
public InfinispanGlobalConfigurer globalConfiguration(JHipsterProperties jHipsterProperties) {
log.info("Defining Infinispan Global Configuration");
<%_ if (serviceDiscoveryType === 'eureka') { _%>
if(this.registration == null) { // if registry is not defined, use native discovery
log.warn("No discovery service is set up, Infinispan will use default discovery for cluster formation");
return () -> GlobalConfigurationBuilder
.defaultClusteredBuilder().transport().defaultTransport()
.addProperty("configurationFile", jHipsterProperties.getCache().getInfinispan().getConfigFile())
.clusterName("infinispan-<%=baseName%>-cluster").globalJmxStatistics()
.enabled(jHipsterProperties.getCache().getInfinispan().isStatsEnabled())
.allowDuplicateDomains(true).build();
}
return () -> GlobalConfigurationBuilder
.defaultClusteredBuilder().transport().transport(new JGroupsTransport(getTransportChannel()))
.clusterName("infinispan-<%=baseName%>-cluster").globalJmxStatistics()
.enabled(jHipsterProperties.getCache().getInfinispan().isStatsEnabled())
.allowDuplicateDomains(true).build();
<%_ }else { _%>
return () -> GlobalConfigurationBuilder
.defaultClusteredBuilder().transport().defaultTransport()
.addProperty("configurationFile", jHipsterProperties.getCache().getInfinispan().getConfigFile())
.clusterName("infinispan-<%=baseName%>-cluster").globalJmxStatistics()
.enabled(jHipsterProperties.getCache().getInfinispan().isStatsEnabled())
.allowDuplicateDomains(true).build();
<%_ } _%>
}
/**
* Initialize cache configuration for Hibernate L2 cache and Spring Cache.
* <p>
* There are three different modes: local, distributed and replicated, and L2 cache options are pre-configured.
*
* <p>
* It supports both jCache and Spring cache abstractions.
* <p>
* Usage:
* <ol>
* <li>
* jCache:
* <pre class="code">@CacheResult(cacheName="dist-app-data") </pre>
* - for creating a distributed cache. In a similar way other cache names and options can be used
* </li>
* <li>
* Spring Cache:
* <pre class="code">@Cacheable(value = "repl-app-data") </pre>
* - for creating a replicated cache. In a similar way other cache names and options can be used
* </li>
* <li>
* Cache manager can also be injected through DI/CDI and data can be manipulated using Infinispan APIs,
* <pre class="code">
* @Autowired (or) @Inject
* private EmbeddedCacheManager cacheManager;
*
* void cacheSample(){
* cacheManager.getCache("dist-app-data").put("hi", "there");
* }
* </pre>
* </li>
* </ol>
*
*/
@Bean
public InfinispanCacheConfigurer cacheConfigurer(JHipsterProperties jHipsterProperties) {
log.info("Defining {} configuration", "app-data for local, replicated and distributed modes");
final JHipsterProperties.Cache.Infinispan cacheInfo = jHipsterProperties.getCache().getInfinispan();
return manager -> {
// initialize application cache
manager.defineConfiguration("local-app-data", new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.eviction().type(EvictionType.COUNT).size(cacheInfo.getLocal().getMaxEntries()).expiration()
.lifespan(cacheInfo.getLocal().getTimeToLiveSeconds(), TimeUnit.MINUTES).build());
manager.defineConfiguration("dist-app-data", new ConfigurationBuilder()
.clustering().cacheMode(CacheMode.DIST_SYNC).hash().numOwners(cacheInfo.getDistributed().getInstanceCount())
.jmxStatistics().enabled(cacheInfo.isStatsEnabled()).eviction()
.type(EvictionType.COUNT).size(cacheInfo.getDistributed().getMaxEntries()).expiration().lifespan(cacheInfo.getDistributed()
.getTimeToLiveSeconds(), TimeUnit.MINUTES).build());
manager.defineConfiguration("repl-app-data", new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_SYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.eviction().type(EvictionType.COUNT).size(cacheInfo.getReplicated()
.getMaxEntries()).expiration().lifespan(cacheInfo.getReplicated().getTimeToLiveSeconds(), TimeUnit.MINUTES).build());
// initialize Hibernate L2 cache
manager.defineConfiguration("entity", new ConfigurationBuilder().clustering().cacheMode(CacheMode.INVALIDATION_SYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("replicated-entity", new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_SYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("local-query", new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("replicated-query", new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_ASYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("timestamps", new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_ASYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("pending-puts", new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.simpleCache(true).transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL).expiration().maxIdle(60000).build());
setCacheManager(manager);
};
}
/**
* <p>
* Instance of {@link JCacheManager} with cache being managed by the underlying Infinispan layer. This helps to record stats
* info if enabled and the same is accessible through MBX:javax.cache,type=CacheStatistics.
*
* <p>
* jCache stats are at instance level. If you need stats at clustering level, then it needs to be retrieved from MBX:org.infinispan
*
*/
@Bean
public JCacheManager getJCacheManager(EmbeddedCacheManager cacheManager, JHipsterProperties jHipsterProperties){
return new InfinispanJCacheManager(Caching.getCachingProvider().getDefaultURI(), cacheManager,
Caching.getCachingProvider(), jHipsterProperties);
}
class InfinispanJCacheManager extends JCacheManager {
public InfinispanJCacheManager(URI uri, EmbeddedCacheManager cacheManager, CachingProvider provider,
JHipsterProperties jHipsterProperties) {
super(uri, cacheManager, provider);
// register individual caches to make the stats info available.
<%_ if (authenticationType === 'oauth2' && applicationType === 'microservice') { _%>
registerPredefinedCache("oAuth2Authentication", new JCache<Object, Object>(
cacheManager.getCache("oAuth2Authentication").getAdvancedCache(), this,
ConfigurationAdapter.create()));
<%_ } _%>
<%_ if (!skipUserManagement || authenticationType === 'oauth2') { _%>
registerPredefinedCache("users", new JCache<Object, Object>(
cacheManager.getCache("users").getAdvancedCache(), this,
ConfigurationAdapter.create()));
registerPredefinedCache(<%=packageName%>.domain.User.class.getName(), new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.User.class.getName()).getAdvancedCache(), this,
ConfigurationAdapter.create()));
registerPredefinedCache(<%=packageName%>.domain.Authority.class.getName(), new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.Authority.class.getName()).getAdvancedCache(), this,
ConfigurationAdapter.create()));
registerPredefinedCache(<%=packageName%>.domain.User.class.getName() + ".authorities", new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.User.class.getName() + ".authorities").getAdvancedCache(), this,
ConfigurationAdapter.create()));
<%_ if (authenticationType === 'session') { _%>
registerPredefinedCache(<%=packageName%>.domain.PersistentToken.class.getName(), new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.PersistentToken.class.getName()).getAdvancedCache(), this,
ConfigurationAdapter.create()));
registerPredefinedCache(<%=packageName%>.domain.User.class.getName() + ".persistentTokens", new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.User.class.getName() + ".persistentTokens").getAdvancedCache(), this,
ConfigurationAdapter.create()));
<%_ } _%>
<%_ if (enableSocialSignIn) { _%>
registerPredefinedCache(<%=packageName%>.domain.SocialUserConnection.class.getName(), new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.SocialUserConnection.class.getName()).getAdvancedCache(), this,
ConfigurationAdapter.create()));
<%_ } _%>
<%_ } _%>
// jhipster-needle-infinispan-add-entry
if (jHipsterProperties.getCache().getInfinispan().isStatsEnabled()) {
for (String cacheName : cacheManager.getCacheNames()) {
enableStatistics(cacheName, true);
}
}
}
}
<%_ if(serviceDiscoveryType === 'eureka') { _%>
/**
* TCP channel with the host details populated from the JHipster Registry.
* <p>
* MPING multicast is replaced with TCPPING with the host details discovered
* from registry and sends only unicast messages to the host list.
*/
private Channel getTransportChannel() {
JChannel channel = new JChannel(false);
List<PhysicalAddress> initialHosts = new ArrayList<>();
try {
for (ServiceInstance instance : discoveryClient.getInstances(registration.getServiceId())) {
String clusterMember = instance.getHost() + ":7800";
log.debug("Adding Infinispan cluster member " + clusterMember);
initialHosts.add(new IpAddress(clusterMember));
}
TCP tcp = new TCP();
tcp.setBindAddress(InetAddress.getLocalHost());
tcp.setBindPort(7800);
tcp.setThreadPoolMinThreads(2);
tcp.setThreadPoolMaxThreads(30);
tcp.setThreadPoolQueueEnabled(false);
tcp.setThreadPoolKeepAliveTime(60000);
tcp.setOOBThreadPoolMinThreads(2);
tcp.setOOBThreadPoolMaxThreads(200);
tcp.setOOBThreadPoolKeepAliveTime(60000);
tcp.setOOBThreadPoolQueueEnabled(false);
TCPPING tcpping = new TCPPING();
initialHosts.add(new IpAddress(InetAddress.getLocalHost(), 7800));
tcpping.setInitialHosts(initialHosts);
tcpping.setErgonomics(false);
tcpping.setPortRange(10);
tcpping.sendCacheInformation();
NAKACK2 nakack = new NAKACK2();
nakack.setUseMcastXmit(false);
nakack.setDiscardDeliveredMsgs(false);
MERGE3 merge = new MERGE3();
merge.setMinInterval(10000);
merge.setMaxInterval(30000);
FD_ALL fd = new FD_ALL();
fd.setTimeout(60000);
fd.setInterval(15000);
fd.setTimeoutCheckInterval(5000);
ProtocolStack stack = new ProtocolStack();
// Order shouldn't be changed
stack
.addProtocol(tcp)
.addProtocol(tcpping)
.addProtocol(merge)
.addProtocol(new FD_SOCK())
.addProtocol(fd)
.addProtocol(new VERIFY_SUSPECT())
.addProtocol(nakack)
.addProtocol(new UNICAST3())
.addProtocol(new STABLE())
.addProtocol(new GMS())
.addProtocol(new MFC())
.addProtocol(new FRAG2());
channel.setProtocolStack(stack);
stack.init();
} catch (Exception e) {
throw new BeanInitializationException("Cache (Infinispan protocol stack) configuration failed", e);
}
return channel;
}
<%_ } _%>
<%_ } _%>
}
| generators/server/templates/src/main/java/package/config/_CacheConfiguration.java | <%#
Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
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 <%=packageName%>.config;
<%_ if (cacheProvider === 'ehcache') { _%>
import io.github.jhipster.config.JHipsterProperties;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
import java.util.concurrent.TimeUnit;
<%_ } _%>
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import com.hazelcast.config.*;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.Hazelcast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
import org.springframework.beans.factory.annotation.Autowired;
<%_ } _%>
<%_ } _%>
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
<%_ if (cacheProvider === 'ehcache') { _%>
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
<%_ } _%>
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
<%_ if (serviceDiscoveryType === 'eureka') { _%>
import org.springframework.boot.autoconfigure.web.ServerProperties;
<%_ } _%>
import org.springframework.cache.CacheManager;
<%_ } _%>
import org.springframework.cache.annotation.EnableCaching;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
<%_ } _%>
import org.springframework.context.annotation.*;
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
import org.springframework.core.env.Environment;
<%_ } _%>
<%_ if (clusteredHttpSession === 'hazelcast') { _%>
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
<%_ } _%>
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
import javax.annotation.PreDestroy;
<%_ } _%>
<%_ if (cacheProvider === 'infinispan') { _%>
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import infinispan.autoconfigure.embedded.InfinispanCacheConfigurer;
import infinispan.autoconfigure.embedded.InfinispanGlobalConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.jhipster.config.JHipsterProperties;
import java.util.concurrent.TimeUnit;
import org.infinispan.eviction.EvictionType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.transaction.TransactionMode;
import infinispan.autoconfigure.embedded.InfinispanEmbeddedCacheManagerAutoConfiguration;
import org.infinispan.jcache.embedded.ConfigurationAdapter;
import org.infinispan.jcache.embedded.JCache;
import org.infinispan.jcache.embedded.JCacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
import java.net.URI;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
import org.springframework.beans.factory.annotation.Autowired;
import org.infinispan.remoting.transport.jgroups.JGroupsTransport;
import org.jgroups.Channel;
import org.jgroups.JChannel;
import org.jgroups.PhysicalAddress;
import org.jgroups.protocols.*;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.protocols.pbcast.NAKACK2;
import org.jgroups.protocols.pbcast.STABLE;
import org.jgroups.stack.IpAddress;
import org.jgroups.stack.ProtocolStack;
import java.net.InetAddress;
import org.springframework.beans.factory.BeanInitializationException;
import java.util.ArrayList;
import java.util.List;
<%_ } _%>
<%_ } _%>
@Configuration
@EnableCaching
@AutoConfigureAfter(value = { MetricsConfiguration.class })
@AutoConfigureBefore(value = { WebConfigurer.class<% if (databaseType === 'sql' || databaseType === 'mongodb') { %>, DatabaseConfiguration.class<% } %> })
<%_ if (cacheProvider === 'infinispan') { _%>
@Import(InfinispanEmbeddedCacheManagerAutoConfiguration.class)
<%_ } _%>
public class CacheConfiguration {
<%_ if (cacheProvider === 'ehcache') { _%>
private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;
public CacheConfiguration(JHipsterProperties jHipsterProperties) {
JHipsterProperties.Cache.Ehcache ehcache =
jHipsterProperties.getCache().getEhcache();
jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
ResourcePoolsBuilder.heap(ehcache.getMaxEntries()))
.withExpiry(Expirations.timeToLiveExpiration(Duration.of(ehcache.getTimeToLiveSeconds(), TimeUnit.SECONDS)))
.build());
}
@Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
return cm -> {
<%_ if (authenticationType === 'oauth2' && applicationType === 'microservice') { _%>
cm.createCache("oAuth2Authentication", jcacheConfiguration);
<%_ } _%>
<%_ if (!skipUserManagement || (authenticationType === 'oauth2' && applicationType === 'monolith')) { _%>
cm.createCache("users", jcacheConfiguration);
cm.createCache(<%=packageName%>.domain.User.class.getName(), jcacheConfiguration);
cm.createCache(<%=packageName%>.domain.Authority.class.getName(), jcacheConfiguration);
cm.createCache(<%=packageName%>.domain.User.class.getName() + ".authorities", jcacheConfiguration);
<%_ if (authenticationType === 'session') { _%>
cm.createCache(<%=packageName%>.domain.PersistentToken.class.getName(), jcacheConfiguration);
cm.createCache(<%=packageName%>.domain.User.class.getName() + ".persistentTokens", jcacheConfiguration);
<%_ } _%>
<%_ if (enableSocialSignIn) { _%>
cm.createCache(<%=packageName%>.domain.SocialUserConnection.class.getName(), jcacheConfiguration);
<%_ } _%>
<%_ } _%>
// jhipster-needle-ehcache-add-entry
};
}
<%_ } _%>
<%_ if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { _%>
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
private final Environment env;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
private final ServerProperties serverProperties;
private final DiscoveryClient discoveryClient;
private Registration registration;
<%_ } _%>
public CacheConfiguration(<% if (cacheProvider === 'hazelcast' || clusteredHttpSession === 'hazelcast') { %>Environment env<% if (serviceDiscoveryType === 'eureka') { %>, ServerProperties serverProperties, DiscoveryClient discoveryClient<% } } %>) {
this.env = env;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
this.serverProperties = serverProperties;
this.discoveryClient = discoveryClient;
<%_ } _%>
}
<%_ if (serviceDiscoveryType === 'eureka') { _%>
@Autowired(required = false)
public void setRegistration(Registration registration) {
this.registration = registration;
}
<%_ } _%>
@PreDestroy
public void destroy() {
log.info("Closing Cache Manager");
Hazelcast.shutdownAll();
}
@Bean
public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
log.debug("Starting HazelcastCacheManager");
CacheManager cacheManager = new com.hazelcast.spring.cache.HazelcastCacheManager(hazelcastInstance);
return cacheManager;
}
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
log.debug("Configuring Hazelcast");
HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("<%=baseName%>");
if (hazelCastInstance != null) {
log.debug("Hazelcast already initialized");
return hazelCastInstance;
}
Config config = new Config();
config.setInstanceName("<%=baseName%>");
<%_ if (serviceDiscoveryType === 'eureka') { _%>
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
if (this.registration == null) {
log.warn("No discovery service is set up, Hazelcast cannot create a cluster.");
} else {
// The serviceId is by default the application's name, see Spring Boot's eureka.instance.appname property
String serviceId = registration.getServiceId();
log.debug("Configuring Hazelcast clustering for instanceId: {}", serviceId);
// In development, everything goes through 127.0.0.1, with a different port
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
log.debug("Application is running with the \"dev\" profile, Hazelcast " +
"cluster will only work with localhost instances");
System.setProperty("hazelcast.local.localAddress", "127.0.0.1");
config.getNetworkConfig().setPort(serverProperties.getPort() + 5701);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) {
String clusterMember = "127.0.0.1:" + (instance.getPort() + 5701);
log.debug("Adding Hazelcast (dev) cluster member " + clusterMember);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember);
}
} else { // Production configuration, one host per instance all using port 5701
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) {
String clusterMember = instance.getHost() + ":5701";
log.debug("Adding Hazelcast (prod) cluster member " + clusterMember);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember);
}
}
}
<%_ } else { _%>
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().setPortAutoIncrement(true);
// In development, remove multicast auto-configuration
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
System.setProperty("hazelcast.local.localAddress", "127.0.0.1");
config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
}
<%_ } _%>
config.getMapConfigs().put("default", initializeDefaultMapConfig());
// Full reference is available at: http://docs.hazelcast.org/docs/management-center/3.9/manual/html/Deploying_and_Starting.html
config.setManagementCenterConfig(initializeDefaultManagementCenterConfig(jHipsterProperties));
<%_ if (cacheProvider === 'hazelcast') { _%>
config.getMapConfigs().put("<%=packageName%>.domain.*", initializeDomainMapConfig(jHipsterProperties));
<%_ } _%>
<%_ if (clusteredHttpSession === 'hazelcast') { _%>
config.getMapConfigs().put("clustered-http-sessions", initializeClusteredSession(jHipsterProperties));
<%_ } _%>
return Hazelcast.newHazelcastInstance(config);
}
private ManagementCenterConfig initializeDefaultManagementCenterConfig(JHipsterProperties jHipsterProperties) {
ManagementCenterConfig managementCenterConfig = new ManagementCenterConfig();
managementCenterConfig.setEnabled(jHipsterProperties.getCache().getHazelcast().getManagementCenter().isEnabled());
managementCenterConfig.setUrl(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUrl());
managementCenterConfig.setUpdateInterval(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUpdateInterval());
return managementCenterConfig;
}
private MapConfig initializeDefaultMapConfig() {
MapConfig mapConfig = new MapConfig();
/*
Number of backups. If 1 is set as the backup-count for example,
then all entries of the map will be copied to another JVM for
fail-safety. Valid numbers are 0 (no backup), 1, 2, 3.
*/
mapConfig.setBackupCount(0);
/*
Valid values are:
NONE (no eviction),
LRU (Least Recently Used),
LFU (Least Frequently Used).
NONE is the default.
*/
mapConfig.setEvictionPolicy(EvictionPolicy.LRU);
/*
Maximum size of the map. When max size is reached,
map is evicted based on the policy defined.
Any integer between 0 and Integer.MAX_VALUE. 0 means
Integer.MAX_VALUE. Default is 0.
*/
mapConfig.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE));
return mapConfig;
}
<%_ if (cacheProvider === 'hazelcast') { _%>
private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds());
return mapConfig;
}
<%_ } _%>
<%_ if (clusteredHttpSession === 'hazelcast') { _%>
private MapConfig initializeClusteredSession(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
mapConfig.setBackupCount(jHipsterProperties.getCache().getHazelcast().getBackupCount());
mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds());
return mapConfig;
}
/**
* Used by Spring Security, to get events from Hazelcast.
*
* @return the session registry
*/
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
<%_ } _%>
<%_ } _%>
<%_ if (cacheProvider === 'infinispan') { _%>
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
// Initialize the cache in a non Spring-managed bean
private static EmbeddedCacheManager cacheManager;
<%_ if (serviceDiscoveryType === 'eureka') { _%>
private DiscoveryClient discoveryClient;
private Registration registration;
@Autowired(required = false)
public void setRegistration(Registration registration) {
this.registration = registration;
}
@Autowired(required = false)
public void setDiscoveryClient(DiscoveryClient discoveryClient) {
this.discoveryClient = discoveryClient;
}
<%_ } _%>
public static EmbeddedCacheManager getCacheManager(){
return cacheManager;
}
public static void setCacheManager(EmbeddedCacheManager cacheManager) {
CacheConfiguration.cacheManager = cacheManager;
}
/**
* Inject a {@link org.infinispan.configuration.global.GlobalConfiguration GlobalConfiguration} for Infinispan cache.
* <p>
* If the JHipster Registry is enabled, then the host list will be populated
* from Eureka.
*
* <p>
* If the JHipster Registry is not enabled, host discovery will be based on
* the default transport settings defined in the 'config-file' packaged within
* the Jar. The 'config-file' can be overridden using the application property
* <i>jhipster.cache.inifnispan.config-file</i>
*
* <p>
* If the JHipster Registry is not defined, you have the choice of 'config-file'
* based on the underlying platform for hosts discovery. Infinispan
* supports discovery natively for most of the platforms like Kubernets/OpenShift,
* AWS, Azure and Google.
*
*/
@Bean
public InfinispanGlobalConfigurer globalConfiguration(JHipsterProperties jHipsterProperties) {
log.info("Defining Infinispan Global Configuration");
<%_ if (serviceDiscoveryType === 'eureka') { _%>
if(this.registration == null) { // if registry is not defined, use native discovery
log.warn("No discovery service is set up, Infinispan will use default discovery for cluster formation");
return () -> GlobalConfigurationBuilder
.defaultClusteredBuilder().transport().defaultTransport()
.addProperty("configurationFile", jHipsterProperties.getCache().getInfinispan().getConfigFile())
.clusterName("infinispan-<%=baseName%>-cluster").globalJmxStatistics()
.enabled(jHipsterProperties.getCache().getInfinispan().isStatsEnabled())
.allowDuplicateDomains(true).build();
}
return () -> GlobalConfigurationBuilder
.defaultClusteredBuilder().transport().transport(new JGroupsTransport(getTransportChannel()))
.clusterName("infinispan-<%=baseName%>-cluster").globalJmxStatistics()
.enabled(jHipsterProperties.getCache().getInfinispan().isStatsEnabled())
.allowDuplicateDomains(true).build();
<%_ }else { _%>
return () -> GlobalConfigurationBuilder
.defaultClusteredBuilder().transport().defaultTransport()
.addProperty("configurationFile", jHipsterProperties.getCache().getInfinispan().getConfigFile())
.clusterName("infinispan-<%=baseName%>-cluster").globalJmxStatistics()
.enabled(jHipsterProperties.getCache().getInfinispan().isStatsEnabled())
.allowDuplicateDomains(true).build();
<%_ } _%>
}
/**
* Initialize cache configuration for Hibernate L2 cache and Spring Cache.
* <p>
* There are three different modes: local, distributed and replicated, and L2 cache options are pre-configured.
*
* <p>
* It supports both jCache and Spring cache abstractions.
* <p>
* Usage:
* <ol>
* <li>
* jCache:
* <pre class="code">@CacheResult(cacheName="dist-app-data") </pre>
* - for creating a distributed cache. In a similar way other cache names and options can be used
* </li>
* <li>
* Spring Cache:
* <pre class="code">@Cacheable(value = "repl-app-data") </pre>
* - for creating a replicated cache. In a similar way other cache names and options can be used
* </li>
* <li>
* Cache manager can also be injected through DI/CDI and data can be manipulated using Infinispan APIs,
* <pre class="code">
* @Autowired (or) @Inject
* private EmbeddedCacheManager cacheManager;
*
* void cacheSample(){
* cacheManager.getCache("dist-app-data").put("hi", "there");
* }
* </pre>
* </li>
* </ol>
*
*/
@Bean
public InfinispanCacheConfigurer cacheConfigurer(JHipsterProperties jHipsterProperties) {
log.info("Defining {} configuration", "app-data for local, replicated and distributed modes");
final JHipsterProperties.Cache.Infinispan cacheInfo = jHipsterProperties.getCache().getInfinispan();
return manager -> {
// initialize application cache
manager.defineConfiguration("local-app-data", new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.eviction().type(EvictionType.COUNT).size(cacheInfo.getLocal().getMaxEntries()).expiration()
.lifespan(cacheInfo.getLocal().getTimeToLiveSeconds(), TimeUnit.MINUTES).build());
manager.defineConfiguration("dist-app-data", new ConfigurationBuilder()
.clustering().cacheMode(CacheMode.DIST_SYNC).hash().numOwners(cacheInfo.getDistributed().getInstanceCount())
.jmxStatistics().enabled(cacheInfo.isStatsEnabled()).eviction()
.type(EvictionType.COUNT).size(cacheInfo.getDistributed().getMaxEntries()).expiration().lifespan(cacheInfo.getDistributed()
.getTimeToLiveSeconds(), TimeUnit.MINUTES).build());
manager.defineConfiguration("repl-app-data", new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_SYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.eviction().type(EvictionType.COUNT).size(cacheInfo.getReplicated()
.getMaxEntries()).expiration().lifespan(cacheInfo.getReplicated().getTimeToLiveSeconds(), TimeUnit.MINUTES).build());
// initilaize Hibernate L2 cache
manager.defineConfiguration("entity", new ConfigurationBuilder().clustering().cacheMode(CacheMode.INVALIDATION_SYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("replicated-entity", new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_SYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("local-query", new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("replicated-query", new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_ASYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("timestamps", new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_ASYNC)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build());
manager.defineConfiguration("pending-puts", new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL)
.jmxStatistics().enabled(cacheInfo.isStatsEnabled())
.simpleCache(true).transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL).expiration().maxIdle(60000).build());
setCacheManager(manager);
};
}
/**
* <p>
* Instance of {@link JCacheManager} with cache being managed by the underlying Infinispan layer. This helps to record stats
* info if enabled and the same is accessible through MBX:javax.cache,type=CacheStatistics.
*
* <p>
* jCache stats are at instance level. If you need stats at clustering level, then it needs to be retrieved from MBX:org.infinispan
*
*/
@Bean
public JCacheManager getJCacheManager(EmbeddedCacheManager cacheManager, JHipsterProperties jHipsterProperties){
return new InfinispanJCacheManager(Caching.getCachingProvider().getDefaultURI(), cacheManager,
Caching.getCachingProvider(), jHipsterProperties);
}
class InfinispanJCacheManager extends JCacheManager {
public InfinispanJCacheManager(URI uri, EmbeddedCacheManager cacheManager, CachingProvider provider,
JHipsterProperties jHipsterProperties) {
super(uri, cacheManager, provider);
// register individual caches to make the stats info available.
<%_ if (authenticationType === 'oauth2' && applicationType === 'microservice') { _%>
registerPredefinedCache("oAuth2Authentication", new JCache<Object, Object>(
cacheManager.getCache("oAuth2Authentication").getAdvancedCache(), this,
ConfigurationAdapter.create()));
<%_ } _%>
<%_ if (!skipUserManagement || authenticationType === 'oauth2') { _%>
registerPredefinedCache("users", new JCache<Object, Object>(
cacheManager.getCache("users").getAdvancedCache(), this,
ConfigurationAdapter.create()));
registerPredefinedCache(<%=packageName%>.domain.User.class.getName(), new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.User.class.getName()).getAdvancedCache(), this,
ConfigurationAdapter.create()));
registerPredefinedCache(<%=packageName%>.domain.Authority.class.getName(), new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.Authority.class.getName()).getAdvancedCache(), this,
ConfigurationAdapter.create()));
registerPredefinedCache(<%=packageName%>.domain.User.class.getName() + ".authorities", new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.User.class.getName() + ".authorities").getAdvancedCache(), this,
ConfigurationAdapter.create()));
<%_ if (authenticationType === 'session') { _%>
registerPredefinedCache(<%=packageName%>.domain.PersistentToken.class.getName(), new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.PersistentToken.class.getName()).getAdvancedCache(), this,
ConfigurationAdapter.create()));
registerPredefinedCache(<%=packageName%>.domain.User.class.getName() + ".persistentTokens", new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.User.class.getName() + ".persistentTokens").getAdvancedCache(), this,
ConfigurationAdapter.create()));
<%_ } _%>
<%_ if (enableSocialSignIn) { _%>
registerPredefinedCache(<%=packageName%>.domain.SocialUserConnection.class.getName(), new JCache<Object, Object>(
cacheManager.getCache(<%=packageName%>.domain.SocialUserConnection.class.getName()).getAdvancedCache(), this,
ConfigurationAdapter.create()));
<%_ } _%>
<%_ } _%>
// jhipster-needle-infinispan-add-entry
if (jHipsterProperties.getCache().getInfinispan().isStatsEnabled()) {
for (String cacheName : cacheManager.getCacheNames()) {
enableStatistics(cacheName, true);
}
}
}
}
<%_ if(serviceDiscoveryType === 'eureka') { _%>
/**
* TCP channel with the host details populated from the JHipster Registry.
* <p>
* MPING multicast is replaced with TCPPING with the host details discovered
* from registry and sends only unicast messages to the host list.
*/
private Channel getTransportChannel() {
JChannel channel = new JChannel(false);
List<PhysicalAddress> initialHosts = new ArrayList<>();
try {
for (ServiceInstance instance : discoveryClient.getInstances(registration.getServiceId())) {
String clusterMember = instance.getHost() + ":7800";
log.debug("Adding Infinispan cluster member " + clusterMember);
initialHosts.add(new IpAddress(clusterMember));
}
TCP tcp = new TCP();
tcp.setBindAddress(InetAddress.getLocalHost());
tcp.setBindPort(7800);
tcp.setThreadPoolMinThreads(2);
tcp.setThreadPoolMaxThreads(30);
tcp.setThreadPoolQueueEnabled(false);
tcp.setThreadPoolKeepAliveTime(60000);
tcp.setOOBThreadPoolMinThreads(2);
tcp.setOOBThreadPoolMaxThreads(200);
tcp.setOOBThreadPoolKeepAliveTime(60000);
tcp.setOOBThreadPoolQueueEnabled(false);
TCPPING tcpping = new TCPPING();
initialHosts.add(new IpAddress(InetAddress.getLocalHost(), 7800));
tcpping.setInitialHosts(initialHosts);
tcpping.setErgonomics(false);
tcpping.setPortRange(10);
tcpping.sendCacheInformation();
NAKACK2 nakack = new NAKACK2();
nakack.setUseMcastXmit(false);
nakack.setDiscardDeliveredMsgs(false);
MERGE3 merge = new MERGE3();
merge.setMinInterval(10000);
merge.setMaxInterval(30000);
FD_ALL fd = new FD_ALL();
fd.setTimeout(60000);
fd.setInterval(15000);
fd.setTimeoutCheckInterval(5000);
ProtocolStack stack = new ProtocolStack();
// Order shouldn't be changed
stack
.addProtocol(tcp)
.addProtocol(tcpping)
.addProtocol(merge)
.addProtocol(new FD_SOCK())
.addProtocol(fd)
.addProtocol(new VERIFY_SUSPECT())
.addProtocol(nakack)
.addProtocol(new UNICAST3())
.addProtocol(new STABLE())
.addProtocol(new GMS())
.addProtocol(new MFC())
.addProtocol(new FRAG2());
channel.setProtocolStack(stack);
stack.init();
} catch (Exception e) {
throw new BeanInitializationException("Cache (Infinispan protocol stack) configuration failed", e);
}
return channel;
}
<%_ } _%>
<%_ } _%>
}
| Wording
| generators/server/templates/src/main/java/package/config/_CacheConfiguration.java | Wording | <ide><path>enerators/server/templates/src/main/java/package/config/_CacheConfiguration.java
<ide> .eviction().type(EvictionType.COUNT).size(cacheInfo.getReplicated()
<ide> .getMaxEntries()).expiration().lifespan(cacheInfo.getReplicated().getTimeToLiveSeconds(), TimeUnit.MINUTES).build());
<ide>
<del> // initilaize Hibernate L2 cache
<add> // initialize Hibernate L2 cache
<ide> manager.defineConfiguration("entity", new ConfigurationBuilder().clustering().cacheMode(CacheMode.INVALIDATION_SYNC)
<ide> .jmxStatistics().enabled(cacheInfo.isStatsEnabled())
<ide> .locking().concurrencyLevel(1000).lockAcquisitionTimeout(15000).build()); |
|
JavaScript | apache-2.0 | 281284d22748768310b619da187335b711dc547c | 0 | input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus | import { action } from 'mobx';
import _ from 'lodash';
import type { appState } from '../state/index';
import Wallet from '../domain/Wallet';
import WalletTransaction from '../domain/WalletTransaction';
import api from '../api';
export default class WalletsController {
state: appState;
constructor(state: appState) {
this.state = state;
}
@action async loadWallets() {
const { activeWallet, account } = this.state;
activeWallet.isLoading = true;
try {
const wallets = await api.loadWallets();
for (const wallet of wallets) {
const newWallet = new Wallet(wallet);
account.addWallet(newWallet);
if (newWallet.lastUsed) this.setActiveWallet(newWallet);
}
activeWallet.isLoading = false;
} catch (error) {
activeWallet.errorLoading = 'Error loading wallets'; // TODO: i18n
}
}
@action async loadActiveWalletTransactions() {
const { activeWallet } = this.state;
const { wallet } = activeWallet;
if (!wallet === null) throw new Error('No active wallet');
try {
const transactions = await api.loadWalletTransactions({
address: wallet.address
});
wallet.transactions.clear();
for (const transaction of transactions) {
wallet.addTransaction(new WalletTransaction(transaction));
}
} catch (error) {
activeWallet.errorLoadingTransactions = error;
// TODO: handling errors from backend and i18n
}
}
@action setActiveWallet(walletId: string|Wallet) {
let wallet = walletId;
if (_.isString(walletId)) {
wallet = _.find(this.state.account.wallets, { address: wallet });
}
const activeWallet = this.state.activeWallet;
if (wallet === activeWallet.wallet) return;
activeWallet.wallet = wallet;
this.loadActiveWalletTransactions();
if (this.state.router) this.state.router.transitionTo(`/wallet/${wallet.address}/home`);
}
@action async sendMoney(transactionDetails: {
receiver: string,
amount: string,
description: ?string
}) {
const { activeWallet } = this.state;
const { wallet } = activeWallet;
try {
const transaction = await api.sendMoney({
...transactionDetails,
amount: parseFloat(transactionDetails.amount),
sender: wallet.address,
currency: wallet.currency
});
wallet.addTransaction(new WalletTransaction(transaction));
if (this.state.router) this.state.router.transitionTo(`/wallet/${wallet.address}/home`);
} catch (error) {
activeWallet.errorSendingMoney = error;
}
}
@action async createPersonalWallet(newWalletData: { name: string, currency: string}) {
try {
const createdWallet = await api.createPersonalWallet(newWalletData);
const newWallet = new Wallet(createdWallet);
this.state.account.addWallet(newWallet);
this.setActiveWallet(newWallet);
// TODO: Navigate to newly created wallet
} catch (error) {
this.state.activeWallet.errorCreating = error; // TODO: handling errors from backend and i18n
}
}
}
| app/controllers/WalletsController.js | import { action } from 'mobx';
import _ from 'lodash';
import type { appState } from '../state/index';
import Wallet from '../domain/Wallet';
import WalletTransaction from '../domain/WalletTransaction';
import api from '../api';
export default class WalletsController {
state: appState;
constructor(state: appState) {
this.state = state;
}
@action async loadWallets() {
const { activeWallet, account } = this.state;
activeWallet.isLoading = true;
try {
const wallets = await api.loadWallets();
for (const wallet of wallets) {
const newWallet = new Wallet(wallet);
account.addWallet(newWallet);
if (newWallet.lastUsed) this.setActiveWallet(newWallet);
}
activeWallet.isLoading = false;
} catch (error) {
activeWallet.errorLoading = 'Error loading wallets'; // TODO: i18n
}
}
@action async loadActiveWalletTransactions() {
const { activeWallet } = this.state;
const { wallet } = activeWallet;
if (!wallet === null) throw new Error('No active wallet');
try {
const transactions = await api.loadWalletTransactions({
address: wallet.address
});
for (const transaction of transactions) {
wallet.addTransaction(new WalletTransaction(transaction));
}
} catch (error) {
activeWallet.errorLoadingTransactions = error;
// TODO: handling errors from backend and i18n
}
}
@action setActiveWallet(walletId: string|Wallet) {
let wallet = walletId;
if (_.isString(walletId)) {
wallet = _.find(this.state.account.wallets, { address: wallet });
}
const activeWallet = this.state.activeWallet;
if (wallet === activeWallet.wallet) return;
activeWallet.wallet = wallet;
this.loadActiveWalletTransactions();
if (this.state.router) this.state.router.transitionTo(`/wallet/${wallet.address}/home`);
}
@action async sendMoney(transactionDetails: {
receiver: string,
amount: string,
description: ?string
}) {
const { activeWallet } = this.state;
const { wallet } = activeWallet;
try {
const transaction = await api.sendMoney({
...transactionDetails,
amount: parseFloat(transactionDetails.amount),
sender: wallet.address,
currency: wallet.currency
});
wallet.addTransaction(new WalletTransaction(transaction));
if (this.state.router) this.state.router.transitionTo(`/wallet/${wallet.address}/home`);
} catch (error) {
activeWallet.errorSendingMoney = error;
}
}
@action async createPersonalWallet(newWalletData: { name: string, currency: string}) {
try {
const createdWallet = await api.createPersonalWallet(newWalletData);
const newWallet = new Wallet(createdWallet);
this.state.account.addWallet(newWallet);
this.setActiveWallet(newWallet);
// TODO: Navigate to newly created wallet
} catch (error) {
this.state.activeWallet.errorCreating = error; // TODO: handling errors from backend and i18n
}
}
}
| Fix loading duplicate wallet transactions
| app/controllers/WalletsController.js | Fix loading duplicate wallet transactions | <ide><path>pp/controllers/WalletsController.js
<ide> const transactions = await api.loadWalletTransactions({
<ide> address: wallet.address
<ide> });
<add> wallet.transactions.clear();
<ide> for (const transaction of transactions) {
<ide> wallet.addTransaction(new WalletTransaction(transaction));
<ide> } |
|
Java | apache-2.0 | adf51f6cb9cd3bdfc613387ba015031b5d720fd4 | 0 | epam-debrecen-rft-2015/atsy,epam-debrecen-rft-2015/atsy,epam-debrecen-rft-2015/atsy | package com.epam.rft.atsy.persistence.entities;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Entity
@Table(name = "state_flow", schema = "atsy")
public class StateFlowEntity extends SuperEntity {
@OneToOne
@JoinColumn(name = "from_id")
private StatesEntity fromStateEntity;
@OneToOne
@JoinColumn(name = "to_id")
private StatesEntity toStateEntity;
@Builder
public StateFlowEntity(Long id, StatesEntity fromStateEntity, StatesEntity toStateEntity) {
super(id);
this.fromStateEntity = fromStateEntity;
this.toStateEntity = toStateEntity;
}
}
| persistence/src/main/java/com/epam/rft/atsy/persistence/entities/StateFlowEntity.java | package com.epam.rft.atsy.persistence.entities;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@Entity
@Table(name = "state_flow", schema = "atsy")
public class StateFlowEntity extends SuperEntity {
@OneToOne
@JoinColumn(name = "from_id")
private StatesEntity fromStateEntity;
@OneToOne
@JoinColumn(name = "to_id")
private StatesEntity toStateEntity;
@Builder
public StateFlowEntity(Long id, StatesEntity fromStateEntity, StatesEntity toStateEntity) {
super(id);
this.fromStateEntity = fromStateEntity;
this.toStateEntity = toStateEntity;
}
}
| fixed StateFlowRepositoryIT
| persistence/src/main/java/com/epam/rft/atsy/persistence/entities/StateFlowEntity.java | fixed StateFlowRepositoryIT | <ide><path>ersistence/src/main/java/com/epam/rft/atsy/persistence/entities/StateFlowEntity.java
<ide> @AllArgsConstructor
<ide> @EqualsAndHashCode(callSuper = true)
<ide> @ToString(callSuper = true)
<del>@Builder
<ide> @Entity
<ide> @Table(name = "state_flow", schema = "atsy")
<ide> public class StateFlowEntity extends SuperEntity { |
|
JavaScript | mit | 4c4774fa04b604f1635fb3538aa98c685a7de2cf | 0 | jorix/OL-FeaturePopups,jorix/OL-FeaturePopups | /* Copyright 2011-2012 Xavier Mamano, http://github.com/jorix/OL-FeaturePopups
* Published under MIT license. All rights reserved. */
/**
* requires OpenLayers/Control/SelectFeature.js
* requires OpenLayers/Lang.js
* requires OpenLayers/Popup.js
*/
/**
* Class: OpenLayers.Control.FeaturePopups
* The FeaturePopups control selects vector features from a given layers on
* click and hover and can show the feature attributes in a popups.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.FeaturePopups = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: mode
* To enable or disable the various behaviors of the control.
*
* Use bitwise operators and one or more of OpenLayers.Control.FeaturePopups:
* NONE - To not activate any particular behavior.
* CLOSE_ON_REMOVE -Popups will close when removing features in a layer,
* is ignored when used in conjunction with SAFE_SELECTION.
* SAFE_SELECTION - Features will remain selected even have been removed
* from the layer. Is useful when using <OpenLayers.Strategy.BBOX> with
* features with "fid" or when using <OpenLayers.Strategy.Cluster>.
* Using "BBOX" when a feature is added back to the layer will be
* re-selected automatically by "fid".
* CLOSE_ON_UNSELECT - Popups will close when unselect the feature.
* CLOSE_BOX - Display a close box inside the popups.
* UNSELECT_ON_CLOSE - To unselect all features when a popup is closed.
* DEFAULT - Includes default behaviors SAFE_SELECTION |
* CLOSE_ON_UNSELECT | CLOSE_BOX | UNSELECT_ON_CLOSE
*
* Default is <OpenLayers.Control.FeaturePopups.DEFAULT>.
*/
mode: null,
/**
* APIProperty: autoActivate
* {Boolean} Activate the control when it is added to a map. Default is
* true.
*/
autoActivate: true,
/**
* APIProperty: selectOptions
* {Object|null} Used to set non-default properties on SelectFeature control
* dedicated to select features. When using a null value the select
* features control is not created. The default is create the control.
*
* Default options other than SelectFeature control:
* - clickout: false
* - multipleKey: 'shiftKey'
* - toggleKey: 'shiftKey'
*
* Options ignored:
* - highlightOnly: always false.
* - box: always false (use <boxSelectionOptions>).
*/
selectOptions: null,
/**
* APIProperty: boxSelectionOptions
* {Object|null} Used to set non-default properties on
* <OpenLayers.Handler.Box> dedicated to select features by a box.
* When using a null value the handler is not created.
* The default is do not create the handler, so don't use box selection.
*
* Default options other than Box handler:
* - KeyMask: OpenLayers.Handler.MOD_CTRL
* - boxDivClassName: 'olHandlerBoxSelectFeature'
*/
boxSelectionOptions: null,
/**
* APIProperty: hoverOptions
* {Object|null} Used to set non-default properties on SelectFeature control
* dedicated to highlight features. When using a null value (or
* selectOptions.hover == true) the highlight features control is
* not created. The default is create the control.
*
* Options ignored:
* - hover: always true
* - highlightOnly: always true
* - box: always false (use <boxSelectionOptions>).
*/
hoverOptions: null,
/**
* APIProperty: popupHoverOptions
* {Object} Options used to create the popup manager for to highlight on
* to hover. See <FeaturePopups.Popup> constructor options for more
* details.
*
* Default options:
* popupClass - <OpenLayers.Popup.Anchored>
* followCursor - true
* anchor - {size: new OpenLayers.Size(15, 19), offset: new OpenLayers.Pixel(-1, -1)}
* relatedToClear - ["hoverList"]
*/
popupHoverOptions: null,
/**
* APIProperty: popupHoverListOptions
* {Object} Options used to create the popup manager for to highlight on
* to hover a cluster. See <FeaturePopups.Popup> constructor options
* for more details.
*
* Default options:
* popupClass - <OpenLayers.Popup.Anchored>
*
* Default options for internal use:
* followCursor - true
* anchor - {size: new OpenLayers.Size(15, 19), offset: new OpenLayers.Pixel(-1, -1)}
* relatedToClear - ["hover"]
*/
popupHoverListOptions: null,
/**
* APIProperty: popupSingleOptions
* {Object} Options used to create the popup manager for single selections.
* See <FeaturePopups.Popup> constructor options for more details.
*
* Default options:
* popupClass - <OpenLayers.Popup.FramedCloud>
*
* Default options for internal use:
* unselectOnClose - Depends on the <mode>
* closeBox - Depends on the <mode>
* observeItems - true
* relatedToClear: ["hover", "hoverList", "list", "listItem"]
*/
popupSingleOptions: null,
/**
* APIProperty: popupListOptions
* {Object} Options used to create the popup manager for multiple selections.
* See <FeaturePopups.Popup> constructor options for more details.
*
* Default options:
* popupClass - <OpenLayers.Popup.FramedCloud>
*
* Default options for internal use:
* unselectOnClose - Depends on the <mode>
* closeBox - Depends on the <mode>
* observeItems - true
* relatedToClear - ["hover", "hoverList", "single", "listItem"]
*/
popupListOptions: null,
/**
* APIProperty: popupListItemOptions
* {Object} Options used to create the popup manager for show a single item
* into a multiple selection. See <FeaturePopups.Popup> constructor
* options for more details.
*
* Default options:
* popupClass - <OpenLayers.Popup.FramedCloud>
*
* Default options for internal use:
* closeBox - Depends on the <mode>
*/
popupListItemOptions: null,
/**
* APIProperty: layerListTemplate
* Default is "<h2>${layer.name} - ${count}</h2><ul>${html}</ul>"
*/
layerListTemplate: "<h2>${layer.name} - ${count}</h2><ul>${html}</ul>",
/**
* APIProperty: hoverClusterTemplate
* Default is "Cluster with ${cluster.length} features<br>on layer \"${layer.name}\"
*/
hoverClusterTemplate: "${i18n('Cluster with ${count} features<br>on layer \"${layer.name}\"')}",
/**
* Property: regExesI18n
* {RegEx} Used to internationalize templates.
*/
regExesI18n: /\$\{i18n\(["']?([\s\S]+?)["']?\)\}/g,
/**
* Property: regExesShow
* {RegEx} Used to activate events in the html elements to show individual
* popup.
*/
regExesShow: /\$\{showPopup\((|id|fid)\)(\w*)\}/g,
/**
* Property: regExesAttributes
* {RegEx} Used to omit the name "attributes" as ${.myPropertyName} instead
* of ${attributes.myPropertyName} to show data on a popup using templates.
*/
regExesAttributes: /\$\{\./g,
/**
* Property: selectingSet
* {Boolean} The control set to true this property while being selected a
* set of features to can ignore individual selection, internal use only.
*/
selectingSet: false,
/**
* Property: unselectingAll
* {Boolean} The control set to true this property while being unselected
* all features to can ignore individual unselection, internal use only.
*/
unselectingAll: false,
/**
* Property: hoverListeners
* {Object} hoverListeners object will be registered with
* <OpenLayers.Events.on> on hover control, internal use only.
*/
hoverListeners: null,
/**
* Property: popupObjs
* {Object} Internal use only.
*/
popupObjs: null,
/**
* Property: controls
* {Object} Internal use only.
*/
controls: null,
/**
* Property: layerObjs
* {Object} stores templates and others objects of this control's layers,
* internal use only.
*/
layerObjs: null,
/**
* Property: layers
* {Array(<OpenLayers.Layer.Vector>)} The layers this control will work on,
* internal use only.
*/
layers: null,
/**
* Property: refreshDelay
* {Number} Number of accepted milliseconds of waiting between removing and
* re-add features (useful when using strategies such as BBOX), after
* this time has expired is forced a popup refresh.
*/
refreshDelay: 300,
/**
* Property: delayedRefresh
* {Number} Timeout id of forced a refresh.
*/
delayedRefresh: null,
/**
* Property: delayedRefreshLayers
* {Object} To store the current layers to refresh.
*/
delayedRefreshLayers: null,
/**
* Constructor: OpenLayers.Control.FeaturePopups
* Create a new control that internally uses two
* <OpenLayers.Control.SelectFeature> one for selecting features, and
* another only to highlight them by hover (see <selectOptions>,
* and <hoverOptions>). This control can use also a
* <OpenLayers.Handler.Box> to select features by a box, see
* <boxSelectionOptions> .
*
* The control can generates three types of popup: "hover", "single" and
* "list", see <addLayer>.
* Each popup has a displayClass according to their type:
* "[displayClass]_hover" ,"[displayClass]_select" and
* "[displayClass]_list" respectively.
*
* options - {Object}
*/
initialize: function (options) {
// Options
// -------
options = OpenLayers.Util.applyDefaults(options, {
mode: OpenLayers.Control.FeaturePopups.DEFAULT
});
var layers = options.layers;
delete options.layers;
OpenLayers.Control.prototype.initialize.call(this, options);
// Internal Objects
// ----------------
this.layerObjs = {};
this.delayedRefreshLayers = {};
this.layers = [];
// Controls
// --------
this.controls = {};
var self = this; // to do some tricks.
// Hover control
if (options.hoverOptions !== null && !(this.selectOptions && this.selectOptions.hover)) {
var hoverOptions = OpenLayers.Util.extend(this.hoverOptions, {
hover: true,
highlightOnly: true,
box: false
});
var hoverClass = OpenLayers.Class(OpenLayers.Control.SelectFeature, {
// Trick to close hover popup when hover over selected feature an leave it.
outFeature: function (feature) {
if (feature._lastHighlighter === this.id) {
if (feature._prevHighlighter &&
feature._prevHighlighter !== this.id) {
this.events.triggerEvent(
"featureunhighlighted", {feature: feature});
}
}
OpenLayers.Control.SelectFeature.prototype.outFeature.apply(
this, arguments);
}
});
var controlHover = new hoverClass([], hoverOptions);
this.hoverListeners = {
scope: this,
featurehighlighted: this.onFeaturehighlighted,
featureunhighlighted: this.onFeatureunhighlighted
};
controlHover.events.on(this.hoverListeners);
this.controls.hover = controlHover;
}
// Select control
if (options.selectOptions !== null) {
var selOptions = OpenLayers.Util.applyDefaults(this.selectOptions, {
clickout: false,
multipleKey: 'shiftKey',
toggleKey: 'shiftKey'
});
OpenLayers.Util.extend(selOptions, {box: false, highlightOnly: false});
var selectClass = OpenLayers.Class(OpenLayers.Control.SelectFeature, {
// Trick to close hover popup when the feature is selected.
highlight: function (feature) {
var _lastHighlighter = feature._lastHighlighter;
OpenLayers.Control.SelectFeature.prototype.highlight.apply(
this, arguments);
if (controlHover && _lastHighlighter &&
_lastHighlighter !== feature._lastHighlighter) {
controlHover.events.triggerEvent(
"featureunhighlighted", {feature: feature});
}
}
});
var control = new selectClass([], selOptions);
if (this.boxSelectionOptions) {
// Handler for the trick to manage selection box.
this.handlerBox = new OpenLayers.Handler.Box(
this, {
done: this.onSelectBox
},
OpenLayers.Util.applyDefaults(this.boxSelectionOptions, {
boxDivClassName: "olHandlerBoxSelectFeature",
keyMask: OpenLayers.Handler.MOD_CTRL
})
);
}
// Trick to refresh popups when click a feature of a multiple selection.
control.unselectAll = function (options) {
self.unselectingAll = true;
OpenLayers.Control.SelectFeature.prototype.unselectAll.apply(
this, arguments);
self.unselectingAll = false;
if (options && options.except) {
var layerId = options.except.layer.id,
layerObj = self.layerObjs[layerId];
if (layerObj.safeSelection) {
layerObj.storeAsSelected(options.except);
}
}
self.refreshLayers();
};
this.controls.select = control;
}
// Popup Object Managers
// ---------------------
var _closeBox = !!(this.mode & OpenLayers.Control.FeaturePopups.CLOSE_BOX),
_unselectOnClose = !!(this.mode & OpenLayers.Control.FeaturePopups.UNSELECT_ON_CLOSE);
var popupObjs = {};
if (options.popupListOptions !== null) {
popupObjs.list = new OpenLayers.Control.FeaturePopups.Popup(
this, "list",
OpenLayers.Util.applyDefaults(options.popupListOptions, {
popupClass: OpenLayers.Popup.FramedCloud,
// options for internal use
closeBox: _closeBox,
unselectOnClose: _unselectOnClose,
observeItems: true,
relatedToClear: ["hover", "hoverList", "single", "listItem"]
})
);
}
if (options.popupSingleOptions !== null) {
popupObjs.single = new OpenLayers.Control.FeaturePopups.Popup(
this, "single",
OpenLayers.Util.applyDefaults(options.popupSingleOptions, {
popupClass: OpenLayers.Popup.FramedCloud,
// options for internal use
closeBox: _closeBox,
unselectOnClose: _unselectOnClose,
relatedToClear: ["hover", "hoverList", "list", "listItem"]
})
);
}
if (options.popupListItemOptions !== null) {
popupObjs.listItem = new OpenLayers.Control.FeaturePopups.Popup(
this, "listItem",
OpenLayers.Util.applyDefaults(options.popupListItemOptions, {
popupClass: OpenLayers.Popup.FramedCloud,
// options for internal use
closeBox: _closeBox
})
);
}
if (options.popupHoverOptions !== null) {
popupObjs.hover = new OpenLayers.Control.FeaturePopups.Popup(
this, "hover",
OpenLayers.Util.applyDefaults(options.popupHoverOptions, {
popupClass: OpenLayers.Popup.Anchored,
followCursor: true,
anchor: {
size: new OpenLayers.Size(15, 19),
offset: new OpenLayers.Pixel(-1, -1)
},
relatedToClear: ["hoverList"]
})
);
}
if (options.popupHoverListOptions !== null) {
popupObjs.hoverList = new OpenLayers.Control.FeaturePopups.Popup(
this, "hoverList",
OpenLayers.Util.applyDefaults(options.popupHoverListOptions, {
popupClass: OpenLayers.Popup.Anchored,
followCursor: true,
anchor: {
size: new OpenLayers.Size(15, 19),
offset: new OpenLayers.Pixel(-1, -1)
},
relatedToClear: ["hover"]
})
);
}
this.popupObjs = popupObjs;
// Add layers
// ----------------
layers && this.addLayers(layers);
},
/**
* APIMethod: destroy
*/
destroy: function () {
this.deactivate();
for (var popupType in this.popupObjs) {
this.popupObjs[popupType].destroy();
}
this.popupObjs = null;
for (var layerId in this.layerObjs) {
this.layerObjs[layerId].destroy();
}
this.layerObjs = null;
this.layers = null;
this.handlerBox && this.handlerBox.destroy();
this.handlerBox = null;
this.controls.select && this.controls.select.destroy();
if (this.controls.hover) {
this.controls.hover.events.un(this.hoverListeners);
this.controls.hover.destroy();
}
this.controls = null;
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
* This control does not have HTML component, so this method should be empty.
*/
draw: function() {},
/**
* APIMethod: activate
* Activates the control.
*
* Returns:
* {Boolean} The control was effectively activated.
*/
activate: function () {
if (!this.events) { // This should be in OpenLayers.Control: Can not activate a destroyed control.
return false;
}
if (OpenLayers.Control.prototype.activate.apply(this, arguments)) {
this.map.events.on({
scope: this,
"addlayer": this.onAddlayer,
"removelayer": this.onRemovelayer,
"changelayer": this.onChangelayer
});
var controls = this.controls;
if (controls.hover) {
controls.hover.setLayer(this.layers);
controls.hover.activate();
}
this.handlerBox && this.handlerBox.activate();
if (controls.select) {
controls.select.setLayer(this.layers);
controls.select.activate();
}
for (var layerId in this.layerObjs) {
this.layerObjs[layerId].activate();
}
this.refreshLayers();
return true;
} else {
return false;
}
},
/**
* APIMethod: deactivate
* Deactivates the control.
*
* Returns:
* {Boolean} The control was effectively deactivated.
*/
deactivate: function () {
if (OpenLayers.Control.prototype.deactivate.apply(this, arguments)) {
this.map.events.un({
scope: this,
"addlayer": this.onAddlayer,
"removelayer": this.onRemovelayer
});
for (var layerId in this.layerObjs) {
this.layerObjs[layerId].deactivate();
}
this.handlerBox && this.handlerBox.deactivate();
var controls = this.controls;
controls.hover && controls.hover.deactivate();
controls.select && controls.select.deactivate();
for (var popupType in this.popupObjs) {
this.popupObjs[popupType].clearPopup();
}
return true;
} else {
return false;
}
},
/**
* Method: setMap
* Set the map property for the control.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
if (this.boxSelectionOptions &&
this.boxSelectionOptions.keyMask === OpenLayers.Handler.MOD_CTRL) {
// To disable the context menu for machines which use CTRL-Click as a right click.
map.viewPortDiv.oncontextmenu = OpenLayers.Function.False;
}
this.controls.hover && map.addControl(this.controls.hover);
this.controls.select && map.addControl(this.controls.select);
this.handlerBox && this.handlerBox.setMap(map);
OpenLayers.Control.prototype.setMap.apply(this, arguments);
},
/**
* Method: onAddlayer
* Listens only if the control it is active, internal use only.
*/
onAddlayer: function (evt) {
var layerObj = this.layerObjs[evt.layer.id];
if (layerObj) {
// Set layers in the control when added to the map after activating this control.
var controls = this.controls;
controls.hover && controls.hover.setLayer(this.layers);
controls.select && controls.select.setLayer(this.layers);
layerObj.activate();
this.refreshLayers();
}
},
/**
* Method: onRemovelayer
* Internal use only.
*/
onRemovelayer: function (evt) {
this.removeLayer(evt.layer);
},
/**
* Method: onChangelayer
* Internal use only.
*/
onChangelayer: function (evt) {
var layerObj = this.layerObjs[evt.layer.id];
if (layerObj && evt.property === "visibility") {
layerObj.setRefreshPending();
this.refreshLayers();
}
},
/**
* APIMethod: addLayer
* Add the layer to control and assigns it the templates, see options.
*
* To add a layer that has already been added (maybe automatically),
* first must be removed using <removeLayer>.
*
* Templates containing patterns as ${i18n("key")} are internationalized
* using <OpenLayers.i18n> function.
*
* The control uses the patterns as ${showPopup()} in a "item" template
* to show individual popups from a list. This pattern becomes a
* combination of the layer.id+feature.id and can be used only as an
* html attribute.
* It is convenient to use ${showPopup(fid)} instead of ${showPopup()}
* when the layer features have fid, this ensures that the popups from
* a list is still shown after zoom, even if a BBOX strategies is used.
* When various html elements (in the same "itemPopupTemplate") uses
* ${showPopup()} should differentiate by a suffix in order to avoid
* duplicate id, eg:
* (code)
* itemPopupTemplate: '<span ${showPopup()1} >...</span><br>' +
* '<img ${showPopup()2} src="...">', ...
* (code)
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>}
* options - {Object} Optional
*
* Valid options:
* templates - {Object} Templates
* eventListeners - {Object} This object will be registered with
* <OpenLayers.Events.on>, default scope is the control.
*
* Valid templates:
* single - {String || Function} template used to show a single feature.
* list - {String || Function} template used to show selected
* features as a list (each feature is shown using "itemTemplate"),
* defaul is <layerListTemplate>.
* item - {String || Function} template used to show a feature as
* a item in a list.
* hover - {String || Function} template used on hover a single feature.
* hoverList - {String || Function} template used on hover a clustered feature.
* hoverItem - {String || Function} template used to show a feature as
* a item in a list on hover a clustered feature.
*
* If specified some template as layer property and as options has priority
* the options template.
*
* Valid events on eventListeners:
* selectionchanged - Triggered after selection is changed, receives a event
* with "layer" and "selection" as array of features (note that
* features are not clustered and in this case may lack the property
* layer)
* featureschanged - Triggered after layer features are changed, fired only
* changing the list of features and ignore the clusters changes or
* recharge if obtained new features but with the same "fid". Receives
* a event with "layer" and "features" as array of features (note that
* features are not clustered and in this case may lack the property
* layer)
*
* Default scope for eventListeners is the control.
*/
addLayer: function (layer, options) {
this.addLayers([[layer, options]]);
},
/**
* APIMethod: addLayers
*
* Parameters:
* layers - Array({<OpenLayers.Layer.Vector>} || Array({Object})) Layers to
* add, and array of layers or pairs of arguments layer and options.
*/
addLayers: function (layers) {
var activated = false,
layerItem;
for (var i = 0, len = layers.length; i < len; i++) {
layerItem = layers[i];
if (OpenLayers.Util.isArray(layerItem)) {
activated = activated ||
this.addLayerToControl.apply(this, layerItem).active;
} else {
activated = activated ||
this.addLayerToControl(layerItem).active;
}
}
if (activated) {
var controls = this.controls;
controls.hover && controls.hover.setLayer(this.layers);
controls.select && controls.select.setLayer(this.layers);
this.refreshLayers();
}
},
/**
* Method: addLayerToControl
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>}
* options - {Object}
*/
addLayerToControl: function (layer, options) {
var layerId = layer.id,
layerObj = this.layerObjs[layerId];
if (!layerObj) {
options = OpenLayers.Util.applyDefaults(options, {templates: {} });
var oTemplates = options.templates;
OpenLayers.Util.applyDefaults(options.templates, {
list: (oTemplates.item? this.layerListTemplate: ""),
hoverList: (
(oTemplates.hover || oTemplates.hoverItem)?
this.hoverClusterTemplate: "")
});
layerObj = new OpenLayers.Control.FeaturePopups.Layer(
this, layer, options);
this.layers.push(layer);
this.layerObjs[layerId] = layerObj;
this.active && layerObj.activate();
}
return layerObj;
},
/**
* APIMethod: removeLayer
*/
removeLayer: function (layer) {
var layerId = layer.id,
layerObj = this.layerObjs[layerId];
if (layerObj) {
if (this.active) {
this.active && layerObj.clear();
this.controls.hover && this.controls.hover.setLayer(this.layers);
this.controls.select && this.controls.select.setLayer(this.layers);
}
layerObj.destroy();
OpenLayers.Util.removeItem(this.layers, layer);
delete this.layerObj[layerId];;
}
},
/**
* Method: onSelectBox
* Callback from the handlerBox set up when <selectBox> is true.
*
* Parameters:
* position - {<OpenLayers.Bounds> || <OpenLayers.Pixel>}
*/
onSelectBox: function(position) {
// Trick to not show individual features when using a selection box.
this.selectingSet = true;
OpenLayers.Control.SelectFeature.prototype.selectBox.apply(
this.controls.select, arguments);
this.selectingSet = false;
this.refreshLayers();
},
/**
* Method: onFeaturehighlighted
* Internal use only.
*/
onFeaturehighlighted: function (evt) {
var feature = evt.feature,
layerObj = this.layerObjs[feature.layer.id];
layerObj.highlightFeature(feature);
},
/**
* Method: onFeatureunhighlighted
*/
onFeatureunhighlighted: function (evt) {
this.popupObjs.hover && this.popupObjs.hover.clear();
},
/**
* APIMethod: showSingleFeatureById
*
* Parameters:
* layerId - {String} id of the layer of selected feature.
* featureId - {String} id of the feature.
* idName - {String} Name of id: "id" or "fid".
*/
showSingleFeatureById: function (layerId, featureId, idName) {
var layerObj = this.layerObjs[layerId];
if (layerObj) {
layerObj.showSingleFeatureById(featureId, idName);
} else {
var popupObj = this.popupObjs.listItem;
popupObj && popupObj.clear();
}
},
/**
* APIMethod: addSelectionByIds
*
* Parameters:
* layerId - {String} id of the layer.
* featureIds - {Array(String)} List of feature ids to be
* added to selection.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
addSelectionByIds: function (layerId, featureIds, silent) {
var layerObj = this.layerObjs[layerId];
layerObj && layerObj.addSelectionByIds(featureIds, silent);
},
/**
* APIMethod: setSelectionByIds
*
* Parameters:
* layerId - {String} id of the layer.
* featureIds - {Array(String)} List of feature ids to set as select.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
setSelectionByIds: function (layerId, featureIds, silent) {
var layerObj = this.layerObjs[layerId];
layerObj && layerObj.setSelectionByIds(featureIds, silent);
},
/**
* APIMethod: removeSelectionByIds
*
* Parameters:
* layerId - {String} id of the layer.
* featureIds - {Array(String)} List of feature ids to be
* removed to selection.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
removeSelectionByIds: function (layerId, featureIds, silent) {
var layerObj = this.layerObjs[layerId];
layerObj && layerObj.removeSelectionByIds(featureIds, silent);
},
/**
* APIFunction: getSelectionIds
*/
getSelectionIds: function (layer){
var layerObj = this.layerObjs[layer.id];
if (layerObj) {
return layerObj.getSelectionIds();
} else {
return [];
}
},
/**
* Method: delayRefreshLayer
* Used by LayerObjs
*/
delayRefreshLayer: function (layerId) {
this.delayedRefreshLayers[layerId] = true;
if (this.delayedRefresh !== null) {
window.clearTimeout(this.delayedRefresh);
}
this.delayedRefresh = window.setTimeout(
OpenLayers.Function.bind(
function() {
this.delayedRefresh = null;
for (var layerId in this.delayedRefreshLayers) {
var layerObj = this.layerObjs[layerId];
layerObj && layerObj.setRefreshPending();
}
this.delayedRefreshLayers = {};
this.refreshLayers();
},
this
),
this.refreshDelay
);
},
/**
* Method: endDelayRefreshLayer
* Used by LayerObjs
*/
endDelayRefreshLayer: function (layerId) {
if (this.delayedRefreshLayers[layerId]) {
delete this.delayedRefreshLayers[layerId];
}
var isEmpty = true;
for(var prop in this.delayedRefreshLayers) {
isEmpty = false;
break;
}
if (isEmpty) {
this.refreshLayers();
}
},
/**
* Method: refreshLayers
*/
refreshLayers: function (useCursorLocation) {
if (this.delayedRefresh !== null) {
window.clearTimeout(this.delayedRefresh);
this.delayedRefresh = null;
this.delayedRefreshLayers = {};
}
var layers = OpenLayers.Array.filter(this.layers,
function(layer) {
return !!layer.map;
}
);
var bounds = new OpenLayers.Bounds(),
invalid = false,
html = [],
countSelected = 0,
sFeature0 = null,
allSelFeatures = [];
var layerObj, lenAux, r;
for (var layerId in this.layerObjs) {
layerObj = this.layerObjs[layerId];
r = layerObj.getListHtml(bounds);
html.push(r.html);
invalid = invalid || r.invalid;
if (r.features.length) {
allSelFeatures.push({layer:layerObj.layer, features:r.features});
lenAux = layerObj.layer.selectedFeatures.length;
countSelected += lenAux;
if (lenAux === 1 && countSelected === 1) {
sFeature0 = layerObj.layer.selectedFeatures[0];
}
}
}
if (invalid) {
var feature,
response = false;
// only one single feature is selected? so... try to show
if (this.popupObjs.single && allSelFeatures.length === 1 &&
allSelFeatures[0].features.length === 1) {
var selObject = allSelFeatures[0],
feature = selObject.features[0];
var rr = this.layerObjs[selObject.layer.id].getSingleHtml(feature)
if (rr.hasTemplate) {
this.popupObjs.single.showPopup(feature, rr.lonLat, rr.html);
response = !!this.popupObjs.single.popup;
}
}
if (this.popupObjs.list && !response) {
var lonLat = (useCursorLocation && countSelected === 1)? // so is only one cluster
this.getLocationFromSelPixel(this.controls.select, sFeature0):
bounds.getCenterLonLat();
this.popupObjs.list.showPopup(
allSelFeatures,
lonLat,
(allSelFeatures.length? html.join("\n"): "")
);
}
}
},
/**
* function: getLocationFromSelPixel
* Get selection location.
*
* Parameters:
* selControls - {<OpenLayers.Control.SelectFeature>}
* feature - {<OpenLayers.Feature.Vector>}
*
* Retruns:
* {<OpenLayers.LonLat>} Location from pixel pixel where the feature was
* selected.
*/
getLocationFromSelPixel: function (selControl, feature) {
var lonLat,
handler = selControl.handlers.feature;
var xy = (handler.feature === feature)? handler.evt.xy: null;
return (xy? this.map.getLonLatFromPixel(xy):
feature.geometry.getBounds().getCenterLonLat()
);
},
/**
* Function: prepareTemplate
* When the template is a string returns a prepared template,
* otherwise returns it as is, see more in <addLayer>.
* This function is used at creating a instance of the control and when
* <addLayer> method is called.
*
* Parameters:
* template - {String || Function}
*
* Returns:
* {String || Function} A internationalized template.
*/
prepareTemplate: function (template) {
if (typeof template == 'string') {
template = template.replace(
this.regExesShow,
function (a, idName, subId) {
idName = idName || "id";
return "id=\"showPopup-${layer.id}-" + idName + "-${" + idName + "}-" + subId + "\"";
}
);
template = template.replace(
this.regExesAttributes,
"${attributes."
);
return template.replace( // internationalize template.
this.regExesI18n,
function (a,key) {
return OpenLayers.i18n(key);
}
);
} else {
return template;
}
},
CLASS_NAME: "OpenLayers.Control.FeaturePopups"
});
/**
* Constant: NONE
* {Integer} Used in <mode> indicates to not activate any particular behavior.
*/
OpenLayers.Control.FeaturePopups.NONE = 0;
/**
* Constant: CLOSE_ON_REMOVE
* {Integer} Used in <mode> indicates that the popups will close when
* removing features in a layer.
*/
OpenLayers.Control.FeaturePopups.CLOSE_ON_REMOVE = 1;
/**
* Constant: SAFE_SELECTION
* {Integer} Used in <mode> indicates that the features will remain
* selected even have been removed from the layer. Is useful when using
* <OpenLayers.Strategy.BBOX> with features with "fid" or when using
* <OpenLayers.Strategy.Cluster>. Using "BBOX" when a feature is added
* back to the layer will be re-selected automatically by "fid".
*/
OpenLayers.Control.FeaturePopups.SAFE_SELECTION = 2;
/**
* Constant: CLOSE_ON_UNSELECT
* {Integer} Used in <mode> indicates that the popups will close when
* unselect the feature.
*/
OpenLayers.Control.FeaturePopups.CLOSE_ON_UNSELECT = 4;
/**
* Constant: CLOSE_BOX
* {Integer} Used in <mode> indicates to display a close box inside the popups.
*/
OpenLayers.Control.FeaturePopups.CLOSE_BOX = 8;
/**
* Constant: UNSELECT_ON_CLOSE
* {Integer} Used in <mode> indicates to unselect all features when a popup is
* closed.
*/
OpenLayers.Control.FeaturePopups.UNSELECT_ON_CLOSE = 16;
/**
* Constant: DEFAULT
* {Integer} Used in <mode> indicates to activate default behaviors
* <SAFE_SELECTION> <CLOSE_ON_UNSELECT> <CLOSE_BOX> and <UNSELECT_ON_CLOSE>.
*/
OpenLayers.Control.FeaturePopups.DEFAULT =
OpenLayers.Control.FeaturePopups.SAFE_SELECTION |
OpenLayers.Control.FeaturePopups.CLOSE_ON_UNSELECT |
OpenLayers.Control.FeaturePopups.CLOSE_BOX |
OpenLayers.Control.FeaturePopups.UNSELECT_ON_CLOSE;
/**
* Class: OpenLayers.Control.FeaturePopups.Popup
*/
OpenLayers.Control.FeaturePopups.Popup = OpenLayers.Class({
/**
* APIProperty: events
* {<OpenLayers.Events>} Events instance for listeners and triggering
* specific events.
*
* Supported event types:
* beforepopupdisplayed - Triggered before a popup is displayed.
* To stop the popup from being displayed, a listener should return
* false. Receives an event with; "popupType" see <Constructor>,
* "selection" a feature except for the "list" porupType that is
* an array of pairs "layer" and "features", "popupClass" popupClass
* that will be used to display the popup.
* popupdisplayed - Triggered after a popup is displayed. Receives an event
* with; "popupType" see <Constructor>, "selection" a feature except
* for the "list" porupType that is an array of pairs "layer" and
* "features", "div" the DOMElement used by the popup and "popup" the
* instance of the popup class that has shown the popup.
* closedbybox - Triggered after close a popup using close box. Receives
* an event with "popupType" see <Constructor>
*/
events: null,
/**
* Constant: EVENT_TYPES
* Only required to use <OpenLayers.Control.FeaturePopups> with 2.11 or less
*/
EVENT_TYPES: ["beforepopupdisplayed", "popupdisplayed", "closedbybox"],
/**
* APIProperty: eventListeners
* {Object} If set on options at construction, the eventListeners
* object will be registered with <OpenLayers.Events.on>. Object
* structure must be a listeners object as shown in the example for
* the events.on method.
*/
eventListeners: null,
/** APIProperty: control
* {<OpenLayers.Control.FeaturePopups>} The control that initialized this
* popup manager.
*/
control: null,
/** APIProperty: type
* {String} Type of popup manager, read only.
*/
type: "",
/** APIProperty: popupClass
* {String|<OpenLayers.Popup>|Function} Type of popup to manage.
*/
popupClass: null,
/**
* APIProperty: anchor
* {Object} Object to which we'll anchor the popup. Must expose a
* 'size' (<OpenLayers.Size>) and 'offset' (<OpenLayers.Pixel>).
*/
anchor: null,
/**
* APIProperty: minSize
* {<OpenLayers.Size>} Minimum size allowed for the popup's contents.
*/
minSize: null,
/**
* APIProperty: maxSize
* {<OpenLayers.Size>} Maximum size allowed for the popup's contents.
*/
maxSize: null,
/**
* APIProperty: unselectOnClose
* {Boolean} If true, closing a popup all features are unselected on
* control.controls.select.
*/
unselectOnClose: false,
/**
* APIProperty: closeBox
* {Boolean} To display a close box inside the popup.
*/
closeBox: false,
/**
* Property: observeItems
* {Boolean} If true, will be activated observers of the DOMElement of the
* popup to trigger some events (mostly in list popups).
*/
observeItems: false,
/**
* Property: relatedToClear
* Array({String}) Related <FeaturePopups.popupObjs> codes from <control>
* to clear.
*/
relatedToClear: [],
/** Property: popupType
* {String} Code of type of popup to manage: "div", "OL" or "custom"
*/
popupType: "",
/**
* Property: popup
* {Boolean|<OpenLayers.Popup>} True or instance of OpenLayers.Popup when
* popup is showing.
*/
popup: null,
/**
* Property: clearCustom
* {Function|null} stores while displaying a custom popup the function to
* clear the popup, this function is returned by the custom popup.
*/
clearCustom: null,
/**
* Property: onCloseBoxMethod
* {Function|null} When the popup is created with closeBox argument to true,
* this property stores the method that implement any measures to close
* the popup, otherwise is null.
*/
onCloseBoxMethod: null,
/**
* Property: moveListener
* {Object} moveListener object will be registered with
* <OpenLayers.Events.on>, use only when <followCursor> is true.
*/
moveListener: null,
/**
* Constructor: OpenLayers.Control.FeaturePopups.Popup
* This class is a handler that is responsible for displaying and clear the
* one kind of popups managed by a <OpenLayers.Control.FeaturePopups>.
*
* The manager popup can handle three types of popups: a div a
* OpenLayers.Popup class or a custom popup, it depends on the type of
* "popupClass" argument.
*
* Parameters:
* control - {<OpenLayers.Control.FeaturePopups>} The control that
* initialized this popup manager.
* popupType - {String} Type of popup manager: "list", "single", "listItem"
* or "hover"
* options - {Object}
*
* Valid ptions:
* eventListeners - {Object} Listeners to register at object creation.
* minSize - {<OpenLayers.Size>} Minimum size allowed for the popup's contents.
* maxSize - {<OpenLayers.Size>} Maximum size allowed for the popup's contents.
* popupClass - {String|<OpenLayers.Popup>|Function} Type of popup to
* manage: string for a "id" of a DOMElement, OpenLayers.Popup and a
* function for a custom popup.
* anchor -{Object} Object to which we'll anchor the popup. Must expose a
* 'size' (<OpenLayers.Size>) and 'offset' (<OpenLayers.Pixel>).
* followCursor - {Boolean} If true, the popup will follow the cursor
* (useful for hover)
* unselectOnClose - {Boolean} If true, closing a popup all features are
* unselected on control.controls.select.
* closeBox - {Boolean} To display a close box inside the popup.
* observeItems - {Boolean} If true, will be activated observers of the
* DOMElement of the popup to trigger some events (mostly by list popups).
* relatedToClear - Array({String}) Related <FeaturePopups.popupObjs> codes
* from <control> to clear.
*/
initialize: function (control, popupType, options) {
// Options
OpenLayers.Util.extend(this, options);
if (this.maxSize) {
this.maxSize.w = isNaN(this.maxSize.w)? 999999: this.maxSize.w;
this.maxSize.h = isNaN(this.maxSize.h)? 999999: this.maxSize.h;
}
if (this.minSize) {
this.minSize.w = isNaN(this.minSize.w)? 0: this.minSize.w;
this.minSize.h = isNaN(this.minSize.h)? 0: this.minSize.h;
}
// Arguments
this.control = control;
this.type = popupType;
// close box
if (this.closeBox) {
this.onCloseBoxMethod = OpenLayers.Function.bind(
function(evt) {
if (this.unselectOnClose && control.controls.select) {
control.controls.select.unselectAll();
}
this.clear();
OpenLayers.Event.stop(evt);
this.events.triggerEvent("closedbybox", {popupType: this.type});
},
this
)
}
// Options
var popupClass = this.popupClass;
if (popupClass) {
if (typeof popupClass == "string") {
this.popupType = "div";
} else if (popupClass.prototype.CLASS_NAME &&
OpenLayers.String.startsWith(
popupClass.prototype.CLASS_NAME, "OpenLayers.Popup")) {
this.popupType = "OL";
this.popupClass = OpenLayers.Class(popupClass, {
autoSize: true,
minSize: this.minSize,
maxSize: this.maxSize,
contentDisplayClass:
popupClass.prototype.contentDisplayClass + " " +
control.displayClass + "_" + this.type
});
} else if (typeof popupClass == "function") {
this.popupType = "custom";
}
}
if (this.followCursor) {
this.moveListener = {
scope: this,
mousemove: function(evt) {
var popup = this.popup;
if (popup && popup.moveTo) {
var map = this.control.map;
popup.moveTo(
map.getLayerPxFromLonLat(
map.getLonLatFromPixel(evt.xy)));
}
}
};
}
this.events = new OpenLayers.Events(this, null, this.EVENT_TYPES);
this.eventListeners && this.events.on(this.eventListeners);
},
/**
* APIMethod: destroy
*/
destroy: function () {
this.clear();
this.eventListeners && this.events.un(this.eventListeners);
this.events.destroy();
this.events = null;
},
/**
* Method: showPopup
* Shows the popup if it has changed, and clears it previously
*
* Parameters:
* selection - {<OpenLayers.Feature.Vector>}|Object} Selected features.
* lonlat - {<OpenLayers.LonLat>} The position on the map the popup will
* be shown.
* html - {String} An HTML string to display inside the popup.
*/
showPopup: function (selection, lonLat, html) {
this.clear();
var popupClass = this.popupClass;
if (popupClass && html) {
var cont = this.events.triggerEvent("beforepopupdisplayed", {
popupType: this.type,
selection: selection,
popupClass: popupClass
});
if (cont !== false) {
// this alters "this.popup"
this.create(lonLat, html);
}
}
if (this.popup) {
this.observeItems && this.observeShowPopup(this.div);
this.events.triggerEvent("popupdisplayed", {
popupType: this.type,
selection: selection,
div: this.div,
popup: this.popup
});
}
},
/**
* Method: clear
* Internal use only.
*/
clear: function () {
this.clearPopup()
var popupObjs = this.control.popupObjs,
related;
for (var i = 0, len = this.relatedToClear.length; i <len; i++) {
related = popupObjs[this.relatedToClear[i]];
related && related.clearPopup();
}
},
/**
* Method: observeShowPopup
* Internal use only.
*
* Parameters:
* div - {DOMElement}
*/
observeShowPopup: function (div) {
for (var i = 0, len = div.childNodes.length; i < len; i++) {
var child = div.childNodes[i];
if (child.id && OpenLayers.String.startsWith(child.id,
"showPopup-OpenLayers")) {
OpenLayers.Event.observe(child, "touchend",
OpenLayers.Function.bindAsEventListener(this.showListItem, this.control));
OpenLayers.Event.observe(child, "click",
OpenLayers.Function.bindAsEventListener(this.showListItem, this.control));
} else {
this.observeShowPopup(child);
}
}
},
/**
* Method: showListItem
* Internal use only.
*
* Parameters:
* div - {DOMElement}
*
* Scope:
* - {<OpenLayers.Control.FeaturePopups>}
*/
showListItem: function (evt) {
var elem = OpenLayers.Event.element(evt);
if (elem.id) {
var ids = elem.id.split("-");
if (ids.length >= 3) {
this.showSingleFeatureById(ids[1], ids[3], ids[2]);
}
}
},
/**
* Method: removeChildren
* Internal use only.
*
* Parameters:
* div - {DOMElement}
*/
removeChildren: function (div) {
var child;
while (child = div.firstChild) {
if (child.id && OpenLayers.String.startsWith(child.id,
"showPopup-OpenLayers")) {
OpenLayers.Event.stopObservingElement(child);
}
this.removeChildren(child);
div.removeChild(child);
}
},
/**
* Method: create
* Create the popup.
*/
create: function (lonLat, html) {
var div, popup,
control = this.control;
switch (this.popupType) {
case "div":
div = document.getElementById(this.popupClass);
if (div) {
div.innerHTML = html;
this.div = div;
this.popup = true;
}
break;
case "OL":
control = this.control;
popup = new this.popupClass(
control.id + "_" + this.type,
lonLat,
new OpenLayers.Size(100,100),
html
);
if (this.anchor) {
popup.anchor = this.anchor;
}
if (this.onCloseBoxMethod) {
// The API of the popups is not homogeneous, closeBox may
// be the fifth or sixth argument, it depends!
// So forces closeBox using other ways.
popup.addCloseBox(this.onCloseBoxMethod);
popup.closeDiv.style.zIndex = 1;
}
control.map.addPopup(popup);
this.div = popup.contentDiv;
this.popup = popup;
this.moveListener && control.map.events.on(this.moveListener);
break;
case "custom":
var returnObj = this.popupClass(
control.map, lonLat, html, this.onCloseBoxMethod, this);
if (returnObj.div) {
this.clearCustom = returnObj.destroy;
this.div = returnObj.div;
this.popup = true;
}
break;
}
},
/**
* Method: clearPopup
* Clear the popup if it is showing.
*/
clearPopup: function () {
if (this.popup) {
this.observeItems && this.removeChildren(this.div);
switch (this.popupType) {
case "OL":
var control = this.control;
if (control.map) {
control.map.removePopup(this.popup);
}
this.popup.destroy();
this.moveListener && control.map.events.un(this.moveListener);
break;
case "custom":
if (this.popup) {
if (this.clearCustom) {
this.clearCustom();
this.clearCustom = null;
}
}
break;
}
this.div = null;
this.popup = null;
}
},
CLASS_NAME: "OpenLayers.Control.FeaturePopups.Popup"
});
/**
* Class: OpenLayers.Control.FeaturePopups.Layer
*/
OpenLayers.Control.FeaturePopups.Layer = OpenLayers.Class({
/**
* APIProperty: events
* {<OpenLayers.Events>} Events instance for listeners and triggering
* specific events.
*
* Supported event types: see <FeaturePopups.AddLayer>
*/
events: null,
/**
* Constant: EVENT_TYPES
* Only required to use <OpenLayers.Control.FeaturePopups> with 2.11 or less
*/
EVENT_TYPES: ["featureschanged", "selectionchanged"],
/**
* APIProperty: eventListeners
* {Object} If set on options at construction, the eventListeners
* object will be registered with <OpenLayers.Events.on>. Object
* structure must be a listeners object as shown in the example for
* the events.on method.
*/
eventListeners: null,
/**
* Property: listenFeatures
* {Boolean} nternal use to optimize performance, true if <eventListeners>
* contains a "featureschanged" event.
*/
listenFeatures: false,
/**
* APIProperty: templates
* {Object} Set of templates, see <FeaturePopups.AddLayer>
*/
templates: null,
/**
* Property: safeSelection
* {Boolean} Internal use to optimize performance, true if
* <FeaturePopups.mode> contains
* <OpenLayers.Control.FeaturePopups.SAFE_SELECTION>.
*/
safeSelection: false,
/**
* Property: selection
* {Object} Used if <safeSelection> is true. Set of the identifiers (id or
* fid if it exists) of the features that were selected, a feature
* remains on the object after being removed from the layer until
* occurs new selection.
*/
selection: {},
/**
* Property: selectionHash
* {String} String unique for the single features of the selected features
* of the layer regardless of the order or clustering of these, is
* based on its id or fid (if it exists)
*/
selectionHash: "",
/**
* Property: featuresHash
* {String} String unique for the single features of the layer regardless
* of the order or clustering of these, is based on its id or fid (if
* it exists)
*/
featuresHash: "",
/**
* Property: refreshPendig
* Array({<OpenLayers.Feature.Vector>}) Layer features cache to use at the
* right time in "featureschanged" event.
*/
refreshPendig: null,
/**
* Property: layerListeners
* {Object} layerListeners object will be registered with
* <OpenLayers.Events.on>, internal use only.
*/
layerListeners: null,
/**
* APIProperty: active
* {Boolean} The object is active (read-only)
*/
active: null,
/**
* Property: updatingSelection
* {Boolean} The control set to true this property while being refreshed
* selection on a set of features to can ignore others acctions,
* internal use only.
*/
updatingSelection: false,
/**
* Property: silentSelection
* {Boolean} Suppress "selectionchanged" event triggering during a selection
* process, internal use only.
*/
silentSelection: false,
/**
* Constructor: OpenLayers.Control.FeaturePopups.Layer
*/
initialize: function (control, layer, options) {
// Options
OpenLayers.Util.extend(this, options);
// Arguments
this.control = control;
this.layer = layer;
// Templates
var oTemplates = options && options.templates || {};
var templates = {};
for (var templateName in oTemplates) {
templates[templateName] =
control.prepareTemplate(oTemplates[templateName]);
}
this.templates = templates;
this.eventListeners = options.eventListeners,
// Events
this.events = new OpenLayers.Events(this, null, this.EVENT_TYPES);
if (this.eventListeners) {
this.events.on(this.eventListeners);
this.listenFeatures = !!(this.eventListeners &&
this.eventListeners["featureschanged"]);
}
// Layer listeners
// ---------------
this.safeSelection = !!(control.mode &
OpenLayers.Control.FeaturePopups.SAFE_SELECTION);
this.layerListeners = {
scope: this,
"featureselected": this.onFeatureselected
};
if (control.mode & OpenLayers.Control.FeaturePopups.CLOSE_ON_UNSELECT ||
this.safeSelection) {
this.layerListeners["featureunselected"] = this.onFeatureunselected;
}
if (this.safeSelection) {
this.layerListeners["beforefeaturesremoved"] = this.onBeforefeaturesremoved;
this.layerListeners["featuresadded"] = this.onFeaturesadded;
} else if (control.mode & OpenLayers.Control.FeaturePopups.CLOSE_ON_REMOVE) {
this.layerListeners["featuresremoved"] = this.onFeaturesremoved;
}
},
/**
* Method: destroy
*/
destroy: function() {
this.deactivate();
this.eventListeners && this.events.un(this.eventListeners);
this.events.destroy();
},
/**
* Method: activate
*/
activate: function () {
if (!this.active && this.layer.getVisibility() && this.layer.map) {
this.layer.events.on(this.layerListeners);
this.setRefreshPending();
this.active = true;
return true;
} else {
return false;
}
},
/**
* Method: deactivate
*/
deactivate: function(){
if (this.active) {
this.layer.events.un(this.layerListeners);
this.active = false;
return true;
} else {
return false;
}
},
/**
* Method: clear
*/
clear: function() {
if (this.active) {
if (!this.isEmptyObject(this.selection)) {
this.events.triggerEvent("selectionchanged", {
layer: this.layer,
control: this.control,
selection: []
});
}
if (this.featuresHash !== "" ) {
this.events.triggerEvent("featureschanged", {
layer: this.layer,
control: this.control,
features: []
});
}
}
this.selection = [];
this.selectionHash = "";
this.featuresHash = "";
},
/**
* Method: isEmptyObject
*
* Parameters:
* obj - {Object}
*/
isEmptyObject: function (obj) {
for(var prop in obj) {
return false;
}
return true;
},
/**
* Method: highlightFeature
* Internal use only.
*/
highlightFeature: function (feature) {
var control = this.control,
popupObjHover = control.popupObjs.hover;
if (!popupObjHover) { return; }
popupObjHover.clear();
var templates = this.templates,
template = templates.hover;
if (template) {
var lonLat = control.getLocationFromSelPixel(control.controls.hover,
feature);
if (feature.cluster) {
if (feature.cluster.length == 1){
// show cluster as a single feature.
popupObjHover.showPopup(feature, lonLat,
this.renderTemplate(
template,
this.cloneDummyFeature(
feature.cluster[0], feature.layer)
)
);
} else {
var html = "",
popupObjHoverList = control.popupObjs.hoverList;
if (popupObjHoverList) {
var cFeatures = feature.cluster,
itemTemplate = templates.hoverItem;
if (itemTemplate) {
var htmlAux = [];
for (var i = 0 , len = cFeatures.length; i <len; i++) {
htmlAux.push(this.renderTemplate(itemTemplate,
cFeatures[i]));
}
html = htmlAux.join("\n")
}
popupObjHoverList.showPopup(cFeatures, lonLat,
this.renderTemplate(templates.hoverList, {
layer: feature.layer,
count: cFeatures.length,
html: html
})
);
}
}
} else {
popupObjHover.showPopup(feature, lonLat,
this.renderTemplate(template, feature));
}
}
},
/**
* Method: onFeatureselected
*
* Parameters:
* evt - {Object}
*/
onFeatureselected: function (evt) {
if (!this.updatingSelection && this.safeSelection) {
this.storeAsSelected(evt.feature);
}
if (!this.control.selectingSet) {
this.control.refreshLayers(true);
}
},
/**
* Method: storeAsSelected
*
* Parameter:
* feature - {OpenLayers.Feature.Vector} Feature to store as selected.
*/
storeAsSelected: function (feature) {
var layerId = feature.layer.id;
var savedSF = this.selection,
fid = feature.fid;
if (fid) {
savedSF[fid] = true;
} else if (feature.cluster) {
for (var i = 0 , len = feature.cluster.length; i <len; i++) {
var cFeature = feature.cluster[i];
var fidfid = cFeature.fid;
if (fidfid) {
savedSF[fidfid] = true;
} else {
savedSF[cFeature.id] = true;
}
}
}
},
/**
* Method: onFeatureunselected
* Called when the select feature control unselects a feature.
*
* Parameters:
* evt - {Object}
*/
onFeatureunselected: function (evt) {
if (this.safeSelection) {
var savedSF = this.selection,
feature = evt.feature;
if (savedSF) {
var fid = feature.fid;
if (fid) {
delete savedSF[fid];
} else if (feature.cluster) {
for (var i = 0 , len = feature.cluster.length; i <len; i++) {
var cFeature = feature.cluster[i];
var fidfid = cFeature.fid;
if (fidfid) {
delete savedSF[fidfid];
} else {
delete savedSF[cFeature.id];
}
}
}
}
}
var control = this.control;
if (!control.unselectingAll &&
(control.mode &
OpenLayers.Control.FeaturePopups.CLOSE_ON_UNSELECT) ) {
control.refreshLayers();
}
},
/**
* Method: onBeforefeaturesremoved
* Called before some features are removed, only used when <mode>
* contains <OpenLayers.Control.FeaturePopups.SAFE_SELECTION>.
*
* Parameters:
* evt - {Object}
*/
onBeforefeaturesremoved: function (evt) {
var layerId = this.layer.id,
control = this.control,
features = evt.features;
if (features.length) {
var delayRefresh = !this.isEmptyObject(this.selection);
if (delayRefresh || this.listenFeatures) {
control.delayRefreshLayer(layerId);
}
}
},
/**
* Method: onFeaturesremoved
* Called when some features are removed, only used when
* <mode> = <OpenLayers.Control.FeaturePopups.CLOSE_ON_REMOVE>
*
* Parameters:
* evt - {Object}
*/
onFeaturesremoved: function (evt) {
this.control.refreshLayers();
},
/**
* Method: onFeaturesadded
* Called when some features are added, only used when value of <mode>
* conbtains <OpenLayers.Control.FeaturePopups..SAFE_SELECTION>.
*
* Parameters:
* evt - {Object}
*/
onFeaturesadded: function (evt) {
var layerId = this.layer.id,
control = this.control,
features = evt.features,
savedSF = this.selection;
if (!this.isEmptyObject(savedSF)) {
var selectCtl = control.controls.select;
control.selectingSet = true;
this.updatingSelection = true;
for (var i = 0 , len = features.length; i <len; i++) {
var feature = features[i];
if (feature.fid && savedSF[feature.fid]) {
selectCtl.select(feature);
} else if (feature.cluster) {
for (var ii = 0 , lenlen = feature.cluster.length; ii <lenlen; ii++) {
var cFeature = feature.cluster[ii];
if (cFeature.fid) {
if (savedSF[cFeature.fid]) {
selectCtl.select(feature);
break;
}
} else if (savedSF[cFeature.id]) {
selectCtl.select(feature);
break;
}
}
} else if (savedSF[feature.id]) {
selectCtl.select(feature);
}
}
control.selectingSet = false;
this.updatingSelection = false;
}
this.setRefreshPending();
control.endDelayRefreshLayer(layerId);
},
/**
* Method: setRefreshPending
*/
setRefreshPending: function () {
if (this.listenFeatures) {
var featuresHash,
layer = this.layer,
layerFeatures = this.getSingleFeatures(layer.features);
// get hash
if (layer.getVisibility() && layer.map) {
var feature,
ids = [];
for (var i=0, len = layerFeatures.length; i<len; ++i) {
feature = layerFeatures[i];
if (feature.fid) {
ids.push(feature.fid);
} else {
ids.push(feature.id);
}
}
featuresHash = ids.sort().join("\t");
} else {
featuresHash = "";
}
// have been changed?
if (featuresHash !== this.featuresHash) {
this.refreshPendig = layerFeatures;
this.featuresHash = featuresHash;
} else {
this.refreshPendig = null;
}
}
},
/**
* Function: getListHtml
*/
getListHtml: function (bounds) {
var layer = this.layer;
if (this.refreshPendig) {
this.events.triggerEvent("featureschanged", {
layer: layer,
features: this.refreshPendig
});
this.refreshPendig = null;
}
var html = "",
features = [],
invalid = false;
if (layer.getVisibility() && layer.inRange) {
var features = this.getLayerSelectionFeatures(),
layerTemplate = this.templates.list;
var i, len, feature,
selectionHash = [],
htmlAux = [],
itemTemplate = this.templates.item;
for (i=0, len = features.length; i<len; ++i) {
feature = features[i];
bounds.extend(feature.geometry.getBounds());
if (!feature.layer) {
feature = this.cloneDummyFeature(feature, layer);
}
layerTemplate && htmlAux.push(this.renderTemplate(itemTemplate, feature));
if (feature.fid) {
selectionHash.push(feature.fid);
} else {
selectionHash.push(feature.id);
}
}
selectionHash = selectionHash.sort().join("\t");
if (selectionHash !== this.selectionHash) {
invalid = true;
this.selectionHash = selectionHash;
}
if (layerTemplate) {
if (htmlAux.length) {
html = this.renderTemplate(
layerTemplate, {
layer: layer,
count: features.length,
html: htmlAux.join("\n")
}
);
}
}
} else if (this.selectionHash !== "") {
invalid = true;
this.selectionHash = "";
}
if (invalid && !this.silentSelection) {
this.events.triggerEvent("selectionchanged", {
layer: layer,
selection: features
});
}
return {invalid: invalid,html: html, features: features};
},
/**
* Function: getSingleHtml
*/
getSingleHtml: function (feature) {
var html = "",
hasTemplate = false,
sTemplate = this.templates.single;
if (sTemplate) {
var lonLat;
if (feature.geometry.getVertices().length > 1) {
lonLat = this.control.getLocationFromSelPixel(this.controls.select,
feature);
} else {
lonLat = feature.geometry.getBounds().getCenterLonLat();
}
if (!feature.layer) {
feature = this.cloneDummyFeature(feature, this.layer);
}
html = this.renderTemplate(sTemplate, feature);
hasTemplate = true;
}
return {hasTemplate: hasTemplate, html: html, lonLat:lonLat};
},
/**
* APIMethod: addSelectionByIds
*
* Parameters:
* featureIds - {Array(String)} List of feature ids to be
* added to selection.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
addSelectionByIds: function (featureIds, silent) {
if (featureIds.length > 0) {
var i, len,
savedSF = this.selection;
for (i=0, len = featureIds.length; i<len; i++) {
savedSF[featureIds[i]] = true;
}
this.applySelection(silent);
}
},
/**
* APIMethod: setSelectionByIds
*
* Parameters:
* featureIds - {Array(String)} List of feature ids to set as select.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
setSelectionByIds: function (featureIds, silent) {
var i, len,
savedSF = {};
for (i=0, len = featureIds.length; i<len; i++) {
savedSF[featureIds[i]] = true;
}
this.selection = savedSF;
this.applySelection(silent);
},
/**
* Method: applySelection
*/
applySelection: function (silent) {
var i, len,
savedSF = this.selection,
control = this.control,
selectCtl = control.controls.select,
_indexOf = OpenLayers.Util.indexOf,
layer = this.layer,
features = layer.features;
control.selectingSet = true;
this.updatingSelection = true;
for (var i = 0 , len = features.length; i <len; i++) {
var feature = features[i],
selected = false;
if (feature.fid && savedSF[feature.fid]) {
selected = true;
} else if (feature.cluster) {
for (var ii = 0 , lenlen = feature.cluster.length; ii <lenlen; ii++) {
var cFeature = feature.cluster[ii];
if (cFeature.fid) {
if (savedSF[cFeature.fid]) {
selected = true;
break;
}
} else if (savedSF[cFeature.id]) {
selected = true;
break;
}
}
} else if (savedSF[feature.id]) {
selected = true;
}
if (selected) {
if (_indexOf(layer.selectedFeatures, feature) == -1) {
selectCtl.select(feature);
}
} else if (_indexOf(layer.selectedFeatures, feature) > -1) {
selectCtl.unselect(feature);
}
}
control.selectingSet = false;
this.updatingSelection = false;
this.silentSelection = !!silent;
control.refreshLayers();
this.silentSelection = false;
},
/**
* APIMethod: removeSelectionByIds
*
* Parameters:
* featureIds - {Array(String)} List of feature ids to be
* removed to selection.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
removeSelectionByIds: function (featureIds, silent) {
if (featureIds.length > 0) {
var i, len,
savedSF = this.selection;
for (i=0, len = featureIds.length; i<len; i++) {
var featureId = featureIds[i];
if (savedSF[featureId]) {
delete savedSF[featureId];
}
}
this.applyDeselection(silent);
}
},
/**
* Method: applyDeselection
*/
applyDeselection: function (silent) {
var i, len,
savedSF = this.selection,
control = this.control,
selectCtl = control.controls.select,
_indexOf = OpenLayers.Util.indexOf,
layer = this.layer,
features = layer.selectedFeatures;
control.selectingSet = true;
this.updatingSelection = true;
for (var i = features.length-1; i >= 0; i--) {
var feature = features[i],
selected = false;
if (feature.fid && savedSF[feature.fid]) {
selected = true;
} else if (feature.cluster) {
for (var ii = 0 , lenlen = feature.cluster.length; ii <lenlen; ii++) {
var cFeature = feature.cluster[ii];
if (cFeature.fid) {
if (savedSF[cFeature.fid]) {
selected = true;
break;
}
} else if (savedSF[cFeature.id]) {
selected = true;
break;
}
}
} else if (savedSF[feature.id]) {
selected = true;
}
if (!selected) {
selectCtl.unselect(feature);
}
}
control.selectingSet = false;
this.updatingSelection = false;
this.silentSelection = !!silent;
control.refreshLayers();
this.silentSelection = false;
},
/**
* function: cloneDummyFeature
* Used on clustered features.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} the feature.
* layer - {<OpenLayers.Layer.Vector>}
*
* Returns:
* {Object} Context of the feature including the layer.
*/
cloneDummyFeature: function (feature, layer) {
feature = OpenLayers.Util.extend({}, feature);
feature.layer = layer;
return feature;
},
/**
* APIMethod: showSingleFeatureById
*
* Parameters:
* featureId - {String} id of the feature.
* idName - {String} Name of id: "id" or "fid".
*/
showSingleFeatureById: function (featureId, idName) {
var popupObj = this.control.popupObjs.listItem;
if (!popupObj) { return; }
idName = idName || "id";
var clearPopup = true;
if (featureId) {
var i, len, feature,
layer = this.layer,
features = layer.features;
for (i=0, len = features.length; i<len; i++) {
feature = features[i];
if (feature.cluster) {
var ii, len2, cFeature;
cFeature = feature;
for (ii=0, len2 = cFeature.cluster.length; ii<len2; ii++) {
feature = cFeature.cluster[ii];
if (feature[idName] == featureId) {
feature = this.cloneDummyFeature(feature, layer);
break;
}
}
}
// Don't try to show a cluster as a single feature,
// templates.single does not support it.
if (feature[idName] == featureId && !feature.cluster) {
popupObj.clear();
var template = this.templates.single;
if (template) {
var html = this.renderTemplate(template, feature)
popupObj.showPopup(
feature,
feature.geometry.getBounds().getCenterLonLat(),
html
);
}
clearPopup = false;
break;
}
}
}
if (clearPopup) {
popupObj.clear();
}
},
/**
* Method: getLayerSelectionFeatures
*/
getLayerSelectionFeatures: function (){
var sFeatures = [],
features = this.layer.selectedFeatures;
var i, len, feature;
if (this.safeSelection) {
var savedSF = this.selection;
if (savedSF) {
for (i=0, len = features.length; i<len; ++i) {
feature = features[i];
if (feature.cluster) {
// Not all features may be selected on a cluster
var clusterFeatures = feature.cluster;
for (var ii = 0 , llen = clusterFeatures.length; ii <llen; ii++) {
var cFeature = clusterFeatures[ii];
if (cFeature.fid) {
if (savedSF[cFeature.fid]) {
sFeatures.push(cFeature);
}
} else if (savedSF[cFeature.id]) {
sFeatures.push(cFeature);
}
}
} else {
sFeatures.push(feature);
}
}
}
} else {
sFeatures = this.getSingleFeatures(features);
}
return sFeatures;
},
/**
* APIFunction: getSelectionIds
*/
getSelectionIds: function (){
var ids = [];
if (this.safeSelection) {
var id,
savedSF = this.selection;
for (id in savedSF) {
ids.push(id);
}
} else {
var i, len,
features = this.layer.selectedFeatures;
for (i=0, len = features.length; i<len; ++i) {
ids.push(features[i].id);
}
}
return ids;
},
/**
* Function: getSingleFeatures
*/
getSingleFeatures: function (features){
var sFeatures = [];
var i, len, feature;
for (i=0, len = features.length; i<len; ++i) {
feature = features[i];
if (feature.cluster) {
Array.prototype.push.apply(sFeatures, feature.cluster);
} else {
sFeatures.push(feature);
}
}
return sFeatures;
},
/**
* Function: renderTemplate
* Given a string with tokens in the form ${token}, return a string
* with tokens replaced with properties from the given context
* object. Represent a literal "${" by doubling it, e.g. "${${".
*
* Parameters:
* template - {String || Function}
* If template is a string then template
* has the form "literal ${token}" where the token will be replaced
* by the value of context["token"]. When is a function it will receive
* the context as a argument.
* context - {Object} Object with properties corresponding to the tokens
* in the template.
*
* Returns:
* {String} A string with tokens replaced from the context object.
*/
renderTemplate: function (template, context) {
if (typeof template == 'string') {
return OpenLayers.String.format(template, context)
} else if (typeof template == 'function') {
return template(context);
} else {
return "";
}
},
CLASS_NAME: "OpenLayers.Control.FeaturePopups.Layer"
}); | lib/FeaturePopups.js | /* Copyright 2011-2012 Xavier Mamano, http://github.com/jorix/OL-FeaturePopups
* Published under MIT license. All rights reserved. */
/**
* requires OpenLayers/Control/SelectFeature.js
* requires OpenLayers/Lang.js
* requires OpenLayers/Popup.js
*/
/**
* Class: OpenLayers.Control.FeaturePopups
* The FeaturePopups control selects vector features from a given layers on
* click and hover and can show the feature attributes in a popups.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.FeaturePopups = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: mode
* To enable or disable the various behaviors of the control.
*
* Use bitwise operators and one or more of OpenLayers.Control.FeaturePopups:
* NONE - To not activate any particular behavior.
* CLOSE_ON_REMOVE -Popups will close when removing features in a layer,
* is ignored when used in conjunction with SAFE_SELECTION.
* SAFE_SELECTION - Features will remain selected even have been removed
* from the layer. Is useful when using <OpenLayers.Strategy.BBOX> with
* features with "fid" or when using <OpenLayers.Strategy.Cluster>.
* Using "BBOX" when a feature is added back to the layer will be
* re-selected automatically by "fid".
* CLOSE_ON_UNSELECT - Popups will close when unselect the feature.
* CLOSE_BOX - Display a close box inside the popups.
* UNSELECT_ON_CLOSE - To unselect all features when a popup is closed.
* DEFAULT - Includes default behaviors SAFE_SELECTION |
* CLOSE_ON_UNSELECT | CLOSE_BOX | UNSELECT_ON_CLOSE
*
* Default is <OpenLayers.Control.FeaturePopups.DEFAULT>.
*/
mode: null,
/**
* APIProperty: autoActivate
* {Boolean} Activate the control when it is added to a map. Default is
* true.
*/
autoActivate: true,
/**
* APIProperty: selectOptions
* {Object|null} Used to set non-default properties on SelectFeature control
* dedicated to select features. When using a null value the select
* features control is not created. The default is create the control.
*
* Default options other than SelectFeature control:
* - clickout: false
* - multipleKey: 'shiftKey'
* - toggleKey: 'shiftKey'
*
* Options ignored:
* - highlightOnly: always false.
* - box: always false (use <boxSelectionOptions>).
*/
selectOptions: null,
/**
* APIProperty: boxSelectionOptions
* {Object|null} Used to set non-default properties on
* <OpenLayers.Handler.Box> dedicated to select features by a box.
* When using a null value the handler is not created.
* The default is do not create the handler, so don't use box selection.
*
* Default options other than Box handler:
* - KeyMask: OpenLayers.Handler.MOD_CTRL
* - boxDivClassName: 'olHandlerBoxSelectFeature'
*/
boxSelectionOptions: null,
/**
* APIProperty: hoverOptions
* {Object|null} Used to set non-default properties on SelectFeature control
* dedicated to highlight features. When using a null value (or
* selectOptions.hover == true) the highlight features control is
* not created. The default is create the control.
*
* Options ignored:
* - hover: always true
* - highlightOnly: always true
* - box: always false (use <boxSelectionOptions>).
*/
hoverOptions: null,
/**
* APIProperty: popupHoverOptions
* {Object} Options used to create the popup manager for to highlight on
* to hover. See <FeaturePopups.Popup> constructor options for more
* details.
*
* Default options:
* popupClass - <OpenLayers.Popup.Anchored>
* followCursor - true
* anchor - {size: new OpenLayers.Size(15, 19), offset: new OpenLayers.Pixel(-1, -1)}
* relatedToClear - ["hoverList"]
*/
popupHoverOptions: null,
/**
* APIProperty: popupHoverListOptions
* {Object} Options used to create the popup manager for to highlight on
* to hover a cluster. See <FeaturePopups.Popup> constructor options
* for more details.
*
* Default options:
* popupClass - <OpenLayers.Popup.Anchored>
*
* Default options for internal use:
* followCursor - true
* anchor - {size: new OpenLayers.Size(15, 19), offset: new OpenLayers.Pixel(-1, -1)}
* relatedToClear - ["hover"]
*/
popupHoverListOptions: null,
/**
* APIProperty: popupSingleOptions
* {Object} Options used to create the popup manager for single selections.
* See <FeaturePopups.Popup> constructor options for more details.
*
* Default options:
* popupClass - <OpenLayers.Popup.FramedCloud>
*
* Default options for internal use:
* unselectOnClose - Depends on the <mode>
* closeBox - Depends on the <mode>
* observeItems - true
* relatedToClear: ["hover", "hoverList", "list", "listItem"]
*/
popupSingleOptions: null,
/**
* APIProperty: popupListOptions
* {Object} Options used to create the popup manager for multiple selections.
* See <FeaturePopups.Popup> constructor options for more details.
*
* Default options:
* popupClass - <OpenLayers.Popup.FramedCloud>
*
* Default options for internal use:
* unselectOnClose - Depends on the <mode>
* closeBox - Depends on the <mode>
* observeItems - true
* relatedToClear - ["hover", "hoverList", "single", "listItem"]
*/
popupListOptions: null,
/**
* APIProperty: popupListItemOptions
* {Object} Options used to create the popup manager for show a single item
* into a multiple selection. See <FeaturePopups.Popup> constructor
* options for more details.
*
* Default options:
* popupClass - <OpenLayers.Popup.FramedCloud>
*
* Default options for internal use:
* closeBox - Depends on the <mode>
*/
popupListItemOptions: null,
/**
* APIProperty: layerListTemplate
* Default is "<h2>${layer.name} - ${count}</h2><ul>${html}</ul>"
*/
layerListTemplate: "<h2>${layer.name} - ${count}</h2><ul>${html}</ul>",
/**
* APIProperty: hoverClusterTemplate
* Default is "Cluster with ${cluster.length} features<br>on layer \"${layer.name}\"
*/
hoverClusterTemplate: "${i18n('Cluster with ${count} features<br>on layer \"${layer.name}\"')}",
/**
* Property: regExesI18n
* {RegEx} Used to internationalize templates.
*/
regExesI18n: /\$\{i18n\(["']?([\s\S]+?)["']?\)\}/g,
/**
* Property: regExesShow
* {RegEx} Used to activate events in the html elements to show individual
* popup.
*/
regExesShow: /\$\{showPopup\((|id|fid)\)(\w*)\}/g,
/**
* Property: regExesAttributes
* {RegEx} Used to omit the name "attributes" as ${.myPropertyName} instead
* of ${attributes.myPropertyName} to show data on a popup using templates.
*/
regExesAttributes: /\$\{\./g,
/**
* Property: selectingSet
* {Boolean} The control set to true this property while being selected a
* set of features to can ignore individual selection, internal use only.
*/
selectingSet: false,
/**
* Property: unselectingAll
* {Boolean} The control set to true this property while being unselected
* all features to can ignore individual unselection, internal use only.
*/
unselectingAll: false,
/**
* Property: hoverListeners
* {Object} hoverListeners object will be registered with
* <OpenLayers.Events.on> on hover control, internal use only.
*/
hoverListeners: null,
/**
* Property: layerListeners
* {Object} layerListeners object will be registered with
* <OpenLayers.Events.on>, internal use only.
*/
layerListeners: null,
/**
* Property: popupObjs
* {Object} Internal use only.
*/
popupObjs: null,
/**
* Property: controls
* {Object} Internal use only.
*/
controls: null,
/**
* Property: layerObjs
* {Object} stores templates and others objects of this control's layers,
* internal use only.
*/
layerObjs: null,
/**
* Property: layers
* {Array(<OpenLayers.Layer.Vector>)} The layers this control will work on,
* internal use only.
*/
layers: null,
/**
* Property: refreshDelay
* {Number} Number of accepted milliseconds of waiting between removing and
* re-add features (useful when using strategies such as BBOX), after
* this time has expired is forced a popup refresh.
*/
refreshDelay: 300,
/**
* Property: delayedRefresh
* {Number} Timeout id of forced a refresh.
*/
delayedRefresh: null,
/**
* Property: delayedRefreshLayers
* {Object} To store the current layers to refresh.
*/
delayedRefreshLayers: null,
/**
* Constructor: OpenLayers.Control.FeaturePopups
* Create a new control that internally uses two
* <OpenLayers.Control.SelectFeature> one for selecting features, and
* another only to highlight them by hover (see <selectOptions>,
* and <hoverOptions>). This control can use also a
* <OpenLayers.Handler.Box> to select features by a box, see
* <boxSelectionOptions> .
*
* The control can generates three types of popup: "hover", "single" and
* "list", see <addLayer>.
* Each popup has a displayClass according to their type:
* "[displayClass]_hover" ,"[displayClass]_select" and
* "[displayClass]_list" respectively.
*
* options - {Object}
*/
initialize: function (options) {
// Options
// -------
options = OpenLayers.Util.applyDefaults(options, {
mode: OpenLayers.Control.FeaturePopups.DEFAULT
});
var layers = options.layers;
delete options.layers;
OpenLayers.Control.prototype.initialize.call(this, options);
// Internal Objects
// ----------------
this.layerObjs = {};
this.delayedRefreshLayers = {};
this.layers = [];
// Controls
// --------
this.controls = {};
var self = this; // to do some tricks.
// Hover control
if (options.hoverOptions !== null && !(this.selectOptions && this.selectOptions.hover)) {
var hoverOptions = OpenLayers.Util.extend(this.hoverOptions, {
hover: true,
highlightOnly: true,
box: false
});
var hoverClass = OpenLayers.Class(OpenLayers.Control.SelectFeature, {
// Trick to close hover popup when hover over selected feature an leave it.
outFeature: function (feature) {
if (feature._lastHighlighter === this.id) {
if (feature._prevHighlighter &&
feature._prevHighlighter !== this.id) {
this.events.triggerEvent(
"featureunhighlighted", {feature: feature});
}
}
OpenLayers.Control.SelectFeature.prototype.outFeature.apply(
this, arguments);
}
});
var controlHover = new hoverClass([], hoverOptions);
this.hoverListeners = {
scope: this,
featurehighlighted: this.onFeaturehighlighted,
featureunhighlighted: this.onFeatureunhighlighted
};
controlHover.events.on(this.hoverListeners);
this.controls.hover = controlHover;
}
// Select control
if (options.selectOptions !== null) {
var selOptions = OpenLayers.Util.applyDefaults(this.selectOptions, {
clickout: false,
multipleKey: 'shiftKey',
toggleKey: 'shiftKey'
});
OpenLayers.Util.extend(selOptions, {box: false, highlightOnly: false});
var selectClass = OpenLayers.Class(OpenLayers.Control.SelectFeature, {
// Trick to close hover popup when the feature is selected.
highlight: function (feature) {
var _lastHighlighter = feature._lastHighlighter;
OpenLayers.Control.SelectFeature.prototype.highlight.apply(
this, arguments);
if (controlHover && _lastHighlighter &&
_lastHighlighter !== feature._lastHighlighter) {
controlHover.events.triggerEvent(
"featureunhighlighted", {feature: feature});
}
}
});
var control = new selectClass([], selOptions);
if (this.boxSelectionOptions) {
// Handler for the trick to manage selection box.
this.handlerBox = new OpenLayers.Handler.Box(
this, {
done: this.onSelectBox
},
OpenLayers.Util.applyDefaults(this.boxSelectionOptions, {
boxDivClassName: "olHandlerBoxSelectFeature",
keyMask: OpenLayers.Handler.MOD_CTRL
})
);
}
// Trick to refresh popups when click a feature of a multiple selection.
control.unselectAll = function (options) {
self.unselectingAll = true;
OpenLayers.Control.SelectFeature.prototype.unselectAll.apply(
this, arguments);
self.unselectingAll = false;
if (options && options.except) {
var layerId = options.except.layer.id,
layerObj = self.layerObjs[layerId];
if (layerObj.safeSelection) {
layerObj.storeAsSelected(options.except);
}
}
self.refreshLayers();
};
this.controls.select = control;
}
// Popup Object Managers
// ---------------------
var _closeBox = !!(this.mode & OpenLayers.Control.FeaturePopups.CLOSE_BOX),
_unselectOnClose = !!(this.mode & OpenLayers.Control.FeaturePopups.UNSELECT_ON_CLOSE);
var popupObjs = {};
if (options.popupListOptions !== null) {
popupObjs.list = new OpenLayers.Control.FeaturePopups.Popup(
this, "list",
OpenLayers.Util.applyDefaults(options.popupListOptions, {
popupClass: OpenLayers.Popup.FramedCloud,
// options for internal use
closeBox: _closeBox,
unselectOnClose: _unselectOnClose,
observeItems: true,
relatedToClear: ["hover", "hoverList", "single", "listItem"]
})
);
}
if (options.popupSingleOptions !== null) {
popupObjs.single = new OpenLayers.Control.FeaturePopups.Popup(
this, "single",
OpenLayers.Util.applyDefaults(options.popupSingleOptions, {
popupClass: OpenLayers.Popup.FramedCloud,
// options for internal use
closeBox: _closeBox,
unselectOnClose: _unselectOnClose,
relatedToClear: ["hover", "hoverList", "list", "listItem"]
})
);
}
if (options.popupListItemOptions !== null) {
popupObjs.listItem = new OpenLayers.Control.FeaturePopups.Popup(
this, "listItem",
OpenLayers.Util.applyDefaults(options.popupListItemOptions, {
popupClass: OpenLayers.Popup.FramedCloud,
// options for internal use
closeBox: _closeBox
})
);
}
if (options.popupHoverOptions !== null) {
popupObjs.hover = new OpenLayers.Control.FeaturePopups.Popup(
this, "hover",
OpenLayers.Util.applyDefaults(options.popupHoverOptions, {
popupClass: OpenLayers.Popup.Anchored,
followCursor: true,
anchor: {
size: new OpenLayers.Size(15, 19),
offset: new OpenLayers.Pixel(-1, -1)
},
relatedToClear: ["hoverList"]
})
);
}
if (options.popupHoverListOptions !== null) {
popupObjs.hoverList = new OpenLayers.Control.FeaturePopups.Popup(
this, "hoverList",
OpenLayers.Util.applyDefaults(options.popupHoverListOptions, {
popupClass: OpenLayers.Popup.Anchored,
followCursor: true,
anchor: {
size: new OpenLayers.Size(15, 19),
offset: new OpenLayers.Pixel(-1, -1)
},
relatedToClear: ["hover"]
})
);
}
this.popupObjs = popupObjs;
// Add layers
// ----------------
layers && this.addLayers(layers);
},
/**
* APIMethod: destroy
*/
destroy: function () {
this.deactivate();
this.layerListeners = null;
for (var popupType in this.popupObjs) {
this.popupObjs[popupType].destroy();
}
this.popupObjs = null;
for (var layerId in this.layerObjs) {
this.layerObjs[layerId].destroy();
}
this.layerObjs = null;
this.layers = null;
this.handlerBox && this.handlerBox.destroy();
this.handlerBox = null;
this.controls.select && this.controls.select.destroy();
if (this.controls.hover) {
this.controls.hover.events.un(this.hoverListeners);
this.controls.hover.destroy();
}
this.controls = null;
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
* This control does not have HTML component, so this method should be empty.
*/
draw: function() {},
/**
* APIMethod: activate
* Activates the control.
*
* Returns:
* {Boolean} The control was effectively activated.
*/
activate: function () {
if (!this.events) { // This should be in OpenLayers.Control: Can not activate a destroyed control.
return false;
}
if (OpenLayers.Control.prototype.activate.apply(this, arguments)) {
this.map.events.on({
scope: this,
"addlayer": this.onAddlayer,
"removelayer": this.onRemovelayer,
"changelayer": this.onChangelayer
});
var controls = this.controls;
if (controls.hover) {
controls.hover.setLayer(this.layers);
controls.hover.activate();
}
this.handlerBox && this.handlerBox.activate();
if (controls.select) {
controls.select.setLayer(this.layers);
controls.select.activate();
}
for (var layerId in this.layerObjs) {
this.layerObjs[layerId].activate();
}
this.refreshLayers();
return true;
} else {
return false;
}
},
/**
* APIMethod: deactivate
* Deactivates the control.
*
* Returns:
* {Boolean} The control was effectively deactivated.
*/
deactivate: function () {
if (OpenLayers.Control.prototype.deactivate.apply(this, arguments)) {
this.map.events.un({
scope: this,
"addlayer": this.onAddlayer,
"removelayer": this.onRemovelayer
});
for (var layerId in this.layerObjs) {
this.layerObjs[layerId].deactivate();
}
this.handlerBox && this.handlerBox.deactivate();
var controls = this.controls;
controls.hover && controls.hover.deactivate();
controls.select && controls.select.deactivate();
for (var popupType in this.popupObjs) {
this.popupObjs[popupType].clearPopup();
}
return true;
} else {
return false;
}
},
/**
* Method: setMap
* Set the map property for the control.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
if (this.boxSelectionOptions &&
this.boxSelectionOptions.keyMask === OpenLayers.Handler.MOD_CTRL) {
// To disable the context menu for machines which use CTRL-Click as a right click.
map.viewPortDiv.oncontextmenu = OpenLayers.Function.False;
}
this.controls.hover && map.addControl(this.controls.hover);
this.controls.select && map.addControl(this.controls.select);
this.handlerBox && this.handlerBox.setMap(map);
OpenLayers.Control.prototype.setMap.apply(this, arguments);
},
/**
* Method: onAddlayer
* Listens only if the control it is active, internal use only.
*/
onAddlayer: function (evt) {
var layerObj = this.layerObjs[evt.layer.id];
if (layerObj) {
// Set layers in the control when added to the map after activating this control.
var controls = this.controls;
controls.hover && controls.hover.setLayer(this.layers);
controls.select && controls.select.setLayer(this.layers);
layerObj.activate();
this.refreshLayers();
}
},
/**
* Method: onRemovelayer
* Internal use only.
*/
onRemovelayer: function (evt) {
this.removeLayer(evt.layer);
},
/**
* Method: onChangelayer
* Internal use only.
*/
onChangelayer: function (evt) {
var layerObj = this.layerObjs[evt.layer.id];
if (layerObj && evt.property === "visibility") {
layerObj.setRefreshPending();
this.refreshLayers();
}
},
/**
* APIMethod: addLayer
* Add the layer to control and assigns it the templates, see options.
* Layers are automatically assigned if they have the properties for any of
* the three types of templates: "hoverPopupTemplate",
* "selectPopupTemplate" and "itemPopupTemplate".
* In a layer can also specify a "listPopupTemplate" (default is
* <layerListTemplate>), this template is ignored if not
* specified in conjunction with "itemPopupTemplate".
*
* To add a layer that has already been added (maybe automatically),
* first must be removed using <removeLayer>.
*
* Templates containing patterns as ${i18n("key")} are internationalized
* using <OpenLayers.i18n> function.
*
* The control uses the patterns as ${showPopup()} in "itemPopupTemplate"
* to show individual popups from a list. This pattern becomes a
* combination of the layer.id+feature.id and can be used only as an
* html attribute.
* It is convenient to use ${showPopup(fid)} instead of ${showPopup()}
* when the layer features have fid, this ensures that the popups from
* a list is still shown after zoom, even if a BBOX strategies is used.
* When various html elements (in the same "itemPopupTemplate") uses
* ${showPopup()} should differentiate by a suffix in order to avoid
* duplicate id, eg:
* (code)
* itemPopupTemplate: '<span ${showPopup()1} >...</span><br>' +
* '<img ${showPopup()2} src="...">', ...
* (code)
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>}
* options - {Object} Optional
*
* Valid options:
* templates - {Object} Templates
* eventListeners - {Object} This object will be registered with
* <OpenLayers.Events.on>, default scope is the control.
*
* Valid templates:
* single - {String || Function} template used to show a single feature.
* list - {String || Function} template used to show selected
* features as a list (each feature is shown using "itemTemplate"),
* defaul is <layerListTemplate>.
* item - {String || Function} template used to show a feature as
* a item in a list.
* hover - {String || Function} template used on hover a single feature.
* hoverList - {String || Function} template used on hover a clustered feature.
* hoverItem - {String || Function} template used to show a feature as
* a item in a list on hover a clustered feature.
*
* If specified some template as layer property and as options has priority
* the options template.
*
* Valid events on eventListeners:
* selectionchanged - Triggered after selection is changed, receives a event
* with "layer" and "selection" as array of features (note that
* features are not clustered and in this case may lack the property
* layer)
* featureschanged - Triggered after layer features are changed, fired only
* changing the list of features and ignore the clusters changes or
* recharge if obtained new features but with the same "fid". Receives
* a event with "layer" and "features" as array of features (note that
* features are not clustered and in this case may lack the property
* layer)
*
* Default scope for eventListeners is the control.
*/
addLayer: function (layer, options) {
this.addLayers([[layer, options]]);
},
/**
* APIMethod: addLayers
*
* Parameters:
* layers - Array({<OpenLayers.Layer.Vector>} || Array({Object})) Layers to
* add, and array of layers or pairs of arguments layer and options.
*/
addLayers: function (layers) {
var activated = false,
layerItem;
for (var i = 0, len = layers.length; i < len; i++) {
layerItem = layers[i];
if (OpenLayers.Util.isArray(layerItem)) {
activated = activated ||
this.addLayerToControl.apply(this, layerItem).active;
} else {
activated = activated ||
this.addLayerToControl(layerItem).active;
}
}
if (activated) {
var controls = this.controls;
controls.hover && controls.hover.setLayer(this.layers);
controls.select && controls.select.setLayer(this.layers);
this.refreshLayers();
}
},
/**
* Method: addLayerToControl
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>}
* options - {Object}
*/
addLayerToControl: function (layer, options) {
var layerId = layer.id,
layerObj = this.layerObjs[layerId];
if (!layerObj) {
options = OpenLayers.Util.applyDefaults(options, {templates: {} });
var oTemplates = options.templates;
OpenLayers.Util.applyDefaults(options.templates, {
list: (oTemplates.item? this.layerListTemplate: ""),
hoverList: (
(oTemplates.hover || oTemplates.hoverItem)?
this.hoverClusterTemplate: "")
});
layerObj = new OpenLayers.Control.FeaturePopups.Layer(
this, layer, options);
this.layers.push(layer);
this.layerObjs[layerId] = layerObj;
this.active && layerObj.activate();
}
return layerObj;
},
/**
* APIMethod: removeLayer
*/
removeLayer: function (layer) {
var layerId = layer.id,
layerObj = this.layerObjs[layerId];
if (layerObj) {
if (this.active) {
this.active && layerObj.clear();
this.controls.hover && this.controls.hover.setLayer(this.layers);
this.controls.select && this.controls.select.setLayer(this.layers);
}
layerObj.destroy();
OpenLayers.Util.removeItem(this.layers, layer);
delete this.layerObj[layerId];;
}
},
/**
* Method: onSelectBox
* Callback from the handlerBox set up when <selectBox> is true.
*
* Parameters:
* position - {<OpenLayers.Bounds> || <OpenLayers.Pixel>}
*/
onSelectBox: function(position) {
// Trick to not show individual features when using a selection box.
this.selectingSet = true;
OpenLayers.Control.SelectFeature.prototype.selectBox.apply(
this.controls.select, arguments);
this.selectingSet = false;
this.refreshLayers();
},
/**
* Method: onFeaturehighlighted
* Internal use only.
*/
onFeaturehighlighted: function (evt) {
var feature = evt.feature,
layerObj = this.layerObjs[feature.layer.id];
layerObj.highlightFeature(feature);
},
/**
* Method: onFeatureunhighlighted
*/
onFeatureunhighlighted: function (evt) {
this.popupObjs.hover && this.popupObjs.hover.clear();
},
/**
* APIMethod: showSingleFeatureById
*
* Parameters:
* layerId - {String} id of the layer of selected feature.
* featureId - {String} id of the feature.
* idName - {String} Name of id: "id" or "fid".
*/
showSingleFeatureById: function (layerId, featureId, idName) {
var layerObj = this.layerObjs[layerId];
if (layerObj) {
layerObj.showSingleFeatureById(featureId, idName);
} else {
var popupObj = this.popupObjs.listItem;
popupObj && popupObj.clear();
}
},
/**
* APIMethod: addSelectionByIds
*
* Parameters:
* layerId - {String} id of the layer.
* featureIds - {Array(String)} List of feature ids to be
* added to selection.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
addSelectionByIds: function (layerId, featureIds, silent) {
var layerObj = this.layerObjs[layerId];
layerObj && layerObj.addSelectionByIds(featureIds, silent);
},
/**
* APIMethod: setSelectionByIds
*
* Parameters:
* layerId - {String} id of the layer.
* featureIds - {Array(String)} List of feature ids to set as select.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
setSelectionByIds: function (layerId, featureIds, silent) {
var layerObj = this.layerObjs[layerId];
layerObj && layerObj.setSelectionByIds(featureIds, silent);
},
/**
* APIMethod: removeSelectionByIds
*
* Parameters:
* layerId - {String} id of the layer.
* featureIds - {Array(String)} List of feature ids to be
* removed to selection.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
removeSelectionByIds: function (layerId, featureIds, silent) {
var layerObj = this.layerObjs[layerId];
layerObj && layerObj.removeSelectionByIds(featureIds, silent);
},
/**
* APIFunction: getSelectionIds
*/
getSelectionIds: function (layer){
var layerObj = this.layerObjs[layer.id];
if (layerObj) {
return layerObj.getSelectionIds();
} else {
return [];
}
},
/**
* Method: delayRefreshLayer
* Used by LayerObjs
*/
delayRefreshLayer: function (layerId) {
this.delayedRefreshLayers[layerId] = true;
if (this.delayedRefresh !== null) {
window.clearTimeout(this.delayedRefresh);
}
this.delayedRefresh = window.setTimeout(
OpenLayers.Function.bind(
function() {
this.delayedRefresh = null;
for (var layerId in this.delayedRefreshLayers) {
var layerObj = this.layerObjs[layerId];
layerObj && layerObj.setRefreshPending();
}
this.delayedRefreshLayers = {};
this.refreshLayers();
},
this
),
this.refreshDelay
);
},
/**
* Method: endDelayRefreshLayer
* Used by LayerObjs
*/
endDelayRefreshLayer: function (layerId) {
if (this.delayedRefreshLayers[layerId]) {
delete this.delayedRefreshLayers[layerId];
}
var isEmpty = true;
for(var prop in this.delayedRefreshLayers) {
isEmpty = false;
break;
}
if (isEmpty) {
this.refreshLayers();
}
},
/**
* Method: refreshLayers
*/
refreshLayers: function (useCursorLocation) {
if (this.delayedRefresh !== null) {
window.clearTimeout(this.delayedRefresh);
this.delayedRefresh = null;
this.delayedRefreshLayers = {};
}
var layers = OpenLayers.Array.filter(this.layers,
function(layer) {
return !!layer.map;
}
);
var bounds = new OpenLayers.Bounds(),
invalid = false,
html = [],
countSelected = 0,
sFeature0 = null,
allSelFeatures = [];
var layerObj, lenAux, r;
for (var layerId in this.layerObjs) {
layerObj = this.layerObjs[layerId];
r = layerObj.getListHtml(bounds);
html.push(r.html);
invalid = invalid || r.invalid;
if (r.features.length) {
allSelFeatures.push({layer:layerObj.layer, features:r.features});
lenAux = layerObj.layer.selectedFeatures.length;
countSelected += lenAux;
if (lenAux === 1 && countSelected === 1) {
sFeature0 = layerObj.layer.selectedFeatures[0];
}
}
}
if (invalid) {
var feature,
response = false;
// only one single feature is selected? so... try to show
if (this.popupObjs.single && allSelFeatures.length === 1 &&
allSelFeatures[0].features.length === 1) {
var selObject = allSelFeatures[0],
feature = selObject.features[0];
var rr = this.layerObjs[selObject.layer.id].getSingleHtml(feature)
if (rr.hasTemplate) {
this.popupObjs.single.showPopup(feature, rr.lonLat, rr.html);
response = !!this.popupObjs.single.popup;
}
}
if (this.popupObjs.list && !response) {
var lonLat = (useCursorLocation && countSelected === 1)? // so is only one cluster
this.getLocationFromSelPixel(this.controls.select, sFeature0):
bounds.getCenterLonLat();
this.popupObjs.list.showPopup(
allSelFeatures,
lonLat,
(allSelFeatures.length? html.join("\n"): "")
);
}
}
},
/**
* function: getLocationFromSelPixel
* Get selection location.
*
* Parameters:
* selControls - {<OpenLayers.Control.SelectFeature>}
* feature - {<OpenLayers.Feature.Vector>}
*
* Retruns:
* {<OpenLayers.LonLat>} Location from pixel pixel where the feature was
* selected.
*/
getLocationFromSelPixel: function (selControl, feature) {
var lonLat,
handler = selControl.handlers.feature;
var xy = (handler.feature === feature)? handler.evt.xy: null;
return (xy? this.map.getLonLatFromPixel(xy):
feature.geometry.getBounds().getCenterLonLat()
);
},
/**
* Function: prepareTemplate
* When the template is a string returns a prepared template,
* otherwise returns it as is, see more in <addLayer>.
* This function is used at creating a instance of the control and when
* <addLayer> method is called.
*
* Parameters:
* template - {String || Function}
*
* Returns:
* {String || Function} A internationalized template.
*/
prepareTemplate: function (template) {
if (typeof template == 'string') {
template = template.replace(
this.regExesShow,
function (a, idName, subId) {
idName = idName || "id";
return "id=\"showPopup-${layer.id}-" + idName + "-${" + idName + "}-" + subId + "\"";
}
);
template = template.replace(
this.regExesAttributes,
"${attributes."
);
return template.replace( // internationalize template.
this.regExesI18n,
function (a,key) {
return OpenLayers.i18n(key);
}
);
} else {
return template;
}
},
CLASS_NAME: "OpenLayers.Control.FeaturePopups"
});
/**
* Constant: NONE
* {Integer} Used in <mode> indicates to not activate any particular behavior.
*/
OpenLayers.Control.FeaturePopups.NONE = 0;
/**
* Constant: CLOSE_ON_REMOVE
* {Integer} Used in <mode> indicates that the popups will close when
* removing features in a layer.
*/
OpenLayers.Control.FeaturePopups.CLOSE_ON_REMOVE = 1;
/**
* Constant: SAFE_SELECTION
* {Integer} Used in <mode> indicates that the features will remain
* selected even have been removed from the layer. Is useful when using
* <OpenLayers.Strategy.BBOX> with features with "fid" or when using
* <OpenLayers.Strategy.Cluster>. Using "BBOX" when a feature is added
* back to the layer will be re-selected automatically by "fid".
*/
OpenLayers.Control.FeaturePopups.SAFE_SELECTION = 2;
/**
* Constant: CLOSE_ON_UNSELECT
* {Integer} Used in <mode> indicates that the popups will close when
* unselect the feature.
*/
OpenLayers.Control.FeaturePopups.CLOSE_ON_UNSELECT = 4;
/**
* Constant: CLOSE_BOX
* {Integer} Used in <mode> indicates to display a close box inside the popups.
*/
OpenLayers.Control.FeaturePopups.CLOSE_BOX = 8;
/**
* Constant: UNSELECT_ON_CLOSE
* {Integer} Used in <mode> indicates to unselect all features when a popup is
* closed.
*/
OpenLayers.Control.FeaturePopups.UNSELECT_ON_CLOSE = 16;
/**
* Constant: DEFAULT
* {Integer} Used in <mode> indicates to activate default behaviors
* <SAFE_SELECTION> <CLOSE_ON_UNSELECT> <CLOSE_BOX> and <UNSELECT_ON_CLOSE>.
*/
OpenLayers.Control.FeaturePopups.DEFAULT =
OpenLayers.Control.FeaturePopups.SAFE_SELECTION |
OpenLayers.Control.FeaturePopups.CLOSE_ON_UNSELECT |
OpenLayers.Control.FeaturePopups.CLOSE_BOX |
OpenLayers.Control.FeaturePopups.UNSELECT_ON_CLOSE;
/**
* Class: OpenLayers.Control.FeaturePopups.Popup
*/
OpenLayers.Control.FeaturePopups.Popup = OpenLayers.Class({
/**
* APIProperty: events
* {<OpenLayers.Events>} Events instance for listeners and triggering
* specific events.
*
* Supported event types:
* beforepopupdisplayed - Triggered before a popup is displayed.
* To stop the popup from being displayed, a listener should return
* false. Receives an event with; "popupType" see <Constructor>,
* "selection" a feature except for the "list" porupType that is
* an array of pairs "layer" and "features", "popupClass" popupClass
* that will be used to display the popup.
* popupdisplayed - Triggered after a popup is displayed. Receives an event
* with; "popupType" see <Constructor>, "selection" a feature except
* for the "list" porupType that is an array of pairs "layer" and
* "features", "div" the DOMElement used by the popup and "popup" the
* instance of the popup class that has shown the popup.
* closedbybox - Triggered after close a popup using close box. Receives
* an event with "popupType" see <Constructor>
*/
events: null,
/**
* Constant: EVENT_TYPES
* Only required to use <OpenLayers.Control.FeaturePopups> with 2.11 or less
*/
EVENT_TYPES: ["beforepopupdisplayed", "popupdisplayed", "closedbybox"],
/**
* APIProperty: eventListeners
* {Object} If set on options at construction, the eventListeners
* object will be registered with <OpenLayers.Events.on>. Object
* structure must be a listeners object as shown in the example for
* the events.on method.
*/
eventListeners: null,
/** APIProperty: control
* {<OpenLayers.Control.FeaturePopups>} The control that initialized this
* popup manager.
*/
control: null,
/** APIProperty: type
* {String} Type of popup manager, read only.
*/
type: "",
/** APIProperty: popupClass
* {String|<OpenLayers.Popup>|Function} Type of popup to manage.
*/
popupClass: null,
/**
* APIProperty: anchor
* {Object} Object to which we'll anchor the popup. Must expose a
* 'size' (<OpenLayers.Size>) and 'offset' (<OpenLayers.Pixel>).
*/
anchor: null,
/**
* APIProperty: minSize
* {<OpenLayers.Size>} Minimum size allowed for the popup's contents.
*/
minSize: null,
/**
* APIProperty: maxSize
* {<OpenLayers.Size>} Maximum size allowed for the popup's contents.
*/
maxSize: null,
/**
* APIProperty: unselectOnClose
* {Boolean} If true, closing a popup all features are unselected on
* control.controls.select.
*/
unselectOnClose: false,
/**
* APIProperty: closeBox
* {Boolean} To display a close box inside the popup.
*/
closeBox: false,
/**
* Property: observeItems
* {Boolean} If true, will be activated observers of the DOMElement of the
* popup to trigger some events (mostly in list popups).
*/
observeItems: false,
/**
* Property: relatedToClear
* Array({String}) Related <FeaturePopups.popupObjs> codes from <control>
* to clear.
*/
relatedToClear: [],
/** Property: popupType
* {String} Code of type of popup to manage: "div", "OL" or "custom"
*/
popupType: "",
/**
* Property: popup
* {Boolean|<OpenLayers.Popup>} True or instance of OpenLayers.Popup when
* popup is showing.
*/
popup: null,
/**
* Property: clearCustom
* {Function|null} stores while displaying a custom popup the function to
* clear the popup, this function is returned by the custom popup.
*/
clearCustom: null,
/**
* Property: onCloseBoxMethod
* {Function|null} When the popup is created with closeBox argument to true,
* this property stores the method that implement any measures to close
* the popup, otherwise is null.
*/
onCloseBoxMethod: null,
/**
* Property: moveListener
* {Object} moveListener object will be registered with
* <OpenLayers.Events.on>, use only when <followCursor> is true.
*/
moveListener: null,
/**
* Constructor: OpenLayers.Control.FeaturePopups.Popup
* This class is a handler that is responsible for displaying and clear the
* one kind of popups managed by a <OpenLayers.Control.FeaturePopups>.
*
* The manager popup can handle three types of popups: a div a
* OpenLayers.Popup class or a custom popup, it depends on the type of
* "popupClass" argument.
*
* Parameters:
* control - {<OpenLayers.Control.FeaturePopups>} The control that
* initialized this popup manager.
* popupType - {String} Type of popup manager: "list", "single", "listItem"
* or "hover"
* options - {Object}
*
* Valid ptions:
* eventListeners - {Object} Listeners to register at object creation.
* minSize - {<OpenLayers.Size>} Minimum size allowed for the popup's contents.
* maxSize - {<OpenLayers.Size>} Maximum size allowed for the popup's contents.
* popupClass - {String|<OpenLayers.Popup>|Function} Type of popup to
* manage: string for a "id" of a DOMElement, OpenLayers.Popup and a
* function for a custom popup.
* anchor -{Object} Object to which we'll anchor the popup. Must expose a
* 'size' (<OpenLayers.Size>) and 'offset' (<OpenLayers.Pixel>).
* followCursor - {Boolean} If true, the popup will follow the cursor
* (useful for hover)
* unselectOnClose - {Boolean} If true, closing a popup all features are
* unselected on control.controls.select.
* closeBox - {Boolean} To display a close box inside the popup.
* observeItems - {Boolean} If true, will be activated observers of the
* DOMElement of the popup to trigger some events (mostly by list popups).
* relatedToClear - Array({String}) Related <FeaturePopups.popupObjs> codes
* from <control> to clear.
*/
initialize: function (control, popupType, options) {
// Options
OpenLayers.Util.extend(this, options);
if (this.maxSize) {
this.maxSize.w = isNaN(this.maxSize.w)? 999999: this.maxSize.w;
this.maxSize.h = isNaN(this.maxSize.h)? 999999: this.maxSize.h;
}
if (this.minSize) {
this.minSize.w = isNaN(this.minSize.w)? 0: this.minSize.w;
this.minSize.h = isNaN(this.minSize.h)? 0: this.minSize.h;
}
// Arguments
this.control = control;
this.type = popupType;
// close box
if (this.closeBox) {
this.onCloseBoxMethod = OpenLayers.Function.bind(
function(evt) {
if (this.unselectOnClose && control.controls.select) {
control.controls.select.unselectAll();
}
this.clear();
OpenLayers.Event.stop(evt);
this.events.triggerEvent("closedbybox", {popupType: this.type});
},
this
)
}
// Options
var popupClass = this.popupClass;
if (popupClass) {
if (typeof popupClass == "string") {
this.popupType = "div";
} else if (popupClass.prototype.CLASS_NAME &&
OpenLayers.String.startsWith(
popupClass.prototype.CLASS_NAME, "OpenLayers.Popup")) {
this.popupType = "OL";
this.popupClass = OpenLayers.Class(popupClass, {
autoSize: true,
minSize: this.minSize,
maxSize: this.maxSize,
contentDisplayClass:
popupClass.prototype.contentDisplayClass + " " +
control.displayClass + "_" + this.type
});
} else if (typeof popupClass == "function") {
this.popupType = "custom";
}
}
if (this.followCursor) {
this.moveListener = {
scope: this,
mousemove: function(evt) {
var popup = this.popup;
if (popup && popup.moveTo) {
var map = this.control.map;
popup.moveTo(
map.getLayerPxFromLonLat(
map.getLonLatFromPixel(evt.xy)));
}
}
};
}
this.events = new OpenLayers.Events(this, null, this.EVENT_TYPES);
this.eventListeners && this.events.on(this.eventListeners);
},
/**
* APIMethod: destroy
*/
destroy: function () {
this.clear();
this.eventListeners && this.events.un(this.eventListeners);
this.events.destroy();
this.events = null;
},
/**
* Method: showPopup
* Shows the popup if it has changed, and clears it previously
*
* Parameters:
* selection - {<OpenLayers.Feature.Vector>}|Object} Selected features.
* lonlat - {<OpenLayers.LonLat>} The position on the map the popup will
* be shown.
* html - {String} An HTML string to display inside the popup.
*/
showPopup: function (selection, lonLat, html) {
this.clear();
var popupClass = this.popupClass;
if (popupClass && html) {
var cont = this.events.triggerEvent("beforepopupdisplayed", {
popupType: this.type,
selection: selection,
popupClass: popupClass
});
if (cont !== false) {
// this alters "this.popup"
this.create(lonLat, html);
}
}
if (this.popup) {
this.observeItems && this.observeShowPopup(this.div);
this.events.triggerEvent("popupdisplayed", {
popupType: this.type,
selection: selection,
div: this.div,
popup: this.popup
});
}
},
/**
* Method: clear
* Internal use only.
*/
clear: function () {
this.clearPopup()
var popupObjs = this.control.popupObjs,
related;
for (var i = 0, len = this.relatedToClear.length; i <len; i++) {
related = popupObjs[this.relatedToClear[i]];
related && related.clearPopup();
}
},
/**
* Method: observeShowPopup
* Internal use only.
*
* Parameters:
* div - {DOMElement}
*/
observeShowPopup: function (div) {
for (var i = 0, len = div.childNodes.length; i < len; i++) {
var child = div.childNodes[i];
if (child.id && OpenLayers.String.startsWith(child.id,
"showPopup-OpenLayers")) {
OpenLayers.Event.observe(child, "touchend",
OpenLayers.Function.bindAsEventListener(this.showListItem, this.control));
OpenLayers.Event.observe(child, "click",
OpenLayers.Function.bindAsEventListener(this.showListItem, this.control));
} else {
this.observeShowPopup(child);
}
}
},
/**
* Method: showListItem
* Internal use only.
*
* Parameters:
* div - {DOMElement}
*
* Scope:
* - {<OpenLayers.Control.FeaturePopups>}
*/
showListItem: function (evt) {
var elem = OpenLayers.Event.element(evt);
if (elem.id) {
var ids = elem.id.split("-");
if (ids.length >= 3) {
this.showSingleFeatureById(ids[1], ids[3], ids[2]);
}
}
},
/**
* Method: removeChildren
* Internal use only.
*
* Parameters:
* div - {DOMElement}
*/
removeChildren: function (div) {
var child;
while (child = div.firstChild) {
if (child.id && OpenLayers.String.startsWith(child.id,
"showPopup-OpenLayers")) {
OpenLayers.Event.stopObservingElement(child);
}
this.removeChildren(child);
div.removeChild(child);
}
},
/**
* Method: create
* Create the popup.
*/
create: function (lonLat, html) {
var div, popup,
control = this.control;
switch (this.popupType) {
case "div":
div = document.getElementById(this.popupClass);
if (div) {
div.innerHTML = html;
this.div = div;
this.popup = true;
}
break;
case "OL":
control = this.control;
popup = new this.popupClass(
control.id + "_" + this.type,
lonLat,
new OpenLayers.Size(100,100),
html
);
if (this.anchor) {
popup.anchor = this.anchor;
}
if (this.onCloseBoxMethod) {
// The API of the popups is not homogeneous, closeBox may
// be the fifth or sixth argument, it depends!
// So forces closeBox using other ways.
popup.addCloseBox(this.onCloseBoxMethod);
popup.closeDiv.style.zIndex = 1;
}
control.map.addPopup(popup);
this.div = popup.contentDiv;
this.popup = popup;
this.moveListener && control.map.events.on(this.moveListener);
break;
case "custom":
var returnObj = this.popupClass(
control.map, lonLat, html, this.onCloseBoxMethod, this);
if (returnObj.div) {
this.clearCustom = returnObj.destroy;
this.div = returnObj.div;
this.popup = true;
}
break;
}
},
/**
* Method: clearPopup
* Clear the popup if it is showing.
*/
clearPopup: function () {
if (this.popup) {
this.observeItems && this.removeChildren(this.div);
switch (this.popupType) {
case "OL":
var control = this.control;
if (control.map) {
control.map.removePopup(this.popup);
}
this.popup.destroy();
this.moveListener && control.map.events.un(this.moveListener);
break;
case "custom":
if (this.popup) {
if (this.clearCustom) {
this.clearCustom();
this.clearCustom = null;
}
}
break;
}
this.div = null;
this.popup = null;
}
},
CLASS_NAME: "OpenLayers.Control.FeaturePopups.Popup"
});
/**
* Class: OpenLayers.Control.FeaturePopups.Layer
*/
OpenLayers.Control.FeaturePopups.Layer = OpenLayers.Class({
/**
* APIProperty: events
* {<OpenLayers.Events>} Events instance for listeners and triggering
* specific events.
*
* Supported event types:
*/
events: null,
/**
* Constant: EVENT_TYPES
* Only required to use <OpenLayers.Control.FeaturePopups> with 2.11 or less
*/
EVENT_TYPES: ["featureschanged", "selectionchanged"],
listenFeatures: false,
templates: null,
selection: {},
selectionHash: "",
featuresHash: "",
refreshPendig: null,
layerListeners: null,
safeSelection: false,
/**
* APIProperty: active
* {Boolean} The object is active (read-only)
*/
active: null,
/**
* Property: safeSelection
* {Boolean} True if <mode> contains
* OpenLayers.Control.FeaturePopups.SAFE_SELECTION.
*/
safeSelection: false,
/**
* Property: updatingSelection
* {Boolean} The control set to true this property while being refreshed
* selection on a set of features to can ignore others acctions,
* internal use only.
*/
updatingSelection: false,
/**
* Property: silentSelection
* {Boolean} Suppress "selectionchanged" event triggering during a selection
* process, internal use only.
*/
silentSelection: false,
/**
* Constructor: OpenLayers.Control.FeaturePopups.Layer
*/
initialize: function (control, layer, options) {
// Options
OpenLayers.Util.extend(this, options);
// Arguments
this.control = control;
this.layer = layer;
// Templates
var oTemplates = options && options.templates || {};
var templates = {};
for (var templateName in oTemplates) {
templates[templateName] =
control.prepareTemplate(oTemplates[templateName]);
}
this.templates = templates;
this.eventListeners = options.eventListeners,
// Events
this.events = new OpenLayers.Events(this, null, this.EVENT_TYPES);
if (this.eventListeners) {
this.events.on(this.eventListeners);
this.listenFeatures = !!(this.eventListeners &&
this.eventListeners["featureschanged"]);
}
// Layer listeners
// ---------------
this.safeSelection = !!(control.mode &
OpenLayers.Control.FeaturePopups.SAFE_SELECTION);
this.layerListeners = {
scope: this,
"featureselected": this.onFeatureselected
};
if (control.mode & OpenLayers.Control.FeaturePopups.CLOSE_ON_UNSELECT ||
this.safeSelection) {
this.layerListeners["featureunselected"] = this.onFeatureunselected;
}
if (this.safeSelection) {
this.layerListeners["beforefeaturesremoved"] = this.onBeforefeaturesremoved;
this.layerListeners["featuresadded"] = this.onFeaturesadded;
} else if (control.mode & OpenLayers.Control.FeaturePopups.CLOSE_ON_REMOVE) {
this.layerListeners["featuresremoved"] = this.onFeaturesremoved;
}
},
/**
* Method: destroy
*/
destroy: function() {
this.deactivate();
this.eventListeners && this.events.un(this.eventListeners);
this.events.destroy();
},
/**
* Method: activate
*/
activate: function () {
if (!this.active && this.layer.getVisibility() && this.layer.map) {
this.layer.events.on(this.layerListeners);
this.setRefreshPending();
this.active = true;
return true;
} else {
return false;
}
},
/**
* Method: deactivate
*/
deactivate: function(){
if (this.active) {
this.layer.events.un(this.layerListeners);
this.active = false;
return true;
} else {
return false;
}
},
/**
* Method: clear
*/
clear: function() {
if (this.active) {
if (!this.isEmptyObject(this.selection)) {
this.events.triggerEvent("selectionchanged", {
layer: this.layer,
control: this.control,
selection: []
});
}
if (this.featuresHash !== "" ) {
this.events.triggerEvent("featureschanged", {
layer: this.layer,
control: this.control,
features: []
});
}
}
this.selection = [];
this.selectionHash = "";
this.featuresHash = "";
},
/**
* Method: isEmptyObject
*
* Parameters:
* obj - {Object}
*/
isEmptyObject: function (obj) {
for(var prop in obj) {
return false;
}
return true;
},
/**
* Method: highlightFeature
* Internal use only.
*/
highlightFeature: function (feature) {
var control = this.control,
popupObjHover = control.popupObjs.hover;
if (!popupObjHover) { return; }
popupObjHover.clear();
var templates = this.templates,
template = templates.hover;
if (template) {
var lonLat = control.getLocationFromSelPixel(control.controls.hover,
feature);
if (feature.cluster) {
if (feature.cluster.length == 1){
// show cluster as a single feature.
popupObjHover.showPopup(feature, lonLat,
this.renderTemplate(
template,
this.cloneDummyFeature(
feature.cluster[0], feature.layer)
)
);
} else {
var html = "",
popupObjHoverList = control.popupObjs.hoverList;
if (popupObjHoverList) {
var cFeatures = feature.cluster,
itemTemplate = templates.hoverItem;
if (itemTemplate) {
var htmlAux = [];
for (var i = 0 , len = cFeatures.length; i <len; i++) {
htmlAux.push(this.renderTemplate(itemTemplate,
cFeatures[i]));
}
html = htmlAux.join("\n")
}
popupObjHoverList.showPopup(cFeatures, lonLat,
this.renderTemplate(templates.hoverList, {
layer: feature.layer,
count: cFeatures.length,
html: html
})
);
}
}
} else {
popupObjHover.showPopup(feature, lonLat,
this.renderTemplate(template, feature));
}
}
},
/**
* Method: onFeatureselected
*
* Parameters:
* evt - {Object}
*/
onFeatureselected: function (evt) {
if (!this.updatingSelection && this.safeSelection) {
this.storeAsSelected(evt.feature);
}
if (!this.control.selectingSet) {
this.control.refreshLayers(true);
}
},
/**
* Method: storeAsSelected
*
* Parameter:
* feature - {OpenLayers.Feature.Vector} Feature to store as selected.
*/
storeAsSelected: function (feature) {
var layerId = feature.layer.id;
var savedSF = this.selection,
fid = feature.fid;
if (fid) {
savedSF[fid] = true;
} else if (feature.cluster) {
for (var i = 0 , len = feature.cluster.length; i <len; i++) {
var cFeature = feature.cluster[i];
var fidfid = cFeature.fid;
if (fidfid) {
savedSF[fidfid] = true;
} else {
savedSF[cFeature.id] = true;
}
}
}
},
/**
* Method: onFeatureunselected
* Called when the select feature control unselects a feature.
*
* Parameters:
* evt - {Object}
*/
onFeatureunselected: function (evt) {
if (this.safeSelection) {
var savedSF = this.selection,
feature = evt.feature;
if (savedSF) {
var fid = feature.fid;
if (fid) {
delete savedSF[fid];
} else if (feature.cluster) {
for (var i = 0 , len = feature.cluster.length; i <len; i++) {
var cFeature = feature.cluster[i];
var fidfid = cFeature.fid;
if (fidfid) {
delete savedSF[fidfid];
} else {
delete savedSF[cFeature.id];
}
}
}
}
}
var control = this.control;
if (!control.unselectingAll &&
(control.mode &
OpenLayers.Control.FeaturePopups.CLOSE_ON_UNSELECT) ) {
control.refreshLayers();
}
},
/**
* Method: onBeforefeaturesremoved
* Called before some features are removed, only used when <mode>
* contains <OpenLayers.Control.FeaturePopups.SAFE_SELECTION>.
*
* Parameters:
* evt - {Object}
*/
onBeforefeaturesremoved: function (evt) {
var layerId = this.layer.id,
control = this.control,
features = evt.features;
if (features.length) {
var delayRefresh = !this.isEmptyObject(this.selection);
if (delayRefresh || this.listenFeatures) {
control.delayRefreshLayer(layerId);
}
}
},
/**
* Method: onFeaturesremoved
* Called when some features are removed, only used when
* <mode> = <OpenLayers.Control.FeaturePopups.CLOSE_ON_REMOVE>
*
* Parameters:
* evt - {Object}
*/
onFeaturesremoved: function (evt) {
this.control.refreshLayers();
},
/**
* Method: onFeaturesadded
* Called when some features are added, only used when value of <mode>
* conbtains <OpenLayers.Control.FeaturePopups..SAFE_SELECTION>.
*
* Parameters:
* evt - {Object}
*/
onFeaturesadded: function (evt) {
var layerId = this.layer.id,
control = this.control,
features = evt.features,
savedSF = this.selection;
if (!this.isEmptyObject(savedSF)) {
var selectCtl = control.controls.select;
control.selectingSet = true;
this.updatingSelection = true;
for (var i = 0 , len = features.length; i <len; i++) {
var feature = features[i];
if (feature.fid && savedSF[feature.fid]) {
selectCtl.select(feature);
} else if (feature.cluster) {
for (var ii = 0 , lenlen = feature.cluster.length; ii <lenlen; ii++) {
var cFeature = feature.cluster[ii];
if (cFeature.fid) {
if (savedSF[cFeature.fid]) {
selectCtl.select(feature);
break;
}
} else if (savedSF[cFeature.id]) {
selectCtl.select(feature);
break;
}
}
} else if (savedSF[feature.id]) {
selectCtl.select(feature);
}
}
control.selectingSet = false;
this.updatingSelection = false;
}
this.setRefreshPending();
control.endDelayRefreshLayer(layerId);
},
/**
* Method: setRefreshPending
*/
setRefreshPending: function () {
if (this.listenFeatures) {
var featuresHash,
layer = this.layer,
layerFeatures = this.getSingleFeatures(layer.features);
// get hash
if (layer.getVisibility() && layer.map) {
var feature,
ids = [];
for (var i=0, len = layerFeatures.length; i<len; ++i) {
feature = layerFeatures[i];
if (feature.fid) {
ids.push(feature.fid);
} else {
ids.push(feature.id);
}
}
featuresHash = ids.sort().join("\t");
} else {
featuresHash = "";
}
// have been changed?
if (featuresHash !== this.featuresHash) {
this.refreshPendig = layerFeatures;
this.featuresHash = featuresHash;
} else {
this.refreshPendig = null;
}
}
},
/**
* Function: getListHtml
*/
getListHtml: function (bounds) {
var layer = this.layer;
if (this.refreshPendig) {
this.events.triggerEvent("featureschanged", {
layer: layer,
features: this.refreshPendig
});
this.refreshPendig = null;
}
var html = "",
features = [],
invalid = false;
if (layer.getVisibility() && layer.inRange) {
var features = this.getLayerSelectionFeatures(),
layerTemplate = this.templates.list;
var i, len, feature,
selectionHash = [],
htmlAux = [],
itemTemplate = this.templates.item;
for (i=0, len = features.length; i<len; ++i) {
feature = features[i];
bounds.extend(feature.geometry.getBounds());
if (!feature.layer) {
feature = this.cloneDummyFeature(feature, layer);
}
layerTemplate && htmlAux.push(this.renderTemplate(itemTemplate, feature));
if (feature.fid) {
selectionHash.push(feature.fid);
} else {
selectionHash.push(feature.id);
}
}
selectionHash = selectionHash.sort().join("\t");
if (selectionHash !== this.selectionHash) {
invalid = true;
this.selectionHash = selectionHash;
}
if (layerTemplate) {
if (htmlAux.length) {
html = this.renderTemplate(
layerTemplate, {
layer: layer,
count: features.length,
html: htmlAux.join("\n")
}
);
}
}
} else if (this.selectionHash !== "") {
invalid = true;
this.selectionHash = "";
}
if (invalid && !this.silentSelection) {
this.events.triggerEvent("selectionchanged", {
layer: layer,
selection: features
});
}
return {invalid: invalid,html: html, features: features};
},
/**
* Function: getSingleHtml
*/
getSingleHtml: function (feature) {
var html = "",
hasTemplate = false,
sTemplate = this.templates.single;
if (sTemplate) {
var lonLat;
if (feature.geometry.getVertices().length > 1) {
lonLat = this.control.getLocationFromSelPixel(this.controls.select,
feature);
} else {
lonLat = feature.geometry.getBounds().getCenterLonLat();
}
if (!feature.layer) {
feature = this.cloneDummyFeature(feature, this.layer);
}
html = this.renderTemplate(sTemplate, feature);
hasTemplate = true;
}
return {hasTemplate: hasTemplate, html: html, lonLat:lonLat};
},
/**
* APIMethod: addSelectionByIds
*
* Parameters:
* featureIds - {Array(String)} List of feature ids to be
* added to selection.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
addSelectionByIds: function (featureIds, silent) {
if (featureIds.length > 0) {
var i, len,
savedSF = this.selection;
for (i=0, len = featureIds.length; i<len; i++) {
savedSF[featureIds[i]] = true;
}
this.applySelection(silent);
}
},
/**
* APIMethod: setSelectionByIds
*
* Parameters:
* featureIds - {Array(String)} List of feature ids to set as select.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
setSelectionByIds: function (featureIds, silent) {
var i, len,
savedSF = {};
for (i=0, len = featureIds.length; i<len; i++) {
savedSF[featureIds[i]] = true;
}
this.selection = savedSF;
this.applySelection(silent);
},
/**
* Method: applySelection
*/
applySelection: function (silent) {
var i, len,
savedSF = this.selection,
control = this.control,
selectCtl = control.controls.select,
_indexOf = OpenLayers.Util.indexOf,
layer = this.layer,
features = layer.features;
control.selectingSet = true;
this.updatingSelection = true;
for (var i = 0 , len = features.length; i <len; i++) {
var feature = features[i],
selected = false;
if (feature.fid && savedSF[feature.fid]) {
selected = true;
} else if (feature.cluster) {
for (var ii = 0 , lenlen = feature.cluster.length; ii <lenlen; ii++) {
var cFeature = feature.cluster[ii];
if (cFeature.fid) {
if (savedSF[cFeature.fid]) {
selected = true;
break;
}
} else if (savedSF[cFeature.id]) {
selected = true;
break;
}
}
} else if (savedSF[feature.id]) {
selected = true;
}
if (selected) {
if (_indexOf(layer.selectedFeatures, feature) == -1) {
selectCtl.select(feature);
}
} else if (_indexOf(layer.selectedFeatures, feature) > -1) {
selectCtl.unselect(feature);
}
}
control.selectingSet = false;
this.updatingSelection = false;
this.silentSelection = !!silent;
control.refreshLayers();
this.silentSelection = false;
},
/**
* APIMethod: removeSelectionByIds
*
* Parameters:
* featureIds - {Array(String)} List of feature ids to be
* removed to selection.
* silent - {Boolean} Supress "selectionchanged" event triggering. Default is false.
*/
removeSelectionByIds: function (featureIds, silent) {
if (featureIds.length > 0) {
var i, len,
savedSF = this.selection;
for (i=0, len = featureIds.length; i<len; i++) {
var featureId = featureIds[i];
if (savedSF[featureId]) {
delete savedSF[featureId];
}
}
this.applyDeselection(silent);
}
},
/**
* Method: applyDeselection
*/
applyDeselection: function (silent) {
var i, len,
savedSF = this.selection,
control = this.control,
selectCtl = control.controls.select,
_indexOf = OpenLayers.Util.indexOf,
layer = this.layer,
features = layer.selectedFeatures;
control.selectingSet = true;
this.updatingSelection = true;
for (var i = features.length-1; i >= 0; i--) {
var feature = features[i],
selected = false;
if (feature.fid && savedSF[feature.fid]) {
selected = true;
} else if (feature.cluster) {
for (var ii = 0 , lenlen = feature.cluster.length; ii <lenlen; ii++) {
var cFeature = feature.cluster[ii];
if (cFeature.fid) {
if (savedSF[cFeature.fid]) {
selected = true;
break;
}
} else if (savedSF[cFeature.id]) {
selected = true;
break;
}
}
} else if (savedSF[feature.id]) {
selected = true;
}
if (!selected) {
selectCtl.unselect(feature);
}
}
control.selectingSet = false;
this.updatingSelection = false;
this.silentSelection = !!silent;
control.refreshLayers();
this.silentSelection = false;
},
/**
* function: cloneDummyFeature
* Used on clustered features.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} the feature.
* layer - {<OpenLayers.Layer.Vector>}
*
* Returns:
* {Object} Context of the feature including the layer.
*/
cloneDummyFeature: function (feature, layer) {
feature = OpenLayers.Util.extend({}, feature);
feature.layer = layer;
return feature;
},
/**
* APIMethod: showSingleFeatureById
*
* Parameters:
* featureId - {String} id of the feature.
* idName - {String} Name of id: "id" or "fid".
*/
showSingleFeatureById: function (featureId, idName) {
var popupObj = this.control.popupObjs.listItem;
if (!popupObj) { return; }
idName = idName || "id";
var clearPopup = true;
if (featureId) {
var i, len, feature,
layer = this.layer,
features = layer.features;
for (i=0, len = features.length; i<len; i++) {
feature = features[i];
if (feature.cluster) {
var ii, len2, cFeature;
cFeature = feature;
for (ii=0, len2 = cFeature.cluster.length; ii<len2; ii++) {
feature = cFeature.cluster[ii];
if (feature[idName] == featureId) {
feature = this.cloneDummyFeature(feature, layer);
break;
}
}
}
// Don't try to show a cluster as a single feature,
// templates.single does not support it.
if (feature[idName] == featureId && !feature.cluster) {
popupObj.clear();
var template = this.templates.single;
if (template) {
var html = this.renderTemplate(template, feature)
popupObj.showPopup(
feature,
feature.geometry.getBounds().getCenterLonLat(),
html
);
}
clearPopup = false;
break;
}
}
}
if (clearPopup) {
popupObj.clear();
}
},
/**
* Method: getLayerSelectionFeatures
*/
getLayerSelectionFeatures: function (){
var sFeatures = [],
features = this.layer.selectedFeatures;
var i, len, feature;
if (this.safeSelection) {
var savedSF = this.selection;
if (savedSF) {
for (i=0, len = features.length; i<len; ++i) {
feature = features[i];
if (feature.cluster) {
// Not all features may be selected on a cluster
var clusterFeatures = feature.cluster;
for (var ii = 0 , llen = clusterFeatures.length; ii <llen; ii++) {
var cFeature = clusterFeatures[ii];
if (cFeature.fid) {
if (savedSF[cFeature.fid]) {
sFeatures.push(cFeature);
}
} else if (savedSF[cFeature.id]) {
sFeatures.push(cFeature);
}
}
} else {
sFeatures.push(feature);
}
}
}
} else {
sFeatures = this.getSingleFeatures(features);
}
return sFeatures;
},
/**
* APIFunction: getSelectionIds
*/
getSelectionIds: function (){
var ids = [];
if (this.safeSelection) {
var id,
savedSF = this.selection;
for (id in savedSF) {
ids.push(id);
}
} else {
var i, len,
features = this.layer.selectedFeatures;
for (i=0, len = features.length; i<len; ++i) {
ids.push(features[i].id);
}
}
return ids;
},
/**
* Function: getSingleFeatures
*/
getSingleFeatures: function (features){
var sFeatures = [];
var i, len, feature;
for (i=0, len = features.length; i<len; ++i) {
feature = features[i];
if (feature.cluster) {
Array.prototype.push.apply(sFeatures, feature.cluster);
} else {
sFeatures.push(feature);
}
}
return sFeatures;
},
/**
* Function: renderTemplate
* Given a string with tokens in the form ${token}, return a string
* with tokens replaced with properties from the given context
* object. Represent a literal "${" by doubling it, e.g. "${${".
*
* Parameters:
* template - {String || Function}
* If template is a string then template
* has the form "literal ${token}" where the token will be replaced
* by the value of context["token"]. When is a function it will receive
* the context as a argument.
* context - {Object} Object with properties corresponding to the tokens
* in the template.
*
* Returns:
* {String} A string with tokens replaced from the context object.
*/
renderTemplate: function (template, context) {
if (typeof template == 'string') {
return OpenLayers.String.format(template, context)
} else if (typeof template == 'function') {
return template(context);
} else {
return "";
}
},
CLASS_NAME: "OpenLayers.Control.FeaturePopups.Layer"
}); | Complete documentation of some properties.
| lib/FeaturePopups.js | Complete documentation of some properties. | <ide><path>ib/FeaturePopups.js
<ide> * <OpenLayers.Events.on> on hover control, internal use only.
<ide> */
<ide> hoverListeners: null,
<del>
<del> /**
<del> * Property: layerListeners
<del> * {Object} layerListeners object will be registered with
<del> * <OpenLayers.Events.on>, internal use only.
<del> */
<del> layerListeners: null,
<ide>
<ide> /**
<ide> * Property: popupObjs
<ide> */
<ide> destroy: function () {
<ide> this.deactivate();
<del> this.layerListeners = null;
<ide> for (var popupType in this.popupObjs) {
<ide> this.popupObjs[popupType].destroy();
<ide> }
<ide> /**
<ide> * APIMethod: addLayer
<ide> * Add the layer to control and assigns it the templates, see options.
<del> * Layers are automatically assigned if they have the properties for any of
<del> * the three types of templates: "hoverPopupTemplate",
<del> * "selectPopupTemplate" and "itemPopupTemplate".
<del> * In a layer can also specify a "listPopupTemplate" (default is
<del> * <layerListTemplate>), this template is ignored if not
<del> * specified in conjunction with "itemPopupTemplate".
<ide> *
<ide> * To add a layer that has already been added (maybe automatically),
<ide> * first must be removed using <removeLayer>.
<ide> * Templates containing patterns as ${i18n("key")} are internationalized
<ide> * using <OpenLayers.i18n> function.
<ide> *
<del> * The control uses the patterns as ${showPopup()} in "itemPopupTemplate"
<add> * The control uses the patterns as ${showPopup()} in a "item" template
<ide> * to show individual popups from a list. This pattern becomes a
<ide> * combination of the layer.id+feature.id and can be used only as an
<ide> * html attribute.
<ide> CLASS_NAME: "OpenLayers.Control.FeaturePopups.Popup"
<ide> });
<ide>
<del>
<ide> /**
<ide> * Class: OpenLayers.Control.FeaturePopups.Layer
<ide> */
<ide> * {<OpenLayers.Events>} Events instance for listeners and triggering
<ide> * specific events.
<ide> *
<del> * Supported event types:
<add> * Supported event types: see <FeaturePopups.AddLayer>
<ide> */
<ide> events: null,
<ide>
<ide> * Only required to use <OpenLayers.Control.FeaturePopups> with 2.11 or less
<ide> */
<ide> EVENT_TYPES: ["featureschanged", "selectionchanged"],
<add>
<add> /**
<add> * APIProperty: eventListeners
<add> * {Object} If set on options at construction, the eventListeners
<add> * object will be registered with <OpenLayers.Events.on>. Object
<add> * structure must be a listeners object as shown in the example for
<add> * the events.on method.
<add> */
<add> eventListeners: null,
<add>
<add> /**
<add> * Property: listenFeatures
<add> * {Boolean} nternal use to optimize performance, true if <eventListeners>
<add> * contains a "featureschanged" event.
<add> */
<ide> listenFeatures: false,
<add>
<add> /**
<add> * APIProperty: templates
<add> * {Object} Set of templates, see <FeaturePopups.AddLayer>
<add> */
<ide> templates: null,
<add>
<add> /**
<add> * Property: safeSelection
<add> * {Boolean} Internal use to optimize performance, true if
<add> * <FeaturePopups.mode> contains
<add> * <OpenLayers.Control.FeaturePopups.SAFE_SELECTION>.
<add> */
<add> safeSelection: false,
<add>
<add> /**
<add> * Property: selection
<add> * {Object} Used if <safeSelection> is true. Set of the identifiers (id or
<add> * fid if it exists) of the features that were selected, a feature
<add> * remains on the object after being removed from the layer until
<add> * occurs new selection.
<add> */
<ide> selection: {},
<add>
<add> /**
<add> * Property: selectionHash
<add> * {String} String unique for the single features of the selected features
<add> * of the layer regardless of the order or clustering of these, is
<add> * based on its id or fid (if it exists)
<add> */
<ide> selectionHash: "",
<add>
<add> /**
<add> * Property: featuresHash
<add> * {String} String unique for the single features of the layer regardless
<add> * of the order or clustering of these, is based on its id or fid (if
<add> * it exists)
<add> */
<ide> featuresHash: "",
<add>
<add> /**
<add> * Property: refreshPendig
<add> * Array({<OpenLayers.Feature.Vector>}) Layer features cache to use at the
<add> * right time in "featureschanged" event.
<add> */
<ide> refreshPendig: null,
<add>
<add> /**
<add> * Property: layerListeners
<add> * {Object} layerListeners object will be registered with
<add> * <OpenLayers.Events.on>, internal use only.
<add> */
<ide> layerListeners: null,
<del> safeSelection: false,
<ide>
<ide> /**
<ide> * APIProperty: active
<ide> * {Boolean} The object is active (read-only)
<ide> */
<ide> active: null,
<del>
<del> /**
<del> * Property: safeSelection
<del> * {Boolean} True if <mode> contains
<del> * OpenLayers.Control.FeaturePopups.SAFE_SELECTION.
<del> */
<del> safeSelection: false,
<ide>
<ide> /**
<ide> * Property: updatingSelection
<ide>
<ide> /**
<ide> * Constructor: OpenLayers.Control.FeaturePopups.Layer
<del>
<ide> */
<ide> initialize: function (control, layer, options) {
<ide> // Options |
|
Java | mit | 19fc1255635b5270fca4a0e9173808dc4aee84c5 | 0 | oleg-nenashev/remoting,jenkinsci/remoting,oleg-nenashev/remoting,jenkinsci/remoting | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
*
* 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 hudson.remoting;
import hudson.remoting.ExportTable.ExportList;
import hudson.remoting.PipeWindow.Key;
import hudson.remoting.PipeWindow.Real;
import hudson.remoting.forward.ListeningPort;
import hudson.remoting.forward.ForwarderFactory;
import hudson.remoting.forward.PortForwarder;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Represents a communication channel to the remote peer.
*
* <p>
* A {@link Channel} is a mechanism for two JVMs to communicate over
* bi-directional {@link InputStream}/{@link OutputStream} pair.
* {@link Channel} represents an endpoint of the stream, and thus
* two {@link Channel}s are always used in a pair.
*
* <p>
* Communication is established as soon as two {@link Channel} instances
* are created at the end fo the stream pair
* until the stream is terminated via {@link #close()}.
*
* <p>
* The basic unit of remoting is an executable {@link Callable} object.
* An application can create a {@link Callable} object, and execute it remotely
* by using the {@link #call(Callable)} method or {@link #callAsync(Callable)} method.
*
* <p>
* In this sense, {@link Channel} is a mechanism to delegate/offload computation
* to other JVMs and somewhat like an agent system. This is bit different from
* remoting technologies like CORBA or web services, where the server exposes a
* certain functionality that clients invoke.
*
* <p>
* {@link Callable} object, as well as the return value / exceptions,
* are transported by using Java serialization. All the necessary class files
* are also shipped over {@link Channel} on-demand, so there's no need to
* pre-deploy such classes on both JVMs.
*
*
* <h2>Implementor's Note</h2>
* <p>
* {@link Channel} builds its features in a layered model. Its higher-layer
* features are built on top of its lower-layer features, and they
* are called layer-0, layer-1, etc.
*
* <ul>
* <li>
* <b>Layer 0</b>:
* See {@link Command} for more details. This is for higher-level features,
* and not likely useful for applications directly.
* <li>
* <b>Layer 1</b>:
* See {@link Request} for more details. This is for higher-level features,
* and not likely useful for applications directly.
* </ul>
*
* @author Kohsuke Kawaguchi
*/
public class Channel implements VirtualChannel, IChannel {
private final ObjectInputStream ois;
private final ObjectOutputStream oos;
/**
* {@link OutputStream} that's given to the constructor. This is the hand-off with the lower layer.
*/
private final OutputStream underlyingOutput;
/**
* Human readable description of where this channel is connected to. Used during diagnostic output
* and error reports.
*/
private final String name;
private volatile boolean isRestricted;
/*package*/ final ExecutorService executor;
/**
* If non-null, the incoming link is already shut down,
* and reader is already terminated. The {@link Throwable} object indicates why the outgoing channel
* was closed.
*/
private volatile Throwable inClosed = null;
/**
* If non-null, the outgoing link is already shut down,
* and no command can be sent. The {@link Throwable} object indicates why the outgoing channel
* was closed.
*/
private volatile Throwable outClosed = null;
/*package*/ final Map<Integer,Request<?,?>> pendingCalls = new Hashtable<Integer,Request<?,?>>();
/**
* Records the {@link Request}s being executed on this channel, sent by the remote peer.
*/
/*package*/ final Map<Integer,Request<?,?>> executingCalls =
Collections.synchronizedMap(new Hashtable<Integer,Request<?,?>>());
/**
* {@link ClassLoader}s that are proxies of the remote classloaders.
*/
/*package*/ final ImportedClassLoaderTable importedClassLoaders = new ImportedClassLoaderTable(this);
/**
* Objects exported via {@link #export(Class, Object)}.
*/
/*package (for test)*/ final ExportTable<Object> exportedObjects = new ExportTable<Object>();
/**
* {@link PipeWindow}s keyed by their OIDs (of the OutputStream exported by the other side.)
*
* <p>
* To make the GC of {@link PipeWindow} automatic, the use of weak references here are tricky.
* A strong reference to {@link PipeWindow} is kept from {@link ProxyOutputStream}, and
* this is the only strong reference. Thus while {@link ProxyOutputStream} is alive,
* it keeps {@link PipeWindow} referenced, which in turn keeps its {@link PipeWindow.Real#key}
* referenced, hence this map can be looked up by the OID. When the {@link ProxyOutputStream}
* will be gone, the key is no longer strongly referenced, so it'll get cleaned up.
*
* <p>
* In some race condition situation, it might be possible for us to lose the tracking of the collect
* window size. But as long as we can be sure that there's only one {@link PipeWindow} instance
* per OID, it will only result in a temporary spike in the effective window size,
* and therefore should be OK.
*/
private final WeakHashMap<PipeWindow.Key, WeakReference<PipeWindow>> pipeWindows = new WeakHashMap<PipeWindow.Key, WeakReference<PipeWindow>>();
/**
* Registered listeners.
*/
private final Vector<Listener> listeners = new Vector<Listener>();
private int gcCounter;
private int commandsSent;
/**
* Total number of nanoseconds spent for remote class loading.
* <p>
* Remote code execution often results in classloading activity
* (more precisely, when the remote peer requests some computation
* on this channel, this channel often has to load necessary
* classes from the remote peer.)
* <p>
* This counter represents the total amount of time this channel
* had to spend loading classes from the remote peer. The time
* measurement doesn't include the time locally spent to actually
* define the class (as the local classloading would have incurred
* the same cost.)
*/
public final AtomicLong classLoadingTime = new AtomicLong();
/**
* Total counts of remote classloading activities. Used in a pair
* with {@link #classLoadingTime}.
*/
public final AtomicInteger classLoadingCount = new AtomicInteger();
/**
* Total number of nanoseconds spent for remote resource loading.
* @see #classLoadingTime
*/
public final AtomicLong resourceLoadingTime = new AtomicLong();
/**
* Total count of remote resource loading.
* @see #classLoadingCount
*/
public final AtomicInteger resourceLoadingCount = new AtomicInteger();
/**
* Property bag that contains application-specific stuff.
*/
private final Hashtable<Object,Object> properties = new Hashtable<Object,Object>();
/**
* Proxy to the remote {@link Channel} object.
*/
private IChannel remoteChannel;
/**
* Capability of the remote {@link Channel}.
*/
public final Capability remoteCapability;
/**
* When did we receive any data from this slave the last time?
* This can be used as a basis for detecting dead connections.
* <p>
* Note that this doesn't include our sender side of the operation,
* as successfully returning from {@link #send(Command)} doesn't mean
* anything in terms of whether the underlying network was able to send
* the data (for example, if the other end of a socket connection goes down
* without telling us anything, the {@link SocketOutputStream#write(int)} will
* return right away, and the socket only really times out after 10s of minutes.
*/
private volatile long lastHeard;
/**
* Single-thread executor for running pipe I/O operations.
*
* It is executed in a separate thread to avoid blocking the channel reader thread
* in case read/write blocks. It is single thread to ensure FIFO; I/O needs to execute
* in the same order the remote peer told us to execute them.
*/
/*package*/ final ExecutorService pipeWriter;
/**
* ClassLaoder that remote classloaders should use as the basis.
*/
/*package*/ final ClassLoader baseClassLoader;
/**
* Communication mode.
* @since 1.161
*/
public enum Mode {
/**
* Send binary data over the stream. Most efficient.
*/
BINARY(new byte[]{0,0,0,0}),
/**
* Send ASCII over the stream. Uses base64, so the efficiency goes down by 33%,
* but this is useful where stream is binary-unsafe, such as telnet.
*/
TEXT("<===[HUDSON TRANSMISSION BEGINS]===>") {
@Override protected OutputStream wrap(OutputStream os) {
return BinarySafeStream.wrap(os);
}
@Override protected InputStream wrap(InputStream is) {
return BinarySafeStream.wrap(is);
}
},
/**
* Let the remote peer decide the transmission mode and follow that.
* Note that if both ends use NEGOTIATE, it will dead lock.
*/
NEGOTIATE(new byte[0]);
/**
* Preamble used to indicate the tranmission mode.
* Because of the algorithm we use to detect the preamble,
* the string cannot be any random string. For example,
* if the preamble is "AAB", we'll fail to find a preamble
* in "AAAB".
*/
private final byte[] preamble;
Mode(String preamble) {
try {
this.preamble = preamble.getBytes("US-ASCII");
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
}
Mode(byte[] preamble) {
this.preamble = preamble;
}
protected OutputStream wrap(OutputStream os) { return os; }
protected InputStream wrap(InputStream is) { return is; }
}
public Channel(String name, ExecutorService exec, InputStream is, OutputStream os) throws IOException {
this(name,exec,Mode.BINARY,is,os,null);
}
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os) throws IOException {
this(name,exec,mode,is,os,null);
}
public Channel(String name, ExecutorService exec, InputStream is, OutputStream os, OutputStream header) throws IOException {
this(name,exec,Mode.BINARY,is,os,header);
}
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header) throws IOException {
this(name,exec,mode,is,os,header,false);
}
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted) throws IOException {
this(name,exec,mode,is,os,header,restricted,null);
}
/**
* Creates a new channel.
*
* @param name
* Human readable name of this channel. Used for debug/logging. Can be anything.
* @param exec
* Commands sent from the remote peer will be executed by using this {@link Executor}.
* @param mode
* The encoding to be used over the stream.
* @param is
* Stream connected to the remote peer. It's the caller's responsibility to do
* buffering on this stream, if that's necessary.
* @param os
* Stream connected to the remote peer. It's the caller's responsibility to do
* buffering on this stream, if that's necessary.
* @param header
* If non-null, receive the portion of data in <tt>is</tt> before
* the data goes into the "binary mode". This is useful
* when the established communication channel might include some data that might
* be useful for debugging/trouble-shooting.
* @param base
* Specify the classloader used for deserializing remote commands.
* This is primarily related to {@link #getRemoteProperty(Object)}. Sometimes two parties
* communicate over a channel and pass objects around as properties, but those types might not be
* visible from the classloader loading the {@link Channel} class. In such a case, specify a classloader
* so that those classes resolve. If null, {@code Channel.class.getClassLoader()} is used.
* @param restricted
* If true, this channel won't accept {@link Command}s that allow the remote end to execute arbitrary closures
* --- instead they can only call methods on objects that are exported by this channel.
* This also prevents the remote end from loading classes into JVM.
*
* Note that it still allows the remote end to deserialize arbitrary object graph
* (provided that all the classes are already available in this JVM), so exactly how
* safe the resulting behavior is is up to discussion.
*/
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base) throws IOException {
this(name,exec,mode,is,os,header,restricted,base,new Capability());
}
/*package*/ Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base, Capability capability) throws IOException {
this.name = name;
this.executor = exec;
this.isRestricted = restricted;
this.underlyingOutput = os;
if (base==null)
base = getClass().getClassLoader();
this.baseClassLoader = base;
if(export(this,false)!=1)
throw new AssertionError(); // export number 1 is reserved for the channel itself
remoteChannel = RemoteInvocationHandler.wrap(this,1,IChannel.class,true,false);
// write the magic preamble.
// certain communication channel, such as forking JVM via ssh,
// may produce some garbage at the beginning (for example a remote machine
// might print some warning before the program starts outputting its own data.)
//
// so use magic preamble and discard all the data up to that to improve robustness.
capability.writePreamble(os);
ObjectOutputStream oos = null;
if(mode!= Mode.NEGOTIATE) {
os.write(mode.preamble);
oos = new ObjectOutputStream(mode.wrap(os));
oos.flush(); // make sure that stream preamble is sent to the other end. avoids dead-lock
}
{// read the input until we hit preamble
Mode[] modes={Mode.BINARY,Mode.TEXT};
byte[][] preambles = new byte[][]{Mode.BINARY.preamble, Mode.TEXT.preamble, Capability.PREAMBLE};
int[] ptr=new int[3];
Capability cap = new Capability(0); // remote capacity that we obtained. If we don't hear from remote, assume no capability
while(true) {
int ch = is.read();
if(ch==-1)
throw new EOFException("unexpected stream termination");
for(int i=0;i<preambles.length;i++) {
byte[] preamble = preambles[i];
if(preamble[ptr[i]]==ch) {
if(++ptr[i]==preamble.length) {
switch (i) {
case 0:
case 1:
// transmission mode negotiation
if(mode==Mode.NEGOTIATE) {
// now we know what the other side wants, so send the consistent preamble
mode = modes[i];
os.write(mode.preamble);
oos = new ObjectOutputStream(mode.wrap(os));
oos.flush();
} else {
if(modes[i]!=mode)
throw new IOException("Protocol negotiation failure");
}
this.oos = oos;
this.remoteCapability = cap;
this.pipeWriter = createPipeWriter();
this.ois = new ObjectInputStreamEx(mode.wrap(is),base);
new ReaderThread(name).start();
return;
case 2:
cap = Capability.read(is);
break;
}
ptr[i]=0; // reset
}
} else {
// didn't match.
ptr[i]=0;
}
}
if(header!=null)
header.write(ch);
}
}
}
/**
* Callback "interface" for changes in the state of {@link Channel}.
*/
public static abstract class Listener {
/**
* When the channel was closed normally or abnormally due to an error.
*
* @param cause
* if the channel is closed abnormally, this parameter
* represents an exception that has triggered it.
* Otherwise null.
*/
public void onClosed(Channel channel, IOException cause) {}
}
/*package*/ boolean isOutClosed() {
return outClosed!=null;
}
/**
* Creates the {@link ExecutorService} for writing to pipes.
*
* <p>
* If the throttling is supported, use a separate thread to free up the main channel
* reader thread (thus prevent blockage.) Otherwise let the channel reader thread do it,
* which is the historical behaviour.
*/
private ExecutorService createPipeWriter() {
if (remoteCapability.supportsPipeThrottling())
return Executors.newSingleThreadExecutor(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r,"Pipe writer thread: "+name);
}
});
return new SynchronousExecutorService();
}
/**
* Sends a command to the remote end and executes it there.
*
* <p>
* This is the lowest layer of abstraction in {@link Channel}.
* {@link Command}s are executed on a remote system in the order they are sent.
*/
/*package*/ synchronized void send(Command cmd) throws IOException {
if(outClosed!=null)
throw new ChannelClosedException(outClosed);
if(logger.isLoggable(Level.FINE))
logger.fine("Send "+cmd);
Channel old = Channel.setCurrent(this);
try {
oos.writeObject(cmd);
oos.flush(); // make sure the command reaches the other end.
} finally {
Channel.setCurrent(old);
commandsSent++;
}
// unless this is the last command, have OOS and remote OIS forget all the objects we sent
// in this command. Otherwise it'll keep objects in memory unnecessarily.
// However, this may fail if the command was the close, because that's supposed to be the last command
// ever sent. See the comment from jglick on HUDSON-3077 about what happens if we do oos.reset().
if(!(cmd instanceof CloseCommand))
oos.reset();
}
/**
* {@inheritDoc}
*/
public <T> T export(Class<T> type, T instance) {
return export(type,instance,true);
}
/**
* @param userProxy
* If true, the returned proxy will be capable to handle classes
* defined in the user classloader as parameters and return values.
* Such proxy relies on {@link RemoteClassLoader} and related mechanism,
* so it's not usable for implementing lower-layer services that are
* used by {@link RemoteClassLoader}.
*
* To create proxies for objects inside remoting, pass in false.
*/
/*package*/ <T> T export(Class<T> type, T instance, boolean userProxy) {
if(instance==null)
return null;
// every so often perform GC on the remote system so that
// unused RemoteInvocationHandler get released, which triggers
// unexport operation.
if((++gcCounter)%10000==0)
try {
send(new GCCommand());
} catch (IOException e) {
// for compatibility reason we can't change the export method signature
logger.log(Level.WARNING, "Unable to send GC command",e);
}
// either local side will auto-unexport, or the remote side will unexport when it's GC-ed
boolean autoUnexportByCaller = exportedObjects.isRecording();
final int id = export(instance,autoUnexportByCaller);
return RemoteInvocationHandler.wrap(null, id, type, userProxy, autoUnexportByCaller);
}
/*package*/ int export(Object instance) {
return exportedObjects.export(instance);
}
/*package*/ int export(Object instance, boolean automaticUnexport) {
return exportedObjects.export(instance,automaticUnexport);
}
/*package*/ Object getExportedObject(int oid) {
return exportedObjects.get(oid);
}
/*package*/ void unexport(int id) {
exportedObjects.unexportByOid(id);
}
/**
* Increase reference count so much to effectively prevent de-allocation.
*
* @see ExportTable.Entry#pin()
*/
public void pin(Object instance) {
exportedObjects.pin(instance);
}
/**
* {@linkplain #pin(Object) Pin down} the exported classloader.
*/
public void pinClassLoader(ClassLoader cl) {
RemoteClassLoader.pin(cl,this);
}
/**
* Preloads jar files on the remote side.
*
* <p>
* This is a performance improvement method that can be safely
* ignored if your goal is just to make things working.
*
* <p>
* Normally, classes are transferred over the network one at a time,
* on-demand. This design is mainly driven by how Java classloading works
* — we can't predict what classes will be necessarily upfront very easily.
*
* <p>
* Classes are loaded only once, so for long-running {@link Channel},
* this is normally an acceptable overhead. But sometimes, for example
* when a channel is short-lived, or when you know that you'll need
* a majority of classes in certain jar files, then it is more efficient
* to send a whole jar file over the network upfront and thereby
* avoiding individual class transfer over the network.
*
* <p>
* That is what this method does. It ensures that a series of jar files
* are copied to the remote side (AKA "preloading.")
* Classloading will consult the preloaded jars before performing
* network transfer of class files.
*
* @param classLoaderRef
* This parameter is used to identify the remote classloader
* that will prefetch the specified jar files. That is, prefetching
* will ensure that prefetched jars will kick in
* when this {@link Callable} object is actually executed remote side.
*
* <p>
* {@link RemoteClassLoader}s are created wisely, one per local {@link ClassLoader},
* so this parameter doesn't have to be exactly the same {@link Callable}
* to be executed later — it just has to be of the same class.
* @param classesInJar
* {@link Class} objects that identify jar files to be preloaded.
* Jar files that contain the specified classes will be preloaded into the remote peer.
* You just need to specify one class per one jar.
* @return
* true if the preloading actually happened. false if all the jars
* are already preloaded. This method is implemented in such a way that
* unnecessary jar file transfer will be avoided, and the return value
* will tell you if this optimization kicked in. Under normal circumstances
* your program shouldn't depend on this return value. It's just a hint.
* @throws IOException
* if the preloading fails.
*/
public boolean preloadJar(Callable<?,?> classLoaderRef, Class... classesInJar) throws IOException, InterruptedException {
return preloadJar(UserRequest.getClassLoader(classLoaderRef),classesInJar);
}
public boolean preloadJar(ClassLoader local, Class... classesInJar) throws IOException, InterruptedException {
URL[] jars = new URL[classesInJar.length];
for (int i = 0; i < classesInJar.length; i++)
jars[i] = Which.jarFile(classesInJar[i]).toURI().toURL();
return call(new PreloadJarTask(jars,local));
}
public boolean preloadJar(ClassLoader local, URL... jars) throws IOException, InterruptedException {
return call(new PreloadJarTask(jars,local));
}
/*package*/ PipeWindow getPipeWindow(int oid) {
synchronized (pipeWindows) {
Key k = new Key(oid);
WeakReference<PipeWindow> v = pipeWindows.get(k);
if (v!=null) {
PipeWindow w = v.get();
if (w!=null)
return w;
}
PipeWindow w;
if (remoteCapability.supportsPipeThrottling())
w = new Real(k, PIPE_WINDOW_SIZE);
else
w = new PipeWindow.Fake();
pipeWindows.put(k,new WeakReference<PipeWindow>(w));
return w;
}
}
/**
* {@inheritDoc}
*/
public <V,T extends Throwable>
V call(Callable<V,T> callable) throws IOException, T, InterruptedException {
UserRequest<V,T> request=null;
try {
request = new UserRequest<V, T>(this, callable);
UserResponse<V,T> r = request.call(this);
return r.retrieve(this, UserRequest.getClassLoader(callable));
// re-wrap the exception so that we can capture the stack trace of the caller.
} catch (ClassNotFoundException e) {
IOException x = new IOException("Remote call on "+name+" failed");
x.initCause(e);
throw x;
} catch (Error e) {
IOException x = new IOException("Remote call on "+name+" failed");
x.initCause(e);
throw x;
} finally {
// since this is synchronous operation, when the round trip is over
// we assume all the exported objects are out of scope.
// (that is, the operation shouldn't spawn a new thread or altter
// global state in the remote system.
if(request!=null)
request.releaseExports();
}
}
/**
* {@inheritDoc}
*/
public <V,T extends Throwable>
Future<V> callAsync(final Callable<V,T> callable) throws IOException {
final Future<UserResponse<V,T>> f = new UserRequest<V,T>(this, callable).callAsync(this);
return new FutureAdapter<V,UserResponse<V,T>>(f) {
protected V adapt(UserResponse<V,T> r) throws ExecutionException {
try {
return r.retrieve(Channel.this, UserRequest.getClassLoader(callable));
} catch (Throwable t) {// really means catch(T t)
throw new ExecutionException(t);
}
}
};
}
/**
* Aborts the connection in response to an error.
*
* @param e
* The error that caused the connection to be aborted. Never null.
*/
protected synchronized void terminate(IOException e) {
if (e==null) throw new IllegalArgumentException();
outClosed=inClosed=e;
try {
synchronized(pendingCalls) {
for (Request<?,?> req : pendingCalls.values())
req.abort(e);
pendingCalls.clear();
}
synchronized (executingCalls) {
for (Request<?, ?> r : executingCalls.values()) {
java.util.concurrent.Future<?> f = r.future;
if(f!=null) f.cancel(true);
}
executingCalls.clear();
}
} finally {
notifyAll();
if (e instanceof OrderlyShutdown) e = null;
for (Listener l : listeners.toArray(new Listener[listeners.size()]))
l.onClosed(this,e);
}
}
/**
* Registers a new {@link Listener}.
*
* @see #removeListener(Listener)
*/
public void addListener(Listener l) {
listeners.add(l);
}
/**
* Removes a listener.
*
* @return
* false if the given listener has not been registered to begin with.
*/
public boolean removeListener(Listener l) {
return listeners.remove(l);
}
/**
* Waits for this {@link Channel} to be closed down.
*
* The close-down of a {@link Channel} might be initiated locally or remotely.
*
* @throws InterruptedException
* If the current thread is interrupted while waiting for the completion.
*/
public synchronized void join() throws InterruptedException {
while(inClosed==null || outClosed==null)
wait();
}
/**
* If the receiving end of the channel is closed (that is, if we are guaranteed to receive nothing further),
* this method returns true.
*/
/*package*/ boolean isInClosed() {
return inClosed!=null;
}
/**
* Returns true if this channel is currently does not load classes from the remote peer.
*/
public boolean isRestricted() {
return isRestricted;
}
public void setRestricted(boolean b) {
isRestricted = b;
}
/**
* Waits for this {@link Channel} to be closed down, but only up the given milliseconds.
*
* @throws InterruptedException
* If the current thread is interrupted while waiting for the completion.
* @since 1.299
*/
public synchronized void join(long timeout) throws InterruptedException {
long start = System.currentTimeMillis();
while(System.currentTimeMillis()-start<timeout && (inClosed==null || outClosed==null))
wait(timeout+start-System.currentTimeMillis());
}
/**
* Notifies the remote peer that we are closing down.
*
* Execution of this command also triggers the {@link ReaderThread} to shut down
* and quit. The {@link CloseCommand} is always the last command to be sent on
* {@link ObjectOutputStream}, and it's the last command to be read.
*/
private static final class CloseCommand extends Command {
private CloseCommand(Throwable cause) {
super(cause);
}
protected void execute(Channel channel) {
try {
channel.close();
channel.terminate(new OrderlyShutdown(createdAt));
} catch (IOException e) {
logger.log(Level.SEVERE,"close command failed on "+channel.name,e);
logger.log(Level.INFO,"close command created at",createdAt);
}
}
@Override
public String toString() {
return "close";
}
// this value is compatible with remoting < 2.8. I made an incompatible change in 2.8 that got corrected in 2.11.
static final long serialVersionUID = 972857271608138115L;
}
/**
* Signals the orderly shutdown of the channel, but captures
* where the termination was initiated as a nested exception.
*/
private static final class OrderlyShutdown extends IOException {
private OrderlyShutdown(Throwable cause) {
super(cause.getMessage());
initCause(cause);
}
private static final long serialVersionUID = 1L;
}
/**
* Resets all the performance counters.
*/
public void resetPerformanceCounters() {
classLoadingCount.set(0);
classLoadingTime.set(0);
resourceLoadingCount.set(0);
resourceLoadingTime.set(0);
}
/**
* {@inheritDoc}
*/
public synchronized void close() throws IOException {
close(null);
}
/**
* Closes the channel.
*
* @param diagnosis
* If someone (either this side or the other side) tries to use a channel that's already closed,
* they'll get a stack trace indicating that the channel has already been closed. This diagnosis,
* if provided, will further chained to that exception, providing more contextual information
* about why the channel was closed.
*
* @since 2.8
*/
public synchronized void close(Throwable diagnosis) throws IOException {
if(outClosed!=null) return; // already closed
send(new CloseCommand(diagnosis));
outClosed = new IOException().initCause(diagnosis); // last command sent. no further command allowed. lock guarantees that no command will slip inbetween
try {
oos.close();
} catch (IOException e) {
// there's a race condition here.
// the remote peer might have already responded to the close command
// and closed the connection, in which case our close invocation
// could fail with errors like
// "java.io.IOException: The pipe is being closed"
// so let's ignore this error.
}
// termination is done by CloseCommand when we received it.
}
/**
* Gets the application specific property set by {@link #setProperty(Object, Object)}.
* These properties are also accessible from the remote channel via {@link #getRemoteProperty(Object)}.
*
* <p>
* This mechanism can be used for one side to discover contextual objects created by the other JVM
* (as opposed to executing {@link Callable}, which cannot have any reference to the context
* of the remote {@link Channel}.
*/
public Object getProperty(Object key) {
return properties.get(key);
}
public <T> T getProperty(ChannelProperty<T> key) {
return key.type.cast(getProperty((Object) key));
}
/**
* Works like {@link #getProperty(Object)} but wait until some value is set by someone.
*/
public Object waitForProperty(Object key) throws InterruptedException {
synchronized (properties) {
while(true) {
Object v = properties.get(key);
if(v!=null) return v;
properties.wait();
}
}
}
public <T> T waitForProperty(ChannelProperty<T> key) throws InterruptedException {
return key.type.cast(waitForProperty((Object) key));
}
/**
* Sets the property value on this side of the channel.
*
* @see #getProperty(Object)
*/
public Object setProperty(Object key, Object value) {
synchronized (properties) {
Object old = value!=null ? properties.put(key, value) : properties.remove(key);
properties.notifyAll();
return old;
}
}
public <T> T setProperty(ChannelProperty<T> key, T value) {
return key.type.cast(setProperty((Object) key, value));
}
/**
* Gets the property set on the remote peer.
*
* @return null
* if the property of the said key isn't set.
*/
public Object getRemoteProperty(Object key) {
return remoteChannel.getProperty(key);
}
public <T> T getRemoteProperty(ChannelProperty<T> key) {
return key.type.cast(getRemoteProperty((Object) key));
}
/**
* Gets the property set on the remote peer.
* This method blocks until the property is set by the remote peer.
*/
public Object waitForRemoteProperty(Object key) throws InterruptedException {
return remoteChannel.waitForProperty(key);
}
public <T> T waitForRemoteProperty(ChannelProperty<T> key) throws InterruptedException {
return key.type.cast(waitForRemoteProperty((Object) key));
}
/**
* Obtain the output stream passed to the constructor.
*
* @deprecated
* Future version of the remoting module may add other modes of creating channel
* that doesn't involve stream pair. Therefore, we aren't committing to this method.
* This method isn't a part of the committed API of the channel class.
* @return
* While the current version always return a non-null value, the caller must not
* make that assumption for the above reason. This method may return null in the future version
* to indicate that the {@link Channel} is not sitting on top of a stream pair.
*/
public OutputStream getUnderlyingOutput() {
return underlyingOutput;
}
/**
* Starts a local to remote port forwarding (the equivalent of "ssh -L").
*
* @param recvPort
* The port on this local machine that we'll listen to. 0 to let
* OS pick a random available port. If you specify 0, use
* {@link ListeningPort#getPort()} to figure out the actual assigned port.
* @param forwardHost
* The remote host that the connection will be forwarded to.
* Connection to this host will be made from the other JVM that
* this {@link Channel} represents.
* @param forwardPort
* The remote port that the connection will be forwarded to.
* @return
*/
public ListeningPort createLocalToRemotePortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException {
return new PortForwarder( recvPort,
ForwarderFactory.create(this,forwardHost,forwardPort));
}
/**
* Starts a remote to local port forwarding (the equivalent of "ssh -R").
*
* @param recvPort
* The port on the remote JVM (represented by this {@link Channel})
* that we'll listen to. 0 to let
* OS pick a random available port. If you specify 0, use
* {@link ListeningPort#getPort()} to figure out the actual assigned port.
* @param forwardHost
* The remote host that the connection will be forwarded to.
* Connection to this host will be made from this JVM.
* @param forwardPort
* The remote port that the connection will be forwarded to.
* @return
*/
public ListeningPort createRemoteToLocalPortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException {
return PortForwarder.create(this,recvPort,
ForwarderFactory.create(forwardHost, forwardPort));
}
/**
* Blocks until all the I/O packets sent before this gets fully executed by the remote side, then return.
*
* @throws IOException
* If the remote doesn't support this operation, or if sync fails for other reasons.
*/
public void syncIO() throws IOException, InterruptedException {
call(new IOSyncer());
}
public void syncLocalIO() throws InterruptedException {
try {
pipeWriter.submit(new Runnable() {
public void run() {
// noop
}
}).get();
} catch (ExecutionException e) {
throw new AssertionError(e); // impossible
}
}
private static final class IOSyncer implements Callable<Object, InterruptedException> {
public Object call() throws InterruptedException {
Channel.current().syncLocalIO();
return null;
}
private static final long serialVersionUID = 1L;
}
@Override
public String toString() {
return super.toString()+":"+name;
}
/**
* Dumps the list of exported objects and their allocation traces to the given output.
*/
public void dumpExportTable(PrintWriter w) throws IOException {
exportedObjects.dump(w);
}
public ExportList startExportRecording() {
return exportedObjects.startRecording();
}
/**
* @see #lastHeard
*/
public long getLastHeard() {
return lastHeard;
}
private final class ReaderThread extends Thread {
private int commandsReceived = 0;
private int commandsExecuted = 0;
public ReaderThread(String name) {
super("Channel reader thread: "+name);
}
@Override
public void run() {
try {
while(inClosed==null) {
Command cmd = null;
try {
Channel old = Channel.setCurrent(Channel.this);
try {
cmd = (Command)ois.readObject();
lastHeard = System.currentTimeMillis();
} finally {
Channel.setCurrent(old);
}
} catch (EOFException e) {
IOException ioe = new IOException("Unexpected termination of the channel");
ioe.initCause(e);
throw ioe;
} catch (ClassNotFoundException e) {
logger.log(Level.SEVERE, "Unable to read a command (channel " + name + ")",e);
continue;
} finally {
commandsReceived++;
}
if(logger.isLoggable(Level.FINE))
logger.fine("Received "+cmd);
try {
cmd.execute(Channel.this);
} catch (Throwable t) {
logger.log(Level.SEVERE, "Failed to execute command "+cmd+ " (channel " + name + ")",t);
logger.log(Level.SEVERE, "This command is created here",cmd.createdAt);
} finally {
commandsExecuted++;
}
}
ois.close();
} catch (IOException e) {
logger.log(Level.SEVERE, "I/O error in channel "+name,e);
terminate(e);
} catch (RuntimeException e) {
logger.log(Level.SEVERE, "Unexpected error in channel "+name,e);
terminate((IOException)new IOException("Unexpected reader termination").initCause(e));
throw e;
} catch (Error e) {
logger.log(Level.SEVERE, "Unexpected error in channel "+name,e);
terminate((IOException)new IOException("Unexpected reader termination").initCause(e));
throw e;
} finally {
pipeWriter.shutdown();
}
}
}
/*package*/ static Channel setCurrent(Channel channel) {
Channel old = CURRENT.get();
CURRENT.set(channel);
return old;
}
/**
* This method can be invoked during the serialization/deserialization of
* objects when they are transferred to the remote {@link Channel},
* as well as during {@link Callable#call()} is invoked.
*
* @return null
* if the calling thread is not performing serialization.
*/
public static Channel current() {
return CURRENT.get();
}
/**
* Remembers the current "channel" associated for this thread.
*/
private static final ThreadLocal<Channel> CURRENT = new ThreadLocal<Channel>();
private static final Logger logger = Logger.getLogger(Channel.class.getName());
public static final int PIPE_WINDOW_SIZE = Integer.getInteger(Channel.class+".pipeWindowSize",128*1024);
// static {
// ConsoleHandler h = new ConsoleHandler();
// h.setFormatter(new Formatter(){
// public synchronized String format(LogRecord record) {
// StringBuilder sb = new StringBuilder();
// sb.append((record.getMillis()%100000)+100000);
// sb.append(" ");
// if (record.getSourceClassName() != null) {
// sb.append(record.getSourceClassName());
// } else {
// sb.append(record.getLoggerName());
// }
// if (record.getSourceMethodName() != null) {
// sb.append(" ");
// sb.append(record.getSourceMethodName());
// }
// sb.append('\n');
// String message = formatMessage(record);
// sb.append(record.getLevel().getLocalizedName());
// sb.append(": ");
// sb.append(message);
// sb.append('\n');
// if (record.getThrown() != null) {
// try {
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// record.getThrown().printStackTrace(pw);
// pw.close();
// sb.append(sw.toString());
// } catch (Exception ex) {
// }
// }
// return sb.toString();
// }
// });
// h.setLevel(Level.FINE);
// logger.addHandler(h);
// logger.setLevel(Level.FINE);
// }
}
| src/main/java/hudson/remoting/Channel.java | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
*
* 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 hudson.remoting;
import hudson.remoting.ExportTable.ExportList;
import hudson.remoting.PipeWindow.Key;
import hudson.remoting.PipeWindow.Real;
import hudson.remoting.forward.ListeningPort;
import hudson.remoting.forward.ForwarderFactory;
import hudson.remoting.forward.PortForwarder;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Represents a communication channel to the remote peer.
*
* <p>
* A {@link Channel} is a mechanism for two JVMs to communicate over
* bi-directional {@link InputStream}/{@link OutputStream} pair.
* {@link Channel} represents an endpoint of the stream, and thus
* two {@link Channel}s are always used in a pair.
*
* <p>
* Communication is established as soon as two {@link Channel} instances
* are created at the end fo the stream pair
* until the stream is terminated via {@link #close()}.
*
* <p>
* The basic unit of remoting is an executable {@link Callable} object.
* An application can create a {@link Callable} object, and execute it remotely
* by using the {@link #call(Callable)} method or {@link #callAsync(Callable)} method.
*
* <p>
* In this sense, {@link Channel} is a mechanism to delegate/offload computation
* to other JVMs and somewhat like an agent system. This is bit different from
* remoting technologies like CORBA or web services, where the server exposes a
* certain functionality that clients invoke.
*
* <p>
* {@link Callable} object, as well as the return value / exceptions,
* are transported by using Java serialization. All the necessary class files
* are also shipped over {@link Channel} on-demand, so there's no need to
* pre-deploy such classes on both JVMs.
*
*
* <h2>Implementor's Note</h2>
* <p>
* {@link Channel} builds its features in a layered model. Its higher-layer
* features are built on top of its lower-layer features, and they
* are called layer-0, layer-1, etc.
*
* <ul>
* <li>
* <b>Layer 0</b>:
* See {@link Command} for more details. This is for higher-level features,
* and not likely useful for applications directly.
* <li>
* <b>Layer 1</b>:
* See {@link Request} for more details. This is for higher-level features,
* and not likely useful for applications directly.
* </ul>
*
* @author Kohsuke Kawaguchi
*/
public class Channel implements VirtualChannel, IChannel {
private final ObjectInputStream ois;
private final ObjectOutputStream oos;
/**
* {@link OutputStream} that's given to the constructor. This is the hand-off with the lower layer.
*/
private final OutputStream underlyingOutput;
/**
* Human readable description of where this channel is connected to. Used during diagnostic output
* and error reports.
*/
private final String name;
private volatile boolean isRestricted;
/*package*/ final ExecutorService executor;
/**
* If non-null, the incoming link is already shut down,
* and reader is already terminated. The {@link Throwable} object indicates why the outgoing channel
* was closed.
*/
private volatile Throwable inClosed = null;
/**
* If non-null, the outgoing link is already shut down,
* and no command can be sent. The {@link Throwable} object indicates why the outgoing channel
* was closed.
*/
private volatile Throwable outClosed = null;
/*package*/ final Map<Integer,Request<?,?>> pendingCalls = new Hashtable<Integer,Request<?,?>>();
/**
* Records the {@link Request}s being executed on this channel, sent by the remote peer.
*/
/*package*/ final Map<Integer,Request<?,?>> executingCalls =
Collections.synchronizedMap(new Hashtable<Integer,Request<?,?>>());
/**
* {@link ClassLoader}s that are proxies of the remote classloaders.
*/
/*package*/ final ImportedClassLoaderTable importedClassLoaders = new ImportedClassLoaderTable(this);
/**
* Objects exported via {@link #export(Class, Object)}.
*/
/*package (for test)*/ final ExportTable<Object> exportedObjects = new ExportTable<Object>();
/**
* {@link PipeWindow}s keyed by their OIDs (of the OutputStream exported by the other side.)
*
* <p>
* To make the GC of {@link PipeWindow} automatic, the use of weak references here are tricky.
* A strong reference to {@link PipeWindow} is kept from {@link ProxyOutputStream}, and
* this is the only strong reference. Thus while {@link ProxyOutputStream} is alive,
* it keeps {@link PipeWindow} referenced, which in turn keeps its {@link PipeWindow.Real#key}
* referenced, hence this map can be looked up by the OID. When the {@link ProxyOutputStream}
* will be gone, the key is no longer strongly referenced, so it'll get cleaned up.
*
* <p>
* In some race condition situation, it might be possible for us to lose the tracking of the collect
* window size. But as long as we can be sure that there's only one {@link PipeWindow} instance
* per OID, it will only result in a temporary spike in the effective window size,
* and therefore should be OK.
*/
private final WeakHashMap<PipeWindow.Key, WeakReference<PipeWindow>> pipeWindows = new WeakHashMap<PipeWindow.Key, WeakReference<PipeWindow>>();
/**
* Registered listeners.
*/
private final Vector<Listener> listeners = new Vector<Listener>();
private int gcCounter;
private int commandsSent;
/**
* Total number of nanoseconds spent for remote class loading.
* <p>
* Remote code execution often results in classloading activity
* (more precisely, when the remote peer requests some computation
* on this channel, this channel often has to load necessary
* classes from the remote peer.)
* <p>
* This counter represents the total amount of time this channel
* had to spend loading classes from the remote peer. The time
* measurement doesn't include the time locally spent to actually
* define the class (as the local classloading would have incurred
* the same cost.)
*/
public final AtomicLong classLoadingTime = new AtomicLong();
/**
* Total counts of remote classloading activities. Used in a pair
* with {@link #classLoadingTime}.
*/
public final AtomicInteger classLoadingCount = new AtomicInteger();
/**
* Total number of nanoseconds spent for remote resource loading.
* @see #classLoadingTime
*/
public final AtomicLong resourceLoadingTime = new AtomicLong();
/**
* Total count of remote resource loading.
* @see #classLoadingCount
*/
public final AtomicInteger resourceLoadingCount = new AtomicInteger();
/**
* Property bag that contains application-specific stuff.
*/
private final Hashtable<Object,Object> properties = new Hashtable<Object,Object>();
/**
* Proxy to the remote {@link Channel} object.
*/
private IChannel remoteChannel;
/**
* Capability of the remote {@link Channel}.
*/
public final Capability remoteCapability;
/**
* When did we receive any data from this slave the last time?
* This can be used as a basis for detecting dead connections.
* <p>
* Note that this doesn't include our sender side of the operation,
* as successfully returning from {@link #send(Command)} doesn't mean
* anything in terms of whether the underlying network was able to send
* the data (for example, if the other end of a socket connection goes down
* without telling us anything, the {@link SocketOutputStream#write(int)} will
* return right away, and the socket only really times out after 10s of minutes.
*/
private volatile long lastHeard;
/**
* Single-thread executor for running pipe I/O operations.
*
* It is executed in a separate thread to avoid blocking the channel reader thread
* in case read/write blocks. It is single thread to ensure FIFO; I/O needs to execute
* in the same order the remote peer told us to execute them.
*/
/*package*/ final ExecutorService pipeWriter;
/**
* ClassLaoder that remote classloaders should use as the basis.
*/
/*package*/ final ClassLoader baseClassLoader;
/**
* Communication mode.
* @since 1.161
*/
public enum Mode {
/**
* Send binary data over the stream. Most efficient.
*/
BINARY(new byte[]{0,0,0,0}),
/**
* Send ASCII over the stream. Uses base64, so the efficiency goes down by 33%,
* but this is useful where stream is binary-unsafe, such as telnet.
*/
TEXT("<===[HUDSON TRANSMISSION BEGINS]===>") {
@Override protected OutputStream wrap(OutputStream os) {
return BinarySafeStream.wrap(os);
}
@Override protected InputStream wrap(InputStream is) {
return BinarySafeStream.wrap(is);
}
},
/**
* Let the remote peer decide the transmission mode and follow that.
* Note that if both ends use NEGOTIATE, it will dead lock.
*/
NEGOTIATE(new byte[0]);
/**
* Preamble used to indicate the tranmission mode.
* Because of the algorithm we use to detect the preamble,
* the string cannot be any random string. For example,
* if the preamble is "AAB", we'll fail to find a preamble
* in "AAAB".
*/
private final byte[] preamble;
Mode(String preamble) {
try {
this.preamble = preamble.getBytes("US-ASCII");
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
}
Mode(byte[] preamble) {
this.preamble = preamble;
}
protected OutputStream wrap(OutputStream os) { return os; }
protected InputStream wrap(InputStream is) { return is; }
}
public Channel(String name, ExecutorService exec, InputStream is, OutputStream os) throws IOException {
this(name,exec,Mode.BINARY,is,os,null);
}
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os) throws IOException {
this(name,exec,mode,is,os,null);
}
public Channel(String name, ExecutorService exec, InputStream is, OutputStream os, OutputStream header) throws IOException {
this(name,exec,Mode.BINARY,is,os,header);
}
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header) throws IOException {
this(name,exec,mode,is,os,header,false);
}
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted) throws IOException {
this(name,exec,mode,is,os,header,restricted,null);
}
/**
* Creates a new channel.
*
* @param name
* Human readable name of this channel. Used for debug/logging. Can be anything.
* @param exec
* Commands sent from the remote peer will be executed by using this {@link Executor}.
* @param mode
* The encoding to be used over the stream.
* @param is
* Stream connected to the remote peer. It's the caller's responsibility to do
* buffering on this stream, if that's necessary.
* @param os
* Stream connected to the remote peer. It's the caller's responsibility to do
* buffering on this stream, if that's necessary.
* @param header
* If non-null, receive the portion of data in <tt>is</tt> before
* the data goes into the "binary mode". This is useful
* when the established communication channel might include some data that might
* be useful for debugging/trouble-shooting.
* @param base
* Specify the classloader used for deserializing remote commands.
* This is primarily related to {@link #getRemoteProperty(Object)}. Sometimes two parties
* communicate over a channel and pass objects around as properties, but those types might not be
* visible from the classloader loading the {@link Channel} class. In such a case, specify a classloader
* so that those classes resolve. If null, {@code Channel.class.getClassLoader()} is used.
* @param restricted
* If true, this channel won't accept {@link Command}s that allow the remote end to execute arbitrary closures
* --- instead they can only call methods on objects that are exported by this channel.
* This also prevents the remote end from loading classes into JVM.
*
* Note that it still allows the remote end to deserialize arbitrary object graph
* (provided that all the classes are already available in this JVM), so exactly how
* safe the resulting behavior is is up to discussion.
*/
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base) throws IOException {
this(name,exec,mode,is,os,header,restricted,base,new Capability());
}
/*package*/ Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base, Capability capability) throws IOException {
this.name = name;
this.executor = exec;
this.isRestricted = restricted;
this.underlyingOutput = os;
if (base==null)
base = getClass().getClassLoader();
this.baseClassLoader = base;
if(export(this,false)!=1)
throw new AssertionError(); // export number 1 is reserved for the channel itself
remoteChannel = RemoteInvocationHandler.wrap(this,1,IChannel.class,true,false);
// write the magic preamble.
// certain communication channel, such as forking JVM via ssh,
// may produce some garbage at the beginning (for example a remote machine
// might print some warning before the program starts outputting its own data.)
//
// so use magic preamble and discard all the data up to that to improve robustness.
capability.writePreamble(os);
ObjectOutputStream oos = null;
if(mode!= Mode.NEGOTIATE) {
os.write(mode.preamble);
oos = new ObjectOutputStream(mode.wrap(os));
oos.flush(); // make sure that stream preamble is sent to the other end. avoids dead-lock
}
{// read the input until we hit preamble
Mode[] modes={Mode.BINARY,Mode.TEXT};
byte[][] preambles = new byte[][]{Mode.BINARY.preamble, Mode.TEXT.preamble, Capability.PREAMBLE};
int[] ptr=new int[3];
Capability cap = new Capability(0); // remote capacity that we obtained. If we don't hear from remote, assume no capability
while(true) {
int ch = is.read();
if(ch==-1)
throw new EOFException("unexpected stream termination");
for(int i=0;i<preambles.length;i++) {
byte[] preamble = preambles[i];
if(preamble[ptr[i]]==ch) {
if(++ptr[i]==preamble.length) {
switch (i) {
case 0:
case 1:
// transmission mode negotiation
if(mode==Mode.NEGOTIATE) {
// now we know what the other side wants, so send the consistent preamble
mode = modes[i];
os.write(mode.preamble);
oos = new ObjectOutputStream(mode.wrap(os));
oos.flush();
} else {
if(modes[i]!=mode)
throw new IOException("Protocol negotiation failure");
}
this.oos = oos;
this.remoteCapability = cap;
this.pipeWriter = createPipeWriter();
this.ois = new ObjectInputStreamEx(mode.wrap(is),base);
new ReaderThread(name).start();
return;
case 2:
cap = Capability.read(is);
break;
}
ptr[i]=0; // reset
}
} else {
// didn't match.
ptr[i]=0;
}
}
if(header!=null)
header.write(ch);
}
}
}
/**
* Callback "interface" for changes in the state of {@link Channel}.
*/
public static abstract class Listener {
/**
* When the channel was closed normally or abnormally due to an error.
*
* @param cause
* if the channel is closed abnormally, this parameter
* represents an exception that has triggered it.
* Otherwise null.
*/
public void onClosed(Channel channel, IOException cause) {}
}
/*package*/ boolean isOutClosed() {
return outClosed!=null;
}
/**
* Creates the {@link ExecutorService} for writing to pipes.
*
* <p>
* If the throttling is supported, use a separate thread to free up the main channel
* reader thread (thus prevent blockage.) Otherwise let the channel reader thread do it,
* which is the historical behaviour.
*/
private ExecutorService createPipeWriter() {
if (remoteCapability.supportsPipeThrottling())
return Executors.newSingleThreadExecutor(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r,"Pipe writer thread: "+name);
}
});
return new SynchronousExecutorService();
}
/**
* Sends a command to the remote end and executes it there.
*
* <p>
* This is the lowest layer of abstraction in {@link Channel}.
* {@link Command}s are executed on a remote system in the order they are sent.
*/
/*package*/ synchronized void send(Command cmd) throws IOException {
if(outClosed!=null)
throw new ChannelClosedException(outClosed);
if(logger.isLoggable(Level.FINE))
logger.fine("Send "+cmd);
Channel old = Channel.setCurrent(this);
try {
oos.writeObject(cmd);
oos.flush(); // make sure the command reaches the other end.
} finally {
Channel.setCurrent(old);
commandsSent++;
}
// unless this is the last command, have OOS and remote OIS forget all the objects we sent
// in this command. Otherwise it'll keep objects in memory unnecessarily.
// However, this may fail if the command was the close, because that's supposed to be the last command
// ever sent. See the comment from jglick on HUDSON-3077 about what happens if we do oos.reset().
if(!(cmd instanceof CloseCommand))
oos.reset();
}
/**
* {@inheritDoc}
*/
public <T> T export(Class<T> type, T instance) {
return export(type,instance,true);
}
/**
* @param userProxy
* If true, the returned proxy will be capable to handle classes
* defined in the user classloader as parameters and return values.
* Such proxy relies on {@link RemoteClassLoader} and related mechanism,
* so it's not usable for implementing lower-layer services that are
* used by {@link RemoteClassLoader}.
*
* To create proxies for objects inside remoting, pass in false.
*/
/*package*/ <T> T export(Class<T> type, T instance, boolean userProxy) {
if(instance==null)
return null;
// every so often perform GC on the remote system so that
// unused RemoteInvocationHandler get released, which triggers
// unexport operation.
if((++gcCounter)%10000==0)
try {
send(new GCCommand());
} catch (IOException e) {
// for compatibility reason we can't change the export method signature
logger.log(Level.WARNING, "Unable to send GC command",e);
}
// either local side will auto-unexport, or the remote side will unexport when it's GC-ed
boolean autoUnexportByCaller = exportedObjects.isRecording();
final int id = export(instance,autoUnexportByCaller);
return RemoteInvocationHandler.wrap(null, id, type, userProxy, autoUnexportByCaller);
}
/*package*/ int export(Object instance) {
return exportedObjects.export(instance);
}
/*package*/ int export(Object instance, boolean automaticUnexport) {
return exportedObjects.export(instance,automaticUnexport);
}
/*package*/ Object getExportedObject(int oid) {
return exportedObjects.get(oid);
}
/*package*/ void unexport(int id) {
exportedObjects.unexportByOid(id);
}
/**
* Increase reference count so much to effectively prevent de-allocation.
*
* @see ExportTable.Entry#pin()
*/
public void pin(Object instance) {
exportedObjects.pin(instance);
}
/**
* {@linkplain #pin(Object) Pin down} the exported classloader.
*/
public void pinClassLoader(ClassLoader cl) {
RemoteClassLoader.pin(cl,this);
}
/**
* Preloads jar files on the remote side.
*
* <p>
* This is a performance improvement method that can be safely
* ignored if your goal is just to make things working.
*
* <p>
* Normally, classes are transferred over the network one at a time,
* on-demand. This design is mainly driven by how Java classloading works
* — we can't predict what classes will be necessarily upfront very easily.
*
* <p>
* Classes are loaded only once, so for long-running {@link Channel},
* this is normally an acceptable overhead. But sometimes, for example
* when a channel is short-lived, or when you know that you'll need
* a majority of classes in certain jar files, then it is more efficient
* to send a whole jar file over the network upfront and thereby
* avoiding individual class transfer over the network.
*
* <p>
* That is what this method does. It ensures that a series of jar files
* are copied to the remote side (AKA "preloading.")
* Classloading will consult the preloaded jars before performing
* network transfer of class files.
*
* @param classLoaderRef
* This parameter is used to identify the remote classloader
* that will prefetch the specified jar files. That is, prefetching
* will ensure that prefetched jars will kick in
* when this {@link Callable} object is actually executed remote side.
*
* <p>
* {@link RemoteClassLoader}s are created wisely, one per local {@link ClassLoader},
* so this parameter doesn't have to be exactly the same {@link Callable}
* to be executed later — it just has to be of the same class.
* @param classesInJar
* {@link Class} objects that identify jar files to be preloaded.
* Jar files that contain the specified classes will be preloaded into the remote peer.
* You just need to specify one class per one jar.
* @return
* true if the preloading actually happened. false if all the jars
* are already preloaded. This method is implemented in such a way that
* unnecessary jar file transfer will be avoided, and the return value
* will tell you if this optimization kicked in. Under normal circumstances
* your program shouldn't depend on this return value. It's just a hint.
* @throws IOException
* if the preloading fails.
*/
public boolean preloadJar(Callable<?,?> classLoaderRef, Class... classesInJar) throws IOException, InterruptedException {
return preloadJar(UserRequest.getClassLoader(classLoaderRef),classesInJar);
}
public boolean preloadJar(ClassLoader local, Class... classesInJar) throws IOException, InterruptedException {
URL[] jars = new URL[classesInJar.length];
for (int i = 0; i < classesInJar.length; i++)
jars[i] = Which.jarFile(classesInJar[i]).toURI().toURL();
return call(new PreloadJarTask(jars,local));
}
public boolean preloadJar(ClassLoader local, URL... jars) throws IOException, InterruptedException {
return call(new PreloadJarTask(jars,local));
}
/*package*/ PipeWindow getPipeWindow(int oid) {
synchronized (pipeWindows) {
Key k = new Key(oid);
WeakReference<PipeWindow> v = pipeWindows.get(k);
if (v!=null) {
PipeWindow w = v.get();
if (w!=null)
return w;
}
PipeWindow w;
if (remoteCapability.supportsPipeThrottling())
w = new Real(k, PIPE_WINDOW_SIZE);
else
w = new PipeWindow.Fake();
pipeWindows.put(k,new WeakReference<PipeWindow>(w));
return w;
}
}
/**
* {@inheritDoc}
*/
public <V,T extends Throwable>
V call(Callable<V,T> callable) throws IOException, T, InterruptedException {
UserRequest<V,T> request=null;
try {
request = new UserRequest<V, T>(this, callable);
UserResponse<V,T> r = request.call(this);
return r.retrieve(this, UserRequest.getClassLoader(callable));
// re-wrap the exception so that we can capture the stack trace of the caller.
} catch (ClassNotFoundException e) {
IOException x = new IOException("Remote call on "+name+" failed");
x.initCause(e);
throw x;
} catch (Error e) {
IOException x = new IOException("Remote call on "+name+" failed");
x.initCause(e);
throw x;
} finally {
// since this is synchronous operation, when the round trip is over
// we assume all the exported objects are out of scope.
// (that is, the operation shouldn't spawn a new thread or altter
// global state in the remote system.
if(request!=null)
request.releaseExports();
}
}
/**
* {@inheritDoc}
*/
public <V,T extends Throwable>
Future<V> callAsync(final Callable<V,T> callable) throws IOException {
final Future<UserResponse<V,T>> f = new UserRequest<V,T>(this, callable).callAsync(this);
return new FutureAdapter<V,UserResponse<V,T>>(f) {
protected V adapt(UserResponse<V,T> r) throws ExecutionException {
try {
return r.retrieve(Channel.this, UserRequest.getClassLoader(callable));
} catch (Throwable t) {// really means catch(T t)
throw new ExecutionException(t);
}
}
};
}
/**
* Aborts the connection in response to an error.
*
* @param e
* The error that caused the connection to be aborted. Never null.
*/
protected synchronized void terminate(IOException e) {
if (e==null) throw new IllegalArgumentException();
outClosed=inClosed=e;
try {
synchronized(pendingCalls) {
for (Request<?,?> req : pendingCalls.values())
req.abort(e);
pendingCalls.clear();
}
synchronized (executingCalls) {
for (Request<?, ?> r : executingCalls.values()) {
java.util.concurrent.Future<?> f = r.future;
if(f!=null) f.cancel(true);
}
executingCalls.clear();
}
} finally {
notifyAll();
if (e instanceof OrderlyShutdown) e = null;
for (Listener l : listeners.toArray(new Listener[listeners.size()]))
l.onClosed(this,e);
}
}
/**
* Registers a new {@link Listener}.
*
* @see #removeListener(Listener)
*/
public void addListener(Listener l) {
listeners.add(l);
}
/**
* Removes a listener.
*
* @return
* false if the given listener has not been registered to begin with.
*/
public boolean removeListener(Listener l) {
return listeners.remove(l);
}
/**
* Waits for this {@link Channel} to be closed down.
*
* The close-down of a {@link Channel} might be initiated locally or remotely.
*
* @throws InterruptedException
* If the current thread is interrupted while waiting for the completion.
*/
public synchronized void join() throws InterruptedException {
while(inClosed==null || outClosed==null)
wait();
}
/**
* If the receiving end of the channel is closed (that is, if we are guaranteed to receive nothing further),
* this method returns true.
*/
/*package*/ boolean isInClosed() {
return inClosed!=null;
}
/**
* Returns true if this channel is currently does not load classes from the remote peer.
*/
public boolean isRestricted() {
return isRestricted;
}
public void setRestricted(boolean b) {
isRestricted = b;
}
/**
* Waits for this {@link Channel} to be closed down, but only up the given milliseconds.
*
* @throws InterruptedException
* If the current thread is interrupted while waiting for the completion.
* @since 1.299
*/
public synchronized void join(long timeout) throws InterruptedException {
long start = System.currentTimeMillis();
while(System.currentTimeMillis()-start<timeout && (inClosed==null || outClosed==null))
wait(timeout+start-System.currentTimeMillis());
}
/**
* Notifies the remote peer that we are closing down.
*
* Execution of this command also triggers the {@link ReaderThread} to shut down
* and quit. The {@link CloseCommand} is always the last command to be sent on
* {@link ObjectOutputStream}, and it's the last command to be read.
*/
private static final class CloseCommand extends Command {
private CloseCommand(Throwable cause) {
super(cause);
}
protected void execute(Channel channel) {
try {
channel.close();
channel.terminate(new OrderlyShutdown(createdAt));
} catch (IOException e) {
logger.log(Level.SEVERE,"close command failed on "+channel.name,e);
logger.log(Level.INFO,"close command created at",createdAt);
}
}
@Override
public String toString() {
return "close";
}
}
/**
* Signals the orderly shutdown of the channel, but captures
* where the termination was initiated as a nested exception.
*/
private static final class OrderlyShutdown extends IOException {
private OrderlyShutdown(Throwable cause) {
super(cause.getMessage());
initCause(cause);
}
private static final long serialVersionUID = 1L;
}
/**
* Resets all the performance counters.
*/
public void resetPerformanceCounters() {
classLoadingCount.set(0);
classLoadingTime.set(0);
resourceLoadingCount.set(0);
resourceLoadingTime.set(0);
}
/**
* {@inheritDoc}
*/
public synchronized void close() throws IOException {
close(null);
}
/**
* Closes the channel.
*
* @param diagnosis
* If someone (either this side or the other side) tries to use a channel that's already closed,
* they'll get a stack trace indicating that the channel has already been closed. This diagnosis,
* if provided, will further chained to that exception, providing more contextual information
* about why the channel was closed.
*
* @since 2.8
*/
public synchronized void close(Throwable diagnosis) throws IOException {
if(outClosed!=null) return; // already closed
send(new CloseCommand(diagnosis));
outClosed = new IOException().initCause(diagnosis); // last command sent. no further command allowed. lock guarantees that no command will slip inbetween
try {
oos.close();
} catch (IOException e) {
// there's a race condition here.
// the remote peer might have already responded to the close command
// and closed the connection, in which case our close invocation
// could fail with errors like
// "java.io.IOException: The pipe is being closed"
// so let's ignore this error.
}
// termination is done by CloseCommand when we received it.
}
/**
* Gets the application specific property set by {@link #setProperty(Object, Object)}.
* These properties are also accessible from the remote channel via {@link #getRemoteProperty(Object)}.
*
* <p>
* This mechanism can be used for one side to discover contextual objects created by the other JVM
* (as opposed to executing {@link Callable}, which cannot have any reference to the context
* of the remote {@link Channel}.
*/
public Object getProperty(Object key) {
return properties.get(key);
}
public <T> T getProperty(ChannelProperty<T> key) {
return key.type.cast(getProperty((Object) key));
}
/**
* Works like {@link #getProperty(Object)} but wait until some value is set by someone.
*/
public Object waitForProperty(Object key) throws InterruptedException {
synchronized (properties) {
while(true) {
Object v = properties.get(key);
if(v!=null) return v;
properties.wait();
}
}
}
public <T> T waitForProperty(ChannelProperty<T> key) throws InterruptedException {
return key.type.cast(waitForProperty((Object) key));
}
/**
* Sets the property value on this side of the channel.
*
* @see #getProperty(Object)
*/
public Object setProperty(Object key, Object value) {
synchronized (properties) {
Object old = value!=null ? properties.put(key, value) : properties.remove(key);
properties.notifyAll();
return old;
}
}
public <T> T setProperty(ChannelProperty<T> key, T value) {
return key.type.cast(setProperty((Object) key, value));
}
/**
* Gets the property set on the remote peer.
*
* @return null
* if the property of the said key isn't set.
*/
public Object getRemoteProperty(Object key) {
return remoteChannel.getProperty(key);
}
public <T> T getRemoteProperty(ChannelProperty<T> key) {
return key.type.cast(getRemoteProperty((Object) key));
}
/**
* Gets the property set on the remote peer.
* This method blocks until the property is set by the remote peer.
*/
public Object waitForRemoteProperty(Object key) throws InterruptedException {
return remoteChannel.waitForProperty(key);
}
public <T> T waitForRemoteProperty(ChannelProperty<T> key) throws InterruptedException {
return key.type.cast(waitForRemoteProperty((Object) key));
}
/**
* Obtain the output stream passed to the constructor.
*
* @deprecated
* Future version of the remoting module may add other modes of creating channel
* that doesn't involve stream pair. Therefore, we aren't committing to this method.
* This method isn't a part of the committed API of the channel class.
* @return
* While the current version always return a non-null value, the caller must not
* make that assumption for the above reason. This method may return null in the future version
* to indicate that the {@link Channel} is not sitting on top of a stream pair.
*/
public OutputStream getUnderlyingOutput() {
return underlyingOutput;
}
/**
* Starts a local to remote port forwarding (the equivalent of "ssh -L").
*
* @param recvPort
* The port on this local machine that we'll listen to. 0 to let
* OS pick a random available port. If you specify 0, use
* {@link ListeningPort#getPort()} to figure out the actual assigned port.
* @param forwardHost
* The remote host that the connection will be forwarded to.
* Connection to this host will be made from the other JVM that
* this {@link Channel} represents.
* @param forwardPort
* The remote port that the connection will be forwarded to.
* @return
*/
public ListeningPort createLocalToRemotePortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException {
return new PortForwarder( recvPort,
ForwarderFactory.create(this,forwardHost,forwardPort));
}
/**
* Starts a remote to local port forwarding (the equivalent of "ssh -R").
*
* @param recvPort
* The port on the remote JVM (represented by this {@link Channel})
* that we'll listen to. 0 to let
* OS pick a random available port. If you specify 0, use
* {@link ListeningPort#getPort()} to figure out the actual assigned port.
* @param forwardHost
* The remote host that the connection will be forwarded to.
* Connection to this host will be made from this JVM.
* @param forwardPort
* The remote port that the connection will be forwarded to.
* @return
*/
public ListeningPort createRemoteToLocalPortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException {
return PortForwarder.create(this,recvPort,
ForwarderFactory.create(forwardHost, forwardPort));
}
/**
* Blocks until all the I/O packets sent before this gets fully executed by the remote side, then return.
*
* @throws IOException
* If the remote doesn't support this operation, or if sync fails for other reasons.
*/
public void syncIO() throws IOException, InterruptedException {
call(new IOSyncer());
}
public void syncLocalIO() throws InterruptedException {
try {
pipeWriter.submit(new Runnable() {
public void run() {
// noop
}
}).get();
} catch (ExecutionException e) {
throw new AssertionError(e); // impossible
}
}
private static final class IOSyncer implements Callable<Object, InterruptedException> {
public Object call() throws InterruptedException {
Channel.current().syncLocalIO();
return null;
}
private static final long serialVersionUID = 1L;
}
@Override
public String toString() {
return super.toString()+":"+name;
}
/**
* Dumps the list of exported objects and their allocation traces to the given output.
*/
public void dumpExportTable(PrintWriter w) throws IOException {
exportedObjects.dump(w);
}
public ExportList startExportRecording() {
return exportedObjects.startRecording();
}
/**
* @see #lastHeard
*/
public long getLastHeard() {
return lastHeard;
}
private final class ReaderThread extends Thread {
private int commandsReceived = 0;
private int commandsExecuted = 0;
public ReaderThread(String name) {
super("Channel reader thread: "+name);
}
@Override
public void run() {
try {
while(inClosed==null) {
Command cmd = null;
try {
Channel old = Channel.setCurrent(Channel.this);
try {
cmd = (Command)ois.readObject();
lastHeard = System.currentTimeMillis();
} finally {
Channel.setCurrent(old);
}
} catch (EOFException e) {
IOException ioe = new IOException("Unexpected termination of the channel");
ioe.initCause(e);
throw ioe;
} catch (ClassNotFoundException e) {
logger.log(Level.SEVERE, "Unable to read a command (channel " + name + ")",e);
continue;
} finally {
commandsReceived++;
}
if(logger.isLoggable(Level.FINE))
logger.fine("Received "+cmd);
try {
cmd.execute(Channel.this);
} catch (Throwable t) {
logger.log(Level.SEVERE, "Failed to execute command "+cmd+ " (channel " + name + ")",t);
logger.log(Level.SEVERE, "This command is created here",cmd.createdAt);
} finally {
commandsExecuted++;
}
}
ois.close();
} catch (IOException e) {
logger.log(Level.SEVERE, "I/O error in channel "+name,e);
terminate(e);
} catch (RuntimeException e) {
logger.log(Level.SEVERE, "Unexpected error in channel "+name,e);
terminate((IOException)new IOException("Unexpected reader termination").initCause(e));
throw e;
} catch (Error e) {
logger.log(Level.SEVERE, "Unexpected error in channel "+name,e);
terminate((IOException)new IOException("Unexpected reader termination").initCause(e));
throw e;
} finally {
pipeWriter.shutdown();
}
}
}
/*package*/ static Channel setCurrent(Channel channel) {
Channel old = CURRENT.get();
CURRENT.set(channel);
return old;
}
/**
* This method can be invoked during the serialization/deserialization of
* objects when they are transferred to the remote {@link Channel},
* as well as during {@link Callable#call()} is invoked.
*
* @return null
* if the calling thread is not performing serialization.
*/
public static Channel current() {
return CURRENT.get();
}
/**
* Remembers the current "channel" associated for this thread.
*/
private static final ThreadLocal<Channel> CURRENT = new ThreadLocal<Channel>();
private static final Logger logger = Logger.getLogger(Channel.class.getName());
public static final int PIPE_WINDOW_SIZE = Integer.getInteger(Channel.class+".pipeWindowSize",128*1024);
// static {
// ConsoleHandler h = new ConsoleHandler();
// h.setFormatter(new Formatter(){
// public synchronized String format(LogRecord record) {
// StringBuilder sb = new StringBuilder();
// sb.append((record.getMillis()%100000)+100000);
// sb.append(" ");
// if (record.getSourceClassName() != null) {
// sb.append(record.getSourceClassName());
// } else {
// sb.append(record.getLoggerName());
// }
// if (record.getSourceMethodName() != null) {
// sb.append(" ");
// sb.append(record.getSourceMethodName());
// }
// sb.append('\n');
// String message = formatMessage(record);
// sb.append(record.getLevel().getLocalizedName());
// sb.append(": ");
// sb.append(message);
// sb.append('\n');
// if (record.getThrown() != null) {
// try {
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// record.getThrown().printStackTrace(pw);
// pw.close();
// sb.append(sw.toString());
// } catch (Exception ex) {
// }
// }
// return sb.toString();
// }
// });
// h.setLevel(Level.FINE);
// logger.addHandler(h);
// logger.setLevel(Level.FINE);
// }
}
| resurrected compatibility with 2.7 and earlier.
| src/main/java/hudson/remoting/Channel.java | resurrected compatibility with 2.7 and earlier. | <ide><path>rc/main/java/hudson/remoting/Channel.java
<ide> public String toString() {
<ide> return "close";
<ide> }
<add>
<add> // this value is compatible with remoting < 2.8. I made an incompatible change in 2.8 that got corrected in 2.11.
<add> static final long serialVersionUID = 972857271608138115L;
<ide> }
<ide>
<ide> /** |
|
Java | mit | 8442af1d8cccb9930ba3a95fa29c4ce6ddf5794b | 0 | facebook/fresco,facebook/fresco,facebook/fresco,facebook/fresco,facebook/fresco,facebook/fresco | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.core;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.net.Uri;
import com.facebook.fresco.vito.options.ImageOptions;
import com.facebook.fresco.vito.options.RoundingOptions;
import com.facebook.fresco.vito.transformation.CircularBitmapTransformation;
import com.facebook.imagepipeline.common.ImageDecodeOptions;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.common.RotationOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.testing.TestNativeLoader;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class ImagePipelineUtilsTest {
static {
TestNativeLoader.init();
}
private static final Uri URI = Uri.parse("test");
private FrescoExperiments mFrescoExperiments;
private ImagePipelineUtils mImagePipelineUtils;
@Before
public void setup() {
mFrescoExperiments = mock(FrescoExperiments.class);
mImagePipelineUtils = new ImagePipelineUtils(mFrescoExperiments);
}
@Test
public void testBuildImageRequest_whenUriNull_thenReturnNull() {
ImageRequest imageRequest =
mImagePipelineUtils.buildImageRequest(null, ImageOptions.defaults());
assertThat(imageRequest).isNull();
}
@Test
public void testBuildImageRequest_whenUriNotNull_thenReturnRequest() {
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, ImageOptions.defaults());
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
}
@Test
public void testBuildImageRequest_whenNoRoundingOptions_thenDoNotRound() {
final ImageOptions imageOptions = ImageOptions.create().build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
assertThat(imageRequest.getImageDecodeOptions()).isEqualTo(ImageDecodeOptions.defaults());
}
@Test
public void testBuildImageRequest_whenRoundAsCircle_thenApplyRoundingParameters() {
when(mFrescoExperiments.useNativeRounding()).thenReturn(true);
final ImageOptions imageOptions =
ImageOptions.create().round(RoundingOptions.asCircle()).build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
ImageDecodeOptions imageDecodeOptions = imageRequest.getImageDecodeOptions();
assertThat(imageDecodeOptions).isNotEqualTo(ImageDecodeOptions.defaults());
assertThat(imageDecodeOptions.bitmapTransformation)
.isInstanceOf(CircularBitmapTransformation.class);
CircularBitmapTransformation transformation =
(CircularBitmapTransformation) imageDecodeOptions.bitmapTransformation;
assertThat(transformation).isNotNull();
assertThat(transformation.isAntiAliased()).isFalse();
}
@Test
public void
testBuildImageRequest_whenRoundAsCircleWithAntiAliasing_thenApplyRoundingParameters() {
when(mFrescoExperiments.useNativeRounding()).thenReturn(true);
final ImageOptions imageOptions =
ImageOptions.create().round(RoundingOptions.asCircle(true)).build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
ImageDecodeOptions imageDecodeOptions = imageRequest.getImageDecodeOptions();
assertThat(imageDecodeOptions).isNotEqualTo(ImageDecodeOptions.defaults());
assertThat(imageDecodeOptions.bitmapTransformation)
.isInstanceOf(CircularBitmapTransformation.class);
CircularBitmapTransformation transformation =
(CircularBitmapTransformation) imageDecodeOptions.bitmapTransformation;
assertThat(transformation).isNotNull();
assertThat(transformation.isAntiAliased()).isTrue();
}
@Test
public void testBuildImageRequest_whenResizingEnabled_thenSetResizeOptions() {
ResizeOptions resizeOptions = ResizeOptions.forDimensions(123, 234);
final ImageOptions imageOptions = ImageOptions.create().resize(resizeOptions).build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
assertThat(imageRequest.getResizeOptions()).isEqualTo(resizeOptions);
}
@Test
public void testBuildImageRequest_whenRotatingEnabled_thenSetRotateOptions() {
RotationOptions rotationOptions = RotationOptions.forceRotation(RotationOptions.ROTATE_270);
final ImageOptions imageOptions = ImageOptions.create().rotate(rotationOptions).build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
assertThat(imageRequest.getRotationOptions()).isEqualTo(rotationOptions);
}
}
| vito/core/src/test/java/com/facebook/fresco/vito/core/ImagePipelineUtilsTest.java | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.core;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.net.Uri;
import com.facebook.fresco.vito.options.ImageOptions;
import com.facebook.fresco.vito.options.RoundingOptions;
import com.facebook.fresco.vito.transformation.CircularBitmapTransformation;
import com.facebook.imagepipeline.common.ImageDecodeOptions;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.common.RotationOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.testing.TestNativeLoader;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class ImagePipelineUtilsTest {
static {
TestNativeLoader.init();
}
private static final Uri URI = Uri.parse("test");
private FrescoExperiments mFrescoExperiments;
private ImagePipelineUtils mImagePipelineUtils;
@Before
public void setup() {
mFrescoExperiments = mock(FrescoExperiments.class);
mImagePipelineUtils = new ImagePipelineUtils(mFrescoExperiments);
}
@Test
public void testBuildImageRequest_whenUriNull_thenReturnNull() {
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(null, ImageOptions.defaults());
assertThat(imageRequest).isNull();
}
@Test
public void testBuildImageRequest_whenUriNotNull_thenReturnRequest() {
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, ImageOptions.defaults());
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
}
@Test
public void testBuildImageRequest_whenNoRoundingOptions_thenDoNotRound() {
final ImageOptions imageOptions = ImageOptions.create().build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
assertThat(imageRequest.getImageDecodeOptions()).isEqualTo(ImageDecodeOptions.defaults());
}
@Test
public void testBuildImageRequest_whenRoundAsCircle_thenApplyRoundingParameters() {
when(mFrescoExperiments.useNativeRounding()).thenReturn(true);
final ImageOptions imageOptions =
ImageOptions.create().round(RoundingOptions.asCircle()).build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
ImageDecodeOptions imageDecodeOptions = imageRequest.getImageDecodeOptions();
assertThat(imageDecodeOptions).isNotEqualTo(ImageDecodeOptions.defaults());
assertThat(imageDecodeOptions.bitmapTransformation)
.isInstanceOf(CircularBitmapTransformation.class);
CircularBitmapTransformation transformation =
(CircularBitmapTransformation) imageDecodeOptions.bitmapTransformation;
assertThat(transformation).isNotNull();
assertThat(transformation.isAntiAliased()).isFalse();
}
@Test
public void
testBuildImageRequest_whenRoundAsCircleWithAntiAliasing_thenApplyRoundingParameters() {
when(mFrescoExperiments.useNativeRounding()).thenReturn(true);
final ImageOptions imageOptions =
ImageOptions.create().round(RoundingOptions.asCircle(true)).build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
ImageDecodeOptions imageDecodeOptions = imageRequest.getImageDecodeOptions();
assertThat(imageDecodeOptions).isNotEqualTo(ImageDecodeOptions.defaults());
assertThat(imageDecodeOptions.bitmapTransformation)
.isInstanceOf(CircularBitmapTransformation.class);
CircularBitmapTransformation transformation =
(CircularBitmapTransformation) imageDecodeOptions.bitmapTransformation;
assertThat(transformation).isNotNull();
assertThat(transformation.isAntiAliased()).isTrue();
}
@Test
public void testBuildImageRequest_whenResizingEnabled_thenSetResizeOptions() {
ResizeOptions resizeOptions = ResizeOptions.forDimensions(123, 234);
final ImageOptions imageOptions = ImageOptions.create().resize(resizeOptions).build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
assertThat(imageRequest.getResizeOptions()).isEqualTo(resizeOptions);
}
@Test
public void testBuildImageRequest_whenRotatingEnabled_thenSetRotateOptions() {
RotationOptions rotationOptions = RotationOptions.forceRotation(RotationOptions.ROTATE_270);
final ImageOptions imageOptions = ImageOptions.create().rotate(rotationOptions).build();
ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(URI, imageOptions);
assertThat(imageRequest).isNotNull();
assertThat(imageRequest.getSourceUri()).isEqualTo(URI);
assertThat(imageRequest.getRotationOptions()).isEqualTo(rotationOptions);
}
}
| Daily `arc lint --take GOOGLEJAVAFORMAT`
Reviewed By: zertosh
Differential Revision: D19901403
fbshipit-source-id: c5fe154ceb99e53ff667c7d9ab66410469ddf440
| vito/core/src/test/java/com/facebook/fresco/vito/core/ImagePipelineUtilsTest.java | Daily `arc lint --take GOOGLEJAVAFORMAT` | <ide><path>ito/core/src/test/java/com/facebook/fresco/vito/core/ImagePipelineUtilsTest.java
<ide>
<ide> @Test
<ide> public void testBuildImageRequest_whenUriNull_thenReturnNull() {
<del> ImageRequest imageRequest = mImagePipelineUtils.buildImageRequest(null, ImageOptions.defaults());
<add> ImageRequest imageRequest =
<add> mImagePipelineUtils.buildImageRequest(null, ImageOptions.defaults());
<ide>
<ide> assertThat(imageRequest).isNull();
<ide> } |
|
Java | mit | 6db60c0abe00ec8a1b55d9020909c20754f128e8 | 0 | dreamhead/moco,dreamhead/moco | package com.github.dreamhead.moco;
import com.github.dreamhead.moco.matcher.AbstractRequestMatcher;
import static com.github.dreamhead.moco.internal.InternalApis.context;
public interface RequestMatcher extends ConfigApplier<RequestMatcher> {
boolean match(Request request);
RequestMatcher ANY_REQUEST_MATCHER = new AbstractRequestMatcher() {
@Override
public boolean match(final Request request) {
return true;
}
@Override
@SuppressWarnings("unchecked")
public RequestMatcher doApply(final MocoConfig config) {
if (config.isFor(MocoConfig.URI_ID)) {
return context((String) config.apply(""));
}
return this;
}
};
}
| moco-core/src/main/java/com/github/dreamhead/moco/RequestMatcher.java | package com.github.dreamhead.moco;
import com.github.dreamhead.moco.matcher.AbstractRequestMatcher;
import static com.github.dreamhead.moco.internal.InternalApis.context;
public interface RequestMatcher extends ConfigApplier<RequestMatcher> {
boolean match(final Request request);
RequestMatcher ANY_REQUEST_MATCHER = new AbstractRequestMatcher() {
@Override
public boolean match(final Request request) {
return true;
}
@Override
@SuppressWarnings("unchecked")
public RequestMatcher doApply(final MocoConfig config) {
if (config.isFor(MocoConfig.URI_ID)) {
return context((String) config.apply(""));
}
return this;
}
};
}
| removed redundant final from request matcher
| moco-core/src/main/java/com/github/dreamhead/moco/RequestMatcher.java | removed redundant final from request matcher | <ide><path>oco-core/src/main/java/com/github/dreamhead/moco/RequestMatcher.java
<ide> import static com.github.dreamhead.moco.internal.InternalApis.context;
<ide>
<ide> public interface RequestMatcher extends ConfigApplier<RequestMatcher> {
<del> boolean match(final Request request);
<add> boolean match(Request request);
<ide>
<ide> RequestMatcher ANY_REQUEST_MATCHER = new AbstractRequestMatcher() {
<ide> @Override |
|
Java | apache-2.0 | e739c5aa87e0b0bc9df8f9c5a9a78b4bc0d3eeb6 | 0 | cdljsj/cat,bryanchou/cat,dadarom/cat,chinaboard/cat,howepeng/cat,jialinsun/cat,chinaboard/cat,redbeans2015/cat,cdljsj/cat,dadarom/cat,ddviplinux/cat,unidal/cat,dianping/cat,javachengwc/cat,dianping/cat,ddviplinux/cat,wuqiangxjtu/cat,redbeans2015/cat,javachengwc/cat,bryanchou/cat,javachengwc/cat,JacksonSha/cat,michael8335/cat,wyzssw/cat,unidal/cat,chqlb/cat,itnihao/cat,xiaojiaqi/cat,chinaboard/cat,jialinsun/cat,xiaojiaqi/cat,howepeng/cat,dadarom/cat,howepeng/cat,bryanchou/cat,howepeng/cat,itnihao/cat,cdljsj/cat,dadarom/cat,JacksonSha/cat,howepeng/cat,chqlb/cat,gspandy/cat,dadarom/cat,TonyChai24/cat,itnihao/cat,dianping/cat,wyzssw/cat,wuqiangxjtu/cat,jialinsun/cat,cdljsj/cat,chinaboard/cat,javachengwc/cat,wyzssw/cat,ddviplinux/cat,wuqiangxjtu/cat,redbeans2015/cat,chqlb/cat,unidal/cat,xiaojiaqi/cat,dianping/cat,wyzssw/cat,wyzssw/cat,redbeans2015/cat,ddviplinux/cat,wuqiangxjtu/cat,chqlb/cat,dianping/cat,TonyChai24/cat,michael8335/cat,dianping/cat,redbeans2015/cat,ddviplinux/cat,chinaboard/cat,gspandy/cat,michael8335/cat,JacksonSha/cat,gspandy/cat,TonyChai24/cat,gspandy/cat,dadarom/cat,javachengwc/cat,gspandy/cat,jialinsun/cat,ddviplinux/cat,TonyChai24/cat,xiaojiaqi/cat,javachengwc/cat,unidal/cat,JacksonSha/cat,unidal/cat,itnihao/cat,xiaojiaqi/cat,itnihao/cat,TonyChai24/cat,xiaojiaqi/cat,bryanchou/cat,cdljsj/cat,chqlb/cat,JacksonSha/cat,bryanchou/cat,gspandy/cat,chinaboard/cat,bryanchou/cat,TonyChai24/cat,wuqiangxjtu/cat,jialinsun/cat,cdljsj/cat,JacksonSha/cat,itnihao/cat,chqlb/cat,wyzssw/cat,howepeng/cat,redbeans2015/cat,michael8335/cat,dianping/cat,michael8335/cat,wuqiangxjtu/cat,michael8335/cat,unidal/cat,jialinsun/cat | package com.dianping.cat.report.task.alert.sender;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.helper.Threads;
import org.unidal.helper.Threads.Task;
import org.unidal.lookup.annotation.Inject;
import org.unidal.tuple.Pair;
import com.dianping.cat.Cat;
import com.dianping.cat.message.Event;
import com.dianping.cat.report.task.alert.sender.decorator.DecoratorManager;
import com.dianping.cat.report.task.alert.sender.receiver.ContactorManager;
import com.dianping.cat.report.task.alert.sender.sender.SenderManager;
import com.dianping.cat.report.task.alert.sender.spliter.SpliterManager;
import com.dianping.cat.report.task.alert.service.AlertEntityService;
import com.dianping.cat.system.config.AlertPolicyManager;
public class AlertManager implements Initializable {
@Inject
private AlertPolicyManager m_policyManager;
@Inject
private DecoratorManager m_decoratorManager;
@Inject
private ContactorManager m_contactorManager;
@Inject
protected SpliterManager m_splitterManager;
@Inject
protected SenderManager m_senderManager;
@Inject
protected AlertEntityService m_alertEntityService;
private BlockingQueue<AlertEntity> m_alerts = new LinkedBlockingDeque<AlertEntity>(10000);
private boolean send(AlertEntity alert) {
boolean result = false;
String type = alert.getType();
String group = alert.getGroup();
String level = alert.getLevel();
List<AlertChannel> channels = m_policyManager.queryChannels(type, group, level);
Cat.logEvent("Alert:" + type, group, Event.SUCCESS, null);
for (AlertChannel channel : channels) {
Pair<String, String> pair = m_decoratorManager.generateTitleAndContent(alert);
String title = pair.getKey();
String content = m_splitterManager.process(pair.getValue(), channel);
List<String> receivers = m_contactorManager.queryReceivers(group, channel, type);
AlertMessageEntity message = new AlertMessageEntity(group, title, content, receivers);
m_alertEntityService.storeAlert(alert, message);
if (m_senderManager.sendAlert(channel, type, message)) {
result = true;
}
}
return result;
}
public boolean addAlert(AlertEntity alert) {
return m_alerts.offer(alert);
}
private class SendExecutor implements Task {
@Override
public void run() {
boolean active = true;
while (active) {
try {
AlertEntity alert = m_alerts.poll(5, TimeUnit.MILLISECONDS);
if (alert != null) {
send(alert);
}
} catch (Exception e) {
Cat.logError(e);
break;
}
}
}
@Override
public String getName() {
return "send-executor";
}
@Override
public void shutdown() {
}
}
@Override
public void initialize() throws InitializationException {
Threads.forGroup("Cat").start(new SendExecutor());
}
}
| cat-home/src/main/java/com/dianping/cat/report/task/alert/sender/AlertManager.java | package com.dianping.cat.report.task.alert.sender;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.helper.Threads;
import org.unidal.helper.Threads.Task;
import org.unidal.lookup.annotation.Inject;
import org.unidal.tuple.Pair;
import com.dianping.cat.Cat;
import com.dianping.cat.report.task.alert.sender.decorator.DecoratorManager;
import com.dianping.cat.report.task.alert.sender.receiver.ContactorManager;
import com.dianping.cat.report.task.alert.sender.sender.SenderManager;
import com.dianping.cat.report.task.alert.sender.spliter.SpliterManager;
import com.dianping.cat.report.task.alert.service.AlertEntityService;
import com.dianping.cat.system.config.AlertPolicyManager;
public class AlertManager implements Initializable {
@Inject
private AlertPolicyManager m_policyManager;
@Inject
private DecoratorManager m_decoratorManager;
@Inject
private ContactorManager m_contactorManager;
@Inject
protected SpliterManager m_splitterManager;
@Inject
protected SenderManager m_senderManager;
@Inject
protected AlertEntityService m_alertEntityService;
private BlockingQueue<AlertEntity> m_alerts = new LinkedBlockingDeque<AlertEntity>(10000);
private boolean send(AlertEntity alert) {
boolean result = false;
String type = alert.getType();
String group = alert.getGroup();
String level = alert.getLevel();
List<AlertChannel> channels = m_policyManager.queryChannels(type, group, level);
for (AlertChannel channel : channels) {
Pair<String, String> pair = m_decoratorManager.generateTitleAndContent(alert);
String title = pair.getKey();
String content = m_splitterManager.process(pair.getValue(), channel);
List<String> receivers = m_contactorManager.queryReceivers(group, channel, type);
AlertMessageEntity message = new AlertMessageEntity(group, title, content, receivers);
m_alertEntityService.storeAlert(alert, message);
if (m_senderManager.sendAlert(channel, type, message)) {
result = true;
}
}
return result;
}
public boolean addAlert(AlertEntity alert) {
return m_alerts.offer(alert);
}
private class SendExecutor implements Task {
@Override
public void run() {
boolean active = true;
while (active) {
try {
AlertEntity alert = m_alerts.poll(5, TimeUnit.MILLISECONDS);
if (alert != null) {
send(alert);
}
} catch (Exception e) {
Cat.logError(e);
break;
}
}
}
@Override
public String getName() {
return "send-executor";
}
@Override
public void shutdown() {
}
}
@Override
public void initialize() throws InitializationException {
Threads.forGroup("Cat").start(new SendExecutor());
}
}
| modify the alert Manager
| cat-home/src/main/java/com/dianping/cat/report/task/alert/sender/AlertManager.java | modify the alert Manager | <ide><path>at-home/src/main/java/com/dianping/cat/report/task/alert/sender/AlertManager.java
<ide> import org.unidal.tuple.Pair;
<ide>
<ide> import com.dianping.cat.Cat;
<add>import com.dianping.cat.message.Event;
<ide> import com.dianping.cat.report.task.alert.sender.decorator.DecoratorManager;
<ide> import com.dianping.cat.report.task.alert.sender.receiver.ContactorManager;
<ide> import com.dianping.cat.report.task.alert.sender.sender.SenderManager;
<ide>
<ide> @Inject
<ide> protected SenderManager m_senderManager;
<del>
<add>
<ide> @Inject
<ide> protected AlertEntityService m_alertEntityService;
<ide>
<ide> String group = alert.getGroup();
<ide> String level = alert.getLevel();
<ide> List<AlertChannel> channels = m_policyManager.queryChannels(type, group, level);
<add>
<add> Cat.logEvent("Alert:" + type, group, Event.SUCCESS, null);
<ide>
<ide> for (AlertChannel channel : channels) {
<ide> Pair<String, String> pair = m_decoratorManager.generateTitleAndContent(alert); |
|
JavaScript | apache-2.0 | 623af0ed6e817650511b41115830010086c1acc1 | 0 | Kitware/geojs,OpenGeoscience/geojs,OpenGeoscience/geojs,dcjohnston/geojs,OpenGeoscience/geojs,Kitware/geojs,dcjohnston/geojs,dcjohnston/geojs,essamjoubori/geojs,dcjohnston/geojs,Kitware/geojs,essamjoubori/geojs,essamjoubori/geojs,essamjoubori/geojs | /*global window*/
(function ($, geo) {
'use strict';
// This requires jquery ui, which we don't want to make a
// hard requirement, so bail out here if the widget factory
// is not available and throw a helpful message when the
// tries to use it.
if (!$.widget) {
$.fn.geojsMap = function () {
throw new Error(
'The geojs jquery plugin requires jquery ui to be available.'
);
};
return;
}
// polyfill console.warn if necessary
var warn;
if (console && console.warn) {
warn = console.warn;
} else {
warn = $.noop;
}
// for multiple initialization detection
var initialized = false;
/**
* @class geojsMap
* @memberOf $.fn
*
* @description Generates a geojs map inside an element. Due to
* current limitations in geojs, only a single map can be instantiated
* on a page. Trying to create a second map will throw an error
* (see issue
* <a href="https://github.com/OpenGeoscience/geojs/issues/154">#154</a>).
* @example <caption>Create a map with the default options.</caption>
* $("#map").geojsMap();
* @example <caption>Create a map with a given initial center and zoom</caption>
* $("#map").geojsMap({
* longitude: -125,
* latitude: 35,
* zoom: 5
* });
*/
$.widget('geojs.geojsMap', /** @lends $.fn.geojsMap */{
/**
* A coordinate object as accepted by geojs to express positions in an
* arbitrary coordinate system (geographic, screen, etc). Coordinates returned by
* geojs methods are always expressed with "x" and "y" properties, but
* it will accept any of the aliased properties.
* @typedef coordinate
* @type {Object}
* @property {number} longitude Alias: "x", "lng", or "lon"
* @property {number} latitude Alias: "y" or "lat"
* @property {number} [elevation=0] Alias: "z", "elev", or "height"
*/
/**
* A geojs renderer is one of the following:
* <ul>
* <li><code>"vglRenderer"</code>: Uses webGL</li>
* <li><code>"d3Renderer"</code>: Uses svg</li>
* </ul>
* @typedef renderer
* @type {string}
*/
/**
* Colors can be expressed in multiple ways:
* <ul>
* <li>css name (<code>"steelblue"</code>)</li>
* <li>24 bit hex value (<code>0xff0051</code>)</li>
* <li>25 bit hex string (<code>"#ff0051"</code>)</li>
* <li>rgb object (values from 0-1, <code>{r: 1, g: 0.5, b: 0}</code>)</li>
* </ul>
* @typedef color
* @type {*}
*/
/**
* Point feature options object. All styles can be
* given as accessor functions or constants. Accessor
* functions are called with the following signature:
* <pre>
* function func(d, i) {
* // d - data object
* // i - index of d in the data array
* // this - geo.pointFeature
* }
* </pre>
* @typedef pointOptions
* @type {Object}
* @property {Object[]} data Data array
* @property {number} radius Radius of the circle in pixels
* @property {boolean} fill Presence or absence of the fill
* @property {color} fillColor Interior color
* @property {float} fillOpacity Opacity of the interior <code>[0,1]</code>
* @property {boolean} stroke Presence or absence of the stroke
* @property {color} strokeColor Stroke color
* @property {float} strokeOpacity Opacity of the stroke <code>[0,1]</code>
*/
/**
* @instance
* @description
* Map options
* @example <caption>Get the current map center</caption>
* var center=$("#map").geojsMap("center");
* @example <caption>Pan the map to a new center</caption>
* $("#map").geojsMap("center", {lat: 10, lng: -100});
* @property {coordinate} [center={lat: 0, lng: 0}] The map center
* @property {number} [zoom=0] The zoom level (floating point >= 0)
* @property {(number|null)} [width=null]
* The width of the map in pixels or null for 100%
* @property {(number|null)} [height=null]
* The height of the map in pixels or null for 100%
* @property {renderer} [renderer="vglRenderer"]
* The renderer for map features (initialization only)
* @property {boolean} [autoresize=true]
* Resize the map on <code>window.resize</code> (initialization only)
*/
options: {
center: {latitude: 0, longitude: 0},
zoom: 0,
width: null,
height: null,
renderer: 'vglRenderer',
// These options are for future use, but shouldn't
// be changed at the moment, so they aren't documented.
baseLayer: 'osm',
baseRenderer: 'vglRenderer'
},
/**
* Internal constructor
* @instance
* @protected
*/
_create: function () {
if (this._map || !this.element.length) {
// when called multiple times on a single element, do nothing
return;
}
if (initialized) {
// when called multiple times on different elements, die
throw new Error(
'Only one map per page is allowed.'
);
}
// set global initialization state
initialized = true;
// create the map
this._map = geo.map({
width: this.options.width,
height: this.options.height,
zoom: this.options.zoom,
center: this.options.center,
node: this.element.get(0)
});
// create the base layer
this._baseLayer = this._map.createLayer(
this.options.baseLayer,
{
renderer: this.options.baseRenderer
}
);
// Trigger a resize to a valid size before adding
// the feature layer to handle some of the bugs that
// occur when initializing onto a node of size 0.
this._resize({width: 800, height: 600});
// store the renderer, because it can't be changed
this._renderer = this.options.renderer;
// create the feature layer
this._featureLayer = this._map.createLayer('feature', {
renderer: this._renderer
});
// create a point feature
this._points = this._featureLayer.createFeature('point').data([]);
// create a line feature
this._lines = this._featureLayer.createFeature('line').data([]);
// trigger an initial draw
this.redraw();
},
/**
* Resize the map canvas.
* @instance
* @protected
* @param {object?} size Explicit size or use this.options.
*/
_resize: function (size) {
var width = this.options.width,
height = this.options.height;
if (size) {
width = size.width;
height = size.height;
}
if (!width) {
width = this.element.width();
}
if (!height) {
height = this.element.height();
}
this._map.resize(0, 0, width, height);
},
/**
* Do a full redraw of the map. In general, users shouldn't need to
* call this method, but it could be useful when accessing lower
* level features of the mapping api.
* @instance
*/
redraw: function () {
this._resize();
},
/**
* Set point feature data and styles. Only the properties provided
* will be applied to the map. For example, if options.data is
* undefined, then the data previously given will be used.
* @instance
* @param {object} options Point options (see {@link pointOptions})
* @example <caption>Initializing point attributes</caption>
* $("#map").points({
* position: function (d) {
* return {x: d.geometry.lon, y: d.geometry.lat}
* },
* radius: function (d) { return d.size; },
* fillColor: "red",
* strokeColor: "#010a10"
* });
* @example <caption>Updating the point data</caption>
* $("#map").points({
* data: data
* });
*/
points: function (options) {
var pt = this._points;
options = options || {};
if (options.data) {
pt.data(options.data);
}
if (options.position) {
pt.position(function () {
// could use some optimization
var f = geo.util.ensureFunction(options.position);
var d = f.apply(this, arguments);
return geo.util.normalizeCoordinates(d);
});
}
pt.style(options).draw();
// handle vglRenderer bug where feature.draw() doesn't cause a redraw
if (this._renderer === 'vglRenderer') {
this._map.draw();
}
}
});
})($ || window.$, geo || window.geo);
| src/plugin/jquery-plugin.js | /*global window*/
(function ($, geo) {
'use strict';
// Default map options that can be over-ridden via plugin options.
var defaultOptions = {
mapOpts: {
center: {latitude: 0, longitude: 0},
zoom: 0
},
baseLayer: 'osm', // a valid geojs base layer name
baseRenderer: 'vglRenderer' // renderer for the base layer
};
// polyfill console.warn if necessary
var warn;
if (console && console.warn) {
warn = console.warn;
} else {
warn = $.noop;
}
// for multiple initialization detection
var initialized = false;
$.fn.geojsMap = function (options) {
return this.each(function () {
var m_this = $(this),
geodata,
opts,
baseLayer,
map;
// geojs limitation:
// https://github.com/OpenGeoscience/geojs/issues/154
if (initialized) {
throw new Error(
'Geojs currently limited to one map per page.'
);
}
initialized = true;
// Get user supplied options
opts = $.extend(true, {}, defaultOptions, options);
// Create the map
map = geo.map($.extend({}, opts.mapOpts, {
node: this
}));
// Set the initial size to something valid just in case
map.resize(0, 0, 800, 600);
// Create the baselayer
baseLayer = map.createLayer(opts.baseLayer);
// Create a resize method and attach it to window.resize
function resize() {
var width = m_this.width(),
height = m_this.height();
// Geojs doesn't handle invalid sizes gracefully.
if (width <= 0 || height <= 0) {
warn(
'Attempting to set invalid size: (' + [width, height] + ')'
);
} else {
map.resize(0, 0, width, height);
}
}
resize();
$(window).resize(resize);
// Attach map information to the node
geodata = {
options: opts,
map: map,
baseLayer: baseLayer
};
$(this).data('geojs', geodata);
});
};
}($ || window.$, geo || window.geo));
| Rewrite jquery plugin using $.widget
| src/plugin/jquery-plugin.js | Rewrite jquery plugin using $.widget | <ide><path>rc/plugin/jquery-plugin.js
<ide> /*global window*/
<del>
<ide> (function ($, geo) {
<ide> 'use strict';
<ide>
<del> // Default map options that can be over-ridden via plugin options.
<del> var defaultOptions = {
<del> mapOpts: {
<del> center: {latitude: 0, longitude: 0},
<del> zoom: 0
<del> },
<del> baseLayer: 'osm', // a valid geojs base layer name
<del> baseRenderer: 'vglRenderer' // renderer for the base layer
<del> };
<add> // This requires jquery ui, which we don't want to make a
<add> // hard requirement, so bail out here if the widget factory
<add> // is not available and throw a helpful message when the
<add> // tries to use it.
<add> if (!$.widget) {
<add> $.fn.geojsMap = function () {
<add> throw new Error(
<add> 'The geojs jquery plugin requires jquery ui to be available.'
<add> );
<add> };
<add> return;
<add> }
<ide>
<ide> // polyfill console.warn if necessary
<ide> var warn;
<ide> // for multiple initialization detection
<ide> var initialized = false;
<ide>
<del> $.fn.geojsMap = function (options) {
<del> return this.each(function () {
<del> var m_this = $(this),
<del> geodata,
<del> opts,
<del> baseLayer,
<del> map;
<del>
<del> // geojs limitation:
<del> // https://github.com/OpenGeoscience/geojs/issues/154
<add> /**
<add> * @class geojsMap
<add> * @memberOf $.fn
<add> *
<add> * @description Generates a geojs map inside an element. Due to
<add> * current limitations in geojs, only a single map can be instantiated
<add> * on a page. Trying to create a second map will throw an error
<add> * (see issue
<add> * <a href="https://github.com/OpenGeoscience/geojs/issues/154">#154</a>).
<add> * @example <caption>Create a map with the default options.</caption>
<add> * $("#map").geojsMap();
<add> * @example <caption>Create a map with a given initial center and zoom</caption>
<add> * $("#map").geojsMap({
<add> * longitude: -125,
<add> * latitude: 35,
<add> * zoom: 5
<add> * });
<add> */
<add> $.widget('geojs.geojsMap', /** @lends $.fn.geojsMap */{
<add> /**
<add> * A coordinate object as accepted by geojs to express positions in an
<add> * arbitrary coordinate system (geographic, screen, etc). Coordinates returned by
<add> * geojs methods are always expressed with "x" and "y" properties, but
<add> * it will accept any of the aliased properties.
<add> * @typedef coordinate
<add> * @type {Object}
<add> * @property {number} longitude Alias: "x", "lng", or "lon"
<add> * @property {number} latitude Alias: "y" or "lat"
<add> * @property {number} [elevation=0] Alias: "z", "elev", or "height"
<add> */
<add>
<add> /**
<add> * A geojs renderer is one of the following:
<add> * <ul>
<add> * <li><code>"vglRenderer"</code>: Uses webGL</li>
<add> * <li><code>"d3Renderer"</code>: Uses svg</li>
<add> * </ul>
<add> * @typedef renderer
<add> * @type {string}
<add> */
<add>
<add> /**
<add> * Colors can be expressed in multiple ways:
<add> * <ul>
<add> * <li>css name (<code>"steelblue"</code>)</li>
<add> * <li>24 bit hex value (<code>0xff0051</code>)</li>
<add> * <li>25 bit hex string (<code>"#ff0051"</code>)</li>
<add> * <li>rgb object (values from 0-1, <code>{r: 1, g: 0.5, b: 0}</code>)</li>
<add> * </ul>
<add> * @typedef color
<add> * @type {*}
<add> */
<add>
<add> /**
<add> * Point feature options object. All styles can be
<add> * given as accessor functions or constants. Accessor
<add> * functions are called with the following signature:
<add> * <pre>
<add> * function func(d, i) {
<add> * // d - data object
<add> * // i - index of d in the data array
<add> * // this - geo.pointFeature
<add> * }
<add> * </pre>
<add> * @typedef pointOptions
<add> * @type {Object}
<add> * @property {Object[]} data Data array
<add> * @property {number} radius Radius of the circle in pixels
<add> * @property {boolean} fill Presence or absence of the fill
<add> * @property {color} fillColor Interior color
<add> * @property {float} fillOpacity Opacity of the interior <code>[0,1]</code>
<add> * @property {boolean} stroke Presence or absence of the stroke
<add> * @property {color} strokeColor Stroke color
<add> * @property {float} strokeOpacity Opacity of the stroke <code>[0,1]</code>
<add> */
<add>
<add> /**
<add> * @instance
<add> * @description
<add> * Map options
<add> * @example <caption>Get the current map center</caption>
<add> * var center=$("#map").geojsMap("center");
<add> * @example <caption>Pan the map to a new center</caption>
<add> * $("#map").geojsMap("center", {lat: 10, lng: -100});
<add> * @property {coordinate} [center={lat: 0, lng: 0}] The map center
<add> * @property {number} [zoom=0] The zoom level (floating point >= 0)
<add> * @property {(number|null)} [width=null]
<add> * The width of the map in pixels or null for 100%
<add> * @property {(number|null)} [height=null]
<add> * The height of the map in pixels or null for 100%
<add> * @property {renderer} [renderer="vglRenderer"]
<add> * The renderer for map features (initialization only)
<add> * @property {boolean} [autoresize=true]
<add> * Resize the map on <code>window.resize</code> (initialization only)
<add> */
<add> options: {
<add> center: {latitude: 0, longitude: 0},
<add> zoom: 0,
<add> width: null,
<add> height: null,
<add> renderer: 'vglRenderer',
<add>
<add> // These options are for future use, but shouldn't
<add> // be changed at the moment, so they aren't documented.
<add> baseLayer: 'osm',
<add> baseRenderer: 'vglRenderer'
<add> },
<add>
<add> /**
<add> * Internal constructor
<add> * @instance
<add> * @protected
<add> */
<add> _create: function () {
<add> if (this._map || !this.element.length) {
<add> // when called multiple times on a single element, do nothing
<add> return;
<add> }
<ide> if (initialized) {
<add> // when called multiple times on different elements, die
<ide> throw new Error(
<del> 'Geojs currently limited to one map per page.'
<add> 'Only one map per page is allowed.'
<ide> );
<ide> }
<add> // set global initialization state
<ide> initialized = true;
<ide>
<del> // Get user supplied options
<del> opts = $.extend(true, {}, defaultOptions, options);
<del>
<del> // Create the map
<del> map = geo.map($.extend({}, opts.mapOpts, {
<del> node: this
<del> }));
<del>
<del> // Set the initial size to something valid just in case
<del> map.resize(0, 0, 800, 600);
<del>
<del> // Create the baselayer
<del> baseLayer = map.createLayer(opts.baseLayer);
<del>
<del> // Create a resize method and attach it to window.resize
<del> function resize() {
<del> var width = m_this.width(),
<del> height = m_this.height();
<del>
<del> // Geojs doesn't handle invalid sizes gracefully.
<del> if (width <= 0 || height <= 0) {
<del> warn(
<del> 'Attempting to set invalid size: (' + [width, height] + ')'
<del> );
<del> } else {
<del> map.resize(0, 0, width, height);
<add> // create the map
<add> this._map = geo.map({
<add> width: this.options.width,
<add> height: this.options.height,
<add> zoom: this.options.zoom,
<add> center: this.options.center,
<add> node: this.element.get(0)
<add> });
<add>
<add> // create the base layer
<add> this._baseLayer = this._map.createLayer(
<add> this.options.baseLayer,
<add> {
<add> renderer: this.options.baseRenderer
<ide> }
<del> }
<del> resize();
<del> $(window).resize(resize);
<del>
<del> // Attach map information to the node
<del> geodata = {
<del> options: opts,
<del> map: map,
<del> baseLayer: baseLayer
<del> };
<del> $(this).data('geojs', geodata);
<del> });
<del> };
<del>}($ || window.$, geo || window.geo));
<add> );
<add>
<add> // Trigger a resize to a valid size before adding
<add> // the feature layer to handle some of the bugs that
<add> // occur when initializing onto a node of size 0.
<add> this._resize({width: 800, height: 600});
<add>
<add> // store the renderer, because it can't be changed
<add> this._renderer = this.options.renderer;
<add>
<add> // create the feature layer
<add> this._featureLayer = this._map.createLayer('feature', {
<add> renderer: this._renderer
<add> });
<add>
<add> // create a point feature
<add> this._points = this._featureLayer.createFeature('point').data([]);
<add>
<add> // create a line feature
<add> this._lines = this._featureLayer.createFeature('line').data([]);
<add>
<add> // trigger an initial draw
<add> this.redraw();
<add> },
<add>
<add> /**
<add> * Resize the map canvas.
<add> * @instance
<add> * @protected
<add> * @param {object?} size Explicit size or use this.options.
<add> */
<add> _resize: function (size) {
<add> var width = this.options.width,
<add> height = this.options.height;
<add> if (size) {
<add> width = size.width;
<add> height = size.height;
<add> }
<add> if (!width) {
<add> width = this.element.width();
<add> }
<add> if (!height) {
<add> height = this.element.height();
<add> }
<add> this._map.resize(0, 0, width, height);
<add> },
<add>
<add> /**
<add> * Do a full redraw of the map. In general, users shouldn't need to
<add> * call this method, but it could be useful when accessing lower
<add> * level features of the mapping api.
<add> * @instance
<add> */
<add> redraw: function () {
<add> this._resize();
<add> },
<add>
<add> /**
<add> * Set point feature data and styles. Only the properties provided
<add> * will be applied to the map. For example, if options.data is
<add> * undefined, then the data previously given will be used.
<add> * @instance
<add> * @param {object} options Point options (see {@link pointOptions})
<add> * @example <caption>Initializing point attributes</caption>
<add> * $("#map").points({
<add> * position: function (d) {
<add> * return {x: d.geometry.lon, y: d.geometry.lat}
<add> * },
<add> * radius: function (d) { return d.size; },
<add> * fillColor: "red",
<add> * strokeColor: "#010a10"
<add> * });
<add> * @example <caption>Updating the point data</caption>
<add> * $("#map").points({
<add> * data: data
<add> * });
<add> */
<add> points: function (options) {
<add> var pt = this._points;
<add> options = options || {};
<add>
<add> if (options.data) {
<add> pt.data(options.data);
<add> }
<add> if (options.position) {
<add> pt.position(function () {
<add> // could use some optimization
<add> var f = geo.util.ensureFunction(options.position);
<add> var d = f.apply(this, arguments);
<add> return geo.util.normalizeCoordinates(d);
<add> });
<add> }
<add> pt.style(options).draw();
<add>
<add> // handle vglRenderer bug where feature.draw() doesn't cause a redraw
<add> if (this._renderer === 'vglRenderer') {
<add> this._map.draw();
<add> }
<add> }
<add> });
<add>})($ || window.$, geo || window.geo); |
|
Java | agpl-3.0 | 7684f10e5fa35769f19a31e10a8d5cc223688cd8 | 0 | cojen/Tupl | /*
* Copyright 2011-2015 Cojen.org
*
* 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.cojen.tupl;
import java.io.IOException;
import org.cojen.tupl.util.Latch;
import static org.cojen.tupl.PageOps.*;
import static org.cojen.tupl.Utils.EMPTY_BYTES;
import static org.cojen.tupl.Utils.closeOnFailure;
import static org.cojen.tupl.Utils.compareUnsigned;
import static org.cojen.tupl.Utils.rethrow;
/**
* Node within a B-tree, undo log, or a large value fragment.
*
* @author Brian S O'Neill
*/
@SuppressWarnings("serial")
final class Node extends Latch implements DatabaseAccess {
// Note: Changing these values affects how the Database class handles the
// commit flag. It only needs to flip bit 0 to switch dirty states.
static final byte
CACHED_CLEAN = 0, // 0b0000
CACHED_DIRTY_0 = 2, // 0b0010
CACHED_DIRTY_1 = 3; // 0b0011
/*
Node type encoding strategy:
bits 7..4: major type 0010 (fragment), 0100 (undo log),
0110 (internal), 0111 (bottom internal), 1000 (leaf)
bits 3..1: sub type for leaf: x0x (normal)
for internal: x1x (6 byte child pointer + 2 byte count), x0x (unused)
for both: bit 1 is set if low extremity, bit 3 for high extremity
bit 0: endianness 0 (little), 1 (big)
TN == Tree Node
Note that leaf type is always negative. If type encoding changes, the isLeaf and
isInternal methods might need to be updated.
*/
static final byte
TYPE_NONE = 0,
/*P*/ // [
TYPE_FRAGMENT = (byte) 0x20, // 0b0010_000_0 (never persisted)
/*P*/ // ]
TYPE_UNDO_LOG = (byte) 0x40, // 0b0100_000_0
TYPE_TN_IN = (byte) 0x64, // 0b0110_010_0
TYPE_TN_BIN = (byte) 0x74, // 0b0111_010_0
TYPE_TN_LEAF = (byte) 0x80; // 0b1000_000_0
static final byte LOW_EXTREMITY = 0x02, HIGH_EXTREMITY = 0x08;
// Tree node header size.
static final int TN_HEADER_SIZE = 12;
static final int STUB_ID = 1;
static final int ENTRY_FRAGMENTED = 0x40;
// Usage list this node belongs to.
final NodeUsageList mUsageList;
// Links within usage list, guarded by NodeUsageList.
Node mMoreUsed; // points to more recently used node
Node mLessUsed; // points to less recently used node
// Links within dirty list, guarded by NodeDirtyList.
Node mNextDirty;
Node mPrevDirty;
/*
Nodes define the contents of Trees and UndoLogs. All node types start
with a two byte header.
+----------------------------------------+
| byte: node type | header
| byte: reserved (must be 0) |
- -
There are two types of tree nodes, having a similar structure and
supporting a maximum page size of 65536 bytes. The ushort type is an
unsigned byte pair, and the ulong type is eight bytes. All multibyte
types are little endian encoded.
+----------------------------------------+
| byte: node type | header
| byte: reserved (must be 0) |
| ushort: garbage in segments |
| ushort: pointer to left segment tail |
| ushort: pointer to right segment tail |
| ushort: pointer to search vector start |
| ushort: pointer to search vector end |
+----------------------------------------+
| left segment |
- -
| |
+----------------------------------------+
| free space | <-- left segment tail (exclusive)
- -
| |
+----------------------------------------+
| search vector | <-- search vector start (inclusive)
- -
| | <-- search vector end (inclusive)
+----------------------------------------+
| free space |
- -
| | <-- right segment tail (exclusive)
+----------------------------------------+
| right segment |
- -
| |
+----------------------------------------+
The left and right segments are used for allocating variable sized entries, and the
tail points to the next allocation. Allocations are made toward the search vector
such that the free space before and after the search vector remain the roughly the
same. The search vector may move if a contiguous allocation is not possible on
either side.
The search vector is used for performing a binary search against keys. The keys are
variable length and are stored anywhere in the left and right segments. The search
vector itself must point to keys in the correct order, supporting binary search. The
search vector is also required to be aligned to an even address, contain fixed size
entries, and it never has holes. Adding or removing entries from the search vector
requires entries to be shifted. The shift operation can be performed from either
side, but the smaller shift is always chosen as a performance optimization.
Garbage refers to the amount of unused bytes within the left and right allocation
segments. Garbage accumulates when entries are deleted and updated from the
segments. Segments are not immediately shifted because the search vector would also
need to be repaired. A compaction operation reclaims garbage by rebuilding the
segments and search vector. A copying garbage collection algorithm is used for this.
The compaction implementation allocates all surviving entries in the left segment,
leaving an empty right segment. There is no requirement that the segments be
balanced -- this only applies to the free space surrounding the search vector.
Leaf nodes support variable length keys and values, encoded as a pair, within the
segments. Entries in the search vector are ushort pointers into the segments. No
distinction is made between the segments because the pointers are absolute.
Entries start with a one byte key header:
0b0xxx_xxxx: key is 1..128 bytes
0b1fxx_xxxx: key is 0..16383 bytes
For keys 1..128 bytes in length, the length is defined as (header + 1). For
keys 0..16383 bytes in length, a second header byte is used. The second byte is
unsigned, and the length is defined as (((header & 0x3f) << 8) | header2). The key
contents immediately follow the header byte(s).
When the 'f' bit is zero, the entry is a normal key. Very large keys are stored in a
fragmented fashion, which is also used by large values. The encoding format is defined by
Database.fragment.
The value follows the key, and its header encodes the entry length:
0b0xxx_xxxx: value is 0..127 bytes
0b1f0x_xxxx: value/entry is 1..8192 bytes
0b1f10_xxxx: value/entry is 1..1048576 bytes
0b1111_1111: ghost value (null)
When the 'f' bit is zero, the entry is a normal value. Otherwise, it is a
fragmented value, defined by Database.fragment.
For entries 1..8192 bytes in length, a second header byte is used. The
length is then defined as ((((h0 & 0x1f) << 8) | h1) + 1). For larger
entries, the length is ((((h0 & 0x0f) << 16) | (h1 << 8) | h2) + 1).
Node limit is currently 65536 bytes, which limits maximum entry length.
The "values" for internal nodes are actually identifiers for child nodes. The number
of child nodes is always one more than the number of keys. For this reason, the
key-value format used by leaf nodes cannot be applied to internal nodes. Also, the
identifiers are always a fixed length, ulong type.
Child node identifiers are encoded immediately following the search vector. Free space
management must account for this, treating it as an extension to the search vector.
Each entry in the child node id segment contains 6 byte child node id, followed by
2 byte count of keys in the child node. The child node ids are in the same order as
keys in the search vector.
+----------------------------------------+
| byte: node type | header
| byte: reserved (must be 0) |
| ushort: garbage in segments |
| ushort: pointer to left segment tail |
| ushort: pointer to right segment tail |
| ushort: pointer to search vector start |
| ushort: pointer to search vector end |
+----------------------------------------+
| left key segment |
- -
| |
+----------------------------------------+
| free space | <-- left segment tail (exclusive)
- -
| |
+----------------------------------------+
| search vector | <-- search vector start (inclusive)
- -
| | <-- search vector end (inclusive)
+----------------------------------------+
| child node id segment |
- -
| |
+----------------------------------------+
| free space |
- -
| | <-- right segment tail (exclusive)
+----------------------------------------+
| right key segment |
- -
| |
+----------------------------------------+
*/
// Raw contents of node.
/*P*/ byte[] mPage;
// Id is often read without acquiring latch, although in most cases, it
// doesn't need to be volatile. This is because a double check with the
// latch held is always performed. So-called double-checked locking doesn't
// work with object initialization, but it's fine with primitive types.
// When nodes are evicted, the write operation must complete before the id
// is re-assigned. For this reason, the id is volatile. A memory barrier
// between the write and re-assignment should work too.
volatile long mId;
byte mCachedState;
/*P*/ // [
// Entries from header, available as fields for quick access.
private byte mType;
private int mGarbage;
private int mLeftSegTail;
private int mRightSegTail;
private int mSearchVecStart;
private int mSearchVecEnd;
/*P*/ // ]
// Next in NodeMap collision chain.
Node mNodeMapNext;
// Linked stack of TreeCursorFrames bound to this Node.
transient volatile TreeCursorFrame mLastCursorFrame;
// Set by a partially completed split.
transient Split mSplit;
Node(NodeUsageList usageList, /*P*/ byte[] page) {
mUsageList = usageList;
mPage = page;
}
// Construct a "lock" object for use when loading a node. See loadChild method.
private Node(long id) {
mUsageList = null;
initExclusive();
mId = id;
}
/**
* Must be called when object is no longer referenced.
*/
void delete(LocalDatabase db) {
acquireExclusive();
try {
doDelete(db);
} finally {
releaseExclusive();
}
}
/**
* Must be called when object is no longer referenced. Caller must acquire exclusive latch.
*/
void doDelete(LocalDatabase db) {
/*P*/ // [|
/*P*/ // if (db.mFullyMapped) {
/*P*/ // // Cannot delete mapped pages.
/*P*/ // closeRoot();
/*P*/ // return;
/*P*/ // }
/*P*/ // ]
/*P*/ byte[] page = mPage;
if (page != p_closedTreePage()) {
p_delete(page);
closeRoot();
}
}
@Override
public LocalDatabase getDatabase() {
return mUsageList.mDatabase;
}
void asEmptyRoot() {
mId = 0;
mCachedState = CACHED_CLEAN;
type((byte) (TYPE_TN_LEAF | LOW_EXTREMITY | HIGH_EXTREMITY));
clearEntries();
}
void asTrimmedRoot() {
type((byte) (TYPE_TN_LEAF | LOW_EXTREMITY | HIGH_EXTREMITY));
clearEntries();
}
/**
* Close the root node when closing a tree.
*/
void closeRoot() {
// Prevent node from being marked dirty.
mId = STUB_ID;
mCachedState = CACHED_CLEAN;
mPage = p_closedTreePage();
readFields();
}
Node cloneNode() {
Node newNode = new Node(mUsageList, mPage);
newNode.mId = mId;
newNode.mCachedState = mCachedState;
/*P*/ // [
newNode.type(type());
newNode.garbage(garbage());
newNode.leftSegTail(leftSegTail());
newNode.rightSegTail(rightSegTail());
newNode.searchVecStart(searchVecStart());
newNode.searchVecEnd(searchVecEnd());
/*P*/ // ]
return newNode;
}
private void clearEntries() {
garbage(0);
leftSegTail(TN_HEADER_SIZE);
int pageSize = pageSize(mPage);
rightSegTail(pageSize - 1);
// Search vector location must be even.
searchVecStart((TN_HEADER_SIZE + ((pageSize - TN_HEADER_SIZE) >> 1)) & ~1);
searchVecEnd(searchVecStart() - 2); // inclusive
}
/**
* Indicate that a non-root node is most recently used. Root node is not managed in usage
* list and cannot be evicted. Caller must hold any latch on node. Latch is never released
* by this method, even if an exception is thrown.
*/
void used() {
mUsageList.used(this);
}
/**
* Indicate that node is least recently used, allowing it to be recycled immediately
* without evicting another node. Node must be latched by caller, which is always released
* by this method.
*/
void unused() {
mUsageList.unused(this);
}
/**
* Allow a Node which was allocated as unevictable to be evictable, starting off as the
* most recently used.
*/
void makeEvictable() {
mUsageList.makeEvictable(this);
}
/**
* Allow a Node which was allocated as unevictable to be evictable, as the least recently
* used.
*/
void makeEvictableNow() {
mUsageList.makeEvictableNow(this);
}
/**
* Allow a Node which was allocated as evictable to be unevictable.
*/
void makeUnevictable() {
mUsageList.makeUnevictable(this);
}
/**
* Search for a value, starting from the root node.
*
* @param node root node
* @param key search key
* @return copy of value or null if not found
*/
static byte[] search(Node node, Tree tree, byte[] key) throws IOException {
node.acquireShared();
// Note: No need to check if root has split, since root splits are always completed
// before releasing the root latch. Also, Node.used is not invoked for the root node,
// because it cannot be evicted.
while (!node.isLeaf()) {
int childPos;
try {
childPos = internalPos(node.binarySearch(key));
} catch (Throwable e) {
node.releaseShared();
throw e;
}
long childId = node.retrieveChildRefId(childPos);
Node childNode = tree.mDatabase.nodeMapGet(childId);
if (childNode != null) {
childNode.acquireShared();
// Need to check again in case evict snuck in.
if (childId == childNode.mId) {
node.releaseShared();
node = childNode;
if (node.mSplit != null) {
node = node.mSplit.selectNode(node, key);
}
node.used();
continue;
}
childNode.releaseShared();
}
node = node.loadChild(tree.mDatabase, childId, OPTION_PARENT_RELEASE_SHARED);
}
// Sub search into leaf with shared latch held.
// Same code as binarySearch, but instead of returning the position, it directly copies
// the value if found. This avoids having to decode the found value location twice.
try {
final /*P*/ byte[] page = node.mPage;
final int keyLen = key.length;
int lowPos = node.searchVecStart();
int highPos = node.searchVecEnd();
int lowMatch = 0;
int highMatch = 0;
outer: while (lowPos <= highPos) {
int midPos = ((lowPos + highPos) >> 1) & ~1;
int compareLoc, compareLen, i;
compare: {
compareLoc = p_ushortGetLE(page, midPos);
compareLen = p_byteGet(page, compareLoc++);
if (compareLen >= 0) {
compareLen++;
} else {
int header = compareLen;
compareLen = ((compareLen & 0x3f) << 8) | p_ubyteGet(page, compareLoc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] compareKey = tree.mDatabase.reconstructKey
(page, compareLoc, compareLen);
int fullCompareLen = compareKey.length;
int minLen = Math.min(fullCompareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = compareKey[i];
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
continue outer;
}
}
// Update compareLen and compareLoc for use by the code after the
// current scope. The compareLoc is completely bogus at this point,
// but is corrected when the value is retrieved below.
compareLoc += compareLen - fullCompareLen;
compareLen = fullCompareLen;
break compare;
}
}
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = p_byteGet(page, compareLoc + i);
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
continue outer;
}
}
}
if (compareLen < keyLen) {
lowPos = midPos + 2;
lowMatch = i;
} else if (compareLen > keyLen) {
highPos = midPos - 2;
highMatch = i;
} else {
return retrieveLeafValueAtLoc(node, page, compareLoc + compareLen);
}
}
return null;
} finally {
node.releaseShared();
}
}
/**
* Options for loadChild. Caller must latch parentas shared or exclusive, which can be
* retained (default) or released. Child node is latched shared (default) or exclusive.
*/
static final int
OPTION_PARENT_RELEASE_SHARED = 0b001,
OPTION_PARENT_RELEASE_EXCLUSIVE = 0b010,
OPTION_CHILD_ACQUIRE_EXCLUSIVE = 0b100;
/**
* With this parent node latched shared or exclusive, loads child with shared or exclusive
* latch. Caller must ensure that child is not already loaded. If an exception is thrown,
* parent and child latches are always released.
*
* @param options descibed described by OPTION_* fields
*/
Node loadChild(LocalDatabase db, long childId, int options) throws IOException {
// Insert a "lock", which is a temporary node latched exclusively. All other threads
// attempting to load the child node will block trying to acquire the exclusive latch.
Node lock = new Node(childId);
try {
while (true) {
Node childNode = db.nodeMapPutIfAbsent(lock);
if (childNode == null) {
break;
}
// Was already loaded, or is currently being loaded.
if ((options & OPTION_CHILD_ACQUIRE_EXCLUSIVE) == 0) {
childNode.acquireShared();
if (childId == childNode.mId) {
return childNode;
}
childNode.releaseShared();
} else {
childNode.acquireExclusive();
if (childId == childNode.mId) {
return childNode;
}
childNode.releaseExclusive();
}
}
} finally {
// Release parent latch before child has been loaded. Any threads which wish to
// access the same child will block until this thread has finished loading the
// child and released its exclusive latch.
if ((options & OPTION_PARENT_RELEASE_SHARED) != 0) {
releaseShared();
} else if ((options & OPTION_PARENT_RELEASE_EXCLUSIVE) != 0) {
releaseExclusive();
}
}
try {
Node childNode;
try {
childNode = db.allocLatchedNode(childId);
childNode.mId = childId;
} catch (Throwable e) {
db.nodeMapRemove(lock);
throw e;
}
// Replace the lock with the real child node, but don't notify any threads waiting
// on the lock just yet. They'd go back to sleep waiting for the read to finish.
db.nodeMapReplace(lock, childNode);
try {
childNode.read(db, childId);
} catch (Throwable e) {
// Another thread might access child and see that it's invalid because the id
// is zero. It will assume it got evicted and will attempt to reload it
db.nodeMapRemove(childNode);
childNode.mId = 0;
childNode.type(TYPE_NONE);
childNode.releaseExclusive();
throw e;
}
if ((options & OPTION_CHILD_ACQUIRE_EXCLUSIVE) == 0){
childNode.downgrade();
}
return childNode;
} catch (Throwable e) {
if ((options & (OPTION_PARENT_RELEASE_SHARED | OPTION_PARENT_RELEASE_EXCLUSIVE)) == 0){
// Obey the method contract and release parent latch due to exception.
releaseEither();
}
throw e;
} finally {
// Wake any threads waiting on the lock now that the real child node is ready, or
// if the load failed. Lock id must be set to zero to ensure that it's not accepted
// as the child node.
lock.mId = 0;
lock.releaseExclusive();
}
}
/**
* With this parent node held exclusively, attempts to return child with exclusive latch
* held. If an exception is thrown, parent and child latches are always released. This
* method is intended to be called for rebalance operations.
*
* @return null or child node, never split
*/
private Node tryLatchChildNotSplit(int childPos) throws IOException {
final long childId = retrieveChildRefId(childPos);
final LocalDatabase db = getDatabase();
Node childNode = db.nodeMapGet(childId);
if (childNode != null) {
if (!childNode.tryAcquireExclusive()) {
return null;
}
// Need to check again in case evict snuck in.
if (childId != childNode.mId) {
childNode.releaseExclusive();
} else if (childNode.mSplit == null) {
// Return without updating LRU position. Node contents were not user requested.
return childNode;
} else {
childNode.releaseExclusive();
return null;
}
}
return loadChild(db, childId, OPTION_CHILD_ACQUIRE_EXCLUSIVE);
}
/**
* Caller must hold exclusive root latch and it must verify that root has split. Caller
* must also exclusively hold stub latch, if applicable. This required for safely unbinding
* parent cursor frames which refer to the old root node.
*/
void finishSplitRoot() throws IOException {
// Create a child node and copy this root node state into it. Then update this
// root node to point to new and split child nodes. New root is always an internal node.
LocalDatabase db = mUsageList.mDatabase;
Node child = db.allocDirtyNode();
db.nodeMapPut(child);
/*P*/ byte[] newRootPage;
/*P*/ // [
newRootPage = child.mPage;
child.mPage = mPage;
child.type(type());
child.garbage(garbage());
child.leftSegTail(leftSegTail());
child.rightSegTail(rightSegTail());
child.searchVecStart(searchVecStart());
child.searchVecEnd(searchVecEnd());
/*P*/ // |
/*P*/ // if (db.mFullyMapped) {
/*P*/ // // Page cannot change, so copy it instead.
/*P*/ // newRootPage = mPage;
/*P*/ // p_copy(newRootPage, 0, child.mPage, 0, db.pageSize());
/*P*/ // } else {
/*P*/ // newRootPage = child.mPage;
/*P*/ // child.mPage = mPage;
/*P*/ // }
/*P*/ // ]
final Split split = mSplit;
final Node sibling = rebindSplitFrames(split);
mSplit = null;
// Fix child node cursor frame bindings.
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
frame.rebind(child, frame.mNodePos);
frame = prev;
}
Node left, right;
if (split.mSplitRight) {
left = child;
right = sibling;
} else {
left = sibling;
right = child;
}
int leftSegTail = split.copySplitKeyToParent(newRootPage, TN_HEADER_SIZE);
// Create new single-element search vector. Center it using the same formula as the
// compactInternal method.
final int searchVecStart = pageSize(newRootPage) -
(((pageSize(newRootPage) - leftSegTail + (2 + 8 + 8)) >> 1) & ~1);
p_shortPutLE(newRootPage, searchVecStart, TN_HEADER_SIZE);
p_longPutLE(newRootPage, searchVecStart + 2, left.mId);
p_longPutLE(newRootPage, searchVecStart + 2 + 8, right.mId);
byte newType = isLeaf() ? (byte) (TYPE_TN_BIN | LOW_EXTREMITY | HIGH_EXTREMITY)
: (byte) (TYPE_TN_IN | LOW_EXTREMITY | HIGH_EXTREMITY);
mPage = newRootPage;
/*P*/ // [
type(newType);
garbage(0);
/*P*/ // |
/*P*/ // p_intPutLE(newRootPage, 0, newType & 0xff); // type, reserved byte, and garbage
/*P*/ // ]
leftSegTail(leftSegTail);
rightSegTail(pageSize(newRootPage) - 1);
searchVecStart(searchVecStart);
searchVecEnd(searchVecStart);
// Add a parent cursor frame for all left and right node cursors.
TreeCursorFrame lock = new TreeCursorFrame();
addParentFrames(lock, left, 0);
addParentFrames(lock, right, 2);
child.releaseExclusive();
sibling.releaseExclusive();
// Split complete, so allow new node to be evictable.
sibling.makeEvictable();
}
private void addParentFrames(TreeCursorFrame lock, Node child, int pos) {
for (TreeCursorFrame frame = child.mLastCursorFrame; frame != null; ) {
TreeCursorFrame lockResult = frame.tryLock(lock);
if (lockResult != null) {
try {
TreeCursorFrame parentFrame = frame.mParentFrame;
if (parentFrame == null) {
parentFrame = new TreeCursorFrame();
parentFrame.bind(this, pos);
frame.mParentFrame = parentFrame;
} else {
parentFrame.rebind(this, pos);
}
} finally {
frame.unlock(lockResult);
}
}
frame = frame.mPrevCousin;
}
}
/**
* Caller must hold exclusive latch. Latch is never released by this method, even if
* an exception is thrown.
*/
void read(LocalDatabase db, long id) throws IOException {
db.readNode(this, id);
try {
readFields();
} catch (IllegalStateException e) {
throw new CorruptDatabaseException(e.getMessage());
}
}
private void readFields() throws IllegalStateException {
/*P*/ byte[] page = mPage;
byte type = p_byteGet(page, 0);
/*P*/ // [
type(type);
// For undo log node, this is top entry pointer.
garbage(p_ushortGetLE(page, 2));
/*P*/ // ]
if (type != TYPE_UNDO_LOG) {
/*P*/ // [
leftSegTail(p_ushortGetLE(page, 4));
rightSegTail(p_ushortGetLE(page, 6));
searchVecStart(p_ushortGetLE(page, 8));
searchVecEnd(p_ushortGetLE(page, 10));
/*P*/ // ]
type &= ~(LOW_EXTREMITY | HIGH_EXTREMITY);
if (type >= 0 && type != TYPE_TN_IN && type != TYPE_TN_BIN) {
throw new IllegalStateException("Unknown node type: " + type + ", id: " + mId);
}
}
if (p_byteGet(page, 1) != 0) {
throw new IllegalStateException
("Illegal reserved byte in node: " + p_byteGet(page, 1));
}
}
/**
* Caller must hold any latch, which is not released, even if an exception is thrown.
*/
void write(PageDb db) throws WriteFailureException {
/*P*/ byte[] page = prepareWrite();
try {
db.writePage(mId, page);
} catch (IOException e) {
throw new WriteFailureException(e);
}
}
private /*P*/ byte[] prepareWrite() {
if (mSplit != null) {
throw new AssertionError("Cannot write partially split node");
}
/*P*/ byte[] page = mPage;
/*P*/ // [
if (type() != TYPE_FRAGMENT) {
p_bytePut(page, 0, type());
p_bytePut(page, 1, 0); // reserved
// For undo log node, this is top entry pointer.
p_shortPutLE(page, 2, garbage());
if (type() != TYPE_UNDO_LOG) {
p_shortPutLE(page, 4, leftSegTail());
p_shortPutLE(page, 6, rightSegTail());
p_shortPutLE(page, 8, searchVecStart());
p_shortPutLE(page, 10, searchVecEnd());
}
}
/*P*/ // ]
return page;
}
/**
* Caller must hold exclusive latch on node. Latch is released by this
* method when false is returned or if an exception is thrown.
*
* @return false if cannot evict
*/
boolean evict(LocalDatabase db) throws IOException {
if (mLastCursorFrame != null || mSplit != null) {
// Cannot evict if in use by a cursor or if splitting. The split
// check is redundant, since a node cannot be in a split state
// without a cursor registered against it.
releaseExclusive();
return false;
}
try {
// Check if <= 0 (already evicted) or stub.
long id = mId;
if (id > STUB_ID) {
PageDb pageDb = db.mPageDb;
if (mCachedState == CACHED_CLEAN) {
// Try to move to a secondary cache.
pageDb.cachePage(id, mPage);
} else {
/*P*/ byte[] page = prepareWrite();
/*P*/ byte[] newPage = pageDb.evictPage(id, page);
if (newPage != page) {
mPage = newPage;
}
mCachedState = CACHED_CLEAN;
}
db.nodeMapRemove(this, Long.hashCode(id));
mId = 0;
// Note: Don't do this. In the fully mapped mode (using MappedPageArray),
// setting the type will corrupt the evicted node. The caller swaps in a
// different page, which is where the type should be written to.
//type(TYPE_NONE);
}
return true;
} catch (Throwable e) {
releaseExclusive();
throw e;
}
}
/**
* Invalidate all cursors, starting from the root. Used when closing an index which still
* has active cursors. Caller must hold exclusive latch on node.
*/
void invalidateCursors() {
invalidateCursors(createClosedNode());
}
private void invalidateCursors(Node closed) {
int pos = isLeaf() ? -1 : 0;
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
frame.mNode = closed;
frame.mNodePos = pos;
frame = frame.unlink();
}
if (!isInternal()) {
return;
}
LocalDatabase db = mUsageList.mDatabase;
closed = null;
int childPtr = searchVecEnd() + 2;
final int highestPtr = childPtr + (highestInternalPos() << 2);
for (; childPtr <= highestPtr; childPtr += 8) {
long childId = p_uint48GetLE(mPage, childPtr);
Node child = db.nodeMapGet(childId);
if (child != null) {
child.acquireExclusive();
if (childId == child.mId) {
if (closed == null) {
closed = createClosedNode();
}
child.invalidateCursors(closed);
}
child.releaseExclusive();
}
}
}
private static Node createClosedNode() {
Node closed = new Node(null, p_closedTreePage());
closed.mId = STUB_ID;
closed.mCachedState = CACHED_CLEAN;
closed.readFields();
return closed;
}
private int pageSize(/*P*/ byte[] page) {
/*P*/ // [
return page.length;
/*P*/ // |
/*P*/ // return mUsageList.pageSize();
/*P*/ // ]
}
/**
* Get the node type.
*/
byte type() {
/*P*/ // [
return mType;
/*P*/ // |
/*P*/ // return p_byteGet(mPage, 0);
/*P*/ // ]
}
/**
* Set the node type.
*/
void type(byte type) {
/*P*/ // [
mType = type;
/*P*/ // |
/*P*/ // p_bytePut(mPage, 0, type);
/*P*/ // ]
}
/**
* Get the node garbage size.
*/
int garbage() {
/*P*/ // [
return mGarbage;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 2);
/*P*/ // ]
}
/**
* Set the node garbage size.
*/
void garbage(int garbage) {
/*P*/ // [
mGarbage = garbage;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 2, garbage);
/*P*/ // ]
}
/**
* Get the undo log node top entry pointer. (same field as garbage)
*/
int undoTop() {
/*P*/ // [
return mGarbage;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 2);
/*P*/ // ]
}
/**
* Set the undo log node top entry pointer. (same field as garbage)
*/
void undoTop(int top) {
/*P*/ // [
mGarbage = top;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 2, top);
/*P*/ // ]
}
/**
* Get the left segment tail pointer.
*/
private int leftSegTail() {
/*P*/ // [
return mLeftSegTail;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 4);
/*P*/ // ]
}
/**
* Set the left segment tail pointer.
*/
private void leftSegTail(int tail) {
/*P*/ // [
mLeftSegTail = tail;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 4, tail);
/*P*/ // ]
}
/**
* Get the right segment tail pointer.
*/
private int rightSegTail() {
/*P*/ // [
return mRightSegTail;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 6);
/*P*/ // ]
}
/**
* Set the right segment tail pointer.
*/
private void rightSegTail(int tail) {
/*P*/ // [
mRightSegTail = tail;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 6, tail);
/*P*/ // ]
}
/**
* Get the search vector start pointer.
*/
int searchVecStart() {
/*P*/ // [
return mSearchVecStart;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 8);
/*P*/ // ]
}
/**
* Set the search vector start pointer.
*/
private void searchVecStart(int start) {
/*P*/ // [
mSearchVecStart = start;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 8, start);
/*P*/ // ]
}
/**
* Get the search vector end pointer.
*/
private int searchVecEnd() {
/*P*/ // [
return mSearchVecEnd;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 10);
/*P*/ // ]
}
/**
* Set the search vector end pointer.
*/
private void searchVecEnd(int end) {
/*P*/ // [
mSearchVecEnd = end;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 10, end);
/*P*/ // ]
}
/**
* Caller must hold any latch.
*/
boolean isLeaf() {
return type() < 0;
}
/**
* Caller must hold any latch. Returns true if node is any kind of internal node.
*/
boolean isInternal() {
return (type() & 0xe0) == 0x60;
}
/**
* Caller must hold any latch.
*/
boolean isBottomInternal() {
return (type() & 0xf0) == 0x70;
}
/**
* Caller must hold any latch.
*/
boolean isNonBottomInternal() {
return (type() & 0xf0) == 0x60;
}
/**
* Caller must hold any latch.
*
* @see #countNonGhostKeys
*/
int numKeys() {
return (searchVecEnd() - searchVecStart() + 2) >> 1;
}
/**
* Caller must hold any latch.
*/
boolean hasKeys() {
return searchVecEnd() >= searchVecStart();
}
/**
* Returns the highest possible key position, which is an even number. If
* node has no keys, return value is negative. Caller must hold any latch.
*/
int highestKeyPos() {
return searchVecEnd() - searchVecStart();
}
/**
* Returns highest leaf or internal position. Caller must hold any latch.
*/
int highestPos() {
int pos = searchVecEnd() - searchVecStart();
if (!isLeaf()) {
pos += 2;
}
return pos;
}
/**
* Returns the highest possible leaf key position, which is an even
* number. If leaf node is empty, return value is negative. Caller must
* hold any latch.
*/
int highestLeafPos() {
return searchVecEnd() - searchVecStart();
}
/**
* Returns the highest possible internal node position, which is an even
* number. Highest position doesn't correspond to a valid key, but instead
* a child node position. If internal node has no keys, node has one child
* at position zero. Caller must hold any latch.
*/
int highestInternalPos() {
return searchVecEnd() - searchVecStart() + 2;
}
/**
* Caller must hold any latch.
*/
int availableBytes() {
return isLeaf() ? availableLeafBytes() : availableInternalBytes();
}
/**
* Caller must hold any latch.
*/
int availableLeafBytes() {
return garbage() + searchVecStart() - searchVecEnd()
- leftSegTail() + rightSegTail() + (1 - 2);
}
/**
* Caller must hold any latch.
*/
int availableInternalBytes() {
return garbage() + 5 * (searchVecStart() - searchVecEnd())
- leftSegTail() + rightSegTail() + (1 - (5 * 2 + 8));
}
/**
* Applicable only to leaf nodes. Caller must hold any latch.
*/
int countNonGhostKeys() {
final /*P*/ byte[] page = mPage;
int count = 0;
for (int i = searchVecStart(); i <= searchVecEnd(); i += 2) {
int loc = p_ushortGetLE(page, i);
if (p_byteGet(page, loc + keyLengthAtLoc(page, loc)) != -1) {
count++;
}
}
return count;
}
/**
* Returns true if leaf is not split and underutilized. If so, it should be
* merged with its neighbors, and possibly deleted. Caller must hold any latch.
*/
boolean shouldLeafMerge() {
return shouldMerge(availableLeafBytes());
}
/**
* Returns true if non-leaf is not split and underutilized. If so, it should be
* merged with its neighbors, and possibly deleted. Caller must hold any latch.
*/
boolean shouldInternalMerge() {
return shouldMerge(availableInternalBytes());
}
boolean shouldMerge(int availBytes) {
return mSplit == null
& (((type() & (LOW_EXTREMITY | HIGH_EXTREMITY)) == 0
& availBytes >= ((pageSize(mPage) - TN_HEADER_SIZE) >> 1))
| !hasKeys());
}
/**
* @return 2-based insertion pos, which is negative if key not found
*/
int binarySearch(byte[] key) throws IOException {
final /*P*/ byte[] page = mPage;
final int keyLen = key.length;
int lowPos = searchVecStart();
int highPos = searchVecEnd();
int lowMatch = 0;
int highMatch = 0;
outer: while (lowPos <= highPos) {
int midPos = ((lowPos + highPos) >> 1) & ~1;
int compareLen, i;
compare: {
int compareLoc = p_ushortGetLE(page, midPos);
compareLen = p_byteGet(page, compareLoc++);
if (compareLen >= 0) {
compareLen++;
} else {
int header = compareLen;
compareLen = ((compareLen & 0x3f) << 8) | p_ubyteGet(page, compareLoc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] compareKey = getDatabase()
.reconstructKey(page, compareLoc, compareLen);
compareLen = compareKey.length;
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = compareKey[i];
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
continue outer;
}
}
break compare;
}
}
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = p_byteGet(page, compareLoc + i);
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
continue outer;
}
}
}
if (compareLen < keyLen) {
lowPos = midPos + 2;
lowMatch = i;
} else if (compareLen > keyLen) {
highPos = midPos - 2;
highMatch = i;
} else {
return midPos - searchVecStart();
}
}
return ~(lowPos - searchVecStart());
}
/**
* @param midPos 2-based starting position
* @return 2-based insertion pos, which is negative if key not found
*/
int binarySearch(byte[] key, int midPos) throws IOException {
int lowPos = searchVecStart();
int highPos = searchVecEnd();
if (lowPos > highPos) {
return -1;
}
midPos += lowPos;
if (midPos > highPos) {
midPos = highPos;
}
final /*P*/ byte[] page = mPage;
final int keyLen = key.length;
int lowMatch = 0;
int highMatch = 0;
while (true) {
compare: {
int compareLen, i;
c2: {
int compareLoc = p_ushortGetLE(page, midPos);
compareLen = p_byteGet(page, compareLoc++);
if (compareLen >= 0) {
compareLen++;
} else {
int header = compareLen;
compareLen = ((compareLen & 0x3f) << 8) | p_ubyteGet(page, compareLoc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] compareKey = getDatabase()
.reconstructKey(page, compareLoc, compareLen);
compareLen = compareKey.length;
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = compareKey[i];
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
break compare;
}
}
break c2;
}
}
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = p_byteGet(page, compareLoc + i);
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
break compare;
}
}
}
if (compareLen < keyLen) {
lowPos = midPos + 2;
lowMatch = i;
} else if (compareLen > keyLen) {
highPos = midPos - 2;
highMatch = i;
} else {
return midPos - searchVecStart();
}
}
if (lowPos > highPos) {
break;
}
midPos = ((lowPos + highPos) >> 1) & ~1;
}
return ~(lowPos - searchVecStart());
}
/**
* Ensure binary search position is positive, for internal node.
*/
static int internalPos(int pos) {
return pos < 0 ? ~pos : (pos + 2);
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
int compareKey(int pos, byte[] rightKey) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] leftKey = getDatabase().reconstructKey(page, loc, keyLen);
return compareUnsigned(leftKey, 0, leftKey.length, rightKey, 0, rightKey.length);
}
}
return p_compareKeysPageToArray(page, loc, keyLen, rightKey, 0, rightKey.length);
}
/**
* @param pos position as provided by binarySearch; must be positive
* @param stats [0]: full length, [1]: number of pages (>0 if fragmented)
*/
void retrieveKeyStats(int pos, long[] stats) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
getDatabase().reconstruct(page, loc, keyLen, stats);
return;
}
}
stats[0] = keyLen;
stats[1] = 0;
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
byte[] retrieveKey(int pos) throws IOException {
final /*P*/ byte[] page = mPage;
return retrieveKeyAtLoc(this, page, p_ushortGetLE(page, searchVecStart() + pos));
}
/**
* @param loc absolute location of entry
*/
byte[] retrieveKeyAtLoc(final /*P*/ byte[] page, int loc) throws IOException {
return retrieveKeyAtLoc(this, page, loc);
}
/**
* @param loc absolute location of entry
*/
static byte[] retrieveKeyAtLoc(DatabaseAccess dbAccess, final /*P*/ byte[] page, int loc)
throws IOException
{
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
return dbAccess.getDatabase().reconstructKey(page, loc, keyLen);
}
}
byte[] key = new byte[keyLen];
p_copyToArray(page, loc, key, 0, keyLen);
return key;
}
/**
* @param loc absolute location of entry
* @param akeyRef [0] is set to the actual key
* @return false if key is fragmented and actual doesn't match original
*/
private boolean retrieveActualKeyAtLoc(final /*P*/ byte[] page, int loc,
final byte[][] akeyRef)
throws IOException
{
boolean result = true;
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
result = (header & ENTRY_FRAGMENTED) == 0;
}
byte[] akey = new byte[keyLen];
p_copyToArray(page, loc, akey, 0, keyLen);
akeyRef[0] = akey;
return result;
}
/**
* Copies the key at the given position based on a limit. If equal, the
* limitKey instance is returned. If beyond the limit, null is returned.
*
* @param pos position as provided by binarySearch; must be positive
* @param limitKey comparison key
* @param limitMode positive for LE behavior, negative for GE behavior
*/
byte[] retrieveKeyCmp(int pos, byte[] limitKey, int limitMode) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
byte[] key = getDatabase().reconstructKey(page, loc, keyLen);
int cmp = compareUnsigned(key, limitKey);
if (cmp == 0) {
return limitKey;
} else {
return (cmp ^ limitMode) < 0 ? key : null;
}
}
}
int cmp = p_compareKeysPageToArray(page, loc, keyLen, limitKey, 0, limitKey.length);
if (cmp == 0) {
return limitKey;
} else if ((cmp ^ limitMode) < 0) {
byte[] key = new byte[keyLen];
p_copyToArray(page, loc, key, 0, keyLen);
return key;
} else {
return null;
}
}
/**
* Used by UndoLog for decoding entries. Only works for non-fragmented values.
*
* @param loc absolute location of entry
*/
static byte[][] retrieveKeyValueAtLoc(DatabaseAccess dbAccess,
final /*P*/ byte[] page, int loc)
throws IOException
{
int header = p_byteGet(page, loc++);
int keyLen;
byte[] key;
copyKey: {
if (header >= 0) {
keyLen = header + 1;
} else {
keyLen = ((header & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
key = dbAccess.getDatabase().reconstructKey(page, loc, keyLen);
break copyKey;
}
}
key = new byte[keyLen];
p_copyToArray(page, loc, key, 0, keyLen);
}
return new byte[][] {key, retrieveLeafValueAtLoc(null, page, loc + keyLen)};
}
/**
* Returns a new key between the low key in this node and the given high key.
*
* @see Utils#midKey
*/
private byte[] midKey(int lowPos, byte[] highKey) throws IOException {
final /*P*/ byte[] lowPage = mPage;
int lowLoc = p_ushortGetLE(lowPage, searchVecStart() + lowPos);
int lowKeyLen = p_byteGet(lowPage, lowLoc);
if (lowKeyLen < 0) {
// Note: An optimized version wouldn't need to copy the whole key.
return Utils.midKey(retrieveKeyAtLoc(lowPage, lowLoc), highKey);
} else {
return p_midKeyLowPage(lowPage, lowLoc + 1, lowKeyLen + 1, highKey, 0, highKey.length);
}
}
/**
* Returns a new key between the given low key and the high key in this node.
*
* @see Utils#midKey
*/
private byte[] midKey(byte[] lowKey, int highPos) throws IOException {
final /*P*/ byte[] highPage = mPage;
int highLoc = p_ushortGetLE(highPage, searchVecStart() + highPos);
int highKeyLen = p_byteGet(highPage, highLoc);
if (highKeyLen < 0) {
// Note: An optimized version wouldn't need to copy the whole key.
return Utils.midKey(lowKey, retrieveKeyAtLoc(highPage, highLoc));
} else {
return p_midKeyHighPage(lowKey, 0, lowKey.length,
highPage, highLoc + 1, highKeyLen + 1);
}
}
/**
* Returns a new key between the low key in this node and the high key of another node.
*
* @see Utils#midKey
*/
byte[] midKey(int lowPos, Node highNode, int highPos) throws IOException {
final /*P*/ byte[] lowPage = mPage;
int lowLoc = p_ushortGetLE(lowPage, searchVecStart() + lowPos);
int lowKeyLen = p_byteGet(lowPage, lowLoc);
if (lowKeyLen < 0) {
// Note: An optimized version wouldn't need to copy the whole key.
return highNode.midKey(retrieveKeyAtLoc(lowPage, lowLoc), highPos);
}
lowLoc++;
lowKeyLen++;
final /*P*/ byte[] highPage = highNode.mPage;
int highLoc = p_ushortGetLE(highPage, highNode.searchVecStart() + highPos);
int highKeyLen = p_byteGet(highPage, highLoc);
if (highKeyLen < 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] highKey = retrieveKeyAtLoc(highPage, highLoc);
return p_midKeyLowPage(lowPage, lowLoc, lowKeyLen, highKey, 0, highKey.length);
}
return p_midKeyLowHighPage(lowPage, lowLoc, lowKeyLen,
highPage, highLoc + 1, highKeyLen + 1);
}
/**
* @param pos position as provided by binarySearch; must be positive
* @return Cursor.NOT_LOADED if value exists, null if ghost
*/
byte[] hasLeafValue(int pos) {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
loc += keyLengthAtLoc(page, loc);
return p_byteGet(page, loc) == -1 ? null : Cursor.NOT_LOADED;
}
/**
* @param pos position as provided by binarySearch; must be positive
* @param stats [0]: full length, [1]: number of pages (>0 if fragmented)
*/
void retrieveLeafValueStats(int pos, long[] stats) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
loc += keyLengthAtLoc(page, loc);
final int header = p_byteGet(page, loc++);
int len;
if (header >= 0) {
len = header;
} else {
if ((header & 0x20) == 0) {
len = 1 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (header != -1) {
len = 1 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
stats[0] = 0;
stats[1] = 0;
return;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
getDatabase().reconstruct(page, loc, len, stats);
return;
}
}
stats[0] = len;
stats[1] = 0;
}
/**
* @param pos position as provided by binarySearch; must be positive
* @return null if ghost
*/
byte[] retrieveLeafValue(int pos) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
loc += keyLengthAtLoc(page, loc);
return retrieveLeafValueAtLoc(this, page, loc);
}
private static byte[] retrieveLeafValueAtLoc(DatabaseAccess dbAccess,
/*P*/ byte[] page, int loc)
throws IOException
{
final int header = p_byteGet(page, loc++);
if (header == 0) {
return EMPTY_BYTES;
}
int len;
if (header >= 0) {
len = header;
} else {
if ((header & 0x20) == 0) {
len = 1 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (header != -1) {
len = 1 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
return null;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
return dbAccess.getDatabase().reconstruct(page, loc, len);
}
}
byte[] value = new byte[len];
p_copyToArray(page, loc, value, 0, len);
return value;
}
/**
* Sets the cursor key and value references. If mode is key-only, then set value is
* Cursor.NOT_LOADED for a value which exists, null if ghost.
*
* @param pos position as provided by binarySearch; must be positive
* @param cursor key and value are updated
*/
void retrieveLeafEntry(int pos, TreeCursor cursor) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
int header = p_byteGet(page, loc++);
int keyLen;
byte[] key;
copyKey: {
if (header >= 0) {
keyLen = header + 1;
} else {
keyLen = ((header & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
key = getDatabase().reconstructKey(page, loc, keyLen);
break copyKey;
}
}
key = new byte[keyLen];
p_copyToArray(page, loc, key, 0, keyLen);
}
loc += keyLen;
cursor.mKey = key;
byte[] value;
if (cursor.mKeyOnly) {
value = p_byteGet(page, loc) == -1 ? null : Cursor.NOT_LOADED;
} else {
value = retrieveLeafValueAtLoc(this, page, loc);
}
cursor.mValue = value;
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
boolean isFragmentedLeafValue(int pos) {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
loc += keyLengthAtLoc(page, loc);
int header = p_byteGet(page, loc);
return ((header & 0xc0) >= 0xc0) & (header < -1);
}
/**
* Transactionally delete a leaf entry, replacing the value with a
* ghost. When read back, it is interpreted as null. Ghosts are used by
* transactional deletes, to ensure that they are not visible by cursors in
* other transactions. They need to acquire a lock first. When the original
* transaction commits, it deletes all the ghosted entries it created.
*
* <p>Caller must hold commit lock and exclusive latch on node.
*
* @param pos position as provided by binarySearch; must be positive
*/
void txnDeleteLeafEntry(LocalTransaction txn, Tree tree, byte[] key, int keyHash, int pos)
throws IOException
{
final /*P*/ byte[] page = mPage;
final int entryLoc = p_ushortGetLE(page, searchVecStart() + pos);
int loc = entryLoc;
// Skip the key.
loc += keyLengthAtLoc(page, loc);
// Read value header.
final int valueHeaderLoc = loc;
int header = p_byteGet(page, loc++);
doUndo: {
// Note: Similar to leafEntryLengthAtLoc.
if (header >= 0) {
// Short value. Move loc to just past end of value.
loc += header;
} else {
// Medium value. Move loc to just past end of value.
if ((header & 0x20) == 0) {
loc += 2 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc));
} else if (header != -1) {
loc += 3 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc) << 8) | p_ubyteGet(page, loc + 1));
} else {
// Already a ghost, so nothing to undo.
break doUndo;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
int valueStartLoc = valueHeaderLoc + 2 + ((header & 0x20) >> 5);
tree.mDatabase.fragmentedTrash().add
(txn, tree.mId, page,
entryLoc, valueHeaderLoc - entryLoc, // keyStart, keyLen
valueStartLoc, loc - valueStartLoc); // valueStart, valueLen
break doUndo;
}
}
// Copy whole entry into undo log.
txn.pushUndoStore(tree.mId, UndoLog.OP_UNDELETE, page, entryLoc, loc - entryLoc);
}
// Ghost will be deleted later when locks are released.
tree.mLockManager.ghosted(tree, key, keyHash);
// Replace value with ghost.
p_bytePut(page, valueHeaderLoc, -1);
garbage(garbage() + loc - valueHeaderLoc - 1);
if (txn.mDurabilityMode != DurabilityMode.NO_REDO) {
txn.redoStore(tree.mId, key, null);
}
}
/**
* Copies existing entry to undo log prior to it being updated. Fragmented
* values are added to the trash and the fragmented bit is cleared. Caller
* must hold commit lock and exlusive latch on node.
*
* @param pos position as provided by binarySearch; must be positive
*/
void txnPreUpdateLeafEntry(LocalTransaction txn, Tree tree, byte[] key, int pos)
throws IOException
{
final /*P*/ byte[] page = mPage;
final int entryLoc = p_ushortGetLE(page, searchVecStart() + pos);
int loc = entryLoc;
// Skip the key.
loc += keyLengthAtLoc(page, loc);
// Read value header.
final int valueHeaderLoc = loc;
int header = p_byteGet(page, loc++);
examineEntry: {
// Note: Similar to leafEntryLengthAtLoc.
if (header >= 0) {
// Short value. Move loc to just past end of value.
loc += header;
break examineEntry;
} else {
// Medium value. Move loc to just past end of value.
if ((header & 0x20) == 0) {
loc += 2 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc));
} else if (header != -1) {
loc += 3 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc) << 8) | p_ubyteGet(page, loc + 1));
} else {
// Already a ghost, so nothing to undo.
break examineEntry;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
int valueStartLoc = valueHeaderLoc + 2 + ((header & 0x20) >> 5);
tree.mDatabase.fragmentedTrash().add
(txn, tree.mId, page,
entryLoc, valueHeaderLoc - entryLoc, // keyStart, keyLen
valueStartLoc, loc - valueStartLoc); // valueStart, valueLen
// Clearing the fragmented bit prevents the update from
// double-deleting the fragments, and it also allows the
// old entry slot to be re-used.
p_bytePut(page, valueHeaderLoc, header & ~ENTRY_FRAGMENTED);
return;
}
}
}
// Copy whole entry into undo log.
txn.pushUndoStore(tree.mId, UndoLog.OP_UNUPDATE, page, entryLoc, loc - entryLoc);
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
long retrieveChildRefId(int pos) {
return p_uint48GetLE(mPage, searchVecEnd() + 2 + (pos << 2));
}
/**
* Retrieves the count of entries for the child node at the given position, or negative if
* unknown. Counts are only applicable to bottom internal nodes, and are invalidated when
* the node is dirty.
*
* @param pos position as provided by binarySearch; must be positive
*/
int retrieveChildEntryCount(int pos) {
return p_ushortGetLE(mPage, searchVecEnd() + (2 + 6) + (pos << 2)) - 1;
}
/**
* Stores the count of entries for the child node at the given position. Counts are only
* applicable to bottom internal nodes, and are invalidated when the node is dirty.
*
* @param pos position as provided by binarySearch; must be positive
* @param count 0..65534
* @see #countNonGhostKeys
*/
void storeChildEntryCount(int pos, int count) {
if (count < 65535) { // safety check
p_shortPutLE(mPage, searchVecEnd() + (2 + 6) + (pos << 2), count + 1);
}
}
/**
* @return length of encoded entry at given location
*/
static int leafEntryLengthAtLoc(/*P*/ byte[] page, final int entryLoc) {
int loc = entryLoc + keyLengthAtLoc(page, entryLoc);
int header = p_byteGet(page, loc++);
if (header >= 0) {
loc += header;
} else {
if ((header & 0x20) == 0) {
loc += 2 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc));
} else if (header != -1) {
loc += 3 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc) << 8) | p_ubyteGet(page, loc + 1));
}
}
return loc - entryLoc;
}
/**
* @return length of encoded key at given location, including the header
*/
static int keyLengthAtLoc(/*P*/ byte[] page, final int keyLoc) {
int header = p_byteGet(page, keyLoc);
return (header >= 0 ? header
: (((header & 0x3f) << 8) | p_ubyteGet(page, keyLoc + 1))) + 2;
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos complement of position as provided by binarySearch; must be positive
* @param okey original key
*/
void insertLeafEntry(TreeCursorFrame frame, Tree tree, int pos, byte[] okey, byte[] value)
throws IOException
{
byte[] akey = okey;
int encodedKeyLen = calculateAllowedKeyLength(tree, okey);
if (encodedKeyLen < 0) {
// Key must be fragmented.
akey = tree.fragmentKey(okey);
encodedKeyLen = 2 + akey.length;
}
try {
int encodedLen = encodedKeyLen + calculateLeafValueLength(value);
int vfrag;
if (encodedLen <= tree.mMaxEntrySize) {
vfrag = 0;
} else {
LocalDatabase db = tree.mDatabase;
value = db.fragment(value, value.length,
db.mMaxFragmentedEntrySize - encodedKeyLen);
if (value == null) {
throw new AssertionError();
}
encodedLen = encodedKeyLen + calculateFragmentedValueLength(value);
vfrag = ENTRY_FRAGMENTED;
}
try {
int entryLoc = createLeafEntry(frame, tree, pos, encodedLen);
if (entryLoc < 0) {
splitLeafAndCreateEntry(tree, okey, akey, vfrag, value, encodedLen, pos, true);
} else {
copyToLeafEntry(okey, akey, vfrag, value, entryLoc);
}
} catch (Throwable e) {
if (vfrag == ENTRY_FRAGMENTED) {
cleanupFragments(e, value);
}
throw e;
}
} catch (Throwable e) {
if (okey != akey) {
cleanupFragments(e, akey);
}
throw e;
}
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos complement of position as provided by binarySearch; must be positive
* @param okey original key
*/
void insertBlankLeafEntry(TreeCursorFrame frame, Tree tree, int pos, byte[] okey, long vlength)
throws IOException
{
byte[] akey = okey;
int encodedKeyLen = calculateAllowedKeyLength(tree, okey);
if (encodedKeyLen < 0) {
// Key must be fragmented.
akey = tree.fragmentKey(okey);
encodedKeyLen = 2 + akey.length;
}
try {
long longEncodedLen = encodedKeyLen + calculateLeafValueLength(vlength);
int encodedLen;
int vfrag;
byte[] value;
if (longEncodedLen <= tree.mMaxEntrySize) {
vfrag = 0;
value = new byte[(int) vlength];
encodedLen = (int) longEncodedLen;
} else {
LocalDatabase db = tree.mDatabase;
value = db.fragment(null, vlength, db.mMaxFragmentedEntrySize - encodedKeyLen);
if (value == null) {
throw new AssertionError();
}
encodedLen = encodedKeyLen + calculateFragmentedValueLength(value);
vfrag = ENTRY_FRAGMENTED;
}
try {
int entryLoc = createLeafEntry(frame, tree, pos, encodedLen);
if (entryLoc < 0) {
splitLeafAndCreateEntry(tree, okey, akey, vfrag, value, encodedLen, pos, true);
} else {
copyToLeafEntry(okey, akey, vfrag, value, entryLoc);
}
} catch (Throwable e) {
if (vfrag == ENTRY_FRAGMENTED) {
cleanupFragments(e, value);
}
throw e;
}
} catch (Throwable e) {
if (okey != akey) {
cleanupFragments(e, akey);
}
throw e;
}
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos complement of position as provided by binarySearch; must be positive
* @param okey original key
*/
void insertFragmentedLeafEntry(TreeCursorFrame frame,
Tree tree, int pos, byte[] okey, byte[] value)
throws IOException
{
byte[] akey = okey;
int encodedKeyLen = calculateAllowedKeyLength(tree, okey);
if (encodedKeyLen < 0) {
// Key must be fragmented.
akey = tree.fragmentKey(okey);
encodedKeyLen = 2 + akey.length;
}
try {
int encodedLen = encodedKeyLen + calculateFragmentedValueLength(value);
int entryLoc = createLeafEntry(frame, tree, pos, encodedLen);
if (entryLoc < 0) {
splitLeafAndCreateEntry
(tree, okey, akey, ENTRY_FRAGMENTED, value, encodedLen, pos, true);
} else {
copyToLeafEntry(okey, akey, ENTRY_FRAGMENTED, value, entryLoc);
}
} catch (Throwable e) {
if (okey != akey) {
cleanupFragments(e, akey);
}
throw e;
}
}
private void panic(Throwable cause) {
try {
getDatabase().close(cause);
} catch (Throwable e) {
// Ignore.
}
}
private void cleanupFragments(Throwable cause, byte[] fragmented) {
if (fragmented != null) {
/*P*/ byte[] copy = p_transfer(fragmented);
try {
getDatabase().deleteFragments(copy, 0, fragmented.length);
} catch (Throwable e) {
cause.addSuppressed(e);
panic(cause);
} finally {
p_delete(copy);
}
}
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos complement of position as provided by binarySearch; must be positive
* @return Location for newly allocated entry, already pointed to by search
* vector, or negative if leaf must be split. Complement of negative value
* is maximum space available.
*/
int createLeafEntry(final TreeCursorFrame frame, Tree tree, int pos, final int encodedLen) {
int searchVecStart = searchVecStart();
int searchVecEnd = searchVecEnd();
int leftSpace = searchVecStart - leftSegTail();
int rightSpace = rightSegTail() - searchVecEnd - 1;
final /*P*/ byte[] page = mPage;
int entryLoc;
alloc: {
if (pos < ((searchVecEnd - searchVecStart + 2) >> 1)) {
// Shift subset of search vector left or prepend.
if ((leftSpace -= 2) >= 0 &&
(entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0)
{
p_copy(page, searchVecStart, page, searchVecStart -= 2, pos);
pos += searchVecStart;
searchVecStart(searchVecStart);
break alloc;
}
// Need to make space, but restore leftSpace value first.
leftSpace += 2;
} else {
// Shift subset of search vector right or append.
if ((rightSpace -= 2) >= 0 &&
(entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0)
{
pos += searchVecStart;
p_copy(page, pos, page, pos + 2, (searchVecEnd += 2) - pos);
searchVecEnd(searchVecEnd);
break alloc;
}
// Need to make space, but restore rightSpace value first.
rightSpace += 2;
}
// Compute remaining space surrounding search vector after insert completes.
int remaining = leftSpace + rightSpace - encodedLen - 2;
if (garbage() > remaining) {
compact: {
// Do full compaction and free up the garbage, or else node must be split.
if (garbage() + remaining < 0) {
// Node compaction won't make enough room, but attempt to rebalance
// before splitting.
TreeCursorFrame parentFrame;
if (frame == null || (parentFrame = frame.mParentFrame) == null) {
// No sibling nodes, so cannot rebalance.
break compact;
}
// "Randomly" choose left or right node first.
if ((mId & 1) == 0) {
int result = tryRebalanceLeafLeft
(tree, parentFrame, pos, encodedLen, -remaining);
if (result == 0) {
// First rebalance attempt failed.
result = tryRebalanceLeafRight
(tree, parentFrame, pos, encodedLen, -remaining);
if (result == 0) {
// Second rebalance attempt failed too, so split.
break compact;
} else if (result > 0) {
return result;
}
} else if (result > 0) {
return result;
} else {
pos += result;
}
} else {
int result = tryRebalanceLeafRight
(tree, parentFrame, pos, encodedLen, -remaining);
if (result == 0) {
// First rebalance attempt failed.
result = tryRebalanceLeafLeft
(tree, parentFrame, pos, encodedLen, -remaining);
if (result == 0) {
// Second rebalance attempt failed too, so split.
break compact;
} else if (result > 0) {
return result;
} else {
pos += result;
}
} else if (result > 0) {
return result;
}
}
}
return compactLeaf(encodedLen, pos, true);
}
// Determine max possible entry size allowed, accounting too for entry pointer,
// key length, and value length. Key and value length might only require only
// require 1 byte fields, but be safe and choose the larger size of 2.
int max = garbage() + leftSpace + rightSpace - (2 + 2 + 2);
return max <= 0 ? -1 : ~max;
}
int vecLen = searchVecEnd - searchVecStart + 2;
int newSearchVecStart;
if (remaining > 0 || (rightSegTail() & 1) != 0) {
// Re-center search vector, biased to the right, ensuring proper alignment.
newSearchVecStart = (rightSegTail() - vecLen + (1 - 2) - (remaining >> 1)) & ~1;
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if ((leftSegTail() & 1) == 0) {
// Move search vector left, ensuring proper alignment.
newSearchVecStart = leftSegTail() + ((remaining >> 1) & ~1);
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// Search vector is misaligned, so do full compaction.
return compactLeaf(encodedLen, pos, true);
}
p_copies(page,
searchVecStart, newSearchVecStart, pos,
searchVecStart + pos, newSearchVecStart + pos + 2, vecLen - pos);
pos += newSearchVecStart;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart + vecLen);
}
// Write pointer to new allocation.
p_shortPutLE(page, pos, entryLoc);
return entryLoc;
}
/**
* Attempt to make room in this node by moving entries to the left sibling node. First
* determines if moving entries to the left node is allowed and would free up enough space.
* Next, attempts to latch parent and child nodes without waiting, avoiding deadlocks.
*
* @param tree required
* @param parentFrame required
* @param pos position to insert into; this position cannot move left
* @param insertLen encoded length of entry to insert
* @param minAmount minimum amount of bytes to move to make room
* @return 0 if try failed, or entry location of re-used slot, or negative 2-based position
* decrement if no slot was found
*/
private int tryRebalanceLeafLeft(Tree tree, TreeCursorFrame parentFrame,
int pos, int insertLen, int minAmount)
{
final /*P*/ byte[] rightPage = mPage;
int moveAmount = 0;
final int lastSearchVecLoc;
int insertLoc = 0;
int insertSlack = Integer.MAX_VALUE;
check: {
int searchVecLoc = searchVecStart();
int searchVecEnd = searchVecLoc + pos - 2;
// Note that loop doesn't examine last entry. At least one must remain.
for (; searchVecLoc < searchVecEnd; searchVecLoc += 2) {
int entryLoc = p_ushortGetLE(rightPage, searchVecLoc);
int encodedLen = leafEntryLengthAtLoc(rightPage, entryLoc);
// Find best fitting slot for insert entry.
int slack = encodedLen - insertLen;
if (slack >= 0 && slack < insertSlack) {
insertLoc = entryLoc;
insertSlack = slack;
}
moveAmount += encodedLen + 2;
if (moveAmount >= minAmount && insertLoc != 0) {
lastSearchVecLoc = searchVecLoc + 2; // +2 to be exclusive
break check;
}
}
return 0;
}
final Node parent = parentFrame.tryAcquireExclusive();
if (parent == null) {
return 0;
}
final int childPos = parentFrame.mNodePos;
if (childPos <= 0
|| parent.mSplit != null
|| parent.mCachedState != mCachedState)
{
// No left child or sanity checks failed.
parent.releaseExclusive();
return 0;
}
final Node left;
try {
left = parent.tryLatchChildNotSplit(childPos - 2);
} catch (IOException e) {
return 0;
}
if (left == null) {
parent.releaseExclusive();
return 0;
}
// Notice that try-finally pattern is not used to release the latches. An uncaught
// exception can only be caused by a bug. Leaving the latches held prevents database
// corruption from being persisted.
final byte[] newKey;
final int newKeyLen;
final /*P*/ byte[] parentPage;
final int parentKeyLoc;
final int parentKeyGrowth;
check: {
try {
int leftAvail = left.availableLeafBytes();
if (leftAvail >= moveAmount) {
// Parent search key will be updated, so verify that it has room.
int highPos = lastSearchVecLoc - searchVecStart();
newKey = midKey(highPos - 2, this, highPos);
// Only attempt rebalance if new key doesn't need to be fragmented.
newKeyLen = calculateAllowedKeyLength(tree, newKey);
if (newKeyLen > 0) {
parentPage = parent.mPage;
parentKeyLoc = p_ushortGetLE
(parentPage, parent.searchVecStart() + childPos - 2);
parentKeyGrowth = newKeyLen - keyLengthAtLoc(parentPage, parentKeyLoc);
if (parentKeyGrowth <= 0 ||
parentKeyGrowth <= parent.availableInternalBytes())
{
// Parent has room for the new search key, so proceed with rebalancing.
break check;
}
}
}
} catch (IOException e) {
// Caused by failed read of a large key. Abort the rebalance attempt.
}
left.releaseExclusive();
parent.releaseExclusive();
return 0;
}
try {
if (tree.mDatabase.markDirty(tree, left)) {
parent.updateChildRefId(childPos - 2, left.mId);
}
} catch (IOException e) {
left.releaseExclusive();
parent.releaseExclusive();
return 0;
}
// Update the parent key.
if (parentKeyGrowth <= 0) {
encodeNormalKey(newKey, parentPage, parentKeyLoc);
parent.garbage(parent.garbage() - parentKeyGrowth);
} else {
parent.updateInternalKey(childPos - 2, parentKeyGrowth, newKey, newKeyLen);
}
int garbageAccum = 0;
int searchVecLoc = searchVecStart();
final int lastPos = lastSearchVecLoc - searchVecLoc;
for (; searchVecLoc < lastSearchVecLoc; searchVecLoc += 2) {
int entryLoc = p_ushortGetLE(rightPage, searchVecLoc);
int encodedLen = leafEntryLengthAtLoc(rightPage, entryLoc);
int leftEntryLoc = left.createLeafEntry
(null, tree, left.highestLeafPos() + 2, encodedLen);
// Note: Must access left page each time, since compaction can replace it.
p_copy(rightPage, entryLoc, left.mPage, leftEntryLoc, encodedLen);
garbageAccum += encodedLen;
}
garbage(garbage() + garbageAccum);
searchVecStart(lastSearchVecLoc);
// Fix cursor positions or move them to the left node.
final int leftEndPos = left.highestLeafPos() + 2;
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
int mask = framePos >> 31;
int newPos = (framePos ^ mask) - lastPos;
// This checks for nodes which should move and also includes not-found frames at
// the low position. They might need to move just higher than the left node high
// position, because the parent key has changed. A new search would position the
// search there. Note that tryRebalanceLeafRight has an identical check, after
// applying De Morgan's law. Because the chosen parent node is not strictly the
// lowest from the right, a comparison must be made to the actual new parent node.
if (newPos < 0 |
((newPos == 0 & mask != 0) && compareUnsigned(frame.mNotFoundKey, newKey) < 0))
{
frame.rebind(left, (leftEndPos + newPos) ^ mask);
frame.adjustParentPosition(-2);
} else {
frame.mNodePos = newPos ^ mask;
}
frame = prev;
}
left.releaseExclusive();
parent.releaseExclusive();
/* Not possible unless aggressive compaction is allowed.
if (insertLoc == 0) {
return -lastPos;
}
*/
// Expand search vector for inserted entry and write pointer to the re-used slot.
garbage(garbage() - insertLen);
pos -= lastPos;
int searchVecStart = searchVecStart();
p_copy(rightPage, searchVecStart, rightPage, searchVecStart -= 2, pos);
searchVecStart(searchVecStart);
p_shortPutLE(rightPage, searchVecStart + pos, insertLoc);
return insertLoc;
}
/**
* Attempt to make room in this node by moving entries to the right sibling node. First
* determines if moving entries to the right node is allowed and would free up enough space.
* Next, attempts to latch parent and child nodes without waiting, avoiding deadlocks.
*
* @param tree required
* @param parentFrame required
* @param pos position to insert into; this position cannot move right
* @param insertLen encoded length of entry to insert
* @param minAmount minimum amount of bytes to move to make room
* @return 0 if try failed, or entry location of re-used slot, or negative if no slot was found
*/
private int tryRebalanceLeafRight(Tree tree, TreeCursorFrame parentFrame,
int pos, int insertLen, int minAmount)
{
final /*P*/ byte[] leftPage = mPage;
int moveAmount = 0;
final int firstSearchVecLoc;
int insertLoc = 0;
int insertSlack = Integer.MAX_VALUE;
check: {
int searchVecStart = searchVecStart() + pos;
int searchVecLoc = searchVecEnd();
// Note that loop doesn't examine first entry. At least one must remain.
for (; searchVecLoc > searchVecStart; searchVecLoc -= 2) {
int entryLoc = p_ushortGetLE(leftPage, searchVecLoc);
int encodedLen = leafEntryLengthAtLoc(leftPage, entryLoc);
// Find best fitting slot for insert entry.
int slack = encodedLen - insertLen;
if (slack >= 0 && slack < insertSlack) {
insertLoc = entryLoc;
insertSlack = slack;
}
moveAmount += encodedLen + 2;
if (moveAmount >= minAmount && insertLoc != 0) {
firstSearchVecLoc = searchVecLoc;
break check;
}
}
return 0;
}
final Node parent = parentFrame.tryAcquireExclusive();
if (parent == null) {
return 0;
}
final int childPos = parentFrame.mNodePos;
if (childPos >= parent.highestInternalPos()
|| parent.mSplit != null
|| parent.mCachedState != mCachedState)
{
// No right child or sanity checks failed.
parent.releaseExclusive();
return 0;
}
final Node right;
try {
right = parent.tryLatchChildNotSplit(childPos + 2);
} catch (IOException e) {
return 0;
}
if (right == null) {
parent.releaseExclusive();
return 0;
}
// Notice that try-finally pattern is not used to release the latches. An uncaught
// exception can only be caused by a bug. Leaving the latches held prevents database
// corruption from being persisted.
final byte[] newKey;
final int newKeyLen;
final /*P*/ byte[] parentPage;
final int parentKeyLoc;
final int parentKeyGrowth;
check: {
try {
int rightAvail = right.availableLeafBytes();
if (rightAvail >= moveAmount) {
// Parent search key will be updated, so verify that it has room.
int highPos = firstSearchVecLoc - searchVecStart();
newKey = midKey(highPos - 2, this, highPos);
// Only attempt rebalance if new key doesn't need to be fragmented.
newKeyLen = calculateAllowedKeyLength(tree, newKey);
if (newKeyLen > 0) {
parentPage = parent.mPage;
parentKeyLoc = p_ushortGetLE
(parentPage, parent.searchVecStart() + childPos);
parentKeyGrowth = newKeyLen - keyLengthAtLoc(parentPage, parentKeyLoc);
if (parentKeyGrowth <= 0 ||
parentKeyGrowth <= parent.availableInternalBytes())
{
// Parent has room for the new search key, so proceed with rebalancing.
break check;
}
}
}
} catch (IOException e) {
// Caused by failed read of a large key. Abort the rebalance attempt.
}
right.releaseExclusive();
parent.releaseExclusive();
return 0;
}
try {
if (tree.mDatabase.markDirty(tree, right)) {
parent.updateChildRefId(childPos + 2, right.mId);
}
} catch (IOException e) {
right.releaseExclusive();
parent.releaseExclusive();
return 0;
}
// Update the parent key.
if (parentKeyGrowth <= 0) {
encodeNormalKey(newKey, parentPage, parentKeyLoc);
parent.garbage(parent.garbage() - parentKeyGrowth);
} else {
parent.updateInternalKey(childPos, parentKeyGrowth, newKey, newKeyLen);
}
int garbageAccum = 0;
int searchVecLoc = searchVecEnd();
final int moved = searchVecLoc - firstSearchVecLoc + 2;
for (; searchVecLoc >= firstSearchVecLoc; searchVecLoc -= 2) {
int entryLoc = p_ushortGetLE(leftPage, searchVecLoc);
int encodedLen = leafEntryLengthAtLoc(leftPage, entryLoc);
int rightEntryLoc = right.createLeafEntry(null, tree, 0, encodedLen);
// Note: Must access right page each time, since compaction can replace it.
p_copy(leftPage, entryLoc, right.mPage, rightEntryLoc, encodedLen);
garbageAccum += encodedLen;
}
garbage(garbage() + garbageAccum);
searchVecEnd(firstSearchVecLoc - 2);
// Fix cursor positions in the right node.
for (TreeCursorFrame frame = right.mLastCursorFrame; frame != null; ) {
int framePos = frame.mNodePos;
int mask = framePos >> 31;
frame.mNodePos = ((framePos ^ mask) + moved) ^ mask;
frame = frame.mPrevCousin;
}
// Move affected cursor frames to the right node.
final int leftEndPos = firstSearchVecLoc - searchVecStart();
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
int mask = framePos >> 31;
int newPos = (framePos ^ mask) - leftEndPos;
// This checks for nodes which should move, but it excludes not-found frames at the
// high position. They might otherwise move to position zero of the right node, but
// the parent key has changed. A new search would position the frame just beyond
// the high position of the left node, which is where it is now. Note that
// tryRebalanceLeafLeft has an identical check, after applying De Morgan's law.
// Because the chosen parent node is not strictly the lowest from the right, a
// comparison must be made to the actual new parent node.
if (newPos >= 0 &
((newPos != 0 | mask == 0) || compareUnsigned(frame.mNotFoundKey, newKey) >= 0))
{
frame.rebind(right, newPos ^ mask);
frame.adjustParentPosition(+2);
}
frame = prev;
}
right.releaseExclusive();
parent.releaseExclusive();
/* Not possible unless aggressive compaction is allowed.
if (insertLoc == 0) {
return -1;
}
*/
// Expand search vector for inserted entry and write pointer to the re-used slot.
garbage(garbage() - insertLen);
pos += searchVecStart();
int newSearchVecEnd = searchVecEnd() + 2;
p_copy(leftPage, pos, leftPage, pos + 2, newSearchVecEnd - pos);
searchVecEnd(newSearchVecEnd);
p_shortPutLE(leftPage, pos, insertLoc);
return insertLoc;
}
/**
* Insert into an internal node following a child node split. This parent node and child
* node must have an exclusive latch held. Parent and child latch are always released, even
* if an exception is thrown.
*
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param keyPos position to insert split key
* @param splitChild child node which split
*/
void insertSplitChildRef(final TreeCursorFrame frame, Tree tree, int keyPos, Node splitChild)
throws IOException
{
final Split split = splitChild.mSplit;
final Node newChild = splitChild.rebindSplitFrames(split);
try {
splitChild.mSplit = null;
//final Node leftChild;
final Node rightChild;
int newChildPos = keyPos >> 1;
if (split.mSplitRight) {
//leftChild = splitChild;
rightChild = newChild;
newChildPos++;
} else {
//leftChild = newChild;
rightChild = splitChild;
}
// Positions of frames higher than split key need to be incremented.
for (TreeCursorFrame f = mLastCursorFrame; f != null; ) {
int fPos = f.mNodePos;
if (fPos > keyPos) {
f.mNodePos = fPos + 2;
}
f = f.mPrevCousin;
}
// Positions of frames equal to split key are in the split itself. Only
// frames for the right split need to be incremented.
for (TreeCursorFrame childFrame = rightChild.mLastCursorFrame; childFrame != null; ) {
childFrame.adjustParentPosition(+2);
childFrame = childFrame.mPrevCousin;
}
// Note: Invocation of createInternalEntry may cause splitInternal to be called,
// which in turn might throw a recoverable exception. State changes can be undone
// by decrementing the incremented frame positions, and then by undoing the
// rebindSplitFrames call. However, this would create an orphaned child node.
// Panicking the database is the safest option.
InResult result = new InResult();
try {
createInternalEntry(frame, result, tree, keyPos, split.splitKeyEncodedLength(),
newChildPos << 3, true);
} catch (Throwable e) {
panic(e);
throw e;
}
// Write new child id.
p_longPutLE(result.mPage, result.mNewChildLoc, newChild.mId);
int entryLoc = result.mEntryLoc;
if (entryLoc < 0) {
// If loc is negative, then node was split and new key was chosen to be promoted.
// It must be written into the new split.
mSplit.setKey(split);
} else {
// Write key entry itself.
split.copySplitKeyToParent(result.mPage, entryLoc);
}
} catch (Throwable e) {
splitChild.releaseExclusive();
newChild.releaseExclusive();
releaseExclusive();
throw e;
}
splitChild.releaseExclusive();
newChild.releaseExclusive();
try {
// Split complete, so allow new node to be evictable.
newChild.makeEvictable();
} catch (Throwable e) {
releaseExclusive();
throw e;
}
}
/**
* Insert into an internal node following a child node split. This parent
* node and child node must have an exclusive latch held. Child latch is
* released, unless an exception is thrown.
*
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param result return result stored here; if node was split, key and entry loc is -1 if
* new key was promoted to parent
* @param keyPos 2-based position
* @param newChildPos 8-based position
* @param allowSplit true if this internal node can be split as a side-effect
* @throws AssertionError if entry must be split to make room but split is not allowed
*/
private void createInternalEntry(final TreeCursorFrame frame, InResult result,
Tree tree, int keyPos, int encodedLen,
int newChildPos, boolean allowSplit)
throws IOException
{
int searchVecStart = searchVecStart();
int searchVecEnd = searchVecEnd();
int leftSpace = searchVecStart - leftSegTail();
int rightSpace = rightSegTail() - searchVecEnd
- ((searchVecEnd - searchVecStart) << 2) - 17;
/*P*/ byte[] page = mPage;
int entryLoc;
alloc: {
// Need to make room for one new search vector entry (2 bytes) and one new child
// id entry (8 bytes). Determine which shift operations minimize movement.
if (newChildPos < ((3 * (searchVecEnd - searchVecStart + 2) + keyPos + 8) >> 1)) {
// Attempt to shift search vector left by 10, shift child ids left by 8.
if ((leftSpace -= 10) >= 0 &&
(entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0)
{
p_copy(page, searchVecStart, page, searchVecStart - 10, keyPos);
p_copy(page, searchVecStart + keyPos,
page, searchVecStart + keyPos - 8,
searchVecEnd - searchVecStart + 2 - keyPos + newChildPos);
searchVecStart(searchVecStart -= 10);
keyPos += searchVecStart;
searchVecEnd(searchVecEnd -= 8);
newChildPos += searchVecEnd + 2;
break alloc;
}
// Need to make space, but restore leftSpace value first.
leftSpace += 10;
} else {
// Attempt to shift search vector left by 2, shift child ids right by 8.
leftSpace -= 2;
rightSpace -= 8;
if (leftSpace >= 0 && rightSpace >= 0 &&
(entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0)
{
p_copy(page, searchVecStart, page, searchVecStart -= 2, keyPos);
searchVecStart(searchVecStart);
keyPos += searchVecStart;
p_copy(page, searchVecEnd + newChildPos + 2,
page, searchVecEnd + newChildPos + (2 + 8),
((searchVecEnd - searchVecStart) << 2) + 8 - newChildPos);
newChildPos += searchVecEnd + 2;
break alloc;
}
// Need to make space, but restore space values first.
leftSpace += 2;
rightSpace += 8;
}
// Compute remaining space surrounding search vector after insert completes.
int remaining = leftSpace + rightSpace - encodedLen - 10;
if (garbage() > remaining) {
compact: {
// Do full compaction and free up the garbage, or else node must be split.
if ((garbage() + remaining) < 0) {
// Node compaction won't make enough room, but attempt to rebalance
// before splitting.
TreeCursorFrame parentFrame;
if (frame == null || (parentFrame = frame.mParentFrame) == null) {
// No sibling nodes, so cannot rebalance.
break compact;
}
// "Randomly" choose left or right node first.
if ((mId & 1) == 0) {
int adjust = tryRebalanceInternalLeft
(tree, parentFrame, keyPos, -remaining);
if (adjust == 0) {
// First rebalance attempt failed.
if (!tryRebalanceInternalRight
(tree, parentFrame, keyPos, -remaining))
{
// Second rebalance attempt failed too, so split.
break compact;
}
} else {
keyPos -= adjust;
newChildPos -= (adjust << 2);
}
} else if (!tryRebalanceInternalRight
(tree, parentFrame, keyPos, -remaining))
{
// First rebalance attempt failed.
int adjust = tryRebalanceInternalLeft
(tree, parentFrame, keyPos, -remaining);
if (adjust == 0) {
// Second rebalance attempt failed too, so split.
break compact;
} else {
keyPos -= adjust;
newChildPos -= (adjust << 2);
}
}
}
compactInternal(result, encodedLen, keyPos, newChildPos);
return;
}
// Node is full, so split it.
if (!allowSplit) {
throw new AssertionError("Split not allowed");
}
// No side-effects if an IOException is thrown here.
splitInternal(result, tree, encodedLen, keyPos, newChildPos);
return;
}
int vecLen = searchVecEnd - searchVecStart + 2;
int childIdsLen = (vecLen << 2) + 8;
int newSearchVecStart;
if (remaining > 0 || (rightSegTail() & 1) != 0) {
// Re-center search vector, biased to the right, ensuring proper alignment.
newSearchVecStart =
(rightSegTail() - vecLen - childIdsLen + (1 - 10) - (remaining >> 1)) & ~1;
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if ((leftSegTail() & 1) == 0) {
// Move search vector left, ensuring proper alignment.
newSearchVecStart = leftSegTail() + ((remaining >> 1) & ~1);
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// Search vector is misaligned, so do full compaction.
compactInternal(result, encodedLen, keyPos, newChildPos);
return;
}
int newSearchVecEnd = newSearchVecStart + vecLen;
p_copies(page,
// Move search vector up to new key position.
searchVecStart, newSearchVecStart, keyPos,
// Move search vector after new key position, to new child id position.
searchVecStart + keyPos,
newSearchVecStart + keyPos + 2,
vecLen - keyPos + newChildPos,
// Move search vector after new child id position.
searchVecEnd + 2 + newChildPos,
newSearchVecEnd + 10 + newChildPos,
childIdsLen - newChildPos);
keyPos += newSearchVecStart;
newChildPos += newSearchVecEnd + 2;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecEnd);
}
// Write pointer to key entry.
p_shortPutLE(page, keyPos, entryLoc);
result.mPage = page;
result.mNewChildLoc = newChildPos;
result.mEntryLoc = entryLoc;
}
/**
* Attempt to make room in this node by moving entries to the left sibling node. First
* determines if moving entries to the left node is allowed and would free up enough space.
* Next, attempts to latch parent and child nodes without waiting, avoiding deadlocks.
*
* @param tree required
* @param parentFrame required
* @param keyPos position to insert into; this position cannot move left
* @param minAmount minimum amount of bytes to move to make room
* @return 2-based position increment; 0 if try failed
*/
private int tryRebalanceInternalLeft(Tree tree, TreeCursorFrame parentFrame,
int keyPos, int minAmount)
{
final Node parent = parentFrame.tryAcquireExclusive();
if (parent == null) {
return 0;
}
final int childPos = parentFrame.mNodePos;
if (childPos <= 0
|| parent.mSplit != null
|| parent.mCachedState != mCachedState)
{
// No left child or sanity checks failed.
parent.releaseExclusive();
return 0;
}
final /*P*/ byte[] parentPage = parent.mPage;
final /*P*/ byte[] rightPage = mPage;
int rightShrink = 0;
int leftGrowth = 0;
final int lastSearchVecLoc;
check: {
int searchVecLoc = searchVecStart();
int searchVecEnd = searchVecLoc + keyPos - 2;
// Note that loop doesn't examine last entry. At least one must remain.
for (; searchVecLoc < searchVecEnd; searchVecLoc += 2) {
int keyLoc = p_ushortGetLE(rightPage, searchVecLoc);
int len = keyLengthAtLoc(rightPage, keyLoc) + (2 + 8);
rightShrink += len;
leftGrowth += len;
if (rightShrink >= minAmount) {
lastSearchVecLoc = searchVecLoc;
// Leftmost key to move comes from the parent, and first moved key in the
// right node does not affect left node growth.
leftGrowth -= len;
keyLoc = p_ushortGetLE(parentPage, parent.searchVecStart() + childPos - 2);
leftGrowth += keyLengthAtLoc(parentPage, keyLoc) + (2 + 8);
break check;
}
}
parent.releaseExclusive();
return 0;
}
final Node left;
try {
left = parent.tryLatchChildNotSplit(childPos - 2);
} catch (IOException e) {
return 0;
}
if (left == null) {
parent.releaseExclusive();
return 0;
}
// Notice that try-finally pattern is not used to release the latches. An uncaught
// exception can only be caused by a bug. Leaving the latches held prevents database
// corruption from being persisted.
final int searchKeyLoc;
final int searchKeyLen;
final int parentKeyLoc;
final int parentKeyLen;
final int parentKeyGrowth;
check: {
int leftAvail = left.availableInternalBytes();
if (leftAvail >= leftGrowth) {
// Parent search key will be updated, so verify that it has room.
searchKeyLoc = p_ushortGetLE(rightPage, lastSearchVecLoc);
searchKeyLen = keyLengthAtLoc(rightPage, searchKeyLoc);
parentKeyLoc = p_ushortGetLE(parentPage, parent.searchVecStart() + childPos - 2);
parentKeyLen = keyLengthAtLoc(parentPage, parentKeyLoc);
parentKeyGrowth = searchKeyLen - parentKeyLen;
if (parentKeyGrowth <= 0 || parentKeyGrowth <= parent.availableInternalBytes()) {
// Parent has room for the new search key, so proceed with rebalancing.
break check;
}
}
left.releaseExclusive();
parent.releaseExclusive();
return 0;
}
try {
if (tree.mDatabase.markDirty(tree, left)) {
parent.updateChildRefId(childPos - 2, left.mId);
}
} catch (IOException e) {
left.releaseExclusive();
parent.releaseExclusive();
return 0;
}
int garbageAccum = searchKeyLen;
int searchVecLoc = searchVecStart();
final int moved = lastSearchVecLoc - searchVecLoc + 2;
try {
// Leftmost key to move comes from the parent.
int pos = left.highestInternalPos();
InResult result = new InResult();
left.createInternalEntry(null, result, tree, pos, parentKeyLen, (pos + 2) << 2, false);
// Note: Must access left page each time, since compaction can replace it.
p_copy(parentPage, parentKeyLoc, left.mPage, result.mEntryLoc, parentKeyLen);
// Remaining keys come from the right node.
for (; searchVecLoc < lastSearchVecLoc; searchVecLoc += 2) {
int keyLoc = p_ushortGetLE(rightPage, searchVecLoc);
int encodedLen = keyLengthAtLoc(rightPage, keyLoc);
pos = left.highestInternalPos();
left.createInternalEntry
(null, result, tree, pos, encodedLen, (pos + 2) << 2, false);
// Note: Must access left page each time, since compaction can replace it.
p_copy(rightPage, keyLoc, left.mPage, result.mEntryLoc, encodedLen);
garbageAccum += encodedLen;
}
} catch (IOException e) {
// Can only be caused by node split, but this is not possible.
throw rethrow(e);
}
// Update the parent key after moving it to the left node.
if (parentKeyGrowth <= 0) {
p_copy(rightPage, searchKeyLoc, parentPage, parentKeyLoc, searchKeyLen);
parent.garbage(parent.garbage() - parentKeyGrowth);
} else {
parent.updateInternalKeyEncoded
(childPos - 2, parentKeyGrowth, rightPage, searchKeyLoc, searchKeyLen);
}
// Move encoded child pointers.
{
int start = searchVecEnd() + 2;
int len = moved << 2;
int end = left.searchVecEnd();
end = end + ((end - left.searchVecStart()) << 2) + (2 + 16) - len;
p_copy(rightPage, start, left.mPage, end, len);
p_copy(rightPage, start + len, rightPage, start, (start - lastSearchVecLoc) << 2);
}
garbage(garbage() + garbageAccum);
searchVecStart(lastSearchVecLoc + 2);
// Fix cursor positions or move them to the left node.
final int leftEndPos = left.highestInternalPos() + 2;
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
int newPos = framePos - moved;
if (newPos < 0) {
frame.rebind(left, leftEndPos + newPos);
frame.adjustParentPosition(-2);
} else {
frame.mNodePos = newPos;
}
frame = prev;
}
left.releaseExclusive();
parent.releaseExclusive();
return moved;
}
/**
* Attempt to make room in this node by moving entries to the right sibling node. First
* determines if moving entries to the right node is allowed and would free up enough space.
* Next, attempts to latch parent and child nodes without waiting, avoiding deadlocks.
*
* @param tree required
* @param parentFrame required
* @param keyPos position to insert into; this position cannot move right
* @param minAmount minimum amount of bytes to move to make room
*/
private boolean tryRebalanceInternalRight(Tree tree, TreeCursorFrame parentFrame,
int keyPos, int minAmount)
{
final Node parent = parentFrame.tryAcquireExclusive();
if (parent == null) {
return false;
}
final int childPos = parentFrame.mNodePos;
if (childPos >= parent.highestInternalPos()
|| parent.mSplit != null
|| parent.mCachedState != mCachedState)
{
// No right child or sanity checks failed.
parent.releaseExclusive();
return false;
}
final /*P*/ byte[] parentPage = parent.mPage;
final /*P*/ byte[] leftPage = mPage;
int leftShrink = 0;
int rightGrowth = 0;
final int firstSearchVecLoc;
check: {
int searchVecStart = searchVecStart() + keyPos;
int searchVecLoc = searchVecEnd();
// Note that loop doesn't examine first entry. At least one must remain.
for (; searchVecLoc > searchVecStart; searchVecLoc -= 2) {
int keyLoc = p_ushortGetLE(leftPage, searchVecLoc);
int len = keyLengthAtLoc(leftPage, keyLoc) + (2 + 8);
leftShrink += len;
rightGrowth += len;
if (leftShrink >= minAmount) {
firstSearchVecLoc = searchVecLoc;
// Rightmost key to move comes from the parent, and first moved key in the
// left node does not affect right node growth.
rightGrowth -= len;
keyLoc = p_ushortGetLE(parentPage, parent.searchVecStart() + childPos);
rightGrowth += keyLengthAtLoc(parentPage, keyLoc) + (2 + 8);
break check;
}
}
parent.releaseExclusive();
return false;
}
final Node right;
try {
right = parent.tryLatchChildNotSplit(childPos + 2);
} catch (IOException e) {
return false;
}
if (right == null) {
parent.releaseExclusive();
return false;
}
// Notice that try-finally pattern is not used to release the latches. An uncaught
// exception can only be caused by a bug. Leaving the latches held prevents database
// corruption from being persisted.
final int searchKeyLoc;
final int searchKeyLen;
final int parentKeyLoc;
final int parentKeyLen;
final int parentKeyGrowth;
check: {
int rightAvail = right.availableInternalBytes();
if (rightAvail >= rightGrowth) {
// Parent search key will be updated, so verify that it has room.
searchKeyLoc = p_ushortGetLE(leftPage, firstSearchVecLoc);
searchKeyLen = keyLengthAtLoc(leftPage, searchKeyLoc);
parentKeyLoc = p_ushortGetLE(parentPage, parent.searchVecStart() + childPos);
parentKeyLen = keyLengthAtLoc(parentPage, parentKeyLoc);
parentKeyGrowth = searchKeyLen - parentKeyLen;
if (parentKeyGrowth <= 0 || parentKeyGrowth <= parent.availableInternalBytes()) {
// Parent has room for the new search key, so proceed with rebalancing.
break check;
}
}
right.releaseExclusive();
parent.releaseExclusive();
return false;
}
try {
if (tree.mDatabase.markDirty(tree, right)) {
parent.updateChildRefId(childPos + 2, right.mId);
}
} catch (IOException e) {
right.releaseExclusive();
parent.releaseExclusive();
return false;
}
int garbageAccum = searchKeyLen;
int searchVecLoc = searchVecEnd();
final int moved = searchVecLoc - firstSearchVecLoc + 2;
try {
// Rightmost key to move comes from the parent.
InResult result = new InResult();
right.createInternalEntry(null, result, tree, 0, parentKeyLen, 0, false);
// Note: Must access right page each time, since compaction can replace it.
p_copy(parentPage, parentKeyLoc, right.mPage, result.mEntryLoc, parentKeyLen);
// Remaining keys come from the left node.
for (; searchVecLoc > firstSearchVecLoc; searchVecLoc -= 2) {
int keyLoc = p_ushortGetLE(leftPage, searchVecLoc);
int encodedLen = keyLengthAtLoc(leftPage, keyLoc);
right.createInternalEntry(null, result, tree, 0, encodedLen, 0, false);
// Note: Must access right page each time, since compaction can replace it.
p_copy(leftPage, keyLoc, right.mPage, result.mEntryLoc, encodedLen);
garbageAccum += encodedLen;
}
} catch (IOException e) {
// Can only be caused by node split, but this is not possible.
throw rethrow(e);
}
// Update the parent key after moving it to the right node.
if (parentKeyGrowth <= 0) {
p_copy(leftPage, searchKeyLoc, parentPage, parentKeyLoc, searchKeyLen);
parent.garbage(parent.garbage() - parentKeyGrowth);
} else {
parent.updateInternalKeyEncoded
(childPos, parentKeyGrowth, leftPage, searchKeyLoc, searchKeyLen);
}
// Move encoded child pointers.
{
int start = searchVecEnd() + 2;
int len = ((start - searchVecStart()) << 2) + 8 - (moved << 2);
p_copy(leftPage, start, leftPage, start - moved, len);
p_copy(leftPage, start + len, right.mPage, right.searchVecEnd() + 2, moved << 2);
}
garbage(garbage() + garbageAccum);
searchVecEnd(firstSearchVecLoc - 2);
// Fix cursor positions in the right node.
for (TreeCursorFrame frame = right.mLastCursorFrame; frame != null; ) {
frame.mNodePos += moved;
frame = frame.mPrevCousin;
}
// Move affected cursor frames to the right node.
final int adjust = firstSearchVecLoc - searchVecStart() + 4;
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int newPos = frame.mNodePos - adjust;
if (newPos >= 0) {
frame.rebind(right, newPos);
frame.adjustParentPosition(+2);
}
frame = prev;
}
right.releaseExclusive();
parent.releaseExclusive();
return true;
}
/**
* Rebind cursor frames affected by split to correct node and
* position. Caller must hold exclusive latch.
*
* @return latched sibling
*/
private Node rebindSplitFrames(Split split) {
final Node sibling = split.latchSiblingEx();
try {
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
split.rebindFrame(frame, sibling);
frame = prev;
}
return sibling;
} catch (Throwable e) {
sibling.releaseExclusive();
throw e;
}
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos position as provided by binarySearch; must be positive
* @param vfrag 0 or ENTRY_FRAGMENTED
*/
void updateLeafValue(TreeCursorFrame frame, Tree tree, int pos, int vfrag, byte[] value)
throws IOException
{
/*P*/ byte[] page = mPage;
final int searchVecStart = searchVecStart();
final int start;
final int keyLen;
final int garbage;
quick: {
int loc;
start = loc = p_ushortGetLE(page, searchVecStart + pos);
loc += keyLengthAtLoc(page, loc);
final int valueHeaderLoc = loc;
// Note: Similar to leafEntryLengthAtLoc and retrieveLeafValueAtLoc.
int len = p_byteGet(page, loc++);
if (len < 0) largeValue: {
int header;
if ((len & 0x20) == 0) {
header = len;
len = 1 + (((len & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (len != -1) {
header = len;
len = 1 + (((len & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
len = 0;
break largeValue;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
tree.mDatabase.deleteFragments(page, loc, len);
// TODO: If new value needs to be fragmented too, try to
// re-use existing value slot.
if (vfrag == 0) {
// Clear fragmented bit in case new value can be quick copied.
p_bytePut(page, valueHeaderLoc, header & ~ENTRY_FRAGMENTED);
}
}
}
final int valueLen = value.length;
if (valueLen > len) {
// Old entry is too small, and so it becomes garbage.
keyLen = valueHeaderLoc - start;
garbage = garbage() + loc + len - start;
break quick;
}
if (valueLen == len) {
// Quick copy with no garbage created.
if (valueLen == 0) {
// Ensure ghost is replaced.
p_bytePut(page, valueHeaderLoc, 0);
} else {
p_copyFromArray(value, 0, page, loc, valueLen);
if (vfrag != 0) {
p_bytePut(page, valueHeaderLoc, p_byteGet(page, valueHeaderLoc) | vfrag);
}
}
} else {
garbage(garbage() + loc + len - copyToLeafValue
(page, vfrag, value, valueHeaderLoc) - valueLen);
}
return;
}
// What follows is similar to createLeafEntry method, except the search
// vector doesn't grow.
int searchVecEnd = searchVecEnd();
int leftSpace = searchVecStart - leftSegTail();
int rightSpace = rightSegTail() - searchVecEnd - 1;
final int vfragOriginal = vfrag;
int encodedLen;
if (vfrag != 0) {
encodedLen = keyLen + calculateFragmentedValueLength(value);
} else {
encodedLen = keyLen + calculateLeafValueLength(value);
if (encodedLen > tree.mMaxEntrySize) {
LocalDatabase db = tree.mDatabase;
value = db.fragment(value, value.length, db.mMaxFragmentedEntrySize - keyLen);
if (value == null) {
throw new AssertionError();
}
encodedLen = keyLen + calculateFragmentedValueLength(value);
vfrag = ENTRY_FRAGMENTED;
}
}
int entryLoc;
alloc: try {
if ((entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0) {
pos += searchVecStart;
break alloc;
}
// Compute remaining space surrounding search vector after update completes.
int remaining = leftSpace + rightSpace - encodedLen;
if (garbage > remaining) {
// Do full compaction and free up the garbage, or split the node.
byte[][] akeyRef = new byte[1][];
int loc = p_ushortGetLE(page, searchVecStart + pos);
boolean isOriginal = retrieveActualKeyAtLoc(page, loc, akeyRef);
byte[] akey = akeyRef[0];
if ((garbage + remaining) < 0) {
if (mSplit == null) {
// TODO: use frame for rebalancing
// Node is full, so split it.
byte[] okey = isOriginal ? akey : retrieveKeyAtLoc(this, page, loc);
splitLeafAndCreateEntry
(tree, okey, akey, vfrag, value, encodedLen, pos, false);
return;
}
// Node is already split, and so value is too large.
if (vfrag != 0) {
// FIXME: Can this happen?
throw new DatabaseException("Fragmented entry doesn't fit");
}
LocalDatabase db = tree.mDatabase;
int max = Math.min(db.mMaxFragmentedEntrySize,
garbage + leftSpace + rightSpace);
value = db.fragment(value, value.length, max);
if (value == null) {
throw new AssertionError();
}
encodedLen = keyLen + calculateFragmentedValueLength(value);
vfrag = ENTRY_FRAGMENTED;
}
garbage(garbage);
entryLoc = compactLeaf(encodedLen, pos, false);
page = mPage;
entryLoc = isOriginal ? encodeNormalKey(akey, page, entryLoc)
: encodeFragmentedKey(akey, page, entryLoc);
copyToLeafValue(page, vfrag, value, entryLoc);
return;
}
int vecLen = searchVecEnd - searchVecStart + 2;
int newSearchVecStart;
if (remaining > 0 || (rightSegTail() & 1) != 0) {
// Re-center search vector, biased to the right, ensuring proper alignment.
newSearchVecStart = (rightSegTail() - vecLen + (1 - 0) - (remaining >> 1)) & ~1;
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if ((leftSegTail() & 1) == 0) {
// Move search vector left, ensuring proper alignment.
newSearchVecStart = leftSegTail() + ((remaining >> 1) & ~1);
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// Search vector is misaligned, so do full compaction.
byte[][] akeyRef = new byte[1][];
int loc = p_ushortGetLE(page, searchVecStart + pos);
boolean isOriginal = retrieveActualKeyAtLoc(page, loc, akeyRef);
byte[] akey = akeyRef[0];
garbage(garbage);
entryLoc = compactLeaf(encodedLen, pos, false);
page = mPage;
entryLoc = isOriginal ? encodeNormalKey(akey, page, entryLoc)
: encodeFragmentedKey(akey, page, entryLoc);
copyToLeafValue(page, vfrag, value, entryLoc);
return;
}
p_copy(page, searchVecStart, page, newSearchVecStart, vecLen);
pos += newSearchVecStart;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart + vecLen - 2);
} catch (Throwable e) {
if (vfrag == ENTRY_FRAGMENTED && vfragOriginal != ENTRY_FRAGMENTED) {
cleanupFragments(e, value);
}
throw e;
}
// Copy existing key, and then copy value.
p_copy(page, start, page, entryLoc, keyLen);
copyToLeafValue(page, vfrag, value, entryLoc + keyLen);
p_shortPutLE(page, pos, entryLoc);
garbage(garbage);
}
/**
* Update an internal node key to be larger than what is currently allocated. Caller must
* ensure that node has enough space available and that it's not split. New key must not
* force this node to split. Key MUST be a normal, non-fragmented key.
*
* @param pos must be positive
* @param growth key size growth
* @param key normal unencoded key
*/
void updateInternalKey(int pos, int growth, byte[] key, int encodedLen) {
int entryLoc = doUpdateInternalKey(pos, growth, encodedLen);
encodeNormalKey(key, mPage, entryLoc);
}
/**
* Update an internal node key to be larger than what is currently allocated. Caller must
* ensure that node has enough space available and that it's not split. New key must not
* force this node to split.
*
* @param pos must be positive
* @param growth key size growth
* @param key page with encoded key
* @param keyStart encoded key start; includes header
*/
void updateInternalKeyEncoded(int pos, int growth,
/*P*/ byte[] key, int keyStart, int encodedLen)
{
int entryLoc = doUpdateInternalKey(pos, growth, encodedLen);
p_copy(key, keyStart, mPage, entryLoc, encodedLen);
}
/**
* @return entryLoc
*/
int doUpdateInternalKey(int pos, final int growth, final int encodedLen) {
int garbage = garbage() + encodedLen - growth;
// What follows is similar to createInternalEntry method, except the search
// vector doesn't grow.
int searchVecStart = searchVecStart();
int searchVecEnd = searchVecEnd();
int leftSpace = searchVecStart - leftSegTail();
int rightSpace = rightSegTail() - searchVecEnd
- ((searchVecEnd - searchVecStart) << 2) - 17;
int entryLoc;
alloc: {
if ((entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0) {
pos += searchVecStart;
break alloc;
}
makeRoom: {
// Compute remaining space surrounding search vector after update completes.
int remaining = leftSpace + rightSpace - encodedLen;
if (garbage > remaining) {
// Do full compaction and free up the garbage.
if ((garbage + remaining) < 0) {
// New key doesn't fit.
throw new AssertionError();
}
break makeRoom;
}
int vecLen = searchVecEnd - searchVecStart + 2;
int childIdsLen = (vecLen << 2) + 8;
int newSearchVecStart;
if (remaining > 0 || (rightSegTail() & 1) != 0) {
// Re-center search vector, biased to the right, ensuring proper alignment.
newSearchVecStart =
(rightSegTail() - vecLen - childIdsLen + (1 - 0) - (remaining >> 1)) & ~1;
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if ((leftSegTail() & 1) == 0) {
// Move search vector left, ensuring proper alignment.
newSearchVecStart = leftSegTail() + ((remaining >> 1) & ~1);
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// Search vector is misaligned, so do full compaction.
break makeRoom;
}
/*P*/ byte[] page = mPage;
p_copy(page, searchVecStart, page, newSearchVecStart, vecLen + childIdsLen);
pos += newSearchVecStart;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart + vecLen - 2);
break alloc;
}
// This point is reached for making room via node compaction.
garbage(garbage);
InResult result = new InResult();
compactInternal(result, encodedLen, pos, Integer.MIN_VALUE);
return result.mEntryLoc;
}
// Point to entry. Caller must copy the key to the location.
p_shortPutLE(mPage, pos, entryLoc);
garbage(garbage);
return entryLoc;
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
void updateChildRefId(int pos, long id) {
p_longPutLE(mPage, searchVecEnd() + 2 + (pos << 2), id);
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
void deleteLeafEntry(int pos) throws IOException {
final /*P*/ byte[] page = mPage;
int searchVecStart = searchVecStart();
final int entryLoc = p_ushortGetLE(page, searchVecStart + pos);
// Note: Similar to leafEntryLengthAtLoc and retrieveLeafValueAtLoc.
int loc = entryLoc;
{
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
loc += keyLen + 1;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
getDatabase().deleteFragments(page, loc, keyLen);
}
loc += keyLen;
}
}
int header = p_byteGet(page, loc++);
if (header >= 0) {
loc += header;
} else largeValue: {
int len;
if ((header & 0x20) == 0) {
len = 1 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (header != -1) {
len = 1 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
break largeValue;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
getDatabase().deleteFragments(page, loc, len);
}
loc += len;
}
doDeleteLeafEntry(pos, loc - entryLoc);
}
void doDeleteLeafEntry(int pos, int entryLen) {
// Increment garbage by the size of the encoded entry.
garbage(garbage() + entryLen);
/*P*/ byte[] page = mPage;
int searchVecStart = searchVecStart();
int searchVecEnd = searchVecEnd();
if (pos < ((searchVecEnd - searchVecStart + 2) >> 1)) {
// Shift left side of search vector to the right.
p_copy(page, searchVecStart, page, searchVecStart += 2, pos);
searchVecStart(searchVecStart);
} else {
// Shift right side of search vector to the left.
pos += searchVecStart;
p_copy(page, pos + 2, page, pos, searchVecEnd - pos);
searchVecEnd(searchVecEnd - 2);
}
}
/**
* Moves all the entries from the right node into the tail of the given
* left node, and then deletes the right node node. Caller must ensure that
* left node has enough room, and that both nodes are latched exclusively.
* Caller must also hold commit lock. The right node is always released as
* a side effect, but left node is never released by this method.
*/
static void moveLeafToLeftAndDelete(Tree tree, Node leftNode, Node rightNode)
throws IOException
{
tree.mDatabase.prepareToDelete(rightNode);
final /*P*/ byte[] rightPage = rightNode.mPage;
final int searchVecEnd = rightNode.searchVecEnd();
final int leftEndPos = leftNode.highestLeafPos() + 2;
int searchVecStart = rightNode.searchVecStart();
while (searchVecStart <= searchVecEnd) {
int entryLoc = p_ushortGetLE(rightPage, searchVecStart);
int encodedLen = leafEntryLengthAtLoc(rightPage, entryLoc);
int leftEntryLoc = leftNode.createLeafEntry
(null, tree, leftNode.highestLeafPos() + 2, encodedLen);
// Note: Must access left page each time, since compaction can replace it.
p_copy(rightPage, entryLoc, leftNode.mPage, leftEntryLoc, encodedLen);
searchVecStart += 2;
}
// All cursors in the right node must be moved to the left node.
for (TreeCursorFrame frame = rightNode.mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
frame.rebind(leftNode, framePos + (framePos < 0 ? (-leftEndPos) : leftEndPos));
frame = prev;
}
// If right node was high extremity, left node now is.
leftNode.type((byte) (leftNode.type() | (rightNode.type() & HIGH_EXTREMITY)));
tree.mDatabase.deleteNode(rightNode);
}
/**
* Moves all the entries from the right node into the tail of the given
* left node, and then deletes the right node node. Caller must ensure that
* left node has enough room, and that both nodes are latched exclusively.
* Caller must also hold commit lock. The right node is always released as
* a side effect, but left node is never released by this method.
*
* @param parentPage source of entry to merge from parent
* @param parentLoc location of parent entry
* @param parentLen length of parent entry
*/
static void moveInternalToLeftAndDelete(Tree tree, Node leftNode, Node rightNode,
/*P*/ byte[] parentPage, int parentLoc, int parentLen)
throws IOException
{
tree.mDatabase.prepareToDelete(rightNode);
// Create space to absorb parent key.
int leftEndPos = leftNode.highestInternalPos();
InResult result = new InResult();
leftNode.createInternalEntry
(null, result, tree, leftEndPos, parentLen, (leftEndPos += 2) << 2, false);
// Copy child id associated with parent key.
final /*P*/ byte[] rightPage = rightNode.mPage;
int rightChildIdsLoc = rightNode.searchVecEnd() + 2;
p_copy(rightPage, rightChildIdsLoc, result.mPage, result.mNewChildLoc, 8);
rightChildIdsLoc += 8;
// Write parent key.
p_copy(parentPage, parentLoc, result.mPage, result.mEntryLoc, parentLen);
final int searchVecEnd = rightNode.searchVecEnd();
int searchVecStart = rightNode.searchVecStart();
while (searchVecStart <= searchVecEnd) {
int entryLoc = p_ushortGetLE(rightPage, searchVecStart);
int encodedLen = keyLengthAtLoc(rightPage, entryLoc);
// Allocate entry for left node.
int pos = leftNode.highestInternalPos();
leftNode.createInternalEntry
(null, result, tree, pos, encodedLen, (pos + 2) << 2, false);
// Copy child id.
p_copy(rightPage, rightChildIdsLoc, result.mPage, result.mNewChildLoc, 8);
rightChildIdsLoc += 8;
// Copy key.
// Note: Must access left page each time, since compaction can replace it.
p_copy(rightPage, entryLoc, result.mPage, result.mEntryLoc, encodedLen);
searchVecStart += 2;
}
// All cursors in the right node must be moved to the left node.
for (TreeCursorFrame frame = rightNode.mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
frame.rebind(leftNode, leftEndPos + framePos);
frame = prev;
}
// If right node was high extremity, left node now is.
leftNode.type((byte) (leftNode.type() | (rightNode.type() & HIGH_EXTREMITY)));
tree.mDatabase.deleteNode(rightNode);
}
/**
* Delete a parent reference to a right child which merged left.
*
* @param childPos non-zero two-based position of the right child
*/
void deleteRightChildRef(int childPos) {
// Fix affected cursors.
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
int framePos = frame.mNodePos;
if (framePos >= childPos) {
frame.mNodePos = framePos - 2;
}
frame = frame.mPrevCousin;
}
deleteChildRef(childPos);
}
/**
* Delete a parent reference to a left child which merged right.
*
* @param childPos two-based position of the left child
*/
void deleteLeftChildRef(int childPos) {
// Fix affected cursors.
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
int framePos = frame.mNodePos;
if (framePos > childPos) {
frame.mNodePos = framePos - 2;
}
frame = frame.mPrevCousin;
}
deleteChildRef(childPos);
}
/**
* Delete a parent reference to child, but doesn't fix any affected cursors.
*
* @param childPos two-based position
*/
private void deleteChildRef(int childPos) {
final /*P*/ byte[] page = mPage;
int keyPos = childPos == 0 ? 0 : (childPos - 2);
int searchVecStart = searchVecStart();
int entryLoc = p_ushortGetLE(page, searchVecStart + keyPos);
// Increment garbage by the size of the encoded entry.
garbage(garbage() + keyLengthAtLoc(page, entryLoc));
// Rescale for long ids as encoded in page.
childPos <<= 2;
int searchVecEnd = searchVecEnd();
// Remove search vector entry (2 bytes) and remove child id entry
// (8 bytes). Determine which shift operations minimize movement.
if (childPos < (3 * (searchVecEnd - searchVecStart) + keyPos + 8) >> 1) {
// Shift child ids right by 8, shift search vector right by 10.
p_copy(page, searchVecStart + keyPos + 2,
page, searchVecStart + keyPos + (2 + 8),
searchVecEnd - searchVecStart - keyPos + childPos);
p_copy(page, searchVecStart, page, searchVecStart += 10, keyPos);
searchVecEnd(searchVecEnd + 8);
} else {
// Shift child ids left by 8, shift search vector right by 2.
p_copy(page, searchVecEnd + childPos + (2 + 8),
page, searchVecEnd + childPos + 2,
((searchVecEnd - searchVecStart) << 2) + 8 - childPos);
p_copy(page, searchVecStart, page, searchVecStart += 2, keyPos);
}
searchVecStart(searchVecStart);
}
/**
* Delete this non-leaf root node, after all keys have been deleted. The
* state of the lone child is swapped with this root node, and the child
* node is repurposed into a stub root node. The old page used by the child
* node is deleted. This design allows active cursors to still function
* normally until they can unbind.
*
* <p>Caller must hold exclusive latches for root node and lone child.
* Caller must also ensure that both nodes are not splitting. No latches
* are released by this method.
*/
void rootDelete(Tree tree, Node child) throws IOException {
tree.mDatabase.prepareToDelete(child);
/*P*/ byte[] rootPage = mPage;
long toDelete = child.mId;
int toDeleteState = child.mCachedState;
byte stubType = type();
/*P*/ // [
mPage = child.mPage;
type(child.type());
garbage(child.garbage());
leftSegTail(child.leftSegTail());
rightSegTail(child.rightSegTail());
searchVecStart(child.searchVecStart());
searchVecEnd(child.searchVecEnd());
/*P*/ // |
/*P*/ // if (tree.mDatabase.mFullyMapped) {
/*P*/ // // Page cannot change, so copy it instead.
/*P*/ // p_copy(child.mPage, 0, rootPage, 0, tree.mDatabase.pageSize());
/*P*/ // rootPage = child.mPage;
/*P*/ // } else {
/*P*/ // mPage = child.mPage;
/*P*/ // }
/*P*/ // ]
// Repurpose the child node into a stub root node. Stub is assigned a
// reserved id (1) and a clean cached state. It cannot be marked dirty,
// but it can be evicted when all cursors have unbound from it.
tree.mDatabase.nodeMapRemove(child, Long.hashCode(toDelete));
child.mPage = rootPage;
child.mId = STUB_ID;
child.mCachedState = CACHED_CLEAN;
child.type(stubType);
child.clearEntries();
// Search vector also needs to point to root.
p_longPutLE(rootPage, child.searchVecEnd() + 2, this.mId);
// Lock the last frames, preventing concurrent unbinding of those frames...
TreeCursorFrame lock = new TreeCursorFrame();
TreeCursorFrame childLastFrame = child.lockLastFrame(lock);
TreeCursorFrame thisLastFrame = this.lockLastFrame(lock);
// ...now they can be swapped...
if (!TreeCursorFrame.cLastUpdater.compareAndSet(this, thisLastFrame, childLastFrame)) {
throw new AssertionError();
}
if (!TreeCursorFrame.cLastUpdater.compareAndSet(child, childLastFrame, thisLastFrame)) {
throw new AssertionError();
}
// ...and now unlock them. Next reference of last frame is always itself.
childLastFrame.unlock(childLastFrame);
thisLastFrame.unlock(thisLastFrame);
this.fixFrameBindings(lock);
child.fixFrameBindings(lock);
tree.addStub(child, toDelete);
// The page can be deleted earlier in the method, but doing it here
// might prevent corruption if an unexpected exception occurs.
tree.mDatabase.deletePage(toDelete, toDeleteState);
}
/**
* Lock the last frame, for use by the rootDelete method.
*/
private TreeCursorFrame lockLastFrame(TreeCursorFrame lock) {
for (TreeCursorFrame f = mLastCursorFrame; f != null; f = f.mPrevCousin) {
if (f.tryLock(lock) != null) {
return f;
}
}
throw new AssertionError();
}
/**
* Bind all the frames of this node, to this node, for use by the rootDelete method.
*/
private void fixFrameBindings(TreeCursorFrame lock) {
for (TreeCursorFrame f = mLastCursorFrame; f != null; f = f.mPrevCousin) {
TreeCursorFrame lockResult = f.tryLock(lock);
if (lockResult != null) {
f.mNode = this;
f.unlock(lockResult);
}
}
}
private static final int SMALL_KEY_LIMIT = 128;
/**
* Calculate encoded key length, including header. Returns -1 if key is too large and must
* be fragmented.
*/
private static int calculateAllowedKeyLength(Tree tree, byte[] key) {
int len = key.length - 1;
if ((len & ~(SMALL_KEY_LIMIT - 1)) == 0) {
// Always safe because minimum node size is 512 bytes.
return len + 2;
} else {
len++;
return len > tree.mMaxKeySize ? -1 : len + 2;
}
}
/**
* Calculate encoded key length, including header. Key must fit in the node or have been
* fragmented.
*/
static int calculateKeyLength(byte[] key) {
int len = key.length - 1;
return len + ((len & ~(SMALL_KEY_LIMIT - 1)) == 0 ? 2 : 3);
}
/**
* Calculate encoded value length for leaf, including header. Value must fit in the node or
* have been fragmented.
*/
private static int calculateLeafValueLength(byte[] value) {
int len = value.length;
return len + ((len <= 127) ? 1 : ((len <= 8192) ? 2 : 3));
}
/**
* Calculate encoded value length for leaf, including header. Value must fit in the node or
* have been fragmented.
*/
private static long calculateLeafValueLength(long vlength) {
return vlength + ((vlength <= 127) ? 1 : ((vlength <= 8192) ? 2 : 3));
}
/**
* Calculate encoded value length for leaf, including header.
*/
private static int calculateFragmentedValueLength(byte[] value) {
return calculateFragmentedValueLength(value.length);
}
/**
* Calculate encoded value length for leaf, including header.
*/
static int calculateFragmentedValueLength(int vlength) {
return vlength + ((vlength <= 8192) ? 2 : 3);
}
/**
* @param key unencoded key
* @param page destination for encoded key, with room for key header
* @return updated pageLoc
*/
static int encodeNormalKey(final byte[] key, final /*P*/ byte[] page, int pageLoc) {
final int keyLen = key.length;
if (keyLen <= SMALL_KEY_LIMIT && keyLen > 0) {
p_bytePut(page, pageLoc++, keyLen - 1);
} else {
p_bytePut(page, pageLoc++, 0x80 | (keyLen >> 8));
p_bytePut(page, pageLoc++, keyLen);
}
p_copyFromArray(key, 0, page, pageLoc, keyLen);
return pageLoc + keyLen;
}
/**
* @param key fragmented key
* @param page destination for encoded key, with room for key header
* @return updated pageLoc
*/
static int encodeFragmentedKey(final byte[] key, final /*P*/ byte[] page, int pageLoc) {
final int keyLen = key.length;
p_bytePut(page, pageLoc++, (0x80 | ENTRY_FRAGMENTED) | (keyLen >> 8));
p_bytePut(page, pageLoc++, keyLen);
p_copyFromArray(key, 0, page, pageLoc, keyLen);
return pageLoc + keyLen;
}
/**
* @return -1 if not enough contiguous space surrounding search vector
*/
private int allocPageEntry(int encodedLen, int leftSpace, int rightSpace) {
final int entryLoc;
if (encodedLen <= leftSpace && leftSpace >= rightSpace) {
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if (encodedLen <= rightSpace) {
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// No room.
return -1;
}
return entryLoc;
}
/**
* @param okey original key
* @param akey key to actually store
* @param vfrag 0 or ENTRY_FRAGMENTED
*/
private void copyToLeafEntry(byte[] okey, byte[] akey, int vfrag, byte[] value, int entryLoc) {
final /*P*/ byte[] page = mPage;
int vloc = okey == akey ? encodeNormalKey(akey, page, entryLoc)
: encodeFragmentedKey(akey, page, entryLoc);
copyToLeafValue(page, vfrag, value, vloc);
}
/**
* @param vfrag 0 or ENTRY_FRAGMENTED
* @return page location for first byte of value (first location after header)
*/
private static int copyToLeafValue(/*P*/ byte[] page, int vfrag, byte[] value, int vloc) {
final int vlen = value.length;
vloc = encodeLeafValueHeader(page, vfrag, vlen, vloc);
p_copyFromArray(value, 0, page, vloc, vlen);
return vloc;
}
/**
* @param vfrag 0 or ENTRY_FRAGMENTED
* @return page location for first byte of value (first location after header)
*/
static int encodeLeafValueHeader(/*P*/ byte[] page, int vfrag, int vlen, int vloc) {
if (vlen <= 127 && vfrag == 0) {
p_bytePut(page, vloc++, vlen);
} else {
vlen--;
if (vlen <= 8192) {
p_bytePut(page, vloc++, 0x80 | vfrag | (vlen >> 8));
p_bytePut(page, vloc++, vlen);
} else {
p_bytePut(page, vloc++, 0xa0 | vfrag | (vlen >> 16));
p_bytePut(page, vloc++, vlen >> 8);
p_bytePut(page, vloc++, vlen);
}
}
return vloc;
}
/**
* Compact leaf by reclaiming garbage and moving search vector towards
* tail. Caller is responsible for ensuring that new entry will fit after
* compaction. Space is allocated for new entry, and the search vector
* points to it.
*
* @param encodedLen length of new entry to allocate
* @param pos normalized search vector position of entry to insert/update
* @return location for newly allocated entry, already pointed to by search vector
*/
private int compactLeaf(int encodedLen, int pos, boolean forInsert) {
/*P*/ byte[] page = mPage;
int searchVecLoc = searchVecStart();
// Size of search vector, possibly with new entry.
int newSearchVecSize = searchVecEnd() - searchVecLoc + 2;
if (forInsert) {
newSearchVecSize += 2;
}
pos += searchVecLoc;
// Determine new location of search vector, with room to grow on both ends.
int newSearchVecStart;
// Capacity available to search vector after compaction.
int searchVecCap = garbage() + rightSegTail() + 1 - leftSegTail() - encodedLen;
newSearchVecStart = pageSize(page) - (((searchVecCap + newSearchVecSize) >> 1) & ~1);
// Copy into a fresh buffer.
int destLoc = TN_HEADER_SIZE;
int newSearchVecLoc = newSearchVecStart;
int newLoc = 0;
final int searchVecEnd = searchVecEnd();
LocalDatabase db = getDatabase();
/*P*/ byte[] dest = db.removeSparePage();
/*P*/ // [|
/*P*/ // p_intPutLE(dest, 0, type() & 0xff); // set type, reserved byte, and garbage
/*P*/ // ]
for (; searchVecLoc <= searchVecEnd; searchVecLoc += 2, newSearchVecLoc += 2) {
if (searchVecLoc == pos) {
newLoc = newSearchVecLoc;
if (forInsert) {
newSearchVecLoc += 2;
} else {
continue;
}
}
p_shortPutLE(dest, newSearchVecLoc, destLoc);
int sourceLoc = p_ushortGetLE(page, searchVecLoc);
int len = leafEntryLengthAtLoc(page, sourceLoc);
p_copy(page, sourceLoc, dest, destLoc, len);
destLoc += len;
}
/*P*/ // [
// Recycle old page buffer and swap in compacted page.
db.addSparePage(page);
mPage = dest;
garbage(0);
/*P*/ // |
/*P*/ // if (db.mFullyMapped) {
/*P*/ // // Copy compacted entries to original page and recycle spare page buffer.
/*P*/ // p_copy(dest, 0, page, 0, pageSize(page));
/*P*/ // db.addSparePage(dest);
/*P*/ // dest = page;
/*P*/ // } else {
/*P*/ // // Recycle old page buffer and swap in compacted page.
/*P*/ // db.addSparePage(page);
/*P*/ // mPage = dest;
/*P*/ // }
/*P*/ // ]
// Write pointer to new allocation.
p_shortPutLE(dest, newLoc == 0 ? newSearchVecLoc : newLoc, destLoc);
leftSegTail(destLoc + encodedLen);
rightSegTail(pageSize(dest) - 1);
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart + newSearchVecSize - 2);
return destLoc;
}
private void cleanupSplit(Throwable cause, Node newNode, Split split) {
if (split != null) {
cleanupFragments(cause, split.fragmentedKey());
}
try {
getDatabase().deleteNode(newNode, true);
} catch (Throwable e) {
cause.addSuppressed(e);
panic(cause);
}
}
/**
* @param okey original key
* @param akey key to actually store
* @param vfrag 0 or ENTRY_FRAGMENTED
* @param encodedLen length of new entry to allocate
* @param pos normalized search vector position of entry to insert/update
*/
private void splitLeafAndCreateEntry(Tree tree, byte[] okey, byte[] akey,
int vfrag, byte[] value,
int encodedLen, int pos, boolean forInsert)
throws IOException
{
if (mSplit != null) {
throw new AssertionError("Node is already split");
}
// Split can move node entries to a new left or right node. Choose such that the
// new entry is more likely to go into the new node. This distributes the cost of
// the split by postponing compaction of this node.
// Since the split key and final node sizes are not known in advance, don't
// attempt to properly center the new search vector. Instead, minimize
// fragmentation to ensure that split is successful.
/*P*/ byte[] page = mPage;
if (page == p_closedTreePage()) {
// Node is a closed tree root.
throw new ClosedIndexException();
}
Node newNode = tree.mDatabase.allocDirtyNode(NodeUsageList.MODE_UNEVICTABLE);
tree.mDatabase.nodeMapPut(newNode);
/*P*/ byte[] newPage = newNode.mPage;
/*P*/ // [
newNode.garbage(0);
/*P*/ // |
/*P*/ // p_intPutLE(newPage, 0, 0); // set type (fixed later), reserved byte, and garbage
/*P*/ // ]
if (forInsert && pos == 0) {
// Inserting into left edge of node, possibly because inserts are
// descending. Split into new left node, but only the new entry
// goes into the new node.
Split split = null;
try {
split = newSplitLeft(newNode);
// Choose an appropriate middle key for suffix compression.
setSplitKey(tree, split, midKey(okey, 0));
} catch (Throwable e) {
cleanupSplit(e, newNode, split);
throw e;
}
mSplit = split;
// Position search vector at extreme left, allowing new entries to
// be placed in a natural descending order.
newNode.leftSegTail(TN_HEADER_SIZE);
newNode.searchVecStart(TN_HEADER_SIZE);
newNode.searchVecEnd(TN_HEADER_SIZE);
int destLoc = pageSize(newPage) - encodedLen;
newNode.copyToLeafEntry(okey, akey, vfrag, value, destLoc);
p_shortPutLE(newPage, TN_HEADER_SIZE, destLoc);
newNode.rightSegTail(destLoc - 1);
newNode.releaseExclusive();
return;
}
final int searchVecStart = searchVecStart();
final int searchVecEnd = searchVecEnd();
pos += searchVecStart;
if (forInsert && pos == searchVecEnd + 2) {
// Inserting into right edge of node, possibly because inserts are
// ascending. Split into new right node, but only the new entry
// goes into the new node.
Split split = null;
try {
split = newSplitRight(newNode);
// Choose an appropriate middle key for suffix compression.
setSplitKey(tree, split, midKey(pos - searchVecStart - 2, okey));
} catch (Throwable e) {
cleanupSplit(e, newNode, split);
throw e;
}
mSplit = split;
// Position search vector at extreme right, allowing new entries to
// be placed in a natural ascending order.
newNode.rightSegTail(pageSize(newPage) - 1);
int newSearchVecStart = pageSize(newPage) - 2;
newNode.searchVecStart(newSearchVecStart);
newNode.searchVecEnd(newSearchVecStart);
newNode.copyToLeafEntry(okey, akey, vfrag, value, TN_HEADER_SIZE);
p_shortPutLE(newPage, pageSize(newPage) - 2, TN_HEADER_SIZE);
newNode.leftSegTail(TN_HEADER_SIZE + encodedLen);
newNode.releaseExclusive();
return;
}
// Amount of bytes available in unsplit node.
int avail = availableLeafBytes();
int garbageAccum = 0;
int newLoc = 0;
int newAvail = pageSize(newPage) - TN_HEADER_SIZE;
// Guess which way to split by examining search position. This doesn't take into
// consideration the variable size of the entries. If the guess is wrong, the new
// entry is inserted into original node, which now has space.
if ((pos - searchVecStart) < (searchVecEnd - pos)) {
// Split into new left node.
int destLoc = pageSize(newPage);
int newSearchVecLoc = TN_HEADER_SIZE;
int searchVecLoc = searchVecStart;
for (; newAvail > avail; searchVecLoc += 2, newSearchVecLoc += 2) {
int entryLoc = p_ushortGetLE(page, searchVecLoc);
int entryLen = leafEntryLengthAtLoc(page, entryLoc);
if (searchVecLoc == pos) {
if ((newAvail -= encodedLen + 2) < 0) {
// Entry doesn't fit into new node.
break;
}
newLoc = newSearchVecLoc;
if (forInsert) {
// Reserve slot in vector for new entry.
newSearchVecLoc += 2;
if (newAvail <= avail) {
// Balanced enough.
break;
}
} else {
// Don't copy old entry.
garbageAccum += entryLen;
avail += entryLen;
continue;
}
}
if ((newAvail -= entryLen + 2) < 0) {
// Entry doesn't fit into new node.
break;
}
// Copy entry and point to it.
destLoc -= entryLen;
p_copy(page, entryLoc, newPage, destLoc, entryLen);
p_shortPutLE(newPage, newSearchVecLoc, destLoc);
garbageAccum += entryLen;
avail += entryLen + 2;
}
newNode.leftSegTail(TN_HEADER_SIZE);
newNode.searchVecStart(TN_HEADER_SIZE);
newNode.searchVecEnd(newSearchVecLoc - 2);
// Prune off the left end of this node.
final int originalStart = searchVecStart();
final int originalGarbage = garbage();
searchVecStart(searchVecLoc);
garbage(originalGarbage + garbageAccum);
Split split = null;
byte[] fv = null;
try {
split = newSplitLeft(newNode);
if (newLoc == 0) {
// Unable to insert new entry into left node. Insert it
// into the right node, which should have space now.
fv = storeIntoSplitLeaf(tree, okey, akey, vfrag, value, encodedLen, forInsert);
} else {
// Create new entry and point to it.
destLoc -= encodedLen;
newNode.copyToLeafEntry(okey, akey, vfrag, value, destLoc);
p_shortPutLE(newPage, newLoc, destLoc);
}
// Choose an appropriate middle key for suffix compression.
setSplitKey(tree, split, newNode.midKey(newNode.highestKeyPos(), this, 0));
newNode.rightSegTail(destLoc - 1);
newNode.releaseExclusive();
} catch (Throwable e) {
searchVecStart(originalStart);
garbage(originalGarbage);
cleanupFragments(e, fv);
cleanupSplit(e, newNode, split);
throw e;
}
mSplit = split;
} else {
// Split into new right node.
int destLoc = TN_HEADER_SIZE;
int newSearchVecLoc = pageSize(newPage) - 2;
int searchVecLoc = searchVecEnd;
for (; newAvail > avail; searchVecLoc -= 2, newSearchVecLoc -= 2) {
int entryLoc = p_ushortGetLE(page, searchVecLoc);
int entryLen = leafEntryLengthAtLoc(page, entryLoc);
if (forInsert) {
if (searchVecLoc + 2 == pos) {
if ((newAvail -= encodedLen + 2) < 0) {
// Inserted entry doesn't fit into new node.
break;
}
// Reserve spot in vector for new entry.
newLoc = newSearchVecLoc;
newSearchVecLoc -= 2;
if (newAvail <= avail) {
// Balanced enough.
break;
}
}
} else {
if (searchVecLoc == pos) {
if ((newAvail -= encodedLen + 2) < 0) {
// Updated entry doesn't fit into new node.
break;
}
// Don't copy old entry.
newLoc = newSearchVecLoc;
garbageAccum += entryLen;
avail += entryLen;
continue;
}
}
if ((newAvail -= entryLen + 2) < 0) {
// Entry doesn't fit into new node.
break;
}
// Copy entry and point to it.
p_copy(page, entryLoc, newPage, destLoc, entryLen);
p_shortPutLE(newPage, newSearchVecLoc, destLoc);
destLoc += entryLen;
garbageAccum += entryLen;
avail += entryLen + 2;
}
newNode.rightSegTail(pageSize(newPage) - 1);
newNode.searchVecStart(newSearchVecLoc + 2);
newNode.searchVecEnd(pageSize(newPage) - 2);
// Prune off the right end of this node.
final int originalEnd = searchVecEnd();
final int originalGarbage = garbage();
searchVecEnd(searchVecLoc);
garbage(originalGarbage + garbageAccum);
Split split = null;
byte[] fv = null;
try {
split = newSplitRight(newNode);
if (newLoc == 0) {
// Unable to insert new entry into new right node. Insert
// it into the left node, which should have space now.
fv = storeIntoSplitLeaf(tree, okey, akey, vfrag, value, encodedLen, forInsert);
} else {
// Create new entry and point to it.
newNode.copyToLeafEntry(okey, akey, vfrag, value, destLoc);
p_shortPutLE(newPage, newLoc, destLoc);
destLoc += encodedLen;
}
// Choose an appropriate middle key for suffix compression.
setSplitKey(tree, split, this.midKey(this.highestKeyPos(), newNode, 0));
newNode.leftSegTail(destLoc);
newNode.releaseExclusive();
} catch (Throwable e) {
searchVecEnd(originalEnd);
garbage(originalGarbage);
cleanupFragments(e, fv);
cleanupSplit(e, newNode, split);
throw e;
}
mSplit = split;
}
}
/**
* Store an entry into a node which has just been split and has room.
*
* @param okey original key
* @param akey key to actually store
* @param vfrag 0 or ENTRY_FRAGMENTED
* @return non-null if value got fragmented
*/
private byte[] storeIntoSplitLeaf(Tree tree, byte[] okey, byte[] akey,
int vfrag, byte[] value,
int encodedLen, boolean forInsert)
throws IOException
{
int pos = binarySearch(okey);
if (forInsert) {
if (pos >= 0) {
throw new AssertionError("Key exists");
}
int entryLoc = createLeafEntry(null, tree, ~pos, encodedLen);
byte[] result = null;
while (entryLoc < 0) {
if (vfrag != 0) {
// FIXME: Can this happen?
throw new DatabaseException("Fragmented entry doesn't fit");
}
LocalDatabase db = tree.mDatabase;
int max = Math.min(~entryLoc, db.mMaxFragmentedEntrySize);
int encodedKeyLen = calculateKeyLength(akey);
value = db.fragment(value, value.length, max - encodedKeyLen);
if (value == null) {
throw new AssertionError();
}
result = value;
vfrag = ENTRY_FRAGMENTED;
encodedLen = encodedKeyLen + calculateFragmentedValueLength(value);
entryLoc = createLeafEntry(null, tree, ~pos, encodedLen);
}
copyToLeafEntry(okey, akey, vfrag, value, entryLoc);
return result;
} else {
if (pos < 0) {
throw new AssertionError("Key not found");
}
updateLeafValue(null, tree, pos, vfrag, value);
return null;
}
}
/**
* @param result split result stored here; key and entry loc is -1 if new key was promoted
* to parent
* @throws IOException if new node could not be allocated; no side-effects
*/
private void splitInternal(final InResult result,
final Tree tree, final int encodedLen,
final int keyPos, final int newChildPos)
throws IOException
{
if (mSplit != null) {
throw new AssertionError("Node is already split");
}
// Split can move node entries to a new left or right node. Choose such that the
// new entry is more likely to go into the new node. This distributes the cost of
// the split by postponing compaction of this node.
// Alloc early in case an exception is thrown.
final LocalDatabase db = getDatabase();
Node newNode;
try {
newNode = db.allocDirtyNode(NodeUsageList.MODE_UNEVICTABLE);
} catch (DatabaseFullException e) {
// Internal node splits are critical. If a child node reference cannot be inserted,
// then it would be orphaned. Try allocating again without any capacity limit, or
// else the caller must panic the database.
db.capacityLimitOverride(-1);
try {
newNode = db.allocDirtyNode(NodeUsageList.MODE_UNEVICTABLE);
} finally {
db.capacityLimitOverride(0);
}
}
db.nodeMapPut(newNode);
final /*P*/ byte[] newPage = newNode.mPage;
/*P*/ // [
newNode.garbage(0);
/*P*/ // |
/*P*/ // p_intPutLE(newPage, 0, 0); // set type (fixed later), reserved byte, and garbage
/*P*/ // ]
final /*P*/ byte[] page = mPage;
final int searchVecStart = searchVecStart();
final int searchVecEnd = searchVecEnd();
if ((searchVecEnd - searchVecStart) == 2 && keyPos == 2) {
// Node has two keys and the key to insert should go in the middle. The new key
// should not be inserted, but instead be promoted to the parent. Treat this as a
// special case -- the code below only promotes an existing key to the parent.
// This case is expected to only occur when using large keys.
// Allocate Split object first, in case it throws an OutOfMemoryError.
Split split;
try {
split = newSplitLeft(newNode);
} catch (Throwable e) {
cleanupSplit(e, newNode, null);
throw e;
}
// Signals that key should not be inserted.
result.mEntryLoc = -1;
int leftKeyLoc = p_ushortGetLE(page, searchVecStart);
int leftKeyLen = keyLengthAtLoc(page, leftKeyLoc);
// Assume a large key will be inserted later, so arrange it with room: entry at far
// left and search vector at far right.
p_copy(page, leftKeyLoc, newPage, TN_HEADER_SIZE, leftKeyLen);
int leftSearchVecStart = pageSize(newPage) - (2 + 8 + 8);
p_shortPutLE(newPage, leftSearchVecStart, TN_HEADER_SIZE);
if (newChildPos == 8) {
// Caller must store child id into left node.
result.mPage = newPage;
result.mNewChildLoc = leftSearchVecStart + (2 + 8);
} else {
if (newChildPos != 16) {
throw new AssertionError();
}
// Caller must store child id into right node.
result.mPage = page;
result.mNewChildLoc = searchVecEnd + (2 + 8);
}
// Copy one or two left existing child ids to left node (newChildPos is 8 or 16).
p_copy(page, searchVecEnd + 2, newPage, leftSearchVecStart + 2, newChildPos);
newNode.leftSegTail(TN_HEADER_SIZE + leftKeyLen);
newNode.rightSegTail(leftSearchVecStart + (2 + 8 + 8 - 1));
newNode.searchVecStart(leftSearchVecStart);
newNode.searchVecEnd(leftSearchVecStart);
newNode.releaseExclusive();
// Prune off the left end of this node by shifting vector towards child ids.
p_copy(page, searchVecEnd, page, searchVecEnd + 8, 2);
int newSearchVecStart = searchVecEnd + 8;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart);
garbage(garbage() + leftKeyLen);
// Caller must set the split key.
mSplit = split;
return;
}
result.mPage = newPage;
final int keyLoc = keyPos + searchVecStart;
int garbageAccum;
int newKeyLoc;
// Guess which way to split by examining search position. This doesn't take into
// consideration the variable size of the entries. If the guess is wrong, do over
// the other way. Internal splits are infrequent, and split guesses are usually
// correct. For these reasons, it isn't worth the trouble to create a special case
// to charge ahead with the wrong guess. Leaf node splits are more frequent, and
// incorrect guesses are easily corrected due to the simpler leaf node structure.
// -2: left
// -1: guess left
// +1: guess right
// +2: right
int splitSide = (keyPos < (searchVecEnd - searchVecStart - keyPos)) ? -1 : 1;
Split split = null;
doSplit: while (true) {
garbageAccum = 0;
newKeyLoc = 0;
// Amount of bytes used in unsplit node, including the page header.
int size = 5 * (searchVecEnd - searchVecStart) + (1 + 8 + 8)
+ leftSegTail() + pageSize(page) - rightSegTail() - garbage();
int newSize = TN_HEADER_SIZE;
// Adjust sizes for extra child id -- always one more than number of keys.
size -= 8;
newSize += 8;
if (splitSide < 0) {
// Split into new left node.
// Since the split key and final node sizes are not known in advance,
// don't attempt to properly center the new search vector. Instead,
// minimize fragmentation to ensure that split is successful.
int destLoc = pageSize(newPage);
int newSearchVecLoc = TN_HEADER_SIZE;
int searchVecLoc = searchVecStart;
while (true) {
if (searchVecLoc == keyLoc) {
newKeyLoc = newSearchVecLoc;
newSearchVecLoc += 2;
// Reserve slot in vector for new entry and account for size increase.
newSize += encodedLen + (2 + 8);
if (newSize > pageSize(newPage)) {
// New entry doesn't fit.
if (splitSide == -1) {
// Guessed wrong; do over on left side.
splitSide = 2;
continue doSplit;
}
// Impossible split. No room for new entry anywhere.
throw new AssertionError();
}
}
int entryLoc = p_ushortGetLE(page, searchVecLoc);
int entryLen = keyLengthAtLoc(page, entryLoc);
// Size change must incorporate child id, although they are copied later.
int sizeChange = entryLen + (2 + 8);
size -= sizeChange;
newSize += sizeChange;
searchVecLoc += 2;
// Note that last examined key is not moved but is dropped. Garbage must
// account for this.
garbageAccum += entryLen;
boolean full = size < TN_HEADER_SIZE | newSize > pageSize(newPage);
if (full || newSize >= size) {
// New node has accumlated enough entries...
if (newKeyLoc != 0) {
// ...and split key has been found.
try {
split = newSplitLeft(newNode);
setSplitKey(tree, split, retrieveKeyAtLoc(page, entryLoc));
} catch (Throwable e) {
cleanupSplit(e, newNode, split);
throw e;
}
break;
}
if (splitSide == -1) {
// Guessed wrong; do over on right side.
splitSide = 2;
continue doSplit;
}
// Keep searching on this side for new entry location.
if (full || splitSide != -2) {
throw new AssertionError();
}
}
// Copy key entry and point to it.
destLoc -= entryLen;
p_copy(page, entryLoc, newPage, destLoc, entryLen);
p_shortPutLE(newPage, newSearchVecLoc, destLoc);
newSearchVecLoc += 2;
}
result.mEntryLoc = destLoc - encodedLen;
// Copy existing child ids and insert new child id.
{
p_copy(page, searchVecEnd + 2, newPage, newSearchVecLoc, newChildPos);
// Leave gap for new child id, to be set by caller.
result.mNewChildLoc = newSearchVecLoc + newChildPos;
int tailChildIdsLen = ((searchVecLoc - searchVecStart) << 2) - newChildPos;
p_copy(page, searchVecEnd + 2 + newChildPos,
newPage, newSearchVecLoc + newChildPos + 8, tailChildIdsLen);
}
newNode.leftSegTail(TN_HEADER_SIZE);
newNode.rightSegTail(destLoc - encodedLen - 1);
newNode.searchVecStart(TN_HEADER_SIZE);
newNode.searchVecEnd(newSearchVecLoc - 2);
newNode.releaseExclusive();
// Prune off the left end of this node by shifting vector towards child ids.
int shift = (searchVecLoc - searchVecStart) << 2;
int len = searchVecEnd - searchVecLoc + 2;
int newSearchVecStart = searchVecLoc + shift;
p_copy(page, searchVecLoc, page, newSearchVecStart, len);
searchVecStart(newSearchVecStart);
searchVecEnd(searchVecEnd + shift);
} else {
// Split into new right node.
// First copy keys and not the child ids. After keys are copied, shift to
// make room for child ids and copy them in place.
int destLoc = TN_HEADER_SIZE;
int newSearchVecLoc = pageSize(newPage);
int searchVecLoc = searchVecEnd + 2;
moveEntries: while (true) {
if (searchVecLoc == keyLoc) {
newSearchVecLoc -= 2;
newKeyLoc = newSearchVecLoc;
// Reserve slot in vector for new entry and account for size increase.
newSize += encodedLen + (2 + 8);
if (newSize > pageSize(newPage)) {
// New entry doesn't fit.
if (splitSide == 1) {
// Guessed wrong; do over on left side.
splitSide = -2;
continue doSplit;
}
// Impossible split. No room for new entry anywhere.
throw new AssertionError();
}
}
searchVecLoc -= 2;
int entryLoc = p_ushortGetLE(page, searchVecLoc);
int entryLen = keyLengthAtLoc(page, entryLoc);
// Size change must incorporate child id, although they are copied later.
int sizeChange = entryLen + (2 + 8);
size -= sizeChange;
newSize += sizeChange;
// Note that last examined key is not moved but is dropped. Garbage must
// account for this.
garbageAccum += entryLen;
boolean full = size < TN_HEADER_SIZE | newSize > pageSize(newPage);
if (full || newSize >= size) {
// New node has accumlated enough entries...
if (newKeyLoc != 0) {
// ...and split key has been found.
try {
split = newSplitRight(newNode);
setSplitKey(tree, split, retrieveKeyAtLoc(page, entryLoc));
} catch (Throwable e) {
cleanupSplit(e, newNode, split);
throw e;
}
break moveEntries;
}
if (splitSide == 1) {
// Guessed wrong; do over on left side.
splitSide = -2;
continue doSplit;
}
// Keep searching on this side for new entry location.
if (full || splitSide != 2) {
throw new AssertionError();
}
}
// Copy key entry and point to it.
p_copy(page, entryLoc, newPage, destLoc, entryLen);
newSearchVecLoc -= 2;
p_shortPutLE(newPage, newSearchVecLoc, destLoc);
destLoc += entryLen;
}
result.mEntryLoc = destLoc;
// Move new search vector to make room for child ids and be centered between
// the segments.
int newVecLen = pageSize(page) - newSearchVecLoc;
{
int highestLoc = pageSize(newPage) - (5 * newVecLen) - 8;
int midLoc = ((destLoc + encodedLen + highestLoc + 1) >> 1) & ~1;
p_copy(newPage, newSearchVecLoc, newPage, midLoc, newVecLen);
newKeyLoc -= newSearchVecLoc - midLoc;
newSearchVecLoc = midLoc;
}
int newSearchVecEnd = newSearchVecLoc + newVecLen - 2;
// Copy existing child ids and insert new child id.
{
int headChildIdsLen = newChildPos - ((searchVecLoc - searchVecStart + 2) << 2);
int newDestLoc = newSearchVecEnd + 2;
p_copy(page, searchVecEnd + 2 + newChildPos - headChildIdsLen,
newPage, newDestLoc, headChildIdsLen);
// Leave gap for new child id, to be set by caller.
newDestLoc += headChildIdsLen;
result.mNewChildLoc = newDestLoc;
int tailChildIdsLen =
((searchVecEnd - searchVecStart) << 2) + 16 - newChildPos;
p_copy(page, searchVecEnd + 2 + newChildPos,
newPage, newDestLoc + 8, tailChildIdsLen);
}
newNode.leftSegTail(destLoc + encodedLen);
newNode.rightSegTail(pageSize(newPage) - 1);
newNode.searchVecStart(newSearchVecLoc);
newNode.searchVecEnd(newSearchVecEnd);
newNode.releaseExclusive();
// Prune off the right end of this node by shifting vector towards child ids.
int len = searchVecLoc - searchVecStart;
int newSearchVecStart = searchVecEnd + 2 - len;
p_copy(page, searchVecStart, page, newSearchVecStart, len);
searchVecStart(newSearchVecStart);
}
break;
} // end doSplit
garbage(garbage() + garbageAccum);
mSplit = split;
// Write pointer to key entry.
p_shortPutLE(newPage, newKeyLoc, result.mEntryLoc);
}
private void setSplitKey(Tree tree, Split split, byte[] fullKey) throws IOException {
byte[] actualKey = fullKey;
if (calculateAllowedKeyLength(tree, fullKey) < 0) {
// Key must be fragmented.
actualKey = tree.fragmentKey(fullKey);
}
split.setKey(fullKey, actualKey);
}
/**
* Compact internal node by reclaiming garbage and moving search vector
* towards tail. Caller is responsible for ensuring that new entry will fit
* after compaction. Space is allocated for new entry, and the search
* vector points to it.
*
* @param result return result stored here
* @param encodedLen length of new entry to allocate
* @param keyPos normalized search vector position of key to insert/update
* @param childPos normalized search vector position of child node id to insert; pass
* MIN_VALUE if updating
*/
private void compactInternal(InResult result, int encodedLen, int keyPos, int childPos) {
/*P*/ byte[] page = mPage;
int searchVecLoc = searchVecStart();
keyPos += searchVecLoc;
// Size of search vector, possibly with new entry.
int newSearchVecSize = searchVecEnd() - searchVecLoc + (2 + 2) + (childPos >> 30);
// Determine new location of search vector, with room to grow on both ends.
int newSearchVecStart;
// Capacity available to search vector after compaction.
int searchVecCap = garbage() + rightSegTail() + 1 - leftSegTail() - encodedLen;
newSearchVecStart = pageSize(page) -
(((searchVecCap + newSearchVecSize + ((newSearchVecSize + 2) << 2)) >> 1) & ~1);
// Copy into a fresh buffer.
int destLoc = TN_HEADER_SIZE;
int newSearchVecLoc = newSearchVecStart;
int newLoc = 0;
final int searchVecEnd = searchVecEnd();
LocalDatabase db = getDatabase();
/*P*/ byte[] dest = db.removeSparePage();
/*P*/ // [|
/*P*/ // p_intPutLE(dest, 0, type() & 0xff); // set type, reserved byte, and garbage
/*P*/ // ]
for (; searchVecLoc <= searchVecEnd; searchVecLoc += 2, newSearchVecLoc += 2) {
if (searchVecLoc == keyPos) {
newLoc = newSearchVecLoc;
if (childPos >= 0) {
newSearchVecLoc += 2;
} else {
continue;
}
}
p_shortPutLE(dest, newSearchVecLoc, destLoc);
int sourceLoc = p_ushortGetLE(page, searchVecLoc);
int len = keyLengthAtLoc(page, sourceLoc);
p_copy(page, sourceLoc, dest, destLoc, len);
destLoc += len;
}
if (childPos >= 0) {
if (newLoc == 0) {
newLoc = newSearchVecLoc;
newSearchVecLoc += 2;
}
// Copy child ids, and leave room for inserted child id.
p_copy(page, searchVecEnd() + 2, dest, newSearchVecLoc, childPos);
p_copy(page, searchVecEnd() + 2 + childPos,
dest, newSearchVecLoc + childPos + 8,
(newSearchVecSize << 2) - childPos);
} else {
if (newLoc == 0) {
newLoc = newSearchVecLoc;
}
// Copy child ids.
p_copy(page, searchVecEnd() + 2, dest, newSearchVecLoc, (newSearchVecSize << 2) + 8);
}
/*P*/ // [
// Recycle old page buffer and swap in compacted page.
db.addSparePage(page);
mPage = dest;
garbage(0);
/*P*/ // |
/*P*/ // if (db.mFullyMapped) {
/*P*/ // // Copy compacted entries to original page and recycle spare page buffer.
/*P*/ // p_copy(dest, 0, page, 0, pageSize(page));
/*P*/ // db.addSparePage(dest);
/*P*/ // dest = page;
/*P*/ // } else {
/*P*/ // // Recycle old page buffer and swap in compacted page.
/*P*/ // db.addSparePage(page);
/*P*/ // mPage = dest;
/*P*/ // }
/*P*/ // ]
// Write pointer to key entry.
p_shortPutLE(dest, newLoc, destLoc);
leftSegTail(destLoc + encodedLen);
rightSegTail(pageSize(dest) - 1);
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecLoc - 2);
result.mPage = dest;
result.mNewChildLoc = newSearchVecLoc + childPos;
result.mEntryLoc = destLoc;
}
/**
* Provides information necessary to complete split by copying split key, pointer to
* split key, and pointer to new child id.
*/
static final class InResult {
/*P*/ byte[] mPage;
int mNewChildLoc; // location of child pointer
int mEntryLoc; // location of key entry, referenced by search vector
}
private Split newSplitLeft(Node newNode) {
Split split = new Split(false, newNode);
// New left node cannot be a high extremity, and this node cannot be a low extremity.
newNode.type((byte) (type() & ~HIGH_EXTREMITY));
type((byte) (type() & ~LOW_EXTREMITY));
return split;
}
private Split newSplitRight(Node newNode) {
Split split = new Split(true, newNode);
// New right node cannot be a low extremity, and this node cannot be a high extremity.
newNode.type((byte) (type() & ~LOW_EXTREMITY));
type((byte) (type() & ~HIGH_EXTREMITY));
return split;
}
/**
* Count the number of cursors bound to this node.
*/
long countCursors() {
// Attempt an exclusive latch to prevent frames from being visited multiple times due
// to recycling.
if (tryAcquireExclusive()) {
long count = 0;
try {
TreeCursorFrame frame = mLastCursorFrame;
while (frame != null) {
count++;
frame = frame.mPrevCousin;
}
} finally {
releaseExclusive();
}
return count;
}
// Iterate over the frames using a lock coupling strategy. Frames which are being
// concurrently removed are skipped over. A shared latch is required to prevent
// observing an in-flight split, which breaks iteration due to rebinding.
acquireShared();
try {
TreeCursorFrame frame = mLastCursorFrame;
if (frame == null) {
return 0;
}
TreeCursorFrame lock = new TreeCursorFrame();
TreeCursorFrame lockResult;
while (true) {
lockResult = frame.tryLock(lock);
if (lockResult != null) {
break;
}
frame = frame.mPrevCousin;
if (frame == null) {
return 0;
}
}
long count = 1;
while (true) {
TreeCursorFrame prev = frame.tryLockPrevious(lock);
frame.unlock(lockResult);
if (prev == null) {
return count;
}
count++;
lockResult = frame;
frame = prev;
}
} finally {
releaseShared();
}
}
/**
* No latches are acquired by this method -- it is only used for debugging.
*/
@Override
@SuppressWarnings("fallthrough")
public String toString() {
String prefix;
switch (type()) {
case TYPE_UNDO_LOG:
return "UndoNode: {id=" + mId +
", cachedState=" + mCachedState +
", topEntry=" + garbage() +
", lowerNodeId=" + + p_longGetLE(mPage, 4) +
", lockState=" + super.toString() +
'}';
/*P*/ // [
case TYPE_FRAGMENT:
return "FragmentNode: {id=" + mId +
", cachedState=" + mCachedState +
", lockState=" + super.toString() +
'}';
/*P*/ // ]
case TYPE_TN_IN:
case (TYPE_TN_IN | LOW_EXTREMITY):
case (TYPE_TN_IN | HIGH_EXTREMITY):
case (TYPE_TN_IN | LOW_EXTREMITY | HIGH_EXTREMITY):
prefix = "Internal";
break;
case TYPE_TN_BIN:
case (TYPE_TN_BIN | LOW_EXTREMITY):
case (TYPE_TN_BIN | HIGH_EXTREMITY):
case (TYPE_TN_BIN | LOW_EXTREMITY | HIGH_EXTREMITY):
prefix = "BottomInternal";
break;
default:
if (!isLeaf()) {
return "Node: {id=" + mId +
", cachedState=" + mCachedState +
", lockState=" + super.toString() +
'}';
}
// Fallthrough...
case TYPE_TN_LEAF:
prefix = "Leaf";
break;
}
return prefix + "Node: {id=" + mId +
", cachedState=" + mCachedState +
", isSplit=" + (mSplit != null) +
", availableBytes=" + availableBytes() +
", extremity=0b" + Integer.toString((type() & (LOW_EXTREMITY | HIGH_EXTREMITY)), 2) +
", lockState=" + super.toString() +
'}';
}
/**
* Caller must acquired shared latch before calling this method. Latch is
* released unless an exception is thrown. If an exception is thrown by the
* observer, the latch would have already been released.
*
* @return false if should stop
*/
boolean verifyTreeNode(int level, VerificationObserver observer) {
int type = type() & ~(LOW_EXTREMITY | HIGH_EXTREMITY);
if (type != TYPE_TN_IN && type != TYPE_TN_BIN && !isLeaf()) {
return verifyFailed(level, observer, "Not a tree node: " + type);
}
final /*P*/ byte[] page = mPage;
if (leftSegTail() < TN_HEADER_SIZE) {
return verifyFailed(level, observer, "Left segment tail: " + leftSegTail());
}
if (searchVecStart() < leftSegTail()) {
return verifyFailed(level, observer, "Search vector start: " + searchVecStart());
}
if (searchVecEnd() < (searchVecStart() - 2)) {
return verifyFailed(level, observer, "Search vector end: " + searchVecEnd());
}
if (rightSegTail() < searchVecEnd() || rightSegTail() > (pageSize(page) - 1)) {
return verifyFailed(level, observer, "Right segment tail: " + rightSegTail());
}
if (!isLeaf()) {
int childIdsStart = searchVecEnd() + 2;
int childIdsEnd = childIdsStart + ((childIdsStart - searchVecStart()) << 2) + 8;
if (childIdsEnd > (rightSegTail() + 1)) {
return verifyFailed(level, observer, "Child ids end: " + childIdsEnd);
}
LHashTable.Int childIds = new LHashTable.Int(512);
for (int i = childIdsStart; i < childIdsEnd; i += 8) {
long childId = p_uint48GetLE(page, i);
if (childId < 0 || childId == 0 || childId == 1) {
return verifyFailed(level, observer, "Illegal child id: " + childId);
}
LHashTable.IntEntry e = childIds.insert(childId);
if (e.value != 0) {
return verifyFailed(level, observer, "Duplicate child id: " + childId);
}
e.value = 1;
}
}
int used = TN_HEADER_SIZE + rightSegTail() + 1 - leftSegTail();
int largeValueCount = 0;
int lastKeyLoc = 0;
int lastKeyLen = 0;
for (int i = searchVecStart(); i <= searchVecEnd(); i += 2) {
int loc = p_ushortGetLE(page, i);
if (loc < TN_HEADER_SIZE || loc >= pageSize(page) ||
(loc >= leftSegTail() && loc <= rightSegTail()))
{
return verifyFailed(level, observer, "Entry location: " + loc);
}
if (isLeaf()) {
used += leafEntryLengthAtLoc(page, loc);
} else {
used += keyLengthAtLoc(page, loc);
}
int keyLen;
try {
keyLen = p_byteGet(page, loc++);
keyLen = keyLen >= 0 ? (keyLen + 1)
: (((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++));
} catch (IndexOutOfBoundsException e) {
return verifyFailed(level, observer, "Key location out of bounds");
}
if (loc + keyLen > pageSize(page)) {
return verifyFailed(level, observer, "Key end location: " + (loc + keyLen));
}
if (lastKeyLoc != 0) {
int result = p_compareKeysPageToPage(page, lastKeyLoc, lastKeyLen,
page, loc, keyLen);
if (result >= 0) {
return verifyFailed(level, observer, "Key order: " + result);
}
}
lastKeyLoc = loc;
lastKeyLoc = keyLen;
if (isLeaf()) value: {
int len;
try {
loc += keyLen;
int header = p_byteGet(page, loc++);
if (header >= 0) {
len = header;
} else {
if ((header & 0x20) == 0) {
len = 1 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (header != -1) {
len = 1 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
break value;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
largeValueCount++;
}
}
} catch (IndexOutOfBoundsException e) {
return verifyFailed(level, observer, "Value location out of bounds");
}
if (loc + len > pageSize(page)) {
return verifyFailed(level, observer, "Value end location: " + (loc + len));
}
}
}
int garbage = pageSize(page) - used;
if (garbage() != garbage) {
return verifyFailed(level, observer, "Garbage: " + garbage() + " != " + garbage);
}
int entryCount = numKeys();
int freeBytes = availableBytes();
long id = mId;
releaseShared();
return observer.indexNodePassed(id, level, entryCount, freeBytes, largeValueCount);
}
private boolean verifyFailed(int level, VerificationObserver observer, String message) {
long id = mId;
releaseShared();
observer.failed = true;
return observer.indexNodeFailed(id, level, message);
}
}
| src/main/java/org/cojen/tupl/Node.java | /*
* Copyright 2011-2015 Cojen.org
*
* 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.cojen.tupl;
import java.io.IOException;
import org.cojen.tupl.util.Latch;
import static org.cojen.tupl.PageOps.*;
import static org.cojen.tupl.Utils.EMPTY_BYTES;
import static org.cojen.tupl.Utils.closeOnFailure;
import static org.cojen.tupl.Utils.compareUnsigned;
import static org.cojen.tupl.Utils.rethrow;
/**
* Node within a B-tree, undo log, or a large value fragment.
*
* @author Brian S O'Neill
*/
@SuppressWarnings("serial")
final class Node extends Latch implements DatabaseAccess {
// Note: Changing these values affects how the Database class handles the
// commit flag. It only needs to flip bit 0 to switch dirty states.
static final byte
CACHED_CLEAN = 0, // 0b0000
CACHED_DIRTY_0 = 2, // 0b0010
CACHED_DIRTY_1 = 3; // 0b0011
/*
Node type encoding strategy:
bits 7..4: major type 0010 (fragment), 0100 (undo log),
0110 (internal), 0111 (bottom internal), 1000 (leaf)
bits 3..1: sub type for leaf: x0x (normal)
for internal: x1x (6 byte child pointer + 2 byte count), x0x (unused)
for both: bit 1 is set if low extremity, bit 3 for high extremity
bit 0: endianness 0 (little), 1 (big)
TN == Tree Node
Note that leaf type is always negative. If type encoding changes, the isLeaf and
isInternal methods might need to be updated.
*/
static final byte
TYPE_NONE = 0,
/*P*/ // [
TYPE_FRAGMENT = (byte) 0x20, // 0b0010_000_0 (never persisted)
/*P*/ // ]
TYPE_UNDO_LOG = (byte) 0x40, // 0b0100_000_0
TYPE_TN_IN = (byte) 0x64, // 0b0110_010_0
TYPE_TN_BIN = (byte) 0x74, // 0b0111_010_0
TYPE_TN_LEAF = (byte) 0x80; // 0b1000_000_0
static final byte LOW_EXTREMITY = 0x02, HIGH_EXTREMITY = 0x08;
// Tree node header size.
static final int TN_HEADER_SIZE = 12;
static final int STUB_ID = 1;
static final int ENTRY_FRAGMENTED = 0x40;
// Usage list this node belongs to.
final NodeUsageList mUsageList;
// Links within usage list, guarded by NodeUsageList.
Node mMoreUsed; // points to more recently used node
Node mLessUsed; // points to less recently used node
// Links within dirty list, guarded by NodeDirtyList.
Node mNextDirty;
Node mPrevDirty;
/*
Nodes define the contents of Trees and UndoLogs. All node types start
with a two byte header.
+----------------------------------------+
| byte: node type | header
| byte: reserved (must be 0) |
- -
There are two types of tree nodes, having a similar structure and
supporting a maximum page size of 65536 bytes. The ushort type is an
unsigned byte pair, and the ulong type is eight bytes. All multibyte
types are little endian encoded.
+----------------------------------------+
| byte: node type | header
| byte: reserved (must be 0) |
| ushort: garbage in segments |
| ushort: pointer to left segment tail |
| ushort: pointer to right segment tail |
| ushort: pointer to search vector start |
| ushort: pointer to search vector end |
+----------------------------------------+
| left segment |
- -
| |
+----------------------------------------+
| free space | <-- left segment tail (exclusive)
- -
| |
+----------------------------------------+
| search vector | <-- search vector start (inclusive)
- -
| | <-- search vector end (inclusive)
+----------------------------------------+
| free space |
- -
| | <-- right segment tail (exclusive)
+----------------------------------------+
| right segment |
- -
| |
+----------------------------------------+
The left and right segments are used for allocating variable sized entries, and the
tail points to the next allocation. Allocations are made toward the search vector
such that the free space before and after the search vector remain the roughly the
same. The search vector may move if a contiguous allocation is not possible on
either side.
The search vector is used for performing a binary search against keys. The keys are
variable length and are stored anywhere in the left and right segments. The search
vector itself must point to keys in the correct order, supporting binary search. The
search vector is also required to be aligned to an even address, contain fixed size
entries, and it never has holes. Adding or removing entries from the search vector
requires entries to be shifted. The shift operation can be performed from either
side, but the smaller shift is always chosen as a performance optimization.
Garbage refers to the amount of unused bytes within the left and right allocation
segments. Garbage accumulates when entries are deleted and updated from the
segments. Segments are not immediately shifted because the search vector would also
need to be repaired. A compaction operation reclaims garbage by rebuilding the
segments and search vector. A copying garbage collection algorithm is used for this.
The compaction implementation allocates all surviving entries in the left segment,
leaving an empty right segment. There is no requirement that the segments be
balanced -- this only applies to the free space surrounding the search vector.
Leaf nodes support variable length keys and values, encoded as a pair, within the
segments. Entries in the search vector are ushort pointers into the segments. No
distinction is made between the segments because the pointers are absolute.
Entries start with a one byte key header:
0b0xxx_xxxx: key is 1..128 bytes
0b1fxx_xxxx: key is 0..16383 bytes
For keys 1..128 bytes in length, the length is defined as (header + 1). For
keys 0..16383 bytes in length, a second header byte is used. The second byte is
unsigned, and the length is defined as (((header & 0x3f) << 8) | header2). The key
contents immediately follow the header byte(s).
When the 'f' bit is zero, the entry is a normal key. Very large keys are stored in a
fragmented fashion, which is also used by large values. The encoding format is defined by
Database.fragment.
The value follows the key, and its header encodes the entry length:
0b0xxx_xxxx: value is 0..127 bytes
0b1f0x_xxxx: value/entry is 1..8192 bytes
0b1f10_xxxx: value/entry is 1..1048576 bytes
0b1111_1111: ghost value (null)
When the 'f' bit is zero, the entry is a normal value. Otherwise, it is a
fragmented value, defined by Database.fragment.
For entries 1..8192 bytes in length, a second header byte is used. The
length is then defined as ((((h0 & 0x1f) << 8) | h1) + 1). For larger
entries, the length is ((((h0 & 0x0f) << 16) | (h1 << 8) | h2) + 1).
Node limit is currently 65536 bytes, which limits maximum entry length.
The "values" for internal nodes are actually identifiers for child nodes. The number
of child nodes is always one more than the number of keys. For this reason, the
key-value format used by leaf nodes cannot be applied to internal nodes. Also, the
identifiers are always a fixed length, ulong type.
Child node identifiers are encoded immediately following the search vector. Free space
management must account for this, treating it as an extension to the search vector.
Each entry in the child node id segment contains 6 byte child node id, followed by
2 byte count of keys in the child node. The child node ids are in the same order as
keys in the search vector.
+----------------------------------------+
| byte: node type | header
| byte: reserved (must be 0) |
| ushort: garbage in segments |
| ushort: pointer to left segment tail |
| ushort: pointer to right segment tail |
| ushort: pointer to search vector start |
| ushort: pointer to search vector end |
+----------------------------------------+
| left key segment |
- -
| |
+----------------------------------------+
| free space | <-- left segment tail (exclusive)
- -
| |
+----------------------------------------+
| search vector | <-- search vector start (inclusive)
- -
| | <-- search vector end (inclusive)
+----------------------------------------+
| child node id segment |
- -
| |
+----------------------------------------+
| free space |
- -
| | <-- right segment tail (exclusive)
+----------------------------------------+
| right key segment |
- -
| |
+----------------------------------------+
*/
// Raw contents of node.
/*P*/ byte[] mPage;
// Id is often read without acquiring latch, although in most cases, it
// doesn't need to be volatile. This is because a double check with the
// latch held is always performed. So-called double-checked locking doesn't
// work with object initialization, but it's fine with primitive types.
// When nodes are evicted, the write operation must complete before the id
// is re-assigned. For this reason, the id is volatile. A memory barrier
// between the write and re-assignment should work too.
volatile long mId;
byte mCachedState;
/*P*/ // [
// Entries from header, available as fields for quick access.
private byte mType;
private int mGarbage;
private int mLeftSegTail;
private int mRightSegTail;
private int mSearchVecStart;
private int mSearchVecEnd;
/*P*/ // ]
// Next in NodeMap collision chain.
Node mNodeMapNext;
// Linked stack of TreeCursorFrames bound to this Node.
transient volatile TreeCursorFrame mLastCursorFrame;
// Set by a partially completed split.
transient Split mSplit;
Node(NodeUsageList usageList, /*P*/ byte[] page) {
mUsageList = usageList;
mPage = page;
}
// Construct a "lock" object for use when loading a node. See loadChild method.
private Node(long id) {
mUsageList = null;
initExclusive();
mId = id;
}
/**
* Must be called when object is no longer referenced.
*/
void delete(LocalDatabase db) {
acquireExclusive();
try {
doDelete(db);
} finally {
releaseExclusive();
}
}
/**
* Must be called when object is no longer referenced. Caller must acquire exclusive latch.
*/
void doDelete(LocalDatabase db) {
/*P*/ // [|
/*P*/ // if (db.mFullyMapped) {
/*P*/ // // Cannot delete mapped pages.
/*P*/ // closeRoot();
/*P*/ // return;
/*P*/ // }
/*P*/ // ]
/*P*/ byte[] page = mPage;
if (page != p_closedTreePage()) {
p_delete(page);
closeRoot();
}
}
@Override
public LocalDatabase getDatabase() {
return mUsageList.mDatabase;
}
void asEmptyRoot() {
mId = 0;
mCachedState = CACHED_CLEAN;
type((byte) (TYPE_TN_LEAF | LOW_EXTREMITY | HIGH_EXTREMITY));
clearEntries();
}
void asTrimmedRoot() {
type((byte) (TYPE_TN_LEAF | LOW_EXTREMITY | HIGH_EXTREMITY));
clearEntries();
}
/**
* Close the root node when closing a tree.
*/
void closeRoot() {
// Prevent node from being marked dirty.
mId = STUB_ID;
mCachedState = CACHED_CLEAN;
mPage = p_closedTreePage();
readFields();
}
Node cloneNode() {
Node newNode = new Node(mUsageList, mPage);
newNode.mId = mId;
newNode.mCachedState = mCachedState;
/*P*/ // [
newNode.type(type());
newNode.garbage(garbage());
newNode.leftSegTail(leftSegTail());
newNode.rightSegTail(rightSegTail());
newNode.searchVecStart(searchVecStart());
newNode.searchVecEnd(searchVecEnd());
/*P*/ // ]
return newNode;
}
private void clearEntries() {
garbage(0);
leftSegTail(TN_HEADER_SIZE);
int pageSize = pageSize(mPage);
rightSegTail(pageSize - 1);
// Search vector location must be even.
searchVecStart((TN_HEADER_SIZE + ((pageSize - TN_HEADER_SIZE) >> 1)) & ~1);
searchVecEnd(searchVecStart() - 2); // inclusive
}
/**
* Indicate that a non-root node is most recently used. Root node is not managed in usage
* list and cannot be evicted. Caller must hold any latch on node. Latch is never released
* by this method, even if an exception is thrown.
*/
void used() {
mUsageList.used(this);
}
/**
* Indicate that node is least recently used, allowing it to be recycled immediately
* without evicting another node. Node must be latched by caller, which is always released
* by this method.
*/
void unused() {
mUsageList.unused(this);
}
/**
* Allow a Node which was allocated as unevictable to be evictable, starting off as the
* most recently used.
*/
void makeEvictable() {
mUsageList.makeEvictable(this);
}
/**
* Allow a Node which was allocated as unevictable to be evictable, as the least recently
* used.
*/
void makeEvictableNow() {
mUsageList.makeEvictableNow(this);
}
/**
* Allow a Node which was allocated as evictable to be unevictable.
*/
void makeUnevictable() {
mUsageList.makeUnevictable(this);
}
/**
* Search for a value, starting from the root node.
*
* @param node root node
* @param key search key
* @return copy of value or null if not found
*/
static byte[] search(Node node, Tree tree, byte[] key) throws IOException {
node.acquireShared();
// Note: No need to check if root has split, since root splits are always completed
// before releasing the root latch. Also, Node.used is not invoked for the root node,
// because it cannot be evicted.
while (!node.isLeaf()) {
int childPos;
try {
childPos = internalPos(node.binarySearch(key));
} catch (Throwable e) {
node.releaseShared();
throw e;
}
long childId = node.retrieveChildRefId(childPos);
Node childNode = tree.mDatabase.nodeMapGet(childId);
if (childNode != null) {
childNode.acquireShared();
// Need to check again in case evict snuck in.
if (childId == childNode.mId) {
node.releaseShared();
node = childNode;
if (node.mSplit != null) {
node = node.mSplit.selectNode(node, key);
}
node.used();
continue;
}
childNode.releaseShared();
}
node = node.loadChild(tree.mDatabase, childId, OPTION_PARENT_RELEASE_SHARED);
}
// Sub search into leaf with shared latch held.
// Same code as binarySearch, but instead of returning the position, it directly copies
// the value if found. This avoids having to decode the found value location twice.
try {
final /*P*/ byte[] page = node.mPage;
final int keyLen = key.length;
int lowPos = node.searchVecStart();
int highPos = node.searchVecEnd();
int lowMatch = 0;
int highMatch = 0;
outer: while (lowPos <= highPos) {
int midPos = ((lowPos + highPos) >> 1) & ~1;
int compareLoc, compareLen, i;
compare: {
compareLoc = p_ushortGetLE(page, midPos);
compareLen = p_byteGet(page, compareLoc++);
if (compareLen >= 0) {
compareLen++;
} else {
int header = compareLen;
compareLen = ((compareLen & 0x3f) << 8) | p_ubyteGet(page, compareLoc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] compareKey = tree.mDatabase.reconstructKey
(page, compareLoc, compareLen);
int fullCompareLen = compareKey.length;
int minLen = Math.min(fullCompareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = compareKey[i];
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
continue outer;
}
}
// Update compareLen and compareLoc for use by the code after the
// current scope. The compareLoc is completely bogus at this point,
// but is corrected when the value is retrieved below.
compareLoc += compareLen - fullCompareLen;
compareLen = fullCompareLen;
break compare;
}
}
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = p_byteGet(page, compareLoc + i);
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
continue outer;
}
}
}
if (compareLen < keyLen) {
lowPos = midPos + 2;
lowMatch = i;
} else if (compareLen > keyLen) {
highPos = midPos - 2;
highMatch = i;
} else {
return retrieveLeafValueAtLoc(node, page, compareLoc + compareLen);
}
}
return null;
} finally {
node.releaseShared();
}
}
/**
* Options for loadChild. Caller must latch parentas shared or exclusive, which can be
* retained (default) or released. Child node is latched shared (default) or exclusive.
*/
static final int
OPTION_PARENT_RELEASE_SHARED = 0b001,
OPTION_PARENT_RELEASE_EXCLUSIVE = 0b010,
OPTION_CHILD_ACQUIRE_EXCLUSIVE = 0b100;
/**
* With this parent node latched shared or exclusive, loads child with shared or exclusive
* latch. Caller must ensure that child is not already loaded. If an exception is thrown,
* parent and child latches are always released.
*
* @param options descibed described by OPTION_* fields
*/
Node loadChild(LocalDatabase db, long childId, int options) throws IOException {
// Insert a "lock", which is a temporary node latched exclusively. All other threads
// attempting to load the child node will block trying to acquire the exclusive latch.
Node lock = new Node(childId);
try {
while (true) {
Node childNode = db.nodeMapPutIfAbsent(lock);
if (childNode == null) {
break;
}
// Was already loaded, or is currently being loaded.
if ((options & OPTION_CHILD_ACQUIRE_EXCLUSIVE) == 0) {
childNode.acquireShared();
if (childId == childNode.mId) {
return childNode;
}
childNode.releaseShared();
} else {
childNode.acquireExclusive();
if (childId == childNode.mId) {
return childNode;
}
childNode.releaseExclusive();
}
}
} finally {
// Release parent latch before child has been loaded. Any threads which wish to
// access the same child will block until this thread has finished loading the
// child and released its exclusive latch.
if ((options & OPTION_PARENT_RELEASE_SHARED) != 0) {
releaseShared();
} else if ((options & OPTION_PARENT_RELEASE_EXCLUSIVE) != 0) {
releaseExclusive();
}
}
try {
Node childNode;
try {
childNode = db.allocLatchedNode(childId);
childNode.mId = childId;
} catch (Throwable e) {
db.nodeMapRemove(lock);
throw e;
}
// Replace the lock with the real child node, but don't notify any threads waiting
// on the lock just yet. They'd go back to sleep waiting for the read to finish.
db.nodeMapReplace(lock, childNode);
try {
childNode.read(db, childId);
} catch (Throwable e) {
// Another thread might access child and see that it's invalid because the id
// is zero. It will assume it got evicted and will attempt to reload it
db.nodeMapRemove(childNode);
childNode.mId = 0;
childNode.type(TYPE_NONE);
childNode.releaseExclusive();
throw e;
}
if ((options & OPTION_CHILD_ACQUIRE_EXCLUSIVE) == 0){
childNode.downgrade();
}
return childNode;
} catch (Throwable e) {
if ((options & (OPTION_PARENT_RELEASE_SHARED | OPTION_PARENT_RELEASE_EXCLUSIVE)) == 0){
// Obey the method contract and release parent latch due to exception.
releaseEither();
}
throw e;
} finally {
// Wake any threads waiting on the lock now that the real child node is ready, or
// if the load failed. Lock id must be set to zero to ensure that it's not accepted
// as the child node.
lock.mId = 0;
lock.releaseExclusive();
}
}
/**
* With this parent node held exclusively, attempts to return child with exclusive latch
* held. If an exception is thrown, parent and child latches are always released. This
* method is intended to be called for rebalance operations.
*
* @return null or child node, never split
*/
private Node tryLatchChildNotSplit(int childPos) throws IOException {
final long childId = retrieveChildRefId(childPos);
final LocalDatabase db = getDatabase();
Node childNode = db.nodeMapGet(childId);
if (childNode != null) {
if (!childNode.tryAcquireExclusive()) {
return null;
}
// Need to check again in case evict snuck in.
if (childId != childNode.mId) {
childNode.releaseExclusive();
} else if (childNode.mSplit == null) {
// Return without updating LRU position. Node contents were not user requested.
return childNode;
} else {
childNode.releaseExclusive();
return null;
}
}
return loadChild(db, childId, OPTION_CHILD_ACQUIRE_EXCLUSIVE);
}
/**
* Caller must hold exclusive root latch and it must verify that root has split. Caller
* must also exclusively hold stub latch, if applicable. This required for safely unbinding
* parent cursor frames which refer to the old root node.
*/
void finishSplitRoot() throws IOException {
// Create a child node and copy this root node state into it. Then update this
// root node to point to new and split child nodes. New root is always an internal node.
LocalDatabase db = mUsageList.mDatabase;
Node child = db.allocDirtyNode();
db.nodeMapPut(child);
/*P*/ byte[] newRootPage;
/*P*/ // [
newRootPage = child.mPage;
child.mPage = mPage;
child.type(type());
child.garbage(garbage());
child.leftSegTail(leftSegTail());
child.rightSegTail(rightSegTail());
child.searchVecStart(searchVecStart());
child.searchVecEnd(searchVecEnd());
/*P*/ // |
/*P*/ // if (db.mFullyMapped) {
/*P*/ // // Page cannot change, so copy it instead.
/*P*/ // newRootPage = mPage;
/*P*/ // p_copy(newRootPage, 0, child.mPage, 0, db.pageSize());
/*P*/ // } else {
/*P*/ // newRootPage = child.mPage;
/*P*/ // child.mPage = mPage;
/*P*/ // }
/*P*/ // ]
final Split split = mSplit;
final Node sibling = rebindSplitFrames(split);
mSplit = null;
// Fix child node cursor frame bindings.
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
frame.rebind(child, frame.mNodePos);
frame = prev;
}
if (mLastCursorFrame != null) {
throw new AssertionError();
}
Node left, right;
if (split.mSplitRight) {
left = child;
right = sibling;
} else {
left = sibling;
right = child;
}
int leftSegTail = split.copySplitKeyToParent(newRootPage, TN_HEADER_SIZE);
// Create new single-element search vector. Center it using the same formula as the
// compactInternal method.
final int searchVecStart = pageSize(newRootPage) -
(((pageSize(newRootPage) - leftSegTail + (2 + 8 + 8)) >> 1) & ~1);
p_shortPutLE(newRootPage, searchVecStart, TN_HEADER_SIZE);
p_longPutLE(newRootPage, searchVecStart + 2, left.mId);
p_longPutLE(newRootPage, searchVecStart + 2 + 8, right.mId);
byte newType = isLeaf() ? (byte) (TYPE_TN_BIN | LOW_EXTREMITY | HIGH_EXTREMITY)
: (byte) (TYPE_TN_IN | LOW_EXTREMITY | HIGH_EXTREMITY);
mPage = newRootPage;
/*P*/ // [
type(newType);
garbage(0);
/*P*/ // |
/*P*/ // p_intPutLE(newRootPage, 0, newType & 0xff); // type, reserved byte, and garbage
/*P*/ // ]
leftSegTail(leftSegTail);
rightSegTail(pageSize(newRootPage) - 1);
searchVecStart(searchVecStart);
searchVecEnd(searchVecStart);
// Add a parent cursor frame for all left and right node cursors.
TreeCursorFrame lock = new TreeCursorFrame();
addParentFrames(lock, left, 0);
addParentFrames(lock, right, 2);
child.releaseExclusive();
sibling.releaseExclusive();
// Split complete, so allow new node to be evictable.
sibling.makeEvictable();
}
private void addParentFrames(TreeCursorFrame lock, Node child, int pos) {
for (TreeCursorFrame frame = child.mLastCursorFrame; frame != null; ) {
TreeCursorFrame lockResult = frame.tryLock(lock);
if (lockResult != null) {
try {
TreeCursorFrame parentFrame = frame.mParentFrame;
if (parentFrame == null) {
parentFrame = new TreeCursorFrame();
parentFrame.bind(this, pos);
frame.mParentFrame = parentFrame;
} else {
parentFrame.rebind(this, pos);
}
} finally {
frame.unlock(lockResult);
}
}
frame = frame.mPrevCousin;
}
}
/**
* Caller must hold exclusive latch. Latch is never released by this method, even if
* an exception is thrown.
*/
void read(LocalDatabase db, long id) throws IOException {
db.readNode(this, id);
try {
readFields();
} catch (IllegalStateException e) {
throw new CorruptDatabaseException(e.getMessage());
}
}
private void readFields() throws IllegalStateException {
/*P*/ byte[] page = mPage;
byte type = p_byteGet(page, 0);
/*P*/ // [
type(type);
// For undo log node, this is top entry pointer.
garbage(p_ushortGetLE(page, 2));
/*P*/ // ]
if (type != TYPE_UNDO_LOG) {
/*P*/ // [
leftSegTail(p_ushortGetLE(page, 4));
rightSegTail(p_ushortGetLE(page, 6));
searchVecStart(p_ushortGetLE(page, 8));
searchVecEnd(p_ushortGetLE(page, 10));
/*P*/ // ]
type &= ~(LOW_EXTREMITY | HIGH_EXTREMITY);
if (type >= 0 && type != TYPE_TN_IN && type != TYPE_TN_BIN) {
throw new IllegalStateException("Unknown node type: " + type + ", id: " + mId);
}
}
if (p_byteGet(page, 1) != 0) {
throw new IllegalStateException
("Illegal reserved byte in node: " + p_byteGet(page, 1));
}
}
/**
* Caller must hold any latch, which is not released, even if an exception is thrown.
*/
void write(PageDb db) throws WriteFailureException {
/*P*/ byte[] page = prepareWrite();
try {
db.writePage(mId, page);
} catch (IOException e) {
throw new WriteFailureException(e);
}
}
private /*P*/ byte[] prepareWrite() {
if (mSplit != null) {
throw new AssertionError("Cannot write partially split node");
}
/*P*/ byte[] page = mPage;
/*P*/ // [
if (type() != TYPE_FRAGMENT) {
p_bytePut(page, 0, type());
p_bytePut(page, 1, 0); // reserved
// For undo log node, this is top entry pointer.
p_shortPutLE(page, 2, garbage());
if (type() != TYPE_UNDO_LOG) {
p_shortPutLE(page, 4, leftSegTail());
p_shortPutLE(page, 6, rightSegTail());
p_shortPutLE(page, 8, searchVecStart());
p_shortPutLE(page, 10, searchVecEnd());
}
}
/*P*/ // ]
return page;
}
/**
* Caller must hold exclusive latch on node. Latch is released by this
* method when false is returned or if an exception is thrown.
*
* @return false if cannot evict
*/
boolean evict(LocalDatabase db) throws IOException {
if (mLastCursorFrame != null || mSplit != null) {
// Cannot evict if in use by a cursor or if splitting. The split
// check is redundant, since a node cannot be in a split state
// without a cursor registered against it.
releaseExclusive();
return false;
}
try {
// Check if <= 0 (already evicted) or stub.
long id = mId;
if (id > STUB_ID) {
PageDb pageDb = db.mPageDb;
if (mCachedState == CACHED_CLEAN) {
// Try to move to a secondary cache.
pageDb.cachePage(id, mPage);
} else {
/*P*/ byte[] page = prepareWrite();
/*P*/ byte[] newPage = pageDb.evictPage(id, page);
if (newPage != page) {
mPage = newPage;
}
mCachedState = CACHED_CLEAN;
}
db.nodeMapRemove(this, Long.hashCode(id));
mId = 0;
// Note: Don't do this. In the fully mapped mode (using MappedPageArray),
// setting the type will corrupt the evicted node. The caller swaps in a
// different page, which is where the type should be written to.
//type(TYPE_NONE);
}
return true;
} catch (Throwable e) {
releaseExclusive();
throw e;
}
}
/**
* Invalidate all cursors, starting from the root. Used when closing an index which still
* has active cursors. Caller must hold exclusive latch on node.
*/
void invalidateCursors() {
invalidateCursors(createClosedNode());
}
private void invalidateCursors(Node closed) {
int pos = isLeaf() ? -1 : 0;
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
frame.mNode = closed;
frame.mNodePos = pos;
frame = frame.unlink();
}
if (!isInternal()) {
return;
}
LocalDatabase db = mUsageList.mDatabase;
closed = null;
int childPtr = searchVecEnd() + 2;
final int highestPtr = childPtr + (highestInternalPos() << 2);
for (; childPtr <= highestPtr; childPtr += 8) {
long childId = p_uint48GetLE(mPage, childPtr);
Node child = db.nodeMapGet(childId);
if (child != null) {
child.acquireExclusive();
if (childId == child.mId) {
if (closed == null) {
closed = createClosedNode();
}
child.invalidateCursors(closed);
}
child.releaseExclusive();
}
}
}
private static Node createClosedNode() {
Node closed = new Node(null, p_closedTreePage());
closed.mId = STUB_ID;
closed.mCachedState = CACHED_CLEAN;
closed.readFields();
return closed;
}
private int pageSize(/*P*/ byte[] page) {
/*P*/ // [
return page.length;
/*P*/ // |
/*P*/ // return mUsageList.pageSize();
/*P*/ // ]
}
/**
* Get the node type.
*/
byte type() {
/*P*/ // [
return mType;
/*P*/ // |
/*P*/ // return p_byteGet(mPage, 0);
/*P*/ // ]
}
/**
* Set the node type.
*/
void type(byte type) {
/*P*/ // [
mType = type;
/*P*/ // |
/*P*/ // p_bytePut(mPage, 0, type);
/*P*/ // ]
}
/**
* Get the node garbage size.
*/
int garbage() {
/*P*/ // [
return mGarbage;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 2);
/*P*/ // ]
}
/**
* Set the node garbage size.
*/
void garbage(int garbage) {
/*P*/ // [
mGarbage = garbage;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 2, garbage);
/*P*/ // ]
}
/**
* Get the undo log node top entry pointer. (same field as garbage)
*/
int undoTop() {
/*P*/ // [
return mGarbage;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 2);
/*P*/ // ]
}
/**
* Set the undo log node top entry pointer. (same field as garbage)
*/
void undoTop(int top) {
/*P*/ // [
mGarbage = top;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 2, top);
/*P*/ // ]
}
/**
* Get the left segment tail pointer.
*/
private int leftSegTail() {
/*P*/ // [
return mLeftSegTail;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 4);
/*P*/ // ]
}
/**
* Set the left segment tail pointer.
*/
private void leftSegTail(int tail) {
/*P*/ // [
mLeftSegTail = tail;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 4, tail);
/*P*/ // ]
}
/**
* Get the right segment tail pointer.
*/
private int rightSegTail() {
/*P*/ // [
return mRightSegTail;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 6);
/*P*/ // ]
}
/**
* Set the right segment tail pointer.
*/
private void rightSegTail(int tail) {
/*P*/ // [
mRightSegTail = tail;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 6, tail);
/*P*/ // ]
}
/**
* Get the search vector start pointer.
*/
int searchVecStart() {
/*P*/ // [
return mSearchVecStart;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 8);
/*P*/ // ]
}
/**
* Set the search vector start pointer.
*/
private void searchVecStart(int start) {
/*P*/ // [
mSearchVecStart = start;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 8, start);
/*P*/ // ]
}
/**
* Get the search vector end pointer.
*/
private int searchVecEnd() {
/*P*/ // [
return mSearchVecEnd;
/*P*/ // |
/*P*/ // return p_ushortGetLE(mPage, 10);
/*P*/ // ]
}
/**
* Set the search vector end pointer.
*/
private void searchVecEnd(int end) {
/*P*/ // [
mSearchVecEnd = end;
/*P*/ // |
/*P*/ // p_shortPutLE(mPage, 10, end);
/*P*/ // ]
}
/**
* Caller must hold any latch.
*/
boolean isLeaf() {
return type() < 0;
}
/**
* Caller must hold any latch. Returns true if node is any kind of internal node.
*/
boolean isInternal() {
return (type() & 0xe0) == 0x60;
}
/**
* Caller must hold any latch.
*/
boolean isBottomInternal() {
return (type() & 0xf0) == 0x70;
}
/**
* Caller must hold any latch.
*/
boolean isNonBottomInternal() {
return (type() & 0xf0) == 0x60;
}
/**
* Caller must hold any latch.
*
* @see #countNonGhostKeys
*/
int numKeys() {
return (searchVecEnd() - searchVecStart() + 2) >> 1;
}
/**
* Caller must hold any latch.
*/
boolean hasKeys() {
return searchVecEnd() >= searchVecStart();
}
/**
* Returns the highest possible key position, which is an even number. If
* node has no keys, return value is negative. Caller must hold any latch.
*/
int highestKeyPos() {
return searchVecEnd() - searchVecStart();
}
/**
* Returns highest leaf or internal position. Caller must hold any latch.
*/
int highestPos() {
int pos = searchVecEnd() - searchVecStart();
if (!isLeaf()) {
pos += 2;
}
return pos;
}
/**
* Returns the highest possible leaf key position, which is an even
* number. If leaf node is empty, return value is negative. Caller must
* hold any latch.
*/
int highestLeafPos() {
return searchVecEnd() - searchVecStart();
}
/**
* Returns the highest possible internal node position, which is an even
* number. Highest position doesn't correspond to a valid key, but instead
* a child node position. If internal node has no keys, node has one child
* at position zero. Caller must hold any latch.
*/
int highestInternalPos() {
return searchVecEnd() - searchVecStart() + 2;
}
/**
* Caller must hold any latch.
*/
int availableBytes() {
return isLeaf() ? availableLeafBytes() : availableInternalBytes();
}
/**
* Caller must hold any latch.
*/
int availableLeafBytes() {
return garbage() + searchVecStart() - searchVecEnd()
- leftSegTail() + rightSegTail() + (1 - 2);
}
/**
* Caller must hold any latch.
*/
int availableInternalBytes() {
return garbage() + 5 * (searchVecStart() - searchVecEnd())
- leftSegTail() + rightSegTail() + (1 - (5 * 2 + 8));
}
/**
* Applicable only to leaf nodes. Caller must hold any latch.
*/
int countNonGhostKeys() {
final /*P*/ byte[] page = mPage;
int count = 0;
for (int i = searchVecStart(); i <= searchVecEnd(); i += 2) {
int loc = p_ushortGetLE(page, i);
if (p_byteGet(page, loc + keyLengthAtLoc(page, loc)) != -1) {
count++;
}
}
return count;
}
/**
* Returns true if leaf is not split and underutilized. If so, it should be
* merged with its neighbors, and possibly deleted. Caller must hold any latch.
*/
boolean shouldLeafMerge() {
return shouldMerge(availableLeafBytes());
}
/**
* Returns true if non-leaf is not split and underutilized. If so, it should be
* merged with its neighbors, and possibly deleted. Caller must hold any latch.
*/
boolean shouldInternalMerge() {
return shouldMerge(availableInternalBytes());
}
boolean shouldMerge(int availBytes) {
return mSplit == null
& (((type() & (LOW_EXTREMITY | HIGH_EXTREMITY)) == 0
& availBytes >= ((pageSize(mPage) - TN_HEADER_SIZE) >> 1))
| !hasKeys());
}
/**
* @return 2-based insertion pos, which is negative if key not found
*/
int binarySearch(byte[] key) throws IOException {
final /*P*/ byte[] page = mPage;
final int keyLen = key.length;
int lowPos = searchVecStart();
int highPos = searchVecEnd();
int lowMatch = 0;
int highMatch = 0;
outer: while (lowPos <= highPos) {
int midPos = ((lowPos + highPos) >> 1) & ~1;
int compareLen, i;
compare: {
int compareLoc = p_ushortGetLE(page, midPos);
compareLen = p_byteGet(page, compareLoc++);
if (compareLen >= 0) {
compareLen++;
} else {
int header = compareLen;
compareLen = ((compareLen & 0x3f) << 8) | p_ubyteGet(page, compareLoc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] compareKey = getDatabase()
.reconstructKey(page, compareLoc, compareLen);
compareLen = compareKey.length;
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = compareKey[i];
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
continue outer;
}
}
break compare;
}
}
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = p_byteGet(page, compareLoc + i);
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
continue outer;
}
}
}
if (compareLen < keyLen) {
lowPos = midPos + 2;
lowMatch = i;
} else if (compareLen > keyLen) {
highPos = midPos - 2;
highMatch = i;
} else {
return midPos - searchVecStart();
}
}
return ~(lowPos - searchVecStart());
}
/**
* @param midPos 2-based starting position
* @return 2-based insertion pos, which is negative if key not found
*/
int binarySearch(byte[] key, int midPos) throws IOException {
int lowPos = searchVecStart();
int highPos = searchVecEnd();
if (lowPos > highPos) {
return -1;
}
midPos += lowPos;
if (midPos > highPos) {
midPos = highPos;
}
final /*P*/ byte[] page = mPage;
final int keyLen = key.length;
int lowMatch = 0;
int highMatch = 0;
while (true) {
compare: {
int compareLen, i;
c2: {
int compareLoc = p_ushortGetLE(page, midPos);
compareLen = p_byteGet(page, compareLoc++);
if (compareLen >= 0) {
compareLen++;
} else {
int header = compareLen;
compareLen = ((compareLen & 0x3f) << 8) | p_ubyteGet(page, compareLoc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] compareKey = getDatabase()
.reconstructKey(page, compareLoc, compareLen);
compareLen = compareKey.length;
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = compareKey[i];
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
break compare;
}
}
break c2;
}
}
int minLen = Math.min(compareLen, keyLen);
i = Math.min(lowMatch, highMatch);
for (; i<minLen; i++) {
byte cb = p_byteGet(page, compareLoc + i);
byte kb = key[i];
if (cb != kb) {
if ((cb & 0xff) < (kb & 0xff)) {
lowPos = midPos + 2;
lowMatch = i;
} else {
highPos = midPos - 2;
highMatch = i;
}
break compare;
}
}
}
if (compareLen < keyLen) {
lowPos = midPos + 2;
lowMatch = i;
} else if (compareLen > keyLen) {
highPos = midPos - 2;
highMatch = i;
} else {
return midPos - searchVecStart();
}
}
if (lowPos > highPos) {
break;
}
midPos = ((lowPos + highPos) >> 1) & ~1;
}
return ~(lowPos - searchVecStart());
}
/**
* Ensure binary search position is positive, for internal node.
*/
static int internalPos(int pos) {
return pos < 0 ? ~pos : (pos + 2);
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
int compareKey(int pos, byte[] rightKey) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] leftKey = getDatabase().reconstructKey(page, loc, keyLen);
return compareUnsigned(leftKey, 0, leftKey.length, rightKey, 0, rightKey.length);
}
}
return p_compareKeysPageToArray(page, loc, keyLen, rightKey, 0, rightKey.length);
}
/**
* @param pos position as provided by binarySearch; must be positive
* @param stats [0]: full length, [1]: number of pages (>0 if fragmented)
*/
void retrieveKeyStats(int pos, long[] stats) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
getDatabase().reconstruct(page, loc, keyLen, stats);
return;
}
}
stats[0] = keyLen;
stats[1] = 0;
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
byte[] retrieveKey(int pos) throws IOException {
final /*P*/ byte[] page = mPage;
return retrieveKeyAtLoc(this, page, p_ushortGetLE(page, searchVecStart() + pos));
}
/**
* @param loc absolute location of entry
*/
byte[] retrieveKeyAtLoc(final /*P*/ byte[] page, int loc) throws IOException {
return retrieveKeyAtLoc(this, page, loc);
}
/**
* @param loc absolute location of entry
*/
static byte[] retrieveKeyAtLoc(DatabaseAccess dbAccess, final /*P*/ byte[] page, int loc)
throws IOException
{
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
return dbAccess.getDatabase().reconstructKey(page, loc, keyLen);
}
}
byte[] key = new byte[keyLen];
p_copyToArray(page, loc, key, 0, keyLen);
return key;
}
/**
* @param loc absolute location of entry
* @param akeyRef [0] is set to the actual key
* @return false if key is fragmented and actual doesn't match original
*/
private boolean retrieveActualKeyAtLoc(final /*P*/ byte[] page, int loc,
final byte[][] akeyRef)
throws IOException
{
boolean result = true;
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
result = (header & ENTRY_FRAGMENTED) == 0;
}
byte[] akey = new byte[keyLen];
p_copyToArray(page, loc, akey, 0, keyLen);
akeyRef[0] = akey;
return result;
}
/**
* Copies the key at the given position based on a limit. If equal, the
* limitKey instance is returned. If beyond the limit, null is returned.
*
* @param pos position as provided by binarySearch; must be positive
* @param limitKey comparison key
* @param limitMode positive for LE behavior, negative for GE behavior
*/
byte[] retrieveKeyCmp(int pos, byte[] limitKey, int limitMode) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
keyLen++;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
byte[] key = getDatabase().reconstructKey(page, loc, keyLen);
int cmp = compareUnsigned(key, limitKey);
if (cmp == 0) {
return limitKey;
} else {
return (cmp ^ limitMode) < 0 ? key : null;
}
}
}
int cmp = p_compareKeysPageToArray(page, loc, keyLen, limitKey, 0, limitKey.length);
if (cmp == 0) {
return limitKey;
} else if ((cmp ^ limitMode) < 0) {
byte[] key = new byte[keyLen];
p_copyToArray(page, loc, key, 0, keyLen);
return key;
} else {
return null;
}
}
/**
* Used by UndoLog for decoding entries. Only works for non-fragmented values.
*
* @param loc absolute location of entry
*/
static byte[][] retrieveKeyValueAtLoc(DatabaseAccess dbAccess,
final /*P*/ byte[] page, int loc)
throws IOException
{
int header = p_byteGet(page, loc++);
int keyLen;
byte[] key;
copyKey: {
if (header >= 0) {
keyLen = header + 1;
} else {
keyLen = ((header & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
key = dbAccess.getDatabase().reconstructKey(page, loc, keyLen);
break copyKey;
}
}
key = new byte[keyLen];
p_copyToArray(page, loc, key, 0, keyLen);
}
return new byte[][] {key, retrieveLeafValueAtLoc(null, page, loc + keyLen)};
}
/**
* Returns a new key between the low key in this node and the given high key.
*
* @see Utils#midKey
*/
private byte[] midKey(int lowPos, byte[] highKey) throws IOException {
final /*P*/ byte[] lowPage = mPage;
int lowLoc = p_ushortGetLE(lowPage, searchVecStart() + lowPos);
int lowKeyLen = p_byteGet(lowPage, lowLoc);
if (lowKeyLen < 0) {
// Note: An optimized version wouldn't need to copy the whole key.
return Utils.midKey(retrieveKeyAtLoc(lowPage, lowLoc), highKey);
} else {
return p_midKeyLowPage(lowPage, lowLoc + 1, lowKeyLen + 1, highKey, 0, highKey.length);
}
}
/**
* Returns a new key between the given low key and the high key in this node.
*
* @see Utils#midKey
*/
private byte[] midKey(byte[] lowKey, int highPos) throws IOException {
final /*P*/ byte[] highPage = mPage;
int highLoc = p_ushortGetLE(highPage, searchVecStart() + highPos);
int highKeyLen = p_byteGet(highPage, highLoc);
if (highKeyLen < 0) {
// Note: An optimized version wouldn't need to copy the whole key.
return Utils.midKey(lowKey, retrieveKeyAtLoc(highPage, highLoc));
} else {
return p_midKeyHighPage(lowKey, 0, lowKey.length,
highPage, highLoc + 1, highKeyLen + 1);
}
}
/**
* Returns a new key between the low key in this node and the high key of another node.
*
* @see Utils#midKey
*/
byte[] midKey(int lowPos, Node highNode, int highPos) throws IOException {
final /*P*/ byte[] lowPage = mPage;
int lowLoc = p_ushortGetLE(lowPage, searchVecStart() + lowPos);
int lowKeyLen = p_byteGet(lowPage, lowLoc);
if (lowKeyLen < 0) {
// Note: An optimized version wouldn't need to copy the whole key.
return highNode.midKey(retrieveKeyAtLoc(lowPage, lowLoc), highPos);
}
lowLoc++;
lowKeyLen++;
final /*P*/ byte[] highPage = highNode.mPage;
int highLoc = p_ushortGetLE(highPage, highNode.searchVecStart() + highPos);
int highKeyLen = p_byteGet(highPage, highLoc);
if (highKeyLen < 0) {
// Note: An optimized version wouldn't need to copy the whole key.
byte[] highKey = retrieveKeyAtLoc(highPage, highLoc);
return p_midKeyLowPage(lowPage, lowLoc, lowKeyLen, highKey, 0, highKey.length);
}
return p_midKeyLowHighPage(lowPage, lowLoc, lowKeyLen,
highPage, highLoc + 1, highKeyLen + 1);
}
/**
* @param pos position as provided by binarySearch; must be positive
* @return Cursor.NOT_LOADED if value exists, null if ghost
*/
byte[] hasLeafValue(int pos) {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
loc += keyLengthAtLoc(page, loc);
return p_byteGet(page, loc) == -1 ? null : Cursor.NOT_LOADED;
}
/**
* @param pos position as provided by binarySearch; must be positive
* @param stats [0]: full length, [1]: number of pages (>0 if fragmented)
*/
void retrieveLeafValueStats(int pos, long[] stats) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
loc += keyLengthAtLoc(page, loc);
final int header = p_byteGet(page, loc++);
int len;
if (header >= 0) {
len = header;
} else {
if ((header & 0x20) == 0) {
len = 1 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (header != -1) {
len = 1 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
stats[0] = 0;
stats[1] = 0;
return;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
getDatabase().reconstruct(page, loc, len, stats);
return;
}
}
stats[0] = len;
stats[1] = 0;
}
/**
* @param pos position as provided by binarySearch; must be positive
* @return null if ghost
*/
byte[] retrieveLeafValue(int pos) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
loc += keyLengthAtLoc(page, loc);
return retrieveLeafValueAtLoc(this, page, loc);
}
private static byte[] retrieveLeafValueAtLoc(DatabaseAccess dbAccess,
/*P*/ byte[] page, int loc)
throws IOException
{
final int header = p_byteGet(page, loc++);
if (header == 0) {
return EMPTY_BYTES;
}
int len;
if (header >= 0) {
len = header;
} else {
if ((header & 0x20) == 0) {
len = 1 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (header != -1) {
len = 1 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
return null;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
return dbAccess.getDatabase().reconstruct(page, loc, len);
}
}
byte[] value = new byte[len];
p_copyToArray(page, loc, value, 0, len);
return value;
}
/**
* Sets the cursor key and value references. If mode is key-only, then set value is
* Cursor.NOT_LOADED for a value which exists, null if ghost.
*
* @param pos position as provided by binarySearch; must be positive
* @param cursor key and value are updated
*/
void retrieveLeafEntry(int pos, TreeCursor cursor) throws IOException {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
int header = p_byteGet(page, loc++);
int keyLen;
byte[] key;
copyKey: {
if (header >= 0) {
keyLen = header + 1;
} else {
keyLen = ((header & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
key = getDatabase().reconstructKey(page, loc, keyLen);
break copyKey;
}
}
key = new byte[keyLen];
p_copyToArray(page, loc, key, 0, keyLen);
}
loc += keyLen;
cursor.mKey = key;
byte[] value;
if (cursor.mKeyOnly) {
value = p_byteGet(page, loc) == -1 ? null : Cursor.NOT_LOADED;
} else {
value = retrieveLeafValueAtLoc(this, page, loc);
}
cursor.mValue = value;
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
boolean isFragmentedLeafValue(int pos) {
final /*P*/ byte[] page = mPage;
int loc = p_ushortGetLE(page, searchVecStart() + pos);
loc += keyLengthAtLoc(page, loc);
int header = p_byteGet(page, loc);
return ((header & 0xc0) >= 0xc0) & (header < -1);
}
/**
* Transactionally delete a leaf entry, replacing the value with a
* ghost. When read back, it is interpreted as null. Ghosts are used by
* transactional deletes, to ensure that they are not visible by cursors in
* other transactions. They need to acquire a lock first. When the original
* transaction commits, it deletes all the ghosted entries it created.
*
* <p>Caller must hold commit lock and exclusive latch on node.
*
* @param pos position as provided by binarySearch; must be positive
*/
void txnDeleteLeafEntry(LocalTransaction txn, Tree tree, byte[] key, int keyHash, int pos)
throws IOException
{
final /*P*/ byte[] page = mPage;
final int entryLoc = p_ushortGetLE(page, searchVecStart() + pos);
int loc = entryLoc;
// Skip the key.
loc += keyLengthAtLoc(page, loc);
// Read value header.
final int valueHeaderLoc = loc;
int header = p_byteGet(page, loc++);
doUndo: {
// Note: Similar to leafEntryLengthAtLoc.
if (header >= 0) {
// Short value. Move loc to just past end of value.
loc += header;
} else {
// Medium value. Move loc to just past end of value.
if ((header & 0x20) == 0) {
loc += 2 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc));
} else if (header != -1) {
loc += 3 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc) << 8) | p_ubyteGet(page, loc + 1));
} else {
// Already a ghost, so nothing to undo.
break doUndo;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
int valueStartLoc = valueHeaderLoc + 2 + ((header & 0x20) >> 5);
tree.mDatabase.fragmentedTrash().add
(txn, tree.mId, page,
entryLoc, valueHeaderLoc - entryLoc, // keyStart, keyLen
valueStartLoc, loc - valueStartLoc); // valueStart, valueLen
break doUndo;
}
}
// Copy whole entry into undo log.
txn.pushUndoStore(tree.mId, UndoLog.OP_UNDELETE, page, entryLoc, loc - entryLoc);
}
// Ghost will be deleted later when locks are released.
tree.mLockManager.ghosted(tree, key, keyHash);
// Replace value with ghost.
p_bytePut(page, valueHeaderLoc, -1);
garbage(garbage() + loc - valueHeaderLoc - 1);
if (txn.mDurabilityMode != DurabilityMode.NO_REDO) {
txn.redoStore(tree.mId, key, null);
}
}
/**
* Copies existing entry to undo log prior to it being updated. Fragmented
* values are added to the trash and the fragmented bit is cleared. Caller
* must hold commit lock and exlusive latch on node.
*
* @param pos position as provided by binarySearch; must be positive
*/
void txnPreUpdateLeafEntry(LocalTransaction txn, Tree tree, byte[] key, int pos)
throws IOException
{
final /*P*/ byte[] page = mPage;
final int entryLoc = p_ushortGetLE(page, searchVecStart() + pos);
int loc = entryLoc;
// Skip the key.
loc += keyLengthAtLoc(page, loc);
// Read value header.
final int valueHeaderLoc = loc;
int header = p_byteGet(page, loc++);
examineEntry: {
// Note: Similar to leafEntryLengthAtLoc.
if (header >= 0) {
// Short value. Move loc to just past end of value.
loc += header;
break examineEntry;
} else {
// Medium value. Move loc to just past end of value.
if ((header & 0x20) == 0) {
loc += 2 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc));
} else if (header != -1) {
loc += 3 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc) << 8) | p_ubyteGet(page, loc + 1));
} else {
// Already a ghost, so nothing to undo.
break examineEntry;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
int valueStartLoc = valueHeaderLoc + 2 + ((header & 0x20) >> 5);
tree.mDatabase.fragmentedTrash().add
(txn, tree.mId, page,
entryLoc, valueHeaderLoc - entryLoc, // keyStart, keyLen
valueStartLoc, loc - valueStartLoc); // valueStart, valueLen
// Clearing the fragmented bit prevents the update from
// double-deleting the fragments, and it also allows the
// old entry slot to be re-used.
p_bytePut(page, valueHeaderLoc, header & ~ENTRY_FRAGMENTED);
return;
}
}
}
// Copy whole entry into undo log.
txn.pushUndoStore(tree.mId, UndoLog.OP_UNUPDATE, page, entryLoc, loc - entryLoc);
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
long retrieveChildRefId(int pos) {
return p_uint48GetLE(mPage, searchVecEnd() + 2 + (pos << 2));
}
/**
* Retrieves the count of entries for the child node at the given position, or negative if
* unknown. Counts are only applicable to bottom internal nodes, and are invalidated when
* the node is dirty.
*
* @param pos position as provided by binarySearch; must be positive
*/
int retrieveChildEntryCount(int pos) {
return p_ushortGetLE(mPage, searchVecEnd() + (2 + 6) + (pos << 2)) - 1;
}
/**
* Stores the count of entries for the child node at the given position. Counts are only
* applicable to bottom internal nodes, and are invalidated when the node is dirty.
*
* @param pos position as provided by binarySearch; must be positive
* @param count 0..65534
* @see #countNonGhostKeys
*/
void storeChildEntryCount(int pos, int count) {
if (count < 65535) { // safety check
p_shortPutLE(mPage, searchVecEnd() + (2 + 6) + (pos << 2), count + 1);
}
}
/**
* @return length of encoded entry at given location
*/
static int leafEntryLengthAtLoc(/*P*/ byte[] page, final int entryLoc) {
int loc = entryLoc + keyLengthAtLoc(page, entryLoc);
int header = p_byteGet(page, loc++);
if (header >= 0) {
loc += header;
} else {
if ((header & 0x20) == 0) {
loc += 2 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc));
} else if (header != -1) {
loc += 3 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc) << 8) | p_ubyteGet(page, loc + 1));
}
}
return loc - entryLoc;
}
/**
* @return length of encoded key at given location, including the header
*/
static int keyLengthAtLoc(/*P*/ byte[] page, final int keyLoc) {
int header = p_byteGet(page, keyLoc);
return (header >= 0 ? header
: (((header & 0x3f) << 8) | p_ubyteGet(page, keyLoc + 1))) + 2;
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos complement of position as provided by binarySearch; must be positive
* @param okey original key
*/
void insertLeafEntry(TreeCursorFrame frame, Tree tree, int pos, byte[] okey, byte[] value)
throws IOException
{
byte[] akey = okey;
int encodedKeyLen = calculateAllowedKeyLength(tree, okey);
if (encodedKeyLen < 0) {
// Key must be fragmented.
akey = tree.fragmentKey(okey);
encodedKeyLen = 2 + akey.length;
}
try {
int encodedLen = encodedKeyLen + calculateLeafValueLength(value);
int vfrag;
if (encodedLen <= tree.mMaxEntrySize) {
vfrag = 0;
} else {
LocalDatabase db = tree.mDatabase;
value = db.fragment(value, value.length,
db.mMaxFragmentedEntrySize - encodedKeyLen);
if (value == null) {
throw new AssertionError();
}
encodedLen = encodedKeyLen + calculateFragmentedValueLength(value);
vfrag = ENTRY_FRAGMENTED;
}
try {
int entryLoc = createLeafEntry(frame, tree, pos, encodedLen);
if (entryLoc < 0) {
splitLeafAndCreateEntry(tree, okey, akey, vfrag, value, encodedLen, pos, true);
} else {
copyToLeafEntry(okey, akey, vfrag, value, entryLoc);
}
} catch (Throwable e) {
if (vfrag == ENTRY_FRAGMENTED) {
cleanupFragments(e, value);
}
throw e;
}
} catch (Throwable e) {
if (okey != akey) {
cleanupFragments(e, akey);
}
throw e;
}
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos complement of position as provided by binarySearch; must be positive
* @param okey original key
*/
void insertBlankLeafEntry(TreeCursorFrame frame, Tree tree, int pos, byte[] okey, long vlength)
throws IOException
{
byte[] akey = okey;
int encodedKeyLen = calculateAllowedKeyLength(tree, okey);
if (encodedKeyLen < 0) {
// Key must be fragmented.
akey = tree.fragmentKey(okey);
encodedKeyLen = 2 + akey.length;
}
try {
long longEncodedLen = encodedKeyLen + calculateLeafValueLength(vlength);
int encodedLen;
int vfrag;
byte[] value;
if (longEncodedLen <= tree.mMaxEntrySize) {
vfrag = 0;
value = new byte[(int) vlength];
encodedLen = (int) longEncodedLen;
} else {
LocalDatabase db = tree.mDatabase;
value = db.fragment(null, vlength, db.mMaxFragmentedEntrySize - encodedKeyLen);
if (value == null) {
throw new AssertionError();
}
encodedLen = encodedKeyLen + calculateFragmentedValueLength(value);
vfrag = ENTRY_FRAGMENTED;
}
try {
int entryLoc = createLeafEntry(frame, tree, pos, encodedLen);
if (entryLoc < 0) {
splitLeafAndCreateEntry(tree, okey, akey, vfrag, value, encodedLen, pos, true);
} else {
copyToLeafEntry(okey, akey, vfrag, value, entryLoc);
}
} catch (Throwable e) {
if (vfrag == ENTRY_FRAGMENTED) {
cleanupFragments(e, value);
}
throw e;
}
} catch (Throwable e) {
if (okey != akey) {
cleanupFragments(e, akey);
}
throw e;
}
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos complement of position as provided by binarySearch; must be positive
* @param okey original key
*/
void insertFragmentedLeafEntry(TreeCursorFrame frame,
Tree tree, int pos, byte[] okey, byte[] value)
throws IOException
{
byte[] akey = okey;
int encodedKeyLen = calculateAllowedKeyLength(tree, okey);
if (encodedKeyLen < 0) {
// Key must be fragmented.
akey = tree.fragmentKey(okey);
encodedKeyLen = 2 + akey.length;
}
try {
int encodedLen = encodedKeyLen + calculateFragmentedValueLength(value);
int entryLoc = createLeafEntry(frame, tree, pos, encodedLen);
if (entryLoc < 0) {
splitLeafAndCreateEntry
(tree, okey, akey, ENTRY_FRAGMENTED, value, encodedLen, pos, true);
} else {
copyToLeafEntry(okey, akey, ENTRY_FRAGMENTED, value, entryLoc);
}
} catch (Throwable e) {
if (okey != akey) {
cleanupFragments(e, akey);
}
throw e;
}
}
private void panic(Throwable cause) {
try {
getDatabase().close(cause);
} catch (Throwable e) {
// Ignore.
}
}
private void cleanupFragments(Throwable cause, byte[] fragmented) {
if (fragmented != null) {
/*P*/ byte[] copy = p_transfer(fragmented);
try {
getDatabase().deleteFragments(copy, 0, fragmented.length);
} catch (Throwable e) {
cause.addSuppressed(e);
panic(cause);
} finally {
p_delete(copy);
}
}
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos complement of position as provided by binarySearch; must be positive
* @return Location for newly allocated entry, already pointed to by search
* vector, or negative if leaf must be split. Complement of negative value
* is maximum space available.
*/
int createLeafEntry(final TreeCursorFrame frame, Tree tree, int pos, final int encodedLen) {
int searchVecStart = searchVecStart();
int searchVecEnd = searchVecEnd();
int leftSpace = searchVecStart - leftSegTail();
int rightSpace = rightSegTail() - searchVecEnd - 1;
final /*P*/ byte[] page = mPage;
int entryLoc;
alloc: {
if (pos < ((searchVecEnd - searchVecStart + 2) >> 1)) {
// Shift subset of search vector left or prepend.
if ((leftSpace -= 2) >= 0 &&
(entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0)
{
p_copy(page, searchVecStart, page, searchVecStart -= 2, pos);
pos += searchVecStart;
searchVecStart(searchVecStart);
break alloc;
}
// Need to make space, but restore leftSpace value first.
leftSpace += 2;
} else {
// Shift subset of search vector right or append.
if ((rightSpace -= 2) >= 0 &&
(entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0)
{
pos += searchVecStart;
p_copy(page, pos, page, pos + 2, (searchVecEnd += 2) - pos);
searchVecEnd(searchVecEnd);
break alloc;
}
// Need to make space, but restore rightSpace value first.
rightSpace += 2;
}
// Compute remaining space surrounding search vector after insert completes.
int remaining = leftSpace + rightSpace - encodedLen - 2;
if (garbage() > remaining) {
compact: {
// Do full compaction and free up the garbage, or else node must be split.
if (garbage() + remaining < 0) {
// Node compaction won't make enough room, but attempt to rebalance
// before splitting.
TreeCursorFrame parentFrame;
if (frame == null || (parentFrame = frame.mParentFrame) == null) {
// No sibling nodes, so cannot rebalance.
break compact;
}
// "Randomly" choose left or right node first.
if ((mId & 1) == 0) {
int result = tryRebalanceLeafLeft
(tree, parentFrame, pos, encodedLen, -remaining);
if (result == 0) {
// First rebalance attempt failed.
result = tryRebalanceLeafRight
(tree, parentFrame, pos, encodedLen, -remaining);
if (result == 0) {
// Second rebalance attempt failed too, so split.
break compact;
} else if (result > 0) {
return result;
}
} else if (result > 0) {
return result;
} else {
pos += result;
}
} else {
int result = tryRebalanceLeafRight
(tree, parentFrame, pos, encodedLen, -remaining);
if (result == 0) {
// First rebalance attempt failed.
result = tryRebalanceLeafLeft
(tree, parentFrame, pos, encodedLen, -remaining);
if (result == 0) {
// Second rebalance attempt failed too, so split.
break compact;
} else if (result > 0) {
return result;
} else {
pos += result;
}
} else if (result > 0) {
return result;
}
}
}
return compactLeaf(encodedLen, pos, true);
}
// Determine max possible entry size allowed, accounting too for entry pointer,
// key length, and value length. Key and value length might only require only
// require 1 byte fields, but be safe and choose the larger size of 2.
int max = garbage() + leftSpace + rightSpace - (2 + 2 + 2);
return max <= 0 ? -1 : ~max;
}
int vecLen = searchVecEnd - searchVecStart + 2;
int newSearchVecStart;
if (remaining > 0 || (rightSegTail() & 1) != 0) {
// Re-center search vector, biased to the right, ensuring proper alignment.
newSearchVecStart = (rightSegTail() - vecLen + (1 - 2) - (remaining >> 1)) & ~1;
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if ((leftSegTail() & 1) == 0) {
// Move search vector left, ensuring proper alignment.
newSearchVecStart = leftSegTail() + ((remaining >> 1) & ~1);
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// Search vector is misaligned, so do full compaction.
return compactLeaf(encodedLen, pos, true);
}
p_copies(page,
searchVecStart, newSearchVecStart, pos,
searchVecStart + pos, newSearchVecStart + pos + 2, vecLen - pos);
pos += newSearchVecStart;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart + vecLen);
}
// Write pointer to new allocation.
p_shortPutLE(page, pos, entryLoc);
return entryLoc;
}
/**
* Attempt to make room in this node by moving entries to the left sibling node. First
* determines if moving entries to the left node is allowed and would free up enough space.
* Next, attempts to latch parent and child nodes without waiting, avoiding deadlocks.
*
* @param tree required
* @param parentFrame required
* @param pos position to insert into; this position cannot move left
* @param insertLen encoded length of entry to insert
* @param minAmount minimum amount of bytes to move to make room
* @return 0 if try failed, or entry location of re-used slot, or negative 2-based position
* decrement if no slot was found
*/
private int tryRebalanceLeafLeft(Tree tree, TreeCursorFrame parentFrame,
int pos, int insertLen, int minAmount)
{
final /*P*/ byte[] rightPage = mPage;
int moveAmount = 0;
final int lastSearchVecLoc;
int insertLoc = 0;
int insertSlack = Integer.MAX_VALUE;
check: {
int searchVecLoc = searchVecStart();
int searchVecEnd = searchVecLoc + pos - 2;
// Note that loop doesn't examine last entry. At least one must remain.
for (; searchVecLoc < searchVecEnd; searchVecLoc += 2) {
int entryLoc = p_ushortGetLE(rightPage, searchVecLoc);
int encodedLen = leafEntryLengthAtLoc(rightPage, entryLoc);
// Find best fitting slot for insert entry.
int slack = encodedLen - insertLen;
if (slack >= 0 && slack < insertSlack) {
insertLoc = entryLoc;
insertSlack = slack;
}
moveAmount += encodedLen + 2;
if (moveAmount >= minAmount && insertLoc != 0) {
lastSearchVecLoc = searchVecLoc + 2; // +2 to be exclusive
break check;
}
}
return 0;
}
final Node parent = parentFrame.tryAcquireExclusive();
if (parent == null) {
return 0;
}
final int childPos = parentFrame.mNodePos;
if (childPos <= 0
|| parent.mSplit != null
|| parent.mCachedState != mCachedState)
{
// No left child or sanity checks failed.
parent.releaseExclusive();
return 0;
}
final Node left;
try {
left = parent.tryLatchChildNotSplit(childPos - 2);
} catch (IOException e) {
return 0;
}
if (left == null) {
parent.releaseExclusive();
return 0;
}
// Notice that try-finally pattern is not used to release the latches. An uncaught
// exception can only be caused by a bug. Leaving the latches held prevents database
// corruption from being persisted.
final byte[] newKey;
final int newKeyLen;
final /*P*/ byte[] parentPage;
final int parentKeyLoc;
final int parentKeyGrowth;
check: {
try {
int leftAvail = left.availableLeafBytes();
if (leftAvail >= moveAmount) {
// Parent search key will be updated, so verify that it has room.
int highPos = lastSearchVecLoc - searchVecStart();
newKey = midKey(highPos - 2, this, highPos);
// Only attempt rebalance if new key doesn't need to be fragmented.
newKeyLen = calculateAllowedKeyLength(tree, newKey);
if (newKeyLen > 0) {
parentPage = parent.mPage;
parentKeyLoc = p_ushortGetLE
(parentPage, parent.searchVecStart() + childPos - 2);
parentKeyGrowth = newKeyLen - keyLengthAtLoc(parentPage, parentKeyLoc);
if (parentKeyGrowth <= 0 ||
parentKeyGrowth <= parent.availableInternalBytes())
{
// Parent has room for the new search key, so proceed with rebalancing.
break check;
}
}
}
} catch (IOException e) {
// Caused by failed read of a large key. Abort the rebalance attempt.
}
left.releaseExclusive();
parent.releaseExclusive();
return 0;
}
try {
if (tree.mDatabase.markDirty(tree, left)) {
parent.updateChildRefId(childPos - 2, left.mId);
}
} catch (IOException e) {
left.releaseExclusive();
parent.releaseExclusive();
return 0;
}
// Update the parent key.
if (parentKeyGrowth <= 0) {
encodeNormalKey(newKey, parentPage, parentKeyLoc);
parent.garbage(parent.garbage() - parentKeyGrowth);
} else {
parent.updateInternalKey(childPos - 2, parentKeyGrowth, newKey, newKeyLen);
}
int garbageAccum = 0;
int searchVecLoc = searchVecStart();
final int lastPos = lastSearchVecLoc - searchVecLoc;
for (; searchVecLoc < lastSearchVecLoc; searchVecLoc += 2) {
int entryLoc = p_ushortGetLE(rightPage, searchVecLoc);
int encodedLen = leafEntryLengthAtLoc(rightPage, entryLoc);
int leftEntryLoc = left.createLeafEntry
(null, tree, left.highestLeafPos() + 2, encodedLen);
// Note: Must access left page each time, since compaction can replace it.
p_copy(rightPage, entryLoc, left.mPage, leftEntryLoc, encodedLen);
garbageAccum += encodedLen;
}
garbage(garbage() + garbageAccum);
searchVecStart(lastSearchVecLoc);
// Fix cursor positions or move them to the left node.
final int leftEndPos = left.highestLeafPos() + 2;
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
int mask = framePos >> 31;
int newPos = (framePos ^ mask) - lastPos;
// This checks for nodes which should move and also includes not-found frames at
// the low position. They might need to move just higher than the left node high
// position, because the parent key has changed. A new search would position the
// search there. Note that tryRebalanceLeafRight has an identical check, after
// applying De Morgan's law. Because the chosen parent node is not strictly the
// lowest from the right, a comparison must be made to the actual new parent node.
if (newPos < 0 |
((newPos == 0 & mask != 0) && compareUnsigned(frame.mNotFoundKey, newKey) < 0))
{
frame.rebind(left, (leftEndPos + newPos) ^ mask);
frame.adjustParentPosition(-2);
} else {
frame.mNodePos = newPos ^ mask;
}
frame = prev;
}
left.releaseExclusive();
parent.releaseExclusive();
/* Not possible unless aggressive compaction is allowed.
if (insertLoc == 0) {
return -lastPos;
}
*/
// Expand search vector for inserted entry and write pointer to the re-used slot.
garbage(garbage() - insertLen);
pos -= lastPos;
int searchVecStart = searchVecStart();
p_copy(rightPage, searchVecStart, rightPage, searchVecStart -= 2, pos);
searchVecStart(searchVecStart);
p_shortPutLE(rightPage, searchVecStart + pos, insertLoc);
return insertLoc;
}
/**
* Attempt to make room in this node by moving entries to the right sibling node. First
* determines if moving entries to the right node is allowed and would free up enough space.
* Next, attempts to latch parent and child nodes without waiting, avoiding deadlocks.
*
* @param tree required
* @param parentFrame required
* @param pos position to insert into; this position cannot move right
* @param insertLen encoded length of entry to insert
* @param minAmount minimum amount of bytes to move to make room
* @return 0 if try failed, or entry location of re-used slot, or negative if no slot was found
*/
private int tryRebalanceLeafRight(Tree tree, TreeCursorFrame parentFrame,
int pos, int insertLen, int minAmount)
{
final /*P*/ byte[] leftPage = mPage;
int moveAmount = 0;
final int firstSearchVecLoc;
int insertLoc = 0;
int insertSlack = Integer.MAX_VALUE;
check: {
int searchVecStart = searchVecStart() + pos;
int searchVecLoc = searchVecEnd();
// Note that loop doesn't examine first entry. At least one must remain.
for (; searchVecLoc > searchVecStart; searchVecLoc -= 2) {
int entryLoc = p_ushortGetLE(leftPage, searchVecLoc);
int encodedLen = leafEntryLengthAtLoc(leftPage, entryLoc);
// Find best fitting slot for insert entry.
int slack = encodedLen - insertLen;
if (slack >= 0 && slack < insertSlack) {
insertLoc = entryLoc;
insertSlack = slack;
}
moveAmount += encodedLen + 2;
if (moveAmount >= minAmount && insertLoc != 0) {
firstSearchVecLoc = searchVecLoc;
break check;
}
}
return 0;
}
final Node parent = parentFrame.tryAcquireExclusive();
if (parent == null) {
return 0;
}
final int childPos = parentFrame.mNodePos;
if (childPos >= parent.highestInternalPos()
|| parent.mSplit != null
|| parent.mCachedState != mCachedState)
{
// No right child or sanity checks failed.
parent.releaseExclusive();
return 0;
}
final Node right;
try {
right = parent.tryLatchChildNotSplit(childPos + 2);
} catch (IOException e) {
return 0;
}
if (right == null) {
parent.releaseExclusive();
return 0;
}
// Notice that try-finally pattern is not used to release the latches. An uncaught
// exception can only be caused by a bug. Leaving the latches held prevents database
// corruption from being persisted.
final byte[] newKey;
final int newKeyLen;
final /*P*/ byte[] parentPage;
final int parentKeyLoc;
final int parentKeyGrowth;
check: {
try {
int rightAvail = right.availableLeafBytes();
if (rightAvail >= moveAmount) {
// Parent search key will be updated, so verify that it has room.
int highPos = firstSearchVecLoc - searchVecStart();
newKey = midKey(highPos - 2, this, highPos);
// Only attempt rebalance if new key doesn't need to be fragmented.
newKeyLen = calculateAllowedKeyLength(tree, newKey);
if (newKeyLen > 0) {
parentPage = parent.mPage;
parentKeyLoc = p_ushortGetLE
(parentPage, parent.searchVecStart() + childPos);
parentKeyGrowth = newKeyLen - keyLengthAtLoc(parentPage, parentKeyLoc);
if (parentKeyGrowth <= 0 ||
parentKeyGrowth <= parent.availableInternalBytes())
{
// Parent has room for the new search key, so proceed with rebalancing.
break check;
}
}
}
} catch (IOException e) {
// Caused by failed read of a large key. Abort the rebalance attempt.
}
right.releaseExclusive();
parent.releaseExclusive();
return 0;
}
try {
if (tree.mDatabase.markDirty(tree, right)) {
parent.updateChildRefId(childPos + 2, right.mId);
}
} catch (IOException e) {
right.releaseExclusive();
parent.releaseExclusive();
return 0;
}
// Update the parent key.
if (parentKeyGrowth <= 0) {
encodeNormalKey(newKey, parentPage, parentKeyLoc);
parent.garbage(parent.garbage() - parentKeyGrowth);
} else {
parent.updateInternalKey(childPos, parentKeyGrowth, newKey, newKeyLen);
}
int garbageAccum = 0;
int searchVecLoc = searchVecEnd();
final int moved = searchVecLoc - firstSearchVecLoc + 2;
for (; searchVecLoc >= firstSearchVecLoc; searchVecLoc -= 2) {
int entryLoc = p_ushortGetLE(leftPage, searchVecLoc);
int encodedLen = leafEntryLengthAtLoc(leftPage, entryLoc);
int rightEntryLoc = right.createLeafEntry(null, tree, 0, encodedLen);
// Note: Must access right page each time, since compaction can replace it.
p_copy(leftPage, entryLoc, right.mPage, rightEntryLoc, encodedLen);
garbageAccum += encodedLen;
}
garbage(garbage() + garbageAccum);
searchVecEnd(firstSearchVecLoc - 2);
// Fix cursor positions in the right node.
for (TreeCursorFrame frame = right.mLastCursorFrame; frame != null; ) {
int framePos = frame.mNodePos;
int mask = framePos >> 31;
frame.mNodePos = ((framePos ^ mask) + moved) ^ mask;
frame = frame.mPrevCousin;
}
// Move affected cursor frames to the right node.
final int leftEndPos = firstSearchVecLoc - searchVecStart();
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
int mask = framePos >> 31;
int newPos = (framePos ^ mask) - leftEndPos;
// This checks for nodes which should move, but it excludes not-found frames at the
// high position. They might otherwise move to position zero of the right node, but
// the parent key has changed. A new search would position the frame just beyond
// the high position of the left node, which is where it is now. Note that
// tryRebalanceLeafLeft has an identical check, after applying De Morgan's law.
// Because the chosen parent node is not strictly the lowest from the right, a
// comparison must be made to the actual new parent node.
if (newPos >= 0 &
((newPos != 0 | mask == 0) || compareUnsigned(frame.mNotFoundKey, newKey) >= 0))
{
frame.rebind(right, newPos ^ mask);
frame.adjustParentPosition(+2);
}
frame = prev;
}
right.releaseExclusive();
parent.releaseExclusive();
/* Not possible unless aggressive compaction is allowed.
if (insertLoc == 0) {
return -1;
}
*/
// Expand search vector for inserted entry and write pointer to the re-used slot.
garbage(garbage() - insertLen);
pos += searchVecStart();
int newSearchVecEnd = searchVecEnd() + 2;
p_copy(leftPage, pos, leftPage, pos + 2, newSearchVecEnd - pos);
searchVecEnd(newSearchVecEnd);
p_shortPutLE(leftPage, pos, insertLoc);
return insertLoc;
}
/**
* Insert into an internal node following a child node split. This parent node and child
* node must have an exclusive latch held. Parent and child latch are always released, even
* if an exception is thrown.
*
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param keyPos position to insert split key
* @param splitChild child node which split
*/
void insertSplitChildRef(final TreeCursorFrame frame, Tree tree, int keyPos, Node splitChild)
throws IOException
{
final Split split = splitChild.mSplit;
final Node newChild = splitChild.rebindSplitFrames(split);
try {
splitChild.mSplit = null;
//final Node leftChild;
final Node rightChild;
int newChildPos = keyPos >> 1;
if (split.mSplitRight) {
//leftChild = splitChild;
rightChild = newChild;
newChildPos++;
} else {
//leftChild = newChild;
rightChild = splitChild;
}
// Positions of frames higher than split key need to be incremented.
for (TreeCursorFrame f = mLastCursorFrame; f != null; ) {
int fPos = f.mNodePos;
if (fPos > keyPos) {
f.mNodePos = fPos + 2;
}
f = f.mPrevCousin;
}
// Positions of frames equal to split key are in the split itself. Only
// frames for the right split need to be incremented.
for (TreeCursorFrame childFrame = rightChild.mLastCursorFrame; childFrame != null; ) {
childFrame.adjustParentPosition(+2);
childFrame = childFrame.mPrevCousin;
}
// Note: Invocation of createInternalEntry may cause splitInternal to be called,
// which in turn might throw a recoverable exception. State changes can be undone
// by decrementing the incremented frame positions, and then by undoing the
// rebindSplitFrames call. However, this would create an orphaned child node.
// Panicking the database is the safest option.
InResult result = new InResult();
try {
createInternalEntry(frame, result, tree, keyPos, split.splitKeyEncodedLength(),
newChildPos << 3, true);
} catch (Throwable e) {
panic(e);
throw e;
}
// Write new child id.
p_longPutLE(result.mPage, result.mNewChildLoc, newChild.mId);
int entryLoc = result.mEntryLoc;
if (entryLoc < 0) {
// If loc is negative, then node was split and new key was chosen to be promoted.
// It must be written into the new split.
mSplit.setKey(split);
} else {
// Write key entry itself.
split.copySplitKeyToParent(result.mPage, entryLoc);
}
} catch (Throwable e) {
splitChild.releaseExclusive();
newChild.releaseExclusive();
releaseExclusive();
throw e;
}
splitChild.releaseExclusive();
newChild.releaseExclusive();
try {
// Split complete, so allow new node to be evictable.
newChild.makeEvictable();
} catch (Throwable e) {
releaseExclusive();
throw e;
}
}
/**
* Insert into an internal node following a child node split. This parent
* node and child node must have an exclusive latch held. Child latch is
* released, unless an exception is thrown.
*
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param result return result stored here; if node was split, key and entry loc is -1 if
* new key was promoted to parent
* @param keyPos 2-based position
* @param newChildPos 8-based position
* @param allowSplit true if this internal node can be split as a side-effect
* @throws AssertionError if entry must be split to make room but split is not allowed
*/
private void createInternalEntry(final TreeCursorFrame frame, InResult result,
Tree tree, int keyPos, int encodedLen,
int newChildPos, boolean allowSplit)
throws IOException
{
int searchVecStart = searchVecStart();
int searchVecEnd = searchVecEnd();
int leftSpace = searchVecStart - leftSegTail();
int rightSpace = rightSegTail() - searchVecEnd
- ((searchVecEnd - searchVecStart) << 2) - 17;
/*P*/ byte[] page = mPage;
int entryLoc;
alloc: {
// Need to make room for one new search vector entry (2 bytes) and one new child
// id entry (8 bytes). Determine which shift operations minimize movement.
if (newChildPos < ((3 * (searchVecEnd - searchVecStart + 2) + keyPos + 8) >> 1)) {
// Attempt to shift search vector left by 10, shift child ids left by 8.
if ((leftSpace -= 10) >= 0 &&
(entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0)
{
p_copy(page, searchVecStart, page, searchVecStart - 10, keyPos);
p_copy(page, searchVecStart + keyPos,
page, searchVecStart + keyPos - 8,
searchVecEnd - searchVecStart + 2 - keyPos + newChildPos);
searchVecStart(searchVecStart -= 10);
keyPos += searchVecStart;
searchVecEnd(searchVecEnd -= 8);
newChildPos += searchVecEnd + 2;
break alloc;
}
// Need to make space, but restore leftSpace value first.
leftSpace += 10;
} else {
// Attempt to shift search vector left by 2, shift child ids right by 8.
leftSpace -= 2;
rightSpace -= 8;
if (leftSpace >= 0 && rightSpace >= 0 &&
(entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0)
{
p_copy(page, searchVecStart, page, searchVecStart -= 2, keyPos);
searchVecStart(searchVecStart);
keyPos += searchVecStart;
p_copy(page, searchVecEnd + newChildPos + 2,
page, searchVecEnd + newChildPos + (2 + 8),
((searchVecEnd - searchVecStart) << 2) + 8 - newChildPos);
newChildPos += searchVecEnd + 2;
break alloc;
}
// Need to make space, but restore space values first.
leftSpace += 2;
rightSpace += 8;
}
// Compute remaining space surrounding search vector after insert completes.
int remaining = leftSpace + rightSpace - encodedLen - 10;
if (garbage() > remaining) {
compact: {
// Do full compaction and free up the garbage, or else node must be split.
if ((garbage() + remaining) < 0) {
// Node compaction won't make enough room, but attempt to rebalance
// before splitting.
TreeCursorFrame parentFrame;
if (frame == null || (parentFrame = frame.mParentFrame) == null) {
// No sibling nodes, so cannot rebalance.
break compact;
}
// "Randomly" choose left or right node first.
if ((mId & 1) == 0) {
int adjust = tryRebalanceInternalLeft
(tree, parentFrame, keyPos, -remaining);
if (adjust == 0) {
// First rebalance attempt failed.
if (!tryRebalanceInternalRight
(tree, parentFrame, keyPos, -remaining))
{
// Second rebalance attempt failed too, so split.
break compact;
}
} else {
keyPos -= adjust;
newChildPos -= (adjust << 2);
}
} else if (!tryRebalanceInternalRight
(tree, parentFrame, keyPos, -remaining))
{
// First rebalance attempt failed.
int adjust = tryRebalanceInternalLeft
(tree, parentFrame, keyPos, -remaining);
if (adjust == 0) {
// Second rebalance attempt failed too, so split.
break compact;
} else {
keyPos -= adjust;
newChildPos -= (adjust << 2);
}
}
}
compactInternal(result, encodedLen, keyPos, newChildPos);
return;
}
// Node is full, so split it.
if (!allowSplit) {
throw new AssertionError("Split not allowed");
}
// No side-effects if an IOException is thrown here.
splitInternal(result, tree, encodedLen, keyPos, newChildPos);
return;
}
int vecLen = searchVecEnd - searchVecStart + 2;
int childIdsLen = (vecLen << 2) + 8;
int newSearchVecStart;
if (remaining > 0 || (rightSegTail() & 1) != 0) {
// Re-center search vector, biased to the right, ensuring proper alignment.
newSearchVecStart =
(rightSegTail() - vecLen - childIdsLen + (1 - 10) - (remaining >> 1)) & ~1;
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if ((leftSegTail() & 1) == 0) {
// Move search vector left, ensuring proper alignment.
newSearchVecStart = leftSegTail() + ((remaining >> 1) & ~1);
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// Search vector is misaligned, so do full compaction.
compactInternal(result, encodedLen, keyPos, newChildPos);
return;
}
int newSearchVecEnd = newSearchVecStart + vecLen;
p_copies(page,
// Move search vector up to new key position.
searchVecStart, newSearchVecStart, keyPos,
// Move search vector after new key position, to new child id position.
searchVecStart + keyPos,
newSearchVecStart + keyPos + 2,
vecLen - keyPos + newChildPos,
// Move search vector after new child id position.
searchVecEnd + 2 + newChildPos,
newSearchVecEnd + 10 + newChildPos,
childIdsLen - newChildPos);
keyPos += newSearchVecStart;
newChildPos += newSearchVecEnd + 2;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecEnd);
}
// Write pointer to key entry.
p_shortPutLE(page, keyPos, entryLoc);
result.mPage = page;
result.mNewChildLoc = newChildPos;
result.mEntryLoc = entryLoc;
}
/**
* Attempt to make room in this node by moving entries to the left sibling node. First
* determines if moving entries to the left node is allowed and would free up enough space.
* Next, attempts to latch parent and child nodes without waiting, avoiding deadlocks.
*
* @param tree required
* @param parentFrame required
* @param keyPos position to insert into; this position cannot move left
* @param minAmount minimum amount of bytes to move to make room
* @return 2-based position increment; 0 if try failed
*/
private int tryRebalanceInternalLeft(Tree tree, TreeCursorFrame parentFrame,
int keyPos, int minAmount)
{
final Node parent = parentFrame.tryAcquireExclusive();
if (parent == null) {
return 0;
}
final int childPos = parentFrame.mNodePos;
if (childPos <= 0
|| parent.mSplit != null
|| parent.mCachedState != mCachedState)
{
// No left child or sanity checks failed.
parent.releaseExclusive();
return 0;
}
final /*P*/ byte[] parentPage = parent.mPage;
final /*P*/ byte[] rightPage = mPage;
int rightShrink = 0;
int leftGrowth = 0;
final int lastSearchVecLoc;
check: {
int searchVecLoc = searchVecStart();
int searchVecEnd = searchVecLoc + keyPos - 2;
// Note that loop doesn't examine last entry. At least one must remain.
for (; searchVecLoc < searchVecEnd; searchVecLoc += 2) {
int keyLoc = p_ushortGetLE(rightPage, searchVecLoc);
int len = keyLengthAtLoc(rightPage, keyLoc) + (2 + 8);
rightShrink += len;
leftGrowth += len;
if (rightShrink >= minAmount) {
lastSearchVecLoc = searchVecLoc;
// Leftmost key to move comes from the parent, and first moved key in the
// right node does not affect left node growth.
leftGrowth -= len;
keyLoc = p_ushortGetLE(parentPage, parent.searchVecStart() + childPos - 2);
leftGrowth += keyLengthAtLoc(parentPage, keyLoc) + (2 + 8);
break check;
}
}
parent.releaseExclusive();
return 0;
}
final Node left;
try {
left = parent.tryLatchChildNotSplit(childPos - 2);
} catch (IOException e) {
return 0;
}
if (left == null) {
parent.releaseExclusive();
return 0;
}
// Notice that try-finally pattern is not used to release the latches. An uncaught
// exception can only be caused by a bug. Leaving the latches held prevents database
// corruption from being persisted.
final int searchKeyLoc;
final int searchKeyLen;
final int parentKeyLoc;
final int parentKeyLen;
final int parentKeyGrowth;
check: {
int leftAvail = left.availableInternalBytes();
if (leftAvail >= leftGrowth) {
// Parent search key will be updated, so verify that it has room.
searchKeyLoc = p_ushortGetLE(rightPage, lastSearchVecLoc);
searchKeyLen = keyLengthAtLoc(rightPage, searchKeyLoc);
parentKeyLoc = p_ushortGetLE(parentPage, parent.searchVecStart() + childPos - 2);
parentKeyLen = keyLengthAtLoc(parentPage, parentKeyLoc);
parentKeyGrowth = searchKeyLen - parentKeyLen;
if (parentKeyGrowth <= 0 || parentKeyGrowth <= parent.availableInternalBytes()) {
// Parent has room for the new search key, so proceed with rebalancing.
break check;
}
}
left.releaseExclusive();
parent.releaseExclusive();
return 0;
}
try {
if (tree.mDatabase.markDirty(tree, left)) {
parent.updateChildRefId(childPos - 2, left.mId);
}
} catch (IOException e) {
left.releaseExclusive();
parent.releaseExclusive();
return 0;
}
int garbageAccum = searchKeyLen;
int searchVecLoc = searchVecStart();
final int moved = lastSearchVecLoc - searchVecLoc + 2;
try {
// Leftmost key to move comes from the parent.
int pos = left.highestInternalPos();
InResult result = new InResult();
left.createInternalEntry(null, result, tree, pos, parentKeyLen, (pos + 2) << 2, false);
// Note: Must access left page each time, since compaction can replace it.
p_copy(parentPage, parentKeyLoc, left.mPage, result.mEntryLoc, parentKeyLen);
// Remaining keys come from the right node.
for (; searchVecLoc < lastSearchVecLoc; searchVecLoc += 2) {
int keyLoc = p_ushortGetLE(rightPage, searchVecLoc);
int encodedLen = keyLengthAtLoc(rightPage, keyLoc);
pos = left.highestInternalPos();
left.createInternalEntry
(null, result, tree, pos, encodedLen, (pos + 2) << 2, false);
// Note: Must access left page each time, since compaction can replace it.
p_copy(rightPage, keyLoc, left.mPage, result.mEntryLoc, encodedLen);
garbageAccum += encodedLen;
}
} catch (IOException e) {
// Can only be caused by node split, but this is not possible.
throw rethrow(e);
}
// Update the parent key after moving it to the left node.
if (parentKeyGrowth <= 0) {
p_copy(rightPage, searchKeyLoc, parentPage, parentKeyLoc, searchKeyLen);
parent.garbage(parent.garbage() - parentKeyGrowth);
} else {
parent.updateInternalKeyEncoded
(childPos - 2, parentKeyGrowth, rightPage, searchKeyLoc, searchKeyLen);
}
// Move encoded child pointers.
{
int start = searchVecEnd() + 2;
int len = moved << 2;
int end = left.searchVecEnd();
end = end + ((end - left.searchVecStart()) << 2) + (2 + 16) - len;
p_copy(rightPage, start, left.mPage, end, len);
p_copy(rightPage, start + len, rightPage, start, (start - lastSearchVecLoc) << 2);
}
garbage(garbage() + garbageAccum);
searchVecStart(lastSearchVecLoc + 2);
// Fix cursor positions or move them to the left node.
final int leftEndPos = left.highestInternalPos() + 2;
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
int newPos = framePos - moved;
if (newPos < 0) {
frame.rebind(left, leftEndPos + newPos);
frame.adjustParentPosition(-2);
} else {
frame.mNodePos = newPos;
}
frame = prev;
}
left.releaseExclusive();
parent.releaseExclusive();
return moved;
}
/**
* Attempt to make room in this node by moving entries to the right sibling node. First
* determines if moving entries to the right node is allowed and would free up enough space.
* Next, attempts to latch parent and child nodes without waiting, avoiding deadlocks.
*
* @param tree required
* @param parentFrame required
* @param keyPos position to insert into; this position cannot move right
* @param minAmount minimum amount of bytes to move to make room
*/
private boolean tryRebalanceInternalRight(Tree tree, TreeCursorFrame parentFrame,
int keyPos, int minAmount)
{
final Node parent = parentFrame.tryAcquireExclusive();
if (parent == null) {
return false;
}
final int childPos = parentFrame.mNodePos;
if (childPos >= parent.highestInternalPos()
|| parent.mSplit != null
|| parent.mCachedState != mCachedState)
{
// No right child or sanity checks failed.
parent.releaseExclusive();
return false;
}
final /*P*/ byte[] parentPage = parent.mPage;
final /*P*/ byte[] leftPage = mPage;
int leftShrink = 0;
int rightGrowth = 0;
final int firstSearchVecLoc;
check: {
int searchVecStart = searchVecStart() + keyPos;
int searchVecLoc = searchVecEnd();
// Note that loop doesn't examine first entry. At least one must remain.
for (; searchVecLoc > searchVecStart; searchVecLoc -= 2) {
int keyLoc = p_ushortGetLE(leftPage, searchVecLoc);
int len = keyLengthAtLoc(leftPage, keyLoc) + (2 + 8);
leftShrink += len;
rightGrowth += len;
if (leftShrink >= minAmount) {
firstSearchVecLoc = searchVecLoc;
// Rightmost key to move comes from the parent, and first moved key in the
// left node does not affect right node growth.
rightGrowth -= len;
keyLoc = p_ushortGetLE(parentPage, parent.searchVecStart() + childPos);
rightGrowth += keyLengthAtLoc(parentPage, keyLoc) + (2 + 8);
break check;
}
}
parent.releaseExclusive();
return false;
}
final Node right;
try {
right = parent.tryLatchChildNotSplit(childPos + 2);
} catch (IOException e) {
return false;
}
if (right == null) {
parent.releaseExclusive();
return false;
}
// Notice that try-finally pattern is not used to release the latches. An uncaught
// exception can only be caused by a bug. Leaving the latches held prevents database
// corruption from being persisted.
final int searchKeyLoc;
final int searchKeyLen;
final int parentKeyLoc;
final int parentKeyLen;
final int parentKeyGrowth;
check: {
int rightAvail = right.availableInternalBytes();
if (rightAvail >= rightGrowth) {
// Parent search key will be updated, so verify that it has room.
searchKeyLoc = p_ushortGetLE(leftPage, firstSearchVecLoc);
searchKeyLen = keyLengthAtLoc(leftPage, searchKeyLoc);
parentKeyLoc = p_ushortGetLE(parentPage, parent.searchVecStart() + childPos);
parentKeyLen = keyLengthAtLoc(parentPage, parentKeyLoc);
parentKeyGrowth = searchKeyLen - parentKeyLen;
if (parentKeyGrowth <= 0 || parentKeyGrowth <= parent.availableInternalBytes()) {
// Parent has room for the new search key, so proceed with rebalancing.
break check;
}
}
right.releaseExclusive();
parent.releaseExclusive();
return false;
}
try {
if (tree.mDatabase.markDirty(tree, right)) {
parent.updateChildRefId(childPos + 2, right.mId);
}
} catch (IOException e) {
right.releaseExclusive();
parent.releaseExclusive();
return false;
}
int garbageAccum = searchKeyLen;
int searchVecLoc = searchVecEnd();
final int moved = searchVecLoc - firstSearchVecLoc + 2;
try {
// Rightmost key to move comes from the parent.
InResult result = new InResult();
right.createInternalEntry(null, result, tree, 0, parentKeyLen, 0, false);
// Note: Must access right page each time, since compaction can replace it.
p_copy(parentPage, parentKeyLoc, right.mPage, result.mEntryLoc, parentKeyLen);
// Remaining keys come from the left node.
for (; searchVecLoc > firstSearchVecLoc; searchVecLoc -= 2) {
int keyLoc = p_ushortGetLE(leftPage, searchVecLoc);
int encodedLen = keyLengthAtLoc(leftPage, keyLoc);
right.createInternalEntry(null, result, tree, 0, encodedLen, 0, false);
// Note: Must access right page each time, since compaction can replace it.
p_copy(leftPage, keyLoc, right.mPage, result.mEntryLoc, encodedLen);
garbageAccum += encodedLen;
}
} catch (IOException e) {
// Can only be caused by node split, but this is not possible.
throw rethrow(e);
}
// Update the parent key after moving it to the right node.
if (parentKeyGrowth <= 0) {
p_copy(leftPage, searchKeyLoc, parentPage, parentKeyLoc, searchKeyLen);
parent.garbage(parent.garbage() - parentKeyGrowth);
} else {
parent.updateInternalKeyEncoded
(childPos, parentKeyGrowth, leftPage, searchKeyLoc, searchKeyLen);
}
// Move encoded child pointers.
{
int start = searchVecEnd() + 2;
int len = ((start - searchVecStart()) << 2) + 8 - (moved << 2);
p_copy(leftPage, start, leftPage, start - moved, len);
p_copy(leftPage, start + len, right.mPage, right.searchVecEnd() + 2, moved << 2);
}
garbage(garbage() + garbageAccum);
searchVecEnd(firstSearchVecLoc - 2);
// Fix cursor positions in the right node.
for (TreeCursorFrame frame = right.mLastCursorFrame; frame != null; ) {
frame.mNodePos += moved;
frame = frame.mPrevCousin;
}
// Move affected cursor frames to the right node.
final int adjust = firstSearchVecLoc - searchVecStart() + 4;
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int newPos = frame.mNodePos - adjust;
if (newPos >= 0) {
frame.rebind(right, newPos);
frame.adjustParentPosition(+2);
}
frame = prev;
}
right.releaseExclusive();
parent.releaseExclusive();
return true;
}
/**
* Rebind cursor frames affected by split to correct node and
* position. Caller must hold exclusive latch.
*
* @return latched sibling
*/
private Node rebindSplitFrames(Split split) {
final Node sibling = split.latchSiblingEx();
try {
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
split.rebindFrame(frame, sibling);
frame = prev;
}
return sibling;
} catch (Throwable e) {
sibling.releaseExclusive();
throw e;
}
}
/**
* @param frame optional frame which is bound to this node; only used for rebalancing
* @param pos position as provided by binarySearch; must be positive
* @param vfrag 0 or ENTRY_FRAGMENTED
*/
void updateLeafValue(TreeCursorFrame frame, Tree tree, int pos, int vfrag, byte[] value)
throws IOException
{
/*P*/ byte[] page = mPage;
final int searchVecStart = searchVecStart();
final int start;
final int keyLen;
final int garbage;
quick: {
int loc;
start = loc = p_ushortGetLE(page, searchVecStart + pos);
loc += keyLengthAtLoc(page, loc);
final int valueHeaderLoc = loc;
// Note: Similar to leafEntryLengthAtLoc and retrieveLeafValueAtLoc.
int len = p_byteGet(page, loc++);
if (len < 0) largeValue: {
int header;
if ((len & 0x20) == 0) {
header = len;
len = 1 + (((len & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (len != -1) {
header = len;
len = 1 + (((len & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
len = 0;
break largeValue;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
tree.mDatabase.deleteFragments(page, loc, len);
// TODO: If new value needs to be fragmented too, try to
// re-use existing value slot.
if (vfrag == 0) {
// Clear fragmented bit in case new value can be quick copied.
p_bytePut(page, valueHeaderLoc, header & ~ENTRY_FRAGMENTED);
}
}
}
final int valueLen = value.length;
if (valueLen > len) {
// Old entry is too small, and so it becomes garbage.
keyLen = valueHeaderLoc - start;
garbage = garbage() + loc + len - start;
break quick;
}
if (valueLen == len) {
// Quick copy with no garbage created.
if (valueLen == 0) {
// Ensure ghost is replaced.
p_bytePut(page, valueHeaderLoc, 0);
} else {
p_copyFromArray(value, 0, page, loc, valueLen);
if (vfrag != 0) {
p_bytePut(page, valueHeaderLoc, p_byteGet(page, valueHeaderLoc) | vfrag);
}
}
} else {
garbage(garbage() + loc + len - copyToLeafValue
(page, vfrag, value, valueHeaderLoc) - valueLen);
}
return;
}
// What follows is similar to createLeafEntry method, except the search
// vector doesn't grow.
int searchVecEnd = searchVecEnd();
int leftSpace = searchVecStart - leftSegTail();
int rightSpace = rightSegTail() - searchVecEnd - 1;
final int vfragOriginal = vfrag;
int encodedLen;
if (vfrag != 0) {
encodedLen = keyLen + calculateFragmentedValueLength(value);
} else {
encodedLen = keyLen + calculateLeafValueLength(value);
if (encodedLen > tree.mMaxEntrySize) {
LocalDatabase db = tree.mDatabase;
value = db.fragment(value, value.length, db.mMaxFragmentedEntrySize - keyLen);
if (value == null) {
throw new AssertionError();
}
encodedLen = keyLen + calculateFragmentedValueLength(value);
vfrag = ENTRY_FRAGMENTED;
}
}
int entryLoc;
alloc: try {
if ((entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0) {
pos += searchVecStart;
break alloc;
}
// Compute remaining space surrounding search vector after update completes.
int remaining = leftSpace + rightSpace - encodedLen;
if (garbage > remaining) {
// Do full compaction and free up the garbage, or split the node.
byte[][] akeyRef = new byte[1][];
int loc = p_ushortGetLE(page, searchVecStart + pos);
boolean isOriginal = retrieveActualKeyAtLoc(page, loc, akeyRef);
byte[] akey = akeyRef[0];
if ((garbage + remaining) < 0) {
if (mSplit == null) {
// TODO: use frame for rebalancing
// Node is full, so split it.
byte[] okey = isOriginal ? akey : retrieveKeyAtLoc(this, page, loc);
splitLeafAndCreateEntry
(tree, okey, akey, vfrag, value, encodedLen, pos, false);
return;
}
// Node is already split, and so value is too large.
if (vfrag != 0) {
// FIXME: Can this happen?
throw new DatabaseException("Fragmented entry doesn't fit");
}
LocalDatabase db = tree.mDatabase;
int max = Math.min(db.mMaxFragmentedEntrySize,
garbage + leftSpace + rightSpace);
value = db.fragment(value, value.length, max);
if (value == null) {
throw new AssertionError();
}
encodedLen = keyLen + calculateFragmentedValueLength(value);
vfrag = ENTRY_FRAGMENTED;
}
garbage(garbage);
entryLoc = compactLeaf(encodedLen, pos, false);
page = mPage;
entryLoc = isOriginal ? encodeNormalKey(akey, page, entryLoc)
: encodeFragmentedKey(akey, page, entryLoc);
copyToLeafValue(page, vfrag, value, entryLoc);
return;
}
int vecLen = searchVecEnd - searchVecStart + 2;
int newSearchVecStart;
if (remaining > 0 || (rightSegTail() & 1) != 0) {
// Re-center search vector, biased to the right, ensuring proper alignment.
newSearchVecStart = (rightSegTail() - vecLen + (1 - 0) - (remaining >> 1)) & ~1;
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if ((leftSegTail() & 1) == 0) {
// Move search vector left, ensuring proper alignment.
newSearchVecStart = leftSegTail() + ((remaining >> 1) & ~1);
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// Search vector is misaligned, so do full compaction.
byte[][] akeyRef = new byte[1][];
int loc = p_ushortGetLE(page, searchVecStart + pos);
boolean isOriginal = retrieveActualKeyAtLoc(page, loc, akeyRef);
byte[] akey = akeyRef[0];
garbage(garbage);
entryLoc = compactLeaf(encodedLen, pos, false);
page = mPage;
entryLoc = isOriginal ? encodeNormalKey(akey, page, entryLoc)
: encodeFragmentedKey(akey, page, entryLoc);
copyToLeafValue(page, vfrag, value, entryLoc);
return;
}
p_copy(page, searchVecStart, page, newSearchVecStart, vecLen);
pos += newSearchVecStart;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart + vecLen - 2);
} catch (Throwable e) {
if (vfrag == ENTRY_FRAGMENTED && vfragOriginal != ENTRY_FRAGMENTED) {
cleanupFragments(e, value);
}
throw e;
}
// Copy existing key, and then copy value.
p_copy(page, start, page, entryLoc, keyLen);
copyToLeafValue(page, vfrag, value, entryLoc + keyLen);
p_shortPutLE(page, pos, entryLoc);
garbage(garbage);
}
/**
* Update an internal node key to be larger than what is currently allocated. Caller must
* ensure that node has enough space available and that it's not split. New key must not
* force this node to split. Key MUST be a normal, non-fragmented key.
*
* @param pos must be positive
* @param growth key size growth
* @param key normal unencoded key
*/
void updateInternalKey(int pos, int growth, byte[] key, int encodedLen) {
int entryLoc = doUpdateInternalKey(pos, growth, encodedLen);
encodeNormalKey(key, mPage, entryLoc);
}
/**
* Update an internal node key to be larger than what is currently allocated. Caller must
* ensure that node has enough space available and that it's not split. New key must not
* force this node to split.
*
* @param pos must be positive
* @param growth key size growth
* @param key page with encoded key
* @param keyStart encoded key start; includes header
*/
void updateInternalKeyEncoded(int pos, int growth,
/*P*/ byte[] key, int keyStart, int encodedLen)
{
int entryLoc = doUpdateInternalKey(pos, growth, encodedLen);
p_copy(key, keyStart, mPage, entryLoc, encodedLen);
}
/**
* @return entryLoc
*/
int doUpdateInternalKey(int pos, final int growth, final int encodedLen) {
int garbage = garbage() + encodedLen - growth;
// What follows is similar to createInternalEntry method, except the search
// vector doesn't grow.
int searchVecStart = searchVecStart();
int searchVecEnd = searchVecEnd();
int leftSpace = searchVecStart - leftSegTail();
int rightSpace = rightSegTail() - searchVecEnd
- ((searchVecEnd - searchVecStart) << 2) - 17;
int entryLoc;
alloc: {
if ((entryLoc = allocPageEntry(encodedLen, leftSpace, rightSpace)) >= 0) {
pos += searchVecStart;
break alloc;
}
makeRoom: {
// Compute remaining space surrounding search vector after update completes.
int remaining = leftSpace + rightSpace - encodedLen;
if (garbage > remaining) {
// Do full compaction and free up the garbage.
if ((garbage + remaining) < 0) {
// New key doesn't fit.
throw new AssertionError();
}
break makeRoom;
}
int vecLen = searchVecEnd - searchVecStart + 2;
int childIdsLen = (vecLen << 2) + 8;
int newSearchVecStart;
if (remaining > 0 || (rightSegTail() & 1) != 0) {
// Re-center search vector, biased to the right, ensuring proper alignment.
newSearchVecStart =
(rightSegTail() - vecLen - childIdsLen + (1 - 0) - (remaining >> 1)) & ~1;
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if ((leftSegTail() & 1) == 0) {
// Move search vector left, ensuring proper alignment.
newSearchVecStart = leftSegTail() + ((remaining >> 1) & ~1);
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// Search vector is misaligned, so do full compaction.
break makeRoom;
}
/*P*/ byte[] page = mPage;
p_copy(page, searchVecStart, page, newSearchVecStart, vecLen + childIdsLen);
pos += newSearchVecStart;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart + vecLen - 2);
break alloc;
}
// This point is reached for making room via node compaction.
garbage(garbage);
InResult result = new InResult();
compactInternal(result, encodedLen, pos, Integer.MIN_VALUE);
return result.mEntryLoc;
}
// Point to entry. Caller must copy the key to the location.
p_shortPutLE(mPage, pos, entryLoc);
garbage(garbage);
return entryLoc;
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
void updateChildRefId(int pos, long id) {
p_longPutLE(mPage, searchVecEnd() + 2 + (pos << 2), id);
}
/**
* @param pos position as provided by binarySearch; must be positive
*/
void deleteLeafEntry(int pos) throws IOException {
final /*P*/ byte[] page = mPage;
int searchVecStart = searchVecStart();
final int entryLoc = p_ushortGetLE(page, searchVecStart + pos);
// Note: Similar to leafEntryLengthAtLoc and retrieveLeafValueAtLoc.
int loc = entryLoc;
{
int keyLen = p_byteGet(page, loc++);
if (keyLen >= 0) {
loc += keyLen + 1;
} else {
int header = keyLen;
keyLen = ((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++);
if ((header & ENTRY_FRAGMENTED) != 0) {
getDatabase().deleteFragments(page, loc, keyLen);
}
loc += keyLen;
}
}
int header = p_byteGet(page, loc++);
if (header >= 0) {
loc += header;
} else largeValue: {
int len;
if ((header & 0x20) == 0) {
len = 1 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (header != -1) {
len = 1 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
break largeValue;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
getDatabase().deleteFragments(page, loc, len);
}
loc += len;
}
doDeleteLeafEntry(pos, loc - entryLoc);
}
void doDeleteLeafEntry(int pos, int entryLen) {
// Increment garbage by the size of the encoded entry.
garbage(garbage() + entryLen);
/*P*/ byte[] page = mPage;
int searchVecStart = searchVecStart();
int searchVecEnd = searchVecEnd();
if (pos < ((searchVecEnd - searchVecStart + 2) >> 1)) {
// Shift left side of search vector to the right.
p_copy(page, searchVecStart, page, searchVecStart += 2, pos);
searchVecStart(searchVecStart);
} else {
// Shift right side of search vector to the left.
pos += searchVecStart;
p_copy(page, pos + 2, page, pos, searchVecEnd - pos);
searchVecEnd(searchVecEnd - 2);
}
}
/**
* Moves all the entries from the right node into the tail of the given
* left node, and then deletes the right node node. Caller must ensure that
* left node has enough room, and that both nodes are latched exclusively.
* Caller must also hold commit lock. The right node is always released as
* a side effect, but left node is never released by this method.
*/
static void moveLeafToLeftAndDelete(Tree tree, Node leftNode, Node rightNode)
throws IOException
{
tree.mDatabase.prepareToDelete(rightNode);
final /*P*/ byte[] rightPage = rightNode.mPage;
final int searchVecEnd = rightNode.searchVecEnd();
final int leftEndPos = leftNode.highestLeafPos() + 2;
int searchVecStart = rightNode.searchVecStart();
while (searchVecStart <= searchVecEnd) {
int entryLoc = p_ushortGetLE(rightPage, searchVecStart);
int encodedLen = leafEntryLengthAtLoc(rightPage, entryLoc);
int leftEntryLoc = leftNode.createLeafEntry
(null, tree, leftNode.highestLeafPos() + 2, encodedLen);
// Note: Must access left page each time, since compaction can replace it.
p_copy(rightPage, entryLoc, leftNode.mPage, leftEntryLoc, encodedLen);
searchVecStart += 2;
}
// All cursors in the right node must be moved to the left node.
for (TreeCursorFrame frame = rightNode.mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
frame.rebind(leftNode, framePos + (framePos < 0 ? (-leftEndPos) : leftEndPos));
frame = prev;
}
// If right node was high extremity, left node now is.
leftNode.type((byte) (leftNode.type() | (rightNode.type() & HIGH_EXTREMITY)));
tree.mDatabase.deleteNode(rightNode);
}
/**
* Moves all the entries from the right node into the tail of the given
* left node, and then deletes the right node node. Caller must ensure that
* left node has enough room, and that both nodes are latched exclusively.
* Caller must also hold commit lock. The right node is always released as
* a side effect, but left node is never released by this method.
*
* @param parentPage source of entry to merge from parent
* @param parentLoc location of parent entry
* @param parentLen length of parent entry
*/
static void moveInternalToLeftAndDelete(Tree tree, Node leftNode, Node rightNode,
/*P*/ byte[] parentPage, int parentLoc, int parentLen)
throws IOException
{
tree.mDatabase.prepareToDelete(rightNode);
// Create space to absorb parent key.
int leftEndPos = leftNode.highestInternalPos();
InResult result = new InResult();
leftNode.createInternalEntry
(null, result, tree, leftEndPos, parentLen, (leftEndPos += 2) << 2, false);
// Copy child id associated with parent key.
final /*P*/ byte[] rightPage = rightNode.mPage;
int rightChildIdsLoc = rightNode.searchVecEnd() + 2;
p_copy(rightPage, rightChildIdsLoc, result.mPage, result.mNewChildLoc, 8);
rightChildIdsLoc += 8;
// Write parent key.
p_copy(parentPage, parentLoc, result.mPage, result.mEntryLoc, parentLen);
final int searchVecEnd = rightNode.searchVecEnd();
int searchVecStart = rightNode.searchVecStart();
while (searchVecStart <= searchVecEnd) {
int entryLoc = p_ushortGetLE(rightPage, searchVecStart);
int encodedLen = keyLengthAtLoc(rightPage, entryLoc);
// Allocate entry for left node.
int pos = leftNode.highestInternalPos();
leftNode.createInternalEntry
(null, result, tree, pos, encodedLen, (pos + 2) << 2, false);
// Copy child id.
p_copy(rightPage, rightChildIdsLoc, result.mPage, result.mNewChildLoc, 8);
rightChildIdsLoc += 8;
// Copy key.
// Note: Must access left page each time, since compaction can replace it.
p_copy(rightPage, entryLoc, result.mPage, result.mEntryLoc, encodedLen);
searchVecStart += 2;
}
// All cursors in the right node must be moved to the left node.
for (TreeCursorFrame frame = rightNode.mLastCursorFrame; frame != null; ) {
// Capture previous frame from linked list before changing the links.
TreeCursorFrame prev = frame.mPrevCousin;
int framePos = frame.mNodePos;
frame.rebind(leftNode, leftEndPos + framePos);
frame = prev;
}
// If right node was high extremity, left node now is.
leftNode.type((byte) (leftNode.type() | (rightNode.type() & HIGH_EXTREMITY)));
tree.mDatabase.deleteNode(rightNode);
}
/**
* Delete a parent reference to a right child which merged left.
*
* @param childPos non-zero two-based position of the right child
*/
void deleteRightChildRef(int childPos) {
// Fix affected cursors.
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
int framePos = frame.mNodePos;
if (framePos >= childPos) {
frame.mNodePos = framePos - 2;
}
frame = frame.mPrevCousin;
}
deleteChildRef(childPos);
}
/**
* Delete a parent reference to a left child which merged right.
*
* @param childPos two-based position of the left child
*/
void deleteLeftChildRef(int childPos) {
// Fix affected cursors.
for (TreeCursorFrame frame = mLastCursorFrame; frame != null; ) {
int framePos = frame.mNodePos;
if (framePos > childPos) {
frame.mNodePos = framePos - 2;
}
frame = frame.mPrevCousin;
}
deleteChildRef(childPos);
}
/**
* Delete a parent reference to child, but doesn't fix any affected cursors.
*
* @param childPos two-based position
*/
private void deleteChildRef(int childPos) {
final /*P*/ byte[] page = mPage;
int keyPos = childPos == 0 ? 0 : (childPos - 2);
int searchVecStart = searchVecStart();
int entryLoc = p_ushortGetLE(page, searchVecStart + keyPos);
// Increment garbage by the size of the encoded entry.
garbage(garbage() + keyLengthAtLoc(page, entryLoc));
// Rescale for long ids as encoded in page.
childPos <<= 2;
int searchVecEnd = searchVecEnd();
// Remove search vector entry (2 bytes) and remove child id entry
// (8 bytes). Determine which shift operations minimize movement.
if (childPos < (3 * (searchVecEnd - searchVecStart) + keyPos + 8) >> 1) {
// Shift child ids right by 8, shift search vector right by 10.
p_copy(page, searchVecStart + keyPos + 2,
page, searchVecStart + keyPos + (2 + 8),
searchVecEnd - searchVecStart - keyPos + childPos);
p_copy(page, searchVecStart, page, searchVecStart += 10, keyPos);
searchVecEnd(searchVecEnd + 8);
} else {
// Shift child ids left by 8, shift search vector right by 2.
p_copy(page, searchVecEnd + childPos + (2 + 8),
page, searchVecEnd + childPos + 2,
((searchVecEnd - searchVecStart) << 2) + 8 - childPos);
p_copy(page, searchVecStart, page, searchVecStart += 2, keyPos);
}
searchVecStart(searchVecStart);
}
/**
* Delete this non-leaf root node, after all keys have been deleted. The
* state of the lone child is swapped with this root node, and the child
* node is repurposed into a stub root node. The old page used by the child
* node is deleted. This design allows active cursors to still function
* normally until they can unbind.
*
* <p>Caller must hold exclusive latches for root node and lone child.
* Caller must also ensure that both nodes are not splitting. No latches
* are released by this method.
*/
void rootDelete(Tree tree, Node child) throws IOException {
tree.mDatabase.prepareToDelete(child);
/*P*/ byte[] rootPage = mPage;
long toDelete = child.mId;
int toDeleteState = child.mCachedState;
byte stubType = type();
/*P*/ // [
mPage = child.mPage;
type(child.type());
garbage(child.garbage());
leftSegTail(child.leftSegTail());
rightSegTail(child.rightSegTail());
searchVecStart(child.searchVecStart());
searchVecEnd(child.searchVecEnd());
/*P*/ // |
/*P*/ // if (tree.mDatabase.mFullyMapped) {
/*P*/ // // Page cannot change, so copy it instead.
/*P*/ // p_copy(child.mPage, 0, rootPage, 0, tree.mDatabase.pageSize());
/*P*/ // rootPage = child.mPage;
/*P*/ // } else {
/*P*/ // mPage = child.mPage;
/*P*/ // }
/*P*/ // ]
// Repurpose the child node into a stub root node. Stub is assigned a
// reserved id (1) and a clean cached state. It cannot be marked dirty,
// but it can be evicted when all cursors have unbound from it.
tree.mDatabase.nodeMapRemove(child, Long.hashCode(toDelete));
child.mPage = rootPage;
child.mId = STUB_ID;
child.mCachedState = CACHED_CLEAN;
child.type(stubType);
child.clearEntries();
// Search vector also needs to point to root.
p_longPutLE(rootPage, child.searchVecEnd() + 2, this.mId);
// Lock the last frames, preventing concurrent unbinding of those frames...
TreeCursorFrame lock = new TreeCursorFrame();
TreeCursorFrame childLastFrame = child.lockLastFrame(lock);
TreeCursorFrame thisLastFrame = this.lockLastFrame(lock);
// ...now they can be swapped...
if (!TreeCursorFrame.cLastUpdater.compareAndSet(this, thisLastFrame, childLastFrame)) {
throw new AssertionError();
}
if (!TreeCursorFrame.cLastUpdater.compareAndSet(child, childLastFrame, thisLastFrame)) {
throw new AssertionError();
}
// ...and now unlock them. Next reference of last frame is always itself.
childLastFrame.unlock(childLastFrame);
thisLastFrame.unlock(thisLastFrame);
this.fixFrameBindings(lock);
child.fixFrameBindings(lock);
tree.addStub(child, toDelete);
// The page can be deleted earlier in the method, but doing it here
// might prevent corruption if an unexpected exception occurs.
tree.mDatabase.deletePage(toDelete, toDeleteState);
}
/**
* Lock the last frame, for use by the rootDelete method.
*/
private TreeCursorFrame lockLastFrame(TreeCursorFrame lock) {
for (TreeCursorFrame f = mLastCursorFrame; f != null; f = f.mPrevCousin) {
if (f.tryLock(lock) != null) {
return f;
}
}
throw new AssertionError();
}
/**
* Bind all the frames of this node, to this node, for use by the rootDelete method.
*/
private void fixFrameBindings(TreeCursorFrame lock) {
for (TreeCursorFrame f = mLastCursorFrame; f != null; f = f.mPrevCousin) {
TreeCursorFrame lockResult = f.tryLock(lock);
if (lockResult != null) {
f.mNode = this;
f.unlock(lockResult);
}
}
}
private static final int SMALL_KEY_LIMIT = 128;
/**
* Calculate encoded key length, including header. Returns -1 if key is too large and must
* be fragmented.
*/
private static int calculateAllowedKeyLength(Tree tree, byte[] key) {
int len = key.length - 1;
if ((len & ~(SMALL_KEY_LIMIT - 1)) == 0) {
// Always safe because minimum node size is 512 bytes.
return len + 2;
} else {
len++;
return len > tree.mMaxKeySize ? -1 : len + 2;
}
}
/**
* Calculate encoded key length, including header. Key must fit in the node or have been
* fragmented.
*/
static int calculateKeyLength(byte[] key) {
int len = key.length - 1;
return len + ((len & ~(SMALL_KEY_LIMIT - 1)) == 0 ? 2 : 3);
}
/**
* Calculate encoded value length for leaf, including header. Value must fit in the node or
* have been fragmented.
*/
private static int calculateLeafValueLength(byte[] value) {
int len = value.length;
return len + ((len <= 127) ? 1 : ((len <= 8192) ? 2 : 3));
}
/**
* Calculate encoded value length for leaf, including header. Value must fit in the node or
* have been fragmented.
*/
private static long calculateLeafValueLength(long vlength) {
return vlength + ((vlength <= 127) ? 1 : ((vlength <= 8192) ? 2 : 3));
}
/**
* Calculate encoded value length for leaf, including header.
*/
private static int calculateFragmentedValueLength(byte[] value) {
return calculateFragmentedValueLength(value.length);
}
/**
* Calculate encoded value length for leaf, including header.
*/
static int calculateFragmentedValueLength(int vlength) {
return vlength + ((vlength <= 8192) ? 2 : 3);
}
/**
* @param key unencoded key
* @param page destination for encoded key, with room for key header
* @return updated pageLoc
*/
static int encodeNormalKey(final byte[] key, final /*P*/ byte[] page, int pageLoc) {
final int keyLen = key.length;
if (keyLen <= SMALL_KEY_LIMIT && keyLen > 0) {
p_bytePut(page, pageLoc++, keyLen - 1);
} else {
p_bytePut(page, pageLoc++, 0x80 | (keyLen >> 8));
p_bytePut(page, pageLoc++, keyLen);
}
p_copyFromArray(key, 0, page, pageLoc, keyLen);
return pageLoc + keyLen;
}
/**
* @param key fragmented key
* @param page destination for encoded key, with room for key header
* @return updated pageLoc
*/
static int encodeFragmentedKey(final byte[] key, final /*P*/ byte[] page, int pageLoc) {
final int keyLen = key.length;
p_bytePut(page, pageLoc++, (0x80 | ENTRY_FRAGMENTED) | (keyLen >> 8));
p_bytePut(page, pageLoc++, keyLen);
p_copyFromArray(key, 0, page, pageLoc, keyLen);
return pageLoc + keyLen;
}
/**
* @return -1 if not enough contiguous space surrounding search vector
*/
private int allocPageEntry(int encodedLen, int leftSpace, int rightSpace) {
final int entryLoc;
if (encodedLen <= leftSpace && leftSpace >= rightSpace) {
// Allocate entry from left segment.
entryLoc = leftSegTail();
leftSegTail(entryLoc + encodedLen);
} else if (encodedLen <= rightSpace) {
// Allocate entry from right segment.
entryLoc = rightSegTail() - encodedLen + 1;
rightSegTail(entryLoc - 1);
} else {
// No room.
return -1;
}
return entryLoc;
}
/**
* @param okey original key
* @param akey key to actually store
* @param vfrag 0 or ENTRY_FRAGMENTED
*/
private void copyToLeafEntry(byte[] okey, byte[] akey, int vfrag, byte[] value, int entryLoc) {
final /*P*/ byte[] page = mPage;
int vloc = okey == akey ? encodeNormalKey(akey, page, entryLoc)
: encodeFragmentedKey(akey, page, entryLoc);
copyToLeafValue(page, vfrag, value, vloc);
}
/**
* @param vfrag 0 or ENTRY_FRAGMENTED
* @return page location for first byte of value (first location after header)
*/
private static int copyToLeafValue(/*P*/ byte[] page, int vfrag, byte[] value, int vloc) {
final int vlen = value.length;
vloc = encodeLeafValueHeader(page, vfrag, vlen, vloc);
p_copyFromArray(value, 0, page, vloc, vlen);
return vloc;
}
/**
* @param vfrag 0 or ENTRY_FRAGMENTED
* @return page location for first byte of value (first location after header)
*/
static int encodeLeafValueHeader(/*P*/ byte[] page, int vfrag, int vlen, int vloc) {
if (vlen <= 127 && vfrag == 0) {
p_bytePut(page, vloc++, vlen);
} else {
vlen--;
if (vlen <= 8192) {
p_bytePut(page, vloc++, 0x80 | vfrag | (vlen >> 8));
p_bytePut(page, vloc++, vlen);
} else {
p_bytePut(page, vloc++, 0xa0 | vfrag | (vlen >> 16));
p_bytePut(page, vloc++, vlen >> 8);
p_bytePut(page, vloc++, vlen);
}
}
return vloc;
}
/**
* Compact leaf by reclaiming garbage and moving search vector towards
* tail. Caller is responsible for ensuring that new entry will fit after
* compaction. Space is allocated for new entry, and the search vector
* points to it.
*
* @param encodedLen length of new entry to allocate
* @param pos normalized search vector position of entry to insert/update
* @return location for newly allocated entry, already pointed to by search vector
*/
private int compactLeaf(int encodedLen, int pos, boolean forInsert) {
/*P*/ byte[] page = mPage;
int searchVecLoc = searchVecStart();
// Size of search vector, possibly with new entry.
int newSearchVecSize = searchVecEnd() - searchVecLoc + 2;
if (forInsert) {
newSearchVecSize += 2;
}
pos += searchVecLoc;
// Determine new location of search vector, with room to grow on both ends.
int newSearchVecStart;
// Capacity available to search vector after compaction.
int searchVecCap = garbage() + rightSegTail() + 1 - leftSegTail() - encodedLen;
newSearchVecStart = pageSize(page) - (((searchVecCap + newSearchVecSize) >> 1) & ~1);
// Copy into a fresh buffer.
int destLoc = TN_HEADER_SIZE;
int newSearchVecLoc = newSearchVecStart;
int newLoc = 0;
final int searchVecEnd = searchVecEnd();
LocalDatabase db = getDatabase();
/*P*/ byte[] dest = db.removeSparePage();
/*P*/ // [|
/*P*/ // p_intPutLE(dest, 0, type() & 0xff); // set type, reserved byte, and garbage
/*P*/ // ]
for (; searchVecLoc <= searchVecEnd; searchVecLoc += 2, newSearchVecLoc += 2) {
if (searchVecLoc == pos) {
newLoc = newSearchVecLoc;
if (forInsert) {
newSearchVecLoc += 2;
} else {
continue;
}
}
p_shortPutLE(dest, newSearchVecLoc, destLoc);
int sourceLoc = p_ushortGetLE(page, searchVecLoc);
int len = leafEntryLengthAtLoc(page, sourceLoc);
p_copy(page, sourceLoc, dest, destLoc, len);
destLoc += len;
}
/*P*/ // [
// Recycle old page buffer and swap in compacted page.
db.addSparePage(page);
mPage = dest;
garbage(0);
/*P*/ // |
/*P*/ // if (db.mFullyMapped) {
/*P*/ // // Copy compacted entries to original page and recycle spare page buffer.
/*P*/ // p_copy(dest, 0, page, 0, pageSize(page));
/*P*/ // db.addSparePage(dest);
/*P*/ // dest = page;
/*P*/ // } else {
/*P*/ // // Recycle old page buffer and swap in compacted page.
/*P*/ // db.addSparePage(page);
/*P*/ // mPage = dest;
/*P*/ // }
/*P*/ // ]
// Write pointer to new allocation.
p_shortPutLE(dest, newLoc == 0 ? newSearchVecLoc : newLoc, destLoc);
leftSegTail(destLoc + encodedLen);
rightSegTail(pageSize(dest) - 1);
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart + newSearchVecSize - 2);
return destLoc;
}
private void cleanupSplit(Throwable cause, Node newNode, Split split) {
if (split != null) {
cleanupFragments(cause, split.fragmentedKey());
}
try {
getDatabase().deleteNode(newNode, true);
} catch (Throwable e) {
cause.addSuppressed(e);
panic(cause);
}
}
/**
* @param okey original key
* @param akey key to actually store
* @param vfrag 0 or ENTRY_FRAGMENTED
* @param encodedLen length of new entry to allocate
* @param pos normalized search vector position of entry to insert/update
*/
private void splitLeafAndCreateEntry(Tree tree, byte[] okey, byte[] akey,
int vfrag, byte[] value,
int encodedLen, int pos, boolean forInsert)
throws IOException
{
if (mSplit != null) {
throw new AssertionError("Node is already split");
}
// Split can move node entries to a new left or right node. Choose such that the
// new entry is more likely to go into the new node. This distributes the cost of
// the split by postponing compaction of this node.
// Since the split key and final node sizes are not known in advance, don't
// attempt to properly center the new search vector. Instead, minimize
// fragmentation to ensure that split is successful.
/*P*/ byte[] page = mPage;
if (page == p_closedTreePage()) {
// Node is a closed tree root.
throw new ClosedIndexException();
}
Node newNode = tree.mDatabase.allocDirtyNode(NodeUsageList.MODE_UNEVICTABLE);
tree.mDatabase.nodeMapPut(newNode);
/*P*/ byte[] newPage = newNode.mPage;
/*P*/ // [
newNode.garbage(0);
/*P*/ // |
/*P*/ // p_intPutLE(newPage, 0, 0); // set type (fixed later), reserved byte, and garbage
/*P*/ // ]
if (forInsert && pos == 0) {
// Inserting into left edge of node, possibly because inserts are
// descending. Split into new left node, but only the new entry
// goes into the new node.
Split split = null;
try {
split = newSplitLeft(newNode);
// Choose an appropriate middle key for suffix compression.
setSplitKey(tree, split, midKey(okey, 0));
} catch (Throwable e) {
cleanupSplit(e, newNode, split);
throw e;
}
mSplit = split;
// Position search vector at extreme left, allowing new entries to
// be placed in a natural descending order.
newNode.leftSegTail(TN_HEADER_SIZE);
newNode.searchVecStart(TN_HEADER_SIZE);
newNode.searchVecEnd(TN_HEADER_SIZE);
int destLoc = pageSize(newPage) - encodedLen;
newNode.copyToLeafEntry(okey, akey, vfrag, value, destLoc);
p_shortPutLE(newPage, TN_HEADER_SIZE, destLoc);
newNode.rightSegTail(destLoc - 1);
newNode.releaseExclusive();
return;
}
final int searchVecStart = searchVecStart();
final int searchVecEnd = searchVecEnd();
pos += searchVecStart;
if (forInsert && pos == searchVecEnd + 2) {
// Inserting into right edge of node, possibly because inserts are
// ascending. Split into new right node, but only the new entry
// goes into the new node.
Split split = null;
try {
split = newSplitRight(newNode);
// Choose an appropriate middle key for suffix compression.
setSplitKey(tree, split, midKey(pos - searchVecStart - 2, okey));
} catch (Throwable e) {
cleanupSplit(e, newNode, split);
throw e;
}
mSplit = split;
// Position search vector at extreme right, allowing new entries to
// be placed in a natural ascending order.
newNode.rightSegTail(pageSize(newPage) - 1);
int newSearchVecStart = pageSize(newPage) - 2;
newNode.searchVecStart(newSearchVecStart);
newNode.searchVecEnd(newSearchVecStart);
newNode.copyToLeafEntry(okey, akey, vfrag, value, TN_HEADER_SIZE);
p_shortPutLE(newPage, pageSize(newPage) - 2, TN_HEADER_SIZE);
newNode.leftSegTail(TN_HEADER_SIZE + encodedLen);
newNode.releaseExclusive();
return;
}
// Amount of bytes available in unsplit node.
int avail = availableLeafBytes();
int garbageAccum = 0;
int newLoc = 0;
int newAvail = pageSize(newPage) - TN_HEADER_SIZE;
// Guess which way to split by examining search position. This doesn't take into
// consideration the variable size of the entries. If the guess is wrong, the new
// entry is inserted into original node, which now has space.
if ((pos - searchVecStart) < (searchVecEnd - pos)) {
// Split into new left node.
int destLoc = pageSize(newPage);
int newSearchVecLoc = TN_HEADER_SIZE;
int searchVecLoc = searchVecStart;
for (; newAvail > avail; searchVecLoc += 2, newSearchVecLoc += 2) {
int entryLoc = p_ushortGetLE(page, searchVecLoc);
int entryLen = leafEntryLengthAtLoc(page, entryLoc);
if (searchVecLoc == pos) {
if ((newAvail -= encodedLen + 2) < 0) {
// Entry doesn't fit into new node.
break;
}
newLoc = newSearchVecLoc;
if (forInsert) {
// Reserve slot in vector for new entry.
newSearchVecLoc += 2;
if (newAvail <= avail) {
// Balanced enough.
break;
}
} else {
// Don't copy old entry.
garbageAccum += entryLen;
avail += entryLen;
continue;
}
}
if ((newAvail -= entryLen + 2) < 0) {
// Entry doesn't fit into new node.
break;
}
// Copy entry and point to it.
destLoc -= entryLen;
p_copy(page, entryLoc, newPage, destLoc, entryLen);
p_shortPutLE(newPage, newSearchVecLoc, destLoc);
garbageAccum += entryLen;
avail += entryLen + 2;
}
newNode.leftSegTail(TN_HEADER_SIZE);
newNode.searchVecStart(TN_HEADER_SIZE);
newNode.searchVecEnd(newSearchVecLoc - 2);
// Prune off the left end of this node.
final int originalStart = searchVecStart();
final int originalGarbage = garbage();
searchVecStart(searchVecLoc);
garbage(originalGarbage + garbageAccum);
Split split = null;
byte[] fv = null;
try {
split = newSplitLeft(newNode);
if (newLoc == 0) {
// Unable to insert new entry into left node. Insert it
// into the right node, which should have space now.
fv = storeIntoSplitLeaf(tree, okey, akey, vfrag, value, encodedLen, forInsert);
} else {
// Create new entry and point to it.
destLoc -= encodedLen;
newNode.copyToLeafEntry(okey, akey, vfrag, value, destLoc);
p_shortPutLE(newPage, newLoc, destLoc);
}
// Choose an appropriate middle key for suffix compression.
setSplitKey(tree, split, newNode.midKey(newNode.highestKeyPos(), this, 0));
newNode.rightSegTail(destLoc - 1);
newNode.releaseExclusive();
} catch (Throwable e) {
searchVecStart(originalStart);
garbage(originalGarbage);
cleanupFragments(e, fv);
cleanupSplit(e, newNode, split);
throw e;
}
mSplit = split;
} else {
// Split into new right node.
int destLoc = TN_HEADER_SIZE;
int newSearchVecLoc = pageSize(newPage) - 2;
int searchVecLoc = searchVecEnd;
for (; newAvail > avail; searchVecLoc -= 2, newSearchVecLoc -= 2) {
int entryLoc = p_ushortGetLE(page, searchVecLoc);
int entryLen = leafEntryLengthAtLoc(page, entryLoc);
if (forInsert) {
if (searchVecLoc + 2 == pos) {
if ((newAvail -= encodedLen + 2) < 0) {
// Inserted entry doesn't fit into new node.
break;
}
// Reserve spot in vector for new entry.
newLoc = newSearchVecLoc;
newSearchVecLoc -= 2;
if (newAvail <= avail) {
// Balanced enough.
break;
}
}
} else {
if (searchVecLoc == pos) {
if ((newAvail -= encodedLen + 2) < 0) {
// Updated entry doesn't fit into new node.
break;
}
// Don't copy old entry.
newLoc = newSearchVecLoc;
garbageAccum += entryLen;
avail += entryLen;
continue;
}
}
if ((newAvail -= entryLen + 2) < 0) {
// Entry doesn't fit into new node.
break;
}
// Copy entry and point to it.
p_copy(page, entryLoc, newPage, destLoc, entryLen);
p_shortPutLE(newPage, newSearchVecLoc, destLoc);
destLoc += entryLen;
garbageAccum += entryLen;
avail += entryLen + 2;
}
newNode.rightSegTail(pageSize(newPage) - 1);
newNode.searchVecStart(newSearchVecLoc + 2);
newNode.searchVecEnd(pageSize(newPage) - 2);
// Prune off the right end of this node.
final int originalEnd = searchVecEnd();
final int originalGarbage = garbage();
searchVecEnd(searchVecLoc);
garbage(originalGarbage + garbageAccum);
Split split = null;
byte[] fv = null;
try {
split = newSplitRight(newNode);
if (newLoc == 0) {
// Unable to insert new entry into new right node. Insert
// it into the left node, which should have space now.
fv = storeIntoSplitLeaf(tree, okey, akey, vfrag, value, encodedLen, forInsert);
} else {
// Create new entry and point to it.
newNode.copyToLeafEntry(okey, akey, vfrag, value, destLoc);
p_shortPutLE(newPage, newLoc, destLoc);
destLoc += encodedLen;
}
// Choose an appropriate middle key for suffix compression.
setSplitKey(tree, split, this.midKey(this.highestKeyPos(), newNode, 0));
newNode.leftSegTail(destLoc);
newNode.releaseExclusive();
} catch (Throwable e) {
searchVecEnd(originalEnd);
garbage(originalGarbage);
cleanupFragments(e, fv);
cleanupSplit(e, newNode, split);
throw e;
}
mSplit = split;
}
}
/**
* Store an entry into a node which has just been split and has room.
*
* @param okey original key
* @param akey key to actually store
* @param vfrag 0 or ENTRY_FRAGMENTED
* @return non-null if value got fragmented
*/
private byte[] storeIntoSplitLeaf(Tree tree, byte[] okey, byte[] akey,
int vfrag, byte[] value,
int encodedLen, boolean forInsert)
throws IOException
{
int pos = binarySearch(okey);
if (forInsert) {
if (pos >= 0) {
throw new AssertionError("Key exists");
}
int entryLoc = createLeafEntry(null, tree, ~pos, encodedLen);
byte[] result = null;
while (entryLoc < 0) {
if (vfrag != 0) {
// FIXME: Can this happen?
throw new DatabaseException("Fragmented entry doesn't fit");
}
LocalDatabase db = tree.mDatabase;
int max = Math.min(~entryLoc, db.mMaxFragmentedEntrySize);
int encodedKeyLen = calculateKeyLength(akey);
value = db.fragment(value, value.length, max - encodedKeyLen);
if (value == null) {
throw new AssertionError();
}
result = value;
vfrag = ENTRY_FRAGMENTED;
encodedLen = encodedKeyLen + calculateFragmentedValueLength(value);
entryLoc = createLeafEntry(null, tree, ~pos, encodedLen);
}
copyToLeafEntry(okey, akey, vfrag, value, entryLoc);
return result;
} else {
if (pos < 0) {
throw new AssertionError("Key not found");
}
updateLeafValue(null, tree, pos, vfrag, value);
return null;
}
}
/**
* @param result split result stored here; key and entry loc is -1 if new key was promoted
* to parent
* @throws IOException if new node could not be allocated; no side-effects
*/
private void splitInternal(final InResult result,
final Tree tree, final int encodedLen,
final int keyPos, final int newChildPos)
throws IOException
{
if (mSplit != null) {
throw new AssertionError("Node is already split");
}
// Split can move node entries to a new left or right node. Choose such that the
// new entry is more likely to go into the new node. This distributes the cost of
// the split by postponing compaction of this node.
// Alloc early in case an exception is thrown.
final LocalDatabase db = getDatabase();
Node newNode;
try {
newNode = db.allocDirtyNode(NodeUsageList.MODE_UNEVICTABLE);
} catch (DatabaseFullException e) {
// Internal node splits are critical. If a child node reference cannot be inserted,
// then it would be orphaned. Try allocating again without any capacity limit, or
// else the caller must panic the database.
db.capacityLimitOverride(-1);
try {
newNode = db.allocDirtyNode(NodeUsageList.MODE_UNEVICTABLE);
} finally {
db.capacityLimitOverride(0);
}
}
db.nodeMapPut(newNode);
final /*P*/ byte[] newPage = newNode.mPage;
/*P*/ // [
newNode.garbage(0);
/*P*/ // |
/*P*/ // p_intPutLE(newPage, 0, 0); // set type (fixed later), reserved byte, and garbage
/*P*/ // ]
final /*P*/ byte[] page = mPage;
final int searchVecStart = searchVecStart();
final int searchVecEnd = searchVecEnd();
if ((searchVecEnd - searchVecStart) == 2 && keyPos == 2) {
// Node has two keys and the key to insert should go in the middle. The new key
// should not be inserted, but instead be promoted to the parent. Treat this as a
// special case -- the code below only promotes an existing key to the parent.
// This case is expected to only occur when using large keys.
// Allocate Split object first, in case it throws an OutOfMemoryError.
Split split;
try {
split = newSplitLeft(newNode);
} catch (Throwable e) {
cleanupSplit(e, newNode, null);
throw e;
}
// Signals that key should not be inserted.
result.mEntryLoc = -1;
int leftKeyLoc = p_ushortGetLE(page, searchVecStart);
int leftKeyLen = keyLengthAtLoc(page, leftKeyLoc);
// Assume a large key will be inserted later, so arrange it with room: entry at far
// left and search vector at far right.
p_copy(page, leftKeyLoc, newPage, TN_HEADER_SIZE, leftKeyLen);
int leftSearchVecStart = pageSize(newPage) - (2 + 8 + 8);
p_shortPutLE(newPage, leftSearchVecStart, TN_HEADER_SIZE);
if (newChildPos == 8) {
// Caller must store child id into left node.
result.mPage = newPage;
result.mNewChildLoc = leftSearchVecStart + (2 + 8);
} else {
if (newChildPos != 16) {
throw new AssertionError();
}
// Caller must store child id into right node.
result.mPage = page;
result.mNewChildLoc = searchVecEnd + (2 + 8);
}
// Copy one or two left existing child ids to left node (newChildPos is 8 or 16).
p_copy(page, searchVecEnd + 2, newPage, leftSearchVecStart + 2, newChildPos);
newNode.leftSegTail(TN_HEADER_SIZE + leftKeyLen);
newNode.rightSegTail(leftSearchVecStart + (2 + 8 + 8 - 1));
newNode.searchVecStart(leftSearchVecStart);
newNode.searchVecEnd(leftSearchVecStart);
newNode.releaseExclusive();
// Prune off the left end of this node by shifting vector towards child ids.
p_copy(page, searchVecEnd, page, searchVecEnd + 8, 2);
int newSearchVecStart = searchVecEnd + 8;
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecStart);
garbage(garbage() + leftKeyLen);
// Caller must set the split key.
mSplit = split;
return;
}
result.mPage = newPage;
final int keyLoc = keyPos + searchVecStart;
int garbageAccum;
int newKeyLoc;
// Guess which way to split by examining search position. This doesn't take into
// consideration the variable size of the entries. If the guess is wrong, do over
// the other way. Internal splits are infrequent, and split guesses are usually
// correct. For these reasons, it isn't worth the trouble to create a special case
// to charge ahead with the wrong guess. Leaf node splits are more frequent, and
// incorrect guesses are easily corrected due to the simpler leaf node structure.
// -2: left
// -1: guess left
// +1: guess right
// +2: right
int splitSide = (keyPos < (searchVecEnd - searchVecStart - keyPos)) ? -1 : 1;
Split split = null;
doSplit: while (true) {
garbageAccum = 0;
newKeyLoc = 0;
// Amount of bytes used in unsplit node, including the page header.
int size = 5 * (searchVecEnd - searchVecStart) + (1 + 8 + 8)
+ leftSegTail() + pageSize(page) - rightSegTail() - garbage();
int newSize = TN_HEADER_SIZE;
// Adjust sizes for extra child id -- always one more than number of keys.
size -= 8;
newSize += 8;
if (splitSide < 0) {
// Split into new left node.
// Since the split key and final node sizes are not known in advance,
// don't attempt to properly center the new search vector. Instead,
// minimize fragmentation to ensure that split is successful.
int destLoc = pageSize(newPage);
int newSearchVecLoc = TN_HEADER_SIZE;
int searchVecLoc = searchVecStart;
while (true) {
if (searchVecLoc == keyLoc) {
newKeyLoc = newSearchVecLoc;
newSearchVecLoc += 2;
// Reserve slot in vector for new entry and account for size increase.
newSize += encodedLen + (2 + 8);
if (newSize > pageSize(newPage)) {
// New entry doesn't fit.
if (splitSide == -1) {
// Guessed wrong; do over on left side.
splitSide = 2;
continue doSplit;
}
// Impossible split. No room for new entry anywhere.
throw new AssertionError();
}
}
int entryLoc = p_ushortGetLE(page, searchVecLoc);
int entryLen = keyLengthAtLoc(page, entryLoc);
// Size change must incorporate child id, although they are copied later.
int sizeChange = entryLen + (2 + 8);
size -= sizeChange;
newSize += sizeChange;
searchVecLoc += 2;
// Note that last examined key is not moved but is dropped. Garbage must
// account for this.
garbageAccum += entryLen;
boolean full = size < TN_HEADER_SIZE | newSize > pageSize(newPage);
if (full || newSize >= size) {
// New node has accumlated enough entries...
if (newKeyLoc != 0) {
// ...and split key has been found.
try {
split = newSplitLeft(newNode);
setSplitKey(tree, split, retrieveKeyAtLoc(page, entryLoc));
} catch (Throwable e) {
cleanupSplit(e, newNode, split);
throw e;
}
break;
}
if (splitSide == -1) {
// Guessed wrong; do over on right side.
splitSide = 2;
continue doSplit;
}
// Keep searching on this side for new entry location.
if (full || splitSide != -2) {
throw new AssertionError();
}
}
// Copy key entry and point to it.
destLoc -= entryLen;
p_copy(page, entryLoc, newPage, destLoc, entryLen);
p_shortPutLE(newPage, newSearchVecLoc, destLoc);
newSearchVecLoc += 2;
}
result.mEntryLoc = destLoc - encodedLen;
// Copy existing child ids and insert new child id.
{
p_copy(page, searchVecEnd + 2, newPage, newSearchVecLoc, newChildPos);
// Leave gap for new child id, to be set by caller.
result.mNewChildLoc = newSearchVecLoc + newChildPos;
int tailChildIdsLen = ((searchVecLoc - searchVecStart) << 2) - newChildPos;
p_copy(page, searchVecEnd + 2 + newChildPos,
newPage, newSearchVecLoc + newChildPos + 8, tailChildIdsLen);
}
newNode.leftSegTail(TN_HEADER_SIZE);
newNode.rightSegTail(destLoc - encodedLen - 1);
newNode.searchVecStart(TN_HEADER_SIZE);
newNode.searchVecEnd(newSearchVecLoc - 2);
newNode.releaseExclusive();
// Prune off the left end of this node by shifting vector towards child ids.
int shift = (searchVecLoc - searchVecStart) << 2;
int len = searchVecEnd - searchVecLoc + 2;
int newSearchVecStart = searchVecLoc + shift;
p_copy(page, searchVecLoc, page, newSearchVecStart, len);
searchVecStart(newSearchVecStart);
searchVecEnd(searchVecEnd + shift);
} else {
// Split into new right node.
// First copy keys and not the child ids. After keys are copied, shift to
// make room for child ids and copy them in place.
int destLoc = TN_HEADER_SIZE;
int newSearchVecLoc = pageSize(newPage);
int searchVecLoc = searchVecEnd + 2;
moveEntries: while (true) {
if (searchVecLoc == keyLoc) {
newSearchVecLoc -= 2;
newKeyLoc = newSearchVecLoc;
// Reserve slot in vector for new entry and account for size increase.
newSize += encodedLen + (2 + 8);
if (newSize > pageSize(newPage)) {
// New entry doesn't fit.
if (splitSide == 1) {
// Guessed wrong; do over on left side.
splitSide = -2;
continue doSplit;
}
// Impossible split. No room for new entry anywhere.
throw new AssertionError();
}
}
searchVecLoc -= 2;
int entryLoc = p_ushortGetLE(page, searchVecLoc);
int entryLen = keyLengthAtLoc(page, entryLoc);
// Size change must incorporate child id, although they are copied later.
int sizeChange = entryLen + (2 + 8);
size -= sizeChange;
newSize += sizeChange;
// Note that last examined key is not moved but is dropped. Garbage must
// account for this.
garbageAccum += entryLen;
boolean full = size < TN_HEADER_SIZE | newSize > pageSize(newPage);
if (full || newSize >= size) {
// New node has accumlated enough entries...
if (newKeyLoc != 0) {
// ...and split key has been found.
try {
split = newSplitRight(newNode);
setSplitKey(tree, split, retrieveKeyAtLoc(page, entryLoc));
} catch (Throwable e) {
cleanupSplit(e, newNode, split);
throw e;
}
break moveEntries;
}
if (splitSide == 1) {
// Guessed wrong; do over on left side.
splitSide = -2;
continue doSplit;
}
// Keep searching on this side for new entry location.
if (full || splitSide != 2) {
throw new AssertionError();
}
}
// Copy key entry and point to it.
p_copy(page, entryLoc, newPage, destLoc, entryLen);
newSearchVecLoc -= 2;
p_shortPutLE(newPage, newSearchVecLoc, destLoc);
destLoc += entryLen;
}
result.mEntryLoc = destLoc;
// Move new search vector to make room for child ids and be centered between
// the segments.
int newVecLen = pageSize(page) - newSearchVecLoc;
{
int highestLoc = pageSize(newPage) - (5 * newVecLen) - 8;
int midLoc = ((destLoc + encodedLen + highestLoc + 1) >> 1) & ~1;
p_copy(newPage, newSearchVecLoc, newPage, midLoc, newVecLen);
newKeyLoc -= newSearchVecLoc - midLoc;
newSearchVecLoc = midLoc;
}
int newSearchVecEnd = newSearchVecLoc + newVecLen - 2;
// Copy existing child ids and insert new child id.
{
int headChildIdsLen = newChildPos - ((searchVecLoc - searchVecStart + 2) << 2);
int newDestLoc = newSearchVecEnd + 2;
p_copy(page, searchVecEnd + 2 + newChildPos - headChildIdsLen,
newPage, newDestLoc, headChildIdsLen);
// Leave gap for new child id, to be set by caller.
newDestLoc += headChildIdsLen;
result.mNewChildLoc = newDestLoc;
int tailChildIdsLen =
((searchVecEnd - searchVecStart) << 2) + 16 - newChildPos;
p_copy(page, searchVecEnd + 2 + newChildPos,
newPage, newDestLoc + 8, tailChildIdsLen);
}
newNode.leftSegTail(destLoc + encodedLen);
newNode.rightSegTail(pageSize(newPage) - 1);
newNode.searchVecStart(newSearchVecLoc);
newNode.searchVecEnd(newSearchVecEnd);
newNode.releaseExclusive();
// Prune off the right end of this node by shifting vector towards child ids.
int len = searchVecLoc - searchVecStart;
int newSearchVecStart = searchVecEnd + 2 - len;
p_copy(page, searchVecStart, page, newSearchVecStart, len);
searchVecStart(newSearchVecStart);
}
break;
} // end doSplit
garbage(garbage() + garbageAccum);
mSplit = split;
// Write pointer to key entry.
p_shortPutLE(newPage, newKeyLoc, result.mEntryLoc);
}
private void setSplitKey(Tree tree, Split split, byte[] fullKey) throws IOException {
byte[] actualKey = fullKey;
if (calculateAllowedKeyLength(tree, fullKey) < 0) {
// Key must be fragmented.
actualKey = tree.fragmentKey(fullKey);
}
split.setKey(fullKey, actualKey);
}
/**
* Compact internal node by reclaiming garbage and moving search vector
* towards tail. Caller is responsible for ensuring that new entry will fit
* after compaction. Space is allocated for new entry, and the search
* vector points to it.
*
* @param result return result stored here
* @param encodedLen length of new entry to allocate
* @param keyPos normalized search vector position of key to insert/update
* @param childPos normalized search vector position of child node id to insert; pass
* MIN_VALUE if updating
*/
private void compactInternal(InResult result, int encodedLen, int keyPos, int childPos) {
/*P*/ byte[] page = mPage;
int searchVecLoc = searchVecStart();
keyPos += searchVecLoc;
// Size of search vector, possibly with new entry.
int newSearchVecSize = searchVecEnd() - searchVecLoc + (2 + 2) + (childPos >> 30);
// Determine new location of search vector, with room to grow on both ends.
int newSearchVecStart;
// Capacity available to search vector after compaction.
int searchVecCap = garbage() + rightSegTail() + 1 - leftSegTail() - encodedLen;
newSearchVecStart = pageSize(page) -
(((searchVecCap + newSearchVecSize + ((newSearchVecSize + 2) << 2)) >> 1) & ~1);
// Copy into a fresh buffer.
int destLoc = TN_HEADER_SIZE;
int newSearchVecLoc = newSearchVecStart;
int newLoc = 0;
final int searchVecEnd = searchVecEnd();
LocalDatabase db = getDatabase();
/*P*/ byte[] dest = db.removeSparePage();
/*P*/ // [|
/*P*/ // p_intPutLE(dest, 0, type() & 0xff); // set type, reserved byte, and garbage
/*P*/ // ]
for (; searchVecLoc <= searchVecEnd; searchVecLoc += 2, newSearchVecLoc += 2) {
if (searchVecLoc == keyPos) {
newLoc = newSearchVecLoc;
if (childPos >= 0) {
newSearchVecLoc += 2;
} else {
continue;
}
}
p_shortPutLE(dest, newSearchVecLoc, destLoc);
int sourceLoc = p_ushortGetLE(page, searchVecLoc);
int len = keyLengthAtLoc(page, sourceLoc);
p_copy(page, sourceLoc, dest, destLoc, len);
destLoc += len;
}
if (childPos >= 0) {
if (newLoc == 0) {
newLoc = newSearchVecLoc;
newSearchVecLoc += 2;
}
// Copy child ids, and leave room for inserted child id.
p_copy(page, searchVecEnd() + 2, dest, newSearchVecLoc, childPos);
p_copy(page, searchVecEnd() + 2 + childPos,
dest, newSearchVecLoc + childPos + 8,
(newSearchVecSize << 2) - childPos);
} else {
if (newLoc == 0) {
newLoc = newSearchVecLoc;
}
// Copy child ids.
p_copy(page, searchVecEnd() + 2, dest, newSearchVecLoc, (newSearchVecSize << 2) + 8);
}
/*P*/ // [
// Recycle old page buffer and swap in compacted page.
db.addSparePage(page);
mPage = dest;
garbage(0);
/*P*/ // |
/*P*/ // if (db.mFullyMapped) {
/*P*/ // // Copy compacted entries to original page and recycle spare page buffer.
/*P*/ // p_copy(dest, 0, page, 0, pageSize(page));
/*P*/ // db.addSparePage(dest);
/*P*/ // dest = page;
/*P*/ // } else {
/*P*/ // // Recycle old page buffer and swap in compacted page.
/*P*/ // db.addSparePage(page);
/*P*/ // mPage = dest;
/*P*/ // }
/*P*/ // ]
// Write pointer to key entry.
p_shortPutLE(dest, newLoc, destLoc);
leftSegTail(destLoc + encodedLen);
rightSegTail(pageSize(dest) - 1);
searchVecStart(newSearchVecStart);
searchVecEnd(newSearchVecLoc - 2);
result.mPage = dest;
result.mNewChildLoc = newSearchVecLoc + childPos;
result.mEntryLoc = destLoc;
}
/**
* Provides information necessary to complete split by copying split key, pointer to
* split key, and pointer to new child id.
*/
static final class InResult {
/*P*/ byte[] mPage;
int mNewChildLoc; // location of child pointer
int mEntryLoc; // location of key entry, referenced by search vector
}
private Split newSplitLeft(Node newNode) {
Split split = new Split(false, newNode);
// New left node cannot be a high extremity, and this node cannot be a low extremity.
newNode.type((byte) (type() & ~HIGH_EXTREMITY));
type((byte) (type() & ~LOW_EXTREMITY));
return split;
}
private Split newSplitRight(Node newNode) {
Split split = new Split(true, newNode);
// New right node cannot be a low extremity, and this node cannot be a high extremity.
newNode.type((byte) (type() & ~LOW_EXTREMITY));
type((byte) (type() & ~HIGH_EXTREMITY));
return split;
}
/**
* Count the number of cursors bound to this node.
*/
long countCursors() {
// Attempt an exclusive latch to prevent frames from being visited multiple times due
// to recycling.
if (tryAcquireExclusive()) {
long count = 0;
try {
TreeCursorFrame frame = mLastCursorFrame;
while (frame != null) {
count++;
frame = frame.mPrevCousin;
}
} finally {
releaseExclusive();
}
return count;
}
// Iterate over the frames using a lock coupling strategy. Frames which are being
// concurrently removed are skipped over. A shared latch is required to prevent
// observing an in-flight split, which breaks iteration due to rebinding.
acquireShared();
try {
TreeCursorFrame frame = mLastCursorFrame;
if (frame == null) {
return 0;
}
TreeCursorFrame lock = new TreeCursorFrame();
TreeCursorFrame lockResult;
while (true) {
lockResult = frame.tryLock(lock);
if (lockResult != null) {
break;
}
frame = frame.mPrevCousin;
if (frame == null) {
return 0;
}
}
long count = 1;
while (true) {
TreeCursorFrame prev = frame.tryLockPrevious(lock);
frame.unlock(lockResult);
if (prev == null) {
return count;
}
count++;
lockResult = frame;
frame = prev;
}
} finally {
releaseShared();
}
}
/**
* No latches are acquired by this method -- it is only used for debugging.
*/
@Override
@SuppressWarnings("fallthrough")
public String toString() {
String prefix;
switch (type()) {
case TYPE_UNDO_LOG:
return "UndoNode: {id=" + mId +
", cachedState=" + mCachedState +
", topEntry=" + garbage() +
", lowerNodeId=" + + p_longGetLE(mPage, 4) +
", lockState=" + super.toString() +
'}';
/*P*/ // [
case TYPE_FRAGMENT:
return "FragmentNode: {id=" + mId +
", cachedState=" + mCachedState +
", lockState=" + super.toString() +
'}';
/*P*/ // ]
case TYPE_TN_IN:
case (TYPE_TN_IN | LOW_EXTREMITY):
case (TYPE_TN_IN | HIGH_EXTREMITY):
case (TYPE_TN_IN | LOW_EXTREMITY | HIGH_EXTREMITY):
prefix = "Internal";
break;
case TYPE_TN_BIN:
case (TYPE_TN_BIN | LOW_EXTREMITY):
case (TYPE_TN_BIN | HIGH_EXTREMITY):
case (TYPE_TN_BIN | LOW_EXTREMITY | HIGH_EXTREMITY):
prefix = "BottomInternal";
break;
default:
if (!isLeaf()) {
return "Node: {id=" + mId +
", cachedState=" + mCachedState +
", lockState=" + super.toString() +
'}';
}
// Fallthrough...
case TYPE_TN_LEAF:
prefix = "Leaf";
break;
}
return prefix + "Node: {id=" + mId +
", cachedState=" + mCachedState +
", isSplit=" + (mSplit != null) +
", availableBytes=" + availableBytes() +
", extremity=0b" + Integer.toString((type() & (LOW_EXTREMITY | HIGH_EXTREMITY)), 2) +
", lockState=" + super.toString() +
'}';
}
/**
* Caller must acquired shared latch before calling this method. Latch is
* released unless an exception is thrown. If an exception is thrown by the
* observer, the latch would have already been released.
*
* @return false if should stop
*/
boolean verifyTreeNode(int level, VerificationObserver observer) {
int type = type() & ~(LOW_EXTREMITY | HIGH_EXTREMITY);
if (type != TYPE_TN_IN && type != TYPE_TN_BIN && !isLeaf()) {
return verifyFailed(level, observer, "Not a tree node: " + type);
}
final /*P*/ byte[] page = mPage;
if (leftSegTail() < TN_HEADER_SIZE) {
return verifyFailed(level, observer, "Left segment tail: " + leftSegTail());
}
if (searchVecStart() < leftSegTail()) {
return verifyFailed(level, observer, "Search vector start: " + searchVecStart());
}
if (searchVecEnd() < (searchVecStart() - 2)) {
return verifyFailed(level, observer, "Search vector end: " + searchVecEnd());
}
if (rightSegTail() < searchVecEnd() || rightSegTail() > (pageSize(page) - 1)) {
return verifyFailed(level, observer, "Right segment tail: " + rightSegTail());
}
if (!isLeaf()) {
int childIdsStart = searchVecEnd() + 2;
int childIdsEnd = childIdsStart + ((childIdsStart - searchVecStart()) << 2) + 8;
if (childIdsEnd > (rightSegTail() + 1)) {
return verifyFailed(level, observer, "Child ids end: " + childIdsEnd);
}
LHashTable.Int childIds = new LHashTable.Int(512);
for (int i = childIdsStart; i < childIdsEnd; i += 8) {
long childId = p_uint48GetLE(page, i);
if (childId < 0 || childId == 0 || childId == 1) {
return verifyFailed(level, observer, "Illegal child id: " + childId);
}
LHashTable.IntEntry e = childIds.insert(childId);
if (e.value != 0) {
return verifyFailed(level, observer, "Duplicate child id: " + childId);
}
e.value = 1;
}
}
int used = TN_HEADER_SIZE + rightSegTail() + 1 - leftSegTail();
int largeValueCount = 0;
int lastKeyLoc = 0;
int lastKeyLen = 0;
for (int i = searchVecStart(); i <= searchVecEnd(); i += 2) {
int loc = p_ushortGetLE(page, i);
if (loc < TN_HEADER_SIZE || loc >= pageSize(page) ||
(loc >= leftSegTail() && loc <= rightSegTail()))
{
return verifyFailed(level, observer, "Entry location: " + loc);
}
if (isLeaf()) {
used += leafEntryLengthAtLoc(page, loc);
} else {
used += keyLengthAtLoc(page, loc);
}
int keyLen;
try {
keyLen = p_byteGet(page, loc++);
keyLen = keyLen >= 0 ? (keyLen + 1)
: (((keyLen & 0x3f) << 8) | p_ubyteGet(page, loc++));
} catch (IndexOutOfBoundsException e) {
return verifyFailed(level, observer, "Key location out of bounds");
}
if (loc + keyLen > pageSize(page)) {
return verifyFailed(level, observer, "Key end location: " + (loc + keyLen));
}
if (lastKeyLoc != 0) {
int result = p_compareKeysPageToPage(page, lastKeyLoc, lastKeyLen,
page, loc, keyLen);
if (result >= 0) {
return verifyFailed(level, observer, "Key order: " + result);
}
}
lastKeyLoc = loc;
lastKeyLoc = keyLen;
if (isLeaf()) value: {
int len;
try {
loc += keyLen;
int header = p_byteGet(page, loc++);
if (header >= 0) {
len = header;
} else {
if ((header & 0x20) == 0) {
len = 1 + (((header & 0x1f) << 8) | p_ubyteGet(page, loc++));
} else if (header != -1) {
len = 1 + (((header & 0x0f) << 16)
| (p_ubyteGet(page, loc++) << 8) | p_ubyteGet(page, loc++));
} else {
// ghost
break value;
}
if ((header & ENTRY_FRAGMENTED) != 0) {
largeValueCount++;
}
}
} catch (IndexOutOfBoundsException e) {
return verifyFailed(level, observer, "Value location out of bounds");
}
if (loc + len > pageSize(page)) {
return verifyFailed(level, observer, "Value end location: " + (loc + len));
}
}
}
int garbage = pageSize(page) - used;
if (garbage() != garbage) {
return verifyFailed(level, observer, "Garbage: " + garbage() + " != " + garbage);
}
int entryCount = numKeys();
int freeBytes = availableBytes();
long id = mId;
releaseShared();
return observer.indexNodePassed(id, level, entryCount, freeBytes, largeValueCount);
}
private boolean verifyFailed(int level, VerificationObserver observer, String message) {
long id = mId;
releaseShared();
observer.failed = true;
return observer.indexNodeFailed(id, level, message);
}
}
| Remove false assertion. A concurrent unbind can prevent a rebind from finishing, and so a non-null last cursor frame can be briefly observed after the rebinding is complete.
| src/main/java/org/cojen/tupl/Node.java | Remove false assertion. A concurrent unbind can prevent a rebind from finishing, and so a non-null last cursor frame can be briefly observed after the rebinding is complete. | <ide><path>rc/main/java/org/cojen/tupl/Node.java
<ide> TreeCursorFrame prev = frame.mPrevCousin;
<ide> frame.rebind(child, frame.mNodePos);
<ide> frame = prev;
<del> }
<del>
<del> if (mLastCursorFrame != null) {
<del> throw new AssertionError();
<ide> }
<ide>
<ide> Node left, right; |
|
Java | mit | 551cc3c900a9fdb0d4fa04c403bac85360961f5e | 0 | shyiko/ktlint,shyiko/ktlint,shyiko/ktlint,shyiko/ktlint | package com.github.shyiko.ktlint.idea;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
private Main() {}
public static void main(String[] args) throws Exception {
Arrays.sort(args);
final boolean help = Arrays.binarySearch(args, "--help") > -1;
final boolean version = Arrays.binarySearch(args, "--version") > -1;
final boolean apply = Arrays.binarySearch(args, "apply") > -1 && !help;
final boolean forceApply = Arrays.binarySearch(args, "-y") > -1;
if (version) {
System.err.println(Main.class.getPackage().getImplementationVersion());
System.exit(0);
}
if (apply) {
try {
final Path workDir = Paths.get(".");
if (!forceApply) {
final Path[] fileList = KtLintIntellijIDEAIntegration.apply(workDir, true);
System.err.println("The following files are going to be updated:\n\n\t" +
Arrays.stream(fileList).map(Path::toString).collect(Collectors.joining("\n\t")) +
"\n\nDo you wish to proceed? [y/n]\n" +
"(in future, use -y flag if you wish to skip confirmation)");
final Scanner scanner = new Scanner(System.in);
final String res = Stream.generate(() -> {
try { return scanner.next(); } catch (NoSuchElementException e) { return "n"; }
})
.filter(line -> !line.trim().isEmpty())
.findFirst()
.get();
if (!"y".equalsIgnoreCase(res)) {
System.err.println("(update canceled)");
System.exit(1);
}
}
KtLintIntellijIDEAIntegration.apply(workDir, false);
} catch (KtLintIntellijIDEAIntegration.ProjectNotFoundException e) {
System.err.println(".idea directory not found. " +
"Are you sure you are inside project root directory?");
System.exit(1);
}
System.err.println("(updated)");
System.err.println("\nPlease restart your IDE");
System.err.println("(if you experience any issues please report them at https://github.com/shyiko/ktlint)");
} else {
System.err.println(
"ktlint Intellij IDEA integration (https://github.com/shyiko/ktlint).\n" +
"\n" +
"Usage:\n" +
" ktlint-intellij-idea-integration <flags> apply\n" +
" java -jar ktlint-intellij-idea-integration <flags> apply\n" +
"\n" +
"Flags:\n" +
" --version : Version\n"
);
if (!help) {
System.exit(1);
}
}
}
}
| ktlint-intellij-idea-integration/src/main/java/com/github/shyiko/ktlint/idea/Main.java | package com.github.shyiko.ktlint.idea;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
private Main() {}
public static void main(String[] args) throws Exception {
Arrays.sort(args);
final boolean help = Arrays.binarySearch(args, "--help") > -1;
final boolean version = Arrays.binarySearch(args, "--version") > -1;
final boolean apply = Arrays.binarySearch(args, "apply") > -1 && !help;
final boolean forceApply = Arrays.binarySearch(args, "-y") > -1;
if (version) {
System.err.println(Main.class.getPackage().getImplementationVersion());
System.exit(0);
}
if (apply) {
try {
final Path workDir = Paths.get(".");
if (!forceApply) {
final Path[] fileList = KtLintIntellijIDEAIntegration.apply(workDir, true);
System.err.println("The following files are going to be updated:\n\n\t" +
Arrays.stream(fileList).map(Path::toString).collect(Collectors.joining("\n\t")) +
"\n\nDo you wish to proceed? [y/n]\n" +
"(in future, use -y flag if you wish to skip confirmation)");
final Scanner scanner = new Scanner(System.in);
final String res = Stream.generate(() -> {
try { return scanner.next(); } catch (NoSuchElementException e) { return "n"; }
})
.filter(line -> !line.trim().isEmpty())
.findFirst()
.get();
if (!"y".equalsIgnoreCase(res)) {
System.err.println("(update canceled)");
System.exit(1);
}
}
KtLintIntellijIDEAIntegration.apply(workDir, false);
} catch (KtLintIntellijIDEAIntegration.ProjectNotFoundException e) {
System.err.println(".idea directory not found. " +
"Are you sure you are executing \"apply\" inside project root directory?");
System.exit(1);
}
System.err.println("(updated)");
System.err.println("\nPlease restart your IDE");
System.err.println("(if you experience any issues please report them at https://github.com/shyiko/ktlint)");
} else {
System.err.println(
"ktlint Intellij IDEA integration (https://github.com/shyiko/ktlint).\n" +
"\n" +
"Usage:\n" +
" ktlint-intellij-idea-integration <flags> apply\n" +
" java -jar ktlint-intellij-idea-integration <flags> apply\n" +
"\n" +
"Flags:\n" +
" --version : Version\n"
);
if (!help) {
System.exit(1);
}
}
}
}
| Updated --apply-to-idea error message shown when .idea directory isn't found
| ktlint-intellij-idea-integration/src/main/java/com/github/shyiko/ktlint/idea/Main.java | Updated --apply-to-idea error message shown when .idea directory isn't found | <ide><path>tlint-intellij-idea-integration/src/main/java/com/github/shyiko/ktlint/idea/Main.java
<ide> KtLintIntellijIDEAIntegration.apply(workDir, false);
<ide> } catch (KtLintIntellijIDEAIntegration.ProjectNotFoundException e) {
<ide> System.err.println(".idea directory not found. " +
<del> "Are you sure you are executing \"apply\" inside project root directory?");
<add> "Are you sure you are inside project root directory?");
<ide> System.exit(1);
<ide> }
<ide> System.err.println("(updated)"); |
|
Java | mit | cfd3bd8a0e6c2108827bf4c65a09b1b6a12db760 | 0 | Quiqucode/Flow,Quiqucode/Flow,Quiqucode/Flow | package flow.compiled;
public abstract class Compiled {
/*
* Psuedo-Compilation for Tokenised code.
* Returns a simpler version of source code.
*/
}
| FlowLanguage/src/flow/compiled/Compiled.java | package flow.compiled;
public class Compiled {
//Testing testing 123
}
| Updated compiled.java | FlowLanguage/src/flow/compiled/Compiled.java | Updated compiled.java | <ide><path>lowLanguage/src/flow/compiled/Compiled.java
<ide> package flow.compiled;
<ide>
<del>public class Compiled {
<del> //Testing testing 123
<add>public abstract class Compiled {
<add> /*
<add> * Psuedo-Compilation for Tokenised code.
<add> * Returns a simpler version of source code.
<add> */
<ide>
<ide> } |
|
Java | lgpl-2.1 | 4cac3bea58d17a479f94c55b42696cb8f0c7f0ae | 0 | getrailo/railo,JordanReiter/railo,JordanReiter/railo,modius/railo,getrailo/railo,getrailo/railo,modius/railo | package railo.runtime.type.scope;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import railo.commons.lang.CFTypes;
import railo.runtime.PageContext;
import railo.runtime.dump.DumpData;
import railo.runtime.dump.DumpProperties;
import railo.runtime.dump.DumpTable;
import railo.runtime.dump.DumpUtil;
import railo.runtime.dump.SimpleDumpData;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.op.Caster;
import railo.runtime.op.Decision;
import railo.runtime.type.Array;
import railo.runtime.type.ArrayImpl;
import railo.runtime.type.Collection;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.Struct;
import railo.runtime.type.StructImpl;
import railo.runtime.type.UDF;
import railo.runtime.type.util.CollectionUtil;
import railo.runtime.type.util.MemberUtil;
import railo.runtime.type.wrap.ArrayAsList;
/**
* implementation of the argument scope
*/
public final class ArgumentImpl extends ScopeSupport implements Argument {
private boolean bind;
private Set functionArgumentNames;
//private boolean supportFunctionArguments;
/**
* constructor of the class
*/
public ArgumentImpl() {
super("arguments",SCOPE_ARGUMENTS,Struct.TYPE_LINKED);
//this(true);
}
/**
* @see railo.runtime.type.scope.ScopeSupport#release()
*/
public void release() {
functionArgumentNames=null;
super.release();
}
@Override
public void release(PageContext pc) {
functionArgumentNames=null;
super.release(pc);
}
/**
* @see railo.runtime.type.scope.Argument#setBind(boolean)
*/
public void setBind(boolean bind) {
this.bind=bind;
}
/**
* @see railo.runtime.type.scope.Argument#isBind()
*/
public boolean isBind() {
return this.bind;
}
public Object getFunctionArgument(String key, Object defaultValue) {
return getFunctionArgument(KeyImpl.getInstance(key), defaultValue);
}
public Object getFunctionArgument(Collection.Key key, Object defaultValue) {
return super.get(key,defaultValue);
}
/**
* @see railo.runtime.type.scope.ArgumentPro#containsFunctionArgumentKey(railo.runtime.type.Collection.Key)
*/
public boolean containsFunctionArgumentKey(Key key) {
return super.containsKey(key);//functionArgumentNames!=null && functionArgumentNames.contains(key);
}
/**
*
* @see railo.runtime.type.StructImpl#get(railo.runtime.type.Collection.Key, java.lang.Object)
*/
public Object get(Collection.Key key, Object defaultValue) {
Object o=super.get(key,null);
if(o!=null)return o;
//char c = key.charAt(0);
//if(!Character.isDigit(c) && c!='+') return defaultValue; // it make sense to have this step between
o=get(Caster.toIntValue(key.getString(),-1),null);
if(o!=null)return o;
return defaultValue;
}
/**
*
* @see railo.runtime.type.StructImpl#get(railo.runtime.type.Collection.Key)
*/
public Object get(Collection.Key key) throws ExpressionException {
Object o=super.get(key,null);
if(o!=null)return o;
//char c = key.charAt(0);
//if(Character.isDigit(c) || c=='+') {
o=get(Caster.toIntValue(key.getString(),-1),null);
if(o!=null)return o;
//}
throw new ExpressionException("key ["+key.getString()+"] doesn't exist in argument scope. existing keys are ["+
railo.runtime.type.List.arrayToList(CollectionUtil.keys(this),", ")
+"]");
}
/**
*
* @see railo.runtime.type.Array#get(int, java.lang.Object)
*/
public Object get(int intKey, Object defaultValue) {
Iterator<Object> it = valueIterator(); //keyIterator();//getMap().keySet().iterator();
int count=0;
Object o;
while(it.hasNext()) {
o=it.next();
if((++count)==intKey) {
return o;//super.get(o.toString(),defaultValue);
}
}
return defaultValue;
}
/**
* return a value matching to key
* @param intKey
* @return value matching key
* @throws PageException
*/
public Object getE(int intKey) throws PageException {
Iterator it = valueIterator();//getMap().keySet().iterator();
int count=0;
Object o;
while(it.hasNext()) {
o=it.next();
if((++count)==intKey) {
return o;//super.get(o.toString());
}
}
throw new ExpressionException("invalid index ["+intKey+"] for argument scope");
}
/**
* @see railo.runtime.dump.Dumpable#toDumpData(railo.runtime.PageContext, int)
*/
public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) {
DumpTable htmlBox = new DumpTable("struct","#9999ff","#ccccff","#000000");
htmlBox.setTitle("Scope Arguments");
if(size()>10 && dp.getMetainfo())htmlBox.setComment("Entries:"+size());
maxlevel--;
//Map mapx=getMap();
Iterator it=keyIterator();//mapx.keySet().iterator();
int count=0;
Collection.Key key;
int maxkeys=dp.getMaxKeys();
int index=0;
while(it.hasNext()) {
key=KeyImpl.toKey(it.next(), null);//it.next();
if(DumpUtil.keyValid(dp, maxlevel,key)){
if(maxkeys<=index++)break;
htmlBox.appendRow(3,
new SimpleDumpData(key.getString()),
new SimpleDumpData(++count),
DumpUtil.toDumpData(get(key,null),
pageContext,maxlevel,dp));
}
}
return htmlBox;
}
/**
* @see railo.runtime.type.Array#getDimension()
*/
public int getDimension() {
return 1;
}
/**
* @see railo.runtime.type.Array#setEL(int, java.lang.Object)
*/
public Object setEL(int intKey, Object value) {
int count=0;
if(intKey>size()) {
return setEL(Caster.toString(intKey),value);
}
//Iterator it = keyIterator();
Key[] keys = keys();
for(int i=0;i<keys.length;i++) {
if((++count)==intKey) {
return super.setEL(keys[i],value);
}
}
return value;
}
/**
* @see railo.runtime.type.Array#setE(int, java.lang.Object)
*/
public Object setE(int intKey, Object value) throws PageException {
if(intKey>size()) {
return set(Caster.toString(intKey),value);
}
//Iterator it = keyIterator();
Key[] keys = keys();
for(int i=0;i<keys.length;i++) {
if((i+1)==intKey) {
return super.set(keys[i],value);
}
}
throw new ExpressionException("invalid index ["+intKey+"] for argument scope");
}
/**
* @see railo.runtime.type.Array#intKeys()
*/
public int[] intKeys() {
int[] ints=new int[size()];
for(int i=0;i<ints.length;i++)ints[i]=i+1;
return ints;
}
/**
* @see railo.runtime.type.Array#insert(int, java.lang.Object)
*/
public boolean insert(int index, Object value) throws ExpressionException {
return insert(index, ""+index, value);
}
/**
* @see railo.runtime.type.scope.Argument#insert(int, java.lang.String, java.lang.Object)
*/
public boolean insert(int index, String key, Object value) throws ExpressionException {
int len=size();
if(index<1 || index>len)
throw new ExpressionException("invalid index to insert a value to argument scope",len==0?"can't insert in a empty argument scope":"valid index goes from 1 to "+(len-1));
// remove all upper
LinkedHashMap lhm = new LinkedHashMap();
Collection.Key[] keys=keys();
Collection.Key k;
for(int i=1;i<=keys.length;i++) {
if(i<index)continue;
k=keys[i-1];
lhm.put(k.getString(),get(k,null));
removeEL(k);
}
// set new value
setEL(key,value);
// reset upper values
Iterator it = lhm.entrySet().iterator();
Map.Entry entry;
while(it.hasNext()) {
entry=(Entry) it.next();
setEL(KeyImpl.toKey(entry.getKey()),entry.getValue());
}
return true;
}
/**
* @see railo.runtime.type.Array#append(java.lang.Object)
*/
public Object append(Object o) throws PageException {
return set(Caster.toString(size()+1),o);
}
/**
* @see railo.runtime.type.Array#appendEL(java.lang.Object)
*/
public Object appendEL(Object o) {
try {
return append(o);
} catch (PageException e) {
return null;
}
}
/**
* @see railo.runtime.type.Array#prepend(java.lang.Object)
*/
public Object prepend(Object o) throws PageException {
for(int i=size();i>0;i--) {
setE(i+1,getE(i));
}
setE(1,o);
return o;
}
/**
* @see railo.runtime.type.Array#resize(int)
*/
public void resize(int to) throws PageException {
for(int i=size(); i<to; i++) {
append(null);
}
//throw new ExpressionException("can't resize this array");
}
/**
* @see railo.runtime.type.Array#sort(java.lang.String, java.lang.String)
*/
public void sort(String sortType, String sortOrder) throws ExpressionException {
// TODO Impl.
throw new ExpressionException("can't sort ["+sortType+"-"+sortOrder+"] Argument Scope","not Implemnted Yet");
}
public void sort(Comparator com) throws ExpressionException {
// TODO Impl.
throw new ExpressionException("can't sort Argument Scope","not Implemnted Yet");
}
/**
* @see railo.runtime.type.Array#toArray()
*/
public Object[] toArray() {
Iterator it = keyIterator();//getMap().keySet().iterator();
Object[] arr=new Object[size()];
int count=0;
while(it.hasNext()) {
arr[count++]=it.next();
}
return arr;
}
public Object setArgument(Object obj) throws PageException {
if(obj==this) return obj;
if(Decision.isStruct(obj)) {
clear(); // TODO bessere impl. anstelle vererbung wrao auf struct
Struct sct=Caster.toStruct(obj);
Iterator it = sct.keyIterator();
String key;
while(it.hasNext()) {
key=it.next().toString();
setEL(key, sct.get(key,null));
}
return obj;
}
throw new ExpressionException("can not overwrite arguments scope");
}
/**
* @see railo.runtime.type.Array#toArrayList()
*/
public ArrayList toArrayList() {
ArrayList list = new ArrayList();
Object[] arr = toArray();
for(int i=0;i<arr.length;i++) {
list.add(arr[i]);
}
return list;
}
/**
* @see railo.runtime.type.Array#removeE(int)
*/
public Object removeE(int intKey) throws PageException {
Key[] keys = keys();
for(int i=0;i<keys.length;i++) {
if((i+1)==intKey) {
return super.remove(keys[i]);
}
}
throw new ExpressionException("can't remove argument number ["+intKey+"], argument doesn't exist");
}
/**
* @see railo.runtime.type.Array#removeEL(int)
*/
public Object removeEL(int intKey) {
Key[] keys = keys();
for(int i=0;i<keys.length;i++) {
if((i+1)==intKey) {
return super.removeEL (keys[i]);
}
}
return null;
}
/**
* @see railo.runtime.type.StructImpl#containsKey(railo.runtime.type.Collection.Key)
*/
public boolean containsKey(Collection.Key key) {
if(super.containsKey(key)) return true;
char c = key.charAt(0);
if(!Character.isDigit(c) && c!='+') return false; // it make sense to have this step between
return containsKey(Caster.toIntValue(key.getString(),-1));
}
/**
* @see railo.runtime.type.Array#containsKey(int)
*/
public boolean containsKey(int key) {
return key>0 && key<=size();
}
/**
* @see railo.runtime.type.Array#toList()
*/
public List toList() {
return ArrayAsList.toList(this);
}
/**
* @see railo.runtime.type.StructImpl#duplicate(boolean)
*/
public Collection duplicate(boolean deepCopy) {
ArgumentImpl trg=new ArgumentImpl();
trg.bind=false;
trg.functionArgumentNames=functionArgumentNames;
//trg.supportFunctionArguments=supportFunctionArguments;
copy(this,trg,deepCopy);
return trg;
}
public void setFunctionArgumentNames(Set functionArgumentNames) {// future add to interface
this.functionArgumentNames=functionArgumentNames;
}
/*
public void setNamedArguments(boolean namedArguments) {
this.namedArguments=namedArguments;
}
public boolean isNamedArguments() {
return namedArguments;
}
*/
/**
* converts a argument scope to a regular struct
* @param arg argument scope to convert
* @return resulting struct
*/
public static Struct toStruct(Argument arg) {
Struct trg=new StructImpl();
StructImpl.copy(arg, trg, false);
return trg;
}
/**
* converts a argument scope to a regular array
* @param arg argument scope to convert
* @return resulting array
*/
public static Array toArray(Argument arg) {
ArrayImpl trg=new ArrayImpl();
int[] keys = arg.intKeys();
for(int i=0;i<keys.length;i++){
trg.setEL(keys[i],
arg.get(keys[i],null));
}
return trg;
}
@Override
public Object get(PageContext pc, Key key, Object defaultValue) {
return get(key, defaultValue);
}
@Override
public Object get(PageContext pc, Key key) throws PageException {
return get(key);
}
@Override
public Object set(PageContext pc, Key propertyName, Object value) throws PageException {
return set(propertyName, value);
}
@Override
public Object setEL(PageContext pc, Key propertyName, Object value) {
return setEL(propertyName, value);
}
@Override
public Object call(PageContext pc, Key methodName, Object[] args) throws PageException {
Object obj = get(methodName,null);
if(obj instanceof UDF) {
return ((UDF)obj).call(pc,args,false);
}
return MemberUtil.call(pc, this, methodName, args, CFTypes.TYPE_ARRAY, "array");
}
@Override
public Object callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException {
Object obj = get(methodName,null);
if(obj instanceof UDF) {
return ((UDF)obj).callWithNamedValues(pc,args,false);
}
return MemberUtil.callWithNamedValues(pc,this,methodName,args, CFTypes.TYPE_ARRAY, "array");
}
} | railo-java/railo-core/src/railo/runtime/type/scope/ArgumentImpl.java | package railo.runtime.type.scope;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import railo.commons.lang.CFTypes;
import railo.runtime.PageContext;
import railo.runtime.dump.DumpData;
import railo.runtime.dump.DumpProperties;
import railo.runtime.dump.DumpTable;
import railo.runtime.dump.DumpUtil;
import railo.runtime.dump.SimpleDumpData;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.op.Caster;
import railo.runtime.op.Decision;
import railo.runtime.type.Array;
import railo.runtime.type.ArrayImpl;
import railo.runtime.type.Collection;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.Struct;
import railo.runtime.type.StructImpl;
import railo.runtime.type.UDF;
import railo.runtime.type.util.CollectionUtil;
import railo.runtime.type.util.MemberUtil;
import railo.runtime.type.wrap.ArrayAsList;
/**
* implementation of the argument scope
*/
public final class ArgumentImpl extends ScopeSupport implements Argument {
private boolean bind;
private Set functionArgumentNames;
//private boolean supportFunctionArguments;
/**
* constructor of the class
*/
public ArgumentImpl() {
super("arguments",SCOPE_ARGUMENTS,Struct.TYPE_LINKED);
//this(true);
}
/**
* @see railo.runtime.type.scope.ScopeSupport#release()
*/
public void release() {
functionArgumentNames=null;
super.release();
}
@Override
public void release(PageContext pc) {
functionArgumentNames=null;
super.release(pc);
}
/**
* @see railo.runtime.type.scope.Argument#setBind(boolean)
*/
public void setBind(boolean bind) {
this.bind=bind;
}
/**
* @see railo.runtime.type.scope.Argument#isBind()
*/
public boolean isBind() {
return this.bind;
}
public Object getFunctionArgument(String key, Object defaultValue) {
return getFunctionArgument(KeyImpl.getInstance(key), defaultValue);
}
public Object getFunctionArgument(Collection.Key key, Object defaultValue) {
return super.get(key,defaultValue);
}
/**
* @see railo.runtime.type.scope.ArgumentPro#containsFunctionArgumentKey(railo.runtime.type.Collection.Key)
*/
public boolean containsFunctionArgumentKey(Key key) {
return super.containsKey(key);//functionArgumentNames!=null && functionArgumentNames.contains(key);
}
/**
*
* @see railo.runtime.type.StructImpl#get(railo.runtime.type.Collection.Key, java.lang.Object)
*/
public Object get(Collection.Key key, Object defaultValue) {
Object o=super.get(key,null);
if(o!=null)return o;
char c = key.charAt(0);
if(!Character.isDigit(c) && c!='+') return defaultValue; // it make sense to have this step between
o=get(Caster.toIntValue(key.getString(),-1),null);
if(o!=null)return o;
return defaultValue;
}
/**
*
* @see railo.runtime.type.StructImpl#get(railo.runtime.type.Collection.Key)
*/
public Object get(Collection.Key key) throws ExpressionException {
Object o=super.get(key,null);
if(o!=null)return o;
char c = key.charAt(0);
if(Character.isDigit(c) || c=='+') {
o=get(Caster.toIntValue(key.getString(),-1),null);
if(o!=null)return o;
}
throw new ExpressionException("key ["+key.getString()+"] doesn't exist in argument scope. existing keys are ["+
railo.runtime.type.List.arrayToList(CollectionUtil.keys(this),", ")
+"]");
}
/**
*
* @see railo.runtime.type.Array#get(int, java.lang.Object)
*/
public Object get(int intKey, Object defaultValue) {
Iterator<Object> it = valueIterator(); //keyIterator();//getMap().keySet().iterator();
int count=0;
Object o;
while(it.hasNext()) {
o=it.next();
if((++count)==intKey) {
return o;//super.get(o.toString(),defaultValue);
}
}
return defaultValue;
}
/**
* return a value matching to key
* @param intKey
* @return value matching key
* @throws PageException
*/
public Object getE(int intKey) throws PageException {
Iterator it = valueIterator();//getMap().keySet().iterator();
int count=0;
Object o;
while(it.hasNext()) {
o=it.next();
if((++count)==intKey) {
return o;//super.get(o.toString());
}
}
throw new ExpressionException("invalid index ["+intKey+"] for argument scope");
}
/**
* @see railo.runtime.dump.Dumpable#toDumpData(railo.runtime.PageContext, int)
*/
public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) {
DumpTable htmlBox = new DumpTable("struct","#9999ff","#ccccff","#000000");
htmlBox.setTitle("Scope Arguments");
if(size()>10 && dp.getMetainfo())htmlBox.setComment("Entries:"+size());
maxlevel--;
//Map mapx=getMap();
Iterator it=keyIterator();//mapx.keySet().iterator();
int count=0;
Collection.Key key;
int maxkeys=dp.getMaxKeys();
int index=0;
while(it.hasNext()) {
key=KeyImpl.toKey(it.next(), null);//it.next();
if(DumpUtil.keyValid(dp, maxlevel,key)){
if(maxkeys<=index++)break;
htmlBox.appendRow(3,
new SimpleDumpData(key.getString()),
new SimpleDumpData(++count),
DumpUtil.toDumpData(get(key,null),
pageContext,maxlevel,dp));
}
}
return htmlBox;
}
/**
* @see railo.runtime.type.Array#getDimension()
*/
public int getDimension() {
return 1;
}
/**
* @see railo.runtime.type.Array#setEL(int, java.lang.Object)
*/
public Object setEL(int intKey, Object value) {
int count=0;
if(intKey>size()) {
return setEL(Caster.toString(intKey),value);
}
//Iterator it = keyIterator();
Key[] keys = keys();
for(int i=0;i<keys.length;i++) {
if((++count)==intKey) {
return super.setEL(keys[i],value);
}
}
return value;
}
/**
* @see railo.runtime.type.Array#setE(int, java.lang.Object)
*/
public Object setE(int intKey, Object value) throws PageException {
if(intKey>size()) {
return set(Caster.toString(intKey),value);
}
//Iterator it = keyIterator();
Key[] keys = keys();
for(int i=0;i<keys.length;i++) {
if((i+1)==intKey) {
return super.set(keys[i],value);
}
}
throw new ExpressionException("invalid index ["+intKey+"] for argument scope");
}
/**
* @see railo.runtime.type.Array#intKeys()
*/
public int[] intKeys() {
int[] ints=new int[size()];
for(int i=0;i<ints.length;i++)ints[i]=i+1;
return ints;
}
/**
* @see railo.runtime.type.Array#insert(int, java.lang.Object)
*/
public boolean insert(int index, Object value) throws ExpressionException {
return insert(index, ""+index, value);
}
/**
* @see railo.runtime.type.scope.Argument#insert(int, java.lang.String, java.lang.Object)
*/
public boolean insert(int index, String key, Object value) throws ExpressionException {
int len=size();
if(index<1 || index>len)
throw new ExpressionException("invalid index to insert a value to argument scope",len==0?"can't insert in a empty argument scope":"valid index goes from 1 to "+(len-1));
// remove all upper
LinkedHashMap lhm = new LinkedHashMap();
Collection.Key[] keys=keys();
Collection.Key k;
for(int i=1;i<=keys.length;i++) {
if(i<index)continue;
k=keys[i-1];
lhm.put(k.getString(),get(k,null));
removeEL(k);
}
// set new value
setEL(key,value);
// reset upper values
Iterator it = lhm.entrySet().iterator();
Map.Entry entry;
while(it.hasNext()) {
entry=(Entry) it.next();
setEL(KeyImpl.toKey(entry.getKey()),entry.getValue());
}
return true;
}
/**
* @see railo.runtime.type.Array#append(java.lang.Object)
*/
public Object append(Object o) throws PageException {
return set(Caster.toString(size()+1),o);
}
/**
* @see railo.runtime.type.Array#appendEL(java.lang.Object)
*/
public Object appendEL(Object o) {
try {
return append(o);
} catch (PageException e) {
return null;
}
}
/**
* @see railo.runtime.type.Array#prepend(java.lang.Object)
*/
public Object prepend(Object o) throws PageException {
for(int i=size();i>0;i--) {
setE(i+1,getE(i));
}
setE(1,o);
return o;
}
/**
* @see railo.runtime.type.Array#resize(int)
*/
public void resize(int to) throws PageException {
for(int i=size(); i<to; i++) {
append(null);
}
//throw new ExpressionException("can't resize this array");
}
/**
* @see railo.runtime.type.Array#sort(java.lang.String, java.lang.String)
*/
public void sort(String sortType, String sortOrder) throws ExpressionException {
// TODO Impl.
throw new ExpressionException("can't sort ["+sortType+"-"+sortOrder+"] Argument Scope","not Implemnted Yet");
}
public void sort(Comparator com) throws ExpressionException {
// TODO Impl.
throw new ExpressionException("can't sort Argument Scope","not Implemnted Yet");
}
/**
* @see railo.runtime.type.Array#toArray()
*/
public Object[] toArray() {
Iterator it = keyIterator();//getMap().keySet().iterator();
Object[] arr=new Object[size()];
int count=0;
while(it.hasNext()) {
arr[count++]=it.next();
}
return arr;
}
public Object setArgument(Object obj) throws PageException {
if(obj==this) return obj;
if(Decision.isStruct(obj)) {
clear(); // TODO bessere impl. anstelle vererbung wrao auf struct
Struct sct=Caster.toStruct(obj);
Iterator it = sct.keyIterator();
String key;
while(it.hasNext()) {
key=it.next().toString();
setEL(key, sct.get(key,null));
}
return obj;
}
throw new ExpressionException("can not overwrite arguments scope");
}
/**
* @see railo.runtime.type.Array#toArrayList()
*/
public ArrayList toArrayList() {
ArrayList list = new ArrayList();
Object[] arr = toArray();
for(int i=0;i<arr.length;i++) {
list.add(arr[i]);
}
return list;
}
/**
* @see railo.runtime.type.Array#removeE(int)
*/
public Object removeE(int intKey) throws PageException {
Key[] keys = keys();
for(int i=0;i<keys.length;i++) {
if((i+1)==intKey) {
return super.remove(keys[i]);
}
}
throw new ExpressionException("can't remove argument number ["+intKey+"], argument doesn't exist");
}
/**
* @see railo.runtime.type.Array#removeEL(int)
*/
public Object removeEL(int intKey) {
Key[] keys = keys();
for(int i=0;i<keys.length;i++) {
if((i+1)==intKey) {
return super.removeEL (keys[i]);
}
}
return null;
}
/**
* @see railo.runtime.type.StructImpl#containsKey(railo.runtime.type.Collection.Key)
*/
public boolean containsKey(Collection.Key key) {
if(super.containsKey(key)) return true;
char c = key.charAt(0);
if(!Character.isDigit(c) && c!='+') return false; // it make sense to have this step between
return containsKey(Caster.toIntValue(key.getString(),-1));
}
/**
* @see railo.runtime.type.Array#containsKey(int)
*/
public boolean containsKey(int key) {
return key>0 && key<=size();
}
/**
* @see railo.runtime.type.Array#toList()
*/
public List toList() {
return ArrayAsList.toList(this);
}
/**
* @see railo.runtime.type.StructImpl#duplicate(boolean)
*/
public Collection duplicate(boolean deepCopy) {
ArgumentImpl trg=new ArgumentImpl();
trg.bind=false;
trg.functionArgumentNames=functionArgumentNames;
//trg.supportFunctionArguments=supportFunctionArguments;
copy(this,trg,deepCopy);
return trg;
}
public void setFunctionArgumentNames(Set functionArgumentNames) {// future add to interface
this.functionArgumentNames=functionArgumentNames;
}
/*
public void setNamedArguments(boolean namedArguments) {
this.namedArguments=namedArguments;
}
public boolean isNamedArguments() {
return namedArguments;
}
*/
/**
* converts a argument scope to a regular struct
* @param arg argument scope to convert
* @return resulting struct
*/
public static Struct toStruct(Argument arg) {
Struct trg=new StructImpl();
StructImpl.copy(arg, trg, false);
return trg;
}
/**
* converts a argument scope to a regular array
* @param arg argument scope to convert
* @return resulting array
*/
public static Array toArray(Argument arg) {
ArrayImpl trg=new ArrayImpl();
int[] keys = arg.intKeys();
for(int i=0;i<keys.length;i++){
trg.setEL(keys[i],
arg.get(keys[i],null));
}
return trg;
}
@Override
public Object get(PageContext pc, Key key, Object defaultValue) {
return get(key, defaultValue);
}
@Override
public Object get(PageContext pc, Key key) throws PageException {
return get(key);
}
@Override
public Object set(PageContext pc, Key propertyName, Object value) throws PageException {
return set(propertyName, value);
}
@Override
public Object setEL(PageContext pc, Key propertyName, Object value) {
return setEL(propertyName, value);
}
@Override
public Object call(PageContext pc, Key methodName, Object[] args) throws PageException {
Object obj = get(methodName,null);
if(obj instanceof UDF) {
return ((UDF)obj).call(pc,args,false);
}
return MemberUtil.call(pc, this, methodName, args, CFTypes.TYPE_ARRAY, "array");
}
@Override
public Object callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException {
Object obj = get(methodName,null);
if(obj instanceof UDF) {
return ((UDF)obj).callWithNamedValues(pc,args,false);
}
return MemberUtil.callWithNamedValues(pc,this,methodName,args, CFTypes.TYPE_ARRAY, "array");
}
} | remove shortcut pre test in argument scope
| railo-java/railo-core/src/railo/runtime/type/scope/ArgumentImpl.java | remove shortcut pre test in argument scope | <ide><path>ailo-java/railo-core/src/railo/runtime/type/scope/ArgumentImpl.java
<ide> Object o=super.get(key,null);
<ide> if(o!=null)return o;
<ide>
<del> char c = key.charAt(0);
<del> if(!Character.isDigit(c) && c!='+') return defaultValue; // it make sense to have this step between
<add> //char c = key.charAt(0);
<add> //if(!Character.isDigit(c) && c!='+') return defaultValue; // it make sense to have this step between
<ide>
<ide>
<ide>
<ide> Object o=super.get(key,null);
<ide> if(o!=null)return o;
<ide>
<del> char c = key.charAt(0);
<del> if(Character.isDigit(c) || c=='+') {
<add> //char c = key.charAt(0);
<add> //if(Character.isDigit(c) || c=='+') {
<ide> o=get(Caster.toIntValue(key.getString(),-1),null);
<ide> if(o!=null)return o;
<del> }
<add> //}
<ide>
<ide> throw new ExpressionException("key ["+key.getString()+"] doesn't exist in argument scope. existing keys are ["+
<ide> railo.runtime.type.List.arrayToList(CollectionUtil.keys(this),", ") |
|
Java | mit | 59a56d3943de9ac01b44e32fcd6a36125fd5e3eb | 0 | ippeb/TetrisBattleBot,ippeb/TetrisBattleBot,ippeb/TetrisBattleBot | // This class deals with everything concerning the Tetris board
// such as saving the current board state and simulating a Tetromino
// drop and Tetromino rotation.
//
// Other methods include counting and clearing the number of
// filled lines (rows).
package TetrisBattleBot;
public class TetrisBoard {
//
// Types of Tetrominoes
//
// 0 ** 1 ** 2 ** 3 * 4 **** 5 * 6 *
// ** ** ** *** *** ***
//
public static final int[][][] TETROMINO = { // [i][j][k], Tetromino type: i/4, rotated by (i mod 4)*90 degrees, [j][k] 2D int array with j=0..3, k=0..3
{{0,0,0,0},{0,0,0,0},{1,1,0,0},{1,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,0,0},{1,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,0,0},{1,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,0,0},{1,1,0,0}}, // 0
{{0,0,0,0},{0,0,0,0},{1,1,0,0},{0,1,1,0}}, {{0,0,0,0},{0,0,1,0},{0,1,1,0},{0,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,0,0},{0,1,1,0}}, {{0,0,0,0},{0,1,0,0},{1,1,0,0},{1,0,0,0}}, // 1
{{0,0,0,0},{0,0,0,0},{0,1,1,0},{1,1,0,0}}, {{0,0,0,0},{0,1,0,0},{0,1,1,0},{0,0,1,0}}, {{0,0,0,0},{0,0,0,0},{0,1,1,0},{1,1,0,0}}, {{0,0,0,0},{1,0,0,0},{1,1,0,0},{0,1,0,0}}, // 2
{{0,0,0,0},{0,0,0,0},{0,1,0,0},{1,1,1,0}}, {{0,0,0,0},{0,1,0,0},{0,1,1,0},{0,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,1,0},{0,1,0,0}}, {{0,0,0,0},{0,1,0,0},{1,1,0,0},{0,1,0,0}}, // 3
{{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,1,1,1}}, {{0,0,1,0},{0,0,1,0},{0,0,1,0},{0,0,1,0}}, {{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,1,1,1}}, {{0,1,0,0},{0,1,0,0},{0,1,0,0},{0,1,0,0}}, // 4
{{0,0,0,0},{0,0,0,0},{1,0,0,0},{1,1,1,0}}, {{0,0,0,0},{0,1,1,0},{0,1,0,0},{0,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,1,0},{0,0,1,0}}, {{0,0,0,0},{0,1,0,0},{0,1,0,0},{1,1,0,0}}, // 5
{{0,0,0,0},{0,0,0,0},{0,0,1,0},{1,1,1,0}}, {{0,0,0,0},{0,1,0,0},{0,1,0,0},{0,1,1,0}}, {{0,0,0,0},{0,0,0,0},{1,1,1,0},{1,0,0,0}}, {{0,0,0,0},{1,1,0,0},{0,1,0,0},{0,1,0,0}}, // 6
};
//
// Board Layout
//
// /-----------------------------\
// | TMARGIN |
// | |
// | /------\ |
// | |BOARDW| |
// | | | |
// | | | |
// | |B | |
// | |O | |
// | |A | |
// |LMARGIN |R | RMARGIN |
// | |D | |
// | |H | |
// | | | |
// | | | |
// | \------/ |
// | |
// | BMARGIN |
// | |
// \-----------------------------/
//
public static final int BOARDH = 20; // height
public static final int BOARDW = 10; // width
public static final int LMARGIN = 20; // left margin
public static final int RMARGIN = 20; // right margin
public static final int TMARGIN = 20; // top margin
public static final int BMARGIN = 20; // bottom margin
private int[][] Board; // board, 0 unfilled, i > 0 filled
private int[] Height; // height at pos x
public int tilemarker = 22;
// 1 is used for wall boundaries at initialization
// 10 ... 16 is used by method detectTetrisBoard
// used in TetrisWebsiteInteraction.java
public int score = 0; // sum of all max(number of subsequently cleared lines - 1, 0)
public boolean filledlinebef = false; // saves if a line was filled in the previous turn
// no-argument constructor
public TetrisBoard() {
Board = new int [BOARDH + TMARGIN + BMARGIN] [BOARDW + LMARGIN + RMARGIN];
for (int j = 0; j < BOARDH + TMARGIN + BMARGIN; j++)
for (int i = 0; i < BOARDW + LMARGIN + RMARGIN; i++)
Board[j][i] = 1;
for (int j = 0; j < BOARDH + TMARGIN; j++)
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
Board[j][i] = 0;
Height = new int [BOARDW + LMARGIN + RMARGIN];
for (int i = 0; i < BOARDW + LMARGIN + RMARGIN; i++)
Height[i] = TMARGIN + BOARDH;
}
// constructor that initializes the Tetris board with
// an int array of dimensions BOARDH x BOARDW
public TetrisBoard(int[][] A) {
Board = new int [BOARDH + TMARGIN + BMARGIN] [BOARDW + LMARGIN + RMARGIN];
for (int j = 0; j < BOARDH + TMARGIN + BMARGIN; j++)
for (int i = 0; i < BOARDW + LMARGIN + RMARGIN; i++)
Board[j][i] = 1;
for (int j = 0; j < TMARGIN; j++)
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
Board[j][i] = 0;
for (int j = TMARGIN; j < BOARDH + TMARGIN; j++)
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
Board[j][i] = A[j - TMARGIN][i - LMARGIN];
Height = new int [BOARDW + LMARGIN + RMARGIN];
updateHeight();
}
// compare current Tetris board to argument,
// only the contents of the board is compared
// not included are:
// * fields within top, left, right and bottom margin
// * Height array
// * member variables such as "score", "filledlinebef",
// "tilemarker", etc.
public int compare(TetrisBoard TB) {
int diff = 0;
for (int j = TMARGIN; j < BOARDH + TMARGIN; j++)
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
if (!( (Board[j][i] == 0 && TB[j][i] == 0) ||
(Board[j][i] > 0 && TB[j][i] > 0) ))
diff++;
return diff;
}
// get height at position "pos"
public int getHeight(int pos) {
return Height[pos];
}
// count for all rows (from left to right) in TetrisBoard.Board
// number of changes from value 0 (empty) to a positive value (filled)
public int horizontalDiff() {
int sol = 0;
for (int i = TMARGIN; i < TMARGIN + BOARDH; i++) {
boolean bef = true;
for (int j = LMARGIN - 1; j < LMARGIN + BOARDW + 1; j++) {
if (bef && Board[i][j] == 0) {
sol++;
bef = false;
}
else if (!bef && Board[i][j] > 0) {
sol++;
bef = true;
}
}
}
return sol;
}
// count for all columns (from top to bottom) in TetrisBoard.Board
// number of changes from value 0 (empty) to a positive value (filled)
public int verticalDiff() {
int sol = 0;
for (int i = LMARGIN; i < LMARGIN + BOARDW; i++) {
boolean bef = false;
for (int j = TMARGIN - 1; j < TMARGIN + BOARDH + 1; j++) {
if (bef && Board[j][i] == 0) {
sol++;
bef = false;
}
else if (!bef && Board[j][i] > 0) {
sol++;
bef = true;
}
}
}
return sol;
}
// prints a Tetromino of type "type"
public static void printTetromino(int type) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print( TETROMINO[type*4][i][j]==0?" ":"x" );
}
System.out.println("");
}
System.out.println("");
}
// update the entire array Height
public void updateHeight() {
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++) {
for (int j = 0; j < TMARGIN + BOARDH + 1; j++) {
if (Board[j][i] != 0) {
Height[i] = j;
break;
}
}
}
}
// set all elements of value marking to zero
// returns true if marking was found
public boolean deleteTile(int marking) {
boolean found = false;
for (int j = 0; j < BOARDH + TMARGIN; j++)
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
if (Board[j][i] == marking) {
found = true;
Board[j][i] = 0;
}
updateHeight();
return found;
}
// count filled horizontal lines
public int countLines() {
int linecount=0;
for (int i = 0; i < TMARGIN + BOARDH; i++) {
boolean zero = false;
for (int j = LMARGIN; j < LMARGIN + BOARDW; j++) {
if (Board[i][j] == 0) {
zero = true;
break;
}
}
if (!zero) linecount++;
}
return linecount;
}
// update score and filledlinebef
public void updateScore(int lcount) {
if (lcount == 0) {
filledlinebef = false;
return ;
}
filledlinebef = true;
if (filledlinebef) score += lcount;
else score += lcount - 1;
}
// clear lines and update array Height
// this function is (typically) used in the main method
// just after a Tetromino was dropped ultimately
public void clearLinesUpdateHeight() {
boolean[] H = new boolean[TMARGIN + BOARDH + BMARGIN];
for (int i = 0; i < TMARGIN + BOARDH; i++) {
boolean zero = false;
for (int j = LMARGIN; j < LMARGIN + BOARDW; j++) {
if (Board[i][j] == 0) {
zero = true;
break;
}
}
if (!zero) H[i] = true;
}
int lcount = 0;
for (int i = TMARGIN + BOARDH - 1; i >= 0; i--) {
if (H[i]){
lcount++;
continue;
}
if (lcount > 0) {
for (int j = LMARGIN; j < LMARGIN + BOARDW; j++)
Board[i+lcount][j] = Board[i][j];
}
}
for (int i = 0; i < lcount; i++) {
for (int j = LMARGIN; j < LMARGIN + BOARDW; j++) {
Board[i][j] = 0;
}
}
updateHeight();
updateScore(lcount);
}
// return the number of "holes"
// a hole is defined as a zero element in TetrisBoard that contains
// a nonzero element above it
public int hole() {
int hole = 0;
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++) {
boolean found = false;
for (int j = 0; j < BOARDH + TMARGIN; j++) {
if (Board[j][i] != 0) found = true;
else if (found == true) hole++;
}
}
return hole;
}
// return the highest filled spot of Board
// Beware: this is a misnomer, the largest height has the smallest value
// since we consider e.g. h=1 higher than h=34
public int maxHeight() {
int tmp = Integer.MAX_VALUE;
for (int i = LMARGIN; i < LMARGIN + BOARDW; i++){
if (Height[i] < tmp) tmp = Height[i];
}
return tmp;
}
// return the lowest filled spot of Board
public int minHeight() {
int tmp = 0;
for (int i = LMARGIN; i < LMARGIN + BOARDW; i++){
if (Height[i] > tmp) tmp = Height[i];
}
return tmp;
}
// print the current Tetris board
// mark wall boundaries as '#'
public void printFullBoard(){
for (int j = TMARGIN; j < TMARGIN + BOARDH + 1; j++){
for (int i = LMARGIN - 1; i < LMARGIN + BOARDW + 1; i++){
System.out.print(Board[j][i]==1?"#":(Board[j][i]==0?" ":Board[j][i]%10));
}
System.out.println("");
}
// System.out.println("Score " + score);
/**/
System.out.println("HEIGHT");
for (int i = LMARGIN; i < LMARGIN + BOARDW; i++){
System.out.print(" "+Height[i]+" ");
}
System.out.println("");
/**/
}
// returns true if a Tetromino type i, rotated by j*90 degrees at position x=k, y=h
// collides with a field on the TetrisBoard
public boolean collide(int i, int j, int k, int h){
for (int l = 0; l < 4; l++)
for (int m = 0; m < 4; m++)
if (Board[h+l][k+m]!=0 && TETROMINO[i*4+j][l][m]!=0)
return true;
return false;
}
// insert Tetromino type j, rotated by j*90 degrees at position x=k, y=h in 2D TetrisBoard
// returns false if there is an overlap or if Tetromino exceeds the boundaries
// of the Tetris board
public boolean insertTetromino(int i, int j, int k, int h, int marker){
if (collide(i, j, k, h)) return false;
for (int l = 0; l < 4; l++)
for (int m = 0; m < 4; m++)
if (TETROMINO[i*4+j][l][m]!=0)
Board[h+l][k+m] = marker;
return true;
}
// drops a Tetromino type i, rotated by j*90 degrees at position x=k with marking "marker"
// returns y coordinate of Tetromino
// returns -1 if Tetromino couldn't be dropped (e.g. overlapped boundary)
public int dropTetromino(int i, int j, int k, int marker) {
int h=Math.min(Math.min(Height[k], Height[k+1]), Math.min(Height[k+2], Height[k+3]))-4;
// there must be a collision
for (; ; h++) {
if (collide(i, j, k, h)) break;
}
h--;
boolean ret = insertTetromino(i, j, k, h, marker);
// System.out.println("problem with dropTetromino: type = " + i + " rot = " + j + " pos = " + k + " h = " + h);
updateHeight();
if (!ret)
return -1;
else
return h;
}
}
| src/TetrisBattleBot/TetrisBoard.java | // This class deals with everything concerning the Tetris board
// such as saving the current board state and simulating a Tetromino
// drop and Tetromino rotation.
//
// Other methods include counting and clearing the number of
// filled lines (rows).
package TetrisBattleBot;
public class TetrisBoard {
//
// Types of Tetrominoes
//
// 0 ** 1 ** 2 ** 3 * 4 **** 5 * 6 *
// ** ** ** *** *** ***
//
public static final int[][][] TETROMINO = { // [i][j][k], Tetromino type: i/4, rotated by (i mod 4)*90 degrees, [j][k] 2D int array with j=0..3, k=0..3
{{0,0,0,0},{0,0,0,0},{1,1,0,0},{1,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,0,0},{1,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,0,0},{1,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,0,0},{1,1,0,0}}, // 0
{{0,0,0,0},{0,0,0,0},{1,1,0,0},{0,1,1,0}}, {{0,0,0,0},{0,0,1,0},{0,1,1,0},{0,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,0,0},{0,1,1,0}}, {{0,0,0,0},{0,1,0,0},{1,1,0,0},{1,0,0,0}}, // 1
{{0,0,0,0},{0,0,0,0},{0,1,1,0},{1,1,0,0}}, {{0,0,0,0},{0,1,0,0},{0,1,1,0},{0,0,1,0}}, {{0,0,0,0},{0,0,0,0},{0,1,1,0},{1,1,0,0}}, {{0,0,0,0},{1,0,0,0},{1,1,0,0},{0,1,0,0}}, // 2
{{0,0,0,0},{0,0,0,0},{0,1,0,0},{1,1,1,0}}, {{0,0,0,0},{0,1,0,0},{0,1,1,0},{0,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,1,0},{0,1,0,0}}, {{0,0,0,0},{0,1,0,0},{1,1,0,0},{0,1,0,0}}, // 3
{{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,1,1,1}}, {{0,0,1,0},{0,0,1,0},{0,0,1,0},{0,0,1,0}}, {{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,1,1,1}}, {{0,1,0,0},{0,1,0,0},{0,1,0,0},{0,1,0,0}}, // 4
{{0,0,0,0},{0,0,0,0},{1,0,0,0},{1,1,1,0}}, {{0,0,0,0},{0,1,1,0},{0,1,0,0},{0,1,0,0}}, {{0,0,0,0},{0,0,0,0},{1,1,1,0},{0,0,1,0}}, {{0,0,0,0},{0,1,0,0},{0,1,0,0},{1,1,0,0}}, // 5
{{0,0,0,0},{0,0,0,0},{0,0,1,0},{1,1,1,0}}, {{0,0,0,0},{0,1,0,0},{0,1,0,0},{0,1,1,0}}, {{0,0,0,0},{0,0,0,0},{1,1,1,0},{1,0,0,0}}, {{0,0,0,0},{1,1,0,0},{0,1,0,0},{0,1,0,0}}, // 6
};
//
// Board Layout
//
// /-----------------------------\
// | TMARGIN |
// | |
// | /------\ |
// | |BOARDW| |
// | | | |
// | | | |
// | |B | |
// | |O | |
// | |A | |
// |LMARGIN |R | RMARGIN |
// | |D | |
// | |H | |
// | | | |
// | | | |
// | \------/ |
// | |
// | BMARGIN |
// | |
// \-----------------------------/
//
public static final int BOARDH = 20; // height
public static final int BOARDW = 10; // width
public static final int LMARGIN = 20; // left margin
public static final int RMARGIN = 20; // right margin
public static final int TMARGIN = 20; // top margin
public static final int BMARGIN = 20; // bottom margin
private int[][] Board; // board, 0 unfilled, i > 0 filled
private int[] Height; // height at pos x
public int tilemarker = 22;
// 1 is used for wall boundaries at initialization
// 10 ... 16 is used by method detectTetrisBoard
// used in TetrisWebsiteInteraction.java
public int score = 0; // sum of all max(number of subsequently cleared lines - 1, 0)
public boolean filledlinebef = false; // saves if a line was filled in the previous turn
// no-argument constructor
public TetrisBoard() {
Board = new int [BOARDH + TMARGIN + BMARGIN] [BOARDW + LMARGIN + RMARGIN];
for (int j = 0; j < BOARDH + TMARGIN + BMARGIN; j++)
for (int i = 0; i < BOARDW + LMARGIN + RMARGIN; i++)
Board[j][i] = 1;
for (int j = 0; j < BOARDH + TMARGIN; j++)
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
Board[j][i] = 0;
Height = new int [BOARDW + LMARGIN + RMARGIN];
for (int i = 0; i < BOARDW + LMARGIN + RMARGIN; i++)
Height[i] = TMARGIN + BOARDH;
}
// constructor that initializes the Tetris board with
// an int array of dimensions BOARDH x BOARDW
public TetrisBoard(int[][] A) {
Board = new int [BOARDH + TMARGIN + BMARGIN] [BOARDW + LMARGIN + RMARGIN];
for (int j = 0; j < BOARDH + TMARGIN + BMARGIN; j++)
for (int i = 0; i < BOARDW + LMARGIN + RMARGIN; i++)
Board[j][i] = 1;
for (int j = 0; j < TMARGIN; j++)
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
Board[j][i] = 0;
for (int j = TMARGIN; j < BOARDH + TMARGIN; j++)
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
Board[j][i] = A[j - TMARGIN][i - LMARGIN];
Height = new int [BOARDW + LMARGIN + RMARGIN];
updateHeight();
}
// get height at position "pos"
public int getHeight(int pos) {
return Height[pos];
}
// count for all rows (from left to right) in TetrisBoard.Board
// number of changes from value 0 (empty) to a positive value (filled)
public int horizontalDiff() {
int sol = 0;
for (int i = TMARGIN; i < TMARGIN + BOARDH; i++) {
boolean bef = true;
for (int j = LMARGIN - 1; j < LMARGIN + BOARDW + 1; j++) {
if (bef && Board[i][j] == 0) {
sol++;
bef = false;
}
else if (!bef && Board[i][j] > 0) {
sol++;
bef = true;
}
}
}
return sol;
}
// count for all columns (from top to bottom) in TetrisBoard.Board
// number of changes from value 0 (empty) to a positive value (filled)
public int verticalDiff() {
int sol = 0;
for (int i = LMARGIN; i < LMARGIN + BOARDW; i++) {
boolean bef = false;
for (int j = TMARGIN - 1; j < TMARGIN + BOARDH + 1; j++) {
if (bef && Board[j][i] == 0) {
sol++;
bef = false;
}
else if (!bef && Board[j][i] > 0) {
sol++;
bef = true;
}
}
}
return sol;
}
// prints a Tetromino of type "type"
public static void printTetromino(int type) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print( TETROMINO[type*4][i][j]==0?" ":"x" );
}
System.out.println("");
}
System.out.println("");
}
// update the entire array Height
public void updateHeight() {
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++) {
for (int j = 0; j < TMARGIN + BOARDH + 1; j++) {
if (Board[j][i] != 0) {
Height[i] = j;
break;
}
}
}
}
// set all elements of value marking to zero
// returns true if marking was found
public boolean deleteTile(int marking) {
boolean found = false;
for (int j = 0; j < BOARDH + TMARGIN; j++)
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
if (Board[j][i] == marking) {
found = true;
Board[j][i] = 0;
}
updateHeight();
return found;
}
// count filled horizontal lines
public int countLines() {
int linecount=0;
for (int i = 0; i < TMARGIN + BOARDH; i++) {
boolean zero = false;
for (int j = LMARGIN; j < LMARGIN + BOARDW; j++) {
if (Board[i][j] == 0) {
zero = true;
break;
}
}
if (!zero) linecount++;
}
return linecount;
}
// update score and filledlinebef
public void updateScore(int lcount) {
if (lcount == 0) {
filledlinebef = false;
return ;
}
filledlinebef = true;
if (filledlinebef) score += lcount;
else score += lcount - 1;
}
// clear lines and update array Height
// this function is (typically) used in the main method
// just after a Tetromino was dropped ultimately
public void clearLinesUpdateHeight() {
boolean[] H = new boolean[TMARGIN + BOARDH + BMARGIN];
for (int i = 0; i < TMARGIN + BOARDH; i++) {
boolean zero = false;
for (int j = LMARGIN; j < LMARGIN + BOARDW; j++) {
if (Board[i][j] == 0) {
zero = true;
break;
}
}
if (!zero) H[i] = true;
}
int lcount = 0;
for (int i = TMARGIN + BOARDH - 1; i >= 0; i--) {
if (H[i]){
lcount++;
continue;
}
if (lcount > 0) {
for (int j = LMARGIN; j < LMARGIN + BOARDW; j++)
Board[i+lcount][j] = Board[i][j];
}
}
for (int i = 0; i < lcount; i++) {
for (int j = LMARGIN; j < LMARGIN + BOARDW; j++) {
Board[i][j] = 0;
}
}
updateHeight();
updateScore(lcount);
}
// return the number of "holes"
// a hole is defined as a zero element in TetrisBoard that contains
// a nonzero element above it
public int hole() {
int hole = 0;
for (int i = LMARGIN; i < BOARDW + LMARGIN; i++) {
boolean found = false;
for (int j = 0; j < BOARDH + TMARGIN; j++) {
if (Board[j][i] != 0) found = true;
else if (found == true) hole++;
}
}
return hole;
}
// return the highest filled spot of Board
// Beware: this is a misnomer, the largest height has the smallest value
// since we consider e.g. h=1 higher than h=34
public int maxHeight() {
int tmp = Integer.MAX_VALUE;
for (int i = LMARGIN; i < LMARGIN + BOARDW; i++){
if (Height[i] < tmp) tmp = Height[i];
}
return tmp;
}
// return the lowest filled spot of Board
public int minHeight() {
int tmp = 0;
for (int i = LMARGIN; i < LMARGIN + BOARDW; i++){
if (Height[i] > tmp) tmp = Height[i];
}
return tmp;
}
// print the current Tetris board
// mark wall boundaries as '#'
public void printFullBoard(){
for (int j = TMARGIN; j < TMARGIN + BOARDH + 1; j++){
for (int i = LMARGIN - 1; i < LMARGIN + BOARDW + 1; i++){
System.out.print(Board[j][i]==1?"#":(Board[j][i]==0?" ":Board[j][i]%10));
}
System.out.println("");
}
// System.out.println("Score " + score);
/**/
System.out.println("HEIGHT");
for (int i = LMARGIN; i < LMARGIN + BOARDW; i++){
System.out.print(" "+Height[i]+" ");
}
System.out.println("");
/**/
}
// returns true if a Tetromino type i, rotated by j*90 degrees at position x=k, y=h
// collides with a field on the TetrisBoard
public boolean collide(int i, int j, int k, int h){
for (int l = 0; l < 4; l++)
for (int m = 0; m < 4; m++)
if (Board[h+l][k+m]!=0 && TETROMINO[i*4+j][l][m]!=0)
return true;
return false;
}
// insert Tetromino type j, rotated by j*90 degrees at position x=k, y=h in 2D TetrisBoard
// returns false if there is an overlap or if Tetromino exceeds the boundaries
// of the Tetris board
public boolean insertTetromino(int i, int j, int k, int h, int marker){
if (collide(i, j, k, h)) return false;
for (int l = 0; l < 4; l++)
for (int m = 0; m < 4; m++)
if (TETROMINO[i*4+j][l][m]!=0)
Board[h+l][k+m] = marker;
return true;
}
// drops a Tetromino type i, rotated by j*90 degrees at position x=k with marking "marker"
// returns y coordinate of Tetromino
// returns -1 if Tetromino couldn't be dropped (e.g. overlapped boundary)
public int dropTetromino(int i, int j, int k, int marker) {
int h=Math.min(Math.min(Height[k], Height[k+1]), Math.min(Height[k+2], Height[k+3]))-4;
// there must be a collision
for (; ; h++) {
if (collide(i, j, k, h)) break;
}
h--;
boolean ret = insertTetromino(i, j, k, h, marker);
// System.out.println("problem with dropTetromino: type = " + i + " rot = " + j + " pos = " + k + " h = " + h);
updateHeight();
if (!ret)
return -1;
else
return h;
}
}
| Added comparison of two TetrisBoards
| src/TetrisBattleBot/TetrisBoard.java | Added comparison of two TetrisBoards | <ide><path>rc/TetrisBattleBot/TetrisBoard.java
<ide> updateHeight();
<ide> }
<ide>
<add> // compare current Tetris board to argument,
<add> // only the contents of the board is compared
<add> // not included are:
<add> // * fields within top, left, right and bottom margin
<add> // * Height array
<add> // * member variables such as "score", "filledlinebef",
<add> // "tilemarker", etc.
<add> public int compare(TetrisBoard TB) {
<add> int diff = 0;
<add> for (int j = TMARGIN; j < BOARDH + TMARGIN; j++)
<add> for (int i = LMARGIN; i < BOARDW + LMARGIN; i++)
<add> if (!( (Board[j][i] == 0 && TB[j][i] == 0) ||
<add> (Board[j][i] > 0 && TB[j][i] > 0) ))
<add> diff++;
<add> return diff;
<add> }
<add>
<ide> // get height at position "pos"
<ide> public int getHeight(int pos) {
<ide> return Height[pos]; |
|
JavaScript | mit | d6b50b7346c1483ed5aaac72522d127aa1397a2f | 0 | sidorares/node-mysql2,sidorares/node-mysql2,sidorares/node-mysql2,sidorares/node-mysql2 | var config = {
host: process.env.MYSQL_HOST || 'localhost',
user: process.env.MYSQL_USER || 'root',
password: (process.env.CI ? process.env.MYSQL_PASSWORD : '') || '',
database: process.env.MYSQL_DATABASE || 'test',
compress: process.env.MYSQL_USE_COMPRESSION,
port: process.env.MYSQL_PORT || 3306
};
var configURI = "mysql://" + config.user + ":" + config.password + "@" + config.host + ":" + config.port + "/" + config.database;
module.exports.SqlString = require('sqlstring');
module.exports.config = config;
module.exports.waitDatabaseReady = function(callback) {
const tryConnect = function() {
const conn = module.exports.createConnection();
conn.on('error', function(err) {
console.log(err);
console.log('not ready');
setTimeout(tryConnect, 1000);
});
conn.on('connect', function() {
console.log('ready!');
conn.close();
callback();
});
};
tryConnect();
};
module.exports.createConnection = function(args, callback) {
if (!args) {
args = {};
}
// hrtime polyfill for old node versions:
if (!process.hrtime) {
process.hrtime = function(start) {
start = [0, 0] || start;
var timestamp = Date.now();
var seconds = Math.ceil(timestamp / 1000);
return [
seconds - start[0],
(timestamp - seconds * 1000) * 1000 - start[1]
];
};
}
if (process.env.BENCHMARK_MARIA) {
var Client = require('mariasql');
var c = new Client();
c.connect({
host: config.host,
user: config.user,
password: config.password,
db: config.database
});
// c.on('connect', function() {
//
// });
setTimeout(function() {
console.log('altering client...');
c.oldQuery = c.query;
c.query = function(sql, callback) {
var rows = [];
var q = c.oldQuery(sql);
q.on('result', function(res) {
res.on('row', function(row) {
rows.push(row);
});
res.on('end', function() {
callback(null, rows);
});
});
};
}, 1000);
return c;
}
var driver = require('../index.js');
if (process.env.BENCHMARK_MYSQL1) {
driver = require('mysql');
}
var params = {
host: args.host || config.host,
rowsAsArray: args.rowsAsArray,
user: (args && args.user) || config.user,
password: (args && args.password) || config.password,
database: (args && args.database) || config.database,
multipleStatements: args ? args.multipleStatements : false,
port: (args && args.port) || config.port,
debug: process.env.DEBUG || (args && args.debug),
supportBigNumbers: args && args.supportBigNumbers,
bigNumberStrings: args && args.bigNumberStrings,
compress: (args && args.compress) || config.compress,
decimalNumbers: args && args.decimalNumbers,
charset: args && args.charset,
dateStrings: args && args.dateStrings,
authSwitchHandler: args && args.authSwitchHandler,
typeCast: args && args.typeCast
};
// console.log('cc params', params);
var conn = driver.createConnection(params);
/*
conn.query('create database IF NOT EXISTS test', function (err) {
if (err) {
console.log('error during "create database IF NOT EXISTS test"', err);
}
});
conn.query('use test', function (err) {
if (err) {
console.log('error during "use test"', err);
}
});
*/
return conn;
};
module.exports.getConfig = function(input) {
const args = input || {};
const params = {
host: args.host || config.host,
rowsAsArray: args.rowsAsArray,
user: (args && args.user) || config.user,
password: (args && args.password) || config.password,
database: (args && args.database) || config.database,
multipleStatements: args ? args.multipleStatements : false,
port: (args && args.port) || config.port,
debug: process.env.DEBUG || (args && args.debug),
supportBigNumbers: args && args.supportBigNumbers,
bigNumberStrings: args && args.bigNumberStrings,
compress: (args && args.compress) || config.compress,
decimalNumbers: args && args.decimalNumbers,
charset: args && args.charset,
dateStrings: args && args.dateStrings,
authSwitchHandler: args && args.authSwitchHandler,
typeCast: args && args.typeCast
};
return params;
};
module.exports.createPool = function(callback) {
var driver = require('../index.js');
if (process.env.BENCHMARK_MYSQL1) {
driver = require('mysql');
}
return driver.createPool(config);
};
module.exports.createConnectionWithURI = function(callback) {
var driver = require('../index.js');
return driver.createConnection({ uri: configURI });
};
module.exports.createTemplate = function() {
var jade = require('jade');
var template = require('fs').readFileSync(
__dirname + '/template.jade',
'ascii'
);
return jade.compile(template);
};
var ClientFlags = require('../lib/constants/client.js');
var portfinder = require('portfinder');
module.exports.createServer = function(onListening, handler) {
var server = require('../index.js').createServer();
server.on('connection', function(conn) {
conn.on('error', function() {
// we are here when client drops connection
});
var flags = 0xffffff;
flags = flags ^ ClientFlags.COMPRESS;
conn.serverHandshake({
protocolVersion: 10,
serverVersion: 'node.js rocks',
connectionId: 1234,
statusFlags: 2,
characterSet: 8,
capabilityFlags: flags
});
if (handler) {
handler(conn);
}
});
portfinder.getPort(function(err, port) {
server.listen(port, onListening);
});
return server;
};
module.exports.useTestDb = function(cb) {
// no-op in my setup, need it for compatibility with node-mysql tests
};
| test/common.js | var config = {
host: process.env.MYSQL_HOST || 'localhost',
user: process.env.MYSQL_USER || 'root',
password: process.env.CI ? process.env.MYSQL_PASSWORD : '',
database: process.env.MYSQL_DATABASE || 'test',
compress: process.env.MYSQL_USE_COMPRESSION,
port: process.env.MYSQL_PORT || 3306
};
console.log(config);
var configURI = "mysql://" + config.user + ":" + config.password + "@" + config.host + ":" + config.port + "/" + config.database;
console.log(configURI);
module.exports.SqlString = require('sqlstring');
module.exports.config = config;
module.exports.waitDatabaseReady = function(callback) {
const tryConnect = function() {
const conn = module.exports.createConnection();
conn.on('error', function(err) {
console.log(err);
console.log('not ready');
setTimeout(tryConnect, 1000);
});
conn.on('connect', function() {
console.log('ready!');
conn.close();
callback();
});
};
tryConnect();
};
module.exports.createConnection = function(args, callback) {
if (!args) {
args = {};
}
// hrtime polyfill for old node versions:
if (!process.hrtime) {
process.hrtime = function(start) {
start = [0, 0] || start;
var timestamp = Date.now();
var seconds = Math.ceil(timestamp / 1000);
return [
seconds - start[0],
(timestamp - seconds * 1000) * 1000 - start[1]
];
};
}
if (process.env.BENCHMARK_MARIA) {
var Client = require('mariasql');
var c = new Client();
c.connect({
host: config.host,
user: config.user,
password: config.password,
db: config.database
});
// c.on('connect', function() {
//
// });
setTimeout(function() {
console.log('altering client...');
c.oldQuery = c.query;
c.query = function(sql, callback) {
var rows = [];
var q = c.oldQuery(sql);
q.on('result', function(res) {
res.on('row', function(row) {
rows.push(row);
});
res.on('end', function() {
callback(null, rows);
});
});
};
}, 1000);
return c;
}
var driver = require('../index.js');
if (process.env.BENCHMARK_MYSQL1) {
driver = require('mysql');
}
var params = {
host: args.host || config.host,
rowsAsArray: args.rowsAsArray,
user: (args && args.user) || config.user,
password: (args && args.password) || config.password,
database: (args && args.database) || config.database,
multipleStatements: args ? args.multipleStatements : false,
port: (args && args.port) || config.port,
debug: process.env.DEBUG || (args && args.debug),
supportBigNumbers: args && args.supportBigNumbers,
bigNumberStrings: args && args.bigNumberStrings,
compress: (args && args.compress) || config.compress,
decimalNumbers: args && args.decimalNumbers,
charset: args && args.charset,
dateStrings: args && args.dateStrings,
authSwitchHandler: args && args.authSwitchHandler,
typeCast: args && args.typeCast
};
// console.log('cc params', params);
var conn = driver.createConnection(params);
/*
conn.query('create database IF NOT EXISTS test', function (err) {
if (err) {
console.log('error during "create database IF NOT EXISTS test"', err);
}
});
conn.query('use test', function (err) {
if (err) {
console.log('error during "use test"', err);
}
});
*/
return conn;
};
module.exports.getConfig = function(input) {
const args = input || {};
const params = {
host: args.host || config.host,
rowsAsArray: args.rowsAsArray,
user: (args && args.user) || config.user,
password: (args && args.password) || config.password,
database: (args && args.database) || config.database,
multipleStatements: args ? args.multipleStatements : false,
port: (args && args.port) || config.port,
debug: process.env.DEBUG || (args && args.debug),
supportBigNumbers: args && args.supportBigNumbers,
bigNumberStrings: args && args.bigNumberStrings,
compress: (args && args.compress) || config.compress,
decimalNumbers: args && args.decimalNumbers,
charset: args && args.charset,
dateStrings: args && args.dateStrings,
authSwitchHandler: args && args.authSwitchHandler,
typeCast: args && args.typeCast
};
return params;
};
module.exports.createPool = function(callback) {
var driver = require('../index.js');
if (process.env.BENCHMARK_MYSQL1) {
driver = require('mysql');
}
return driver.createPool(config);
};
module.exports.createConnectionWithURI = function(callback) {
var driver = require('../index.js');
return driver.createConnection({ uri: configURI });
};
module.exports.createTemplate = function() {
var jade = require('jade');
var template = require('fs').readFileSync(
__dirname + '/template.jade',
'ascii'
);
return jade.compile(template);
};
var ClientFlags = require('../lib/constants/client.js');
var portfinder = require('portfinder');
module.exports.createServer = function(onListening, handler) {
var server = require('../index.js').createServer();
server.on('connection', function(conn) {
conn.on('error', function() {
// we are here when client drops connection
});
var flags = 0xffffff;
flags = flags ^ ClientFlags.COMPRESS;
conn.serverHandshake({
protocolVersion: 10,
serverVersion: 'node.js rocks',
connectionId: 1234,
statusFlags: 2,
characterSet: 8,
capabilityFlags: flags
});
if (handler) {
handler(conn);
}
});
portfinder.getPort(function(err, port) {
server.listen(port, onListening);
});
return server;
};
module.exports.useTestDb = function(cb) {
// no-op in my setup, need it for compatibility with node-mysql tests
};
| This should fix CI test. I think.
| test/common.js | This should fix CI test. I think. | <ide><path>est/common.js
<ide> var config = {
<ide> host: process.env.MYSQL_HOST || 'localhost',
<ide> user: process.env.MYSQL_USER || 'root',
<del> password: process.env.CI ? process.env.MYSQL_PASSWORD : '',
<add> password: (process.env.CI ? process.env.MYSQL_PASSWORD : '') || '',
<ide> database: process.env.MYSQL_DATABASE || 'test',
<ide> compress: process.env.MYSQL_USE_COMPRESSION,
<ide> port: process.env.MYSQL_PORT || 3306
<ide> };
<ide>
<del>console.log(config);
<ide> var configURI = "mysql://" + config.user + ":" + config.password + "@" + config.host + ":" + config.port + "/" + config.database;
<del>console.log(configURI);
<ide>
<ide> module.exports.SqlString = require('sqlstring');
<ide> module.exports.config = config; |
|
Java | mit | dfaa5d48fc443917c84e1a80283ddf3478c35a73 | 0 | avast/metrics | package com.avast.metrics.statsd;
import com.avast.metrics.api.Counter;
import com.timgroup.statsd.StatsDClient;
import java.util.concurrent.atomic.AtomicLong;
public class StatsDCounter implements Counter, StatsDMetric {
private final StatsDClient client;
private final String name;
private double sampleRate;
private final AtomicLong count = new AtomicLong(0);
StatsDCounter(final StatsDClient client, final String name) {
this(client, name, 1.0);
}
StatsDCounter(final StatsDClient client, final String name, double sampleRate) {
this.client = client;
this.name = name;
this.sampleRate = sampleRate;
}
@Override
public String getName() {
return name;
}
@Override
public void inc() {
count.incrementAndGet();
underlying(1);
}
@Override
public void inc(final long n) {
count.addAndGet(n);
underlying(n);
}
@Override
public void dec() {
count.decrementAndGet();
underlying(-1);
}
@Override
public void dec(final int n) {
final int delta = -n;
count.addAndGet(delta);
underlying(delta);
}
@Override
public long count() {
return count.get();
}
@Override
public void init() {
client.count(name, 0);
}
private void underlying(final long value) {
client.count(name, value, sampleRate);
}
}
| statsd/src/main/java/com/avast/metrics/statsd/StatsDCounter.java | package com.avast.metrics.statsd;
import com.avast.metrics.api.Counter;
import com.timgroup.statsd.StatsDClient;
import java.util.concurrent.atomic.AtomicLong;
public class StatsDCounter implements Counter, StatsDMetric {
private final StatsDClient client;
private final String name;
private double sampleRate;
private final AtomicLong count = new AtomicLong(0);
StatsDCounter(final StatsDClient client, final String name) {
this(client, name, 1.0);
}
StatsDCounter(final StatsDClient client, final String name, double sampleRate) {
this.client = client;
this.name = name;
this.sampleRate = sampleRate;
}
@Override
public String getName() {
return name;
}
@Override
public void inc() {
count.incrementAndGet();
underlying(1);
}
@Override
public void inc(final long n) {
count.addAndGet(n);
underlying(n);
}
@Override
public void dec() {
count.decrementAndGet();
underlying(-1);
}
@Override
public void dec(final int n) {
final int delta = -n;
count.addAndGet(delta);
underlying(delta);
}
@Override
public long count() {
return count.get();
}
@Override
public void init() {
client.count(name, 0, sampleRate);
}
private void underlying(final long value) {
client.count(name, value, sampleRate);
}
}
| Fixed sample rate
| statsd/src/main/java/com/avast/metrics/statsd/StatsDCounter.java | Fixed sample rate | <ide><path>tatsd/src/main/java/com/avast/metrics/statsd/StatsDCounter.java
<ide>
<ide> @Override
<ide> public void init() {
<del> client.count(name, 0, sampleRate);
<add> client.count(name, 0);
<ide> }
<ide>
<ide> private void underlying(final long value) { |
|
JavaScript | mit | f2052ae23e80e033a67d9a8c6577936ddc462eb8 | 0 | drougge/wwwwellpapp,drougge/wwwwellpapp,drougge/wwwwellpapp | function tagmode_mkb(txt, func, cn) {
var button;
button = document.createElement("input");
button.type = "submit";
button.value = txt;
button.onclick = function () {
func();
if (wp.tagging) { wp.tm_input.focus(); }
return false;
};
if (cn) { button.className = cn; }
return button;
}
function tagmode_loop(func) {
var thumbs = document.getElementsByClassName("thumb");
wp_foreach(thumbs, func);
}
function tagmode_init() {
var form, div, tags;
if (wp.tagging) { return tagmode_disable(); }
wp.tagbar = document.getElementById("tagbar");
if (!wp.tm_inited) {
tagmode_loop(function (t) {
var span = document.createElement("span");
t.insertBefore(span, t.firstChild);
t.onclick = tag_toggle;
wp_foreach(t.getElementsByTagName("a"), function (a) {
a.id = "a" + t.id.substr(1);
});
});
wp_foreach(document.getElementsByTagName("a"), function (a) {
if (!a.onclick && !a.id) { a.onclick = tagmode_confirm; }
});
tags = document.getElementById("tags");
if (tags) {
wp_foreach(tags.getElementsByTagName("a"), function (el) {
el.onclick = tagmode_taglinkclick;
});
}
form = document.createElement("form");
form.onsubmit = tagmode_apply;
form.id = "tag";
div = document.createElement("div");
div.id = "tmr";
div.appendChild(tagmode_mkb(" Apply ", tagmode_apply, "apply"));
wp.tm_spinner = document.createElement("img");
wp.tm_spinner.src = wp.uribase + "static/ajaxload.gif";
div.appendChild(wp.tm_spinner);
div.appendChild(tagmode_mkb("Exit tagmode", tagmode_disable, "exit"));
form.appendChild(div);
div = document.createElement("div");
div.id = "tml";
div.appendChild(tagmode_mkb("Select all", tagmode_select_all, null));
div.appendChild(tagmode_mkb("Select none", tagmode_unselect_all, null));
div.appendChild(tagmode_mkb("Toggle selection", tagmode_toggle_all, null));
form.appendChild(div);
wp.tm_input = document.createElement("input");
wp.tm_input.type = "text";
wp.tm_input.id = "tagmode-tags";
div = document.createElement("div");
div.id = "tmt";
div.appendChild(wp.tm_input);
form.appendChild(div);
wp.tagbar.appendChild(form);
wp.tm_inited = true;
}
if (wp.tm_saved) {
tagmode_loop(function (t) {
if (wp.tm_saved[t.id]) {
t.className = "thumb selected";
}
});
}
wp.tagging = true;
wp.tagbar.style.display = "block";
wp.tm_input.focus();
init_completion(wp.tm_input);
return false;
}
function tagmode_confirm() {
var anysel = false;
if (!wp.tagging) { return true; }
tagmode_loop(function (t) {
if (t.className !== "thumb") { anysel = true; }
});
if (wp.tm_input.value !== "" || anysel) {
return confirm("Leave tagmode?");
}
return true;
}
function tagmode_taglinkclick() {
var txt = "", val, lastc, lastc2;
if (!wp.tagging) { return true; }
wp_foreach(this.childNodes, function (el) {
if (el.nodeType === 3) {
txt += el.data.replace("\u200b", "");
}
});
val = wp.tm_input.value;
if (val !== "") {
lastc = val.substr(val.length - 1);
if (val.length > 1) {
lastc2 = val.substr(val.length - 2, 1);
} else {
lastc2 = " ";
}
if (lastc !== " " && (lastc2 !== " " || tag_prefix(lastc) === "")) {
val += " ";
}
}
wp.tm_input.value = val + txt + " ";
wp.tm_input.focus();
return false;
}
function tagmode_disable() {
var saved = {};
tagmode_loop(function (t) {
if (t.className !== "thumb") {
saved[t.id] = true;
t.className = "thumb";
}
});
wp.tm_saved = saved;
wp.tagging = false;
wp.tagbar.style.display = "none";
return false;
}
function tagmode_select_all() {
tagmode_loop(function (t) {
t.className = "thumb selected";
});
}
function tagmode_unselect_all() {
tagmode_loop(function (t) {
t.className = "thumb";
});
}
function tagmode_toggle_all() {
tagmode_loop(tag_toggle_i);
}
function tag_toggle_i(t) {
if (t.className === "thumb") {
t.className = "thumb selected";
} else {
t.className = "thumb";
}
}
function tag_toggle() {
if (!wp.tagging) { return true; }
tag_toggle_i(this);
wp.tm_input.focus();
return false;
}
function tagmode_getselected(ask) {
var m = [];
tagmode_loop(function (t) {
if (t.className !== "thumb") {
m.push(t.id.substr(1));
}
});
if (!m.length) {
tagmode_loop(function (t) {
m.push(t.id.substr(1));
});
if (ask && m.length > 1 && !confirm("Nothing selected, apply to all?")) {
return [];
}
}
return m;
}
function tagmode_apply() {
var m, data, x;
if (wp.tm_ajax) { return false; }
if (wp.tm_input.value === "") { return false; }
m = tagmode_getselected(true);
if (!m.length) { return false; }
wp.tm_spinner.style.visibility = "visible";
data = "tags=" + encodeURIComponent(wp.tm_input.value) + "&m=" + m.join("+");
x = new XMLHttpRequest();
wp.tm_ajax = x;
x.open("POST", wp.uribase + "ajax-tag", true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.onreadystatechange = function () {
var txt, r;
if (x.readyState !== 4) { return; }
wp.tm_ajax = null;
wp.tm_spinner.style.visibility = "hidden";
txt = x.responseText;
if (x.status !== 200) {
alert("Error " + x.status + "\n\n" + txt);
return;
}
if (txt.substr(0, 1) !== "{") {
alert("Error\n\n" + txt);
return;
}
r = JSON.parse(txt);
tagmode_result(r, true);
};
x.send(data);
return false;
}
function tagmode_result(r, full) {
tagmode_loop(function (t) {
var m, img;
m = t.id.substr(1);
if (r.m[m]) {
img = t.getElementsByTagName("img")[0];
img.title = r.m[m];
}
});
if (full) {
wp.tm_input.value = r.failed;
if (r.msg) { alert(r.msg); }
if (r.failed) { tagmode_create_init(r.types); }
}
}
function tagmode_create() {
var form = this, name, type, m, data, x;
name = form.name.value;
type = form.type.value;
m = form.m.value;
data = "name=" + encodeURIComponent(name) + "&type=" + encodeURIComponent(type) + "&m=" + m;
form.onsubmit = function () { return false; };
wp_foreach(form.getElementsByTagName("img"), function (img) {
img.style.visibility = "visible";
});
x = new XMLHttpRequest();
x.open("POST", wp.uribase + "ajax-tag", true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.onreadystatechange = function () {
var txt, err, r, good = true;
if (x.readyState !== 4) { return; }
txt = x.responseText;
err = "Error creating tag " + name + "\n\n";
if (x.status !== 200) {
alert(err + x.status + "\n\n" + txt);
} else if (txt.substr(0, 1) !== "{") {
alert(err + txt);
} else {
good = true;
}
r = JSON.parse(txt);
if (r.msg) {
good = false;
alert(err + r.msg);
}
if (!good) { tagmode_create_cancel_put(form); }
form.parentNode.removeChild(form);
tagmode_result(r, false);
};
x.send(data);
return false;
}
function tagmode_create_cancel_put(form) {
var txt = form.name.value;
if (wp.tm_input.value.length) { txt = " " + txt; }
wp.tm_input.value += txt;
}
function tagmode_create_cancel() {
var form = this.parentNode.parentNode;
tagmode_create_cancel_put(form);
form.parentNode.removeChild(form);
return false;
}
function tagmode_create_init(types) {
var m = tagmode_getselected(false);
wp_foreach(wp.tm_input.value.split(" "), function (n) {
var form, div, input, sel;
form = document.createElement("form");
form.onsubmit = tagmode_create;
div = document.createElement("div");
div.className = "createtag";
form.appendChild(div);
div.appendChild(document.createTextNode("Create " + n + " "));
input = document.createElement("input");
input.type = "hidden";
input.name = "name";
input.value = n;
div.appendChild(input);
input = document.createElement("input");
input.type = "hidden";
input.name = "m";
input.value = m.join("+");
div.appendChild(input);
sel = document.createElement("select");
sel.name = "type";
div.appendChild(sel);
wp_foreach(types, function (n) {
opt = document.createElement("option");
opt.value = n;
opt.className = "tt-" + n;
opt.appendChild(document.createTextNode(n));
sel.appendChild(opt);
});
wp_foreach(["Create", "Cancel"], function (n) {
input = document.createElement("input");
input.type = "submit";
input.value = n;
div.appendChild(input);
});
input.onclick = tagmode_create_cancel;
img = document.createElement("img");
img.src = wp.uribase + "static/ajaxload.gif";
div.appendChild(img);
wp.tagbar.appendChild(form);
});
wp.tm_input.value = "";
}
| static/tagmode.js | function tagmode_mkb(txt, func, cn) {
var button;
button = document.createElement("input");
button.type = "submit";
button.value = txt;
button.onclick = function () {
func();
if (wp.tagging) { wp.tagging_input.focus(); }
return false;
};
if (cn) { button.className = cn; }
return button;
}
function tagmode_loop(func) {
var thumbs = document.getElementsByClassName("thumb");
wp_foreach(thumbs, func);
}
function tagmode_init() {
var form, div, tags;
if (wp.tagging) { return tagmode_disable(); }
wp.tagbar = document.getElementById("tagbar");
if (!wp.tagging_inited) {
tagmode_loop(function (t) {
var span = document.createElement("span");
t.insertBefore(span, t.firstChild);
t.onclick = tag_toggle;
wp_foreach(t.getElementsByTagName("a"), function (a) {
a.id = "a" + t.id.substr(1);
});
});
wp_foreach(document.getElementsByTagName("a"), function (a) {
if (!a.onclick && !a.id) { a.onclick = tagmode_confirm; }
});
tags = document.getElementById("tags");
if (tags) {
wp_foreach(tags.getElementsByTagName("a"), function (el) {
el.onclick = tagmode_taglinkclick;
});
}
form = document.createElement("form");
form.onsubmit = tagmode_apply;
form.id = "tag";
div = document.createElement("div");
div.id = "tmr";
div.appendChild(tagmode_mkb(" Apply ", tagmode_apply, "apply"));
wp.tagging_spinner = document.createElement("img");
wp.tagging_spinner.src = wp.uribase + "static/ajaxload.gif";
div.appendChild(wp.tagging_spinner);
div.appendChild(tagmode_mkb("Exit tagmode", tagmode_disable, "exit"));
form.appendChild(div);
div = document.createElement("div");
div.id = "tml";
div.appendChild(tagmode_mkb("Select all", tagmode_select_all, null));
div.appendChild(tagmode_mkb("Select none", tagmode_unselect_all, null));
div.appendChild(tagmode_mkb("Toggle selection", tagmode_toggle_all, null));
form.appendChild(div);
wp.tagging_input = document.createElement("input");
wp.tagging_input.type = "text";
wp.tagging_input.id = "tagmode-tags";
div = document.createElement("div");
div.id = "tmt";
div.appendChild(wp.tagging_input);
form.appendChild(div);
wp.tagbar.appendChild(form);
wp.tagging_inited = true;
}
if (wp.tagging_saved) {
tagmode_loop(function (t) {
if (wp.tagging_saved[t.id]) {
t.className = "thumb selected";
}
});
}
wp.tagging = true;
wp.tagbar.style.display = "block";
wp.tagging_input.focus();
init_completion(wp.tagging_input);
return false;
}
function tagmode_confirm() {
var anysel = false;
if (!wp.tagging) { return true; }
tagmode_loop(function (t) {
if (t.className !== "thumb") { anysel = true; }
});
if (wp.tagging_input.value !== "" || anysel) {
return confirm("Leave tagmode?");
}
return true;
}
function tagmode_taglinkclick() {
var txt = "", val, lastc, lastc2;
if (!wp.tagging) { return true; }
wp_foreach(this.childNodes, function (el) {
if (el.nodeType === 3) {
txt += el.data.replace("\u200b", "");
}
});
val = wp.tagging_input.value;
if (val !== "") {
lastc = val.substr(val.length - 1);
if (val.length > 1) {
lastc2 = val.substr(val.length - 2, 1);
} else {
lastc2 = " ";
}
if (lastc !== " " && (lastc2 !== " " || tag_prefix(lastc) === "")) {
val += " ";
}
}
wp.tagging_input.value = val + txt + " ";
wp.tagging_input.focus();
return false;
}
function tagmode_disable() {
var saved = {};
tagmode_loop(function (t) {
if (t.className !== "thumb") {
saved[t.id] = true;
t.className = "thumb";
}
});
wp.tagging_saved = saved;
wp.tagging = false;
wp.tagbar.style.display = "none";
return false;
}
function tagmode_select_all() {
tagmode_loop(function (t) {
t.className = "thumb selected";
});
}
function tagmode_unselect_all() {
tagmode_loop(function (t) {
t.className = "thumb";
});
}
function tagmode_toggle_all() {
tagmode_loop(tag_toggle_i);
}
function tag_toggle_i(t) {
if (t.className === "thumb") {
t.className = "thumb selected";
} else {
t.className = "thumb";
}
}
function tag_toggle() {
if (!wp.tagging) { return true; }
tag_toggle_i(this);
wp.tagging_input.focus();
return false;
}
function tagmode_getselected(ask) {
var m = [];
tagmode_loop(function (t) {
if (t.className !== "thumb") {
m.push(t.id.substr(1));
}
});
if (!m.length) {
tagmode_loop(function (t) {
m.push(t.id.substr(1));
});
if (ask && m.length > 1 && !confirm("Nothing selected, apply to all?")) {
return [];
}
}
return m;
}
function tagmode_apply() {
var m, data, x;
if (wp.tagging_ajax) { return false; }
if (wp.tagging_input.value === "") { return false; }
m = tagmode_getselected(true);
if (!m.length) { return false; }
wp.tagging_spinner.style.visibility = "visible";
data = "tags=" + encodeURIComponent(wp.tagging_input.value) + "&m=" + m.join("+");
x = new XMLHttpRequest();
wp.tagging_ajax = x;
x.open("POST", wp.uribase + "ajax-tag", true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.onreadystatechange = function () {
var txt, r;
if (x.readyState !== 4) { return; }
wp.tagging_ajax = null;
wp.tagging_spinner.style.visibility = "hidden";
txt = x.responseText;
if (x.status !== 200) {
alert("Error " + x.status + "\n\n" + txt);
return;
}
if (txt.substr(0, 1) !== "{") {
alert("Error\n\n" + txt);
return;
}
r = JSON.parse(txt);
tagmode_result(r, true);
};
x.send(data);
return false;
}
function tagmode_result(r, full) {
tagmode_loop(function (t) {
var m, img;
m = t.id.substr(1);
if (r.m[m]) {
img = t.getElementsByTagName("img")[0];
img.title = r.m[m];
}
});
if (full) {
wp.tagging_input.value = r.failed;
if (r.msg) { alert(r.msg); }
if (r.failed) { tagmode_create_init(r.types); }
}
}
function tagmode_create() {
var form = this, name, type, m, data, x;
name = form.name.value;
type = form.type.value;
m = form.m.value;
data = "name=" + encodeURIComponent(name) + "&type=" + encodeURIComponent(type) + "&m=" + m;
form.onsubmit = function () { return false; };
wp_foreach(form.getElementsByTagName("img"), function (img) {
img.style.visibility = "visible";
});
x = new XMLHttpRequest();
x.open("POST", wp.uribase + "ajax-tag", true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.onreadystatechange = function () {
var txt, err, r, good = true;
if (x.readyState !== 4) { return; }
txt = x.responseText;
err = "Error creating tag " + name + "\n\n";
if (x.status !== 200) {
alert(err + x.status + "\n\n" + txt);
} else if (txt.substr(0, 1) !== "{") {
alert(err + txt);
} else {
good = true;
}
r = JSON.parse(txt);
if (r.msg) {
good = false;
alert(err + r.msg);
}
if (!good) { tagmode_create_cancel_put(form); }
form.parentNode.removeChild(form);
tagmode_result(r, false);
};
x.send(data);
return false;
}
function tagmode_create_cancel_put(form) {
var txt = form.name.value;
if (wp.tagging_input.value.length) { txt = " " + txt; }
wp.tagging_input.value += txt;
}
function tagmode_create_cancel() {
var form = this.parentNode.parentNode;
tagmode_create_cancel_put(form);
form.parentNode.removeChild(form);
return false;
}
function tagmode_create_init(types) {
var m = tagmode_getselected(false);
wp_foreach(wp.tagging_input.value.split(" "), function (n) {
var form, div, input, sel;
form = document.createElement("form");
form.onsubmit = tagmode_create;
div = document.createElement("div");
div.className = "createtag";
form.appendChild(div);
div.appendChild(document.createTextNode("Create " + n + " "));
input = document.createElement("input");
input.type = "hidden";
input.name = "name";
input.value = n;
div.appendChild(input);
input = document.createElement("input");
input.type = "hidden";
input.name = "m";
input.value = m.join("+");
div.appendChild(input);
sel = document.createElement("select");
sel.name = "type";
div.appendChild(sel);
wp_foreach(types, function (n) {
opt = document.createElement("option");
opt.value = n;
opt.className = "tt-" + n;
opt.appendChild(document.createTextNode(n));
sel.appendChild(opt);
});
wp_foreach(["Create", "Cancel"], function (n) {
input = document.createElement("input");
input.type = "submit";
input.value = n;
div.appendChild(input);
});
input.onclick = tagmode_create_cancel;
img = document.createElement("img");
img.src = wp.uribase + "static/ajaxload.gif";
div.appendChild(img);
wp.tagbar.appendChild(form);
});
wp.tagging_input.value = "";
}
| Rename wp.tagging_* -> wp.tm_* (for sanity).
| static/tagmode.js | Rename wp.tagging_* -> wp.tm_* (for sanity). | <ide><path>tatic/tagmode.js
<ide> button.value = txt;
<ide> button.onclick = function () {
<ide> func();
<del> if (wp.tagging) { wp.tagging_input.focus(); }
<add> if (wp.tagging) { wp.tm_input.focus(); }
<ide> return false;
<ide> };
<ide> if (cn) { button.className = cn; }
<ide> var form, div, tags;
<ide> if (wp.tagging) { return tagmode_disable(); }
<ide> wp.tagbar = document.getElementById("tagbar");
<del> if (!wp.tagging_inited) {
<add> if (!wp.tm_inited) {
<ide> tagmode_loop(function (t) {
<ide> var span = document.createElement("span");
<ide> t.insertBefore(span, t.firstChild);
<ide> div = document.createElement("div");
<ide> div.id = "tmr";
<ide> div.appendChild(tagmode_mkb(" Apply ", tagmode_apply, "apply"));
<del> wp.tagging_spinner = document.createElement("img");
<del> wp.tagging_spinner.src = wp.uribase + "static/ajaxload.gif";
<del> div.appendChild(wp.tagging_spinner);
<add> wp.tm_spinner = document.createElement("img");
<add> wp.tm_spinner.src = wp.uribase + "static/ajaxload.gif";
<add> div.appendChild(wp.tm_spinner);
<ide> div.appendChild(tagmode_mkb("Exit tagmode", tagmode_disable, "exit"));
<ide> form.appendChild(div);
<ide> div = document.createElement("div");
<ide> div.appendChild(tagmode_mkb("Select none", tagmode_unselect_all, null));
<ide> div.appendChild(tagmode_mkb("Toggle selection", tagmode_toggle_all, null));
<ide> form.appendChild(div);
<del> wp.tagging_input = document.createElement("input");
<del> wp.tagging_input.type = "text";
<del> wp.tagging_input.id = "tagmode-tags";
<add> wp.tm_input = document.createElement("input");
<add> wp.tm_input.type = "text";
<add> wp.tm_input.id = "tagmode-tags";
<ide> div = document.createElement("div");
<ide> div.id = "tmt";
<del> div.appendChild(wp.tagging_input);
<add> div.appendChild(wp.tm_input);
<ide> form.appendChild(div);
<ide> wp.tagbar.appendChild(form);
<del> wp.tagging_inited = true;
<del> }
<del> if (wp.tagging_saved) {
<add> wp.tm_inited = true;
<add> }
<add> if (wp.tm_saved) {
<ide> tagmode_loop(function (t) {
<del> if (wp.tagging_saved[t.id]) {
<add> if (wp.tm_saved[t.id]) {
<ide> t.className = "thumb selected";
<ide> }
<ide> });
<ide> }
<ide> wp.tagging = true;
<ide> wp.tagbar.style.display = "block";
<del> wp.tagging_input.focus();
<del> init_completion(wp.tagging_input);
<add> wp.tm_input.focus();
<add> init_completion(wp.tm_input);
<ide> return false;
<ide> }
<ide>
<ide> tagmode_loop(function (t) {
<ide> if (t.className !== "thumb") { anysel = true; }
<ide> });
<del> if (wp.tagging_input.value !== "" || anysel) {
<add> if (wp.tm_input.value !== "" || anysel) {
<ide> return confirm("Leave tagmode?");
<ide> }
<ide> return true;
<ide> txt += el.data.replace("\u200b", "");
<ide> }
<ide> });
<del> val = wp.tagging_input.value;
<add> val = wp.tm_input.value;
<ide> if (val !== "") {
<ide> lastc = val.substr(val.length - 1);
<ide> if (val.length > 1) {
<ide> val += " ";
<ide> }
<ide> }
<del> wp.tagging_input.value = val + txt + " ";
<del> wp.tagging_input.focus();
<add> wp.tm_input.value = val + txt + " ";
<add> wp.tm_input.focus();
<ide> return false;
<ide> }
<ide>
<ide> t.className = "thumb";
<ide> }
<ide> });
<del> wp.tagging_saved = saved;
<add> wp.tm_saved = saved;
<ide> wp.tagging = false;
<ide> wp.tagbar.style.display = "none";
<ide> return false;
<ide> function tag_toggle() {
<ide> if (!wp.tagging) { return true; }
<ide> tag_toggle_i(this);
<del> wp.tagging_input.focus();
<add> wp.tm_input.focus();
<ide> return false;
<ide> }
<ide>
<ide>
<ide> function tagmode_apply() {
<ide> var m, data, x;
<del> if (wp.tagging_ajax) { return false; }
<del> if (wp.tagging_input.value === "") { return false; }
<add> if (wp.tm_ajax) { return false; }
<add> if (wp.tm_input.value === "") { return false; }
<ide> m = tagmode_getselected(true);
<ide> if (!m.length) { return false; }
<del> wp.tagging_spinner.style.visibility = "visible";
<del> data = "tags=" + encodeURIComponent(wp.tagging_input.value) + "&m=" + m.join("+");
<add> wp.tm_spinner.style.visibility = "visible";
<add> data = "tags=" + encodeURIComponent(wp.tm_input.value) + "&m=" + m.join("+");
<ide> x = new XMLHttpRequest();
<del> wp.tagging_ajax = x;
<add> wp.tm_ajax = x;
<ide> x.open("POST", wp.uribase + "ajax-tag", true);
<ide> x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
<ide> x.onreadystatechange = function () {
<ide> var txt, r;
<ide> if (x.readyState !== 4) { return; }
<del> wp.tagging_ajax = null;
<del> wp.tagging_spinner.style.visibility = "hidden";
<add> wp.tm_ajax = null;
<add> wp.tm_spinner.style.visibility = "hidden";
<ide> txt = x.responseText;
<ide> if (x.status !== 200) {
<ide> alert("Error " + x.status + "\n\n" + txt);
<ide> }
<ide> });
<ide> if (full) {
<del> wp.tagging_input.value = r.failed;
<add> wp.tm_input.value = r.failed;
<ide> if (r.msg) { alert(r.msg); }
<ide> if (r.failed) { tagmode_create_init(r.types); }
<ide> }
<ide>
<ide> function tagmode_create_cancel_put(form) {
<ide> var txt = form.name.value;
<del> if (wp.tagging_input.value.length) { txt = " " + txt; }
<del> wp.tagging_input.value += txt;
<add> if (wp.tm_input.value.length) { txt = " " + txt; }
<add> wp.tm_input.value += txt;
<ide> }
<ide> function tagmode_create_cancel() {
<ide> var form = this.parentNode.parentNode;
<ide>
<ide> function tagmode_create_init(types) {
<ide> var m = tagmode_getselected(false);
<del> wp_foreach(wp.tagging_input.value.split(" "), function (n) {
<add> wp_foreach(wp.tm_input.value.split(" "), function (n) {
<ide> var form, div, input, sel;
<ide> form = document.createElement("form");
<ide> form.onsubmit = tagmode_create;
<ide> div.appendChild(img);
<ide> wp.tagbar.appendChild(form);
<ide> });
<del> wp.tagging_input.value = "";
<del>}
<add> wp.tm_input.value = "";
<add>} |
|
Java | agpl-3.0 | 3b9166173a77c0864f105a5b43cef26f432caa69 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 1c3b26b0-2e62-11e5-9284-b827eb9e62be | hello.java | 1c35c4b8-2e62-11e5-9284-b827eb9e62be | 1c3b26b0-2e62-11e5-9284-b827eb9e62be | hello.java | 1c3b26b0-2e62-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>1c35c4b8-2e62-11e5-9284-b827eb9e62be
<add>1c3b26b0-2e62-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 906205e0bfc68bb377434ce9dc4d7499f3d51aad | 0 | ysc/superword,ysc/superword,simpleabc/MyTest,ysc/superword,simpleabc/MyTest | /**
*
* APDPlat - Application Product Development Platform Copyright (c) 2013, 杨尚川,
* [email protected]
*
* 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 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.apdplat.superword.tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* 文本索引
*
* 索引文件结构:
* 1、一个词的索引由=分割的三部分组成,第一部分是词,第二部分是这个词在多少个文档中出现过(上限1000),第三部分是倒排表
* 2、倒排表由多个倒排表项目组成,倒排表项目之间使用|分割
* 3、倒排表项目的组成又分为三部分,用_分割,第一部分是文档ID,第二部分是词频,第三部分是词的位置
* 4、词的位置用:分割
*
* 例如:
* the=1000=1_2_3:13|1_3_15:31:35
* 表示词the的索引:
* 词:the
* 有1000个文档包含the这个词
* 包含这个词的第一篇文档的ID是1,the的词频是2,出现the的位置分别是3和13
* 包含这个词的第二篇文档的ID是1+1=2,the的词频是3,出现the的位置分别是是15、31和35
*
* ID为1的文档的内容为:
* License perpetual the right patent rig Implement interfaces Space, or
* Licensor implemen the applic foregoing hereunder extent of interest in
* Lead's lic registered.《Java EE 7 Specification》【1213/1】
*
* ID为2的文档的内容为:
* Specification Lead hereby grants you a fully-paid, non-exclusive,
* ferable, worldwide, limited license (without the right to sublicense),
* under Specification Lead's intellectual property rights to view, download,
* use and reproduce the Specification only for the internal evaluation.
* 《Java EE 7 Specification》【1213/2】
*
* @author 杨尚川
*/
public class TextIndexer {
private TextIndexer(){}
private static final Logger LOGGER = LoggerFactory.getLogger(TextIndexer.class);
private static final String INDEX_TEXT = "target/index_text.txt";
private static final String INDEX = "target/index.txt";
private static final int INDEX_LENGTH_LIMIT = 1000;
public static void index(String path){
try {
//词 -> [{文档ID,位置}, {文档ID,位置}]
Map<String, Posting> index = new HashMap<>();
AtomicInteger lineCount = new AtomicInteger();
BufferedWriter writer = Files.newBufferedWriter(Paths.get(INDEX_TEXT), Charset.forName("utf-8"));
//将所有文本合成一个文件,每一行分配一个行号
TextAnalyzer.getFileNames(path).forEach(file -> {
try {
List<String> lines = Files.readAllLines(Paths.get(file));
AtomicInteger i = new AtomicInteger();
lines.forEach(line -> {
try {
writer.append(line).append("《").append(Paths.get(file).getFileName().toString().split("\\.")[0]).append("》【").append(lines.size()+"/"+i.incrementAndGet()).append("】\n");
lineCount.incrementAndGet();
List<String> words = TextAnalyzer.seg(line);
for(int j=0; j< words.size(); j++){
String word = words.get(j);
//准备倒排表
index.putIfAbsent(word, new Posting());
//倒排表长度限制
if(index.get(word).size()<INDEX_LENGTH_LIMIT) {
//一篇文档对应倒排表中的一项
index.get(word).putIfAbsent(lineCount.get());
index.get(word).get(lineCount.get()).addPosition(j+1);
}
}
} catch (IOException e) {
LOGGER.error("文件写入错误", e);
}
});
} catch (IOException e) {
LOGGER.error("文件读取错误", e);
}
});
writer.close();
List<String> indices =
index
.entrySet()
.stream()
.sorted((a,b)->(b.getValue().size()-a.getValue().size()))
.map(entry -> {
StringBuilder docs = new StringBuilder();
AtomicInteger lastDocId = new AtomicInteger();
entry.getValue().getPostingItems().stream().sorted().forEach(postingItem -> {
//保存增量
docs.append(postingItem.getDocId()-lastDocId.get()).append("_").append(postingItem.getFrequency()).append("_").append(postingItem.positionsToStr()).append("|");
lastDocId.set(postingItem.getDocId());
});
if (docs.length() > 1) {
docs.setLength(docs.length() - 1);
return entry.getKey() + "=" + entry.getValue().size() + "=" + docs.toString();
}
return entry.getKey() + "=0";
})
.collect(Collectors.toList());
Files.write(Paths.get(INDEX), indices, Charset.forName("utf-8"));
}catch (Exception e){
LOGGER.error("索引操作出错", e);
}
}
public static void main(String[] args) {
//index("src/test/resources/text");
index("src/main/resources/it");
}
}
| src/main/java/org/apdplat/superword/tools/TextIndexer.java | /**
*
* APDPlat - Application Product Development Platform Copyright (c) 2013, 杨尚川,
* [email protected]
*
* 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 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.apdplat.superword.tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* 文本索引
* @author 杨尚川
*/
public class TextIndexer {
private TextIndexer(){}
private static final Logger LOGGER = LoggerFactory.getLogger(TextIndexer.class);
private static final String INDEX_TEXT = "target/index_text.txt";
private static final String INDEX = "target/index.txt";
private static final int INDEX_LENGTH_LIMIT = 1000;
public static void index(String path){
try {
//词 -> [{文档ID,位置}, {文档ID,位置}]
Map<String, Posting> index = new HashMap<>();
AtomicInteger lineCount = new AtomicInteger();
BufferedWriter writer = Files.newBufferedWriter(Paths.get(INDEX_TEXT), Charset.forName("utf-8"));
//将所有文本合成一个文件,每一行分配一个行号
TextAnalyzer.getFileNames(path).forEach(file -> {
try {
List<String> lines = Files.readAllLines(Paths.get(file));
AtomicInteger i = new AtomicInteger();
lines.forEach(line -> {
try {
writer.append(line).append("《").append(Paths.get(file).getFileName().toString().split("\\.")[0]).append("》【").append(lines.size()+"/"+i.incrementAndGet()).append("】\n");
lineCount.incrementAndGet();
List<String> words = TextAnalyzer.seg(line);
for(int j=0; j< words.size(); j++){
String word = words.get(j);
//准备倒排表
index.putIfAbsent(word, new Posting());
//倒排表长度限制
if(index.get(word).size()<INDEX_LENGTH_LIMIT) {
//一篇文档对应倒排表中的一项
index.get(word).putIfAbsent(lineCount.get());
index.get(word).get(lineCount.get()).addPosition(j+1);
}
}
} catch (IOException e) {
LOGGER.error("文件写入错误", e);
}
});
} catch (IOException e) {
LOGGER.error("文件读取错误", e);
}
});
writer.close();
List<String> indices =
index
.entrySet()
.stream()
.sorted((a,b)->(b.getValue().size()-a.getValue().size()))
.map(entry -> {
StringBuilder docs = new StringBuilder();
AtomicInteger lastDocId = new AtomicInteger();
entry.getValue().getPostingItems().stream().sorted().forEach(postingItem -> {
//保存增量
docs.append(postingItem.getDocId()-lastDocId.get()).append("_").append(postingItem.getFrequency()).append("_").append(postingItem.positionsToStr()).append("|");
lastDocId.set(postingItem.getDocId());
});
if (docs.length() > 1) {
docs.setLength(docs.length() - 1);
return entry.getKey() + "=" + entry.getValue().size() + "=" + docs.toString();
}
return entry.getKey() + "=0";
})
.collect(Collectors.toList());
Files.write(Paths.get(INDEX), indices, Charset.forName("utf-8"));
}catch (Exception e){
LOGGER.error("索引操作出错", e);
}
}
public static void main(String[] args) {
//index("src/test/resources/text");
index("src/main/resources/it");
}
}
| 索引文件结构
| src/main/java/org/apdplat/superword/tools/TextIndexer.java | 索引文件结构 | <ide><path>rc/main/java/org/apdplat/superword/tools/TextIndexer.java
<ide>
<ide> /**
<ide> * 文本索引
<add> *
<add> * 索引文件结构:
<add> * 1、一个词的索引由=分割的三部分组成,第一部分是词,第二部分是这个词在多少个文档中出现过(上限1000),第三部分是倒排表
<add> * 2、倒排表由多个倒排表项目组成,倒排表项目之间使用|分割
<add> * 3、倒排表项目的组成又分为三部分,用_分割,第一部分是文档ID,第二部分是词频,第三部分是词的位置
<add> * 4、词的位置用:分割
<add> *
<add> * 例如:
<add> * the=1000=1_2_3:13|1_3_15:31:35
<add> * 表示词the的索引:
<add> * 词:the
<add> * 有1000个文档包含the这个词
<add> * 包含这个词的第一篇文档的ID是1,the的词频是2,出现the的位置分别是3和13
<add> * 包含这个词的第二篇文档的ID是1+1=2,the的词频是3,出现the的位置分别是是15、31和35
<add> *
<add> * ID为1的文档的内容为:
<add> * License perpetual the right patent rig Implement interfaces Space, or
<add> * Licensor implemen the applic foregoing hereunder extent of interest in
<add> * Lead's lic registered.《Java EE 7 Specification》【1213/1】
<add> *
<add> * ID为2的文档的内容为:
<add> * Specification Lead hereby grants you a fully-paid, non-exclusive,
<add> * ferable, worldwide, limited license (without the right to sublicense),
<add> * under Specification Lead's intellectual property rights to view, download,
<add> * use and reproduce the Specification only for the internal evaluation.
<add> * 《Java EE 7 Specification》【1213/2】
<add> *
<ide> * @author 杨尚川
<ide> */
<ide> public class TextIndexer { |
|
JavaScript | mpl-2.0 | 8626a99de79694448d398150eeba008643c6a555 | 0 | g-bo/eea.webforms.generator | /**
* @file xsdwebform.parser.log.js
* XSD Schema to HTML5 Web Form
* @author George Bouris <[email protected]>
* @copyright Copyright (C) 2017 EEA, Eworx, George Bouris. All rights reserved.
*/
'use strict';
/**
* Class XSDWebFormParserLog
* Parser for XSD Schema Tags
* Static
*/
class XSDWebFormParserLog {
/**
* Class constructor
*/
constructor() {
this.htmlOutput = `<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script>
$(function () {
var cnt = 0;
var objs = $("ul.clvl");
var objsLength = $("ul.clvl").length;
objs.each(function (index) {
var th = 15;
if (objsLength < 1000) {
var lvl = $(this).attr("lvl");
var prlvl = $(this).prevAll("ul.clvl[lvl="+lvl+"]");
var prlvlP1 = $(this).prevAll("ul.clvl:first");
var pos = $(this).offset();
var parentPos = prlvl.offset();
if (parentPos && prlvlP1.attr("lvl") > lvl) {
th = pos.top - parentPos.top - $(prlvl).outerHeight() - 1;
if (th < 0 ) th = 15;
}
}
$(this).prepend($("<div style=\\"margin-top: -" + th + "px;position: absolute; background-color: #cc0000; height: " + th + "px; width: 16px;\\"></div>"));
});
$(".htmlo li.src .srvs:first").show();
});
function toggleTab(obj, did) {
$(".tbtn").removeClass("active");
$(".tabpanel").hide();
$("#" + did).toggle();
$(obj).addClass("active");
}
</script>
<style>
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
background-color: #222;
color: #999;
padding: 0;
margin: 0;
}
ul {
list-style-type: none;
}
li.xsdc {
box-shadow: 2px 1px 1px #ccc;
padding: 4px 8px;font-size:14px;
border-radius: 0 50% 50% 0;
line-height: 25px;
}
li.xsdc span {
color: #999;
font-size: 11px;
float: right;
margin-right: 10px
}
.ftag {
width: 98%;
z-index: -2;
padding: 4px 8px;
font-size: 12px;
position: absolute;
color: #eee;
background-color: #242424;
}
/*
.ftag:after {
display: block;
width: 92%;
height: 1px;
content: " ";
sborder-top: 1px dashed #2a2a2a;
margin-left: 120px;
margin-top: -8px;
position: absolute;
}*/
.phtmlt {
width: auto;
z-index: -1;
padding: 8px 50px;
font-size: 12px;
position: relative;
color: #fff;
background-color: #222;
}
.lvlln {
width:150px;
min-width:150px;
color: #eee;
}
.lvlln:after {
content: " ";
margin: 20px 4px 4px 4px;
display: block;
height: 95%;
z-index: -1;
min-height: 95%;
position: fixed;
border-left: 1px dashed #2a2a2a;
}
.htmlo li.svc {
font-family: monospace;
font-size: 11px;
background-color: #006699;
margin: 10px;
border-radius: 5px 5px 0 0;
border: solid 5px rgba(104, 104, 104, 1);
border-bottom: none;
padding: 8px;
color: #fff;
cursor: pointer;
}
.htmlo li.src {
font-family: monospace;
margin: -10px 10px 30px 10px;
border-radius: 0 0 5px 5px;
border: solid 5px rgba(104, 104, 104, 1);
border-top: none;
color: #fff;
background-color: #006699;
}
.htmlo li.src .srvs {
background-color: rgb(128, 128, 128);
padding: 8px;
display: none;
border-radius: 35px;
border: solid 20px rgba(104, 104, 104, 1);
margin: 10px;
}
.svcimg {
width: 800px;
text-align: center;
border-radius: 5px;
border: solid 15px rgba(104, 104, 104, 1);
padding: 0;
margin: 0 auto;
margin-bottom: 50px;
}
.svcimg img {
width: 800px;
margin-bottom: -4px;
}
.tbtn {
text-align: center;
cursor: pointer;
width: 200px;
background-color: #999;
color: #222;
padding: 8px;
font-weight: 900;
}
.tbtn:active {
background-color: #777;
}
.tbtn.active {
color: #fff;
}
</style>
</head>
<body>
<div style="display: flex;margin-bottom: 30px;background-color:#444;width:auto;padding:2px;"><div onclick="toggleTab(this, 'xsdpanel');" class="tbtn active">XSD</div><div onclick="toggleTab(this, 'htmlpanel')" class="tbtn">HTML</div></div>
<div id="xsdpanel" class="tabpanel">
<div style="width:auto;display:flex;position:relative;top:0">
<div style="width:194px;min-width:194px"> </div>
<div class="lvlln">0</div>
<div class="lvlln">1</div>
<div class="lvlln">2</div>
<div class="lvlln">3</div>
<div class="lvlln">4</div>
<div class="lvlln">5</div>
<div class="lvlln">6</div>
<div class="lvlln">7</div>
<div class="lvlln">8</div>
<div class="lvlln">9</div>
<div class="lvlln">10</div>
</div>
`;
}
/**
* showLog
*/
showLogs(sender) {
if (!sender.verbose)
console.log("");
// process.stdout.write(sender.htmlOutput.HTMLObjects[0]);
if (sender.verbose) {
console.log("\n\n\x1b[0m\x1b[32mHTML OBJECTS: \x1b[0m\x1b[36m");
this.htmlOutput += `<div style="background-color: #222;padding: 8px;font-size:12px;"><BR><BR><h2>HTML OBJECTS: </h2>\n\n<div class="svcimg"><img src="scrnsht.png"></div>\n<BR><p style="margin-left:50px;">DoubleClick for src</p>\n`;
console.log("\x1b[0m\x1b[2m");
this.htmlOutput += `\n<ul style="color: #fff;" class="htmlo">\n`;
sender.htmlOutput.HTMLObjects.forEach( (item, index1) => {
item.itemObject.groups.forEach( (gitem, index2) => {
gitem.itemObject.items.forEach( (eitem, index3) => {
console.log(eitem.toString().substring(0, 40) + "...");
this.htmlOutput += `<li class="svc" ondblclick="$('#src${index1}_${index2}_${index3}').slideToggle()"><code>${eitem}</code></li>\n`;
this.htmlOutput += `<li class="src"><div class="srvs" id="src${index1}_${index2}_${index3}" ><code>${eitem.toString().replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<BR>').replace(/\t/g, ' ')}</code></div></li>\n`;
});
});
});
this.htmlOutput += `</ul>\n</div>\n`;
} else {
console.log("");
}
console.log("\x1b[0m");
console.log(new Date());
this.htmlOutput += `\n<div style="background-color: #222;font-size:12px;color:#777"><BR><BR>${new Date()}</div>\n`;
console.log("\n\x1b[2m\x1b[33m==================================================================================================================================================\n\x1b[0m");
}
/**
* logXSD
* @param xObject
*/
logXSD(xObject) {
console.log("\n\n\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
console.log(` \x1b[1m\x1b[36mFILE : ${xObject.xfile} \x1b[0m\n`);
console.log("\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");
this.htmlOutput += `<h2><span style="color:#777;background-color: #222;">XSD File:</span> ${xObject.xfile}</h2>\n`;
}
/**
* logHTML
* @param xObject
*/
logHTML(xObject) {
console.log("\n\n\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
console.log(` \x1b[1m\x1b[33mFILE : ${xObject.hfile} \x1b[0m\n`);
console.log("\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");
this.htmlOutput += `\n</div>\n<div id="htmlpanel" class="tabpanel" style="display:none;">\n<h2 style="background-color: #222;margin: 0;"><span style="color:#777;">XML File:</span> ${xObject.hfile}</h2>\n`;
}
/**
* showItemLog - ShowLog
* @param xsdItem
*/
showItemLog(xsdItem, verbose) {
let xspace = " ";
for (let i = 0; i < xsdItem.level; i++) {
xspace += "\t";
}
console.log(`${xspace}\x1b[0m\x1b[31m▓▓▓▓▓▓▓▓▓▓▓▓▓\x1b[0m`);
process.stdout.write(`${xspace}\x1b[2m▓▓▓▓ \x1b[0m\x1b[2mL:${xsdItem.level} \x1b[2m▓▓▓▓\x1b[0m\x1b[31m⇢\x1b[0m `);
this.htmlOutput += `<ul style="margin-left:${(xsdItem.level +1) * 150}px;" class="clvl" lvl="${xsdItem.level}"><div style="width:100px;padding:4px 8px;font-size:14px;color:#fff;background-color:#006699;font-weight:700;">Level ${xsdItem.level}</div>`;
if (xsdItem.children) {
process.stdout.write(`\x1b[1m${xsdItem.name}`);
this.htmlOutput += `<li class="xsdc" style="width:200px;color:#006699;background-color:#fff;">${xsdItem.name}\t<span>line ${xsdItem.line}</span></li>\n`;
if (xsdItem.attr.name) {
process.stdout.write(` - ${xsdItem.attr.name}`);
this.htmlOutput += `<li class="xsdc" style="border-radius:0;width:300px;font-size:13px;color:#cc0000;background-color:#fafafa;"><b>${xsdItem.attr.name}</b></li>\n`;
if (verbose) {
if (xsdItem.name === "xs:element") {
let txmlItem = xsdItem.toString();
txmlItem = txmlItem.split("\n").join("");
txmlItem = txmlItem.split("<").join(xspace + `\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m<`);
let pos1 = txmlItem.indexOf("<xs:documentation>");
if (pos1 > 0) {
let pos2 = txmlItem.indexOf("</xs:documentation>");
txmlItem = txmlItem.substring(0, pos1) + "<xs:documentation> ..." + txmlItem.substring(pos2);
}
process.stdout.write(`\x1b[2m${txmlItem}`);
}
}
} else if (xsdItem.attr.value) {
process.stdout.write(`\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m${xsdItem.attr.value}\x1b[0m`);
this.htmlOutput += `<li class="xsdc"style="border-radius:0;width:300px;font-size:11px;color:#333;background-color:#dcedf4;"><b>${xsdItem.attr.value}</b></li>\n`;
} else if (xsdItem.attr.ref) {
process.stdout.write(`\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m\x1b[36mRef: \x1b[1m\x1b[36m${xsdItem.attr.ref}\x1b[0m`);
this.htmlOutput += `<li class="xsdc"style="border-radius:0;width:300px;font-size:11px;color:#333;background-color:#dcedf4;">Ref: ${xsdItem.attr.ref}</li>\n`;
}
process.stdout.write(`\n\x1b[2m${xspace}▓▓▓▓▓▓▓▓▓▓▓▓▓`);
if (xsdItem.name === "xs:documentation" && xsdItem.xparent.name === "xs:annotation") {
let txmlItem = xsdItem.val.toString().trim();
if (txmlItem.length > 60)
txmlItem = txmlItem.substring(0, 60) + "...";
process.stdout.write(` \x1b[2m\x1b[37m ${txmlItem}\x1b[0m\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓`);
}
if (xsdItem.xparent) {
console.log(`\x1b[2m\x1b[32m parent ::\x1b[1m ${xsdItem.xparent.name}\x1b[0m`);
if (xsdItem.xparent.attr.name) {
console.log(`${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m\x1b[32m par.name ::\x1b[1m ${xsdItem.xparent.attr.name}\x1b[0m`);
}
}
}
if (xsdItem.level === 0)
console.log(" ");
this.htmlOutput += `</ul>`;
process.stdout.write(`\x1b[2m${xspace} ▒▒`);
}
/**
* logXsdTag - Log XSD Element Tag
* @param item
*/
logXsdTag(item) {
console.log(`\x1b[0m\x1b[31m⇣\x1b[2m Found Tag \x1b[33m${item}\x1b[0m`);
this.htmlOutput += `<div class="ftag"># ${item}</div>\n`;
}
/**
* logTODO - Log XSD Element Tag
* @param msg
*/
logTODO(msg) {
console.log(`\x1b[1m\x1b[31mTODO: \x1b[0m${msg}\x1b[0m`);
}
/**
* logHtmlTag - Log HTML Element Tag
* @param item
*/
logHtmlTag(item, sender) {
if (sender.verbose) {
console.log(`\x1b[0m\x1b[31m⇣\n\x1b[2mParsing HTML Tag ⇢ \x1b[33m${item.name}\x1b[0m\n`);
this.htmlOutput += `<div class="phtmlt"># <b>${item.name}</b> :: <b>${item.attr.element || item.attr.name || ' '}</b></div>\n`;
}
}
/**
* getHtmlLog
*/
getHtmlLog() {
return this.htmlOutput + `
</body>
</html> `;
}
}
module.exports = XSDWebFormParserLog; | src/lib/xsdwebform.parser.log.js | /**
* @file xsdwebform.parser.log.js
* XSD Schema to HTML5 Web Form
* @author George Bouris <[email protected]>
* @copyright Copyright (C) 2017 EEA, Eworx, George Bouris. All rights reserved.
*/
'use strict';
/**
* Class XSDWebFormParserLog
* Parser for XSD Schema Tags
* Static
*/
class XSDWebFormParserLog {
/**
* Class constructor
*/
constructor() {
this.htmlOutput = `<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script>
$(function () {
var cnt = 0;
var objs = $("ul.clvl");
var objsLength = $("ul.clvl").length;
objs.each(function (index) {
var th = 15;
if (objsLength < 1000) {
var lvl = $(this).attr("lvl");
var prlvl = $(this).prevAll("ul.clvl[lvl="+lvl+"]");
var prlvlP1 = $(this).prevAll("ul.clvl:first");
var pos = $(this).offset();
var parentPos = prlvl.offset();
if (parentPos && prlvlP1.attr("lvl") > lvl) {
th = pos.top - parentPos.top - $(prlvl).outerHeight() - 1;
if (th < 0 ) th = 15;
}
}
$(this).prepend($("<div style=\\"margin-top: -" + th + "px;position: absolute; background-color: #cc0000; height: " + th + "px; width: 16px;\\"></div>"));
});
$(".htmlo li.src .srvs:first").show();
});
function toggleTab(obj, did) {
$(".tbtn").removeClass("active");
$(".tabpanel").hide();
$("#" + did).toggle();
$(obj).addClass("active");
}
</script>
<style>
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
background-color: #222;
color: #999;
padding: 0;
margin: 0;
}
ul {
list-style-type: none;
}
li.xsdc {
box-shadow: 2px 1px 1px #ccc;
padding: 4px 8px;font-size:14px;
border-radius: 0 50% 50% 0;
line-height: 25px;
}
li.xsdc span {
color: #999;
font-size: 11px;
float: right;
margin-right: 10px
}
.ftag {
width: 98%;
z-index: -2;
padding: 4px 8px;
font-size: 12px;
position: absolute;
color: #eee;
background-color: #242424;
}
/*
.ftag:after {
display: block;
width: 92%;
height: 1px;
content: " ";
sborder-top: 1px dashed #2a2a2a;
margin-left: 120px;
margin-top: -8px;
position: absolute;
}*/
.phtmlt {
width: auto;
z-index: -1;
padding: 8px 50px;
font-size: 12px;
position: relative;
color: #fff;
background-color: #222;
}
.lvlln {
width:150px;
min-width:150px;
color: #eee;
}
.lvlln:after {
content: " ";
margin: 20px 4px 4px 4px;
display: block;
height: 95%;
z-index: -1;
min-height: 95%;
position: fixed;
border-left: 1px dashed #2a2a2a;
}
.htmlo li.svc {
font-family: monospace;
font-size: 11px;
background-color: #006699;
margin: 10px;
border-radius: 5px 5px 0 0;
border: solid 5px rgba(104, 104, 104, 1);
border-bottom: none;
padding: 8px;
color: #fff;
cursor: pointer;
}
.htmlo li.src {
font-family: monospace;
margin: -10px 10px 30px 10px;
border-radius: 0 0 5px 5px;
border: solid 5px rgba(104, 104, 104, 1);
border-top: none;
color: #fff;
background-color: #006699;
}
.htmlo li.src .srvs {
background-color: rgb(128, 128, 128);
padding: 8px;
display: none;
border-radius: 35px;
border: solid 20px rgba(104, 104, 104, 1);
margin: 10px;
}
.svcimg {
width: 800px;
text-align: center;
border-radius: 5px;
border: solid 15px rgba(104, 104, 104, 1);
padding: 0;
margin: 0 auto;
margin-bottom: 50px;
}
.svcimg img {
width: 800px;
margin-bottom: -4px;
}
.tbtn {
cursor: pointer;
width: 200px;
background-color: #999;
color: #222;
padding: 8px;
font-weight: 900;
}
.tbtn:active {
background-color: #777;
}
.tbtn.active {
color: #fff;
}
</style>
</head>
<body>
<div style="display: flex;margin-bottom: 30px;background-color:#444;width:auto;padding:2px;"><div onclick="toggleTab(this, 'xsdpanel');" class="tbtn active">XSD</div><div onclick="toggleTab(this, 'htmlpanel')" class="tbtn">HTML</div></div>
<div id="xsdpanel" class="tabpanel">
<div style="width:auto;display:flex;position:relative;top:0">
<div style="width:194px;min-width:194px"> </div>
<div class="lvlln">0</div>
<div class="lvlln">1</div>
<div class="lvlln">2</div>
<div class="lvlln">3</div>
<div class="lvlln">4</div>
<div class="lvlln">5</div>
<div class="lvlln">6</div>
<div class="lvlln">7</div>
<div class="lvlln">8</div>
<div class="lvlln">9</div>
<div class="lvlln">10</div>
</div>
`;
}
/**
* showLog
*/
showLogs(sender) {
if (!sender.verbose)
console.log("");
// process.stdout.write(sender.htmlOutput.HTMLObjects[0]);
if (sender.verbose) {
console.log("\n\n\x1b[0m\x1b[32mHTML OBJECTS: \x1b[0m\x1b[36m");
this.htmlOutput += `<div style="background-color: #222;padding: 8px;font-size:12px;"><BR><BR><h2>HTML OBJECTS: </h2>\n\n<div class="svcimg"><img src="scrnsht.png"></div>\n<BR><p style="margin-left:50px;">DoubleClick for src</p>\n`;
console.log("\x1b[0m\x1b[2m");
this.htmlOutput += `\n<ul style="color: #fff;" class="htmlo">\n`;
sender.htmlOutput.HTMLObjects.forEach( (item, index1) => {
item.itemObject.groups.forEach( (gitem, index2) => {
gitem.itemObject.items.forEach( (eitem, index3) => {
console.log(eitem.toString().substring(0, 40) + "...");
this.htmlOutput += `<li class="svc" ondblclick="$('#src${index1}_${index2}_${index3}').slideToggle()"><code>${eitem}</code></li>\n`;
this.htmlOutput += `<li class="src"><div class="srvs" id="src${index1}_${index2}_${index3}" ><code>${eitem.toString().replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<BR>').replace(/\t/g, ' ')}</code></div></li>\n`;
});
});
});
this.htmlOutput += `</ul>\n</div>\n`;
} else {
console.log("");
}
console.log("\x1b[0m");
console.log(new Date());
this.htmlOutput += `\n<div style="background-color: #222;font-size:12px;color:#777"><BR><BR>${new Date()}</div>\n`;
console.log("\n\x1b[2m\x1b[33m==================================================================================================================================================\n\x1b[0m");
}
/**
* logXSD
* @param xObject
*/
logXSD(xObject) {
console.log("\n\n\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
console.log(` \x1b[1m\x1b[36mFILE : ${xObject.xfile} \x1b[0m\n`);
console.log("\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");
this.htmlOutput += `<h2><span style="color:#777;background-color: #222;">XSD File:</span> ${xObject.xfile}</h2>\n`;
}
/**
* logHTML
* @param xObject
*/
logHTML(xObject) {
console.log("\n\n\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
console.log(` \x1b[1m\x1b[33mFILE : ${xObject.hfile} \x1b[0m\n`);
console.log("\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");
this.htmlOutput += `\n</div>\n<div id="htmlpanel" class="tabpanel" style="display:none;">\n<h2 style="background-color: #222;margin: 0;"><span style="color:#777;">XML File:</span> ${xObject.hfile}</h2>\n`;
}
/**
* showItemLog - ShowLog
* @param xsdItem
*/
showItemLog(xsdItem, verbose) {
let xspace = " ";
for (let i = 0; i < xsdItem.level; i++) {
xspace += "\t";
}
console.log(`${xspace}\x1b[0m\x1b[31m▓▓▓▓▓▓▓▓▓▓▓▓▓\x1b[0m`);
process.stdout.write(`${xspace}\x1b[2m▓▓▓▓ \x1b[0m\x1b[2mL:${xsdItem.level} \x1b[2m▓▓▓▓\x1b[0m\x1b[31m⇢\x1b[0m `);
this.htmlOutput += `<ul style="margin-left:${(xsdItem.level +1) * 150}px;" class="clvl" lvl="${xsdItem.level}"><div style="width:100px;padding:4px 8px;font-size:14px;color:#fff;background-color:#006699;font-weight:700;">Level ${xsdItem.level}</div>`;
if (xsdItem.children) {
process.stdout.write(`\x1b[1m${xsdItem.name}`);
this.htmlOutput += `<li class="xsdc" style="width:200px;color:#006699;background-color:#fff;">${xsdItem.name}\t<span>line ${xsdItem.line}</span></li>\n`;
if (xsdItem.attr.name) {
process.stdout.write(` - ${xsdItem.attr.name}`);
this.htmlOutput += `<li class="xsdc" style="border-radius:0;width:300px;font-size:13px;color:#cc0000;background-color:#fafafa;"><b>${xsdItem.attr.name}</b></li>\n`;
if (verbose) {
if (xsdItem.name === "xs:element") {
let txmlItem = xsdItem.toString();
txmlItem = txmlItem.split("\n").join("");
txmlItem = txmlItem.split("<").join(xspace + `\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m<`);
let pos1 = txmlItem.indexOf("<xs:documentation>");
if (pos1 > 0) {
let pos2 = txmlItem.indexOf("</xs:documentation>");
txmlItem = txmlItem.substring(0, pos1) + "<xs:documentation> ..." + txmlItem.substring(pos2);
}
process.stdout.write(`\x1b[2m${txmlItem}`);
}
}
} else if (xsdItem.attr.value) {
process.stdout.write(`\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m${xsdItem.attr.value}\x1b[0m`);
this.htmlOutput += `<li class="xsdc"style="border-radius:0;width:300px;font-size:11px;color:#333;background-color:#dcedf4;"><b>${xsdItem.attr.value}</b></li>\n`;
} else if (xsdItem.attr.ref) {
process.stdout.write(`\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m\x1b[36mRef: \x1b[1m\x1b[36m${xsdItem.attr.ref}\x1b[0m`);
this.htmlOutput += `<li class="xsdc"style="border-radius:0;width:300px;font-size:11px;color:#333;background-color:#dcedf4;">Ref: ${xsdItem.attr.ref}</li>\n`;
}
process.stdout.write(`\n\x1b[2m${xspace}▓▓▓▓▓▓▓▓▓▓▓▓▓`);
if (xsdItem.name === "xs:documentation" && xsdItem.xparent.name === "xs:annotation") {
let txmlItem = xsdItem.val.toString().trim();
if (txmlItem.length > 60)
txmlItem = txmlItem.substring(0, 60) + "...";
process.stdout.write(` \x1b[2m\x1b[37m ${txmlItem}\x1b[0m\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓`);
}
if (xsdItem.xparent) {
console.log(`\x1b[2m\x1b[32m parent ::\x1b[1m ${xsdItem.xparent.name}\x1b[0m`);
if (xsdItem.xparent.attr.name) {
console.log(`${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m\x1b[32m par.name ::\x1b[1m ${xsdItem.xparent.attr.name}\x1b[0m`);
}
}
}
if (xsdItem.level === 0)
console.log(" ");
this.htmlOutput += `</ul>`;
process.stdout.write(`\x1b[2m${xspace} ▒▒`);
}
/**
* logXsdTag - Log XSD Element Tag
* @param item
*/
logXsdTag(item) {
console.log(`\x1b[0m\x1b[31m⇣\x1b[2m Found Tag \x1b[33m${item}\x1b[0m`);
this.htmlOutput += `<div class="ftag"># ${item}</div>\n`;
}
/**
* logTODO - Log XSD Element Tag
* @param msg
*/
logTODO(msg) {
console.log(`\x1b[1m\x1b[31mTODO: \x1b[0m${msg}\x1b[0m`);
}
/**
* logHtmlTag - Log HTML Element Tag
* @param item
*/
logHtmlTag(item, sender) {
if (sender.verbose) {
console.log(`\x1b[0m\x1b[31m⇣\n\x1b[2mParsing HTML Tag ⇢ \x1b[33m${item.name}\x1b[0m\n`);
this.htmlOutput += `<div class="phtmlt"># <b>${item.name}</b> :: <b>${item.attr.element || item.attr.name || ' '}</b></div>\n`;
}
}
/**
* getHtmlLog
*/
getHtmlLog() {
return this.htmlOutput + `
</body>
</html> `;
}
}
module.exports = XSDWebFormParserLog; | Updated log
| src/lib/xsdwebform.parser.log.js | Updated log | <ide><path>rc/lib/xsdwebform.parser.log.js
<ide> margin-bottom: -4px;
<ide> }
<ide> .tbtn {
<add> text-align: center;
<ide> cursor: pointer;
<ide> width: 200px;
<ide> background-color: #999; |
|
Java | epl-1.0 | 34b12c65869d93531a25be57ae7c0b75b208e6a2 | 0 | jboss-reddeer/reddeer,jboss-reddeer/reddeer,djelinek/reddeer,djelinek/reddeer | /*******************************************************************************
* Copyright (c) 2016 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.reddeer.core.util;
import org.jboss.reddeer.common.logging.Logger;
import org.jboss.reddeer.core.interceptor.SyncInterceptorManager;
import org.jboss.reddeer.core.exception.CoreLayerException;
/**
* RedDeer display provider.
*
* @author Jiri Peterka
* @author Lucia Jelinkova
*/
public class Display {
private static final Logger log = Logger.getLogger(Display.class);
private static org.eclipse.swt.widgets.Display display;
private static SyncInterceptorManager sim = SyncInterceptorManager.getInstance();
private Display(){
super();
}
/**
* Returns {@link org.eclipse.swt.widgets.Display} instance.
*
* @return current Display instance or throws CoreLayerException if there is no display
*/
public static org.eclipse.swt.widgets.Display getDisplay() {
if ((display == null) || display.isDisposed()) {
display = null;
Thread[] allThreads = allThreads();
for (Thread thread : allThreads) {
org.eclipse.swt.widgets.Display d = org.eclipse.swt.widgets.Display.findDisplay(thread);
if (d != null && !d.isDisposed())
display = d;
}
if (display == null)
throw new CoreLayerException("Could not find a display");
}
return display;
}
/**
* Run sync in UI thread without returning any result.
*
* @param runnable runnable
*/
public static void syncExec(Runnable runnable) {
syncExec(new VoidResultRunnable(runnable));
}
/**
* Run sync in UI thread with ability to return result.
*
* @param <T> the generic type
* @param runnable runnable
* @return result of runnable
*/
@SuppressWarnings("unchecked")
public static <T> T syncExec(final ResultRunnable<T> runnable) {
if (!sim.isIntercepted()) {
sim.performBeforeSync();
}
ErrorHandlingRunnable<T> errorHandlingRunnable = new ErrorHandlingRunnable<T>(runnable);
if (!isUIThread()) {
Display.getDisplay().syncExec(errorHandlingRunnable);
} else {
if (runnable instanceof ErrorHandlingRunnable){
errorHandlingRunnable = (ErrorHandlingRunnable<T>) runnable;
}
errorHandlingRunnable.run();
}
if (errorHandlingRunnable.exceptionOccurred()){
throw new CoreLayerException("Exception during sync execution in UI thread", errorHandlingRunnable.getException());
}
if (!sim.isIntercepted()) {
sim.performAfterSync();
}
return errorHandlingRunnable.getResult();
}
/**
* Run async in UI thread without returning any result.
*
* @param runnable runnable
*/
public static void asyncExec(Runnable runnable) {
ErrorHandlingRunnable<Void> errorHandlingRunnable = new ErrorHandlingRunnable<Void>(new VoidResultRunnable(runnable));
getDisplay().asyncExec(errorHandlingRunnable);
if (errorHandlingRunnable.exceptionOccurred()){
throw new CoreLayerException("Exception during async execution in UI thread", errorHandlingRunnable.getException());
}
}
private static boolean isUIThread() {
return getDisplay().getThread() == Thread.currentThread();
}
private static Thread[] allThreads() {
ThreadGroup threadGroup = primaryThreadGroup();
Thread[] threads = new Thread[64];
int enumerate = threadGroup.enumerate(threads, true);
Thread[] result = new Thread[enumerate];
System.arraycopy(threads, 0, result, 0, enumerate);
return result;
}
private static ThreadGroup primaryThreadGroup() {
ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
while (threadGroup.getParent() != null)
threadGroup = threadGroup.getParent();
return threadGroup;
}
/**
* Decorator around the {@link ResultRunnable} classes. Its purpose is to catch any exception from UI thread and store
* it so it will be thrown in non UI thread.
*
* @author Lucia Jelinkova
*
* @param <T>
*/
private static class ErrorHandlingRunnable<T> implements Runnable {
private ResultRunnable<T> runnable;
private T result;
private Exception exception;
private ErrorHandlingRunnable(ResultRunnable<T> runnable) {
super();
this.runnable = runnable;
}
@Override
public void run() {
try {
result = runnable.run();
} catch (Exception e) {
exception = e;
}
}
public boolean exceptionOccurred(){
return getException() != null;
}
public Exception getException() {
return exception;
}
public T getResult() {
return result;
}
}
/**
* Wrapper class that converts {@link Runnable} to {@link ResultRunnable}
* @author Lucia Jelinkova
*
*/
private static class VoidResultRunnable implements ResultRunnable<Void> {
private Runnable runnable;
public VoidResultRunnable(Runnable runnable) {
this.runnable = runnable;
}
@Override
public Void run() {
runnable.run();
return null;
}
}
}
| plugins/org.jboss.reddeer.core/src/org/jboss/reddeer/core/util/Display.java | /*******************************************************************************
* Copyright (c) 2016 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.reddeer.core.util;
import org.jboss.reddeer.common.logging.Logger;
import org.jboss.reddeer.core.interceptor.SyncInterceptorManager;
import org.jboss.reddeer.core.exception.CoreLayerException;
/**
* RedDeer display provider.
*
* @author Jiri Peterka
* @author Lucia Jelinkova
*/
public class Display {
private static final Logger log = Logger.getLogger(Display.class);
private static org.eclipse.swt.widgets.Display display;
private static SyncInterceptorManager sim = SyncInterceptorManager.getInstance();
private static boolean firstAttempt = true;
private Display(){
super();
}
/**
* Returns {@link org.eclipse.swt.widgets.Display} instance.
*
* @return current Display instance or throws CoreLayerException if there is no display
*/
public static org.eclipse.swt.widgets.Display getDisplay() {
if ((display == null) || display.isDisposed()) {
display = null;
Thread[] allThreads = allThreads();
for (Thread thread : allThreads) {
org.eclipse.swt.widgets.Display d = org.eclipse.swt.widgets.Display.findDisplay(thread);
if (d != null && !d.isDisposed())
display = d;
}
if (display == null)
throw new CoreLayerException("Could not find a display");
}
return display;
}
/**
* Run sync in UI thread without returning any result.
*
* @param runnable runnable
*/
public static void syncExec(Runnable runnable) {
syncExec(new VoidResultRunnable(runnable));
}
/**
* Run sync in UI thread with ability to return result.
*
* @param <T> the generic type
* @param runnable runnable
* @return result of runnable
*/
@SuppressWarnings("unchecked")
public static <T> T syncExec(final ResultRunnable<T> runnable) {
if (!sim.isIntercepted()) {
sim.performBeforeSync();
}
ErrorHandlingRunnable<T> errorHandlingRunnable = new ErrorHandlingRunnable<T>(runnable);
if (!isUIThread()) {
firstAttempt = true;
Display.getDisplay().syncExec(errorHandlingRunnable);
} else {
if (firstAttempt) {
log.debug("UI Call chaining attempt");
firstAttempt = false;
}
if (runnable instanceof ErrorHandlingRunnable){
errorHandlingRunnable = (ErrorHandlingRunnable<T>) runnable;
}
errorHandlingRunnable.run();
}
if (errorHandlingRunnable.exceptionOccurred()){
throw new CoreLayerException("Exception during sync execution in UI thread", errorHandlingRunnable.getException());
}
if (!sim.isIntercepted()) {
sim.performAfterSync();
}
return errorHandlingRunnable.getResult();
}
/**
* Run async in UI thread without returning any result.
*
* @param runnable runnable
*/
public static void asyncExec(Runnable runnable) {
ErrorHandlingRunnable<Void> errorHandlingRunnable = new ErrorHandlingRunnable<Void>(new VoidResultRunnable(runnable));
getDisplay().asyncExec(errorHandlingRunnable);
if (errorHandlingRunnable.exceptionOccurred()){
throw new CoreLayerException("Exception during async execution in UI thread", errorHandlingRunnable.getException());
}
}
private static boolean isUIThread() {
return getDisplay().getThread() == Thread.currentThread();
}
private static Thread[] allThreads() {
ThreadGroup threadGroup = primaryThreadGroup();
Thread[] threads = new Thread[64];
int enumerate = threadGroup.enumerate(threads, true);
Thread[] result = new Thread[enumerate];
System.arraycopy(threads, 0, result, 0, enumerate);
return result;
}
private static ThreadGroup primaryThreadGroup() {
ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
while (threadGroup.getParent() != null)
threadGroup = threadGroup.getParent();
return threadGroup;
}
/**
* Decorator around the {@link ResultRunnable} classes. Its purpose is to catch any exception from UI thread and store
* it so it will be thrown in non UI thread.
*
* @author Lucia Jelinkova
*
* @param <T>
*/
private static class ErrorHandlingRunnable<T> implements Runnable {
private ResultRunnable<T> runnable;
private T result;
private Exception exception;
private ErrorHandlingRunnable(ResultRunnable<T> runnable) {
super();
this.runnable = runnable;
}
@Override
public void run() {
try {
result = runnable.run();
} catch (Exception e) {
exception = e;
}
}
public boolean exceptionOccurred(){
return getException() != null;
}
public Exception getException() {
return exception;
}
public T getResult() {
return result;
}
}
/**
* Wrapper class that converts {@link Runnable} to {@link ResultRunnable}
* @author Lucia Jelinkova
*
*/
private static class VoidResultRunnable implements ResultRunnable<Void> {
private Runnable runnable;
public VoidResultRunnable(Runnable runnable) {
this.runnable = runnable;
}
@Override
public Void run() {
runnable.run();
return null;
}
}
}
| Remove UI call chaining attept log message. Fixes #1498
| plugins/org.jboss.reddeer.core/src/org/jboss/reddeer/core/util/Display.java | Remove UI call chaining attept log message. Fixes #1498 | <ide><path>lugins/org.jboss.reddeer.core/src/org/jboss/reddeer/core/util/Display.java
<ide> private static org.eclipse.swt.widgets.Display display;
<ide> private static SyncInterceptorManager sim = SyncInterceptorManager.getInstance();
<ide>
<del> private static boolean firstAttempt = true;
<del>
<ide> private Display(){
<ide> super();
<ide> }
<ide> ErrorHandlingRunnable<T> errorHandlingRunnable = new ErrorHandlingRunnable<T>(runnable);
<ide>
<ide> if (!isUIThread()) {
<del> firstAttempt = true;
<ide> Display.getDisplay().syncExec(errorHandlingRunnable);
<ide> } else {
<del> if (firstAttempt) {
<del> log.debug("UI Call chaining attempt");
<del> firstAttempt = false;
<del> }
<ide> if (runnable instanceof ErrorHandlingRunnable){
<ide> errorHandlingRunnable = (ErrorHandlingRunnable<T>) runnable;
<ide> } |
|
JavaScript | mit | c992c3110f1fb17cf8d78e4251758eff58ae8c55 | 0 | johncipponeri/substitute-news | var substitutions = [
"witnesses", "these dudes I know",
"allegedly", "kinda probably",
"new study", "tumblr post",
"rebuild", "avenge",
"space", "spaaace",
"google glass", "virtual boy",
"smartphone", "pokedex",
"electric", "atomic",
"senator", "elf-lord",
"car", "cat",
"election", "eating contest",
"congressional leaders", "river spirits",
"homeland security", "homestar runner",
"could not be reached for comment", "is guilty and everyone knows it"
];
var lines = document.body.textContent.split('\n');
for(var l = 0; l < lines.length; l += 1) {
var words = lines[l].split(/\s+/);
for(var w = 0; w < words.length; w += 1) {
for(var s = 0; s < substitutions.length; s += 2) {
words[w] = words[w].toLowerCase().replace(new RegExp(substitutions[s], 'g'), substitutions[s + 1]);
}
} lines[l] = words.join(" ");
}
document.body.textContent = lines.join('\n'); | src/script.js | var substitutions = [
"witnesses", "these dudes I know",
"allegedly", "kinda probably",
"new study", "tumblr post",
"rebuild", "avenge",
"space", "spaaace",
"google glass", "virtual boy",
"smartphone", "pokedex",
"electric", "atomic",
"senator", "elf-lord",
"car", "cat",
"election", "eating contest",
"congressional leaders", "river spirits",
"homeland security", "homestar runner",
"could not be reached for comment", "is guilty and everyone knows it"
];
var lines = document.body.innerHTML.split('\n');
for(var l = 0; l < lines.length; l += 1) {
for(var s = 0; s < substitutions.length; s += 2) {
lines[l] = lines[l].toLowerCase().replace(new RegExp(substitutions[s], 'g'), substitutions[s + 1]);
}
}
document.body.innerHTML = lines.join('\n'); | - Corrected in-word substitutions
- Replaced innerHTML with textContent
- Now loops through individual words per line
| src/script.js | - Corrected in-word substitutions - Replaced innerHTML with textContent - Now loops through individual words per line | <ide><path>rc/script.js
<ide> "could not be reached for comment", "is guilty and everyone knows it"
<ide> ];
<ide>
<del>var lines = document.body.innerHTML.split('\n');
<add>var lines = document.body.textContent.split('\n');
<ide>
<ide> for(var l = 0; l < lines.length; l += 1) {
<del> for(var s = 0; s < substitutions.length; s += 2) {
<del> lines[l] = lines[l].toLowerCase().replace(new RegExp(substitutions[s], 'g'), substitutions[s + 1]);
<del> }
<add> var words = lines[l].split(/\s+/);
<add>
<add> for(var w = 0; w < words.length; w += 1) {
<add> for(var s = 0; s < substitutions.length; s += 2) {
<add> words[w] = words[w].toLowerCase().replace(new RegExp(substitutions[s], 'g'), substitutions[s + 1]);
<add> }
<add> } lines[l] = words.join(" ");
<ide> }
<ide>
<del>document.body.innerHTML = lines.join('\n');
<add>document.body.textContent = lines.join('\n'); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.