text:
package com.yy.cloud.core.assess.data.repositories;

import com.yy.cloud.core.assess.data.domain.PerAssessCategory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.List;

/**
 * Function: TODO ADD FUNCTION.

 * Reason:	 TODO ADD REASON.

 * Date:     11/11/17 5:20 PM

 *
 * @author chenxj
 * @see
 * @since JDK 1.8
 */
@RepositoryRestResource(collectionResourceRel = "perAssessCategory", path = "perAssessCategory")
public interface PerAssessCategoryRepository extends JpaRepository<PerAssessCategory, String> {
    @Query(value = "SELECT p FROM PerAssessCategory p, PerApAcMap paam where p.id = paam.assessCategoryId and paam.assessPaperId = :assessPaperId order by p.createDate asc") // order by p.createDate asc
    List<PerAssessCategory> findByAssessPaper(@Param("assessPaperId") String _assessPaperId);
    Page<PerAssessCategory> findAllByOrderByCreateDateAsc(Pageable _page);
}


text:
declare module '@rjsf/core/dist/cjs/utils' {
	import { JSONSchema7 as JSONSchema } from 'json-schema';
	import { UiSchema } from '@rjsf/core';

	export function getDefaultRegistry(): any;
	export function getUiOptions(schema: UiSchema): any;
	export function orderProperties(
		properties: string[],
		order: string[] | undefined,
	): any;
	export function retrieveSchema(
		schema: JSONSchema,
		definitions: any,
		formData: any,
	): any;
}

redpajama_set_name: RedPajamaGithub


text:
package com.microrisc.simply.iqrf.dpa.v22x.types;

/**
 * Properties of currently loading code image (eg. custom DPA handler, iqrf
 * plugin and etc.).
 *
 * @author Martin Strouhal
 */
public class LoadingCodeProperties {

    /** Identify action while is code loading. */
    public enum LoadingAction {
       /** Computes and matches the checksum only without loading code image. */
       ComputeAndMatchChecksumWithoutCodeLoading,

       /** Same as above plus loads the code into Flash if the checksum matches. */
       ComputeAndMatchChecksumWithCodeLoading;
    }

    /** Identify code image which is loading. */
    public enum LoadingContent {
       Hex,
       IQRF_Plugin;
    }

    private LoadingAction action;
    private LoadingContent content;
    private int address, length, checksum;

    /**
     * Create a new instance of {@link LoadingCodeProperties}.
     *
     * @param action which is executed while code image is loading
     * @param content of code image
     * @param address of memory to load the code image from
     * @param length of the code image
     * @param checksum of the code image
     */
    public LoadingCodeProperties(LoadingAction action, LoadingContent content,
            int address, int length, int checksum) {
       this.action = action;
       this.content = content;
       this.address = address;
       this.length = length;
       this.checksum = checksum;
    }

    /**
     * @return {@link LoadingAction} which is executed while code image is
     * loading
     */
    public LoadingAction getAction() {
       return action;
    }

    /**
     * @return {@link LoadingContent} of code image
     */
    public LoadingContent getContent() {
       return content;
    }

    /**
     * @return address of memory to load the code image from
     */
    public int getAddress() {
       return address;
    }

    /**
     * @return length of the code image
     */
    public int getLength() {
       return length;
    }

    /**
     * @return checksum of the code image
     */
    public int getChecksum() {
       return checksum;
    }
}


text:
ChromeSearchResult::ChromeSearchResult()
    : metadata_(std::make_unique<ash::SearchResultMetadata>()) {}

ChromeSearchResult::~ChromeSearchResult() = default;

