text:
	#region FilteredColumns
	// Used by CSLA Objects                                                            Guid
	public bool IsGuid(IColumn column){
		return(column.LanguageType=="timestamp");}
	public ArrayList Guid(IColumns columns){
		return FilteredColumns(columns,new Filter(IsGuid));}
	// Used in CSLA Business Objects                                                   AutoKey
	public bool AutoKey(IColumn column){
		return(column.IsAutoKey);}
	public ArrayList AutoKey(IColumns columns){
		return FilteredColumns(columns,new Filter(AutoKey));}
	public ArrayList AutoKey(IForeignKey fk){
		ArrayList l = new ArrayList();
		foreach(IColumn column in fk.ForeignTable.Columns){
			if(column.IsAutoKey && !IsIn(column,fk.ForeignColumns))l.Add(column);}
		return l;}
	// Used in CSLA Stored Procedures
	private ArrayList AutoKey(ITable tbl){
		return FilteredColumns(tbl.Columns,new Filter(AutoKey));}
	// Used in CSLA Stored Procedures                                                  Updatable
	public bool Updatable(IColumn column){
		return(!NotUpdatable(column));}
	private ArrayList Updatable(ITable tbl){
		return FilteredColumns(tbl.Columns,new Filter(Updatable));}
	// Used in CSLA Stored Procedures                                                  Not Updatable
	public bool NotUpdatable(IColumn column){
		return(column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed);}
	private ArrayList NotUpdatable(ITable tbl){
		return FilteredColumns(tbl.Columns,new Filter(NotUpdatable));}
	// Used in CSLA Stored Procedures                                                  PrimaryKey
	public bool PrimaryKey(IColumn column){
		return(column.IsInPrimaryKey);}
	private ArrayList PrimaryKey(ITable tbl){
		return FilteredColumns(tbl.Columns,new Filter(PrimaryKey));}
	// Used in CSLA Stored Procedures                                                  Insertable
	public bool Insertable(IColumn column){
		return(!NotInsertable(column));}
	private ArrayList Insertable(ITable tbl){
		return FilteredColumns(tbl.Columns,new Filter(Insertable));}
	// Used in CSLA Stored Procedures                                                  Not Insertable
	public bool NotInsertable(IColumn column){
		return(column.IsAutoKey || column.IsComputed);}
	private ArrayList NotInsertable(ITable tbl){
		return FilteredColumns(tbl.Columns,new Filter(NotInsertable));}
	// Used in CSLA Stored Procedures & CSLA Business Objects                          Computed
	public bool Computed(IColumn column){
		return(column.IsComputed);}
	private ArrayList Computed(ITable tbl){
		return FilteredColumns(tbl.Columns,new Filter(Computed));	}
	// Used in CSLA Stored Procedures                                                  Not TimeStamp
	public bool NotTimestamp(IColumn column){
		return(!Timestamp(column));}
	private ArrayList NotTimestamp(ITable tbl){
		return FilteredColumns(tbl.Columns,new Filter(NotTimestamp));}
	private ArrayList NotTimestamp(IColumns cols){
		return FilteredColumns(cols,new Filter(NotTimestamp));}
	// Used in CSLA Business Objects
	public bool IsRequired(IColumn column)
	{
		if(column.IsNullable) return false;
		if(!column.HasDefault) return true;
		// If it is the parent column it is required
		return IsParentColumn(column);
//		return false;
	}
//	public bool ForeignKey(IColumn column)
//	{
//		return(column.IsInForeignKey);
//	}
	// Used in CSLA Business Objects                                                   Automatic
	public bool IsAutomatic(IColumn column)
	{
		bool retval=column.Description.IndexOf("{auto}") >= 0;
		return retval;
	}
	// Used in CSLA Business Objects                                                   TimeStamp
	public bool Timestamp(IColumn column){
		return(column.DataTypeName=="timestamp");}
	public ArrayList IsTimestamp(IColumns columns){
		return FilteredColumns(columns,new Filter(Timestamp));}
	// Used in CSLA Stored Procedures and Business Objects
	public ArrayList FilteredColumns(IColumns columns,Filter f){
		ArrayList l = new ArrayList();
		foreach(IColumn column in columns)
		{
			if(f(column))l.Add(column);
		}
		return l;
	}
	// Used in CSLA Business Objects
	public ArrayList ExcludedColumns(IColumns columns,Filter f){
		ArrayList l = new ArrayList();
		foreach(IColumn column in columns)
		{
			if(!f(column))l.Add(column);
		}
		return l;
	}
	private int CountRequiredFields( IColumns Columns ){
		return Columns.Count - CountNullableFields( Columns );}
	private int CountNullableFields( IColumns Columns )
	{
		int i = 0;
		foreach( IColumn c in Columns )
		{
			if( c.IsNullable )
			{
				i++;
			}
		}
		return i;
	}

	private int CountUniqueFields( IColumns Columns )
	{
		int i = 0;
		foreach( IColumn c in Columns )
		{
			if( !c.IsNullable && c.IsInPrimaryKey )
			{
				i++;
			}
		}
		return i;
	}
	public ArrayList MakeList(IColumns columns)
	{
		ArrayList l = new ArrayList();
		foreach(IColumn column in columns)
		if(!column.IsAutoKey && !IsAutomatic(column) && !column.IsComputed)
				l.Add(column);
		return l;
	}
	public ArrayList MakeList4(IColumns columns)
	{
		ArrayList l = new ArrayList();
		foreach(IColumn column in columns)
		if((!column.IsAutoKey && !IsAutomatic(column) && !column.IsComputed ) &&
		 (column.HasDefault==false || column.ForeignKeys.Count != 0))
				l.Add(column);
		return l;
	}
	public ArrayList ReqList(IColumns columns)
	{
		ArrayList l = new ArrayList();
		foreach(IColumn column in columns)
			if(IsRequired(column) && !column.IsComputed && !column.IsAutoKey)
				l.Add(column);
		return l;
	}
	public ArrayList ReqListNoDefault(IColumns columns)
	{
		ArrayList l = new ArrayList();
		foreach(IColumn column in columns)
			if(IsRequired(column) && !column.IsComputed && !column.IsAutoKey && column.HasDefault)
				l.Add(column);
		return l;
	}
	public ArrayList MakeList2(IColumns columns)
	{
		ArrayList l = new ArrayList();
		foreach(IColumn column in columns)
		if(!column.IsAutoKey && !column.IsComputed)
				l.Add(column);
		return l;
	}
	public ArrayList MakeList3(IColumns columns)
	{
		ArrayList l = new ArrayList();
		foreach(IColumn column in columns)
		if(IsAutomatic(column))
				l.Add(column);
		return l;
	}
	public void BuildLists(IList cols,ref string sMakeListParamTypes, ref string sMakeListParams,
	  ref string sSetTmp, ref string sParentCheck)
	{
		string sep = "";
		string sepSet = "";
		string sPrefixType="";
		string sPrefix="";
		string sPrefixSet="";
		string sCheckSep = "if( ";
		sMakeListParamTypes = "";
		sMakeListParams = "";
		sSetTmp = "";
		sParentCheck="";
//		ArrayList parentCols = new ArrayList();
		foreach(IColumn col in cols)
		{
				sMakeListParamTypes += sep + FormatColumn("{!rtype} {!local}",col);
				sMakeListParams += sep + FormatColumn("{!local}",col);
				sSetTmp += sepSet + FormatColumn("\t\t\ttmp.{!memberprop} = {!local};",col);
				sep=", ";
				sepSet="\r\n";
				if(IsRelObj(col))  // If item is null, don't look it up
				{
					sParentCheck += sCheckSep + LocalName(RelObjProp(col)) + " != null ";
					sCheckSep = "|| ";
				}
		}
		if(sParentCheck != "")sParentCheck += ") ";
		sMakeListParamTypes = sPrefixType + sMakeListParamTypes;
		sMakeListParams = sPrefix + sMakeListParams;
		sSetTmp = sPrefixSet + sSetTmp;
		//sParentCheck=FormatColumns("{!rtype} {!local} = {autoseed};\r\n\t\t\tif (parent != null)\r\n\t\t\t{\r\n\t\t\t\t{!local} = parent;\r\n\t\t\t}\r\n\t\t\t",parentCols,"\r\n","");
		//sParentCheck="";
	}
	public bool SameList(IList lst1, IList lst2)
	{
		ArrayList l = new ArrayList();
		foreach(IColumn col in lst1)l.Add(col.Name);
		foreach(IColumn col in lst2)
			if(l.Contains(col.Name))l.Remove(col.Name);
			else return false;
		return l.Count ==0;
	}
	public string SameList2(IList lst1, IList lst2)
	{
		ArrayList l = new ArrayList();
		foreach(IColumn col in lst1)l.Add(col.Name);
		foreach(IColumn col in lst2)l.Remove(col.Name);
		string sList="";
		string sep="Difference: ";
		foreach(string ss in l){
			sList+=sep+ss;
			sep=", ";
		}
		return sList;
	}
	public bool SameTypes(IList lst1, IList lst2)
	{
		if(lst1.Count != lst2.Count) return false;
		for(int i=0;i<lst1.Count;i++)
		{
			IColumn col1 = (IColumn)(lst1[i]);
			IColumn col2 = (IColumn)(lst2[i]);
			if(CSLAType(col1)!=CSLAType(col2))
				return false;
		}
				return true;
	}
	public string FieldName(IColumn col)
	{
		return col.Table.Name + "." + col.Name;
	}
	public bool SameFields(IList lst1, IList lst2)
	{
		if(lst1.Count != lst2.Count) return false;
		for(int i=0;i<lst1.Count;i++)
		{
			IColumn col1 = (IColumn)(lst1[i]);
			IColumn col2 = (IColumn)(lst2[i]);
			if(FieldName(col1)!=FieldName(col2))
				return false;
		}
		return true;
	}
