text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using SharpKit.JavaScript;
using UnityEngine;
using Object = UnityEngine.Object;

public class JSDataExchangeMgr
{
    #region Delegates

    public delegate T DGetV<T>();

    #endregion

    public enum eGetType
    {
        GetARGV,
        GetARGVRefOut,
        GetJSFUNRET,
        Jsval
    }

    public enum eSetType
    {
        SetRval,
        UpdateARGVRefOut,
        Jsval
        //GetJSFUNRET
    }

    private static readonly Dictionary<string, Type> typeCache = new Dictionary<string, Type>();

    public static Type GetTypeByJsParam(int e)
    {
        string typeFullName = JSApi.getStringS(e);
        return GetTypeByName(typeFullName);
    }

    public static Type GetTypeByName(string typeName, Type defaultType = null)
    {
        if (string.IsNullOrEmpty(typeName))
            return null;

        Type t = null;
        if (!typeCache.TryGetValue(typeName, out t))
        {
            t = Type.GetType(typeName);
            if (t == null)
            {
                foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    t = a.GetType(typeName);
                    if (t != null)
                        break;
                }
            }

            //忽略带JsType属性的类型
            if (t != null)
            {
                string fullName = t.FullName;
                if (JSCache.IsJsComTypeName(fullName))
                {
                    t = typeof (JSComponent);
                }
                else if (t.IsDefined(typeof(JsTypeAttribute), false) || JSCache.IsJsTypeName(t.FullName))
                {
                    t = null;
                }
            }

            typeCache[typeName] = t; // perhaps null
            //if (t == null)
            //{
            //    Debug.LogError("GetType of \"" + typeName + "\" is null. Did you export that class to JavaScript?");
            //}
        }
        if (t == null)
        {
            return defaultType; // typeof(CSRepresentedObject);
        }
        return t;
    }

    /*
    // Runtime Only
    // type: class type
    // methodName: method name
    // TCount: generic parameter count
    // vc: JSVCall instance
    public static MethodInfo MakeGenericConstructor(Type type, int TCount, int paramCount, JSVCall vc)
    {
        // Get generic method by name and param count.
        ConstructorInfo conT = JSDataExchangeMgr.GetGenericConstructorInfo(type, TCount, paramCount);
        if (conT == null)
        {
            return null;
        }

        // get T types
        Type[] genericTypes = new Type[TCount];
        for (int i = 0; i < TCount; i++)
        {
            // Get generic types from js.
            System.Type t = JSDataExchangeMgr.GetTypeByName(JSMgr.datax.getString(JSDataExchangeMgr.eGetType.GetARGV));
            genericTypes[i] = t;
            if (t == null)
            {
                return null;
            }
        }

        // Make generic method.
        MethodInfo method = methodT.MakeGenericMethod(genericTypes);
        return method;
    }
    // Runtime Only
    // called by MakeGenericConstructor
    // get generic Constructor by matching TCount,paramCount, if more than 1 match, return null.
    static ConstructorInfo GetGenericConstructorInfo(Type type, int TCount, int paramCount)
    {
        ConstructorInfo[] constructors = type.GetConstructors();
        if (constructors == null || constructors.Length == 0)
        {
            return null;
        }

        ConstructorInfo con = null;
        for (int i = 0; i < constructors.Length; i++)
        {
            if (constructors[i].IsGenericMethodDefinition &&
                constructors[i].GetGenericArguments().Length == TCount &&
                constructors[i].GetParameters().Length == paramCount)
            {
                if (con == null)
                    con = constructors[i];
                else
                {
                    Debug.LogError("More than 1 Generic Constructor found!!! " + GetTypeFullName(type) + "." + name);
                    return null;
                }
            }
        }
        if (con == null)
        {
            Debug.LogError("No generic constructor found! " + GetTypeFullName(type));
        }
        return con;
    }*/

    public static ConstructorInfo makeGenericConstructor(Type type, ConstructorID constructorID)
    {
        int tCount = type.GetGenericArguments().Length;
        var genericTypes = new Type[tCount];
        for (int i = 0; i < tCount; i++)
        {
            string typeName = JSApi.getStringS((int) JSApi.GetType.Arg);
            var t = GetTypeByName(typeName, typeof (CSRepresentedObject));
            genericTypes[i] = t;
            if (t == null)
            {
                return null;
            }
        }

        var exactType = type.MakeGenericType(genericTypes);
        var exactConstructor = GenericTypeCache.getConstructor(exactType, constructorID);
        return exactConstructor;
    }

    /// <summary>
    ///     Makes the generic method.
    ///     not run in Editor mode, only runtime.
    /// </summary>
    /// <param name="type">The type.</param>
    /// <param name="methodID">The method identifier.</param>
    /// <param name="TCount">The t count.</param>
    /// <returns></returns>
    public static MethodInfo makeGenericMethod(Type type, MethodID methodID, int TCount)
    {
        var methodT = GenericTypeCache.getMethod(type, methodID);
        if (methodT == null)
        {
            return null;
        }

        var genericTypes = new Type[TCount];
        for (int i = 0; i < TCount; i++)
        {
            string typeName = JSApi.getStringS((int) JSApi.GetType.Arg);
            var t = GetTypeByName(typeName, typeof (CSRepresentedObject));
            genericTypes[i] = GetGenericTypeBaseType(t);
            if (t == null)
            {
                return null;
            }
        }

        var method = methodT.MakeGenericMethod(genericTypes);
        return method;
    }

    /// <summary>
    ///     递归遍历获取带泛型参数类型的基类,例如:TweenerCore<T1, T2, TPlugOptions>,返回Tweener
    /// </summary>
    /// <returns>The generic type base type.</returns>
    /// <param name="type">Type.</param>
    public static Type GetGenericTypeBaseType(Type type)
    {
        if (!type.ContainsGenericParameters)
            return type;

        var baseType = type.BaseType;
        if (baseType == null)
        {
            return typeof (object);
        }

        return GetGenericTypeBaseType(baseType);
    }

    //
    //
    //
    public static Type[] RecursivelyGetGenericParameters(Type type, List<Type> lst = null)
    {
        if (lst == null)
            lst = new List<Type>();

        if (type.ContainsGenericParameters)
        {
            if (type.IsGenericParameter)
            {
                lst.Add(type);
            }
            else if (type.HasElementType)
            {
                RecursivelyGetGenericParameters(type.GetElementType(), lst);
            }
            else if (type.IsGenericType)
            {
                var genericArguments = type.GetGenericArguments();
                for (int i = 0; i < genericArguments.Length; i++)
                {
                    RecursivelyGetGenericParameters(genericArguments[i], lst);
                }
            }
        }
        return lst.ToArray();
    }

    public static T GetJSArg<T>(DGetV<T> del)
    {
        return del();
    }

    #region Get Operation

    public object getObject(int e)
    {
        int jsObjID = JSApi.getObject(e);
        if (jsObjID == 0)
        {
            // no error
            return null;
        }

        var csObj = JSMgr.getCSObj(jsObjID);
        if (csObj == null)
        {
            csObj = new CSRepresentedObject(jsObjID);
        }
        return csObj;
    }

    /// <summary>
    ///     Gets object by type.
    ///     for concrete type e.g. setInt32 setString, they know how to return object
    ///     but for T parameters, type is unknown until runtime
    ///     so this function needs a 'Type' argument
    ///     which is passed through mTempObj
    /// </summary>
    /// <param name="eType">Type of the e.</param>
    /// <returns></returns>
    public object getByType(JSApi.GetType eType)
    {
        int e = (int) eType;
        Type type = null;
        if (type.IsByRef)
            type = type.GetElementType();

        if (type == typeof (string))
            return JSApi.getStringS(e);
        if (type.IsEnum)
            return JSApi.getEnum(e);
        if (type.IsPrimitive)
        {
            if (type == typeof (bool))
                return JSApi.getBooleanS(e);
            if (type == typeof (char))
                return JSApi.getChar(e);
            if (type == typeof (byte))
                return JSApi.getByte(e);
            if (type == typeof (sbyte))
                return JSApi.getSByte(e);
            if (type == typeof (ushort))
                return JSApi.getUInt16(e);
            if (type == typeof (short))
                return JSApi.getInt16(e);
            if (type == typeof (uint))
                return JSApi.getUInt32(e);
            if (type == typeof (int))
                return JSApi.getInt32(e);
            if (type == typeof (ulong))
                return JSApi.getUInt64(e);
            if (type == typeof (long))
                return JSApi.getInt64(e);
            if (type == typeof (float))
                return JSApi.getSingle(e);
            if (type == typeof (double))
                return JSApi.getDouble(e);
            if (type == typeof (IntPtr))
                return JSApi.getIntPtr(e);
            Debug.LogError("Unknown primitive type" + type.Name);
        }
        else if (type == typeof (Vector2))
        {
            return JSApi.getVector2S(e);
        }
        else if (type == typeof (Vector3))
        {
            return JSApi.getVector3S(e);
        }
        else
        {
            return JSApi.getObject(e);
        }
        return null;
    }

    public object getWhatever(int e)
    {
        uint tag = JSApi.getTag(e);
        if (JSApi.jsval.isNullOrUndefined(tag))
            return null;
        if (JSApi.jsval.isBoolean(tag))
            return JSApi.getBooleanS(e);
        if (JSApi.jsval.isInt32(tag))
            return JSApi.getInt32(e);
        if (JSApi.jsval.isDouble(tag))
            return JSApi.getSingle(e);
        if (JSApi.jsval.isString(tag))
            return JSApi.getStringS(e);
        if (JSApi.jsval.isObject(tag))
        {
            if (JSApi.isVector2S(e))
            {
                return JSApi.getVector2S(e);
            }
            if (JSApi.isVector3S(e))
            {
                return JSApi.getVector3S(e);
            }
            return getObject(e);
        }
        return null;
    }

    public object getDelegate(eGetType e)
    {
        switch (e)
        {
            case eGetType.GetARGV:
            {
                // TODO check: index must ++
                int jsObjID = JSApi.getObject((int) JSApi.GetType.Arg);
                if (jsObjID == 0)
                    return null;

                var csObj = JSMgr.getCSObj(jsObjID);
                return csObj;

//                     IntPtr jsObj = JSApi.JSh_ArgvObject(JSMgr.cx, vc.vp, vc.currIndex++);
//                     if (jsObj == IntPtr.Zero)
//                         return null;
//
//                     object csObj = JSMgr.getCSObj(jsObj);
//                     return csObj;
            }
            // break; !!
//             case eGetType.GetARGVRefOut:
//                 {
//                     jsval val = new jsval();
//                     JSApi.JSh_SetJsvalUndefined(ref val);
//                     getJSValueOfParam(ref val, vc.currIndex++);
//
//                     IntPtr jsObj = JSApi.JSh_GetJsvalObject(ref val);
//                     if (jsObj == IntPtr.Zero)
//                         return null;
//
//                     JSApi.JSh_GetUCProperty(JSMgr.cx, jsObj, "__nativeObj", -1, ref val);
//                     IntPtr __nativeObj = JSApi.JSh_GetJsvalObject(ref val);
//                     if (__nativeObj == IntPtr.Zero)
//                         return null;
//
//                     object csObj = JSMgr.getCSObj(__nativeObj);
//                     return csObj;
//                 }
//                 break;
//             case eGetType.Jsval:
//                 {
//                     jsval val = new jsval();
//                     JSApi.JSh_SetJsvalUndefined(ref val);
//
//                     IntPtr jsObj = JSApi.JSh_GetJsvalObject(ref vc.valTemp);
//                     if (jsObj == IntPtr.Zero)
//                         return null;
//
//                     object csObj = JSMgr.getCSObj(jsObj);
//                     return csObj;
//                 }
//                 break;
            default:
                Debug.LogError("Not Supported");
                break;
        }
        return null;
    }

    #endregion

    #region Set Operation

    // for generic type
    // type is assigned during runtime
    public void setWhatever(int e, object obj)
    {
//         Type type = (Type)mTempObj;
//         if (type.IsByRef)
//             type = type.GetElementType();

        // ?? TODO use mTempObj or not?

        // TODO check
        if (obj == null)
        {
            JSApi.setUndefined(e);
            return;
        }

        if (obj is Object)
        {
            if (obj.Equals(null))
            {
                JSApi.setUndefined(e);
                return;
            }
        }

        var type = obj.GetType();

        if (type == typeof (string))
            JSApi.setStringS(e, (string) obj);
        else if (type.IsEnum)
            JSApi.setEnum(e, (int) obj);
        else if (type.IsPrimitive)
        {
            if (type == typeof (bool))
                JSApi.setBooleanS(e, (bool) obj);
            else if (type == typeof (char))
                JSApi.setChar(e, (char) obj);
            else if (type == typeof (byte))
                JSApi.setByte(e, (byte) obj);
            else if (type == typeof (sbyte))
                JSApi.setSByte(e, (sbyte) obj);
            else if (type == typeof (ushort))
                JSApi.setUInt16(e, (ushort) obj);
            else if (type == typeof (short))
                JSApi.setInt16(e, (short) obj);
            else if (type == typeof (uint))
                JSApi.setUInt32(e, (uint) obj);
            else if (type == typeof (int))
                JSApi.setInt32(e, (int) obj);
            else if (type == typeof (ulong))
                JSApi.setUInt64(e, (ulong) obj);
            else if (type == typeof (long))
                JSApi.setInt64(e, (long) obj);
            else if (type == typeof (float))
                JSApi.setSingle(e, (float) obj);
            else if (type == typeof (double))
                JSApi.setDouble(e, (double) obj);
            else
                Debug.LogError("Unknown primitive type");
        }
        else if (type == typeof (Vector3))
        {
            JSApi.setVector3S(e, (Vector3) obj);
        }
        else if (type == typeof (Vector2))
        {
            JSApi.setVector2S(e, (Vector2) obj);
        }
        else
        {
            setObject(e, obj);
        }
    }

    /// <summary>
    ///     Should return base type object?
    /// </summary>
    /// <param name="typeName">Name of the type.</param>
    /// <returns></returns>
    /// <summary>
    ///     Sets the object.
    ///     if e == UpdateRefARGV, currIndex must be set before this function
    ///     operation of this function:
    ///     1) if JavaScript already exists, return that JavaScript object.
    ///     2) else, create a new JavaScript object and return it.
    /// </summary>
    /// <param name="e">The e.</param>
    /// <param name="csObj">The cs object.</param>
    /// <returns></returns>
    public int setObject( /* JSApi.SetType */ int e, object csObj)
    {
        // http://answers.unity3d.com/questions/1087158/unityengineobject-is-null-but-systemobject-is-not.html
        if (csObj != null && csObj is Object)
        {
            if (csObj.Equals(null))
                csObj = null;
        }

        int jsObjID = 0;
        if (csObj != null)
        {
            var csType = csObj.GetType();
            var typeInfo = JSCache.GetTypeInfo(csType);

            if (typeInfo.IsClass)
            {
                jsObjID = JSMgr.getJSObj(csObj, typeInfo);
            }
            if (jsObjID == 0)
            {
                if (csObj is CSRepresentedObject)
                {
                    jsObjID = ((CSRepresentedObject) csObj).jsObjID;
                }
                else if (csObj is IEnumerator)
                {
                    //如果是实现IEnumerator接口的类型,直接创建IEnumerator对应的js对象
                    string typeName = "System.Collections.IEnumerator";
                    jsObjID = JSApi.createJSClassObject(typeName);
                    if (jsObjID != 0)
                        JSMgr.addJSCSRel(jsObjID, csObj);
                    else
                        Debug.LogError("Return a \"" + typeName +
                                       "\" to JS failed. Did you forget to export that class?");
                }
                else
                {
                    if (typeInfo.IsDelegate)
                    {
                        jsObjID = JSMgr.getFunIDByDelegate((Delegate) csObj);
                    }
                    if (jsObjID == 0)
                    {
                        string typeName = string.Empty;
                        // create a JSRepresentedObject object in JS to represent a C# delegate object
                        if (typeInfo.IsDelegate)
                        {
                            typeName = "JSRepresentedObject";
                            jsObjID = JSApi.createJSClassObject(typeName);
                        }
                        else
                        {
                            typeName = typeInfo.JSTypeFullName;
                            jsObjID = JSApi.createJSClassObject(typeName);
                            if (jsObjID == 0)
                            {
                                var baseType = csType.BaseType;
                                var baseTypeInfo = JSCache.GetTypeInfo(baseType);
                                if (baseType != null)
                                {
                                    string baseTypeName = baseTypeInfo.JSTypeFullName;
                                    jsObjID = JSApi.createJSClassObject(baseTypeName);
                                    if (jsObjID != 0)
                                    {
                                        Debug.LogWarning("WARNING: Return a \"" + typeName +
                                                         "\" to JS failed. Return base type\"" + baseTypeName +
                                                         "\" instead.");
                                    }
                                }
                            }
                        }

                        if (jsObjID != 0)
                            JSMgr.addJSCSRel(jsObjID, csObj);
                        else
                            Debug.LogError("Return a \"" + typeName +
                                           "\" to JS failed. Did you forget to export that class?");
                    }
                }
            }
        }

        JSApi.setObject(e, jsObjID);
        return jsObjID;
    }

    // TODO what?
