text:
---
layout: post
title: "Hello World Spring 3"
tags: [spring, spring mvc, java, java web, webdev]
image:
  feature: posts/2014-09-23/spring-framework.png
comments: true
share: true
---

Nesse post explicarei como fazer criar um projeto spring mvc de forma rápida e fácil.

Nosso projeto terá:

- Um controlador que recebe uma requisição `GET` e retorna uma mensagem

As tecnologias usadas serão:

- Spring 3.2.11-RELEASE
- JDK 1.7
- Maven 3
- Intellij IDEA 13

### Criando a estrutura de diretórios

Essa é a estrutura necessária para a criação de aplicativos web com o maven.

{% highlight bash %}
springHelloWorld/
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── phillipe
        │           └── web
        │               └── controllers
        │                   └── HelloController.java
        ├── resources
        └── webapp
            └── WEB-INF
                ├── mvc-dispatcher-servlet.xml
                ├── pages
                │   └── hello.jsp
                └── web.xml
{% endhighlight %}

### Configurando a aplicação

Nessa parte, vamos editar os arquivos *pom.xml*, *mvc-dispatcher-servlet.xml* e *web.xml*.

- **mvc-dispatcher-servlet.xml**: Contém as configurações do Spring MVC. O *bean* que será configurado aqui vai dizer onde estão as páginas do projeto e qual sua extensão (.html, .jsp, .jsf, .xhtml, etc);
- **web.xml**: Também conhecido como [*Deployment Descriptor* (DD)](https://cloud.google.com/appengine/docs/java/config/webxml). Aqui configuramos o *servlet* e o *listener* do Spring. Uma boa referência para se entender bem sobre *servlets* é o livro *Use a Cabeça! Servlets & JSP*.

Vamos para o que interessa! No *pom.xml* adicionamos as dependências para o Spring MVC:

{% highlight xml %}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.phillipe</groupId>
    <artifactId>springHelloWorld</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <spring.version>3.2.11.RELEASE</spring.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

    </dependencies>
</project>
{% endhighlight %}

Configuramos o pacote onde o Spring procurará pelo controller e onde e qual o formato das páginas no *mvc-dispatcher-servlet.xml*:

{% highlight xml %}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.phillipe.web.controllers"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
{% endhighlight %}

Configuramos o servlet do Spring e criamos um mapeamento para ele no *web.xml*:

{% highlight xml %}
<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring MVC Application</display-name>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>
{% endhighlight %}

### Programando o controller

Agora que já temos tudo configurado, criamos um controller. Só lembrando que ele deve estar dentro do pacote configurado no *mvc-dispatcher-servlet.xml*.

{% highlight java %}
package com.phillipe.web.controllers;

@Controller
@RequestMapping
public class HelloController {

    /*Captura a url '/hello'. */
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String helloWorldMethod(ModelMap model) {

    /*
    Adicionamos um atributo com nome 'message'.
    Poderemos acessar esse atributo na página depois.
    Note que no lugar de "Hello World!" também podemos colocar qualquer objeto!.
    */
        model.addAttribute("message", "Hello World!");

        // "hello" é o nome sem sufixo da página que a gente criou,
        // no caso é hello.jsp
        return "hello";
    }
}
{% endhighlight %}

### Programando a página

Agora só resta criar a view. É um html simples que exibe a mensagem que criamos no controller.

{% highlight jsp %}

<%-- Usamos ${nomeDoAtributo} para poder acessar
os atributos adicionados pelo controller. --%>

Message : ${message}

{% endhighlight %}

Isso é tudo, agora é só dar deploy no container de sua preferência e ver o resultado.

Sugestões ou erros no exemplo? Comente :)

Download:

- [https://github.com/paflopes/springHelloWorld.git](https://github.com/paflopes/springHelloWorld.git)

Referências:

- [Spring 3 MVC hello world example (mkyong.com)](http://www.mkyong.com/spring3/spring-3-mvc-hello-world-example/)
- Head First Servlets & JSP - 2nd edition

redpajama_set_name: RedPajamaGithub


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\TbBnDetalleActaDescargoSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'CodigoDetalleActaDescargo') ?>

    <?= $form->field($model, 'CodigoActaDescargo') ?>

    <?= $form->field($model, 'CodigoDetalleActaAsignacion') ?>

    <?= $form->field($model, 'CodigoEquipo') ?>

    <?= $form->field($model, 'CodigoActaAsignacion') ?>

    <?php // echo $form->field($model, 'CodigoEstadoEquipo') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
using RsPackage;
using RsPackage.ReportingService;
using RsPackage.Execution;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RsPackage.Logging;

namespace RsPackage.Factory
{
    public class ServiceBuilder
    {
        private Options options;
        private ReportingService2010 rs;
        private ILogger logger;
        private Dictionary<Type, BaseService> services;
        private bool isBuilt;

        public ServiceBuilder()
        {
            this.logger = new NullLogger();
            this.services = new Dictionary<Type, BaseService>();
            this.isBuilt = false;
        }

        public void Setup(Options options)
        {
            this.options = options;
            this.isBuilt = false;
        }

        public void Build()
        {
            this.rs = BuildReportingService(options);
            this.logger = BuildLogger(options);
            AddService(new ReportService(rs));
            AddService(new FolderService(rs));
            AddService(new DataSourceService(rs));
            AddService(new PolicyService(rs));
            this.isBuilt = true;
        }

        private void AddService(BaseService service)
        {
            services.Add(service.GetType(), service);
            service.MessageSent += logger.WriteMessage;
        }

        protected virtual ILogger BuildLogger(Options options)
        {
            var loggerFactory = new LoggerFactory();
            return loggerFactory.Build(options);
        }

        protected virtual ReportingService2010 BuildReportingService(Options options)
        {
            var rs = new ReportingService2010();
            var urlBuilder = new UrlBuilder();
            urlBuilder.Setup(options);
            urlBuilder.Build();
            rs.Url = urlBuilder.GetUrl();
            rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            return rs;
        }

        protected virtual BaseService GetService(Type type)
        {
            if (!isBuilt)
                throw new InvalidOperationException();

            if (services.ContainsKey(type))
                return services[type];
            else
                throw new ArgumentOutOfRangeException();
        }

        public ReportService GetReportService()
        {
            return (ReportService)GetService(typeof(ReportService));
        }

        public FolderService GetFolderService()
        {
            return (FolderService)GetService(typeof(FolderService));
        }

        public DataSourceService GetDataSourceService()
        {
            return (DataSourceService)GetService(typeof(DataSourceService));
        }

        public PolicyService GetPolicyService()
        {
            return (PolicyService)GetService(typeof(PolicyService));
        }
    }
}


text:
'use strict';

module.exports = function whereNotNull() {
  var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  return this.where(key, '!==', null);
};


text:
class Number < ActiveRecord::Base
  has_many :lexemes

  def to_s
    value
  end
end


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
// German
var strings = {
  prefixAgo: 'vor',
  prefixFromNow: 'in',
  suffixAgo: '',
  suffixFromNow: '',
  seconds: 'wenigen Sekunden',
  minute: 'etwa einer Minute',
  minutes: '%d Minuten',
  hour: 'etwa einer Stunde',
  hours: '%d Stunden',
  day: 'etwa einem Tag',
  days: '%d Tagen',
  month: 'etwa einem Monat',
  months: '%d Monaten',
  year: 'etwa einem Jahr',
  years: '%d Jahren'
};
var _default = strings;
exports["default"] = _default;


text:
//
//  OLFacebookPhotosOfUserRequest.m
//  FacebookImagePicker
//
//  Created by Andrew Morris on 14/08/2015.
//  Copyright (c) 2015 Deon Botha. All rights reserved.
//

#import "OLFacebookPhotosOfUserRequest.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import "OLFacebookImage.h"
#import "OLFacebookImagePickerConstants.h"

@interface OLFacebookPhotosOfUserRequest ()
@property (nonatomic, assign) BOOL cancelled;
@property (nonatomic, strong) NSString *after;
@end

@implementation OLFacebookPhotosOfUserRequest

- (id)initAfter:(NSString *)after {

    if (self = [super init]) {
        self.after = after;
    }

    return self;
}

- (void)getPhotos:(OLFacebookPhotosOfUserRequestHandler)handler {

    __block BOOL runOnce = NO;

    if ([FBSDKAccessToken currentAccessToken]) {

        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        if (runOnce || self.cancelled) {
            return;
        }
        runOnce = YES;

        NSString *graphPath = @"me/photos?limit=500";
        if (self.after) {
            graphPath = [graphPath stringByAppendingFormat:@"&after=%@", self.after];
        }
        [[[FBSDKGraphRequest alloc] initWithGraphPath:graphPath
                                           parameters:@{@"fields": @"picture, source, images"}]
                           startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

             if (!error) {
                 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                 if (self.cancelled) {
                     return;
                 }

                 NSString *parsingErrorMessage = @"Failed to parse Facebook Response. Please check your internet connectivity and try again.";
                 NSError *parsingError = [NSError errorWithDomain:kOLErrorDomainFacebookImagePicker code:kOLErrorCodeFacebookImagePickerBadResponse userInfo:@{NSLocalizedDescriptionKey: parsingErrorMessage}];
                 id data = [result objectForKey:@"data"];
                 if (![data isKindOfClass:[NSArray class]]) {
                     handler(nil, parsingError, nil);
                     return;
                 }

                 NSMutableArray *photosOfUser = [[NSMutableArray alloc] init];
                 for (id photo in data) {
                     id thumbURLString = [photo objectForKey:@"picture"];
                     id fullURLString  = [photo objectForKey:@"source"];

                     if (!([thumbURLString isKindOfClass:[NSString class]] && [fullURLString isKindOfClass:[NSString class]])) {
                         continue;
                     }

                     NSMutableArray *sourceImages = [[NSMutableArray alloc] init];
                     if ([photo[@"images"] isKindOfClass:[NSArray class]]) {
                         for (id image in photo[@"images"]) {
                             id source = image[@"source"];
                             id width = image[@"width"];
                             id height = image[@"height"];
                             if ([source isKindOfClass:[NSString class]] &&
                                 [width isKindOfClass:[NSNumber class]] &&
                                 [height isKindOfClass:[NSNumber class]]) {
                                 [sourceImages addObject:[[OLFacebookImageURL alloc] initWithURL:[NSURL URLWithString:source] size:CGSizeMake([width doubleValue], [height doubleValue])]];
                             }
                         }
                     }

                     OLFacebookImage *image = [[OLFacebookImage alloc] initWithThumbURL:[NSURL URLWithString:thumbURLString] fullURL:[NSURL URLWithString:fullURLString] albumId:nil sourceImages:sourceImages];
                     [photosOfUser addObject:image];
                 }

                 // get next page cursor
                 OLFacebookPhotosOfUserRequest *nextPageRequest = nil;
                 id paging = [result objectForKey:@"paging"];
                 if ([paging isKindOfClass:[NSDictionary class]]) {
                     id cursors = [paging objectForKey:@"cursors"];
                     id next = [paging objectForKey:@"next"]; // next will be non nil if a next page exists
                     if (next && [cursors isKindOfClass:[NSDictionary class]]) {
                         id after = [cursors objectForKey:@"after"];
                         if ([after isKindOfClass:[NSString class]]) {
                             nextPageRequest = [[OLFacebookPhotosOfUserRequest alloc] initAfter:after];
                         }
                     }
                 }

                 handler(photosOfUser, nil, nextPageRequest);
             }
         }];
    }
}