//	public ArrayList IsNotAutoKey(IColumns columns)
//	{
//		return ExcludedColumns(columns,new Filter(AutoKey));
//	}
//	public bool TypeString(IColumn column)
//	{
//		return(CSLAType(column)=="string");
//	}
	public bool HasDefault(IColumn column)
	{
		return column.HasDefault;
	}
	public ArrayList HasDefaults(IColumns columns)
	{
		return FilteredColumns(columns,new Filter(HasDefault));
	}
	public ArrayList HasDefaults(IForeignKey fk)
	{
		ArrayList l = new ArrayList();
		foreach(IColumn column in fk.ForeignTable.Columns)
		{
			if(column.HasDefault && !IsIn(column,fk.ForeignColumns))l.Add(column);
		}
		return l;
	}
	private string RelatedObject(IForeignKey fk, IColumn column){
		if(column.ForeignKeys.Count == 1){
			IForeignKey pk = column.ForeignKeys[0];
			string sObj = _nameSpace + "." + ClassName( pk.PrimaryTable );
			return FormatColumn(sObj + ".Get" + "({local})",column);
		}
		else
		{
			return FormatColumn("{local}",column);
		}
	}
	private string RelatedObjectType(IColumn column){
		if(column.ForeignKeys.Count == 1){
			IForeignKey pk = column.ForeignKeys[0];
			string sObj = ClassName( pk.PrimaryTable );
			return sObj + " " + LocalName(sObj);
		}
		else
		{
			return FormatColumn("{ctype} {local}",column);
		}
	}
	public string GetNewAlias2(IForeignKey fk,IForeignKey pk)
	{
		// First determine if there are more than one key linking two tables
		int iCount = 0;
		foreach(IForeignKey tk in fk.ForeignTable.ForeignKeys)
		{
//				WriteLine("fk {0} pk {1} pk.PrimaryTable.Name {2} pk.ForeignTable.Name {3} fk.ForeignTable.Name {4}",
//					fk.Name,pk.Name,pk.PrimaryTable.Name,pk.ForeignTable.Name,fk.ForeignTable.Name);

			if(tk.PrimaryTable == pk.PrimaryTable)iCount++;
		}
		if(iCount==0)return "";
		return pk.ForeignColumns[0].Name;
	}
	public string GetNewAlias(IForeignKey fk,IForeignKey pk)
	{
		// First determine if there are more than one key linking two tables
		int iCount = 0;
//		WriteLine("fk {0} fk.Primary {1} fk.Foreign {2}",fk.Name,fk.PrimaryTable.Name,fk.ForeignTable.Name);
//		WriteLine("  pk {0} pk.Primary {1} pk.Foreign {2}",pk.Name,pk.PrimaryTable.Name,pk.ForeignTable.Name);
		foreach(IForeignKey tk in fk.ForeignTable.ForeignKeys)
		{
			if(tk.ForeignTable == pk.ForeignTable && tk.PrimaryTable == pk.PrimaryTable){
//				WriteLine("    tk {0} tk.Primary {1} tk.Foreign {2}",tk.Name,tk.PrimaryTable.Name,tk.ForeignTable.Name);
				iCount++;
			}
		}
		if(iCount==1)return "";
//		WriteLine("iCount {0}",iCount);
		return pk.ForeignColumns[0].Name;
	}
	private string RelatedObjectType2(IForeignKey fk,IColumn column){
		if(column.ForeignKeys.Count == 1){
			IForeignKey pk = column.ForeignKeys[0];
			string sObj = ClassName( pk.PrimaryTable );
			//return sObj + " " + LocalName(sObj) + column.Name;
			return sObj + " " + LocalName(sObj) + GetNewAlias(fk,pk);
		}
		else
		{
			return FormatColumn("{ctype} {local}",column);
		}
	}
	private bool IsPrimaryKey(IColumn col)
	{
		return (col.IsInPrimaryKey && col.Table.PrimaryKeys.Count == 1);
	}
	private IForeignKey RelObjFK(IColumn col)
	{
		if(!col.IsComputed && !col.IsAutoKey && !IsPrimaryKey(col) && col.ForeignKeys.Count==1)
		{
			IForeignKey fk = col.ForeignKeys[0];
//			if(fk.PrimaryTable.Name != fk.ForeignTable.Name)
//			{
//			return (col.Name=="RangeID"?fk:null);
				return fk;
//			}
		}
		return null;
	}
	private bool IsRelObj(IColumn col)
	{
		if(col.Table.Name != _workingTable.Name && col.IsInPrimaryKey && col.Table.PrimaryKeys.Count ==1)
			return true;
		IForeignKey fk = RelObjFK(col);
		if(fk != null)
			return true;
		else
			return false;
	}
	private string RelObjType(IColumn col)
	{
		if(col.Table.Name != _workingTable.Name && col.IsInPrimaryKey && col.Table.PrimaryKeys.Count ==1)
			return ClassName( col.Table );
		IForeignKey fk = RelObjFK(col);
		if(fk != null)
			return ClassName( fk.PrimaryTable );
		else
			return CSLAType(col);
	}
	private string RelObjProp(IColumn col)
	{
		if(col.Table.Name != _workingTable.Name && col.IsInPrimaryKey && col.Table.PrimaryKeys.Count ==1)
				return "My" + ClassName( col.Table );
		IForeignKey fk = RelObjFK(col);
		if(fk != null)
			if(fk.PrimaryTable.Name == fk.ForeignTable.Name)
				return "My" + ParentName(fk) + GetNewAlias(fk,fk);
			else
				return "My" + ClassName( fk.PrimaryTable ) + GetNewAlias(fk,fk);
		else
			return PropertyName(col);
	}
	private string RelObjCol(IColumn col)
	{
		IForeignKey fk = RelObjFK(col);
		if(fk != null)
			return PropertyName(fk.PrimaryColumns[0]);
		else
			return PropertyName(col);
	}
	private string RelObjEmpty(IColumn col)
	{
		IForeignKey fk = RelObjFK(col);
		if(col.IsNullable)return "null";
		if(fk != null && fk.PrimaryTable.Name == fk.ForeignTable.Name)
			return MemberName(fk.PrimaryColumns[0]);
		if(CSLAType(col)=="string")return "null";
		return "0";
	}
	private string RelObjTypeCast(IColumn col)
	{
		IForeignKey fk = RelObjFK(col);
		if(col.IsNullable)return "(" + CSLAType(col,"") + ")";
		return "";
	}
	private ArrayList _TableStack = new ArrayList();
	private void PushTable(ITable tbl)
	{
		_TableStack.Add(_workingTable);
		_workingTable=tbl;
	}
	private void PopTable()
	{
		if(_TableStack.Count > 0)
		{
			_workingTable=(ITable) _TableStack[_TableStack.Count-1];
			_TableStack.RemoveAt(_TableStack.Count-1);
		}
	}
	private bool ForeignRequired(IForeignKey pk)
	{
		bool bRequired=true;
		foreach(IColumn col in pk.ForeignColumns)
			bRequired &= !col.IsNullable;
		return bRequired;
	}
	private bool ForeignPrimary(IForeignKey fk)
	{
		bool bPrimary=true;
		foreach(IColumn col in fk.ForeignColumns)
		{
			bPrimary &= col.IsInPrimaryKey;
		}
		return bPrimary;
	}
	public int FindColumn(IList cols, IColumn col)
	{
		for(int i=0;i<cols.Count;i++)
			if(((IColumn) cols[i]).Name==col.Name)
				return i;
		return -1;
	}
	public ArrayList FindUniqueChildren(IForeignKey fk){
		ArrayList retval = new ArrayList();
		foreach(IIndex ind in fk.ForeignTable.Indexes)
		{
			if(ind.Unique)
			{
				ArrayList uniqueColumns = new ArrayList();
				foreach(IColumn col in ind.Columns)
				{
					uniqueColumns.Add(col);
				}
				foreach(IColumn col in fk.ForeignColumns)
				{
					int ii = FindColumn(uniqueColumns,col);
					if(ii >= 0)
					{
						uniqueColumns.RemoveAt(ii);
					}
					else
					{
						uniqueColumns.Clear();
					}
				}
				if(uniqueColumns.Count > 0)// This is a uniqueIndex which includes the parent columns
				{
					//ShowColumns(uniqueColumns,4,"Unique Index " + ind.Name);
					retval.Add(uniqueColumns);
				}
			}
		}
		return retval;
	}
	public bool ContainsList(IList lst1, IList lst2)
	{
		foreach(IColumn col in lst2)
			if(FindColumn(lst1,col)<0)return false;
		return true;
	}
	public IList FindUnique(ArrayList lst, IList cols)
	{
		foreach(IList lstcols in lst)
		{
			if(ContainsList(cols,lstcols))return lstcols;
		}
		return null;
	}
	//public ArrayList zzFilteredColumnsAny(IColumns columns,Filter [] fs){
	//	ArrayList l = new ArrayList();
	//	foreach(IColumn column in columns)
	//	{
	//		bool check = false;
	//		foreach(Filter f in fs)check |= f(column);
	//		if(check)l.Add(column);
	//	}
	//	return l;
	//}
	//public ArrayList zzExcludedColumnsAny(IColumns columns,Filter [] fs){
	//	ArrayList l = new ArrayList();
	//	foreach(IColumn column in columns)
	//	{
	//		bool check = false;
	//		foreach(Filter f in fs)check |= f(column);
	//		if(!check)l.Add(column);
	//	}
	//	return l;
	//}
	#endregion


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>galleries | Yao He's Awesome Site</title>
<link href="../assets/css/all-nocdn.css" rel="stylesheet" type="text/css">
<link rel="alternate" type="application/rss+xml" title="RSS" href="../rss.xml">
<link rel="canonical" href="https://stephen0921.github.io/galleries/">
<link rel="alternate" type="application/rss+xml" title="RSS" href="rss.xml">