//     public void setDelegate(eSetType e, object csObj)
//     {
//         switch (e)
//         {
//             case eSetType.Jsval:
//             case eSetType.SetRval:
//                 {
//                     JSApi.JSh_SetJsvalUndefined(ref vc.valReturn);
//                     if (csObj != null)
//                     {
//                         IntPtr jsObj = IntPtr.Zero;
//                         Type csType = csObj.GetType();
//                         if (csType.IsClass && (jsObj = JSMgr.getJSObj(csObj)) != IntPtr.Zero)
//                         {
//                             JSApi.JSh_SetJsvalObject(ref vc.valReturn, jsObj);
//                         }
//                         else
//                         {
//                             string typeName = JSNameMgr.GetJSTypeFullName(csType);
//                             IntPtr jstypeObj = JSDataExchangeMgr.GetJSObjectByname(typeName);
//                             if (jstypeObj != IntPtr.Zero)
//                             {
//                                 jsObj = JSApi.JSh_NewObjectAsClass(JSMgr.cx, jstypeObj, "ctor", null /*JSMgr.mjsFinalizer*/);
//
//                                 // __nativeObj
//                                 IntPtr __nativeObj = JSApi.JSh_NewMyClass(JSMgr.cx, JSMgr.mjsFinalizer);
//                                 JSMgr.addJSCSRelation(jsObj, __nativeObj, csObj);
//
//                                 // jsObj.__nativeObj = __nativeObj
//                                 jsval val = new jsval();
//                                 JSApi.JSh_SetJsvalObject(ref val, __nativeObj);
//                                 JSApi.JSh_SetUCProperty(JSMgr.cx, jsObj, "__nativeObj", -1, ref val);
//
//                                 JSApi.JSh_SetJsvalObject(ref vc.valReturn, jsObj);
//                             }
//                             else
//                             {
//                                 Debug.LogError("Return a \"" + typeName + "\" to JS failed. Did you forget to export that class?");
//                             }
//                         }
//                     }
//
//                     if (e == eSetType.Jsval)
//                         vc.valTemp = vc.valReturn;
//                     else if (e == eSetType.SetRval)
//                         JSApi.JSh_SetRvalJSVAL(JSMgr.cx, vc.vp, ref vc.valReturn);
//                 }
//                 break;
//             case eSetType.UpdateARGVRefOut:
//                 {
//                     jsval val = new jsval(); val.asBits = 0;
//                     IntPtr argvJSObj = JSApi.JSh_ArgvObject(JSMgr.cx, vc.vp, vc.currIndex);
//                     if (argvJSObj != IntPtr.Zero)
//                     {
//                         bool success = false;
//
//                         IntPtr jsObj = IntPtr.Zero;
//                         Type csType = csObj.GetType();
//                         if (csType.IsClass && (jsObj = JSMgr.getJSObj(csObj)) != IntPtr.Zero)
//                         {
//                             // 3)
//                             // argvObj.Value = jsObj
//                             //
//                             JSApi.JSh_SetJsvalObject(ref val, jsObj);
//                             JSApi.JSh_SetUCProperty(JSMgr.cx, argvJSObj, "Value", -1, ref val);
//                             success = true;
//                         }
//                         else
//                         {
//                             // csObj must not be null
//                             IntPtr jstypeObj = JSDataExchangeMgr.GetJSObjectByname(JSNameMgr.GetTypeFullName(csObj.GetType()));
//                             if (jstypeObj != IntPtr.Zero)
//                             {
//                                 // 1)
//                                 // jsObj: prototype
//                                 // __nativeObj: csObj + finalizer
//                                 //
//                                 jsObj = JSApi.JSh_NewObjectAsClass(JSMgr.cx, jstypeObj, "ctor", null /*JSMgr.mjsFinalizer*/);
//                                 // __nativeObj
//                                 IntPtr __nativeObj = JSApi.JSh_NewMyClass(JSMgr.cx, JSMgr.mjsFinalizer);
//                                 JSMgr.addJSCSRelation(jsObj, __nativeObj, csObj);
//
//                                 //
//                                 // 2)
//                                 // jsObj.__nativeObj = __nativeObj
//                                 //
//                                 JSApi.JSh_SetJsvalObject(ref val, __nativeObj);
//                                 JSApi.JSh_SetUCProperty(JSMgr.cx, jsObj, "__nativeObj", -1, ref val);
//
//                                 // 3)
//                                 // argvObj.Value = jsObj
//                                 //
//                                 JSApi.JSh_SetJsvalObject(ref val, jsObj);
//                                 JSApi.JSh_SetUCProperty(JSMgr.cx, argvJSObj, "Value", -1, ref val);
//                                 success = true;
//                             }
//                             else
//                             {
//                                 Debug.LogError("Return a \"" + JSNameMgr.GetTypeFullName(csObj.GetType()) + "\" to JS failed. Did you forget to export that class?");
//                             }
//                         }
//
//                         if (!success)
//                         {
//                             JSApi.JSh_SetJsvalUndefined(ref val);
//                             JSApi.JSh_SetUCProperty(JSMgr.cx, argvJSObj, "Value", -1, ref val);
//                         }
//                     }
//                 }
//                 break;
//             default:
//                 Debug.LogError("Not Supported");
//                 break;
//         }
//     }

    #endregion
}