- (void)cancel {

    self.cancelled = YES;
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

+ (void)handleFacebookError:(NSError *)error completionHandler:(OLFacebookPhotosOfUserRequestHandler)handler {

    /*
     NSString *message;
     if ([FBErrorUtility shouldNotifyUserForError:error]) {
     message = [FBErrorUtility userMessageForError:error];
     } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession) {
     message = @"Your current Facebook session is no longer valid. Please log in again.";
     } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
     message = @"The app requires authorization to access your Facebook photos to continue. Please open Settings and provide access.";
     } else {
     message = @"Failed to access your Facebook photos. Please check your internet connectivity and try again.";
     }

     handler(nil, [NSError errorWithDomain:error.domain code:error.code userInfo:@{NSLocalizedDescriptionKey: message}], nil);

     */
}

@end


text:
package printer

import (
	"strings"
	"syscall"
	"time"
	"unsafe"

	"golang.org/x/sys/windows"
)

//go:generate go run mksyscall_windows.go -output zapi.go printer.go

type DOC_INFO_1 struct {
	DocName    *uint16
	OutputFile *uint16
	Datatype   *uint16
}

type PRINTER_INFO_5 struct {
	PrinterName              *uint16
	PortName                 *uint16
	Attributes               uint32
	DeviceNotSelectedTimeout uint32
	TransmissionRetryTimeout uint32
}

type DRIVER_INFO_8 struct {
	Version                  uint32
	Name                     *uint16
	Environment              *uint16
	DriverPath               *uint16
	DataFile                 *uint16
	ConfigFile               *uint16
	HelpFile                 *uint16
	DependentFiles           *uint16
	MonitorName              *uint16
	DefaultDataType          *uint16
	PreviousNames            *uint16
	DriverDate               syscall.Filetime
	DriverVersion            uint64
	MfgName                  *uint16
	OEMUrl                   *uint16
	HardwareID               *uint16
	Provider                 *uint16
	PrintProcessor           *uint16
	VendorSetup              *uint16
	ColorProfiles            *uint16
	InfPath                  *uint16
	PrinterDriverAttributes  uint32
	CoreDriverDependencies   *uint16
	MinInboxDriverVerDate    syscall.Filetime
	MinInboxDriverVerVersion uint32
}

type JOB_INFO_1 struct {
	JobID        uint32
	PrinterName  *uint16
	MachineName  *uint16
	UserName     *uint16
	Document     *uint16
	DataType     *uint16
	Status       *uint16
	StatusCode   uint32
	Priority     uint32
	Position     uint32
	TotalPages   uint32
	PagesPrinted uint32
	Submitted    syscall.Systemtime
}

const (
	PRINTER_ENUM_LOCAL       = 2
	PRINTER_ENUM_CONNECTIONS = 4

	PRINTER_DRIVER_XPS = 0x00000002
)

const (
	JOB_STATUS_PAUSED            = 0x00000001 // Job is paused
	JOB_STATUS_ERROR             = 0x00000002 // An error is associated with the job
	JOB_STATUS_DELETING          = 0x00000004 // Job is being deleted
	JOB_STATUS_SPOOLING          = 0x00000008 // Job is spooling
	JOB_STATUS_PRINTING          = 0x00000010 // Job is printing
	JOB_STATUS_OFFLINE           = 0x00000020 // Printer is offline
	JOB_STATUS_PAPEROUT          = 0x00000040 // Printer is out of paper
	JOB_STATUS_PRINTED           = 0x00000080 // Job has printed
	JOB_STATUS_DELETED           = 0x00000100 // Job has been deleted
	JOB_STATUS_BLOCKED_DEVQ      = 0x00000200 // Printer driver cannot print the job
	JOB_STATUS_USER_INTERVENTION = 0x00000400 // User action required
	JOB_STATUS_RESTART           = 0x00000800 // Job has been restarted
	JOB_STATUS_COMPLETE          = 0x00001000 // Job has been delivered to the printer
	JOB_STATUS_RETAINED          = 0x00002000 // Job has been retained in the print queue
	JOB_STATUS_RENDERING_LOCALLY = 0x00004000 // Job rendering locally on the client
)

//sys	GetDefaultPrinter(buf *uint16, bufN *uint32) (err error) = winspool.GetDefaultPrinterW
//sys	ClosePrinter(h syscall.Handle) (err error) = winspool.ClosePrinter
//sys	OpenPrinter(name *uint16, h *syscall.Handle, defaults uintptr) (err error) = winspool.OpenPrinterW
//sys	StartDocPrinter(h syscall.Handle, level uint32, docinfo *DOC_INFO_1) (err error) = winspool.StartDocPrinterW
//sys	EndDocPrinter(h syscall.Handle) (err error) = winspool.EndDocPrinter
//sys	WritePrinter(h syscall.Handle, buf *byte, bufN uint32, written *uint32) (err error) = winspool.WritePrinter
//sys	StartPagePrinter(h syscall.Handle) (err error) = winspool.StartPagePrinter
//sys	EndPagePrinter(h syscall.Handle) (err error) = winspool.EndPagePrinter
//sys	EnumPrinters(flags uint32, name *uint16, level uint32, buf *byte, bufN uint32, needed *uint32, returned *uint32) (err error) = winspool.EnumPrintersW
//sys	GetPrinterDriver(h syscall.Handle, env *uint16, level uint32, di *byte, n uint32, needed *uint32) (err error) = winspool.GetPrinterDriverW
//sys	EnumJobs(h syscall.Handle, firstJob uint32, noJobs uint32, level uint32, buf *byte, bufN uint32, bytesNeeded *uint32, jobsReturned *uint32) (err error) = winspool.EnumJobsW

func Default() (string, error) {
	b := make([]uint16, 3)
	n := uint32(len(b))
	err := GetDefaultPrinter(&b[0], &n)
	if err != nil {
		if err != syscall.ERROR_INSUFFICIENT_BUFFER {
			return "", err
		}
		b = make([]uint16, n)
		err = GetDefaultPrinter(&b[0], &n)
		if err != nil {
			return "", err
		}
	}
	return syscall.UTF16ToString(b), nil
}

// ReadNames return printer names on the system
func ReadNames() ([]string, error) {
	const flags = PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS
	var needed, returned uint32
	buf := make([]byte, 1)
	err := EnumPrinters(flags, nil, 5, &buf[0], uint32(len(buf)), &needed, &returned)
	if err != nil {
		if err != syscall.ERROR_INSUFFICIENT_BUFFER {
			return nil, err
		}
		buf = make([]byte, needed)
		err = EnumPrinters(flags, nil, 5, &buf[0], uint32(len(buf)), &needed, &returned)
		if err != nil {
			return nil, err
		}
	}
	ps := (*[1024]PRINTER_INFO_5)(unsafe.Pointer(&buf[0]))[:returned:returned]
	names := make([]string, 0, returned)
	for _, p := range ps {
		names = append(names, windows.UTF16PtrToString(p.PrinterName))
	}
	return names, nil
}

type Printer struct {
	h syscall.Handle
}

func Open(name string) (*Printer, error) {
	var p Printer
	// TODO: implement pDefault parameter
	err := OpenPrinter(&(syscall.StringToUTF16(name))[0], &p.h, 0)
	if err != nil {
		return nil, err
	}
	return &p, nil
}

// DriverInfo stores information about printer driver.
type DriverInfo struct {
	Name        string
	Environment string
	DriverPath  string
	Attributes  uint32
}

// JobInfo stores information about a print job.
type JobInfo struct {
	JobID           uint32
	UserMachineName string
	UserName        string
	DocumentName    string
	DataType        string
	Status          string
	StatusCode      uint32
	Priority        uint32
	Position        uint32
	TotalPages      uint32
	PagesPrinted    uint32
	Submitted       time.Time
}

// Jobs returns information about all print jobs on this printer
func (p *Printer) Jobs() ([]JobInfo, error) {
	var bytesNeeded, jobsReturned uint32
	buf := make([]byte, 1)
	for {
		err := EnumJobs(p.h, 0, 255, 1, &buf[0], uint32(len(buf)), &bytesNeeded, &jobsReturned)
		if err == nil {
			break
		}
		if err != syscall.ERROR_INSUFFICIENT_BUFFER {
			return nil, err
		}
		if bytesNeeded <= uint32(len(buf)) {
			return nil, err
		}
		buf = make([]byte, bytesNeeded)
	}
	if jobsReturned <= 0 {
		return nil, nil
	}
	pjs := make([]JobInfo, 0, jobsReturned)
	ji := (*[2048]JOB_INFO_1)(unsafe.Pointer(&buf[0]))[:jobsReturned:jobsReturned]
	for _, j := range ji {
		pji := JobInfo{
			JobID:        j.JobID,
			StatusCode:   j.StatusCode,
			Priority:     j.Priority,
			Position:     j.Position,
			TotalPages:   j.TotalPages,
			PagesPrinted: j.PagesPrinted,
		}
		if j.MachineName != nil {
			pji.UserMachineName = windows.UTF16PtrToString(j.MachineName)
		}
		if j.UserName != nil {
			pji.UserName = windows.UTF16PtrToString(j.UserName)
		}
		if j.Document != nil {
			pji.DocumentName = windows.UTF16PtrToString(j.Document)
		}
		if j.DataType != nil {
			pji.DataType = windows.UTF16PtrToString(j.DataType)
		}
		if j.Status != nil {
			pji.Status = windows.UTF16PtrToString(j.Status)
		}
		if strings.TrimSpace(pji.Status) == "" {
			if pji.StatusCode == 0 {
				pji.Status += "Queue Paused, "
			}
			if pji.StatusCode&JOB_STATUS_PRINTING != 0 {
				pji.Status += "Printing, "
			}
			if pji.StatusCode&JOB_STATUS_PAUSED != 0 {
				pji.Status += "Paused, "
			}
			if pji.StatusCode&JOB_STATUS_ERROR != 0 {
				pji.Status += "Error, "
			}
			if pji.StatusCode&JOB_STATUS_DELETING != 0 {
				pji.Status += "Deleting, "
			}
			if pji.StatusCode&JOB_STATUS_SPOOLING != 0 {
				pji.Status += "Spooling, "
			}
			if pji.StatusCode&JOB_STATUS_OFFLINE != 0 {
				pji.Status += "Printer Offline, "
			}
			if pji.StatusCode&JOB_STATUS_PAPEROUT != 0 {
				pji.Status += "Out of Paper, "
			}
			if pji.StatusCode&JOB_STATUS_PRINTED != 0 {
				pji.Status += "Printed, "
			}
			if pji.StatusCode&JOB_STATUS_DELETED != 0 {
				pji.Status += "Deleted, "
			}
			if pji.StatusCode&JOB_STATUS_BLOCKED_DEVQ != 0 {
				pji.Status += "Driver Error, "
			}
			if pji.StatusCode&JOB_STATUS_USER_INTERVENTION != 0 {
				pji.Status += "User Action Required, "
			}
			if pji.StatusCode&JOB_STATUS_RESTART != 0 {
				pji.Status += "Restarted, "
			}
			if pji.StatusCode&JOB_STATUS_COMPLETE != 0 {
				pji.Status += "Sent to Printer, "
			}
			if pji.StatusCode&JOB_STATUS_RETAINED != 0 {
				pji.Status += "Retained, "
			}
			if pji.StatusCode&JOB_STATUS_RENDERING_LOCALLY != 0 {
				pji.Status += "Rendering on Client, "
			}
			pji.Status = strings.TrimRight(pji.Status, ", ")
		}
		pji.Submitted = time.Date(
			int(j.Submitted.Year),
			time.Month(int(j.Submitted.Month)),
			int(j.Submitted.Day),
			int(j.Submitted.Hour),
			int(j.Submitted.Minute),
			int(j.Submitted.Second),
			int(1000*j.Submitted.Milliseconds),
			time.Local,
		).UTC()
		pjs = append(pjs, pji)
	}
	return pjs, nil
}

// DriverInfo returns information about printer p driver.
func (p *Printer) DriverInfo() (*DriverInfo, error) {
	var needed uint32
	b := make([]byte, 1024*10)
	for {
		err := GetPrinterDriver(p.h, nil, 8, &b[0], uint32(len(b)), &needed)
		if err == nil {
			break
		}
		if err != syscall.ERROR_INSUFFICIENT_BUFFER {
			return nil, err
		}
		if needed <= uint32(len(b)) {
			return nil, err
		}
		b = make([]byte, needed)
	}
	di := (*DRIVER_INFO_8)(unsafe.Pointer(&b[0]))
	return &DriverInfo{
		Attributes:  di.PrinterDriverAttributes,
		Name:        windows.UTF16PtrToString(di.Name),
		DriverPath:  windows.UTF16PtrToString(di.DriverPath),
		Environment: windows.UTF16PtrToString(di.Environment),
	}, nil
}

func (p *Printer) StartDocument(name, datatype string) error {
	d := DOC_INFO_1{
		DocName:    &(syscall.StringToUTF16(name))[0],
		OutputFile: nil,
		Datatype:   &(syscall.StringToUTF16(datatype))[0],
	}
	return StartDocPrinter(p.h, 1, &d)
}

// StartRawDocument calls StartDocument and passes either "RAW" or "XPS_PASS"
// as a document type, depending if printer driver is XPS-based or not.
func (p *Printer) StartRawDocument(name string) error {
	di, err := p.DriverInfo()
	if err != nil {
		return err
	}
	// See https://support.microsoft.com/en-us/help/2779300/v4-print-drivers-using-raw-mode-to-send-pcl-postscript-directly-to-the
	// for details.
	datatype := "RAW"
	if di.Attributes&PRINTER_DRIVER_XPS != 0 {
		datatype = "XPS_PASS"
	}
	return p.StartDocument(name, datatype)
}

func (p *Printer) Write(b []byte) (int, error) {
	var written uint32
	err := WritePrinter(p.h, &b[0], uint32(len(b)), &written)
	if err != nil {
		return 0, err
	}
	return int(written), nil
}

func (p *Printer) EndDocument() error {
	return EndDocPrinter(p.h)
}

func (p *Printer) StartPage() error {
	return StartPagePrinter(p.h)
}

func (p *Printer) EndPage() error {
	return EndPagePrinter(p.h)
}

func (p *Printer) Close() error {
	return ClosePrinter(p.h)
}


text:
using System.Collections.Concurrent;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;

namespace Microsoft.AspNetCore.Analyzers;

public abstract class StartupAnalyzerTest
{
    public StartupAnalyzerTest()
    {
        StartupAnalyzer = new StartupAnalyzer();

        Analyses = new ConcurrentBag<object>();
        ConfigureServicesMethods = new ConcurrentBag<IMethodSymbol>();
        ConfigureMethods = new ConcurrentBag<IMethodSymbol>();
        StartupAnalyzer.ServicesAnalysisCompleted += (sender, analysis) => Analyses.Add(analysis);
        StartupAnalyzer.OptionsAnalysisCompleted += (sender, analysis) => Analyses.Add(analysis);
        StartupAnalyzer.MiddlewareAnalysisCompleted += (sender, analysis) => Analyses.Add(analysis);
        StartupAnalyzer.ConfigureServicesMethodFound += (sender, method) => ConfigureServicesMethods.Add(method);
        StartupAnalyzer.ConfigureMethodFound += (sender, method) => ConfigureMethods.Add(method);
    }

    internal StartupAnalyzer StartupAnalyzer { get; }

    internal ConcurrentBag<object> Analyses { get; }

    internal ConcurrentBag<IMethodSymbol> ConfigureServicesMethods { get; }

    internal ConcurrentBag<IMethodSymbol> ConfigureMethods { get; }

    [Fact]
    public async Task StartupAnalyzer_FindsStartupMethods_StartupSignatures_Standard()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class StartupSignatures_Standard
    {
        public void ConfigureServices(IServiceCollection services)
        {
        }

        public void Configure(IApplicationBuilder app)
        {

        }
    }
}
";
        // Act
        await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);

        // Assert
        Assert.Collection(ConfigureServicesMethods, m => Assert.Equal("ConfigureServices", m.Name));
        Assert.Collection(ConfigureMethods, m => Assert.Equal("Configure", m.Name));
    }

    [Fact]
    public async Task StartupAnalyzer_FindsStartupMethods_StartupSignatures_MoreVariety()
    {
        // Arrange
        var source = @"
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class StartupSignatures_MoreVariety
    {
        public void ConfigureServices(IServiceCollection services)
        {
        }

        public void ConfigureServices(IServiceCollection services, StringBuilder s) // Ignored
        {
        }

        public void Configure(StringBuilder s) // Ignored,
        {
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
        }

        public void ConfigureProduction(IWebHostEnvironment env, IApplicationBuilder app)
        {
        }

        private void Configure(IApplicationBuilder app)  // Ignored
        {
        }
    }
}
";

        // Act
        await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);

        // Assert
        Assert.Collection(
            ConfigureServicesMethods.OrderBy(m => m.Name),
            m => Assert.Equal("ConfigureServices", m.Name));

        Assert.Collection(
            ConfigureMethods.OrderBy(m => m.Name),
            m => Assert.Equal("Configure", m.Name),
            m => Assert.Equal("ConfigureProduction", m.Name));
    }

    [Fact]
    public async Task StartupAnalyzer_MvcOptionsAnalysis_UseMvc_FindsEndpointRoutingDisabled()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class MvcOptions_UseMvcWithDefaultRouteAndEndpointRoutingDisabled
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => options.EnableEndpointRouting = false);
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseMvcWithDefaultRoute();
        }
    }
}";

        // Act
        await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);

        // Assert
        var optionsAnalysis = Assert.Single(Analyses.OfType<OptionsAnalysis>());
        Assert.True(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis));

        var middlewareAnalysis = Assert.Single(Analyses.OfType<MiddlewareAnalysis>());
        var middleware = Assert.Single(middlewareAnalysis.Middleware);
        Assert.Equal("UseMvcWithDefaultRoute", middleware.UseMethod.Name);
    }

    [Fact]
    public async Task StartupAnalyzer_MvcOptionsAnalysis_AddMvcOptions_FindsEndpointRoutingDisabled()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class MvcOptions_UseMvcWithDefaultRouteAndAddMvcOptionsEndpointRoutingDisabled
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddMvcOptions(options => options.EnableEndpointRouting = false);
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseMvcWithDefaultRoute();
        }
    }
}
";

        // Act
        await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);

        // Assert
        var optionsAnalysis = Assert.Single(Analyses.OfType<OptionsAnalysis>());
        Assert.True(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis));

        var middlewareAnalysis = Assert.Single(Analyses.OfType<MiddlewareAnalysis>());
        var middleware = Assert.Single(middlewareAnalysis.Middleware);
        Assert.Equal("UseMvcWithDefaultRoute", middleware.UseMethod.Name);
    }

    [Fact]
    public Task StartupAnalyzer_MvcOptionsAnalysis_UseMvc_FindsEndpointRoutingEnabled()
    {
        var source = @"
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class MvcOptions_UseMvc
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            {|#0:app.UseMvc()|};
        }
    }
}";
        var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting)
            .WithArguments("UseMvc", "ConfigureServices")
            .WithLocation(0);

        return VerifyMvcOptionsAnalysis(source, "UseMvc", diagnosticResult);
    }

    [Fact]
    public Task StartupAnalyzer_MvcOptionsAnalysis_UseMvcAndConfiguredRoutes_FindsEndpointRoutingEnabled()
    {
        var source = @"
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class MvcOptions_UseMvcAndConfiguredRoutes
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            {|#0:app.UseMvc(routes =>
            {
                routes.MapRoute(""Name"", ""Template"");
            })|};
        }
    }
}
";
        var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting)
            .WithArguments("UseMvc", "ConfigureServices")
            .WithLocation(0);

        return VerifyMvcOptionsAnalysis(source, "UseMvc", diagnosticResult);
    }

    [Fact]
    public Task StartupAnalyzer_MvcOptionsAnalysis_MvcOptions_UseMvcWithDefaultRoute_FindsEndpointRoutingEnabled()
    {
        var source = @"
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class MvcOptions_UseMvcWithDefaultRoute
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            {|#0:app.UseMvcWithDefaultRoute()|};
        }
    }
}
";
        var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting)
            .WithArguments("UseMvcWithDefaultRoute", "ConfigureServices")
            .WithLocation(0);

        return VerifyMvcOptionsAnalysis(source, "UseMvcWithDefaultRoute", diagnosticResult);
    }

    private async Task VerifyMvcOptionsAnalysis(string source, string mvcMiddlewareName, params DiagnosticResult[] diagnosticResults)
    {
        // Arrange
        await VerifyAnalyzerAsync(source, diagnosticResults);

        // Assert
        var optionsAnalysis = Analyses.OfType<OptionsAnalysis>().First();
        Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis));

        var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First();
        var middleware = Assert.Single(middlewareAnalysis.Middleware);
        Assert.Equal(mvcMiddlewareName, middleware.UseMethod.Name);
    }

    [Fact]
    public async Task StartupAnalyzer_MvcOptionsAnalysis_MultipleMiddleware()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class MvcOptions_UseMvcWithOtherMiddleware
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
            app.UseMiddleware<AuthorizationMiddleware>();

            {|#0:app.UseMvc()|};

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
            });
        }
    }
}";
        var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting)
            .WithLocation(0)
            .WithArguments("UseMvc", "ConfigureServices");

        // Act
        await VerifyAnalyzerAsync(source, diagnosticResult);

        // Assert
        var optionsAnalysis = Analyses.OfType<OptionsAnalysis>().First();
        Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis));

        var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First();

        Assert.Collection(
            middlewareAnalysis.Middleware,
            item => Assert.Equal("UseStaticFiles", item.UseMethod.Name),
            item => Assert.Equal("UseMiddleware", item.UseMethod.Name),
            item => Assert.Equal("UseMvc", item.UseMethod.Name),
            item => Assert.Equal("UseRouting", item.UseMethod.Name),
            item => Assert.Equal("UseEndpoints", item.UseMethod.Name));
    }

    [Fact]
    public async Task StartupAnalyzer_MvcOptionsAnalysis_MultipleUseMvc()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class MvcOptions_UseMvcMultiple
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            {|#0:app.UseMvcWithDefaultRoute()|};

            app.UseStaticFiles();
            app.UseMiddleware<AuthorizationMiddleware>();

            {|#1:app.UseMvc()|};

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
            });

            {|#2:app.UseMvc()|};
        }
    }
}";
        var diagnosticResults = new[]
        {
            new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting)
                .WithLocation(0)
                .WithArguments("UseMvcWithDefaultRoute", "ConfigureServices"),

            new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting)
                .WithLocation(1)
                .WithArguments("UseMvc", "ConfigureServices"),

            new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting)
                .WithLocation(2)
                .WithArguments("UseMvc", "ConfigureServices"),
        };

        // Act
        await VerifyAnalyzerAsync(source, diagnosticResults);

        // Assert
        var optionsAnalysis = Analyses.OfType<OptionsAnalysis>().First();
        Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis));
    }

    [Fact]
    public async Task StartupAnalyzer_ServicesAnalysis_CallBuildServiceProvider()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class ConfigureServices_BuildServiceProvider
    {
        public void ConfigureServices(IServiceCollection services)
        {
            {|#0:services.BuildServiceProvider()|};
        }

        public void Configure(IApplicationBuilder app)
        {
        }
    }
}";

        var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.BuildServiceProviderShouldNotCalledInConfigureServicesMethod)
            .WithLocation(0);

        // Act
        await VerifyAnalyzerAsync(source, diagnosticResult);

        // Assert
        var servicesAnalysis = Analyses.OfType<ServicesAnalysis>().First();
        Assert.NotEmpty(servicesAnalysis.Services);
    }

    [Fact]
    public async Task StartupAnalyzer_UseAuthorizationConfiguredCorrectly_ReportsNoDiagnostics()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class UseAuthConfiguredCorrectly
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(r => { });
        }
    }
}";

        // Act
        await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);

        // Assert
        var middlewareAnalysis = Assert.Single(Analyses.OfType<MiddlewareAnalysis>());
        Assert.NotEmpty(middlewareAnalysis.Middleware);
    }

    [Fact]
    public async Task StartupAnalyzer_UseAuthorizationConfiguredAsAChain_ReportsNoDiagnostics()
    {
        // Regression test for https://github.com/dotnet/aspnetcore/issues/15203
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest {
    public class UseAuthConfiguredCorrectlyChained
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting()
               .UseAuthorization()
               .UseEndpoints(r => { });
        }
    }
}";

        // Act
        await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);

        // Assert
        var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First();
        Assert.NotEmpty(middlewareAnalysis.Middleware);
    }

    [Fact]
    public async Task StartupAnalyzer_UseAuthorizationInvokedMultipleTimesInEndpointRoutingBlock_ReportsNoDiagnostics()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class UseAuthMultipleTimes
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();
            app.UseAuthorization();
            app.UseAuthorization();
            app.UseEndpoints(r => { });
        }
    }
}";

        // Act
        await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);

        // Assert
        var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First();
        Assert.NotEmpty(middlewareAnalysis.Middleware);
    }

    [Fact]
    public async Task StartupAnalyzer_UseAuthorizationConfiguredBeforeUseRouting_ReportsDiagnostics()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class UseAuthBeforeUseRouting
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseFileServer();
            {|#0:app.UseAuthorization()|};
            app.UseRouting();
            app.UseEndpoints(r => { });
        }
    }
}";

        var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.IncorrectlyConfiguredAuthorizationMiddleware)
            .WithLocation(0);

        // Act
        await VerifyAnalyzerAsync(source, diagnosticResult);
    }

    [Fact]
    public async Task StartupAnalyzer_UseAuthorizationConfiguredBeforeUseRoutingChained_ReportsDiagnostics()
    {
        // This one asserts a false negative for https://github.com/dotnet/aspnetcore/issues/15203.
        // We don't correctly identify chained calls, this test verifies the behavior.
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class UseAuthBeforeUseRoutingChained
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseFileServer()
               .UseAuthorization()
               .UseRouting()
               .UseEndpoints(r => { });
        }
    }
}";

        // Act
        await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);

        // Assert
        var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First();
        Assert.NotEmpty(middlewareAnalysis.Middleware);
    }

    [Fact]
    public async Task StartupAnalyzer_UseAuthorizationConfiguredAfterUseEndpoints_ReportsDiagnostics()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class UseAuthAfterUseEndpoints
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();
            app.UseEndpoints(r => { });
            {|#0:app.UseAuthorization()|};
        }
    }
}
";
        var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.IncorrectlyConfiguredAuthorizationMiddleware)
            .WithLocation(0);

        // Act
        await VerifyAnalyzerAsync(source, diagnosticResult);

        // Assert
        var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First();
        Assert.NotEmpty(middlewareAnalysis.Middleware);
    }

    [Fact]
    public async Task StartupAnalyzer_MultipleUseAuthorization_ReportsNoDiagnostics()
    {
        // Arrange
        var source = @"
using Microsoft.AspNetCore.Builder;

namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest
{
    public class UseAuthFallbackPolicy
    {
        public void Configure(IApplicationBuilder app)
        {
            // This sort of setup would be useful if the user wants to use Auth for non-endpoint content to be handled using the Fallback policy, while
            // using the second instance for regular endpoint routing based auth. We do not want to produce a warning in this case.
            app.UseAuthorization();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(r => { });
        }
    }
}";

        // Act
        await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults);

        // Assert
        var middlewareAnalysis = Assert.Single(Analyses.OfType<MiddlewareAnalysis>());
        Assert.NotEmpty(middlewareAnalysis.Middleware);
    }

    private Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
    {
        var test = new StartupCSharpAnalyzerTest(StartupAnalyzer, TestReferences.MetadataReferences)
        {
            TestCode = source,
            ReferenceAssemblies = TestReferences.EmptyReferenceAssemblies,
        };

        test.ExpectedDiagnostics.AddRange(expected);
        return test.RunAsync();
    }
}