Skip to main content

                        Yao He's Awesome Site

            ☰

Archive

Tags

RSS feed

galleries

galleries

 Nikola Tesla

        <button class="btn btn-fab btn-raised btn-material-green btn-footer" data-toggle="modal" data-target="#footer-dialog">

        </button>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Yao He's Awesome Site credits

                    Contents © 2018         Yao He - Powered by         Nikola

                <button class="btn btn-primary" data-dismiss="modal">Ok</button>

redpajama_set_name: RedPajamaGithub


text:
import { Router } from "express";
import { Instance } from "multer";
import { ModelValidationHandler, ValidationGroup } from "../../app/index";
import { AuthValidationHandler } from "../../auth/index";
import { SocoboUserRoleType } from "../../socobouser/index";
import { Recipe, RecipeCategory, RecipeCategoryHandler, RecipeMiddleware } from "../index";

export class RecipeCategoryRoute {

  constructor (
    private _router: Router,
    private _recipeCategoryHandler: RecipeCategoryHandler,
    private _authValidationHandler: AuthValidationHandler,
    private _modelValidationHandler: ModelValidationHandler) {}

  public createRoutes (): Router {

    this._router.get("/",
      this._authValidationHandler.checkToken,
      this._recipeCategoryHandler.getAll);

    this._router.get("/:id",
      this._authValidationHandler.checkToken,
      this._recipeCategoryHandler.getById);

    this._router.post("/",
      this._authValidationHandler.checkToken,
      this._authValidationHandler.checkUser(SocoboUserRoleType.Admin),
      this._modelValidationHandler.validateObject(new RecipeCategory(), [ValidationGroup.RECIPE]),
      this._recipeCategoryHandler.save);

    this._router.put("/:id",
      this._authValidationHandler.checkToken,
      this._authValidationHandler.checkUser(SocoboUserRoleType.Admin),
      this._modelValidationHandler.validateObject(new RecipeCategory(), [ValidationGroup.RECIPE]),
      this._recipeCategoryHandler.update);

    this._router.delete ("/:id",
      this._authValidationHandler.checkToken,
      this._authValidationHandler.checkUser(SocoboUserRoleType.Admin),
      this._recipeCategoryHandler.delete);

    return this._router;
  }
}