/// <summary>
///     CSRepresentedObject
///     if we have a JavaScript Message, like this:
///     var Message =
///     {
///     id: 4,
///     str: "hello, world"
///     }
///     when it comes to C#, (e.g. store in a C# version List<>), there is no C# type matching it
///     so we make a CSRepresentedObject to wrap it
/// </summary>
public class CSRepresentedObject
{
    public static int s_objCount;
    public static int s_funCount;
    private readonly int jsEngineRound;
    public bool bFunction;

    public int jsObjID;

//     public static bool operator !=(CSRepresentedObject x, CSRepresentedObject y)
//     {
//         return !(x == y);
//     }
//     public static bool operator ==(CSRepresentedObject x, CSRepresentedObject y)
//     {
//         // If both are null, or both are same instance, return true.
//         if (System.Object.ReferenceEquals(x, y))
//         {
//             return true;
//         }
//         return x.jsObjID == y.jsObjID;
//     }
//     public override bool Equals(object obj)
//     {
//         // If parameter is null return false.
//         if (obj == null)
//         {
//             return false;
//         }
//
//         // If parameter cannot be cast to Point return false.
//         CSRepresentedObject p = obj as CSRepresentedObject;
//         if ((System.Object)p == null)
//         {
//             return false;
//         }
//         return this.jsObjID == p.jsObjID;
//     }

    // don't create this object directly, should use JSDataExchangeMgr.getObject
    public CSRepresentedObject(int jsObjID, bool bFunction = false)
    {
        jsEngineRound = JSMgr.jsEngineRound;
        this.jsObjID = jsObjID;
        this.bFunction = bFunction;
        JSMgr.addJSCSRel(jsObjID, this, true);

        if (bFunction)
            s_funCount++;
        else
            s_objCount++;

        // !
        // inc 之后 refCount 可能 > 1
        // getCSObj 可能检查 WeakReference.Target == null,表明 ~CSRepresentedObject 未被调用
        // 此时我们继续创建另一个 CSRepresentedObject 对象
        // 那么 refCount 就会 > 1

        //int refCount =
        JSApi.incRefCount(jsObjID);
        //Debug.Log(new StringBuilder().AppendFormat("+ CSRepresentedObject {0} Ref[{1}] Fun[{1}]", jsObjID, refCount, bFunction ? 1 : 0));
    }

    ~CSRepresentedObject()
    {
        if (JSMgr.IsShutDown)
            return;

        var action = CreateDestructAction(bFunction, jsObjID, jsEngineRound);
        JSEngine.inst.DoThreadSafeAction(action);

        //Debug.Log(new StringBuilder().AppendFormat("- CSRepresentedObject {0} Ref[{1}] Fun[{1}]", jsObjID, refCount, bFunction ? 1 : 0));
    }

    private Action CreateDestructAction(bool bFunction, int jsObjID, int round)
    {
        return () =>
        {
            if (bFunction)
                s_funCount--;
            else
                s_objCount--;

            int refCount = JSApi.decRefCount(jsObjID);
            if (refCount <= 0)
            {
                JSMgr.removeJSCSRel(jsObjID, round);
                if (bFunction)
                {
                    JSMgr.removeJSFunCSDelegateRel(jsObjID);
                }
            }
            //else
            //{
            //    Debug.LogError(";;;//IIL.x&");
            //}
        };
    }
}


text:
package org.wso2.carbon.identity.user.rename.core.internal.service.impl;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.user.rename.core.exception.UsernameUpdateException;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * The class which executes the forget me tool script with needed arguments.
 * <p>
 * The applicable script file (.sh or .bat) is picked based on the OS and run as a separate process.
 */
public class ForgetMeToolExecutor {

    private final static Log log = LogFactory.getLog(ForgetMeToolExecutor.class);

    private static final String SYSTEM_PROPERTY_CARBON_HOME = "carbon.home";
    private static final String FORGETME_TOOL_HOME = "repository/components/tools/forget-me";
    private static final String SCRIPT_NAME_BASH = "forgetme.sh";
    private static final String SCRIPT_NAME_WINDOWS = "forgetme.bat";
    private static final String SYSTEM_PROPERTY_OS_NAME = "os.name";
    private static final String USER_STORE_EXTENSION_CONF_RELATIVE_PATH = "extensions/user-store/conf";

    /**
     * Executes ForgetMeTool to update the existing username of the user.
     *
     * @param existingUsername existing username of the user
     * @param newUsername new username of the user
     * @param userStoreDomain user store domain of the user
     * @param tenantDomain tenant domain of the user
     * @param tenantId tenant id
     * @throws UsernameUpdateException
     */
    public static void run(String existingUsername, String newUsername, String userStoreDomain, String tenantDomain,
                           int tenantId) throws UsernameUpdateException {

        int status = new ForgetMeToolExecutor().execute(existingUsername, newUsername, userStoreDomain, tenantDomain,
                tenantId);
        if (status != 0) {
            throw new UsernameUpdateException("Error while updating the username from : " + existingUsername + " to: " +
                    newUsername + " of user in userstore domain: " + userStoreDomain + " and tenant domain: " +
                    tenantDomain + ". Refer logs at " + Paths.get(System.getProperty(SYSTEM_PROPERTY_CARBON_HOME))
                    .resolve(Paths.get(FORGETME_TOOL_HOME)).resolve(Paths.get
                            (USER_STORE_EXTENSION_CONF_RELATIVE_PATH)).toString() + " for more information");
        }
    }