void ChromeSearchResult::SetActions(const Actions& actions) {
  metadata_->actions = actions;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetDisplayScore(double display_score) {
  metadata_->display_score = display_score;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetIsInstalling(bool is_installing) {
  metadata_->is_installing = is_installing;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetTitle(const base::string16& title) {
  metadata_->title = title;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetTitleTags(const Tags& tags) {
  metadata_->title_tags = tags;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetDetails(const base::string16& details) {
  metadata_->details = details;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetDetailsTags(const Tags& tags) {
  metadata_->details_tags = tags;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetAccessibleName(const base::string16& name) {
  metadata_->accessible_name = name;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetRating(float rating) {
  metadata_->rating = rating;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetFormattedPrice(
    const base::string16& formatted_price) {
  metadata_->formatted_price = formatted_price;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetDisplayType(DisplayType display_type) {
  metadata_->display_type = display_type;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetResultType(ResultType result_type) {
  metadata_->result_type = result_type;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetDisplayIndex(DisplayIndex display_index) {
  metadata_->display_index = display_index;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetPositionPriority(float position_priority) {
  metadata_->position_priority = position_priority;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetIsOmniboxSearch(bool is_omnibox_search) {
  metadata_->is_omnibox_search = is_omnibox_search;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetIsRecommendation(bool is_recommendation) {
  metadata_->is_recommendation = is_recommendation;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetQueryUrl(const GURL& url) {
  metadata_->query_url = url;
  auto* updater = model_updater();
  if (updater)
    updater->SetSearchResultMetadata(id(), CloneMetadata());
}

void ChromeSearchResult::SetEquivalentResutlId(
    const std::string& equivlanet_result_id) {
  metadata_->equivalent_result_id = equivlanet_result_id;
  auto* updater = model_updater();
  if (updater)
    updater->SetSearchResultMetadata(id(), CloneMetadata());
}

void ChromeSearchResult::SetIcon(const gfx::ImageSkia& icon) {
  icon.EnsureRepsForSupportedScales();
  metadata_->icon = icon;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetChipIcon(const gfx::ImageSkia& chip_icon) {
  chip_icon.EnsureRepsForSupportedScales();
  metadata_->chip_icon = chip_icon;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetBadgeIcon(const gfx::ImageSkia& badge_icon) {
  badge_icon.EnsureRepsForSupportedScales();
  metadata_->badge_icon = badge_icon;
  SetSearchResultMetadata();
}

void ChromeSearchResult::SetNotifyVisibilityChange(
    bool notify_visibility_change) {
  metadata_->notify_visibility_change = notify_visibility_change;
}

void ChromeSearchResult::SetSearchResultMetadata() {
  AppListModelUpdater* updater = model_updater();
  if (updater)
    updater->SetSearchResultMetadata(id(), CloneMetadata());
}

void ChromeSearchResult::InvokeAction(int action_index, int event_flags) {}

void ChromeSearchResult::OnVisibilityChanged(bool visibility) {
  VLOG(1) << " Visibility change to " << visibility << " and ID is " << id();
}

void ChromeSearchResult::UpdateFromMatch(const TokenizedString& title,
                                         const TokenizedStringMatch& match) {
  const TokenizedStringMatch::Hits& hits = match.hits();

  Tags tags;
  tags.reserve(hits.size());
  for (const auto& hit : hits)
    tags.push_back(Tag(Tag::MATCH, hit.start(), hit.end()));

  SetTitle(title.text());
  SetTitleTags(tags);
  set_relevance(match.relevance());
}

void ChromeSearchResult::GetContextMenuModel(GetMenuModelCallback callback) {
  std::move(callback).Run(nullptr);
}

// static
std::string ChromeSearchResult::TagsDebugStringForTest(const std::string& text,
                                                       const Tags& tags) {
  std::string result = text;

  // Build a table of delimiters to insert.
  std::map<size_t, std::string> inserts;
  for (const auto& tag : tags) {
    if (tag.styles & Tag::URL)
      inserts[tag.range.start()].push_back('{');
    if (tag.styles & Tag::MATCH)
      inserts[tag.range.start()].push_back('[');
    if (tag.styles & Tag::DIM) {
      inserts[tag.range.start()].push_back('<');
      inserts[tag.range.end()].push_back('>');
    }
    if (tag.styles & Tag::MATCH)
      inserts[tag.range.end()].push_back(']');
    if (tag.styles & Tag::URL)
      inserts[tag.range.end()].push_back('}');
  }
  // Insert the delimiters (in reverse order, to preserve indices).
  for (const auto& insert : base::Reversed(inserts))
    result.insert(insert.first, insert.second);

  return result;
}

app_list::AppContextMenu* ChromeSearchResult::GetAppContextMenu() {
  return nullptr;
}


text:
package seghandler

import (
	"context"
	"sort"

	"github.com/scionproto/scion/go/lib/ctrl/path_mgmt"
	"github.com/scionproto/scion/go/lib/ctrl/seg"
	"github.com/scionproto/scion/go/lib/log"
	"github.com/scionproto/scion/go/lib/pathdb"
	"github.com/scionproto/scion/go/lib/revcache"
)

// SegStats provides statistics about segment insertion/updates.
type SegStats struct {
	// InsertedSegs are the log IDs of the inserted segments.
	InsertedSegs []string
	// UpdatedSegs are the log IDs of the updated segments.
	UpdatedSegs []string
}

// Total returns the total amount of updates and inserts.
func (s SegStats) Total() int {
	return len(s.InsertedSegs) + len(s.UpdatedSegs)
}

// Log logs the statistics with the given logger.
func (s *SegStats) Log(ctx context.Context) {
	logger := log.FromCtx(ctx)
	if len(s.InsertedSegs) > 0 {
		logger.Debug("Segments inserted in DB", "segments", s.InsertedSegs)
	}
	if len(s.UpdatedSegs) > 0 {
		logger.Debug("Segments updated in DB", "segments", s.UpdatedSegs)
	}
}

// Storage is used to store segments and revocations.
type Storage interface {
	StoreSegs(context.Context, []*seg.Meta) (SegStats, error)
	StoreRevs(context.Context, []*path_mgmt.RevInfo) error
}

// DefaultStorage wraps path DB and revocation cache and offers
// convenience methods that implement the Storage interface.
type DefaultStorage struct {
	PathDB   pathdb.DB
	RevCache revcache.RevCache
}

// StoreSegs stores the given segments in the pathdb in a transaction.
func (s *DefaultStorage) StoreSegs(ctx context.Context, segs []*seg.Meta) (SegStats, error) {
	tx, err := s.PathDB.BeginTransaction(ctx, nil)
	if err != nil {
		return SegStats{}, err
	}
	defer tx.Rollback()
	// Sort to prevent sql deadlock.
	sort.Slice(segs, func(i, j int) bool {
		return segs[i].Segment.GetLoggingID() < segs[j].Segment.GetLoggingID()
	})
	segStats := SegStats{}
	for _, seg := range segs {
		stats, err := tx.Insert(ctx, seg)
		if err != nil {
			return SegStats{}, err
		}
		if stats.Inserted > 0 {
			segStats.InsertedSegs = append(segStats.InsertedSegs, seg.Segment.GetLoggingID())
		} else if stats.Updated > 0 {
			segStats.UpdatedSegs = append(segStats.UpdatedSegs, seg.Segment.GetLoggingID())
		}
	}
	if err := tx.Commit(); err != nil {
		return SegStats{}, err
	}
	segStats.Log(ctx)
	return segStats, nil
}

// StoreRevs stores the given revocations in the revocation cache.
func (s *DefaultStorage) StoreRevs(ctx context.Context,
	revs []*path_mgmt.RevInfo) error {

	for _, rev := range revs {
		if _, err := s.RevCache.Insert(ctx, rev); err != nil {
			return err
		}
	}
	return nil
}


text:
// Software License Agreement (BSD License)
//
// Copyright (c) 2010-2016, Deusty, LLC
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms,
// with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Neither the name of Deusty nor the names of its contributors may be used
//   to endorse or promote products derived from this software without specific
//   prior written permission of Deusty, LLC.

/**
 * Welcome to CocoaLumberjack!
 *
 * The project page has a wealth of documentation if you have any questions.
 *
 * If you're new to the project you may wish to read "Getting Started" at:
 * Documentation/GettingStarted.md
 *
 * Otherwise, here is a quick refresher.
 * There are three steps to using the macros:
 *
 * Step 1:
 * Import the header in your implementation or prefix file:
 *
 * #import <CocoaLumberjack/CocoaLumberjack.h>
 *
 * Step 2:
 * Define your logging level in your implementation file:
 *
 * // Log levels: off, error, warn, info, verbose
 * static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
 *
 * Step 2 [3rd party frameworks]:
 *
 * Define your LOG_LEVEL_DEF to a different variable/function than ddLogLevel:
 *
 * // #undef LOG_LEVEL_DEF // Undefine first only if needed
 * #define LOG_LEVEL_DEF myLibLogLevel
 *
 * Define your logging level in your implementation file:
 *
 * // Log levels: off, error, warn, info, verbose
 * static const DDLogLevel myLibLogLevel = DDLogLevelVerbose;
 *
 * Step 3:
 * Replace your NSLog statements with DDLog statements according to the severity of the message.
 *
 * NSLog(@"Fatal error, no dohickey found!"); -> OSSLogError(@"Fatal error, no dohickey found!");
 *
 * DDLog works exactly the same as NSLog.
 * This means you can pass it multiple variables just like NSLog.
 **/

#import <Foundation/Foundation.h>

// Disable legacy macros
#ifndef OSSDD_LEGACY_MACROS
    #define OSSDD_LEGACY_MACROS 0
#endif

// Core
#import "OSSDDLog.h"

// Main macros
#import "OSSLogMacros.h"

// Loggers
#import "OSSFileLogger.h"
#import "OSSNSLogger.h"


text:
// ============================================================================
// FileName: HighriseRequest.cs
//
// Description:
// Base class to send requests to 37 Signals contact management system Highrise.
//
// Author(s):
// Aaron Clauson
//
// History:
// 13 Feb 2011  Aaron Clauson   Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2011 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery Pty Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of SIP Sorcery Ltd.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ============================================================================

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Web;
using SIPSorcery.Sys;
using log4net;

namespace SIPSorcery.CRM.ThirtySevenSignals
{
    /// <summary>
    /// This class submits HTTP requests to the 37 Signals Highrise API.
    /// </summary>
    /// <typeparam name="S">The singular object type for retrieving single items, e.g. Person or Company.</typeparam>
    /// <typeparam name="T">The plural object type for retrieving lists of items, e.g. People or Companies.</typeparam>
    public class HighriseRequest<S, T>
    {
        private const int MAX_HTTP_REQUEST_TIMEOUT = 10;
        private const string NO_RESULTS_RESPONSE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<nil-classes type=\"array\"/>\n";   // There's got to be a better way. The XML deserialiser throws an exception when it gets this.

        private static ILog logger = AppState.logger;

        private string m_urlNoun;
        private string m_authToken;

        protected string BaseUrl { get; private set; }

        public HighriseRequest(string baseUrl, string urlNoun, string authToken)
        {
            BaseUrl = baseUrl;
            m_urlNoun = urlNoun;
            m_authToken = authToken;
        }

        public S GetByID(int id)
        {
            string requestURL = BaseUrl + "/" + m_urlNoun + "/" + id + ".xml";
            return GetItem(requestURL);
        }

        public T GetByPhoneNumber(string phoneNumber)
        {
            string requestURL = BaseUrl + "/" + m_urlNoun + "/search.xml?" + Uri.EscapeDataString("criteria[phone]=" + phoneNumber);
            return GetList(requestURL);
        }

        public T GetByCustomField(string customField, string searchString)
        {
            string requestURL = BaseUrl + "/" + m_urlNoun + "/search.xml?" + Uri.EscapeDataString("criteria[" + customField + "]=" + searchString);
            return GetList(requestURL);
        }

        public T GetByCustomSearch(string customSearch)
        {
            string requestURL = BaseUrl + "/" + m_urlNoun + "/search.xml?" + Uri.EscapeDataString(customSearch);
            return GetList(requestURL);
        }

        public T GetByName(string name)
        {
            string requestURL = BaseUrl + "/" + m_urlNoun + "/search.xml?" + Uri.EscapeDataString("term=" + name);
            return GetList(requestURL);
        }

        protected virtual S GetItem(string url)
        {
            string response = GetResponse(url);

            if (!response.IsNullOrBlank())
            {
                S item = default(S);

                using (TextReader xmlReader = new StringReader(response))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(S));
                    item = (S)serializer.Deserialize(xmlReader);
                }

                return item;
            }
            else
            {
                return default(S);
            }
        }

        protected virtual T GetList(string url)
        {
            logger.Debug("HighRiseRequest url " + url + ".");

            string response = GetResponse(url);

            if (response == NO_RESULTS_RESPONSE)
            {
                return default(T);
            }
            else if (!response.IsNullOrBlank())
            {
                T list = default(T);

                using (TextReader xmlReader = new StringReader(response))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    list = (T)serializer.Deserialize(xmlReader);
                }

                return list;
            }
            else
            {
                return default(T);
            }
        }

        private string GetResponse(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.AllowAutoRedirect = true;
            request.Timeout = MAX_HTTP_REQUEST_TIMEOUT * 1000;
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(m_authToken)));

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode != HttpStatusCode.OK)
            {
                response.Close();
                throw new ApplicationException("37 Signals Highrise request to " + url + " failed with response " + response.StatusCode + ".");
            }

            StreamReader reader = new StreamReader(response.GetResponseStream());
            string responseStr = reader.ReadToEnd();
            response.Close();

            if (responseStr != null)
            {
                return Regex.Replace(responseStr, "nil=\"true\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"");
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Attempts to create a new Highrise item.
        /// </summary>
        /// <param name="createUrl">The URL to send the creation request to. The URL can determine where the object gets created.
        /// For example to create a new note on a person the URL would be /people/#{person-id}/notes.xml.</param>
        /// <param name="itemXML">The XML that contains the information to create the new Highrise item.</param>
        /// <returns>If sucessful the reponse HTTP Location header which indicates the URL for the newly created item.</returns>
        protected string CreateItem(string createUrl, string itemXML)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(createUrl);
            request.Method = "POST";
            request.AllowAutoRedirect = true;
            request.Timeout = MAX_HTTP_REQUEST_TIMEOUT * 1000;
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(m_authToken)));
            request.ContentType = "application/xml";
            Stream requestStream = request.GetRequestStream();
            byte[] requestBytes = Encoding.UTF8.GetBytes(itemXML);
            requestStream.Write(requestBytes, 0, requestBytes.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode != HttpStatusCode.Created)
            {
                response.Close();
                throw new ApplicationException("37 Signals Highrise create request to " + createUrl + " failed with response " + response.StatusCode + ".");
            }

            return response.Headers["Location"];
        }
    }
}


text:
local ffi =             require "ffi"
local log =             require "turbo.log"
local httputil =        require "turbo.httputil"
local httpserver =      require "turbo.httpserver"
local buffer =          require "turbo.structs.buffer"
local bufferptr =       require "turbo.structs.bufferptr"
local escape =          require "turbo.escape"
local platform =        require "turbo.platform"
local response_codes =  require "turbo.http_response_codes"
local mime_types =      require "turbo.mime_types"
local util =            require "turbo.util"
local hash =            require "turbo.hash"
local socket =          require "turbo.socket_ffi"
local syscall =         require "turbo.syscall"
local fs
if platform.__WINDOWS__ then
    -- Support for stat'ing in StaticFileHandler on Windows OS.
    fs = require "lfs"
else
    fs = require "turbo.fs"
end
require "turbo.3rdparty.middleclass"
require "turbo.cdef"

-- Use funpack instead of native as the native is not implemented in the
-- LuaJIT compiler. Traces abort in a bad spot if not used.
local unpack = util.funpack
local is_in = util.is_in
local _std_supported_met = {"GET", "HEAD", "POST", "DELETE", "PUT", "OPTIONS"}
local _ssl_enabled = _G.TURBO_SSL

local web = {} -- web namespace
web.Mustache = require "turbo.mustache" -- include the Mustache templater.

--- Base RequestHandler class. The heart of Turbo.lua.
-- The usual flow of using Turbo.lua is sub-classing the RequestHandler
-- class and implementing the HTTP request methods described in
-- self.SUPPORTED_METHODS. The main goal of this class is to wrap a HTTP
-- request and offer utilities to respond to the request. Requests are
-- deligated to RequestHandler's by the Application class.
web.RequestHandler = class("RequestHandler")

--- Initialize a new RequestHandler class instance.
-- Normally a user is not the one to initialize this, but rather a Application
-- class instance which has receive a HTTP request. Normal there should not be
-- a need for you to redefine this initializer,  instead look at the different
-- entry points given longer down.
-- @param application (Application instance) The calling application should
-- leave a self reference.
-- @param request (HTTPRequest instance) The request.
-- @param url_args (Table) Table of arguments to call matching method with.
-- These arguments are normally captured by the pattern given on initializing
-- of a Application class.
-- @param options (Table) 3rd argument given in Application class route table.
function web.RequestHandler:initialize(application, request, url_args, options)
    self.SUPPORTED_METHODS = _std_supported_met
    self.application = application
    self.request = request
    self._headers_written = false
    self._finished = false
    self._auto_finish = true
    self._url_args = url_args
    self._set_cookie = {}
    -- Set standard headers by calling the clear method.
    self:clear()
    if self.request.headers:get("Connection") then
        self.request.connection.stream:set_close_callback(
            self.on_connection_close,
            self)
    end
    self.options = options
    self:on_create(self.options)
end

--- Get the applications settings.
-- @return Applications settings.
function web.RequestHandler:settings() return self.application.settings end

--*************** Entry points ***************

--- Redefine this method if you want to do something after the class has been
-- initialized. This method unlike on_create, is only called if the method has
-- been found to be supported.
function web.RequestHandler:prepare() end

--- Redefine this method if you want to do something straight after the class
-- has been initialized. This is called after a request has been
-- receive, and before the HTTP method has been verified against supported
-- methods. So if a not supported method is requested, this method is still
-- called.
function web.RequestHandler:on_create(kwargs) end

--- Redefine this method after your likings. Called after the end of a request.
-- Usage of this method could be something like a clean up etc.
function web.RequestHandler:on_finish() end

--- Redefine this method to set HTTP headers at the beginning of all the
-- request receive by the RequestHandler. For example setting some kind
-- of cookie or adjusting the Server key in the headers would be sensible
-- to do in this method.
function web.RequestHandler:set_default_headers() end

--- Standard methods for RequestHandler class.
-- Subclass RequestHandler and implement any of the following methods to handle
-- the corresponding HTTP request.
-- If not implemented they will provide a 405 (Method Not Allowed).
-- These methods receive variable arguments, depending on what the Application
-- instance calling them has captured from the pattern matching of the request
-- URL. The methods are run protected, so they are error safe. When a error
-- occurs in the execution of these methods the request is given a
-- 500 Internal Server Error response. In debug mode, the stack trace leading
-- to the crash is also a part of the response. If not debug mode is set, then
-- only the status code is set.
function web.RequestHandler:head(...) error(web.HTTPError:new(405)) end
function web.RequestHandler:get(...) error(web.HTTPError:new(405)) end
function web.RequestHandler:post(...) error(web.HTTPError:new(405)) end
function web.RequestHandler:delete(...) error(web.HTTPError:new(405)) end
function web.RequestHandler:put(...) error(web.HTTPError:new(405)) end
function web.RequestHandler:options(...) error(web.HTTPError:new(405)) end

--*************** Input ***************

--- Returns the value of the argument with the given name.
-- If multiple values are set with the same name, then only one is returned.
-- For multiple arguments, use get_arguments() instead.
-- If default value is not given the argument is considered to be required and
-- will result in a raise of a HTTPError 400 Bad Request if the argument does
-- not exist.
-- @param name (String) Name of the argument to get.
-- @param default (String) Optional fallback value in case argument is not set.
-- @param strip (Boolean) Remove whitespace from head and tail of string.
-- @return Value of argument if set.
function web.RequestHandler:get_argument(name, default, strip)
    local args = self:get_arguments(name, strip)
    local t = type(args)
    if t == "string" then
        return args
    elseif t == "table" then
        -- form-data arguments are wrapped in an additional table
        -- in order to associate their fields and content-disposition
        -- parameters with the argument
        if type(args[1]) == "table" then
            return args[1][1]
        end
        return args[1]
    elseif default ~= nil then
        return default
    else
        error(web.HTTPError:new(400, "Missing required argument."))
    end
end

--- Returns the values of the argument with the given name.
-- Will return a empty table if argument does not exist.
-- @param name (String) Name of the argument to get.
-- @param strip (Boolean) Remove whitespace from head and tail of string.
-- @return (Table) Argument values.
function web.RequestHandler:get_arguments(name, strip)
    local values
    local n = 0
    local url_args = self.request.arguments
    local form_args = self.request.connection.arguments

    -- Combine argument lists from HTTPConnection and HTTPRequest.
    if not url_args and not form_args then
        return
    end
    if url_args and url_args[name] then
        values = url_args[name]
        if type(values) == "table" then
            n = #values
        else
            n = 1
        end
    end
    if form_args and form_args[name] then
        if n == 0 then
            values = form_args[name]
        elseif n > 0 then
            if n == 1 then
                values = {values}
            end
            for i = 1, #form_args[name] do
                values[#values+1] = form_args[name][i]
            end
        end
    end
    if strip then
        if type(values) == "string" then
            values = escape.trim(values)
        elseif type(values) == "table" and not type(values[i]) == "table" then
            for i = 1, #values do
                values[i] = escape.trim(values[i])
            end
        end
    end
    return values
end

--- Returns JSON request data as a table. By default, it only parses json
-- mimetype. It will return an empty table if request data is empty.
-- @param force (Boolean) if set to true, mimetype will be ignored.
-- @return (Table) parsed from request data, return nil if mimetype is not
-- json and force option is not set.
function web.RequestHandler:get_json(force)
    local content_type = self.request.headers:get("content-type", true)
    if not content_type then
        content_type = ""
    end
    if force ~= true and not content_type:find("application/json", 1, true) then
        return nil
    end
    return escape.json_decode(self.request.body)
end

--*************** Output ***************

--- Reset all headers and content for this request. Run on class initialization.
function web.RequestHandler:clear()
    self.headers = httputil.HTTPHeaders:new()
    self:set_default_headers()
    self:add_header("Server", self.application.application_name)
    if not self.request:supports_http_1_1() then
        local con = self.request.headers:get("Connection")
        if con == "Keep-Alive" or con == "keep-alive" then
            self:add_header("Connection", "Keep-Alive")
        end
    end
    self._write_buffer = buffer:new()
    self._status_code = 200
end

--- Add the given name and value pair to the HTTP response headers.
-- To overwite use the set_header method instead.
-- @param name (String) Key string for header field.
-- @param value (String or number) Value for header field.
function web.RequestHandler:add_header(name, value)
    self.headers:add(name, value)
end

--- Set the given name and value pair to the HTTP response headers.
-- Difference from add_header that set_header will overwrite existing header
-- key.
-- @param name (String) Key string for header field.
-- @param value (String or number) Value for header field.
function web.RequestHandler:set_header(name, value)
    self.headers:set(name, value)
end

--- Returns the current value set to given key.
-- @param name (String) Key string for header field.
-- @return Value of header field or nil if not set, may return a table
-- if multiple values with same key exists.
function web.RequestHandler:get_header(key)
    return self.headers:get(key)
end

--- Sets the HTTP status code for our response.
-- @param status_code The status code to set. Must be number or a error is
-- raised.
function web.RequestHandler:set_status(status_code)
    if type(status_code) ~= "number" then
        error("set_status method requires number.")
    end
    self._status_code = status_code
end

---  Get the curent status code of the HTTP response headers.
-- @return (Number) Current HTTP status code.
function web.RequestHandler:get_status() return self._status_code end

--- Redirect client to another URL. Sets headers and finish request.
-- User can not send data after this.
-- @note Finishes request, no further operations can be done
-- @param url (String) The URL to redirect to.
-- @param permanent (Boolean) Browser hint that says the redirect is
-- permanent.
function web.RequestHandler:redirect(url, permanent)
    if self._headers_written then
        error("Cannot redirect after headers have been written")
    end
    local status = permanent and 301 or 302
    self:set_status(status)
    self:add_header("Location", url)
    self:finish()
end

--- Raises an HTTPError with the provided status code and optional message.
-- @param status_code The status code to set. Must be number or a error is
-- raised.
-- @param msg An optional custom message for the error.
function web.RequestHandler:send_error(status_code, msg)
    if type(status_code) ~= "number" then
        error("status code must be a number")
    end
    if msg then
        error(web.HTTPError(status_code, msg))
    else
        error(web.HTTPError(status_code))
    end
end

--- Check status of request being handled. If finished the response is sent.
-- @return (Boolean) true or false.
function web.RequestHandler:finished()
    return self._finished == true
end

--- Get cookie value from incoming request.
-- @param name The name of the cookie to get.
-- @param default A default value if no cookie is found.
-- @return Cookie or the default value.
function web.RequestHandler:get_cookie(name, default)
    if not self._cookies_parsed then
        self:_parse_cookies()
    end
    if not self._cookies[name] then
        return default
    else
        return self._cookies[name]
    end
end

--- Get a signed cookie value from incoming request.
-- If the cookie can not be validated, then an error with a string error
-- is raised.
-- Hash-based message authentication code (HMAC) is used to be able to verify
-- that the cookie has been created with the "cookie_secret" set in the
-- Application class kwargs. This is simply verifing that the cookie has been
-- signed by your key, IT IS NOT ENCRYPTING DATA.
-- @param name The name of the cookie to get.
-- @param default A default value if no cookie is found.
-- @param max_age Timestamp used to sign cookie must be not be older than this
-- value in seconds.
-- @return Cookie or the default value.
function web.RequestHandler:get_secure_cookie(name, default, max_age)
    local cookie = self:get_cookie(name)
    if not cookie then
        return default
    end
    local hmac, len, timestamp, value = cookie:match("(%w*)|(%d*)|(%d*)|(.*)")
    assert(tonumber(len) == value:len(), "Cookie value length has changed!")
    assert(hmac:len() == 40, "Could not get secure cookie. Hash to short.")
    if max_age then
        max_age = max_age * 1000 -- Get milliseconds.
        local cookietime = tonumber(timestamp)
        assert(util.gettimeofday() - timestamp < max_age, "Cookie has expired.")
    end
    local hmac_cmp = hash.HMAC(self.application.kwargs.cookie_secret,
                               string.format("%d|%s|%s",
                                             len,
                                             tostring(timestamp),
                                             value))
    assert(hmac == hmac_cmp, "Secure cookie does not match hash. \
                              Either the cookie is forged or the cookie secret \
                              has been changed")
    return value
end

--- Set a cookie with value to response.
-- @param name The name of the cookie to set.
-- @param value The value of the cookie.
-- @param domain The domain to apply cookie for.
-- @param expire_hours Set cookie to expire in given amount of hours.
-- @note Expiring relies on the requesting browser and may or may not be
-- respected. Also keep in mind that the servers time is used to calculate
-- expiry date, so the server should ideally be set up with NTP server.
function web.RequestHandler:set_cookie(name, value, domain, expire_hours)
    self._set_cookie[#self._set_cookie+1] = {
        name = name,
        value = value,
        domain = domain,
        expire_hours = expire_hours or 1
    }
end

--- Set a signed cookie value to response.
-- Hash-based message authentication code (HMAC) is used to be able to verify
-- that the cookie has been created with the "cookie_secret" set in the
-- Application class kwargs. This is simply verifing that the cookie has been
-- signed by your key, IT IS NOT ENCRYPTING DATA.
-- @param name The name of the cookie to set.
-- @param value The value of the cookie.
-- @param domain The domain to apply cookie for.
-- @param expire_hours Set cookie to expire in given amount of hours.
-- @note Expiring relies on the requesting browser and may or may not be
-- respected. Also keep in mind that the servers time is used to calculate
-- expiry date, so the server should ideally be set up with NTP server.
function web.RequestHandler:set_secure_cookie(name, value, domain, expire_hours)
    -- The secure cookie format is as follows:
    -- Each column is separated by a pipe.
    -- value length | HMAC hash | timestamp | value
    -- timestamp and value separated by a pipe char is what is being hashed.
    assert(type(self.application.kwargs.cookie_secret) == "string",
           "No cookie secret has been set in the Application class.")
    if type(value) ~= "string" then
        value = tostring(value)
    end
    local to_hash = string.format("%d|%s|%s",
                                  value:len(),
                                  tostring(util.gettimeofday()),
                                  value)
    local cookie = string.format("%s|%s",
                                 hash.HMAC(
                                    self.application.kwargs.cookie_secret,
                                    to_hash),
                                 to_hash)
    return self:set_cookie(name, cookie, domain, expire_hours)
end

--- Clear a cookie.
-- @param name The name of the cookie to clear.
-- @note Expiring relies on the requesting browser and may or may not be
-- respected.
function web.RequestHandler:clear_cookie(name)
    -- Clear cookie by setting expiry date to 0 and
    -- empty values...
    self:set_cookie(name, "", nil, 0)
end

--- Set handler to not call finish() when request method has been called and
-- returned. Default is false. When set to true, the user must explicitly call
-- finish.
-- @param bool (Boolean)
function web.RequestHandler:set_async(bool)
    if type(bool) ~= "boolean" then
        error("bool must be boolean!")
    end
    self._auto_finish = bool == false
end

--- Use chunked encoding on writes. Must be written before :flush() is called.
-- Once set, the mode is irreversible. Modifying the flag manually will cause
-- undefined behaviour. Call :write() as usual, and when ready to send one
-- chunk call :flush(). finish() must be called to signal the end of the stream.
function web.RequestHandler:set_chunked_write()
    if self._headers_written == true then
        error("Headers already written, can not switch to chunked write.")
    elseif self.request.headers.method == "HEAD" then
        error("Chunked write gives no meaning for HEAD requests.")
    end
    self.chunked = true
    self:add_header("Transfer-Encoding", "chunked")
end

--- Writes the given chunk to the output buffer.
-- To write the output to the network, use the flush() method.
-- If the given chunk is a Lua table, it will be automatically
-- stringifed to JSON.
-- @param chunk (String) Data chunk to write to underlying connection.
function web.RequestHandler:write(chunk)
    if self._finished then
        error("write() method was called after finish().")
    end
    local t = type(chunk)
    if t == "nil" then
        -- Accept writing empty blocks.
        return
    elseif t == "string" and chunk:len() == 0 then
        return
    elseif t == "table" then
        self:add_header("Content-Type", "application/json; charset=UTF-8")
        chunk = escape.json_encode(chunk)
    elseif t ~= "string" and t ~= "table" then
        error("Unsupported type written as response; "..t)
    end
    self._write_buffer:append_luastr_right(chunk)
end

--- Flushes the current output buffer to the IO stream.
-- If callback is given it will be run when the buffer has been written to the
-- socket. Note that only one callback flush callback can be present per
-- request. Giving a new callback before the pending has been run leads to
-- discarding of the current pending callback. For HEAD method request the
-- chunk is ignored and only headers are written to the socket.
-- @param callback (Function) Callback function.
function web.RequestHandler:flush(callback, arg)
    local headers
    if not self._headers_written then
        self._headers_written = true
        headers = self:_gen_headers()
    end
    local chunk = tostring(self._write_buffer)
    self._write_buffer:clear()
    -- Lines below uses multiple calls to write to avoid creating new
    -- temporary strings. The write will essentially just be appended
    -- to the IOStream class, which will actually not perform any writes
    -- until the calling function returns to IOLoop.
    if self.chunked then
        -- Transfer-Encoding: chunked support.
        if headers then
            if chunk:len() ~= 0 then
                self.request:write(headers)
                self.request:write("\r\n")
                self.request:write(util.hex(chunk:len()))
                self.request:write("\r\n")
                self.request:write(chunk)
                self.request:write("\r\n", callback, arg)
            else
                self.request:write(headers)
                self.request:write("\r\n", callback, arg)
            end
        elseif chunk:len() ~= 0 then
            self.request:write(util.hex(chunk:len()))
            self.request:write("\r\n")
            self.request:write(chunk)
            self.request:write("\r\n")
        end
    else
        -- Not chunked with Content-Length set.
        if headers then
            if self.request.headers.method == "HEAD" then
                self.request:write(headers, callback, arg)
            elseif chunk:len() ~= 0 then
                self.request:write(headers)
                self.request:write("\r\n")
                self.request:write(chunk, callback, arg)
            else
                self.request:write(headers)
                self.request:write("\r\n", callback, arg)
            end
        elseif chunk:len() ~= 0 then
            self.request:write(chunk, callback, arg)
        end
    end
end

function web.RequestHandler:_gen_headers()
    if self:get_status() ~= 204 then
        if not self:get_header("Content-Type") then
            -- No content type is set, assume that it is text/html.
            -- This might not be preferable in all cases.
            self:add_header("Content-Type", "text/html; charset=UTF-8")
        end
        if not self:get_header("Content-Length") and not self.chunked then
            -- No length is set, add current write buffer size.
            self:add_header("Content-Length",
                tonumber(self._write_buffer:len()))
        end
    end
    self.headers:set_status_code(self._status_code)
    self.headers:set_version("HTTP/1.1")
    if #self._set_cookie ~= 0 then
        local c = self._set_cookie
        for i = 1, #c do
            local expire_time
            if c[i].expire_hours == 0 then
                expire_time = 0
            else
                expire_time = os.time() + (c[i].expire_hours*60*60)
            end
            local expire_str = util.time_format_cookie(expire_time)
            local cookie = string.format("%s=%s; path=%s; expires=%s",
                escape.escape(c[i].name),
                escape.escape(c[i].value or ""),
                c[i].domain or "/",
                expire_str)
            self:add_header("Set-Cookie", cookie)
        end
    end
    return self.headers:stringify_as_response()
end

--- Finishes the HTTP request. This method can only be called once for each
-- request. This method flushes all data in the write buffer.
-- @param chunk (String) Final data to write to stream before finishing.
function web.RequestHandler:finish(chunk)
    if self._finished then
        error("finish() called twice. Something terrible has happened")
    end
    self._finished = true
    if chunk then
        self:write(chunk)
    end
    self:flush() -- Make sure everything in buffers are flushed to IOStream.
    if self.chunked then
        self.request:write("0\r\n\r\n", self._finish, self)
        return
    end
    self:_finish()
end

--- Parse cookies according to the RFC 6265 document.
-- Valid cookie format is:
-- cookie-pair       = cookie-name "=" cookie-value
-- cookie-name       = token
-- cookie-value      = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
-- cookie-octet      = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
--                       ; US-ASCII characters excluding CTLs,
--                       ; whitespace DQUOTE, comma, semicolon,
--                       ; and backslash

local EQUAL         = string.byte("=")
local SEMICOLON     = string.byte(";")
local SPACE         = string.byte(" ")
local HTAB          = string.byte("\t")

local function get_cookie_table(text_cookie)
    if type(text_cookie) ~= "string" then
        error(string.format("Expect text_cookie to be \"string\" but found %s",
            type(text_cookie)))
    end

    local EXPECT_KEY    = 1
    local EXPECT_VALUE  = 2
    local EXPECT_SP     = 3

    local n = 0
    local len = #text_cookie

    for i = 1, len do
        if string.byte(text_cookie, i) == SEMICOLON then
            n = n + 1
        end
    end

    local cookie_table  = {}

    local state = EXPECT_SP
    local i = 1
    local j = 1
    local key, value

    while j <= len do
        if state == EXPECT_KEY then
            if string.byte(text_cookie, j) == EQUAL then
                key = string.sub(text_cookie, i, j - 1)
                state = EXPECT_VALUE
                i = j + 1
            end
        elseif state == EXPECT_VALUE then
            if string.byte(text_cookie, j) == SEMICOLON
                    or string.byte(text_cookie, j) == SPACE
                    or string.byte(text_cookie, j) == HTAB
            then
                value = string.sub(text_cookie, i, j - 1)
                cookie_table[escape.unescape(key)] = escape.unescape(value)

                key, value = nil, nil
                state = EXPECT_SP
                i = j + 1
            end
        elseif state == EXPECT_SP then
            if string.byte(text_cookie, j) ~= SPACE
                and string.byte(text_cookie, j) ~= HTAB
            then
                state = EXPECT_KEY
                i = j
                j = j - 1
            end
        end
        j = j + 1
    end

    if key ~= nil and value == nil then
        cookie_table[escape.unescape(key)] = escape.unescape(
            string.sub(text_cookie, i))
    end

    return cookie_table
end

function web.RequestHandler:_parse_cookies()
    local cookie_str, cnt = self.request.headers:get("Cookie")

    self._cookies_parsed = true
    if cnt == 0 then
        self._cookies = {}
        return
    elseif cnt == 1 then
        self._cookies = get_cookie_table(cookie_str)
    elseif cnt > 1 then
        self._cookies = {}
        for i = 1, cnt do
            self._cookies = util.tablemerge(
                self._cookies,
                get_cookie_table(cookie_str[i])
            )
        end
    end
end

function web.RequestHandler:_finish()
    if self._status_code == 200 or self._status_code == 304 then
        log.success(string.format([[[web.lua] %d %s %s %s (%s) %dms]],
            self._status_code,
            response_codes[self._status_code],
            self.request.headers:get_method(),
            self.request.headers:get_url(),
            self.request.remote_ip,
            self.request:request_time()))
    else
        log.warning(string.format([[[web.lua] %d %s %s %s (%s) %dms]],
            self._status_code,
            response_codes[self._status_code],
            self.request.headers:get_method(),
            self.request.headers:get_url(),
            self.request.remote_ip,
            self.request:request_time()))
    end
    self.request:finish()
    self:on_finish()
end

--- Called in asynchronous handlers when the connection is closed.
function web.RequestHandler:on_connection_close() end

function web.RequestHandler:_execute_func_table_unpack(func)
    if type(func) == "table" then
        for i = 1, #func, 1 do
            func[i](self, unpack(self._url_args))
        end
    else
        func(self, unpack(self._url_args))
    end
end

function web.RequestHandler:_execute_func_table(func)
    if type(func) == "table" then
        for i = 1, #func, 1 do
            func[i](self)
        end
    else
        func(self)
    end
end

--- Main entry point for the Application class.
function web.RequestHandler:_execute()
    -- Supported methods can be extended in inheriting classes by setting the
    -- self.SUPPORT_METHODS table.
    if not is_in(self.request.method, self.SUPPORTED_METHODS) then
        error(web.HTTPError:new(405))
    end
    self:prepare()
    if not self._finished then
        -- If there is no URL args then do not unpack as this has a significant
        -- cost.
        local method = self[self.request.method:lower()]
        if self._url_args and #self._url_args > 0 then
            if type(method) == "table" then
                -- Table based request method.
                if method.pre then
                    self:_execute_func_table_unpack(method.pre)
                end
                if method.main then
                    self:_execute_func_table_unpack(method.main)
                end
                if method.post then
                    self:_execute_func_table_unpack(method.post)
                end
            else
                method(self, unpack(self._url_args))
            end
        else
            if type(method) == "table" then
                -- Table based request method.
                if method.pre then
                    self:_execute_func_table(method.pre)
                end
                if method.main then
                    self:_execute_func_table(method.main)
                end
                if method.post then
                    self:_execute_func_table(method.post)
                end
            else
                -- Is function based method.
                method(self)
            end
        end
        if self._auto_finish and not self._finished then
            self:finish()
        end
    end
end

local STATICWEBCACHE_MAX = _G.TURBO_STATIC_MAX or 1024*1024*1
local SWCRC_CACHE = 0
local SWCRC_TOO_BIG = 1
local SWCRC_NOT_FOUND = -1
local SWCT_CACHE = 0
local SWCT_FILE = 1
local SWCT_NOFILE = -1
--- Static files cache class.
-- Files that does not exist in cache are added to cache on first read.
web._StaticWebCache = class("_StaticWebCache")
function web._StaticWebCache:initialize()
    self.files = {}
end

--- Read complete file.
-- @param path (String) Path to file.
-- @return 0 + buffer (String) on success, else -1.
function web._StaticWebCache:read_file(path)
    local fd, err = io.open(path, "rb")
    if not fd then
        return -1, err
    end
    local file = fd:read("*all")
    if not file then
        return -1, err
    end
    local sz = file:len()
    local buf = buffer(sz)
    buf:append_right(file, sz)
    local sha1sum = nil
    if _ssl_enabled then
        local digest = hash.SHA1(file)
        digest:finalize()
        sha1sum = digest:hex()
    end
    return 0, buf, sha1sum
end

--- Get file. If not in cache, it is read and put in the global _StaticWebCache
-- class.
-- @path (String) Path to file.
-- @return 0 + buffer (String) on success, else -1.
function web._StaticWebCache:get_file(path)
    local cf = self.files[path]

    -- Full path hash lookup.
    if cf and STATICWEBCACHE_MAX ~= -1 then
        -- index 1 = type
        -- index 2 = stat_t
        -- index 3 = buf or file
        -- index 4 = mime string (optional)
        -- index 5 = sha1 checksum
        if cf[1] == SWCT_CACHE then
            return SWCRC_CACHE, cf[2], cf[3], cf[4], cf[5]
        elseif cf[1] == SWCT_FILE then
            local file = io.open(path, "rb")
            if not file then
                log.error(string.format(
                    "[web.lua] Could not open file for reading; %s.",
                    err))
                return SWCRC_NOT_FOUND
            end
            return SWCRC_TOO_BIG, cf[2], file, cf[4]
        elseif cf[1] == SWCT_NOFILE then
            return SWCRC_NOT_FOUND
        end
    end

    -- Not in cache, or opened before.
    local stat, err
    if not platform.__WINDOWS__ then
        stat, err = fs.stat(path)
        if stat == -1 then
            self.files[path] = {SWCT_NOFILE}
            return SWCRC_NOT_FOUND -- File not found.
        end
    else
        stat, err = fs.attributes(path)
        if stat == nil then
            self.files[path] = {SWCT_NOFILE}
            return SWCRC_NOT_FOUND -- File not found.
        end
        -- Small rewrite of table to make it compatible with Linux stat.
        stat.st_size = stat.size
    end

    if stat.st_size > STATICWEBCACHE_MAX then
        -- File will not be cached because of size.
        -- Open file ptr instead.
        local rc, mime = self:get_mime(path)
        if rc == 0 then
            self.files[path] = {SWCT_FILE, stat, nil, mime}
        else
            self.files[path] = {SWCT_FILE, stat}
        end
        local file, err = io.open(path, "rb")
        if not file then
            log.error(string.format(
                "[web.lua] Could not open file for reading; %s.",
                err))
            return SWCRC_NOT_FOUND
        end
        return SWCRC_TOO_BIG, stat, file, mime
    end
    -- Small size, relative to STATICWEBCACHE_MAX, load file to
    -- a buffer.
    local rc, buf, sha1sum = self:read_file(path)
    if rc == 0 then
        local rc, mime = self:get_mime(path)
        if rc == 0 then
            self.files[path] = {SWCT_CACHE, stat, buf, mime, sha1sum}
        else
            self.files[path] = {SWCT_CACHE, stat, buf, nil, sha1sum}
        end
        log.notice(string.format(
            "[web.lua] Added %s (%d bytes) to static file cache. ",
            path,
            tonumber(buf:len())))
        return SWCRC_CACHE, stat, buf, mime, sha1sum
    else
        log.error(string.format(
            "[web.lua] Could not read file; %s.",
            buf))
        return SWCRC_NOT_FOUND
    end

end

--- Determine MIME type according to file exstension.
-- @error If no filename is set, a error is raised.
-- @return 0 + MIME (String) on success, else -1.
function web._StaticWebCache:get_mime(path)
    if not path then
        error("No filename suplied to get_mime()")
    end
    local parts = util.strsplit(path, ".")
    if #parts == 0 then
        return -1
    end
    local file_ending = parts[#parts]
    local mime_type = mime_types[file_ending]
    if mime_type then
        return 0, mime_type
    else
        return -1
    end
end

STATIC_CACHE = web._StaticWebCache:new() -- Global cache.
web.STATIC_CACHE = STATIC_CACHE

--- Simple static file handler class.
-- File system path is provided in the Application class.
-- If you are planning to serve big files, then it is recommended to use a
-- proper static file web server instead. For small files that can be kept
-- in memory it is ok.
web.StaticFileHandler = class("StaticFileHandler", web.RequestHandler)
function web.StaticFileHandler:prepare()
    if not self.options or type(self.options) ~= "string" then
        error("StaticFileHandler not initialized with correct parameters.")
    end
    self.path = self.options
    -- Check if this is a single file or directory.
    local last_char = self.path:sub(self.path:len())
    if last_char ~= "/" then
        self.file = true
    end
end

function web.StaticFileHandler:_headers_flushed_cb()
    self.request:write_zero_copy(
        self._static_buffer,
        self.finish,
        self)
end

function web.StaticFileHandler:_send_next_chunk()
    if self._file_offset == self._file_stat.st_size then
        self._file:close()
        self:finish()
        return
    end
    local sz = math.min(1024*32, -- 32KB chunks seems like a good value?
                        tonumber(self._file_stat.st_size - self._file_offset))
    self._file_offset = self._file_offset + sz
    local data, err = self._file:read(sz)
    if not data then
        log.error(string.format(
            "[web.lua] Could not read file; %s.",
            err))
        self:finish()
        return
    end
    if not data:len() == sz then
        log.error("[web.lua] Read size mismatch.")
        self:finish()
        return
    end
    self.__file_data_ref = data -- Make sure a reference to string is kept.
    self.request:write_zero_copy(
        bufferptr(ffi.cast("const char *", data), data:len()),
        self._send_next_chunk,
        self)
end

function web.StaticFileHandler:_send_from_file(stat, file)
    file:seek("set")
    self._file = file
    self._file_offset = 0
    self._file_stat = stat
    self:flush(self._send_next_chunk, self)
end

--- GET method for static file handling.
-- @param path The path captured from request.
function web.StaticFileHandler:get(path)
    local full_path

    self:set_async(true)
    if not self.file then
        if #self._url_args == 0 or self._url_args[1]:len() == 0 then
            error(web.HTTPError(404))
        end
        local filename = escape.unescape(self._url_args[1])
        if filename:match("%.%.", 0, true) then -- Prevent dir traversing.
            error(web.HTTPError(401))
        end
        full_path = string.format("%s%s", self.path, filename)
    else
        full_path = self.path
    end

    local rc, stat, buf, mime, sha1 = STATIC_CACHE:get_file(full_path)
    if mime then
        self:add_header("Content-Type", mime)
    end
    if sha1 then
        -- Etag check.
        if self.request.headers:get("If-None-Match") == sha1 then
            -- Client has the most recent file. Do not send :).
            self:set_status(304)
            self:add_header("Etag", sha1)
            self:finish()
            return
        end
    end
    if rc == SWCRC_CACHE then
        self._static_buffer = buf
        self.headers:set_status_code(200)
        self.headers:set_version("HTTP/1.1")
        self:add_header("Content-Length", tonumber(buf:len()))
        if sha1 then
            self:add_header("Etag", sha1)
        end
        self:flush(web.StaticFileHandler._headers_flushed_cb, self)
    elseif rc == SWCRC_TOO_BIG then
        self.headers:set_status_code(200)
        self.headers:set_version("HTTP/1.1")
        self:add_header("Content-Length", tonumber(stat.st_size))
        self:_send_from_file(stat, buf)
    elseif rc == SWCRC_NOT_FOUND then
        error(web.HTTPError(404)) -- Not found
    end
end

--- HEAD method for static file handling.
-- @param path The path captured from request.
function web.StaticFileHandler:head(path)
    if #self._url_args == 0 or self._url_args[1]:len() == 0 then
        error(web.HTTPError(404))
    end
    local filename = self._url_args[1]
    if filename:match("%.%.", 0, true) then -- Prevent dir traversing.
        error(web.HTTPError(401))
    end
    local full_path = string.format("%s%s", self.path,
        escape.unescape(filename))
    local rc, buf, mime = STATIC_CACHE:get_file(full_path)
    if rc == 0 then
        if mime then
            self:add_header("Content-Type", mime_type)
        end
        self:add_header("Content-Length", tonumber(buf:len()))
    else
        error(web.HTTPError(404)) -- Not found
    end
end

--- HTTPError class.
-- This error is raisable from RequestHandler instances. It provides a
-- convinent and safe way to handle errors in handlers. E.g it is allowed to
-- do this:
-- function MyHandler:get()
--      local item = self:get_argument("item")
--      if not find_in_store(item) then
--          error(turbo.web.HTTPError(400, "Could not find item in store"))
--      end
--      ...
-- end
-- The result is that the status code is set to 400 and the message is sent as
-- the body of the request. The request is always finished on error.
web.HTTPError = class("HTTPError")
function web.HTTPError:initialize(code, message)
    if type(code) ~= "number" then
        error("HTTPError code argument must be number.")
    end
    self.code = code
    self.message = message and message or response_codes[code]
end

--- Class to handout HTTP errors.
-- Internal class to produce sensible error output.
web.ErrorHandler = class("ErrorHandler", web.RequestHandler)

function web.ErrorHandler:initialize(app, request, code, message)
    web.RequestHandler.initialize(self, app, request)
    if (message) then
        self:write(message)
    else
        self:write(response_codes[code])
    end
    self:set_status(code)
    self:finish()
end

--- Static redirect handler that simple redirect the client to the given
-- URL in 3rd argument of a entry in the Application class's routing table.
-- Example:
-- local application = turbo.web.Application({
--      {"^/redirector$", turbo.web.RedirectHandler, "http://turbolua.org"}
-- })
web.RedirectHandler = class("RedirectHandler", web.RequestHandler)
function web.RedirectHandler:prepare()
    if not self.options or type(self.options) ~= "string" then
        error(web.HTTPError(500,
            "RedirectHandler executed without URL argument."))
    end
    self:redirect(self.options, true)
end

--- The Application class is a collection of request handler classes that
-- together make up a web application. Example:
-- local application = turbo.web.Application({
--      {"^/static/(.*)$", turbo.web.StaticFileHandler, "/var/www/"},
--      {"^/$", ExampleHandler},
--      {"^/item/(%d*)", ItemHandler}
-- })
-- The constructor of this class takes a "map" of URL patterns and their
-- respective handlers. The third element in the table are optional parameters
-- the handler class might have. This could be a single value or a table.
-- E.g the turbo.web.StaticFileHandler class takes the root path for your
-- static handler.
-- The first element in the table is the URL that the application class matches
-- incoming request with to determine which handler it should be sent to. These
-- URLs simply be a URL or a any kind of Lua pattern. The ItemHandler URL
-- pattern is an example on how to map numbers from URL to your handlers.
-- Pattern encased in parantheses are used as parameters when calling the
-- request methods in Request handlers.
web.Application = class("Application")

--- Initialize a new Application class instance.
-- @param handlers (Table) As described above.

-- @param kwargs (Table) Key word arguments.
-- Key word arguments supported:
-- "default_host" = Redirect to this URL if no matching handler is found.
-- "cookie_secret" = Sequence of bytes used for to sign cookies.
-- "settings" = Global user settings that can be accessed in
--     RequestHandler's through self.application.settings
function web.Application:initialize(handlers, kwargs)
    self.handlers = handlers or {}
    self.kwargs = kwargs or {}
    self.settings = self.kwargs.settings
    self.default_host = self.kwargs.default_host
    self.application_name = self.kwargs.application_name or "Turbo.lua v2"
end

--- Sets the server name.
-- @param name (String) Set the server name of the Application.
function web.Application:set_server_name(name)
    self.application_name = name
end

--- Returns the server name.
-- @return (String) Server name.
function web.Application:get_server_name() return self.application_name end

--- Add handler to Application.
-- @param pattern (String) Lua pattern string.
-- @param handler (RequestHandler class)
-- @param arg Argument for handler.
function web.Application:add_handler(pattern, handler, arg)
    self.handlers[#self.handlers + 1] = {pattern, handler, arg}
end

--- Starts an HTTP server for this application on the given port.
-- This is really just a convinence method. The same effect can be achieved
-- by creating a HTTPServer class instance and assigning the Application to
-- instance to its request_callback parameter and calling its listen()
-- method.
-- @param port (Number) Port to bind server to.
-- @param address (String) Address to bind server to. E.g "127.0.0.1".
-- @param kwargs (Table) Keyword arguments passed on to
--      ``turbo.httpserver.HTTPServer``. See documentation for that class for
--      available options.
function web.Application:listen(port, address, kwargs)
    -- Key word arguments supported:
    -- ** SSL Options **
    -- To enable SSL remember to set the _G.TURBO_SSL global.
    -- ``key_file`` = SSL key file if a SSL enabled server is wanted.
    -- ``cert_file`` = Certificate file. key_file must also be set.
    local server = httpserver.HTTPServer:new(self, nil, nil, nil, kwargs)
    server:listen(port, address)
end

--- Find a matching request handler for the request object.
-- Simply match the URI against the pattern matches supplied to the Application
-- class.
-- @param request (HTTPRequest instance)
function web.Application:_get_request_handlers(request)
    local path = request.path
    if not path then
        path = "/"
    end
    local handlers_sz = #self.handlers
    for i = 1, handlers_sz do
        local handler = self.handlers[i]
        local pattern = handler[1]
        local match = {path:match(pattern)}
        if #match > 0 then
            return handler[2], match, handler[3]
        end
    end
end

local _str_borders_down = string.rep("▼", 80)
local _str_borders_up = string.rep("▲", 80)
--- Entry point for requests receive by HTTPServer.
-- @param request (HTTPRequest instance)
function web.Application:__call(request)
    local handler = nil
    local handlers, args, options = self:_get_request_handlers(request)
    if handlers then
        handler = handlers(self, request, args, options)
        local status, err = pcall(handler._execute, handler)
        if err then
            if instanceOf(web.HTTPError, err) then
                web.ErrorHandler(self,
                    request,
                    err.code,
                    err.message)
            elseif type(err) == "string" then
                local thread = coroutine.running()
                local trace = debug.traceback(coroutine.running(), err, 2)

                log.error(
                    string.format(
                        "[web.lua] Error in RequestHandler, %s is dead.\n%s\n%s\n%s",
                        thread,
                        _str_borders_down,
                        trace,
                        _str_borders_up))
                web.ErrorHandler(
                    self,
                    request,
                    500,
                    string.format('<pre style="font-size:12px; font-family:monospace; color:#8B0000;">[web.lua] Error in RequestHandler, %s is dead.\r\n%s\r\n%s\r\n%s</pre>',
                        thread, _str_borders_down, escape.html_escape(trace), _str_borders_up))
            else
                local thread = coroutine.running()
                local trace = debug.traceback(coroutine.running(),
                                              log.stringify(err), 2)

                log.error(
                    string.format(
                        "[web.lua] Unknown error in RequestHandler, %s is dead.\n%s\n%s\n%s",
                        thread,
                        _str_borders_down,
                        trace,
                        _str_borders_up))
                web.ErrorHandler(
                    self,
                    request,
                    500,
                    string.format('<pre style="font-size:12px; font-family:monospace; color:#8B0000;">[web.lua] Unknown error in RequestHandler, %s is dead.\r\n%s\r\n%s\r\n%s</pre>',
                        thread, _str_borders_down, escape.html_escape(trace), _str_borders_up))
            end
        end
    elseif not handlers and self.default_host then
        handler = web.RedirectHandler(self, request, nil, self.default_host):_execute()
    else
        handler = web.ErrorHandler(self, request, 404)
    end
end

return web


text:
package metrics

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	go_metrics "github.com/rcrowley/go-metrics"
)

// Well-known metric names.
const (
	ServerHandler       = "server_handler"
	ServerQueryCacheHit = "server_query_cache_hit"
	RegoQueryCompile    = "rego_query_compile"
	RegoQueryEval       = "rego_query_eval"
	RegoQueryParse      = "rego_query_parse"
	RegoModuleParse     = "rego_module_parse"
	RegoDataParse       = "rego_data_parse"
	RegoModuleCompile   = "rego_module_compile"
	RegoPartialEval     = "rego_partial_eval"
	RegoInputParse      = "rego_input_parse"
	RegoLoadFiles       = "rego_load_files"
	RegoLoadBundles     = "rego_load_bundles"
)

// Info contains attributes describing the underlying metrics provider.
type Info struct {
	Name string `json:"name"` // name is a unique human-readable identifier for the provider.
}

// Metrics defines the interface for a collection of performance metrics in the
// policy engine.
type Metrics interface {
	Info() Info
	Timer(name string) Timer
	Histogram(name string) Histogram
	Counter(name string) Counter
	All() map[string]interface{}
	Clear()
	json.Marshaler
}

type metrics struct {
	mtx        sync.Mutex
	timers     map[string]Timer
	histograms map[string]Histogram
	counters   map[string]Counter
}

// New returns a new Metrics object.
func New() Metrics {
	m := &metrics{}
	m.Clear()
	return m
}

type metric struct {
	Key   string
	Value interface{}
}

func (m *metrics) Info() Info {
	return Info{
		Name: "<built-in>",
	}
}

func (m *metrics) String() string {

	all := m.All()
	sorted := make([]metric, 0, len(all))

	for key, value := range all {
		sorted = append(sorted, metric{
			Key:   key,
			Value: value,
		})
	}

	sort.Slice(sorted, func(i, j int) bool {
		return sorted[i].Key < sorted[j].Key
	})

	buf := make([]string, len(sorted))
	for i := range sorted {
		buf[i] = fmt.Sprintf("%v:%v", sorted[i].Key, sorted[i].Value)
	}

	return strings.Join(buf, " ")
}

func (m *metrics) MarshalJSON() ([]byte, error) {
	return json.Marshal(m.All())
}

func (m *metrics) Timer(name string) Timer {
	m.mtx.Lock()
	defer m.mtx.Unlock()
	t, ok := m.timers[name]
	if !ok {
		t = &timer{}
		m.timers[name] = t
	}
	return t
}

func (m *metrics) Histogram(name string) Histogram {
	m.mtx.Lock()
	defer m.mtx.Unlock()
	h, ok := m.histograms[name]
	if !ok {
		h = newHistogram()
		m.histograms[name] = h
	}
	return h
}

func (m *metrics) Counter(name string) Counter {
	m.mtx.Lock()
	defer m.mtx.Unlock()
	c, ok := m.counters[name]
	if !ok {
		zero := counter{}
		c = &zero
		m.counters[name] = c
	}
	return c
}

func (m *metrics) All() map[string]interface{} {
	m.mtx.Lock()
	defer m.mtx.Unlock()
	result := map[string]interface{}{}
	for name, timer := range m.timers {
		result[m.formatKey(name, timer)] = timer.Value()
	}
	for name, hist := range m.histograms {
		result[m.formatKey(name, hist)] = hist.Value()
	}
	for name, cntr := range m.counters {
		result[m.formatKey(name, cntr)] = cntr.Value()
	}
	return result
}

func (m *metrics) Clear() {
	m.mtx.Lock()
	defer m.mtx.Unlock()
	m.timers = map[string]Timer{}
	m.histograms = map[string]Histogram{}
	m.counters = map[string]Counter{}
}

func (m *metrics) formatKey(name string, metrics interface{}) string {
	switch metrics.(type) {
	case Timer:
		return "timer_" + name + "_ns"
	case Histogram:
		return "histogram_" + name
	case Counter:
		return "counter_" + name
	default:
		return name
	}
}

// Timer defines the interface for a restartable timer that accumulates elapsed
// time.
type Timer interface {
	Value() interface{}
	Int64() int64
	Start()
	Stop() int64
}

type timer struct {
	mtx   sync.Mutex
	start time.Time
	value int64
}

func (t *timer) Start() {
	t.mtx.Lock()
	defer t.mtx.Unlock()
	t.start = time.Now()
}

func (t *timer) Stop() int64 {
	t.mtx.Lock()
	defer t.mtx.Unlock()
	delta := time.Now().Sub(t.start).Nanoseconds()
	t.value += delta
	return delta
}

func (t *timer) Value() interface{} {
	return t.Int64()
}

func (t *timer) Int64() int64 {
	t.mtx.Lock()
	defer t.mtx.Unlock()
	return t.value
}

// Histogram defines the interface for a histogram with hardcoded percentiles.
type Histogram interface {
	Value() interface{}
	Update(int64)
}

type histogram struct {
	hist go_metrics.Histogram // is thread-safe because of the underlying ExpDecaySample
}

func newHistogram() Histogram {
	// NOTE(tsandall): the reservoir size and alpha factor are taken from
	// https://github.com/rcrowley/go-metrics. They may need to be tweaked in
	// the future.
	sample := go_metrics.NewExpDecaySample(1028, 0.015)
	hist := go_metrics.NewHistogram(sample)
	return &histogram{hist}
}

func (h *histogram) Update(v int64) {
	h.hist.Update(v)
}

func (h *histogram) Value() interface{} {
	values := map[string]interface{}{}
	snap := h.hist.Snapshot()
	percentiles := snap.Percentiles([]float64{
		0.5,
		0.75,
		0.9,
		0.95,
		0.99,
		0.999,
		0.9999,
	})
	values["count"] = snap.Count()
	values["min"] = snap.Min()
	values["max"] = snap.Max()
	values["mean"] = snap.Mean()
	values["stddev"] = snap.StdDev()
	values["median"] = percentiles[0]
	values["75%"] = percentiles[1]
	values["90%"] = percentiles[2]
	values["95%"] = percentiles[3]
	values["99%"] = percentiles[4]
	values["99.9%"] = percentiles[5]
	values["99.99%"] = percentiles[6]
	return values
}

// Counter defines the interface for a monotonic increasing counter.
type Counter interface {
	Value() interface{}
	Incr()
}

type counter struct {
	c uint64
}

func (c *counter) Incr() {
	atomic.AddUint64(&c.c, 1)
}

func (c *counter) Value() interface{} {
	return atomic.LoadUint64(&c.c)
}


text:
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Jenny Yu, Hewlett-Packard Company (jenny_yu@hp.com)
//
// Modified By:
//        Sushma Fernandes, Hewlett-Packard Company (sushma_fernandes@hp.com)
//        Nag Boranna, Hewlett-Packard Company (nagaraja_boranna@hp.com)
//
//%////////////////////////////////////////////////////////////////////////////

#ifndef ShutdownProvider_h
#define ShutdownProvider_h

///////////////////////////////////////////////////////////////////////////////
//  Shutdown Provider
///////////////////////////////////////////////////////////////////////////////

#include <Pegasus/Common/Config.h>
#include <Pegasus/Common/Tracer.h>

#include <Pegasus/Common/IPC.h>
#include <Pegasus/Provider/CIMMethodProvider.h>
#include <Pegasus/Server/ShutdownService.h>
#include <Pegasus/Server/Linkage.h>

PEGASUS_NAMESPACE_BEGIN

/**
    The ShutdownProvider is a method provider that implements the shutdown
    method in the PG_ShutdownService class.  It provides response to the
    shutdown request from clients to shutdown cimom gracefully.
*/

class PEGASUS_SERVER_LINKAGE ShutdownProvider
    : public CIMMethodProvider
{
public:

    /** Constructor */
    ShutdownProvider(CIMServer* cimserver)
    {
        PEG_METHOD_ENTER(TRC_SHUTDOWN, "ShutdownProvider::ShutdownProvider");

        //
        // get an instance of the Shutdown Service
        //
        _shutdownService = ShutdownService::getInstance(cimserver);

        PEG_METHOD_EXIT();
    }

    /** Destructor */
    virtual ~ShutdownProvider()
    {
        PEG_METHOD_ENTER(TRC_SHUTDOWN,"ShutdownProvider::~ShutdownProvider");
        PEG_METHOD_EXIT();
    }

    void terminate(void)
    {
        PEG_METHOD_ENTER(TRC_SHUTDOWN,"ShutdownProvider::terminate");
	delete this;
        PEG_METHOD_EXIT();
    }

    /**
        Invoke Method.  Used to shutdown cimom.
    */
    void invokeMethod(
        const OperationContext & context,
        const CIMObjectPath & objectReference,
        const CIMName & methodName,
        const Array<CIMParamValue> & inParameters,
        MethodResultResponseHandler & handler);

    /**
     Standard initialization function for the provider.
    */
    void initialize(CIMOMHandle& cimomHandle)
    {
        // This method should never be called, since this is an internal
        // control provider
    }

private:

    //
    // Shutdown Service Instance variable
    //
    ShutdownService*      _shutdownService;
};

PEGASUS_NAMESPACE_END

#endif  // ShutdownProvider_h


text:
package scalaj
package collection
package s2j

import java.{lang => jl, util => ju}
import scala.{collection => sc, math => sm}
import scala.collection.{immutable => sci, mutable => scm}

object Implicits extends Implicits

trait Implicits {
  implicit def RichSOrdered[A](underlying: sm.Ordered[A]): RichOrdered[A] = new RichOrdered(underlying)
  implicit def RichSOrdering[A](underlying: sm.Ordering[A]): RichOrdering[A] = new RichOrdering(underlying)
  implicit def RichSIterator[A](underlying: sc.Iterator[A]): RichIterator[A] = new RichIterator(underlying)
  implicit def RichSIterable[A](underlying: sc.Iterable[A]): RichIterable[A] = new RichIterable(underlying)
  implicit def RichSSeq[A](underlying: sc.Seq[A]): RichSeq[A] = new RichSeq(underlying)
  implicit def RichSMutableSeq[A](underlying: scm.Seq[A]): RichMutableSeq[A] = new RichMutableSeq(underlying)
  implicit def RichSBuffer[A](underlying: scm.Buffer[A]): RichBuffer[A] = new RichBuffer(underlying)
  implicit def RichSSet[A](underlying: sc.Set[A]): RichSet[A] = new RichSet(underlying)
  implicit def RichSMutableSet[A](underlying: scm.Set[A]): RichMutableSet[A] = new RichMutableSet(underlying)
  implicit def RichSMap[A, B](underlying: sc.Map[A, B]): RichMap[A, B] = new RichMap(underlying)
  implicit def RichSMutableMap[A, B](underlying: scm.Map[A, B]): RichMutableMap[A, B] = new RichMutableMap(underlying)
}

sealed trait Coercible[-A, +B] {
  def apply(x: A): B
}

object Coercible extends LowPriorityCoercible {
  private[collection] def coerce[M[_], A, B](m: M[A])(implicit c: Coercible[A, B]): M[B] = m.asInstanceOf[M[B]]
  private[collection] def coerce2[M[_, _], A, B, C, D](m: M[A, B])(implicit c1: Coercible[A, C], c2: Coercible[B, D]): M[C, D] = m.asInstanceOf[M[C, D]]

  implicit object CoercibleBoolean extends PrimitiveCoercible[Boolean, jl.Boolean]
  implicit object CoercibleChar extends PrimitiveCoercible[Char, jl.Character]
  implicit object CoercibleByte extends PrimitiveCoercible[Byte, jl.Byte]
  implicit object CoercibleShort extends PrimitiveCoercible[Short, jl.Short]
  implicit object CoercibleInt extends PrimitiveCoercible[Int, jl.Integer]
  implicit object CoercibleLong extends PrimitiveCoercible[Long, jl.Long]
  implicit object CoercibleFloat extends PrimitiveCoercible[Float, jl.Float]
  implicit object CoercibleDouble extends PrimitiveCoercible[Double, jl.Double]

  private[Coercible] class PrimitiveCoercible[A, B] extends Coercible[A, B] {
    override def apply(x: A): B = x.asInstanceOf[B]
  }
}

trait LowPriorityCoercible {
  implicit def CoercibleSelf[A]: Coercible[A, A] = CoercibleSelfObject.asInstanceOf[Coercible[A, A]]

  private object CoercibleSelfObject extends Coercible[Any, Any] {
    override def apply(x: Any): Any = x
  }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
所有类
</TITLE>

<META NAME="date" CONTENT="2015-02-03">

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

所有类

AbsServer

AccessToken

AccessTokenMemServer

AccessTokenServer

AccessTokenTimer

AccountManager

ArticleResponse

Config

CustomerMsg

CustomerServer

EventType

ImageResponse

IServer

Item

JsApiTicketMemServer

JsApiTicketServer

JsApiTicketTimer

MediaFile

MediaType

MsgType

MusicResponse

ScanCodeInfo

SendLocationInfo

SendPicsInfo

SignatureParam

TemplateMsg

TemplateMsgBody

TemplateMsgData

Ticket

TicketServer

TicketType

Token

TokenListener

TokenProxy

TokenServer

UserManager

ValidateSignature

VideoResponse

VoiceResponse

WechatParamName

WechatRequest

WechatResponse

WechatSupport


text:
begin
  require 'blacklight'
  require 'blacklight/gallery'
  require 'blacklight_advanced_search'
  require 'blacklight/maps'
  require 'blacklight_range_limit'
  require 'blacklight_iiif_search'
  require 'typhoeus'
  require 'font-awesome-sass'
  require 'unicode'
  require 'madison'
  require 'rsolr' unless defined? RSolr
  require 'iiif/presentation'
  require 'recaptcha'
rescue LoadError => e
  puts "A Gem Dependency is Missing....#{e.message}"
end

module CommonwealthVlrEngine
  class Engine < Rails::Engine
    # for db migrations
    engine_name 'commonwealth_vlr_engine'

    # This makes our rake tasks visible.
    rake_tasks do
      Dir.chdir(File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))) do
        Dir.glob(File.join('tasks', '*.rake')).each do |railtie|
          load railtie
        end
        Dir.glob(File.join('lib/railties', '*.rake')).each do |railtie|
          load railtie
        end
      end
    end

    # as of sprockets >= 4 have to explicitly declare each file
    initializer 'commonwealth.assets.precompile' do |app|
      vlr_asset_base_path = File.join(CommonwealthVlrEngine.root, 'app', 'assets')
      vlr_assets = [
        Dir.glob(File.join(vlr_asset_base_path, 'images', 'commonwealth-vlr-engine', '*.{gif,png}')),
        Dir.glob(File.join(vlr_asset_base_path, 'javascripts', 'commonwealth-vlr-engine', '*'))
      ]
      vlr_assets.each do |assets|
        assets.each do |asset|
          asset_filename = asset.split('/').last.gsub(/\.erb/, '')
          app.config.assets.precompile << "commonwealth-vlr-engine/#{asset_filename}"
        end
      end
      osd_images = Dir.glob(File.join(vlr_asset_base_path, 'images', 'commonwealth-vlr-engine', 'openseadragon', '*.png'))
      osd_images.each do |osd_img|
        app.config.assets.precompile << "commonwealth-vlr-engine/openseadragon/#{osd_img.split('/').last}"
      end
      app.config.assets.precompile << 'openseadragon.js'
    end
  end
end


text:
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/
/**********************************************************\
 *                                                        *
 * ConnectionHandler.java                                 *
 *                                                        *
 * hprose ConnectionHandler interface for Java.           *
 *                                                        *
 * LastModified: Apr 21, 2016                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/
package hprose.net;

import java.nio.ByteBuffer;

public interface ConnectionHandler {
    void onConnect(Connection conn);
    void onConnected(Connection conn);
    void onReceived(Connection conn, ByteBuffer data, Integer id);
    void onSended(Connection conn, Integer id);
    void onClose(Connection conn);
    void onError(Connection conn, Exception e);
    void onTimeout(Connection conn, TimeoutType type);
    int getReadTimeout();
    int getWriteTimeout();
    int getConnectTimeout();
}