text:
package thrift

import (
	"context"
	"testing"
)

type counter struct {
	count int
}

func (c *counter) incr() {
	c.count++
}

func newCounter(t *testing.T) *counter {
	c := counter{}
	if c.count != 0 {
		t.Fatal("Unexpected initial count.")
	}
	return &c
}

func testProcessorMiddleware(c *counter) ProcessorMiddleware {
	return func(name string, next TProcessorFunction) TProcessorFunction {
		return WrappedTProcessorFunction{
			Wrapped: func(ctx context.Context, seqId int32, in, out TProtocol) (bool, TException) {
				c.incr()
				return next.Process(ctx, seqId, in, out)
			},
		}
	}
}

func testClientMiddleware(c *counter) ClientMiddleware {
	return func(next TClient) TClient {
		return WrappedTClient{
			Wrapped: func(ctx context.Context, method string, args, result TStruct) (ResponseMeta, error) {
				c.incr()
				return next.Call(ctx, method, args, result)
			},
		}
	}
}

func TestWrapProcessor(t *testing.T) {
	name := "test"
	processor := &mockWrappableProcessor{
		ProcessorFuncs: map[string]TProcessorFunction{
			name: WrappedTProcessorFunction{
				Wrapped: func(ctx context.Context, seqId int32, in, out TProtocol) (bool, TException) {
					return true, nil
				},
			},
		},
	}
	c := newCounter(t)
	ctx := setMockWrappableProcessorName(context.Background(), name)
	wrapped := WrapProcessor(processor, testProcessorMiddleware(c))
	wrapped.Process(ctx, nil, nil)
	if c.count != 1 {
		t.Fatalf("Unexpected count value %v", c.count)
	}
}

func TestWrapTMultiplexedProcessor(t *testing.T) {
	name := "test"
	processorName := "foo"
	c := newCounter(t)
	processor := &TMultiplexedProcessor{}
	processor.RegisterDefault(&mockWrappableProcessor{
		ProcessorFuncs: map[string]TProcessorFunction{
			name: WrappedTProcessorFunction{
				Wrapped: func(ctx context.Context, seqId int32, in, out TProtocol) (bool, TException) {
					return true, nil
				},
			},
		},
	})
	processor.RegisterProcessor(processorName, &mockWrappableProcessor{
		ProcessorFuncs: map[string]TProcessorFunction{
			name: WrappedTProcessorFunction{
				Wrapped: func(ctx context.Context, seqId int32, in, out TProtocol) (bool, TException) {
					return true, nil
				},
			},
		},
	})
	wrapped := WrapProcessor(processor, testProcessorMiddleware(c))
	ctx := setMockWrappableProcessorName(context.Background(), name)
	in := NewStoredMessageProtocol(nil, name, 1, 1)
	wrapped.Process(ctx, in, nil)
	if c.count != 1 {
		t.Fatalf("Unexpected count value %v", c.count)
	}

	in = NewStoredMessageProtocol(nil, processorName+MULTIPLEXED_SEPARATOR+name, 1, 1)
	wrapped.Process(ctx, in, nil)
	if c.count != 2 {
		t.Fatalf("Unexpected count value %v", c.count)
	}
}

func TestWrapClient(t *testing.T) {
	client := WrappedTClient{
		Wrapped: func(ctx context.Context, method string, args, result TStruct) (ResponseMeta, error) {
			return ResponseMeta{}, nil
		},
	}
	c := newCounter(t)
	wrapped := WrapClient(client, testClientMiddleware(c))
	wrapped.Call(context.Background(), "test", nil, nil)
	if c.count != 1 {
		t.Fatalf("Unexpected count value %v", c.count)
	}
}


text:
import { convertDate } from './Date.utils';

describe('DateWidget utils', () => {
	describe('convertDate', () => {
		it('should convert date to iso format', () => {
			const schema = {
				format: 'iso-datetime',
			};
			const value = new Date(Date.UTC(2019, 8, 30));

			const converted = convertDate(value, '', schema);
			expect(converted).toBe('2019-09-30T00:00:00.000Z');
		});
		it('should convert date to timestamp', () => {
			const schema = {
				type: 'number',
			};
			const value = new Date(Date.UTC(2019, 8, 30));

			const converted = convertDate(value, '', schema);
			expect(converted).toBe(1569801600000);
		});
		it('should return string of date when no format specified', () => {
			const value = new Date(Date.UTC(2019, 8, 30));

			const converted = convertDate(value, '2019-09-30', {});
			expect(converted).toBe('2019-09-30');
		});
	});
});


text:
using System.Configuration;

namespace WebsitePanel.WebDav.Core.Config.WebConfigSections
{
    [ConfigurationCollection(typeof(OwaSupportedBrowsersElement))]
    public class OwaSupportedBrowsersElementCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new OwaSupportedBrowsersElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((OwaSupportedBrowsersElement)element).Browser;
        }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

  <link rel="stylesheet" href="<?=base_url().'assets/user/'?>select2/select2.min.css">