    private int execute(String existingUsername, String newUsername, String userStoreDomain, String tenantDomain,
                        int tenantId) throws UsernameUpdateException {

        String scriptName = getScriptForOS();

        if (scriptName == null) {
            throw new UsernameUpdateException(String.format("The operating system '%s' doesn't support the forget-me tool script.",
                    System.getProperty(SYSTEM_PROPERTY_OS_NAME)));
        }

        String scriptPath = Paths.get(System.getProperty(SYSTEM_PROPERTY_CARBON_HOME)).resolve(Paths.get
                (FORGETME_TOOL_HOME, "bin", scriptName)).toString();
        if (log.isDebugEnabled()) {
            log.debug("Resolved forget-me tool script path to: " + scriptPath);
        }

        String arguments = buildForgetMeToolArguments(existingUsername, newUsername, userStoreDomain, tenantDomain, tenantId);
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(scriptPath + " " + arguments);
            if (log.isInfoEnabled()) {
                log.info(IOUtils.toString(process.getInputStream()));
            }
            process.waitFor();
            return process.exitValue();
        } catch (IOException | InterruptedException e) {
            throw new UsernameUpdateException("Error while executing username update process for user: " +
                    existingUsername + " in tenant: " + tenantDomain, e);
        }
    }

    private String getScriptForOS() {

        String osName = System.getProperty(SYSTEM_PROPERTY_OS_NAME);
        String scriptName = null;

        if (isUnixOS(osName) || isMacOS(osName)) {
            scriptName = SCRIPT_NAME_BASH;
        } else if (isWindowsOS(osName)) {
            scriptName = SCRIPT_NAME_WINDOWS;
        }

        return scriptName;
    }

    private boolean isWindowsOS(String osName) {

        return osName.toUpperCase().indexOf("WIN") >= 0;
    }

    private boolean isUnixOS(String osName) {

        return (osName.toUpperCase().indexOf("NIX") >= 0 ||
                osName.toUpperCase().indexOf("NUX") >= 0 ||
                osName.toUpperCase().indexOf("AIX") > 0);

    }

    private boolean isMacOS(String osName) {

        return (osName.toUpperCase().indexOf("MAC") >= 0);
    }

    private String buildForgetMeToolArguments(String existingUsername, String newUsername, String userStoreDomain,
                                              String tenantDomain, int tenantId) {

        List<String> args = new ArrayList<>();

        args.add("-d");
        String configDirectoryPath = Paths.get(System.getProperty(SYSTEM_PROPERTY_CARBON_HOME)).resolve(Paths.get
                (FORGETME_TOOL_HOME, USER_STORE_EXTENSION_CONF_RELATIVE_PATH)).toString();
        args.add(configDirectoryPath);

        args.add("-U");
        args.add(existingUsername);

        args.add("-pu");
        args.add(newUsername);

        args.add("-TID");
        args.add(String.valueOf(tenantId));

        args.add("-T");
        args.add(tenantDomain);

        args.add("-D");
        args.add(userStoreDomain);

        return String.join(" ", args);
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function() {

	Smart.ui.createProductLijstWindow = function() {
		var productLijstWin = Titanium.UI.createWindow(style.Window);
		var lblTitle = Titanium.UI.createLabel(Smart.combine(style.titleBar, {
			text : 'Product toevoegen'
		}));
		productLijstWin.setTitleControl(lblTitle);

		productLijstWin.addEventListener('open', function() {
			getProducts();
		});

		//Backbutton
		var backButton = Titanium.UI.createButton(style.backButton);
		backButton.addEventListener('click', function() {
			Smart.navGroup.close(productLijstWin, {
				animated : false
			});
		});
		productLijstWin.leftNavButton = backButton;

		//
		//Inhoud window
		//
		var searchBg = Titanium.UI.createView(style.searchBar);
		productLijstWin.add(searchBg);

		var searchbar = Titanium.UI.createTextField(Smart.combine(style.SearchField,{
			hintText : 'Voeg producten toe aan lijst...'
		}));
		productLijstWin.add(searchbar);

		searchbar.addEventListener('change', function() {
			getProductNaam();
		});

		var categorieLbl = Titanium.UI.createLabel(Smart.combine(style.textProductTitle, {
			text : 'Zoek product in categoriëen',
			top : 60
		}));

		productLijstWin.add(categorieLbl);

		return productLijstWin;

		//////////////////////////////////////////////////////////////////////////////////////
		/// Product toevoegen door zoeken op naam											//
		//////////////////////////////////////////////////////////////////////////////////////
		function getProductNaam() {

			var data = [];

			var getReq = Titanium.Network.createHTTPClient();
			if(Ti.App.localonline === "local") {
				getReq.open("GET", "http://localhost/smartscan/get_allproducts.php");
			} else {
				getReq.open("GET", "http://sofiehendrickx.eu/SmartScan/get_allproducts.php");
			}

			getReq.timeout = 5000;

			getReq.onload = function() {
				try {
					var products = JSON.parse(this.responseText);
					Titanium.App.product = products;
					Titanium.App.dataproduct = products.length;

					//Er zijn nog geen linken in de databank
					if(products.getProd === false) {
						var lblNoCat = Titanium.UI.createLabel(Smart.combine(style.textError, {
							top : 42,
							text : 'Geen producten gevonden.',
							left : 45,
							right : 30,
							width : 300,
							height : 'auto'
						}));
						productLijstWin.add(lblNoCat);

					} else {
						for(var i = 0; i < products.length; i++) {
							var id = products[i].id;
							var pNaam = products[i].naam;

							var row = Ti.UI.createTableViewRow(style.row);

							var name = Ti.UI.createLabel(Smart.combine(style.textNormal, {
								text : pNaam
							}));

							row.add(name);
							row.className = 'item' + i;
							data[i] = row;
						};

						var listCat = Titanium.UI.createTableView(Smart.combine(style.tableView, {
							data : data,
							top:40,
							bottom:200
						}));
						productLijstWin.add(listCat);

						listCat.addEventListener('click', function(e) {
							Titanium.App.selectedProdIndex = products[e.index].id;
							addProduct();
						});

					}

				} catch(e) {
					alert(e);
				}
			};
			var params = {
				name : searchbar.value
			};
			Ti.API.info('Search: '+params.name);

			getReq.onerror = function(e) {
				Ti.API.info("TEXT onerror:   " + this.responseText);
				alert('Er is iets mis met de databank.');
			}

			getReq.send(params);
		}

		//////////////////////////////////////////////////////////////////////////////////////
		/// Product toevoegen aan boodschappenlijst door zoeken op naam						//
		//////////////////////////////////////////////////////////////////////////////////////
		function addProduct() {
			var createReq = Titanium.Network.createHTTPClient();
			if(Ti.App.localonline === "local") {
				createReq.open("POST", "http://localhost/smartscan/post_addproduct.php");
			} else {
				createReq.open("POST", "http://sofiehendrickx.eu/SmartScan/post_addproduct.php");
			}

			var params = {
				list_id : Titanium.App.selectedLijstje,
				product_id : Titanium.App.selectedProdIndex
			};
			Ti.API.info('Add: ' + params.list_id + ' ' + params.product_id);

			createReq.onload = function() {
				try {
					var json = this.responseText;
					var response = JSON.parse(json);
					Titanium.API.info(this.responseText);
					if(response.add === true) {

						Ti.App.fireEvent('app:reloadLijst', {
							action : 'Reload links'
						});
						Smart.navGroup.close(productLijstWin, {
							animated : false
						});
						Smart.ui.createLijstjeInhoudWindow();

					} else {
						alert('Product staat al op lijstje');
					}
				} catch(e) {
					alert(e);
				}
			};
			createReq.onerror = function(e) {
				Ti.API.info("TEXT onerror:   " + this.responseText);
				alert('Er is iets mis met de databank.');
			}

			createReq.send(params);
		}

		//////////////////////////////////////////////////////////////////////////////////////
		/// Producten van gekozen categorie													//
		//////////////////////////////////////////////////////////////////////////////////////
		function getProducts() {

			var data = [];

			var getReq = Titanium.Network.createHTTPClient();
			if(Ti.App.localonline === "local") {
				getReq.open("GET", "http://localhost/smartscan/get_category_products.php");
			} else {
				getReq.open("GET", "http://sofiehendrickx.eu/SmartScan/get_category_products.php");
			}

			getReq.timeout = 5000;

			getReq.onload = function() {
				try {
					var categories = JSON.parse(this.responseText);

					if(categories.getCatProd === false) {
						var lblNoCat = Titanium.UI.createLabel(Smart.combine(style.textError, {
							top : 130,
							text : 'Geen producten gevonden.',
							left : 30
						}));
						productLijstWin.add(lblNoCat);

					} else {
						for(var i = 0; i < categories.length; i++) {
							var id = categories[i].id;
							var naam = categories[i].naam;
							var discount = categories[i].discount;

							var row = Ti.UI.createTableViewRow(style.row);

							var name = Ti.UI.createLabel(Smart.combine(style.textNormal, {
								text : naam
							}));

							var discountLbl = Ti.UI.createLabel(Smart.combine(style.textError, {
								text : 'PROMO',
								textAlign : 'right',
								right:60
							}));

							if(discount===null){
								discountLbl.text="";
							}

							row.add(name);
							row.add(discountLbl);
							row.className = 'item' + i;
							data[i] = row;
						};

						var listCat = Titanium.UI.createTableView(Smart.combine(style.tableView, {
							top : 100,
							data : data
						}));
						productLijstWin.add(listCat);

						//Open detail van window
						listCat.addEventListener('click', function(e) {
							Titanium.App.selectedProdIndex = categories[e.index].id;
							Titanium.App.selectedProdNaam = categories[e.index].naam;
							Ti.API.info('Titanium.App.selectedProdIndex: ' + categories[e.index].id);
							Ti.API.info('Titanium.App.selectedProdNaam: ' + categories[e.index].naam);
							Smart.navGroup.close(productLijstWin, {
								animated : false
							});
							addProduct();
							Smart.navGroup.open(Smart.ui.createLijstjeInhoudWindow(), {
								animated : false
							});
						});
					}

				} catch(e) {
					alert(e);
				}
			};
			getReq.onerror = function(e) {
				Ti.API.info("TEXT onerror:   " + this.responseText);
				alert('Er is iets mis met de databank.');
			}
			var params = {
				id : Titanium.App.selectedCatIndex
			};

			getReq.send(params);
		}

	};
})();


text:
var mongoose = require('mongoose');
var Users    = mongoose.model('Users');
var Ideas    = mongoose.model('Ideas');
var Projects = mongoose.model('Projects');
var Notifications   = mongoose.model('Notifications');
var IdeaComments    = mongoose.model('IdeaComments');
var ProjectComments = mongoose.model('ProjectComments');
var core 		= require('../core.js');

/*
Edit user information.
Can change location (+visibility), email (+visibility), full name.
*/
exports.edit = function(req, res) {
  var email = false, loc = false;
  if (req.body.email_pub) email = true;
  if (req.body.location_pub) loc = true;

  var conditions = { 'user_id': req.session.auth.github.user.id };
  var update = {$set: {
    'location': 			req.body.location,
    'user_fullname':  req.body.fullname,
    'user_email': 		req.body.email,
    'location_pub':   loc,
    'email_pub':  		email
  }};
  Users.update(conditions, update, function (err, num) {
    console.log("* " + req.session.auth.github.user.login + " made profile changes.");
    res.redirect('/' + req.session.auth.github.user.login);
  });
}

/*
User profile page. Shows all info about selected user.
*/
exports.index = function(req, res) {
  var cname = req.url.substring(1, (req.url + '/').substring(1).indexOf('/')+1);
  var uid = ((req.session.auth) ? req.session.auth.github.user.id : null);

  Users.findOne ({ 'user_name': cname }, function(err, cuser) {
    if (!cuser) return res.status(404).render('404', {title: "404: File not found"})
    else {

      Users.findOne ({ 'user_id': uid }, function(err, user) {

          Ideas
          .find({ 'user_name': cuser.user_name })
          .sort('-date_post')
          .limit(3)
          .exec(function(err, ideas) {
            Projects
            .find({ 'user_name': cuser.user_name })
            .sort('-date_post')
            .limit(3)
            .exec(function(err, projects) {

              // List just first 3 repos
              cuser.repos = cuser.repos.slice(0, 3);

              res.render('profile', {
                title:     cuser.user_fullname,
                currentUrl:'',
                cuser: 	  cuser,
                projects:  projects,
                ideas: 		ideas,
                user: 		 user
              });

            })
          })

      })
    }
  })
}