text:
Views
=====

.. automodule:: bambu_bootstrap.views
   :members:


text:
<?php
namespace Lawoole\Foundation;

use Illuminate\Contracts\Foundation\Application as ApplicationContract;
use Illuminate\Events\EventServiceProvider;
use Illuminate\Foundation\Application as BaseApplication;
use Illuminate\Log\LogServiceProvider;

class Application extends BaseApplication implements ApplicationContract
{
    /**
     * The Lawoole framework version.
     *
     * @var string
     */
    const VERSION = '1.0.3';

    /**
     * The name of service.
     *
     * @var string
     */
    protected $name = 'The Lawoole Service';

    /**
     * Get the name of application.
     *
     * @return string
     */
    public function name()
    {
        return $this->name;
    }

    /**
     * Set the name of application.
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * {@inheritdoc}
     */
    public function version()
    {
        return static::VERSION.' (Laravel Components 5.7.*)';
    }

    /**
     * {@inheritdoc}
     */
    protected function registerBaseServiceProviders()
    {
        $this->register(new EventServiceProvider($this));
        $this->register(new LogServiceProvider($this));
    }

    /**
     * {@inheritdoc}
     */
    protected function bindPathsInContainer()
    {
        parent::bindPathsInContainer();

        $this->instance('path.route', $this->routePath());
    }