<?php echo $title;?>

            <form role="form" method="post" action="<?=base_url().'user_profile/update_info/'?>" enctype="multipart/form-data">
            <?=validation_errors()?>
                <input type="hidden" name='id' value="<?php echo $user_detail['id'];?>">
    	        <input type="hidden" name='user_type' value="<?php echo $user_detail['user_type'];?>">

    	                First Name

    	                    <input type="text" name="f_name" class="form-control"  placeholder="Enter First Name" value="<?=set_value('f_name',$user_detail['f_name']);?>"/>
    	                    <?=form_error('f_name')?>

                        Last Name

                            <input type="text" name="l_name" class="form-control" placeholder="Enter Last Name" value="<?=set_value('l_name',$user_detail['l_name']);?>"/>
                         <?= form_error('l_name') ?>

                        Gender

                                    <input type="radio" value="1" name="gender" <?php if(set_value('gender',$user_detail['gender'])=='1'){echo "checked";}?> >Male

                                    <input type="radio" value="0" name="gender" <?php if(set_value('gender',$user_detail['gender'])=='0'){echo "checked";}?> >Female

                                <?= form_error('gender') ?>

                        Image

                            <?php if($user_detail['image']!="") { ?>
                                <img src="<?=base_url()?>uploads/user/images/<?=$user_detail['image']?>" style="height:inherit;width:inherit;" />
                            <?php
                            }
                            ?>
                            <input type="file" name="image">
                            <input type="hidden" name="prev_image" value="<?=$user_detail['image']?>" />
                            <?= form_error('image') ?>

                        Phone

                           <input type="text" name="phone" class="form-control input-sm" value="<?=set_value('phone',$user_detail['phone']);?>"/>
                        <?= form_error('phone') ?>

                        Date of birth

                            <input type="text" name="dob_estd" id="datepicker" class="form-control input-sm" value="<?=set_value('dob_estd',$user_detail['dob_estd']);?>"/>
                        <?= form_error('dob_estd') ?>

                        Address

                            <input type="text" id="address" name="address" value="<?php echo set_value('address',$user_detail['address']);?>" class="form-control input-sm"></input>
                            <?= form_error('address') ?>

                        Marital Status

                                <input type="radio" value="1" name="marital_status" <?php if(set_value('marital_status', $user_detail['marital_status'])=='0'){echo "checked";}?> >Unmarried

                                <input type="radio" value="0" name="marital_status" <?php if(set_value('marital_status', $user_detail['marital_status'])=='1'){echo "checked";}?> >Married

                            <?= form_error('marital_status') ?>

                <?php
                    $categories = $this->helper_model->get_category();
                ?>

                        Please select job categories that you'd like to receive notification for.

                            <select style="width:120%" class="form-control select2" name="job_category[]" multiple="multiple" data-placeholder="Select job categories" style="width: 100%;">
                            <?php
                                foreach ($categories as $category) {
                             ?>
                                <option value="<?=$category['id']?>" <?php if(in_array($category['id'], $user_categories)){echo 'selected';} ?>><?=$category['name']?></option>
                          <?php } ?>
                            </select>
                            <?= form_error('job_category[]') ?>

                <?php
                    $tags = $this->helper_model->get_tags();
                ?>

                        Please select keywords that best describe the skills you have.

                            <select style="width:120%;" class="form-control select2" name="tag[]" multiple="multiple" data-placeholder="Select job categories" style="width: 100%;">
                            <?php
                                foreach ($tags as $tag) {
                             ?>
                                <option value="<?=$tag['id']?>" <?php if(in_array($tag['id'], $user_tags)){echo 'selected';} ?>><?=$tag['name']?></option>
                          <?php } ?>
                            </select>
                            <?= form_error('tags[]') ?>

                        Newsletter Subscription

                            <input type="hidden" name="newsletter_subscription" value="0" />
                            <input type="checkbox" name="newsletter_subscription" value="1" <?php if(set_value('newsletter_subscription',$user_detail['newsletter_subscription'])=='1'){echo "checked";}?> />
                            Would you like to receive our newsletter?

                        <input type="submit" value="Update" class="btn btn-primary btn-sm">

        </form>


text:
package org.jbpm.ruleflow.core.factory;

import org.jbpm.process.instance.impl.Action;
import org.jbpm.ruleflow.core.RuleFlowNodeContainerFactory;
import org.jbpm.workflow.core.DroolsAction;
import org.jbpm.workflow.core.Node;
import org.jbpm.workflow.core.NodeContainer;
import org.jbpm.workflow.core.impl.DroolsConsequenceAction;
import org.jbpm.workflow.core.node.ActionNode;

/**
 *
 */
public class ActionNodeFactory extends NodeFactory {

    public ActionNodeFactory(RuleFlowNodeContainerFactory nodeContainerFactory, NodeContainer nodeContainer, long id) {
        super(nodeContainerFactory, nodeContainer, id);
    }

    protected Node createNode() {
        return new ActionNode();
    }

    protected ActionNode getActionNode() {
        return (ActionNode) getNode();
    }

    public ActionNodeFactory name(String name) {
        getNode().setName(name);
        return this;
    }

    public ActionNodeFactory action(String dialect, String action) {
        getActionNode().setAction(new DroolsConsequenceAction(dialect, action));
        return this;
    }

    //
    // Allow the creation of programmatic actions that implement org.jbpm.process.instance.impl.Action interface.
    // I just want to write simple classes to execute arbitrary logic without having to use a file.
    //
    public ActionNodeFactory action(Action action) {
      DroolsAction droolsAction = new DroolsAction();
      droolsAction.setMetaData("Action",action);
      getActionNode().setAction(droolsAction);
      return this;
  }
}


text:
import 'whatwg-fetch';

// fetch URL
let _url = '';

// fetch options
let _options = {};

// retry delay milliseconds
let _retryDelay = 0;

// timeout for total retry
let _timeout = 0;

// whether timeout occurred
let _isTimeout = false;

// whether fetch succeeded
let _isResolve = false;

// retry fetch task ID
let _retryFetchTaskId = null;

/**
 * fetch wrapper
 *
 * @param  {String} url     URL
 * @param  {Object} options extended fetch option
 * @return {Promise}        fetch result
 *
 * # usage
 *
 * import fetch from 'js/utils/FetchRetry';
 *
 * fetch(url, {
 *   retries: 3,        // retry count
 *   retryDelay: 1000,  // retry delay milliseconds
 *   timeout: 3000,     // timeout for total retry
 * })
 * .then((response) => {
 * })
 */