/*
Ideas tab.
*/
exports.ideas = function(req, res) {
  var uid = ((req.session.auth) ? req.session.auth.github.user.id : null);

  Users.findOne ({ 'user_name': req.params.user }, function(err, cuser) {
    if (!cuser) return res.render('404', {title: "404: File not found"});
    else {

      Users.findOne ({ 'user_id': uid }, function(err, user) {

        Ideas
        .find({ 'user_name': cuser.user_name })
        .sort('-date_post')
        .exec(function(err, ideas) {
          res.render('profile', {
            'title':      cuser.user_fullname,
            'currentUrl': 'ideas',
            'cuser':      cuser,
            'projects':   '',
            'ideas':      ideas,
            'user':       user
          })
        })

      })
    }
  })
}

/*
Projects tab.
*/
exports.projects = function(req, res) {
  var uid = ((req.session.auth) ? req.session.auth.github.user.id : null);

  Users.findOne ({ 'user_name': req.params.user }, function(err, cuser) {
    if (!cuser) return res.render('404', {title: "404: File not found"});
    else {

      Users.findOne ({ 'user_id': uid }, function(err, user) {

        Projects
        .find({ 'user_name': cuser.user_name })
        .sort('-date_post')
        .exec(function(err, projects) {
          res.render('profile', {
            'title':      cuser.user_fullname,
            'currentUrl': 'projects',
            'cuser':      cuser,
            'projects':   projects,
            'ideas':      '',
            'user':       user
          })
        })

      })
    }
  })
}

/*
Notifications tab.
*/
exports.notifications = function(req, res) {
  var uid = ((req.session.auth) ? req.session.auth.github.user.id : null);

  Users.findOne ({ 'user_name': req.params.user }, function(err, cuser) {
    if (!cuser) return res.render('404', {title: "404: File not found"});
    else {

      Users.findOne ({ 'user_id': uid }, function(err, user) {

        // Users must only see their own notifications
        if (!user || user.user_name != cuser.user_name) {
          return res.redirect('/' + cuser.user_name);

        } else {
          // Update general unread
          var conditions = {user_name: cuser.user_name};
          var update = {$set: {unread: false}};
          Users.update(conditions, update).exec();

          Notifications
          .find({ 'dest': cuser.user_name })
          .sort({ 'date' : -1 })
          .exec(function(err, notif) {

            for (var i in notif) {
              // Format date
              notif[i].date_f = core.get_time_from(notif[i].date);
            }

            res.render('profile', {
              'title':      cuser.user_fullname,
              'currentUrl': 'notifications',
              'cuser':      cuser,
              'notif':      notif,
              'user':       user
            })

          })
        }
      })
    }
  })
}

/*
Repositories tab.
*/
exports.repos = function(req, res) {
  var uid = ((req.session.auth) ? req.session.auth.github.user.id : null);

  Users.findOne ({ 'user_name': req.params.user }, function(err, cuser) {
    if (!cuser) return res.render('404', {title: "404: File not found"});
    else {

      Users.findOne ({ 'user_id': uid }, function(err, user) {

        res.render('profile', {
          'title':      cuser.user_fullname,
          'currentUrl': 'repos',
          'cuser':      cuser,
          'projects':   '',
          'ideas':      '',
          'user':       user
        })

      })
    }
  })
}

/*
Edit profile tab.
*/
exports.edit_profile = function(req, res) {
  var uid = ((req.session.auth) ? req.session.auth.github.user.id : null);

  Users.findOne ({ 'user_name': req.params.user }, function(err, cuser) {
    if (!cuser) return res.render('404', {title: "404: File not found"});
    else {

      Users.findOne ({ 'user_id': uid }, function(err, user) {

        // Users can edit only their own profile
        if (!user || user.user_name != cuser.user_name)
          res.redirect('/' + cuser.user_name);
        else
          res.render('profile', {
            'title':      cuser.user_fullname,
            'currentUrl': 'edit_profile',
            'cuser':      cuser,
            'projects':   '',
            'ideas':      '',
            'user':       user
          })

      })
    }
  })
}

/*
Cups tab. Display info about users's score.
*/
exports.cups = function(req, res) {
  var uid = ((req.session.auth) ? req.session.auth.github.user.id : null);

  Users.findOne ({ 'user_name': req.params.user }, function(err, cuser) {
    if (!cuser) return res.render('404', {title: "404: File not found"});
    else {

      Users.findOne ({ 'user_id': uid }, function(err, user) {

        res.render('profile', {
          'title':      cuser.user_fullname,
          'currentUrl': 'cups',
          'cuser':      cuser,
          'projects':   '',
          'ideas':      '',
          'user':       user
        })

      })
    }
  })
}

/*
Remove user account and all associated content.
Keep username in notifications (as src) and Challenges. When someone clicks
on his name, they will get 404.
*/
exports.remove = function(req, res) {
  res.redirect('/logout')

  var user = req.session.auth.github.user.login

  // Remove all ideas
  Ideas.remove({'user_name': user}, function (err, num) {
    if (err) console.log("[ERR] Could not remove ideas.");
  })

  // Remove all idea comments
  IdeaComments.remove({'user_name': user}, function (err, num) {
    if (err) console.log("[ERR] Could not remove idea comments.");
  })

  // Remove all projects
  Projects.remove({'user_name': user}, function (err, num) {
    if (err) console.log("[ERR] Could not remove projects.");
  })

  // Remove all project comments
  ProjectComments.remove({'user_name': user}, function (err, num) {
    if (err) console.log("[ERR] Could not remove project comments.");
  })

  // Remove notifications that he received
  Notifications.remove({'dest': user}, function (err, num) {
    if (err) console.log("[ERR] Could not remove user notifications.");
  })

  // Remove user data
  Users.remove({'user_name': user}, function (err, num) {
    if (err) console.log("[ERR] Could not remove user info.");
  })

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
AgentSpecificMeddraLowLevelTerm
</TITLE>

<META NAME="keywords" CONTENT="gov.nih.nci.cabig.caaers.domain.AgentSpecificMeddraLowLevelTerm class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nih.nci.cabig.caaers.domain

Class AgentSpecificMeddraLowLevelTerm

java.lang.Object
  gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject
      gov.nih.nci.cabig.caaers.domain.AgentSpecificTerm<LowLevelTerm>
          gov.nih.nci.cabig.caaers.domain.AgentSpecificMeddraLowLevelTerm

All Implemented Interfaces:
gov.nih.nci.cabig.ctms.domain.DomainObject, gov.nih.nci.cabig.ctms.domain.GridIdentifiable, gov.nih.nci.cabig.ctms.domain.MutableDomainObject

public class AgentSpecificMeddraLowLevelTerm
extends AgentSpecificTerm<LowLevelTerm>

The Class AgentSpecificMeddraLowLevelTerm.

Author:

Ion C. Olaru

Constructor Summary

AgentSpecificMeddraLowLevelTerm()

Method Summary

 AgentSpecificMeddraLowLevelTerm
copy()

          Copy.

 java.lang.String
getFullName()

          Gets the full name.

 LowLevelTerm
getTerm()

          Gets the term.

 boolean
isMedDRA()

          Checks if is med dra.

 boolean
isOtherRequired()

          Checks if is other required.

 void
setLowLevelTerm(LowLevelTerm lowlevelTerm)

          Sets the low level term.

Methods inherited from class gov.nih.nci.cabig.caaers.domain.AgentSpecificTerm

getAgent, getDeleted, getOtherToxicity, setAgent, setDeleted, setOtherToxicity, setTerm

Methods inherited from class gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject

getGridId, getId, getVersion, hasGridId, setGridId, setId, setVersion

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AgentSpecificMeddraLowLevelTerm

public AgentSpecificMeddraLowLevelTerm()

Method Detail

getFullName

public java.lang.String getFullName()

Description copied from class: AgentSpecificTerm

Gets the full name.

Specified by:
getFullName in class AgentSpecificTerm<LowLevelTerm>

Returns:
the full name

getTerm

public LowLevelTerm getTerm()

Description copied from class: AgentSpecificTerm

Gets the term.

Overrides:
getTerm in class AgentSpecificTerm<LowLevelTerm>

Returns:
the term

setLowLevelTerm

public void setLowLevelTerm(LowLevelTerm lowlevelTerm)

Sets the low level term.

Parameters:
lowlevelTerm - the new low level term

copy

public AgentSpecificMeddraLowLevelTerm copy()

Description copied from class: AgentSpecificTerm

Copy.

Overrides:
copy in class AgentSpecificTerm<LowLevelTerm>

Returns:
the agent specific term

isMedDRA

public boolean isMedDRA()

Description copied from class: AgentSpecificTerm

Checks if is med dra.

Specified by:
isMedDRA in class AgentSpecificTerm<LowLevelTerm>

Returns:
true, if is med dra

isOtherRequired

public boolean isOtherRequired()

Description copied from class: AgentSpecificTerm

Checks if is other required.

Specified by:
isOtherRequired in class AgentSpecificTerm<LowLevelTerm>

Returns:
true, if is other required

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using Com.PhilChuang.Utils;

namespace Demo.Utils
{
    public abstract class NotifyPropertyChangedBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged = delegate { };
        protected event PropertyChangedEventHandler PropertyChangedInternal = delegate { };

        protected virtual void RaisePropertyChanged<T> (Expression<Func<T>> propertyExpression)
        {
            RaisePropertyChanged (propertyExpression.GetPropertyName ());
        }

        protected virtual void RaisePropertyChanged ([CallerMemberName] string propertyName = null)
        {
            RaisePropertyChanged (new PropertyChangedEventArgs (propertyName));
        }

        protected virtual void RaisePropertyChanged (PropertyChangedEventArgs args)
        {
            if (PropertyChanged != null)
            {
                var handler = PropertyChanged;
                handler (this, args);
            }
            RaisePropertyChangedInternal (args);
        }

        protected virtual void RaisePropertyChangedInternal ([CallerMemberName] string propertyName = null)
        {
            RaisePropertyChangedInternal (new PropertyChangedEventArgs (propertyName));
        }

        protected virtual void RaisePropertyChangedInternal (PropertyChangedEventArgs args)
        {
            if (PropertyChangedInternal != null)
            {
                var handler = PropertyChangedInternal;
                handler (this, args);
            }
        }
    }
}


text:
package de.uniaugsburg.isse.constraints.csemiring;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.uniaugsburg.isse.constraints.SoftConstraint;
import de.uniaugsburg.isse.constraints.Variable;