    /**
     * {@inheritdoc}
     */
    public function environmentPath()
    {
        return $this->environmentPath ?: $this->configPath('environment');
    }

    /**
     * Get the path to the route files.
     *
     * @return string
     */
    public function routePath()
    {
        return $this->basePath.DIRECTORY_SEPARATOR.'routes';
    }

    /**
     * {@inheritdoc}
     */
    public function registerConfiguredProviders()
    {
        $providers = $this['config']['app.providers'];

        // Since the service is started, the request can be processed repeatedly, and
        // we can ignore the consumption of the application startup, so that we do not
        // need to do delay registration and cache compilation.
        foreach ($providers as $provider) {
            $this->register($provider);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function configurationIsCached()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function routesAreCached()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function registerCoreContainerAliases()
    {
        parent::registerCoreContainerAliases();

        foreach ([
             'app'                  => [\Lawoole\Foundation\Application::class],
             'console.input'        => [\Symfony\Component\Console\Input\InputInterface::class],
             'console.output'       => [\Symfony\Component\Console\Output\OutputInterface::class],
             'console.output.style' => [\Illuminate\Console\OutputStyle::class, \Lawoole\Console\OutputStyle::class],
             'homer'                => [\Lawoole\Contracts\Homer\Homer::class, \Lawoole\Homer\HomerManager::class],
             'homer.context'        => [\Lawoole\Contracts\Homer\Context::class, \Lawoole\Homer\Context::class],
             'homer.dispatcher'     => [\Lawoole\Homer\Calling\Dispatcher::class],
             'respondent'           => [\Lawoole\Http\Respondent::class],
             'schedule'             => [\Illuminate\Console\Scheduling\Schedule::class],
             'server'               => [\Lawoole\Contracts\Server\Server::class, \Lawoole\Server\Server::class],
             'server.swoole'        => [\Swoole\Server::class],
             'snowflake'            => [\Lawoole\Contracts\Snowflake\Snowflake::class, \Lawoole\Snowflake\Snowflake::class],
         ] as $key => $aliases) {
            foreach ($aliases as $alias) {
                $this->alias($key, $alias);
            }
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>My Project: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

My Project

Here is a list of all class members with links to the classes they belong to:

contactsUtils()
: PhoneNumber

display()
: PhoneNumber

displayContent()
: PhoneNumber

insert()
: PhoneNumber

processing()
: PhoneNumber

<address class="footer">
Generated by

 1.8.13
</address>


text:
package policy

import (
	"log"
	"time"

	"github.com/coredns/coredns/plugin/dnstap"
	tapmsg "github.com/coredns/coredns/plugin/dnstap/msg"
	"github.com/coredns/coredns/plugin/dnstap/taprw"
	tap "github.com/dnstap/golang-dnstap"
	"github.com/golang/protobuf/proto"
	pb "github.com/infobloxopen/themis/contrib/coredns/policy/dnstap"
	"github.com/miekg/dns"
	context "golang.org/x/net/context"
)

type dnstapSender interface {
	sendCRExtraMsg(w dns.ResponseWriter, msg *dns.Msg, ah *attrHolder)
}

type policyDnstapSender struct {
	ior dnstap.IORoutine
}

func newPolicyDnstapSender(io dnstap.IORoutine) dnstapSender {
	return &policyDnstapSender{ior: io}
}

// sendCRExtraMsg creates Client Response (CR) dnstap Message and writes an array
// of extra attributes to Dnstap.Extra field. Then it asynchronously sends the
// message with IORoutine interface
func (s *policyDnstapSender) sendCRExtraMsg(w dns.ResponseWriter, msg *dns.Msg, ah *attrHolder) {
	if w == nil || msg == nil {
		log.Printf("[ERROR] Failed to create dnstap CR message - no DNS response message found")
		return
	}
	now := time.Now()
	b := tapmsg.Builder{Full: true}
	b.TimeSec = uint64(now.Unix())
	timeNs := uint32(now.Nanosecond())
	err := b.AddrMsg(w.RemoteAddr(), msg)
	if err != nil {
		log.Printf("[ERROR] Failed to create dnstap CR message (%v)", err)
		return
	}
	crMsg := b.ToClientResponse()
	crMsg.ResponseTimeNsec = &timeNs
	t := tap.Dnstap_MESSAGE

	var extra []byte
	if ah != nil {
		extra, err = proto.Marshal(&pb.Extra{Attrs: ah.convertAttrs()})
		if err != nil {
			log.Printf("[ERROR] Failed to create extra data for dnstap CR message (%v)", err)
		}
	}
	dnstapMsg := tap.Dnstap{Type: &t, Message: crMsg, Extra: extra}
	s.ior.Dnstap(dnstapMsg)
}

func resetCqCr(ctx context.Context) {
	if v := ctx.Value(dnstap.DnstapSendOption); v != nil {
		if so, ok := v.(*taprw.SendOption); ok {
			so.Cq = false
			so.Cr = false
		}
	}
}


text:
declare module '@storybook/addon-options' {
  declare type Theme = {
   /**
    * applied to root `background`
    * @default: 'linear-gradient(to bottom right, black, gray'
    */
   mainBackground?: string,
   /**
    * applied to panels `border`
    * @default: '1px solid rgba(0,0,0,0.1)'
    */
   mainBorder?: string,
   /**
    * applied for most borders
    * @default: 'rgba(0,0,0,0.1)'
    */
   mainBorderColor?: string,
   /**
    * applied to panels, buttons, inputs
    * @default: 4
    */
   mainBorderRadius?: string,
   /**
    * applied to panels `background`
    * @default: 'rgba(255,255,255,0.89)'
    */
   mainFill?: string,
   /**
    * applied to TabsBar `background`
    * @default: 'rgba(255,255,255,1)'
    */
   barFill?: string,
   /**
    * applied to Input `background`
    * @default: 'rgba(0,0,0,0.05)'
    */
   inputFill?: string,
   /**
    * applied to root `font-family`
    */
   mainTextFace?: string,
   /**
    * applied to root & buttons & input `color`
    * @default: black
    */
   mainTextColor?: string,
   /**
    * applied to root
    * @default: 13
    */
   mainTextSize?: string,
   /**
    * applied in less important text
    * @default: 'rgba(0,0,0,0.4)'
    */
   dimmedTextColor?: string,
   /**
    * applied to indicate selection
    * @default: '#9fdaff'
    */
   highlightColor?: string,
   /**
    * applied to indicate positive
    * @default: '#0edf62'
    */
   successColor?: string,
   /**
    * applied to indicate negative
    * @default: '#ff3f3f'
    */
   failColor?: string,
   /**
    * applied to indicate ow-ow
    * @default: 'orange'
    */
   warnColor?: string,
   /**
    * applied to pre,
    */
   monoTextFace?: string,
   /**
    * applied to space panels
    * @default: 10
    */
   layoutMargin?: string,
   /**
    * applied to overlay `background`
    * @default: 'linear-gradient(to bottom right, rgba(233, 233, 233, 0.6), rgba(255, 255, 255, 0.8))'
    */
   overlayBackground?: string,
   ...
  };

  declare type Options = {
   theme?: Theme,
   /**
    * name to display in the top left corner
    */
   name?: string,
   /**
    * URL for name in top left corner to link to
    */
   url?: string,
   /**
    * show story component as full screen
    */
   goFullScreen?: boolean,
   /**
    * display panel that shows a list of stories
    */
   showStoriesPanel?: boolean,
   /**
    * display panel that shows addon configurations
    */
   showAddonPanel?: boolean,
   /**
    * display floating search box to search through stories
    */
   showSearchBox?: boolean,
   /**
    * show addon panel as a vertical panel on the right
    */
   addonPanelInRight?: boolean,
   /**
    * sorts stories
    */
   sortStoriesByKind?: boolean,
   /**
    * regex for finding the hierarchy separator
    * @example:
    *   null - turn off hierarchy
    *   /\// - split by `/`
    *   /\./ - split by `.`
    *   /\/|\./ - split by `/` or `.`
    */
   hierarchySeparator?: RegExp | string,
   /**
    * regex for finding the hierarchy root separator
    * @example:
    *   null - turn off multiple hierarchy roots
    *   /\|/ - split by `|`
    */
   hierarchyRootSeparator?: RegExp | string,
   /**
    * sidebar tree animations
    */
   sidebarAnimations?: boolean,
   /**
    * id to select an addon panel
    * The order of addons in the "Addon panel" is the same as you import them in 'addons.js'.
    * The first panel will be opened by default as you run Storybook
    */
   selectedAddonPanel?: string,
   /**
    * enable/disable shortcuts
    * @default true
    */
   enableShortcuts?: boolean,
   ...
  };

  declare function setOptions(options: $Exact<Options>): void; // deprecated: use `withOptions`
  declare function withOptions(options: $Exact<Options>): void;
}


text:
package org.apache.bcel.generic;

/**
 * LASTORE - Store into long array
 *
 * <PRE>
 * Stack: ..., arrayref, index, value.word1, value.word2 -> ...
 * </PRE>
 */
public class LASTORE extends ArrayInstruction implements StackConsumer {

    /**
     * Store long into array
     */
    public LASTORE() {
        super(org.apache.bcel.Const.LASTORE);
    }

    /**
     * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call
     * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last.
     *
     * @param v Visitor object
     */
    @Override
    public void accept(final Visitor v) {
        v.visitStackConsumer(this);
        v.visitExceptionThrower(this);
        v.visitTypedInstruction(this);
        v.visitArrayInstruction(this);
        v.visitLASTORE(this);
    }
}


text:
using namespace arangodb;

std::string stats::fromGroupType(stats::GroupType gt) {
  switch (gt) {
    case stats::GroupType::System:
      return "system";
    case stats::GroupType::Client:
      return "client";
    case stats::GroupType::ClientUser:
      return "clientUser";
    case stats::GroupType::Http:
      return "http";
    case stats::GroupType::Vst:
      return "vst";
    case stats::GroupType::Server:
      return "server";
  }
  TRI_ASSERT(false);
  THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER);
}

void stats::Group::toVPack(velocypack::Builder& b) const {
  b.add("group", VPackValue(stats::fromGroupType(type)));
  b.add("name", VPackValue(name));
  b.add("description", VPackValue(description));
}

std::string stats::fromFigureType(stats::FigureType t) {
  switch (t) {
    case stats::FigureType::Current:
      return "current";
    case stats::FigureType::Accumulated:
      return "accumulated";
    case stats::FigureType::Distribution:
      return "distribution";
  }
  TRI_ASSERT(false);
  THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER);
}

std::string stats::fromUnit(stats::Unit u) {
  switch (u) {
    case stats::Unit::Seconds:
      return "seconds";
    case stats::Unit::Bytes:
      return "bytes";
    case stats::Unit::Percent:
      return "percent";
    case stats::Unit::Number:
      return "number";
  }
  TRI_ASSERT(false);
  THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER);
}

void stats::Figure::toVPack(velocypack::Builder& b) const {
  b.add("group", VPackValue(stats::fromGroupType(groupType)));
  b.add("identifier", VPackValue(identifier));
  b.add("name", VPackValue(name));
  b.add("description", VPackValue(description));
  b.add("type", VPackValue(stats::fromFigureType(type)));
  if (type == stats::FigureType::Distribution) {
    TRI_ASSERT(!cuts.empty());
    b.add("cuts", VPackValue(VPackValueType::Array, true));
    for (double cut : cuts) {
      b.add(VPackValue(cut));
    }
    b.close();
  }
  b.add("units", VPackValue(stats::fromUnit(units)));
}

stats::Descriptions::Descriptions(application_features::ApplicationServer& server)
    : _server(server),
      _requestTimeCuts(statistics::RequestTimeDistributionCuts),
      _connectionTimeCuts(statistics::ConnectionTimeDistributionCuts),
      _bytesSendCuts(statistics::BytesSentDistributionCuts),
      _bytesReceivedCuts(statistics::BytesReceivedDistributionCuts) {
  _groups.emplace_back(Group{stats::GroupType::System, "Process Statistics",
                             "Statistics about the ArangoDB process"});
  _groups.emplace_back(Group{stats::GroupType::Client,
                             "Client Connection Statistics",
                             "Statistics about the connections."});
  _groups.emplace_back(Group{stats::GroupType::ClientUser,
                             "Client User Connection Statistics",
                             "Statistics about the connections, only user traffic (ignoring superuser JWT traffic)."});
  _groups.emplace_back(Group{stats::GroupType::Http, "HTTP Request Statistics",
                             "Statistics about the HTTP requests."});
  _groups.emplace_back(Group{stats::GroupType::Server, "Server Statistics",
                             "Statistics about the ArangoDB server"});

  _figures.emplace_back(Figure{stats::GroupType::System,
                               "userTime",
                               "User Time",
                               "Amount of time that this process has been "
                               "scheduled in user mode, measured in seconds.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Seconds,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::System,
                               "systemTime",
                               "System Time",
                               "Amount of time that this process has been "
                               "scheduled in kernel mode, measured in seconds.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Seconds,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::System,
                               "numberOfThreads",
                               "Number of Threads",
                               "Number of threads in the arangod process.",
                               stats::FigureType::Current,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{
      stats::GroupType::System,
      "residentSize",
      "Resident Set Size",
      "The total size of the number of pages the process has in real memory. "
      "This is just the pages which count toward text, data, or stack space. "
      "This does not include pages which have not been demand-loaded in, or "
      "which are swapped out. The resident set size is reported in bytes.",
      stats::FigureType::Current,
      stats::Unit::Bytes,
      {}});

  _figures.emplace_back(Figure{stats::GroupType::System,
                               "residentSizePercent",
                               "Resident Set Size",
                               "The percentage of physical memory used by the "
                               "process as resident set size.",
                               stats::FigureType::Current,
                               stats::Unit::Percent,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::System,
                               "virtualSize",
                               "Virtual Memory Size",
                               "On Windows, this figure contains the total "
                               "amount of memory that the memory manager has "
                               "committed for the arangod process. On other "
                               "systems, this figure contains The size of the "
                               "virtual memory the process is using.",
                               stats::FigureType::Current,
                               stats::Unit::Bytes,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::System,
                               "minorPageFaults",
                               "Minor Page Faults",
                               "The number of minor faults the process has "
                               "made which have not required loading a memory "
                               "page from disk. This figure is not reported on "
                               "Windows.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{
      stats::GroupType::System,
      "majorPageFaults",
      "Major Page Faults",
      "On Windows, this figure contains the total number of page faults. On "
      "other system, this figure contains the number of major faults the "
      "process has made which have required loading a memory page from disk.",
      stats::FigureType::Accumulated,
      stats::Unit::Number,
      {}});

  // .............................................................................
  // client statistics
  // .............................................................................

  _figures.emplace_back(
      Figure{stats::GroupType::Client,
             "httpConnections",
             "Client Connections",
             "The number of connections that are currently open.",
             stats::FigureType::Current,
             stats::Unit::Number,
             {}});

  _figures.emplace_back(
      Figure{stats::GroupType::Client, "totalTime", "Total Time",
             "Total time needed to answer a request.", stats::FigureType::Distribution,
             // cuts: internal.requestTimeDistribution,
             stats::Unit::Seconds, _requestTimeCuts});

  _figures.emplace_back(
      Figure{stats::GroupType::Client, "requestTime", "Request Time",
             "Request time needed to answer a request.", stats::FigureType::Distribution,
             // cuts: internal.requestTimeDistribution,
             stats::Unit::Seconds, _requestTimeCuts});

  _figures.emplace_back(
      Figure{stats::GroupType::Client, "queueTime", "Queue Time",
             "Queue time needed to answer a request.", stats::FigureType::Distribution,
             // cuts: internal.requestTimeDistribution,
             stats::Unit::Seconds, _requestTimeCuts});

  _figures.emplace_back(Figure{stats::GroupType::Client, "bytesSent",
                               "Bytes Sent", "Bytes sents for a request.",
                               stats::FigureType::Distribution,
                               // cuts: internal.bytesSentDistribution,
                               stats::Unit::Bytes, _bytesSendCuts});

  _figures.emplace_back(Figure{stats::GroupType::Client, "bytesReceived",
                               "Bytes Received", "Bytes received for a request.",
                               stats::FigureType::Distribution,
                               // cuts: internal.bytesReceivedDistribution,
                               stats::Unit::Bytes, _bytesReceivedCuts});

  _figures.emplace_back(
      Figure{stats::GroupType::Client, "connectionTime", "Connection Time",
             "Total connection time of a client.", stats::FigureType::Distribution,
             // cuts: internal.connectionTimeDistribution,
             stats::Unit::Seconds, _connectionTimeCuts});

  // Only user traffic:

  _figures.emplace_back(
      Figure{stats::GroupType::ClientUser,
             "httpConnections",
             "Client Connections",
             "The number of connections that are currently open (only user traffic).",
             stats::FigureType::Current,
             stats::Unit::Number,
             {}});

  _figures.emplace_back(
      Figure{stats::GroupType::ClientUser, "totalTime", "Total Time",
             "Total time needed to answer a request (only user traffic).",
             stats::FigureType::Distribution,
             // cuts: internal.requestTimeDistribution,
             stats::Unit::Seconds, _requestTimeCuts});

  _figures.emplace_back(
      Figure{stats::GroupType::ClientUser, "requestTime", "Request Time",
             "Request time needed to answer a request (only user traffic).",
             stats::FigureType::Distribution,
             // cuts: internal.requestTimeDistribution,
             stats::Unit::Seconds, _requestTimeCuts});

  _figures.emplace_back(
      Figure{stats::GroupType::ClientUser, "queueTime", "Queue Time",
             "Queue time needed to answer a request (only user traffic).",
             stats::FigureType::Distribution,
             // cuts: internal.requestTimeDistribution,
             stats::Unit::Seconds, _requestTimeCuts});

  _figures.emplace_back(Figure{stats::GroupType::ClientUser, "bytesSent",
                               "Bytes Sent",
                               "Bytes sents for a request (only user traffic).",
                               stats::FigureType::Distribution,
                               // cuts: internal.bytesSentDistribution,
                               stats::Unit::Bytes, _bytesSendCuts});

  _figures.emplace_back(Figure{stats::GroupType::ClientUser, "bytesReceived",
                               "Bytes Received",
                               "Bytes received for a request (only user traffic).",
                               stats::FigureType::Distribution,
                               // cuts: internal.bytesReceivedDistribution,
                               stats::Unit::Bytes, _bytesReceivedCuts});

  _figures.emplace_back(
      Figure{stats::GroupType::ClientUser, "connectionTime",
             "Connection Time",
             "Total connection time of a client (only user traffic).",
             stats::FigureType::Distribution,
             // cuts: internal.connectionTimeDistribution,
             stats::Unit::Seconds, _connectionTimeCuts});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsTotal",
                               "Total requests",
                               "Total number of HTTP requests.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsSuperuser",
                               "Total superuser requests",
                               "Total number of HTTP requests executed by superuser/JWT.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsUser",
                               "Total user requests",
                               "Total number of HTTP requests executed by clients.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(
      Figure{stats::GroupType::Http,
             "requestsAsync",
             "Async requests",
             "Number of asynchronously executed HTTP requests.",
             stats::FigureType::Accumulated,
             stats::Unit::Number,
             {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsGet",
                               "HTTP GET requests",
                               "Number of HTTP GET requests.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsHead",
                               "HTTP HEAD requests",
                               "Number of HTTP HEAD requests.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsPost",
                               "HTTP POST requests",
                               "Number of HTTP POST requests.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsPut",
                               "HTTP PUT requests",
                               "Number of HTTP PUT requests.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsPatch",
                               "HTTP PATCH requests",
                               "Number of HTTP PATCH requests.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsDelete",
                               "HTTP DELETE requests",
                               "Number of HTTP DELETE requests.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsOptions",
                               "HTTP OPTIONS requests",
                               "Number of HTTP OPTIONS requests.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Http,
                               "requestsOther",
                               "other HTTP requests",
                               "Number of other HTTP requests.",
                               stats::FigureType::Accumulated,
                               stats::Unit::Number,
                               {}});

  // .............................................................................
  // server statistics
  // .............................................................................

  _figures.emplace_back(Figure{stats::GroupType::Server,
                               "uptime",
                               "Server Uptime",
                               "Number of seconds elapsed since server start.",
                               stats::FigureType::Current,
                               stats::Unit::Seconds,
                               {}});

  _figures.emplace_back(Figure{stats::GroupType::Server,
                               "physicalMemory",
                               "Physical Memory",
                               "Physical memory in bytes.",
                               stats::FigureType::Current,
                               stats::Unit::Bytes,
                               {}});
}

void stats::Descriptions::serverStatistics(velocypack::Builder& b) const {
  auto& dealer = _server.getFeature<V8DealerFeature>();

  ServerStatistics const& info = _server.getFeature<MetricsFeature>().serverStatistics();
  b.add("uptime", VPackValue(info.uptime()));
  b.add("physicalMemory", VPackValue(PhysicalMemory::getValue()));

  b.add("transactions", VPackValue(VPackValueType::Object));
  b.add("started", VPackValue(info._transactionsStatistics._transactionsStarted.load()));
  b.add("aborted", VPackValue(info._transactionsStatistics._transactionsAborted.load()));
  b.add("committed", VPackValue(info._transactionsStatistics._transactionsCommitted.load()));
  b.add("intermediateCommits", VPackValue(info._transactionsStatistics._intermediateCommits.load()));
  b.close();

  if (dealer.isEnabled()) {
    b.add("v8Context", VPackValue(VPackValueType::Object, true));
    auto v8Counters = dealer.getCurrentContextNumbers();
    auto memoryStatistics = dealer.getCurrentContextDetails();
    b.add("available", VPackValue(v8Counters.available));
    b.add("busy", VPackValue(v8Counters.busy));
    b.add("dirty", VPackValue(v8Counters.dirty));
    b.add("free", VPackValue(v8Counters.free));
    b.add("max", VPackValue(v8Counters.max));
    b.add("min", VPackValue(v8Counters.min));
    {
      b.add("memory", VPackValue(VPackValueType::Array));
      for (auto const& memStatistic : memoryStatistics) {
        b.add(VPackValue(VPackValueType::Object));
        b.add("contextId", VPackValue(memStatistic.id));
        b.add("tMax", VPackValue(memStatistic.tMax));
        b.add("countOfTimes", VPackValue(memStatistic.countOfTimes));
        b.add("heapMax", VPackValue(memStatistic.heapMax));
        b.add("heapMin", VPackValue(memStatistic.heapMin));
        b.add("invocations", VPackValue(memStatistic.invocations));
        b.close();
      }
      b.close();
    }
    b.close();
  }

  b.add("threads", VPackValue(VPackValueType::Object, true));
  SchedulerFeature::SCHEDULER->toVelocyPack(b);
  b.close();
}

////////////////////////////////////////////////////////////////////////////////
/// @brief fills the distribution
////////////////////////////////////////////////////////////////////////////////

static void FillDistribution(VPackBuilder& b, std::string const& name,
                             statistics::Distribution const& dist) {
  b.add(name, VPackValue(VPackValueType::Object, true));
  b.add("sum", VPackValue(dist._total));
  b.add("count", VPackValue(dist._count));
  b.add("counts", VPackValue(VPackValueType::Array, true));
  for (auto const& it : dist._counts) {
    b.add(VPackValue(it));
  }
  b.close();
  b.close();
}

void stats::Descriptions::clientStatistics(velocypack::Builder& b, RequestStatisticsSource source) const {
  // FIXME why are httpConnections in here ?
  ConnectionStatistics::Snapshot connectionStats;
  ConnectionStatistics::getSnapshot(connectionStats);

  b.add("httpConnections", VPackValue(connectionStats.httpConnections.get()));
  FillDistribution(b, "connectionTime", connectionStats.connectionTime);

  RequestStatistics::Snapshot requestStats;
  RequestStatistics::getSnapshot(requestStats, source);

  FillDistribution(b, "totalTime", requestStats.totalTime);
  FillDistribution(b, "requestTime", requestStats.requestTime);
  FillDistribution(b, "queueTime", requestStats.queueTime);
  FillDistribution(b, "ioTime", requestStats.ioTime);
  FillDistribution(b, "bytesSent", requestStats.bytesSent);
  FillDistribution(b, "bytesReceived", requestStats.bytesReceived);
}

void stats::Descriptions::httpStatistics(velocypack::Builder& b) const {
  ConnectionStatistics::Snapshot stats;
  ConnectionStatistics::getSnapshot(stats);

  // request counters
  b.add("requestsTotal", VPackValue(stats.totalRequests.get()));
  b.add("requestsSuperuser", VPackValue(stats.totalRequestsSuperuser.get()));
  b.add("requestsUser", VPackValue(stats.totalRequestsUser.get()));
  b.add("requestsAsync", VPackValue(stats.asyncRequests.get()));
  b.add("requestsGet", VPackValue(stats.methodRequests[(int)rest::RequestType::GET].get()));
  b.add("requestsHead", VPackValue(stats.methodRequests[(int)rest::RequestType::HEAD].get()));
  b.add("requestsPost", VPackValue(stats.methodRequests[(int)rest::RequestType::POST].get()));
  b.add("requestsPut", VPackValue(stats.methodRequests[(int)rest::RequestType::PUT].get()));
  b.add("requestsPatch",
        VPackValue(stats.methodRequests[(int)rest::RequestType::PATCH].get()));
  b.add("requestsDelete",
        VPackValue(stats.methodRequests[(int)rest::RequestType::DELETE_REQ].get()));
  b.add("requestsOptions",
        VPackValue(stats.methodRequests[(int)rest::RequestType::OPTIONS].get()));
  b.add("requestsOther",
        VPackValue(stats.methodRequests[(int)rest::RequestType::ILLEGAL].get()));
}

void stats::Descriptions::processStatistics(VPackBuilder& b) const {
  ProcessInfo info = TRI_ProcessInfoSelf();
  double rss = (double)info._residentSize;
  double rssp = 0;

  if (PhysicalMemory::getValue() != 0) {
    rssp = rss / PhysicalMemory::getValue();
  }

  b.add("minorPageFaults", VPackValue(info._minorPageFaults));
  b.add("majorPageFaults", VPackValue(info._majorPageFaults));
  b.add("userTime", VPackValue((double)info._userTime / (double)info._scClkTck));
  b.add("systemTime", VPackValue((double)info._systemTime / (double)info._scClkTck));
  b.add("numberOfThreads", VPackValue(info._numberThreads));
  b.add("residentSize", VPackValue(rss));
  b.add("residentSizePercent", VPackValue(rssp));
  b.add("virtualSize", VPackValue(info._virtualSize));
}


text:
drop table public.topics_topics;
drop table public.topics_links;