function wrappedFetch(url, options) {
  _url = url;
  _options = options;
  const retries = options && options.retries ? options.retries : 0;
  _retryDelay = options && options.retryDelay ? options.retryDelay : 0;
  _timeout = options && options.timeout ? options.timeout : 0;

  // delete extended options not in fetch
  delete _options.retries;
  delete _options.retryDelay;
  delete _options.timeout;

  return new Promise((resolve, reject) => {
    setTimeoutAllProcesses(reject);
    retryFetch(retries, resolve);
  });
}

/**
 * set task for time out total retrying
 * @param {Promise.reject} reject reject
 */
function setTimeoutAllProcesses(reject) {
  let timeoutId;
  if (_timeout > 0) {
    timeoutId = setTimeout(() => {
      if (_isResolve) {
        clearTimeout(timeoutId);
        return;
      }
      _isTimeout = true;
      if (_retryFetchTaskId) clearTimeout(_retryFetchTaskId);
      reject(new Error('fetch timeout'));
    }, _timeout);
  }
}

/**
 * retry fetch
 * @param  {Number} retries retry count
 * @param  {Promise.resolve} resolve resolve
 * @return {Promise}         Promise
 */
function retryFetch(retries, resolve) {
  fetch(_url, _options)
    .then((res) => {
      if (!res.ok && retries > 0 && !_isTimeout) {
        _retryFetchTaskId = setTimeout(() => {
          retryFetch(retries - 1, resolve);
        }, _retryDelay);
        return;
      }
      _isResolve = true;
      resolve(res);
    });
}

export default wrappedFetch;


text:
package decorator.beverage;

/**
 * @author Marcin Przygoda
 */
public class Juice implements Beverage {
	@Override
	public String getStatus() {
		return "Juice";
	}
}


text:
package org.rsna.ctp.stdstages.storage;

import org.apache.log4j.Logger;
import org.rsna.server.HttpRequest;
import org.rsna.server.HttpResponse;
import org.rsna.server.Path;
import org.rsna.server.User;
import org.rsna.server.Users;
import org.rsna.servlets.Servlet;
import org.rsna.util.XmlUtil;
import org.w3c.dom.Document;

import java.io.File;

/**
 * A Servlet which provides web access to the studies stored in a FileStorageService.
 */
public class GuestListServlet extends Servlet {

	static final Logger logger = Logger.getLogger(GuestListServlet.class);

	/**
	 * Static init method to set up the root directory..
	 * This method copies the CSS and JS files needed
	 * by the viewer into the root directory.
	 */
	public static void init(File root) {
		root.mkdirs();
	}

	/**
	 * Construct a GuestListServlet.
	 * @param root the root directory of the server.
	 * @param context the path identifying the servlet.
	 */
	public GuestListServlet(File root, String context) {
		super(root, context);
	}

	/**
	 * The GET handler: return a page with a form displaying
	 * the guest list for the current user and providing editing
	 * capability. If the user has the proxy privilege, allow
	 * the user to manage a different user's guest list.
	 * @param req the request object
	 * @param res the response object
	 */
	@Override
  public void doGet(HttpRequest req, HttpResponse res) {

		//Get the user
		User user = req.getUser();
		if (user == null) {
			res.setResponseCode(403);
			res.send();
			return;
		}

		//Get the Users instance.
		Users users = Users.getInstance();

		//See if this is a proxy.
		Path path = new Path(req.getPath());
		if ((path.length() > 1) && user.hasRole("proxy")) {
			user = users.getUser(path.element(1));
			//If the proxied user doesn't exist, stay with the current user.
			if (user == null) user = req.getUser();
		}

		//Get the FileSystemManager.
		FileSystemManager fsm = FileSystemManager.getInstance(root);
		if (fsm == null) {
			//There is no FileSystemManager for this root, return a 404.
			res.setResponseCode(404);
			res.send();
		}

		//Get the FileSystem corresponding to the user
		FileSystem fs = fsm.getFileSystem(user.getUsername());
		if (fs == null) {
			//There is no FileSystem for this user, return a 404.
			res.setResponseCode(404);
			res.send();
		}

		try {
			//Get the guest list for this FileSystem
			Document guestsXML = fs.getGuestList().getXML();

			//Get a String containing the usernames of users who have the guest role and
			//another String containing all the usernames.
			//
			//It would be nicer to pass an XML document containing all the users
			//and let the XSL do all the work, but it turns out that the XSL processor
			//in Java has a bug which causes it to get a conversion error when a document
			//is passed as a param. It would be possible to get around this by including
			//the Xalan release as a class library with CTP, but that would triple the size
			//of the download, so I decided to simply provide Strings instead.
			String[] usernames = users.getUsernames();
			StringBuffer allUsers = new StringBuffer();
			StringBuffer guestUsers = new StringBuffer();
			for (int i=0; i<usernames.length; i++) {
				User u = users.getUser(usernames[i]);
				allUsers.append(u.getUsername() + ";");
				if ((u != null) && u.hasRole("guest")) {
					guestUsers.append(u.getUsername() + ";");
				}
			}

			//Generate the page
			File xslFile = new File("pages/guest-manager.xsl");
			Object[] params = new Object[] {
				"context",		context,
				"all-users",	allUsers.toString(),
				"guest-users",	guestUsers.toString(),
				"user",			user.getUsername(),
				"proxy",		(req.getUser().hasRole("proxy") ? "yes" : "no")
			};
			String page = XmlUtil.getTransformedText(guestsXML, xslFile, params);
			res.write(page);
			res.setContentType("html");
			res.disableCaching();
			res.send();
		}
		catch (Exception e) {
			logger.warn("Unable to make the page",e);
			res.setResponseCode(500);
			res.send();
		}
	}