public abstract class ConstraintCentricCSemiring<T> implements CSemiring<T> {

	protected boolean domainCheck; // try tighter bounds by iterating through
									// partner's domain

	protected Collection<SoftConstraint> softConstraints;

	public static class WeightsComparator implements Comparator<SoftConstraint> {

		@Override
		public int compare(SoftConstraint first, SoftConstraint second) {
			// use descending order according to weights
			return new Integer(second.getWeight()).compareTo(new Integer(first
					.getWeight()));
		}
	}

	public List<String> getVariableOrder(
			Collection<SoftConstraint> variables) {
		ArrayList<SoftConstraint> constraintsOrdered = new ArrayList<SoftConstraint>(variables);
		Collections.sort(constraintsOrdered, new WeightsComparator());
		// now just add the variables of the most important constraints
		List<String> vars = new LinkedList<String>();
		for(SoftConstraint sc : constraintsOrdered) {
			for(String c : sc.getScope()) {
				if(!vars.contains(c)) {
					vars.add(c);
				}
			}
		}
		return vars;
	}

	public boolean isDomainCheck() {
		return domainCheck;
	}

	public T bestCase(Map<String, Variable> valuation, Map<String, Variable> variableMap) {
		T violationWeight = getMax();

		for(SoftConstraint sc : softConstraints) {
			if(sc.assignedBy(valuation)) {
				if(!sc.getRelation().evaluateVarMap(valuation)) {
					T constraintValuated = valuateViolatedConstraint(sc);
					violationWeight = combine(violationWeight, constraintValuated);
				}
			} else if (sc.partiallyAssignedBy(valuation) && domainCheck) {
				// for d in other variable domain : if all violated -> add weight
				Map<String, Variable> copiedValuation = new  HashMap<String, Variable>(valuation);
				boolean foundSatisfyingAssignment = false;
				for(String otherVar : sc.getScope()) {
					if(!copiedValuation.containsKey(otherVar)) {
						Variable otherVariable = variableMap.get(otherVar);
						for(int domainItem : otherVariable.getDomain().getDomainItems()) {
							otherVariable.setValue(domainItem);
							otherVariable.setAssigned(true);
							copiedValuation.put(otherVar, otherVariable);
							if(sc.getRelation().evaluateVarMap(copiedValuation)) {
								foundSatisfyingAssignment = true;
								otherVariable.setValue(0);
								otherVariable.setAssigned(false);
								copiedValuation.remove(otherVar);
								break;
							}
							otherVariable.setValue(0);
							otherVariable.setAssigned(false);
							copiedValuation.remove(otherVar);
						}
					}
				}
				// encapsulate this!
				if(!foundSatisfyingAssignment) {
					T constraintValuated = valuateViolatedConstraint(sc);
					violationWeight = combine(violationWeight, constraintValuated);
				}
			}
		}
		return violationWeight;
	}

	public T worstCase(Map<String, Variable> valuation, Map<String, Variable> variableMap) {
		T violationWeight = getMax();

		for(SoftConstraint sc : softConstraints) {
			if(sc.assignedBy(valuation)) {
				if(!sc.getRelation().evaluateVarMap(valuation)) {
					T valuatedConstraint = valuateViolatedConstraint(sc);
					violationWeight = combine(violationWeight, valuatedConstraint);
				}
			} else { // take unassigneds also into account - only if some assignment of the other variable exists here
				if(sc.partiallyAssignedBy(valuation) && domainCheck) {
					Map<String, Variable> copiedValuation = new  HashMap<String, Variable>(valuation);
					boolean foundViolatingAssignment = false;
					for(String otherVar : sc.getScope()) {
						if(!copiedValuation.containsKey(otherVar)) {
							Variable otherVariable = variableMap.get(otherVar);
							for(int domainItem : otherVariable.getDomain().getDomainItems()) {
								otherVariable.setValue(domainItem);
								otherVariable.setAssigned(true);
								copiedValuation.put(otherVar, otherVariable);
								if(!sc.getRelation().evaluateVarMap(copiedValuation)) {
									foundViolatingAssignment = true;
									otherVariable.setValue(0);
									otherVariable.setAssigned(false);
									copiedValuation.remove(otherVar);
									break;
								}
								otherVariable.setValue(0);
								otherVariable.setAssigned(false);
								copiedValuation.remove(otherVar);
							}
						}
					}
					if(foundViolatingAssignment) {
						T valuatedConstraint = valuateViolatedConstraint(sc);
						violationWeight = combine(violationWeight, valuatedConstraint);
					}
				} else {
					T valuatedConstraint = valuateViolatedConstraint(sc);
					violationWeight = combine(violationWeight, valuatedConstraint);
				}
			}
		}
		return violationWeight;
	}

	public abstract T valuateViolatedConstraint(SoftConstraint sc);

	public void setDomainCheck(boolean domainCheck) {
		this.domainCheck = domainCheck;
	}

	@Override
	/**
	 * Default implementation: a <= b iff a + b = b
	 */
	public boolean worseOrEqual(T first, T second) {
		T res = compare(first, second);
		return second.equals(res);
	}

}


text:
//
//  NSMutableURLRequest+WFOAuth2.h
//  WFOAuth2
//
//  Created by Conrad Kramer on 3/24/16.
//  Copyright © 2016 DeskConnect, Inc. All rights reserved.
//

#import <WFOAuth2/WFOAuth2Credential.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSMutableURLRequest (WFOAuth2)

/**
 Sets the authorization header of the request with the access token of the provided credential.

 @param credential The credential configure on the request. The token must be a bearer token.
 */
- (void)wfo_setAuthorizationWithCredential:(nullable WFOAuth2Credential *)credential;

/**
 Sets the body of the request with the provided query items using form encoding. This method
 also sets the Content-Type header to @"application/x-www-form-urlencoded"

 @param queryItems The query items to set in the body of the request.
 */
- (void)wfo_setBodyWithQueryItems:(nullable NSArray<NSURLQueryItem *> *)queryItems;

@end

NS_ASSUME_NONNULL_END


text:
Meteor.methods({
  getUsers:function(query){
    return Meteor.users.find(query).fetch()
  }
})


text:
package cmd

import (
	"context"
	"fmt"

	"github.com/urfave/cli"

	"github.com/manifoldco/torus-cli/api"
	"github.com/manifoldco/torus-cli/config"
	"github.com/manifoldco/torus-cli/errs"
)

func init() {
	login := cli.Command{
		Name:     "login",
		Usage:    "Log in to a user account, authenticating the CLI",
		Category: "ACCOUNT",
		Action:   chain(ensureDaemon, login, checkUpdates),
	}
	Cmds = append(Cmds, login)
}

func login(ctx *cli.Context) error {
	email, err := EmailPrompt("")
	if err != nil {
		return err
	}

	password, err := PasswordPrompt(false, nil)
	if err != nil {
		return err
	}

	cfg, err := config.LoadConfig()
	if err != nil {
		return err
	}

	client := api.NewClient(cfg)

	c := context.Background()
	return performLogin(c, client, email, password, true)
}

func performLogin(c context.Context, client *api.Client, email, password string, shouldPrint bool) error {
	err := client.Session.UserLogin(context.Background(), email, password)
	if err != nil {
		return errs.NewErrorExitError("Login failed.", err)
	}

	if shouldPrint {
		fmt.Println("You are now authenticated.")
	}
	return nil
}

func testLogin(c context.Context, client *api.Client, email, password string) error {
	return performLogin(c, client, email, password, false)
}


text:
class GBOamView : public ResizeDlg, IUpdateListener
{
 private:
  BITMAPINFO bmpInfo;
  u8 *data;
  int w;
  int h;
  int number;
  bool autoUpdate;
  BitmapControl oamView;
  ZoomControl oamZoom;
  ColorControl color;

  // Construction
 public:
  void updateScrollInfo();
  void save();
  void savePNG(const char *name);
  void saveBMP(const char *name);
  void render();
  void setAttributes(int y, int x, int tile, int flags);
  void paint();
  ~GBOamView();
  GBOamView(CWnd* pParent = NULL);   // standard constructor

  afx_msg LRESULT OnColInfo(WPARAM wParam, LPARAM lParam);
  afx_msg LRESULT OnMapInfo(WPARAM wParam, LPARAM lParam);
  virtual void update();

  // Dialog Data
  //{{AFX_DATA(GBOamView)
  enum { IDD = IDD_GB_OAM_VIEW };
  CEdit  m_sprite;
  BOOL  m_stretch;
  //}}AFX_DATA

  // Overrides
  // ClassWizard generated virtual function overrides
  //{{AFX_VIRTUAL(GBOamView)
 protected:
  virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
  virtual void PostNcDestroy();
  //}}AFX_VIRTUAL

  // Implementation
 protected:

  // Generated message map functions
  //{{AFX_MSG(GBOamView)
  virtual BOOL OnInitDialog();
  afx_msg void OnStretch();
  afx_msg void OnAutoUpdate();
  afx_msg void OnChangeSprite();
  afx_msg void OnClose();
  afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
  //}}AFX_MSG
  DECLARE_MESSAGE_MAP()
    };

    //{{AFX_INSERT_LOCATION}}
    // Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_GBOAMVIEW_H__FE8105E6_9693_479A_8C57_DEEA1B2EA3D6__INCLUDED_)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.machinelearningservices.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The properties for Quota update or retrieval. */
@Fluent
public final class QuotaBaseProperties {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(QuotaBaseProperties.class);

    /*
     * Specifies the resource ID.
     */
    @JsonProperty(value = "id")
    private String id;

    /*
     * Specifies the resource type.
     */
    @JsonProperty(value = "type")
    private String type;

    /*
     * The maximum permitted quota of the resource.
     */
    @JsonProperty(value = "limit")
    private Long limit;

    /*
     * An enum describing the unit of quota measurement.
     */
    @JsonProperty(value = "unit")
    private QuotaUnit unit;

    /**
     * Get the id property: Specifies the resource ID.
     *
     * @return the id value.
     */
    public String id() {
        return this.id;
    }

    /**
     * Set the id property: Specifies the resource ID.
     *
     * @param id the id value to set.
     * @return the QuotaBaseProperties object itself.
     */
    public QuotaBaseProperties withId(String id) {
        this.id = id;
        return this;
    }

    /**
     * Get the type property: Specifies the resource type.
     *
     * @return the type value.
     */
    public String type() {
        return this.type;
    }

    /**
     * Set the type property: Specifies the resource type.
     *
     * @param type the type value to set.
     * @return the QuotaBaseProperties object itself.
     */
    public QuotaBaseProperties withType(String type) {
        this.type = type;
        return this;
    }

    /**
     * Get the limit property: The maximum permitted quota of the resource.
     *
     * @return the limit value.
     */
    public Long limit() {
        return this.limit;
    }

    /**
     * Set the limit property: The maximum permitted quota of the resource.
     *
     * @param limit the limit value to set.
     * @return the QuotaBaseProperties object itself.
     */
    public QuotaBaseProperties withLimit(Long limit) {
        this.limit = limit;
        return this;
    }

    /**
     * Get the unit property: An enum describing the unit of quota measurement.
     *
     * @return the unit value.
     */
    public QuotaUnit unit() {
        return this.unit;
    }

    /**
     * Set the unit property: An enum describing the unit of quota measurement.
     *
     * @param unit the unit value to set.
     * @return the QuotaBaseProperties object itself.
     */
    public QuotaBaseProperties withUnit(QuotaUnit unit) {
        this.unit = unit;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
package org.apache.camel.component.microprofile.faulttolerance;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;

import io.smallrye.faulttolerance.core.FaultToleranceStrategy;
import io.smallrye.faulttolerance.core.InvocationContext;
import io.smallrye.faulttolerance.core.bulkhead.FutureThreadPoolBulkhead;
import io.smallrye.faulttolerance.core.circuit.breaker.CircuitBreaker;
import io.smallrye.faulttolerance.core.fallback.Fallback;
import io.smallrye.faulttolerance.core.stopwatch.SystemStopwatch;
import io.smallrye.faulttolerance.core.timeout.ScheduledExecutorTimeoutWatcher;
import io.smallrye.faulttolerance.core.timeout.Timeout;
import io.smallrye.faulttolerance.core.timeout.TimeoutWatcher;
import io.smallrye.faulttolerance.core.timer.ThreadTimer;
import io.smallrye.faulttolerance.core.util.ExceptionDecision;
import org.apache.camel.AsyncCallback;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePropertyKey;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.ExtendedExchange;
import org.apache.camel.Navigate;
import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.RuntimeExchangeException;
import org.apache.camel.api.management.ManagedAttribute;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.processor.PooledExchangeTask;
import org.apache.camel.processor.PooledExchangeTaskFactory;
import org.apache.camel.processor.PooledTaskFactory;
import org.apache.camel.processor.PrototypeTaskFactory;
import org.apache.camel.spi.IdAware;
import org.apache.camel.spi.ProcessorExchangeFactory;
import org.apache.camel.spi.RouteIdAware;
import org.apache.camel.spi.UnitOfWork;
import org.apache.camel.support.AsyncProcessorSupport;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.support.UnitOfWorkHelper;
import org.apache.camel.support.service.ServiceHelper;
import org.apache.camel.util.ObjectHelper;
import org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException;
import org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.smallrye.faulttolerance.core.Invocation.invocation;

/**
 * Implementation of Circuit Breaker EIP using microprofile fault tolerance.
 */
@ManagedResource(description = "Managed FaultTolerance Processor")
public class FaultToleranceProcessor extends AsyncProcessorSupport
        implements CamelContextAware, Navigate<Processor>, org.apache.camel.Traceable, IdAware, RouteIdAware {

    private static final Logger LOG = LoggerFactory.getLogger(FaultToleranceProcessor.class);

    private volatile CircuitBreaker circuitBreaker;
    private CamelContext camelContext;
    private String id;
    private String routeId;
    private final FaultToleranceConfiguration config;
    private final Processor processor;
    private final Processor fallbackProcessor;
    private ScheduledExecutorService scheduledExecutorService;
    private boolean shutdownScheduledExecutorService;
    private ExecutorService executorService;
    private boolean shutdownExecutorService;
    private ExecutorService threadTimerExecutorService;
    private boolean shutdownThreadTimerExecutorService;
    private ProcessorExchangeFactory processorExchangeFactory;
    private PooledExchangeTaskFactory taskFactory;
    private PooledExchangeTaskFactory fallbackTaskFactory;

    public FaultToleranceProcessor(FaultToleranceConfiguration config, Processor processor,
                                   Processor fallbackProcessor) {
        this.config = config;
        this.processor = processor;
        this.fallbackProcessor = fallbackProcessor;
    }

    @Override
    public CamelContext getCamelContext() {
        return camelContext;
    }

    @Override
    public void setCamelContext(CamelContext camelContext) {
        this.camelContext = camelContext;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String getRouteId() {
        return routeId;
    }

    @Override
    public void setRouteId(String routeId) {
        this.routeId = routeId;
    }

    public CircuitBreaker getCircuitBreaker() {
        return circuitBreaker;
    }

    public void setCircuitBreaker(CircuitBreaker circuitBreaker) {
        this.circuitBreaker = circuitBreaker;
    }

    public boolean isShutdownExecutorService() {
        return shutdownExecutorService;
    }

    public void setShutdownExecutorService(boolean shutdownExecutorService) {
        this.shutdownExecutorService = shutdownExecutorService;
    }

    public ExecutorService getExecutorService() {
        return executorService;
    }

    public void setExecutorService(ExecutorService executorService) {
        this.executorService = executorService;
    }

    @Override
    public String getTraceLabel() {
        return "faultTolerance";
    }

    @ManagedAttribute(description = "Returns the current delay in milliseconds.")
    public long getDelay() {
        return config.getDelay();
    }

    @ManagedAttribute(description = "Returns the current failure rate in percentage.")
    public float getFailureRate() {
        return config.getFailureRatio();
    }

    @ManagedAttribute(description = "Returns the current request volume threshold.")
    public int getRequestVolumeThreshold() {
        return config.getRequestVolumeThreshold();
    }

    @ManagedAttribute(description = "Returns the current success threshold.")
    public int getSuccessThreshold() {
        return config.getSuccessThreshold();
    }

    @ManagedAttribute(description = "Is timeout enabled")
    public boolean isTimeoutEnabled() {
        return config.isTimeoutEnabled();
    }

    @ManagedAttribute(description = "The timeout wait duration")
    public long getTimeoutDuration() {
        return config.getTimeoutDuration();
    }

    @ManagedAttribute(description = "The timeout pool size for the thread pool")
    public int getTimeoutPoolSize() {
        return config.getTimeoutPoolSize();
    }

    @ManagedAttribute(description = "Is bulkhead enabled")
    public boolean isBulkheadEnabled() {
        return config.isBulkheadEnabled();
    }

    @ManagedAttribute(description = "The max amount of concurrent calls the bulkhead will support.")
    public int getBulkheadMaxConcurrentCalls() {
        return config.getBulkheadMaxConcurrentCalls();
    }

    @ManagedAttribute(description = "The task queue size for holding waiting tasks to be processed by the bulkhead")
    public int getBulkheadWaitingTaskQueue() {
        return config.getBulkheadWaitingTaskQueue();
    }

    @ManagedAttribute(description = "Returns the current state of the circuit breaker")
    public String getCircuitBreakerState() {
        if (circuitBreaker != null) {
            int state = circuitBreaker.currentState();
            if (state == 2) {
                return "HALF_OPEN";
            } else if (state == 1) {
                return "OPEN";
            } else {
                return "CLOSED";
            }
        }
        return null;
    }

    @Override
    public List<Processor> next() {
        if (!hasNext()) {
            return null;
        }
        List<Processor> answer = new ArrayList<>();
        answer.add(processor);
        if (fallbackProcessor != null) {
            answer.add(fallbackProcessor);
        }
        return answer;
    }

    @Override
    public boolean hasNext() {
        return true;
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean process(Exchange exchange, AsyncCallback callback) {
        // run this as if we run inside try .. catch so there is no regular
        // Camel error handler
        exchange.setProperty(ExchangePropertyKey.TRY_ROUTE_BLOCK, true);

        CircuitBreakerFallbackTask fallbackTask = null;
        CircuitBreakerTask task = null;
        try {
            task = (CircuitBreakerTask) taskFactory.acquire(exchange, callback);

            // circuit breaker
            FaultToleranceStrategy target = circuitBreaker;

            // 1. bulkhead
            if (config.isBulkheadEnabled()) {
                target = new FutureThreadPoolBulkhead(
                        target, "bulkhead", config.getBulkheadMaxConcurrentCalls(),
                        config.getBulkheadWaitingTaskQueue());
            }
            // 2. timeout
            if (config.isTimeoutEnabled()) {
                TimeoutWatcher watcher = new ScheduledExecutorTimeoutWatcher(scheduledExecutorService);
                target = new Timeout(target, "timeout", config.getTimeoutDuration(), watcher);
            }
            // 3. fallback
            if (fallbackProcessor != null) {
                fallbackTask = (CircuitBreakerFallbackTask) fallbackTaskFactory.acquire(exchange, callback);
                final CircuitBreakerFallbackTask fFallbackTask = fallbackTask;
                target = new Fallback(target, "fallback", fallbackContext -> {
                    exchange.setException(fallbackContext.failure);
                    return fFallbackTask.call();
                }, ExceptionDecision.ALWAYS_FAILURE);
            }

            target.apply(new InvocationContext(task));

        } catch (CircuitBreakerOpenException e) {
            // the circuit breaker triggered a call rejected
            exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false);
            exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false);
            exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, true);
            exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_REJECTED, true);
        } catch (Exception e) {
            // some other kind of exception
            exchange.setException(e);
        } finally {
            if (task != null) {
                taskFactory.release(task);
            }
            if (fallbackTask != null) {
                fallbackTaskFactory.release(fallbackTask);
            }
        }

        exchange.removeProperty(ExchangePropertyKey.TRY_ROUTE_BLOCK);
        callback.done(true);
        return true;
    }