	/**
	 * The POST handler: update the guest list and return a page
	 * allowing further updates.
	 * @param req the request object
	 * @param res the response object
	 */
	@Override
  public void doPost(HttpRequest req, HttpResponse res) {

		//Require that the post came from this servlet.
		if (!req.isReferredFrom(context)) {
			res.setResponseCode(HttpResponse.forbidden);
			res.send();
			return;
		}

		//Update the guest list from the form

		//Get the user
		User user = req.getUser();
		if (user == null) {
			res.setResponseCode(HttpResponse.forbidden);
			res.send();
			return;
		}

		//Get the Users instance.
		Users users = Users.getInstance();

		//See if this is a proxy.
		Path path = new Path(req.getPath());
		if ((path.length() > 1) && user.hasRole("proxy")) {
			user = users.getUser(path.element(1));
			//If the proxied user doesn't exist, stay with the current user.
			if (user == null) user = req.getUser();
		}

		//Get the FileSystemManager.
		FileSystemManager fsm = FileSystemManager.getInstance(root);
		if (fsm == null) {
			//There is no FileSystemManager for this root, return a 404.
			res.setResponseCode(HttpResponse.notfound);
			res.send();
		}

		//Get the FileSystem corresponding to the user
		FileSystem fs = fsm.getFileSystem(user.getUsername());
		if (fs == null) {
			//There is no FileSystem for this user, return a 404.
			res.setResponseCode(HttpResponse.notfound);
			res.send();
		}

		//Get the guest list for this FileSystem
		GuestList guestList = fs.getGuestList();

		//Walk through the parameters and update the guestList.
		int i = 1;
		String username;
		String checkbox;
		while ( (username = req.getParameter("un"+i)) != null) {
			checkbox = req.getParameter("cb"+i);
			if ((checkbox == null) || !checkbox.equals("yes")) guestList.remove(username);
			i++;
		}
		username = req.getParameter("addguest");
		if ( (username != null) && !username.trim().equals("")) {
			User guestUser = users.getUser(username);
			if ((guestUser != null) && guestUser.hasRole("guest")) {
				guestList.add(username);
			}
		}

		//Return the current page
		doGet(req,res);
	}

}


text:
title: Serving Certificates, Authentication, and Authorization
layout: docwithnav
---

This document outlines how the service catalog handles authentication.

The service catalog Helm chart's defaults paired with most Kubernetes
distributions will automatically set up all authentication details correctly.
This documentation, therefore, exists for the benefit of
those who wish to develop and advanced understanding of this topic and those
who have a need to address various outlying scenarios.

## Certificates Overview

Certificates are used for parties to identify themselves to one another.

CA (Certificate Authority) certificates are used to delegate trust.
Whenever something trusts the CA, it can trust any certificates *signed*
by the CA.

If a certificate is not signed by a separate CA, it is instead
*self-signed*. A self-signed certificate must either be trusted directly
(instead of being trusted indirectly by trusting a CA), or not trusted at
all.  Generally, our client CA certificates will be self-signed, since
they represent the "root" of our trust relationship: clients must
inherently trust the CA.

The service catalog Helm chart automatically generates new CA.
This CA signs "serving" certificates, which are used to encrypt communication
over HTTPS.There is generally no need to override this.

### Generating certificates

In the common case  CA certificate referenced above already
exist as part of the installation.