    @Override
    protected void doBuild() throws Exception {
        ObjectHelper.notNull(camelContext, "CamelContext", this);

        boolean pooled = camelContext.adapt(ExtendedCamelContext.class).getExchangeFactory().isPooled();
        if (pooled) {
            int capacity = camelContext.adapt(ExtendedCamelContext.class).getExchangeFactory().getCapacity();
            taskFactory = new PooledTaskFactory(getId()) {
                @Override
                public PooledExchangeTask create(Exchange exchange, AsyncCallback callback) {
                    return new CircuitBreakerTask();
                }
            };
            taskFactory.setCapacity(capacity);
            fallbackTaskFactory = new PooledTaskFactory(getId()) {
                @Override
                public PooledExchangeTask create(Exchange exchange, AsyncCallback callback) {
                    return new CircuitBreakerFallbackTask();
                }
            };
            fallbackTaskFactory.setCapacity(capacity);
        } else {
            taskFactory = new PrototypeTaskFactory() {
                @Override
                public PooledExchangeTask create(Exchange exchange, AsyncCallback callback) {
                    return new CircuitBreakerTask();
                }
            };
            fallbackTaskFactory = new PrototypeTaskFactory() {
                @Override
                public PooledExchangeTask create(Exchange exchange, AsyncCallback callback) {
                    return new CircuitBreakerFallbackTask();
                }
            };
        }

        // create a per processor exchange factory
        this.processorExchangeFactory = getCamelContext().adapt(ExtendedCamelContext.class)
                .getProcessorExchangeFactory().newProcessorExchangeFactory(this);
        this.processorExchangeFactory.setRouteId(getRouteId());
        this.processorExchangeFactory.setId(getId());

        ServiceHelper.buildService(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void doInit() throws Exception {
        ObjectHelper.notNull(camelContext, "CamelContext", this);
        if (circuitBreaker == null) {
            threadTimerExecutorService
                    = getCamelContext().getExecutorServiceManager().newCachedThreadPool(this, "CircuitBreakerThreadTimer");
            shutdownThreadTimerExecutorService = true;

            circuitBreaker = new CircuitBreaker<>(
                    invocation(), id, ExceptionDecision.ALWAYS_FAILURE, config.getDelay(), config.getRequestVolumeThreshold(),
                    config.getFailureRatio(),
                    config.getSuccessThreshold(), SystemStopwatch.INSTANCE, new ThreadTimer(threadTimerExecutorService));
        }

        ServiceHelper.initService(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
    }

    @Override
    protected void doStart() throws Exception {
        if (config.isTimeoutEnabled() && scheduledExecutorService == null) {
            scheduledExecutorService = getCamelContext().getExecutorServiceManager().newScheduledThreadPool(this,
                    "CircuitBreakerTimeout", config.getTimeoutPoolSize());
            shutdownScheduledExecutorService = true;
        }
        if (config.isBulkheadEnabled() && executorService == null) {
            executorService = getCamelContext().getExecutorServiceManager().newThreadPool(this, "CircuitBreakerBulkhead",
                    config.getBulkheadMaxConcurrentCalls(), config.getBulkheadMaxConcurrentCalls());
            shutdownExecutorService = true;
        }

        ServiceHelper.startService(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
    }

    @Override
    protected void doStop() throws Exception {
        if (shutdownScheduledExecutorService && scheduledExecutorService != null) {
            getCamelContext().getExecutorServiceManager().shutdownNow(scheduledExecutorService);
            scheduledExecutorService = null;
        }
        if (shutdownExecutorService && executorService != null) {
            getCamelContext().getExecutorServiceManager().shutdownNow(executorService);
            executorService = null;
        }
        if (shutdownThreadTimerExecutorService && threadTimerExecutorService != null) {
            getCamelContext().getExecutorServiceManager().shutdownNow(threadTimerExecutorService);
            threadTimerExecutorService = null;
        }

        ServiceHelper.stopService(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
    }

    @Override
    protected void doShutdown() throws Exception {
        ServiceHelper.stopAndShutdownServices(processorExchangeFactory, taskFactory, fallbackTaskFactory, processor);
    }

    private final class CircuitBreakerTask implements PooledExchangeTask, Callable<Exchange> {

        private Exchange exchange;

        @Override
        public void prepare(Exchange exchange, AsyncCallback callback) {
            this.exchange = exchange;
            // callback not in use
        }

        @Override
        public void reset() {
            this.exchange = null;
        }

        @Override
        public void run() {
            // not in use
        }

        @Override
        public Exchange call() throws Exception {
            Exchange copy = null;
            UnitOfWork uow = null;
            Throwable cause;

            // turn of interruption to allow fault tolerance to process the exchange under its handling
            exchange.adapt(ExtendedExchange.class).setInterruptable(false);

            try {
                LOG.debug("Running processor: {} with exchange: {}", processor, exchange);

                // prepare a copy of exchange so downstream processors don't
                // cause side-effects if they mutate the exchange
                // in case timeout processing and continue with the fallback etc
                copy = processorExchangeFactory.createCorrelatedCopy(exchange, false);
                if (copy.getUnitOfWork() != null) {
                    uow = copy.getUnitOfWork();
                } else {
                    // prepare uow on copy
                    uow = copy.getContext().adapt(ExtendedCamelContext.class).getUnitOfWorkFactory().createUnitOfWork(copy);
                    copy.adapt(ExtendedExchange.class).setUnitOfWork(uow);
                    // the copy must be starting from the route where its copied from
                    Route route = ExchangeHelper.getRoute(exchange);
                    if (route != null) {
                        uow.pushRoute(route);
                    }
                }

                // process the processor until its fully done
                processor.process(copy);

                // handle the processing result
                if (copy.getException() != null) {
                    exchange.setException(copy.getException());
                } else {
                    // copy the result as its regarded as success
                    ExchangeHelper.copyResults(exchange, copy);
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, true);
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false);
                }
            } catch (Exception e) {
                exchange.setException(e);
            } finally {
                // must done uow
                UnitOfWorkHelper.doneUow(uow, copy);
                // remember any thrown exception
                cause = exchange.getException();
            }

            // and release exchange back in pool
            processorExchangeFactory.release(exchange);

            if (cause != null) {
                // throw exception so resilient4j know it was a failure
                throw RuntimeExchangeException.wrapRuntimeException(cause);
            }
            return exchange;
        }
    }

    private final class CircuitBreakerFallbackTask implements PooledExchangeTask, Callable<Exchange> {

        private Exchange exchange;

        @Override
        public void prepare(Exchange exchange, AsyncCallback callback) {
            this.exchange = exchange;
            // callback not in use
        }

        @Override
        public void reset() {
            this.exchange = null;
        }

        @Override
        public void run() {
            // not in use
        }

        @Override
        public Exchange call() throws Exception {
            Throwable throwable = exchange.getException();
            if (fallbackProcessor == null) {
                if (throwable instanceof TimeoutException) {
                    // the circuit breaker triggered a timeout (and there is no
                    // fallback) so lets mark the exchange as failed
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false);
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false);
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, false);
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_TIMED_OUT, true);
                    exchange.setException(throwable);
                    return exchange;
                } else if (throwable instanceof CircuitBreakerOpenException) {
                    // the circuit breaker triggered a call rejected
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false);
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false);
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, true);
                    exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_REJECTED, true);
                    return exchange;
                } else {
                    // throw exception so fault tolerance know it was a failure
                    throw RuntimeExchangeException.wrapRuntimeException(throwable);
                }
            }

            // fallback route is handling the exception so its short-circuited
            exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false);
            exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, true);
            exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, true);

            // store the last to endpoint as the failure endpoint
            if (exchange.getProperty(ExchangePropertyKey.FAILURE_ENDPOINT) == null) {
                exchange.setProperty(ExchangePropertyKey.FAILURE_ENDPOINT,
                        exchange.getProperty(ExchangePropertyKey.TO_ENDPOINT));
            }
            // give the rest of the pipeline another chance
            exchange.setProperty(ExchangePropertyKey.EXCEPTION_HANDLED, true);
            exchange.setProperty(ExchangePropertyKey.EXCEPTION_CAUGHT, exchange.getException());
            exchange.setRouteStop(false);
            exchange.setException(null);
            // and we should not be regarded as exhausted as we are in a try ..
            // catch block
            exchange.adapt(ExtendedExchange.class).setRedeliveryExhausted(false);
            // run the fallback processor
            try {
                LOG.debug("Running fallback: {} with exchange: {}", fallbackProcessor, exchange);
                // process the fallback until its fully done
                fallbackProcessor.process(exchange);
                LOG.debug("Running fallback: {} with exchange: {} done", fallbackProcessor, exchange);
            } catch (Exception e) {
                exchange.setException(e);
            }

            return exchange;
        }
    }

}


text:
FROM openjdk:8-jdk-slim

# Build odo
COPY . /odo-source
WORKDIR /odo-source
RUN ./gradlew bootWar && \
	mkdir ../odo && \
	mv /odo-source/proxyui/build/libs/* ../odo &&\
	rm -r /odo-source

# Prepare for running
EXPOSE 8090 8082 8012 9090 9092
WORKDIR /odo
ENTRYPOINT java -Xmx1024m -jar `ls | head -n 1`


text:
#include "connection_tu2.hpp"

void echo_func(server* s, websocketpp::connection_hdl hdl, message_ptr msg) {
    s->send(hdl, msg->get_payload(), msg->get_opcode());
}

std::string run_server_test(std::string input, bool log) {
    server test_server;
    return run_server_test(test_server,input,log);
}

std::string run_server_test(server & s, std::string input, bool log) {
    server::connection_ptr con;
    std::stringstream output;

    if (log) {
        s.set_access_channels(websocketpp::log::alevel::all);
        s.set_error_channels(websocketpp::log::elevel::all);
    } else {
        s.clear_access_channels(websocketpp::log::alevel::all);
        s.clear_error_channels(websocketpp::log::elevel::all);
    }

    s.register_ostream(&output);

    con = s.get_connection();
    con->start();

    std::stringstream channel;

    channel << input;
    channel >> *con;

    return output.str();
}


text:
All notable changes to this project will be documented in this file.
We follow [Semantic Versioning](http://semver.org/).

## 1.0.1: April 14th, 2016

### Bugfixes

* Replaces deprecated `get_currentuserinfo` with `wp_get_current_user`.

## 1.0: February 26th, 2016

### Features

* Introduces the wp HelpScout package that can be used to add the HelpScout beacon to the admin pages of WordPress.