In case you need to generate any of the CA certificate pairs mentioned
above yourself, the Kubernetes documentation has [detailed
instructions](https://kubernetes.io/docs/admin/authentication/#creating-certificates)
on how to create certificates several different ways.

Service Catalog Helm chart uses build-in [Sprig's](https://github.com/Masterminds/sprig) functions to generate
all needed certificates used by Webhook Server:
```
{{- $ca := genCA "service-catalog-webhook-ca" 3650 }}
{{- $cn := printf "%s-webhook" (include "fullname" .) }}
{{- $altName1 := printf "%s.%s" $cn .Release.Namespace }}
{{- $altName2 := printf "%s.%s.svc" $cn .Release.Namespace }}
{{- $cert := genSignedCert $cn nil (list $altName1 $altName2) 3650 $ca }}
```

## Authentication

CRDs always use the same authentication and authorization as the built-in resources of your API Server.
If you use RBAC for authorization, most RBAC roles will not grant access to the new resources (except the cluster-admin role or any role created with wildcard rules).
You'll need to explicitly grant access to the new resources.

### Client Certificate Authentication

Client certificate authentication authenticates clients who connect using
certificates signed by a given CA (as specified by the *client CA
certificate*).  This same mechanism is also generally used by the main
Kubernetes API server.

Generally, the default admin user in a cluster connects with client
certificate authentication.  Additionally, off-cluster non-human clients
often use client certificate authentication.

See the [x509 client
certificates](https://kubernetes.io/docs/admin/authentication/#x509-client-certs)
section of the Kubernetes documentation for more information.


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.webapps.launchpad;

import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import org.chromium.ui.modelutil.PropertyKey;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.modelutil.PropertyModelChangeProcessor.ViewBinder;

/**
 *  A {@link ViewBinder} responsible for gluing {@link AppManagementMenuHeaderProperties} to the
 *  view.
 */
class AppManagementMenuHeaderViewBinder implements ViewBinder<PropertyModel, View, PropertyKey> {
    @Override
    public void bind(PropertyModel model, View view, PropertyKey propertyKey) {
        if (propertyKey == AppManagementMenuHeaderProperties.TITLE) {
            TextView titleText = view.findViewById(R.id.menu_header_title);
            titleText.setText(model.get(AppManagementMenuHeaderProperties.TITLE));
        } else if (propertyKey == AppManagementMenuHeaderProperties.URL) {
            TextView urlText = view.findViewById(R.id.menu_header_url);
            urlText.setText(model.get(AppManagementMenuHeaderProperties.URL));
        } else if (propertyKey == AppManagementMenuHeaderProperties.ICON) {
            Bitmap bitmap = model.get(AppManagementMenuHeaderProperties.ICON);
            if (bitmap != null) {
                ImageView imageView = view.findViewById(R.id.menu_header_image);
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}


text:
package io.hekate.core.service.internal;

import io.hekate.core.Hekate;
import io.hekate.core.HekateConfigurationException;
import io.hekate.core.HekateException;
import io.hekate.core.ServiceInfo;
import io.hekate.core.report.ConfigReporter;
import io.hekate.core.service.DefaultServiceFactory;
import io.hekate.core.service.InitializationContext;
import io.hekate.core.service.Service;
import io.hekate.core.service.ServiceFactory;
import io.micrometer.core.instrument.MeterRegistry;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.StampedLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet;

public class ServiceManager {
    private static final Logger log = LoggerFactory.getLogger(ServiceManager.class);

    private static final boolean DEBUG = log.isDebugEnabled();

    private static final Service NULL_SERVICE = new Service() {
        // No-op.
    };

    private final String nodeName;

    private final Hekate container;

    private final ServiceInitOrder initOrder = new ServiceInitOrder();

    private final List<ServiceHandler> handlers = new ArrayList<>();

    private final Map<Class<? extends Service>, Service> lookupCache = new HashMap<>();

    private final StampedLock lookupLock = new StampedLock();

    private final List<? extends Service> builtInServices;

    private final List<ServiceFactory<?>> factories;

    private final List<Class<? extends Service>> coreServices;

    private final MeterRegistry metrics;

    private Map<String, ServiceInfo> servicesInfo;

    private Set<Class<? extends Service>> serviceTypes;

    public ServiceManager(
        String nodeName,
        Hekate container,
        MeterRegistry metrics,
        List<? extends Service> builtInServices,
        List<Class<? extends Service>> coreServices,
        List<? extends ServiceFactory<?>> factories
    ) {
        this.nodeName = nodeName;
        this.container = container;
        this.metrics = metrics;
        this.builtInServices = builtInServices;
        this.coreServices = coreServices;
        this.factories = new ArrayList<>(factories);
    }

    public String nodeName() {
        return nodeName;
    }

    public Hekate container() {
        return container;
    }

    public void instantiate() {
        if (DEBUG) {
            log.debug("Instantiating services...");
        }

        // Register built-in services.
        builtInServices.forEach(this::registerService);

        // Instantiate services.
        for (ServiceFactory<? extends Service> factory : factories) {
            if (DEBUG) {
                log.debug("Creating new service [factory={}]", factory);
            }

            registerService(factory.createService());
        }

        // Ensure that all core services are registered.
        coreServices.forEach(this::findOrCreateService);

        // Resolve dependencies.
        ServiceDependencyContext depCtx = new ServiceDependencyContext(this);

        // Use index-based iteration since new handlers can be added dynamically during dependencies resolution.
        for (int i = 0; i < handlers.size(); i++) {
            ServiceHandler handler = handlers.get(i);

            handler.resolve(depCtx);
        }

        // Make sure that all services are registered to initialization order.
        handlers.forEach(initOrder::register);

        // Configure services.
        ServiceConfigurationContext cfgCtx = new ServiceConfigurationContext(container, this);

        handlers.forEach(handler ->
            handler.configure(cfgCtx)
        );

        servicesInfo = unmodifiableMap(cfgCtx.servicesInfo());

        serviceTypes = unmodifiableSet(depCtx.serviceTypes());

        if (DEBUG) {
            log.debug("Instantiated services.");
        }
    }

    public void preInitialize(InitializationContext ctx) throws HekateException {
        if (DEBUG) {
            log.debug("Pre-initializing services [context={}]", ctx);
        }

        // Initialize services.
        for (ServiceHandler handler : initOrder.order()) {
            handler.preInitialize(ctx);
        }

        if (DEBUG) {
            log.debug("Pre-initialized services.");
        }
    }

    public void initialize(InitializationContext ctx) throws HekateException {
        if (DEBUG) {
            log.debug("Initializing services [context={}]", ctx);
        }

        // Initialize services.
        for (ServiceHandler handler : initOrder.order()) {
            handler.initialize(ctx);
        }

        if (DEBUG) {
            log.debug("Initialized services.");
        }
    }

    public void postInitialize(InitializationContext ctx) throws HekateException {
        if (DEBUG) {
            log.debug("Post-initializing services [context={}]", ctx);
        }

        // Initialize services.
        for (ServiceHandler handler : initOrder.order()) {
            handler.postInitialize(ctx);
        }

        if (DEBUG) {
            log.debug("Post-initialized services.");
        }
    }

    public void configReport(ConfigReporter reporter) {
        for (ServiceHandler handler : initOrder.order()) {
            handler.configReport(reporter);
        }
    }

    public void preTerminate() {
        if (DEBUG) {
            log.debug("Pre-terminating services...");
        }

        List<ServiceHandler> order = initOrder.order();

        // Terminate in reversed order.
        for (int i = order.size() - 1; i >= 0; i--) {
            order.get(i).preTerminate();
        }

        if (DEBUG) {
            log.debug("Pre-terminated services.");
        }
    }

    public void terminate() {
        if (DEBUG) {
            log.debug("Terminating services...");
        }

        List<ServiceHandler> order = initOrder.order();

        // Terminate in reversed order.
        for (int i = order.size() - 1; i >= 0; i--) {
            order.get(i).terminate();
        }

        if (DEBUG) {
            log.debug("Terminated services.");
        }
    }

    public void postTerminate() {
        if (DEBUG) {
            log.debug("Post-terminating services...");
        }

        List<ServiceHandler> order = initOrder.order();

        // Terminate in reversed order.
        for (int i = order.size() - 1; i >= 0; i--) {
            order.get(i).postTerminate();
        }

        if (DEBUG) {
            log.debug("Post-terminated services.");
        }
    }

    public <T extends Service> T findService(Class<T> type) {
        Service service;

        // Try to find with the read lock.
        long readLock = lookupLock.readLock();

        try {
            service = lookupCache.get(type);
        } finally {
            lookupLock.unlock(readLock);
        }

        if (service == null) {
            // Try to resolve service while holding the write lock.
            long writeLock = lookupLock.writeLock();

            try {
                // Double check that service was not registered while we were obtaining the write lock.
                service = lookupCache.get(type);

                if (service == null) {
                    ServiceHandler handler = findServiceDirect(type);

                    if (handler == null) {
                        service = NULL_SERVICE;
                    } else {
                        service = handler.service();
                    }

                    lookupCache.put(type, service);
                }
            } finally {
                lookupLock.unlock(writeLock);
            }

        }

        return service != NULL_SERVICE ? type.cast(service) : null;
    }

    public Map<String, ServiceInfo> getServicesInfo() {
        return servicesInfo;
    }

    public Set<Class<? extends Service>> getServiceTypes() {
        return serviceTypes;
    }

    public List<ServiceHandler> getHandlers() {
        return handlers;
    }

    public MeterRegistry metrics() {
        return metrics;
    }

    ServiceHandler findServiceDirect(Class<? extends Service> type) {
        for (ServiceHandler handler : handlers) {
            Object service = handler.service();

            if (type.isAssignableFrom(service.getClass())) {
                return handler;
            }
        }

        return null;
    }

    ServiceHandler findOrCreateService(Class<? extends Service> type) {
        ServiceHandler handler = findServiceDirect(type);

        if (handler == null && type.isAnnotationPresent(DefaultServiceFactory.class)) {
            Class<? extends ServiceFactory<?>> factoryType = type.getAnnotation(DefaultServiceFactory.class).value();

            if (DEBUG) {
                log.debug("Instantiating service with default factory [type={}, factory={}]", type.getName(), factoryType.getName());
            }

            try {
                ServiceFactory<?> factory = factoryType.getConstructor().newInstance();

                Service service = factory.createService();

                if (!type.isAssignableFrom(service.getClass())) {
                    throw new HekateConfigurationException("Invalid usage of @" + DefaultServiceFactory.class.getName() + " annotation. "
                        + "Service factory was expected to create an instance of " + type.getName() + " but created an instance of "
                        + service.getClass().getName());
                }

                handler = registerService(service);
            } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                throw new HekateConfigurationException("Failed to instantiate service with default factory "
                    + "[service=" + type.getName() + ", factory=" + factoryType.getName() + ']', e);
            }
        }

        return handler;
    }

    private ServiceHandler registerService(Service service) {
        ServiceHandler handler = new ServiceHandler(service, initOrder);

        handlers.add(handler);

        return handler;
    }
}