text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="robots" content="index, follow, all" />
    <title>Hayttp\Request | Hayttp API</title>

            <link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="../css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="../css/sami.css">

        <meta name="MobileOptimized" content="width">
        <meta name="HandheldFriendly" content="true">
        <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">

                    <form action="#" method="GET">
                <select id="version-switcher" name="version">
                                            <option value="../../1.0.0/index.html" data-version="1.0.0">1.0.0</option>
                                            <option value="../../1.0.1/index.html" data-version="1.0.1">1.0.1</option>
                                            <option value="../../master/index.html" data-version="master">master dev branch</option>
                                    </select>
            </form>

        <form id="search-form" action="../search.html" method="GET">

            <input name="search"
                   class="typeahead form-control"
                   type="search"
                   placeholder="Search">
        </form>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
                    Toggle navigation

                </button>
                Hayttp API

Classes

Namespaces

Interfaces

Traits

Index

Search

class

Hayttp

\

Request

            Request

    class
    Request        implements
        Request        (View source)

HTTP Request class.

Traits

                                            Extendable

                    Make a class dynamically extendable.

                                            SendsRequest

                                            HasWithMethods

                                            HasRequestAccessors

                                            CreatesRequests

                                            HasCompleteDebugInfo

                    Add __debugInfo support.

                                            ExpectsCommonMimeTypes

                                            HandlesMultipartPayloads

                                            DeprecatedRequestMethods

Properties

                    static                    protected                                        array

                $extensions

                from Extendable

                                        protected                                        string

                $method

                                        protected                                        Engine

                $engine

                                        protected                                        string

                $userAgent

                                        protected                                        string

                $url

                                        protected                                        array

                $headers

                                        protected                                        Payload

                $payload

                                        protected                                        string|null

                $proxy

                                        protected                                        bool

                $secureSsl

                                        protected                                        float

                $timeout

                                        protected                                        array

                $cryptoMethod

                                        protected                                        array

                $responseCalls

                                        protected                                        array

                $mockedEndpoints

Methods

                    static

                    hasExtension($methodName)

No description

from Extendable

                    static $this

                    extend(string $methodName, callable $callable)

Add a method to the class.

from Extendable

                    static $this

                    mixin(object $object)

Mix in all the public methods of an object.

from Extendable

                    mixed

                    execDynamicCallable(callable $callable, array $args)

Execute a static call with the correct class scope.

from Extendable

                    static mixed

                    execStaticCallable(callable $callable, array $args)

Execute a static call with the correct class scope.

from Extendable

                    mixed

                    __call(string $methodName, array $args)

Magic Method for dynamic method names.

                    static mixed

                    __callStatic(string $methodName, array $args)

Magic Method for dynamic names of static methods.

from Extendable

                    Response

                    send()

Send/execute the request.

from SendsRequest

                    Response

                    sendRaw(string $payload, string $contentType = 'application/octet-stream')

Set the raw payload of the request and send/execute the request.

from SendsRequest

                    Response

                    sendJson($json)

Set a JSON payload and send/execute the request.

from SendsRequest

                    Response

                    sendXml(SimpleXmlElement|string $xml)

Set an XML payload and send/execute the request.

from SendsRequest

                    Response

                    sendFormData(array $data)

Set a URL-encoded payload and send/execute the request.

from SendsRequest

                    Request

                    with(string $property, mixed $value)

Clone object with a new property value.

                    Request

                    withTimeout(float $seconds)

Set the timeout.

from HasWithMethods

                    Request

                    withUserAgent(string $userAgent)

Set the user agent header.

from HasWithMethods

                    Request

                    withCryptoMethod(string $cryptoMethod)

Set the allowed crypto method.

from HasWithMethods

                    Request

                    withInsecureSsl()

Disable all SSL certificate checks.

from HasWithMethods

                    Request

                    withEngine(Engine $engine)

Set the transfer engine.

from HasWithMethods

                    Request

                    withHeaders(array $headers)

Set all headers.

from HasWithMethods

                    Request

                    withAdditionalHeaders(array $additionalHeaders)

Add an array of headers.

from HasWithMethods

                    Request

                    withProxy(string $proxy)

Set the proxy server.

from HasWithMethods

                    Request

                    withHeader(string $name, string $value)

Add a header to the request.

from HasWithMethods

                    Request

                    withTls(string $version)

Set the TLS version.

from HasWithMethods

                    Request

                    withBasicAuth(string $username, string $password)

Add a basic authorization (which is actually an authenticaation) header.

from HasWithMethods

                    Request

                    withPayload(Payload $payload)

Set the payload of the request.

from HasWithMethods

                    Request

                    withResponseCall(string $methodName, array $args = [])

Execute the $response->$methodName(.

from HasWithMethods

                    Request

                    withRawPayload(string $payload, string $contentType = 'application/octet-stream')

Set the raw payload of the request.

from HasWithMethods

                    Request

                    withJsonPayload(array|object $payload, string $contentType = 'application/json')

Set a JSON payload.

from HasWithMethods

                    Request

                    withXmlPayload(SimpleXmlElement|string $xml)

Set an XML payload.

from HasWithMethods

                    Request

                    withFormDataPayload(array $form)

Set a URL-encoded payload.

from HasWithMethods

                    string

                    method()

The http method.

from HasRequestAccessors

                    Engine

                    engine()

The request engine.

from HasRequestAccessors

                    array

                    events()

All registered event hooks.

from HasRequestAccessors

                    string

                    userAgent()

The user agent string.

from HasRequestAccessors

                    string

                    url()

The target url.

from HasRequestAccessors

                    array

                    headers()

No description

from HasRequestAccessors

                    string|null

                    header(string $headerName)

Get the contents of a given header.

from HasRequestAccessors

                    Payload

                    payload()

The request payload.

from HasRequestAccessors

                    string|null

                    proxy()

The proxy to use.

from HasRequestAccessors

                    bool

                    secureSsl()

Are we doing strict SSL checking?

from HasRequestAccessors

                    float

                    timeout()

Timeout in seconds.

from HasRequestAccessors

                    array

                    cryptoMethod()

Cryptographic transport method.

from HasRequestAccessors

                    string

                    body()

The request body.

from HasRequestAccessors

                    string|null

                    contentType()

Get the contents of the Content-Type header.

from HasRequestAccessors

                    static Request

                    delete(string $url)

Factory.

from CreatesRequests

                    static Request

                    get(string $url)

Factory.

from CreatesRequests

                    static Request

                    head(string $url)

Factory.

from CreatesRequests

                    static Request

                    options(string $url)

Factory.

from CreatesRequests

                    static Request

                    patch(string $url)

Factory.

from CreatesRequests

                    static Request

                    post(string $url)

Factory.

from CreatesRequests

                    static Request

                    put(string $url)

Factory.

from CreatesRequests

                    array

                    instanceVariables()

Public accessor for all instance variables.

from HasCompleteDebugInfo

                    array

                    __debugInfo()

Return debug info for var_dump, et al.

from HasCompleteDebugInfo

                    Request

                    expectsJson()

Accept application/json.

from ExpectsCommonMimeTypes

                    expectsXml()

Accept application/xml.

from ExpectsCommonMimeTypes

                    Request

                    expectsAny()

Accept * / *.

from ExpectsCommonMimeTypes

                    Request

                    ensureJson()

Expect json response type and throw an exception if json is not returned.

from ExpectsCommonMimeTypes

                    Request

                    ensureXml()

Expect json response type and throw an exception if json is not returned.

from ExpectsCommonMimeTypes

                    Request

                    addMultipartField(string $name, string $data, string $filename = null, string $contentType = null)

Add a multipart entry.

from HandlesMultipartPayloads

                    Request

                    addFile(string $name, string $file, string $filename = null, string $contentType = null)

Add a file to the multipart payload.

from HandlesMultipartPayloads

                    Request

                    addBlob(string $name, string $data, string|null $contentType = null)

Add a data field to the multipart payload.

from HandlesMultipartPayloads

                    Request

                    sendsRaw(string $payload, string $contentType = 'application/octet-stream')
        deprecated

Set the raw payload of the request.

from DeprecatedRequestMethods

                    Request

                    sendsJson(array|object $payload)
        deprecated

Set a JSON payload.

from DeprecatedRequestMethods

                    Request

                    sendsXml(SimpleXmlElement|string $xml)
        deprecated

Set a XML payload.

from DeprecatedRequestMethods

                    Request

                    sends(array $data)
        deprecated

Set a URL-encoded payload.

from DeprecatedRequestMethods

                    string[]

                    preparedHeaders()

Format headers.

                    __construct(string $method, string $url)

Constructor.

                    string

                    __toString()

Return the request as a string.

                    __set(string $name, mixed $value)

Setter.

                    string

                    render()

Return the request as a string.

                    Request

                    expects(string $mimeType)

Add Accept header.

                    Request

                    expectsMany(array $types)

Add Accept header with many types.

                    array

                    responseCalls()

Get the calls that are to be executed on the response
as soon as we have one.

                    Request

                    withMockedEndpoint(string $methodPattern, string $urlPattern, callable $handler)

Mock an end point.

Details

in Extendable at         line 26

                static
    hasExtension($methodName)

Parameters

                $methodName

in Extendable at         line 40

                static            $this
    extend(string $methodName, callable $callable)

Add a method to the class.

Parameters

                string
                $methodName

                callable
                $callable

Return Value

            $this

in Extendable at         line 52

                static            $this
    mixin(object $object)

Mix in all the public methods of an object.

Parameters

                object
                $object

Return Value

            $this

in Extendable at         line 73

                            mixed
    execDynamicCallable(callable $callable, array $args)

Execute a static call with the correct class scope.

Parameters

                callable
                $callable

                array
                $args

Return Value

            mixed

in Extendable at         line 90

                static            mixed
    execStaticCallable(callable $callable, array $args)

Execute a static call with the correct class scope.

Parameters

                callable
                $callable

                array
                $args

Return Value

            mixed

at         line 289

                            mixed
    __call(string $methodName, array $args)

Magic Method for dynamic method names.

Parameters

                string
                $methodName

                array
                $args

Return Value

            mixed

in Extendable at         line 128

                static            mixed
    __callStatic(string $methodName, array $args)

Magic Method for dynamic names of static methods.

Parameters

                string
                $methodName

                array
                $args

Return Value

            mixed

in SendsRequest at         line 25

                            Response
    send()

Send/execute the request.

Return Value

            Response

Exceptions

                ConnectionException
                if connection could not be established

in SendsRequest at         line 46

                            Response
    sendRaw(string $payload, string $contentType = 'application/octet-stream')

Set the raw payload of the request and send/execute the request.

Parameters

                string
                $payload

                string
                $contentType

Return Value

            Response

in SendsRequest at         line 58

                            Response
    sendJson($json)

Set a JSON payload and send/execute the request.

Parameters

                $json

Return Value

            Response

in SendsRequest at         line 70

                            Response
    sendXml(SimpleXmlElement|string $xml)

Set an XML payload and send/execute the request.

Parameters

                SimpleXmlElement|string
                $xml

Return Value

            Response

in SendsRequest at         line 82

                            Response
    sendFormData(array $data)

Set a URL-encoded payload and send/execute the request.

Parameters

                array
                $data
                key/value pairs to post as normal urlencoded fields

Return Value

            Response

at         line 104

                    protected        Request
    with(string $property, mixed $value)

Clone object with a new property value.

Parameters

                string
                $property

                mixed
                $value

Return Value

            Request

in HasWithMethods at         line 42

                            Request
    withTimeout(float $seconds)

Set the timeout.

Parameters

                float
                $seconds

Return Value

            Request

in HasWithMethods at         line 54

                            Request
    withUserAgent(string $userAgent)

Set the user agent header.

Parameters

                string
                $userAgent

Return Value

            Request

in HasWithMethods at         line 68

                            Request
    withCryptoMethod(string $cryptoMethod)

Set the allowed crypto method.

A Crypto method can be one of the CRYPTO_* constants

Parameters

                string
                $cryptoMethod

Return Value

            Request

in HasWithMethods at         line 86

                            Request
    withInsecureSsl()

Disable all SSL certificate checks.

Return Value

            Request

in HasWithMethods at         line 98

                            Request
    withEngine(Engine $engine)

Set the transfer engine.

Parameters

                Engine
                $engine

Return Value

            Request

in HasWithMethods at         line 110

                            Request
    withHeaders(array $headers)

Set all headers.

Parameters

                array
                $headers

Return Value

            Request

in HasWithMethods at         line 122

                            Request
    withAdditionalHeaders(array $additionalHeaders)

Add an array of headers.

Parameters

                array
                $additionalHeaders

Return Value

            Request

in HasWithMethods at         line 145

                            Request
    withProxy(string $proxy)

Set the proxy server.

Parameters

                string
                $proxy
                URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

Return Value

            Request

in HasWithMethods at         line 158

                            Request
    withHeader(string $name, string $value)

Add a header to the request.

Parameters

                string
                $name

                string
                $value

Return Value

            Request

in HasWithMethods at         line 170

                            Request
    withTls(string $version)

Set the TLS version.

Parameters

                string
                $version
                currently, 1.*, 1.0, 1.1 and 1.2 are supported

Return Value

            Request

in HasWithMethods at         line 197

                            Request
    withBasicAuth(string $username, string $password)

Add a basic authorization (which is actually an authenticaation) header.

Parameters

                string
                $username

                string
                $password

Return Value

            Request

in HasWithMethods at         line 212

                            Request
    withPayload(Payload $payload)

Set the payload of the request.

Parameters

                Payload
                $payload

Return Value

            Request

in HasWithMethods at         line 225

                            Request
    withResponseCall(string $methodName, array $args = [])

Execute the $response->$methodName(.

..$args) as soon as we have a response.

Parameters

                string
                $methodName

                array
                $args

Return Value

            Request

in HasWithMethods at         line 249

                            Request
    withRawPayload(string $payload, string $contentType = 'application/octet-stream')

Set the raw payload of the request.

Parameters

                string
                $payload

                string
                $contentType

Return Value

            Request

in HasWithMethods at         line 267

                            Request
    withJsonPayload(array|object $payload, string $contentType = 'application/json')

Set a JSON payload.

NOTE that the neither unicode characters nor slashes are escaped.
This behaviors is compatible with the json standard as well as
most browsers' * JSON.stringify() and JSON.parse().
However, it is not default output of json_encode.

Parameters

                array|object
                $payload
                the payload to send - the payload will always be json encoded

                string
                $contentType

Return Value

            Request

in HasWithMethods at         line 279

                            Request
    withXmlPayload(SimpleXmlElement|string $xml)

Set an XML payload.

Parameters

                SimpleXmlElement|string
                $xml

Return Value

            Request

in HasWithMethods at         line 295

                            Request
    withFormDataPayload(array $form)

Set a URL-encoded payload.

Parameters

                array
                $form
                key/value pairs to post as normal urlencoded fields

Return Value

            Request

in HasRequestAccessors at         line 23

                            string
    method()

The http method.

Return Value

            string

in HasRequestAccessors at         line 33

                            Engine
    engine()

The request engine.

Return Value

            Engine

in HasRequestAccessors at         line 43

                            array
    events()

All registered event hooks.

Return Value

            array

in HasRequestAccessors at         line 53

                            string
    userAgent()

The user agent string.

Return Value

            string

in HasRequestAccessors at         line 63

                            string
    url()

The target url.

Return Value

            string

in HasRequestAccessors at         line 71

                            array
    headers()

Return Value

            array

in HasRequestAccessors at         line 83

                            string|null
    header(string $headerName)

Get the contents of a given header.

Parameters

                string
                $headerName
                The name of the header to search for

Return Value

            string|null
            the contents of the header or null if it was not found

in HasRequestAccessors at         line 96

                            Payload
    payload()

The request payload.

Return Value

            Payload

in HasRequestAccessors at         line 106

                            string|null
    proxy()

The proxy to use.

Return Value

            string|null

in HasRequestAccessors at         line 116

                            bool
    secureSsl()

Are we doing strict SSL checking?

Return Value

            bool

in HasRequestAccessors at         line 126

                            float
    timeout()

Timeout in seconds.

Return Value

            float

in HasRequestAccessors at         line 136

                            array
    cryptoMethod()

Cryptographic transport method.

Return Value

            array

in HasRequestAccessors at         line 146

                            string
    body()

The request body.

Return Value

            string

in HasRequestAccessors at         line 156

                            string|null
    contentType()

Get the contents of the Content-Type header.

Return Value

            string|null

in CreatesRequests at         line 26

                static            Request
    delete(string $url)

Factory.

Initialize a DELETE request

Parameters

                string
                $url

Return Value

            Request

in CreatesRequests at         line 40

                static            Request
    get(string $url)

Factory.

Initialize a GET request

Parameters

                string
                $url

Return Value

            Request

in CreatesRequests at         line 54

                static            Request
    head(string $url)

Factory.

Initialize a HEAD request

Parameters

                string
                $url

Return Value

            Request

in CreatesRequests at         line 68

                static            Request
    options(string $url)

Factory.

Initialize a OPTIONS request

Parameters

                string
                $url

Return Value

            Request

in CreatesRequests at         line 82

                static            Request
    patch(string $url)

Factory.

Initialize a PATCH request

Parameters

                string
                $url

Return Value

            Request

in CreatesRequests at         line 96

                static            Request
    post(string $url)

Factory.

Initialize a POST request

Parameters

                string
                $url

Return Value

            Request

in CreatesRequests at         line 110

                static            Request
    put(string $url)

Factory.

Initialize a PUT request

Parameters

                string
                $url

Return Value

            Request

in HasCompleteDebugInfo at         line 25

                            array
    instanceVariables()

Public accessor for all instance variables.

Return Value

            array

in HasCompleteDebugInfo at         line 35

                            array
    __debugInfo()

Return debug info for var_dump, et al.

Return Value

            array

in ExpectsCommonMimeTypes at         line 22

                            Request
    expectsJson()

Accept application/json.

Return Value

            Request

in ExpectsCommonMimeTypes at         line 30

    expectsXml()

Accept application/xml.

in ExpectsCommonMimeTypes at         line 40

                            Request
    expectsAny()

Accept * / *.

Return Value

            Request

in ExpectsCommonMimeTypes at         line 50

                            Request
    ensureJson()

Expect json response type and throw an exception if json is not returned.

Return Value

            Request

in ExpectsCommonMimeTypes at         line 61

                            Request
    ensureXml()

Expect json response type and throw an exception if json is not returned.

Return Value

            Request

in HandlesMultipartPayloads at         line 28

                            Request
    addMultipartField(string $name, string $data, string $filename = null, string $contentType = null)

Add a multipart entry.

Parameters

                string
                $name
                posted Field name

                string
                $data
                the data blob to add

                string
                $filename
                The filename to use. If null, no filename is sent.

                string
                $contentType
                The content type to send. If null, no content-type will be sent.

Return Value

            Request

in HandlesMultipartPayloads at         line 49

                            Request
    addFile(string $name, string $file, string $filename = null, string $contentType = null)

Add a file to the multipart payload.

Parameters

                string
                $name
                The posted field name

                string
                $file
                The filename on the physical HD

                string
                $filename
                The filename to post. If null, the basename of $filename will be used.

                string
                $contentType
                The content type of the file. If null, the content type will be inferred via mime_content_type()

Return Value

            Request

in HandlesMultipartPayloads at         line 75

                            Request
    addBlob(string $name, string $data, string|null $contentType = null)

Add a data field to the multipart payload.

Parameters

                string
                $name
                The posted field name

                string
                $data
                the data blob to add

                string|null
                $contentType
                The content type to send. If null, no content-type will be sent.

Return Value

            Request

in DeprecatedRequestMethods at         line 27

                            Request
    sendsRaw(string $payload, string $contentType = 'application/octet-stream')
        deprecated

                deprecated

Set the raw payload of the request.

Parameters

                string
                $payload

                string
                $contentType

Return Value

            Request

in DeprecatedRequestMethods at         line 41

                            Request
    sendsJson(array|object $payload)
        deprecated

                deprecated

Set a JSON payload.

Parameters

                array|object
                $payload
                the payload to send - the payload will always be json encoded

Return Value

            Request

in DeprecatedRequestMethods at         line 55

                            Request
    sendsXml(SimpleXmlElement|string $xml)
        deprecated

                deprecated

Set a XML payload.

Parameters

                SimpleXmlElement|string
                $xml

Return Value

            Request

in DeprecatedRequestMethods at         line 69

                            Request
    sends(array $data)
        deprecated

                deprecated

Set a URL-encoded payload.

Parameters

                array
                $data
                key/value pairs to post as normal urlencoded fields

Return Value

            Request

at         line 122

                            string[]
    preparedHeaders()

Format headers.

Only one hosts header, which must be the first header
Only one User Agent header.
All other headers are copied verbatim.

Return Value

            string[]

at         line 158

    __construct(string $method, string $url)

Constructor.

Parameters

                string
                $method

                string
                $url

at         line 169

                            string
    __toString()

Return the request as a string.

Return Value

            string

at         line 182

    __set(string $name, mixed $value)

Setter.

Parameters

                string
                $name

                mixed
                $value

Exceptions

                LogicException
                whenever setting a non-existing property is attempted

at         line 195

                            string
    render()

Return the request as a string.

Return Value

            string

at         line 224

                            Request
    expects(string $mimeType)

Add Accept header.

Parameters

                string
                $mimeType

Return Value

            Request

at         line 236

                            Request
    expectsMany(array $types)

Add Accept header with many types.

Parameters

                array
                $types
                associative array of [mimeType => qualityFactor]

Return Value

            Request

at         line 254

                            array
    responseCalls()

Get the calls that are to be executed on the response
as soon as we have one.

Return Value

            array

at         line 268

                            Request
    withMockedEndpoint(string $methodPattern, string $urlPattern, callable $handler)

Mock an end point.

Parameters

                string
                $methodPattern

                string
                $urlPattern

                callable
                $handler

Return Value

            Request

        Generated by Sami, the API Documentation Generator.


text:
import { storiesOf } from '@storybook/angular';
import { Welcome } from '@storybook/angular/demo';

storiesOf('General|Permissions', module).add('Overview', () => ({
  component: Welcome,
  props: {},
}));

redpajama_set_name: RedPajamaGithub


text:
package com.workday.autoparse.json.demo;

import com.workday.autoparse.json.utils.CollectionUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static com.workday.autoparse.json.demo.InstanceUpdaterTestUtils.CONTEXT;
import static com.workday.autoparse.json.demo.InstanceUpdaterTestUtils.getUpdateMapFromFile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * @author nathan.taylor
 * @since 2015-08-17.
 */
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class InstanceUpdaterTest {

    private static final float ERROR = 1e-6f;

    @Test
    public void testPrimitives() {
        TestObject testObject = new TestObject();
        testObject.myBoolean = false;
        testObject.myByte = 1;
        testObject.myChar = 'a';
        testObject.myDouble = 1.1;
        testObject.myFloat = 1.1f;
        testObject.myInt = 1;
        testObject.myLong = 1L;
        testObject.myShort = 1;

        Map<String, Object> updates = new HashMap<>();
        updates.put("myBoolean", true);
        updates.put("myByte", (byte) 2);
        updates.put("myChar", 'b');
        updates.put("myDouble", 2.2);
        updates.put("myFloat", 2.2f);
        updates.put("myInt", 2);
        updates.put("myLong", 2L);
        updates.put("myShort", (short) 2);

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("myBoolean", true, testObject.myBoolean);
        assertEquals("myByte", 2, testObject.myByte);
        assertEquals("myChar", 'b', testObject.myChar);
        assertEquals("myDouble", 2.2, testObject.myDouble, ERROR);
        assertEquals("myFloat", 2.2f, testObject.myFloat, ERROR);
        assertEquals("myInt", 2, testObject.myInt);
        assertEquals("myLong", 2L, testObject.myLong);
        assertEquals("myShort", (short) 2, testObject.myShort);
    }

    @Test
    public void testPrimitivesFromStrings() {
        TestObject testObject = new TestObject();
        testObject.myBoolean = false;
        testObject.myByte = 1;
        testObject.myChar = 'a';
        testObject.myDouble = 1.1;
        testObject.myFloat = 1.1f;
        testObject.myInt = 1;
        testObject.myLong = 1L;
        testObject.myShort = 1;

        Map<String, Object> updates = new HashMap<>();
        updates.put("myBoolean", true);
        updates.put("myByte", "2");
        updates.put("myChar", "b");
        updates.put("myDouble", "2.2");
        updates.put("myFloat", "2.2");
        updates.put("myInt", "2");
        updates.put("myLong", "2");
        updates.put("myShort", "2");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("myBoolean", true, testObject.myBoolean);
        assertEquals("myByte", 2, testObject.myByte);
        assertEquals("myChar", 'b', testObject.myChar);
        assertEquals("myDouble", 2.2, testObject.myDouble, ERROR);
        assertEquals("myFloat", 2.2f, testObject.myFloat, ERROR);
        assertEquals("myInt", 2, testObject.myInt);
        assertEquals("myLong", 2L, testObject.myLong);
        assertEquals("myShort", (short) 2, testObject.myShort);
    }

    @Test
    public void testBoxedPrimitives() {
        TestObject testObject = new TestObject();
        testObject.myBoxedBoolean = false;
        testObject.myBoxedByte = 1;
        testObject.myBoxedChar = 'a';
        testObject.myBoxedDouble = 1.1;
        testObject.myBoxedFloat = 1.1f;
        testObject.myBoxedInt = 1;
        testObject.myBoxedLong = 1L;
        testObject.myBoxedShort = 1;

        Map<String, Object> updates = new HashMap<>();
        updates.put("myBoxedBoolean", true);
        updates.put("myBoxedByte", (byte) 2);
        updates.put("myBoxedChar", 'b');
        updates.put("myBoxedDouble", 2.2);
        updates.put("myBoxedFloat", 2.2f);
        updates.put("myBoxedInt", 2);
        updates.put("myBoxedLong", 2L);
        updates.put("myBoxedShort", (short) 2);

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("myBoxedBoolean", true, testObject.myBoxedBoolean);
        assertEquals("myBoxedByte", Byte.valueOf((byte) 2), testObject.myBoxedByte);
        assertEquals("myBoxedChar", Character.valueOf('b'), testObject.myBoxedChar);
        assertEquals("myBoxedDouble", Double.valueOf(2.2), testObject.myBoxedDouble);
        assertEquals("myBoxedFloat", Float.valueOf(2.2f), testObject.myBoxedFloat);
        assertEquals("myBoxedInt", Integer.valueOf(2), testObject.myBoxedInt);
        assertEquals("myBoxedLong", Long.valueOf(2L), testObject.myBoxedLong);
        assertEquals("myBoxedShort", Short.valueOf((short) 2), testObject.myBoxedShort);
    }

    @Test(expected = RuntimeException.class)
    public void testCannotConvertObjectToPrimitive() {
        TestObject testObject = new TestObject();

        Map<String, Object> updates = new HashMap<>();
        updates.put("myBoolean", new JSONObject());

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);
    }

    @Test
    public void testSpecialObjects() {
        TestObject testObject = new TestObject();
        testObject.myString = "antman";
        testObject.myBigDecimal = BigDecimal.valueOf(1.1);
        testObject.myBigInteger = BigInteger.valueOf(1);

        Map<String, Object> updates = new HashMap<>();
        updates.put("myString", "batman");
        updates.put("myBigDecimal", BigDecimal.valueOf(2.2));
        updates.put("myBigInteger", BigInteger.valueOf(2));

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("myString", "batman", testObject.myString);
        assertEquals("myBigDecimal", BigDecimal.valueOf(2.2), testObject.myBigDecimal);
        assertEquals("myBigInteger", BigInteger.valueOf(2), testObject.myBigInteger);
    }

    @Test
    public void testBigNumbersFromStrings() {
        TestObject testObject = new TestObject();
        testObject.myBigDecimal = BigDecimal.valueOf(1.1);
        testObject.myBigInteger = BigInteger.valueOf(1);

        Map<String, Object> updates = new HashMap<>();
        updates.put("myBigDecimal", "2.2");
        updates.put("myBigInteger", "2");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("myBigDecimal", BigDecimal.valueOf(2.2), testObject.myBigDecimal);
        assertEquals("myBigInteger", BigInteger.valueOf(2), testObject.myBigInteger);
    }

    @Test
    public void testMaps() {
        TestObject testObject = new TestObject();
        testObject.myInterfaceMap = new java.util.LinkedHashMap<>();
        testObject.myInterfaceMap.put("value", new TestObject.InnerTestObject("inside"));

        Map<String, Object> updates = new HashMap<>();

        LinkedHashMap<String, TestObject.InnerTestObject> newInterfaceMap = new LinkedHashMap<>();
        newInterfaceMap.put("value", new TestObject.InnerTestObject("out"));
        updates.put("myInterfaceMap", newInterfaceMap);

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("myInterfaceMap", newInterfaceMap, testObject.myInterfaceMap);
    }

    @Test
    public void testMapsFromJsonObjects() throws Exception {
        TestObject testObject = new TestObject();
        testObject.myInterfaceMap = new LinkedHashMap<>();
        testObject.myInterfaceMap.put("value", new TestObject.InnerTestObject("inside"));

        Map<String, Object> updates = getUpdateMapFromFile("update-maps.json");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        LinkedHashMap<String, TestObject.InnerTestObject> expected = new LinkedHashMap<>();
        expected.put("value", new TestObject.InnerTestObject("out"));
        assertEquals("myInterfaceMap", expected, testObject.myInterfaceMap);
    }

    @Test(expected = RuntimeException.class)
    public void testCannotConvertArrayToMap() {
        TestObject testObject = new TestObject();

        Map<String, Object> updates = new HashMap<>();
        updates.put("myInterfaceMap", new JSONArray());

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);
    }

    @Test
    public void testCollections() {
        TestObject testObject = new TestObject();

        HashMap<String, Object> updates = new HashMap<>();
        List<List<Integer>> lists = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        list.add(5);
        lists.add(list);
        updates.put("myCollectionOfCollections", lists);

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals(CollectionUtils.<List>newArrayList(CollectionUtils.newArrayList(5)),
                     testObject.myCollectionOfCollections);
    }

    @Test
    public void testCollectionsFromJsonArrays() throws Exception {
        TestObject testObject = new TestObject();
        testObject.myStringCollection = CollectionUtils.newArrayList("one", "two", "three");

        Map<String, Object> updates = getUpdateMapFromFile("update-collections.json");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals(CollectionUtils.newArrayList("3", "2", "1"), testObject.myStringCollection);
    }

    @Test(expected = RuntimeException.class)
    public void testCannotConvertStringToCollection() {
        TestObject testObject = new TestObject();

        HashMap<String, Object> updates = new HashMap<>();
        updates.put("myStringCollection", "I don't belong :`( ");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);
    }

    @Test
    public void testCustomObjects() {
        TestObject testObject = new TestObject();
        testObject.myInnerObject = new TestObject.InnerTestObject("Remus");

        Map<String, Object> updates = new HashMap<>();
        updates.put("myInnerObject", new TestObject.InnerTestObject("Romulus"));

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("myInnerObject.string", "Romulus", testObject.myInnerObject.string);
    }

    @Test
    public void testCustomObjectWithNullValueInMap() {
        TestObject testObject = new TestObject();
        testObject.myInnerObject = new TestObject.InnerTestObject("Malcom Reynolds");

        Map<String, Object> updates = new HashMap<>();
        updates.put("myInnerObject", null);

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("myInnerObject", null, testObject.myInnerObject);
    }

    @Test
    public void testCustomObjectsFromJson() throws Exception {
        TestObject testObject = new TestObject();
        testObject.myInnerObject = new TestObject.InnerTestObject("Remus");

        Map<String, Object> updates = getUpdateMapFromFile("update-custom-object.json");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("myInnerObject.string", "Romulus", testObject.myInnerObject.string);
    }

    @Test(expected = RuntimeException.class)
    public void testCannotConvertStringToObject() {
        TestObject testObject = new TestObject();

        Map<String, Object> updates = new HashMap<>();
        updates.put("myInnerObject", "Nobody loves me.");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);
    }

    @Test
    public void testJSONObject() throws Exception {
        TestObject testObject = new TestObject();

        Map<String, Object> updates = getUpdateMapFromFile("update-json-object.json");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertNotNull("testObject.myJsonObject", testObject.myJsonObject);
        assertEquals("Klingon", testObject.myJsonObject.optString("string"));
    }

    @Test(expected = RuntimeException.class)
    public void testCannotConvertJsonArrayToJsonObject() {
        TestObject testObject = new TestObject();

        Map<String, Object> updates = new HashMap<>();
        updates.put("myJsonObject", new JSONArray());

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);
    }

    @Test
    public void testJSONArray() throws Exception {
        TestObject testObject = new TestObject();

        Map<String, Object> updates = getUpdateMapFromFile("update-json-array.json");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertNotNull("testObject.myJsonArray", testObject.myJsonArray);
        assertEquals(3, testObject.myJsonArray.length());
        assertEquals("one", testObject.myJsonArray.optString(0));
        assertEquals(2, testObject.myJsonArray.optInt(1));
        assertTrue("myJsonArray[2] instanceof JSONObject", testObject.myJsonArray.opt(2) instanceof JSONObject);
    }

    @Test
    public void testCollectionWithNullValueUpdate() throws Exception {
        TestObject testObject = new TestObject();
        testObject.myCollectionWithNullValues = CollectionUtils.newArrayList("one", null, "null");

        Map<String, Object> updates = getUpdateMapFromFile("update-json-array-with-nulls.json");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals(testObject.myCollectionWithNullValues, CollectionUtils.newArrayList("one", null, "null"));
    }

    @Test(expected = RuntimeException.class)
    public void testCannotConvertJsonObjectToJsonArray() {
        TestObject testObject = new TestObject();

        Map<String, Object> updates = new HashMap<>();
        updates.put("myJsonArray", new JSONObject());

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);
    }

    @Test
    public void testJSONObjectCollection() throws Exception {
        TestObject testObject = new TestObject();

        Map<String, Object> updates = getUpdateMapFromFile("update-json-object-collection.json");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertNotNull(testObject.myJsonObjectCollection);
        assertEquals(2, testObject.myJsonObjectCollection.size());
        assertNotNull(testObject.myJsonObjectCollection.get(0));
        assertNotNull(testObject.myJsonObjectCollection.get(1));
    }

    @Test
    public void testSelfValuesMap() {
        SelfMapObject selfMapObject = new SelfMapObject();
        selfMapObject.string = "a";
        selfMapObject.selfValues = new HashMap<>();
        selfMapObject.selfValues.put("key1", "value 1");
        selfMapObject.selfValues.put("key2", "value 2");

        Map<String, Object> updates = new HashMap<>();
        updates.put("string", "b");
        updates.put("key1", "value 1 updated");

        SelfMapObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(selfMapObject, updates, CONTEXT);

        assertEquals("string", "b", selfMapObject.string);
        assertEquals("selfValues.size", 2, selfMapObject.selfValues.size());
        assertEquals("selfValues[key1]", "value 1 updated", selfMapObject.selfValues.get("key1"));
        assertEquals("selfValues[key2]", "value 2", selfMapObject.selfValues.get("key2"));
    }

    @Test
    public void testSelfValuesMapFromJsonObject() throws Exception {
        SelfMapObject selfMapObject = new SelfMapObject();
        selfMapObject.string = "a";
        selfMapObject.selfValues = new HashMap<>();
        selfMapObject.selfValues.put("key1", "value 1");
        selfMapObject.selfValues.put("key2", "value 2");

        Map<String, Object> updates = getUpdateMapFromFile("update-self-values.json");

        SelfMapObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(selfMapObject, updates, CONTEXT);

        assertEquals("string", "b", selfMapObject.string);
        assertEquals("selfValues.size", 3, selfMapObject.selfValues.size());
        assertEquals("selfValues[key1]", "value 1 updated", selfMapObject.selfValues.get("key1"));
        assertEquals("selfValues[key2]", "value 2", selfMapObject.selfValues.get("key2"));
        assertEquals("selfValues[key3]", new SimpleTestObject("simple string", "simpleTestObject"),
                     selfMapObject.selfValues.get("key3"));
    }

    @Test
    public void testSelfValuesMapUnconverted() throws Exception {
        SelfMapObjectUnconverted selfMapObject = new SelfMapObjectUnconverted();
        selfMapObject.string = "a";
        selfMapObject.selfValuesUnconverted = new HashMap<>();
        selfMapObject.selfValuesUnconverted.put("key1", "value 1");
        selfMapObject.selfValuesUnconverted.put("key2", "value 2");

        Map<String, Object> updates = getUpdateMapFromFile("update-self-values.json");

        SelfMapObjectUnconverted$$JsonObjectParser.INSTANCE.updateInstanceFromMap(selfMapObject, updates, CONTEXT);

        assertEquals("string", "b", selfMapObject.string);
        assertEquals("selfValuesUnconverted.size", 3, selfMapObject.selfValuesUnconverted.size());
        assertEquals("selfValuesUnconverted[key1]", "value 1 updated", selfMapObject.selfValuesUnconverted.get("key1"));
        assertEquals("selfValuesUnconverted[key2]", "value 2", selfMapObject.selfValuesUnconverted.get("key2"));
        assertThat(selfMapObject.selfValuesUnconverted.get("key3")).isInstanceOf(JSONObject.class);
    }

    @Test
    public void testNoChanges() {
        TestObject testObject = new TestObject();
        testObject.myString = "C-3PO";

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, new HashMap<String, Object>(0),
                                                                    CONTEXT);

        assertEquals("myString", "C-3PO", testObject.myString);
    }

    @Test
    public void testStringWithNullValueInMap() {
        TestObject testObject = new TestObject();
        testObject.myString = "BB-8";

        Map<String, Object> updates = new HashMap<>();
        updates.put("myString", null);

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals(null, testObject.myString);
    }

    @Test
    public void testSetters() {
        TestObject testObject = new TestObject();
        testObject.stringFromSetter = "B-4";

        Map<String, Object> updates = new HashMap<>();
        updates.put("stringSetter", "Data");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("stringSetter", "Data", testObject.stringFromSetter);
    }

    @Test
    public void testPostCreateChildMethodCalled() throws Exception {
        TestObject testObject = new TestObject();

        Map<String, Object> updates = getUpdateMapFromFile("update-collection-of-collections.json");

        TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

        assertEquals("post-parse:original", testObject.mySetsOfTestObjects.get(0).iterator().next().myString);
    }
}


text:
package org.apache.camel.support.jsse;

import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;

import org.apache.camel.CamelContext;
import org.apache.camel.TestSupport;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.DefaultCamelContext;

public abstract class AbstractJsseParametersTest extends TestSupport {

    protected CamelContext createPropertiesPlaceholderAwareContext() throws Exception {
        Properties supplementalProperties = new Properties();

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        SecureRandom sr = null;
        try {
            sr = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
            // Ignore
        }

        SSLContext sslc = SSLContext.getInstance("TLS");
        sslc.init(null, null, null);
        SSLSocket socket = (SSLSocket) sslc.getSocketFactory().createSocket();

        supplementalProperties.setProperty("keyStoreParameters.type", KeyStore.getDefaultType());
        supplementalProperties.setProperty("keyStoreParameters.provider", ks.getProvider().getName());

        supplementalProperties.setProperty("keyManagersParameters.algorithm", KeyManagerFactory.getDefaultAlgorithm());
        supplementalProperties.setProperty("keyManagersParameters.provider", kmf.getProvider().getName());

        supplementalProperties.setProperty("trustManagersParameters.algorithm", TrustManagerFactory.getDefaultAlgorithm());
        supplementalProperties.setProperty("trustManagersParameters.provider", tmf.getProvider().getName());

        if (sr != null) {
            supplementalProperties.setProperty("secureRandomParameters.algorithm", "SHA1PRNG");
            supplementalProperties.setProperty("secureRandomParameters.provider", sr.getProvider().getName());
        }

        supplementalProperties.setProperty("sslContextParameters.provider", sslc.getProvider().getName());
        supplementalProperties.setProperty("cipherSuite.0", socket.getSupportedCipherSuites()[0]);

        // Have to skip this guy because he doesn't work with TLS as the SSLContext protocol
        String ssp = "";
        for (String protocol : socket.getSupportedProtocols()) {
            if (!"SSLv2Hello".equals(protocol)) {
                ssp = protocol;
                break;
            }
        }
        supplementalProperties.setProperty("secureSocketProtocol.0", ssp);

        return this.createPropertiesPlaceholderAwareContext(supplementalProperties);
    }

    protected CamelContext createPropertiesPlaceholderAwareContext(Properties supplementalProperties) throws IOException {
        Properties properties = new Properties(supplementalProperties);
        properties.load(AbstractJsseParametersTest.class.getResourceAsStream("test.properties"));

        if (supplementalProperties != null) {
            Properties mergedProps = new Properties();

            Set<String> keys = new HashSet<>();
            keys.addAll(properties.stringPropertyNames());
            keys.addAll(supplementalProperties.stringPropertyNames());

            for (String key : keys) {
                mergedProps.setProperty(key, properties.getProperty(key));
            }

            properties = mergedProps;
        }

        properties.store(new FileOutputStream("target/jsse-test.properties"),
                "Generated by " + AbstractJsseParametersTest.class.getName());

        PropertiesComponent pc = new PropertiesComponent();
        pc.setLocation("file:./target/jsse-test.properties");

        CamelContext context = new DefaultCamelContext();
        context.addComponent("properties", pc);

        return context;
    }

}


text:
package object

import (
	"github.com/RotatingFans/govmomi/vim25"
	"github.com/RotatingFans/govmomi/vim25/methods"
	"github.com/RotatingFans/govmomi/vim25/mo"
	"github.com/RotatingFans/govmomi/vim25/types"
	"golang.org/x/net/context"
)

type HostVirtualNicManager struct {
	Common
	Host *HostSystem
}

func NewHostVirtualNicManager(c *vim25.Client, ref types.ManagedObjectReference, host types.ManagedObjectReference) *HostVirtualNicManager {
	return &HostVirtualNicManager{
		Common: NewCommon(c, ref),
		Host:   NewHostSystem(c, host),
	}
}

func (m HostVirtualNicManager) Info(ctx context.Context) (*types.HostVirtualNicManagerInfo, error) {
	var vnm mo.HostVirtualNicManager

	err := m.Properties(ctx, m.Reference(), []string{"info"}, &vnm)
	if err != nil {
		return nil, err
	}

	return &vnm.Info, nil
}

func (m HostVirtualNicManager) DeselectVnic(ctx context.Context, nicType string, device string) error {
	if nicType == string(types.HostVirtualNicManagerNicTypeVsan) {
		// Avoid fault.NotSupported:
		// "Error deselecting device '$device': VSAN interfaces must be deselected using vim.host.VsanSystem"
		s, err := m.Host.ConfigManager().VsanSystem(ctx)
		if err != nil {
			return err
		}

		return s.updateVnic(ctx, device, false)
	}

	req := types.DeselectVnicForNicType{
		This:    m.Reference(),
		NicType: nicType,
		Device:  device,
	}

	_, err := methods.DeselectVnicForNicType(ctx, m.Client(), &req)
	return err
}

func (m HostVirtualNicManager) SelectVnic(ctx context.Context, nicType string, device string) error {
	if nicType == string(types.HostVirtualNicManagerNicTypeVsan) {
		// Avoid fault.NotSupported:
		// "Error selecting device '$device': VSAN interfaces must be selected using vim.host.VsanSystem"
		s, err := m.Host.ConfigManager().VsanSystem(ctx)
		if err != nil {
			return err
		}

		return s.updateVnic(ctx, device, true)
	}

	req := types.SelectVnicForNicType{
		This:    m.Reference(),
		NicType: nicType,
		Device:  device,
	}

	_, err := methods.SelectVnicForNicType(ctx, m.Client(), &req)
	return err
}


text: * Complete rewrite to make use of livedata


text:
using System;

namespace Azure.ResourceManager.Media.Models
{
    /// <summary> Akamai Signature Header authentication key. </summary>
    public partial class AkamaiSignatureHeaderAuthenticationKey
    {
        /// <summary> Initializes a new instance of AkamaiSignatureHeaderAuthenticationKey. </summary>
        public AkamaiSignatureHeaderAuthenticationKey()
        {
        }

        /// <summary> Initializes a new instance of AkamaiSignatureHeaderAuthenticationKey. </summary>
        /// <param name="identifier"> identifier of the key. </param>
        /// <param name="base64Key"> authentication key. </param>
        /// <param name="expireOn"> The expiration time of the authentication key. </param>
        internal AkamaiSignatureHeaderAuthenticationKey(string identifier, string base64Key, DateTimeOffset? expireOn)
        {
            Identifier = identifier;
            Base64Key = base64Key;
            ExpireOn = expireOn;
        }

        /// <summary> identifier of the key. </summary>
        public string Identifier { get; set; }
        /// <summary> authentication key. </summary>
        public string Base64Key { get; set; }
        /// <summary> The expiration time of the authentication key. </summary>
        public DateTimeOffset? ExpireOn { get; set; }
    }
}


text:
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}

module Main (main) where

import Data.Time
import Data.Time.Zones
import Test.Framework.Providers.HUnit
import Test.Framework.TH
import Test.HUnit hiding (Test, assert)

case_utcTZ_is_utc = timeZoneForPOSIX utcTZ 0 @?= utc

case_utcTZ_zero_diff = diffForPOSIX utcTZ 0 @?= 0

case_DB_utc_is_utc = do
  tz <- loadTZFromDB "UTC"
  tz @?= utcTZ

mkLocal y m d hh mm ss
  = LocalTime (fromGregorian y m d) (TimeOfDay hh mm ss)

mkUTC y m d hh mm ss
  = UTCTime (fromGregorian y m d) (timeOfDayToTime $ TimeOfDay hh mm ss)

case_Budapest_LocalToUTC = do
  tz <- loadTZFromDB "Europe/Budapest"
  let zWinter = TimeZone 60 False "CET"
      zSummer = TimeZone 120 True "CEST"
  -- Handle std times:
  localTimeToUTCFull tz (mkLocal 1970 01 01  01 00 00) @?=
    LTUUnique (mkUTC 1970 01 01  00 00 00) zWinter
  localTimeToUTCFull tz (mkLocal 2014 03 23  00 15 15.15) @?=
    LTUUnique (mkUTC 2014 03 22  23 15 15.15) zWinter

  -- Handle time in winter->summer transition:
  localTimeToUTCFull tz (mkLocal 2014 03 30  02 15 15) @?=
    LTUNone (mkUTC 2014 03 30  01 15 15) zWinter
  -- That utc time is acually in dst already:
  localTimeToUTCFull tz (mkLocal 2014 03 30  03 15 15) @?=
    LTUUnique (mkUTC 2014 03 30  01 15 15) zSummer

  -- Handle dst times:
  localTimeToUTCFull tz (mkLocal 2014 04 05  06 07 08.987654321999) @?=
    LTUUnique (mkUTC 2014 04 05  04 07 08.987654321999) zSummer

  -- Handle time in summer->winter transition:
  localTimeToUTCFull tz (mkLocal 2013 10 27  02 15 15) @?=
    LTUAmbiguous (mkUTC 2013 10 27  00 15 15) (mkUTC 2013 10 27  01 15 15)
      zSummer zWinter

-- Local->UTC, test for time zones that stop having DST.
-- Bug reported in #8
case_Moscow_LocalToUTC = do
  tz <- loadTZFromDB "Europe/Moscow"
  let zMoscow = TimeZone 180 False "MSK"
  localTimeToUTCFull tz (mkLocal 2015 11 23  00 00 00) @?=
    LTUUnique (mkUTC 2015 11 22  21 00 00) zMoscow

case_UTC_diffForAbbr = do
  tz <- loadTZFromDB "UTC"
  diffForAbbr tz "UTC" @?= Just 0
  diffForAbbr tz "XYZ" @?= Nothing

case_Paris_diffForAbbr = do
  tz <- loadTZFromDB "Europe/Paris"
  diffForAbbr tz "CET" @?= Just 3600
  diffForAbbr tz "CEST" @?= Just 7200
  diffForAbbr tz "WET" @?= Just 0
  diffForAbbr tz "LMT" @?= Just 561
  diffForAbbr tz "XYZ" @?= Nothing

main :: IO ()
main = $defaultMainGenerator


text:
[![Code Climate](https://codeclimate.com/github/forward3d/rbhive/badges/gpa.svg)](https://codeclimate.com/github/forward3d/rbhive)

### WARNING

This is u2i fork of [rbhive](https://github.com/forward3d/rbhive).

```
gem 'rbhive-u2i', require: 'rbhive'
```

RBHive is a simple Ruby gem to communicate with the [Apache Hive](http://hive.apache.org)
Thrift servers.

It supports:
* Hiveserver (the original Thrift service shipped with Hive since early releases)
* Hiveserver2 (the new, concurrent Thrift service shipped with Hive releases since 0.10)
* Any other 100% Hive-compatible Thrift service (e.g. [Sharkserver](https://github.com/amplab/shark))

It is capable of using the following Thrift transports:
* BufferedTransport (the default)
* SaslClientTransport ([SASL-enabled](http://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer) transport)
* HTTPClientTransport (tunnels Thrift over HTTP)

As of version 1.0, it supports asynchronous execution of queries. This allows you to submit
a query, disconnect, then reconnect later to check the status and retrieve the results.
This frees systems of the need to keep a persistent TCP connection.

## About Thrift services and transports

### Hiveserver

Hiveserver (the original Thrift interface) only supports a single client at a time. RBHive
implements this with the `RBHive::Connection` class. It only supports a single transport,
BufferedTransport.

### Hiveserver2

[Hiveserver2](https://cwiki.apache.org/confluence/display/Hive/Setting+up+HiveServer2)
(the new Thrift interface) can support many concurrent client connections. It is shipped
with Hive 0.10 and later. In Hive 0.10, only BufferedTranport and SaslClientTransport are
supported; starting with Hive 0.12, HTTPClientTransport is also supported.

Each of the versions after Hive 0.10 has a slightly different Thrift interface; when
connecting, you must specify the Hive version or you may get an exception.

Hiveserver2 supports (in versions later than 0.12) asynchronous query execution. This
works by submitting a query and retrieving a handle to the execution process; you can
then reconnect at a later time and retrieve the results using this handle.
Using the asynchronous methods has some caveats - please read the Asynchronous Execution
section of the documentation thoroughly before using them.

RBHive implements this client with the `RBHive::TCLIConnection` class.

#### Warning!

We had to set the following in hive-site.xml to get the BufferedTransport Thrift service
to work with RBHive:

    <property>
      <name>hive.server2.enable.doAs</name>
      <value>false</value>
    </property>

Otherwise you'll get this nasty-looking exception in the logs:

    ERROR server.TThreadPoolServer: Error occurred during processing of message.
    java.lang.ClassCastException: org.apache.thrift.transport.TSocket cannot be cast to org.apache.thrift.transport.TSaslServerTransport
      at org.apache.hive.service.auth.TUGIContainingProcessor.process(TUGIContainingProcessor.java:35)
      at org.apache.thrift.server.TThreadPoolServer$WorkerProcess.run(TThreadPoolServer.java:206)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
      at java.lang.Thread.run(Thread.java:662)

### Other Hive-compatible services

Consult the documentation for the service, as this will vary depending on the service you're using.

## Connecting to Hiveserver and Hiveserver2

### Hiveserver

Since Hiveserver has no options, connection code is very simple:

    RBHive.connect('hive.server.address', 10_000) do |connection|
      connection.fetch 'SELECT city, country FROM cities'
    end
    ➔ [{:city => "London", :country => "UK"}, {:city => "Mumbai", :country => "India"}, {:city => "New York", :country => "USA"}]

### Hiveserver2

Hiveserver2 has several options with how it is run. The connection code takes
a hash with these possible parameters:
* `:transport` - one of `:buffered` (BufferedTransport), `:http` (HTTPClientTransport), or `:sasl` (SaslClientTransport)
* `:hive_version` - the number after the period in the Hive version; e.g. `10`, `11`, `12`, `13` or one of
   a set of symbols; see [Hiveserver2 protocol versions](#hiveserver2-protocol-versions) below for details
* `:timeout` - if using BufferedTransport or SaslClientTransport, this is how long the timeout on the socket will be
* `:sasl_params` - if using SaslClientTransport, this is a hash of parameters to set up the SASL connection

If you pass either an empty hash or nil in place of the options (or do not supply them), the connection
is attempted with the Hive version set to 0.10, using `:buffered` as the transport, and a timeout of 1800 seconds.

Connecting with the defaults:

    RBHive.tcli_connect('hive.server.address', 10_000) do |connection|
      connection.fetch('SHOW TABLES')
    end

Connecting with a Logger:

    RBHive.tcli_connect('hive.server.address', 10_000, { logger: Logger.new(STDOUT) }) do |connection|
      connection.fetch('SHOW TABLES')
    end

Connecting with a specific Hive version (0.12 in this case):

    RBHive.tcli_connect('hive.server.address', 10_000, { hive_version: 12 }) do |connection|
      connection.fetch('SHOW TABLES')
    end

Connecting with a specific Hive version (0.12) and using the `:http` transport:

    RBHive.tcli_connect('hive.server.address', 10_000, { hive_version: 12, transport: :http }) do |connection|
      connection.fetch('SHOW TABLES')
    end

We have not tested the SASL connection, as we don't run SASL; pull requests and testing are welcomed.

#### Hiveserver2 protocol versions

Since the introduction of Hiveserver2 in Hive 0.10, there have been a number of revisions to the Thrift protocol it uses.

The following table lists the available values you can supply to the `:hive_version` parameter when making a connection
to Hiveserver2.

| value   | Thrift protocol version | notes
| ------- | ----------------------- | -----
| `10`    | V1                      | First version of the Thrift protocol used only by Hive 0.10
| `11`    | V2                      | Used by the Hive 0.11 release (*but not CDH5 which ships with Hive 0.11!*) - adds asynchronous execution
| `12`    | V3                      | Used by the Hive 0.12 release, adds varchar type and primitive type qualifiers
| `13`    | V7                      | Used by the Hive 0.13 release, adds features from V4, V5 and V6, plus token-based delegation connections
| `:cdh4` | V1                      | CDH4 uses the V1 protocol as it ships with the upstream Hive 0.10
| `:cdh5` | V5                      | CDH5 ships with upstream Hive 0.11, but adds patches to bring the Thrift protocol up to V5

In addition, you can explicitly set the Thrift protocol version according to this table:

| value           | Thrift protocol version | notes
| --------------- | ----------------------- | -----
| `:PROTOCOL_V1`  | V1                      | Used by Hive 0.10 release
| `:PROTOCOL_V2`  | V2                      | Used by Hive 0.11 release
| `:PROTOCOL_V3`  | V3                      | Used by Hive 0.12 release
| `:PROTOCOL_V4`  | V4                      | Updated during Hive 0.13 development, adds decimal precision/scale, char type
| `:PROTOCOL_V5`  | V5                      | Updated during Hive 0.13 development, adds error details when GetOperationStatus returns in error state
| `:PROTOCOL_V6`  | V6                      | Updated during Hive 0.13 development, adds binary type for binary payload, uses columnar result set
| `:PROTOCOL_V7`  | V7                      | Used by Hive 0.13 release, support for token-based delegation connections

## Asynchronous execution with Hiveserver2

In versions of Hive later than 0.12, the Thrift server supports asynchronous execution.

The high-level view of using this feature is as follows:

1. Submit your query using `async_execute(query)`. This function returns a hash
   with the following keys: `:guid`, `:secret`, and `:session`. You don't need to
   care about the internals of this hash - all methods that interact with an async
   query require this hash, and you can just store it and hand it to the methods.
2. To check the state of the query, call `async_state(handles)`, where `handles`
   is the handles hash given to you when you called `async_execute(query)`.
3. To retrieve results, call either `async_fetch(handles)` or `async_fetch_in_batch(handles)`,
   which work like the non async methods.
4. When you're done with the query, call `async_close_session(handles)`.

### Memory leaks

When you call `async_close_session(handles)`, *all async handles created during this
session are closed*.

If you do not close the sessions you create, *you will leak memory in the Hiveserver2 process*.
Be very careful to close your sessions!

### Method documentation

#### `async_execute(query)`

This method submits a query for async execution. The hash you get back is used in the other
async methods, and will look like this:

    {
      :guid => (binary string),
      :secret => (binary string),
      :session => (binary string)
    }

The Thrift protocol specifies the strings as "binary" - which means they have no encoding.
Be *extremely* careful when manipulating or storing these values, as they can quite easily
get converted to UTF-8 strings, which will make them invalid when trying to retrieve async data.

#### `async_state(handles)`

`handles` is the hash returned by `async_execute(query)`. The state will be a symbol with
one of the following values and meanings:

| symbol                | meaning
| --------------------- | -------
| :initialized          | The query is initialized in Hive and ready to run
| :running              | The query is running (either as a MapReduce job or within process)
| :finished             | The query is completed and results can be retrieved
| :cancelled            | The query was cancelled by a user
| :closed               | Unknown at present
| :error                | The query is invalid semantically or broken in another way
| :unknown              | The query is in an unknown state
| :pending              | The query is ready to run but is not running

There are also the utility methods `async_is_complete?(handles)`, `async_is_running?(handles)`,
`async_is_failed?(handles)` and `async_is_cancelled?(handles)`.

#### `async_cancel(handles)`

Calling this method will cancel the query in execution.

#### `async_fetch(handles)`, `async_fetch_in_batch(handles)`

These methods let you fetch the results of the async query, if they are complete. If you call
these methods on an incomplete query, they will raise an exception. They work in exactly the
same way as the normal synchronous methods.

## Examples

### Fetching results

#### Hiveserver

    RBHive.connect('hive.server.address', 10_000) do |connection|
      connection.fetch 'SELECT city, country FROM cities'
    end
    ➔ [{:city => "London", :country => "UK"}, {:city => "Mumbai", :country => "India"}, {:city => "New York", :country => "USA"}]

#### Hiveserver2

    RBHive.tcli_connect('hive.server.address', 10_000) do |connection|
      connection.fetch 'SELECT city, country FROM cities'
    end
    ➔ [{:city => "London", :country => "UK"}, {:city => "Mumbai", :country => "India"}, {:city => "New York", :country => "USA"}]

### Executing a query

#### Hiveserver

    RBHive.connect('hive.server.address') do |connection|
      connection.execute 'DROP TABLE cities'
    end
    ➔ nil

#### Hiveserver2

    RBHive.tcli_connect('hive.server.address') do |connection|
      connection.execute 'DROP TABLE cities'
    end
    ➔ nil

### Creating tables

    table = TableSchema.new('person', 'List of people that owe me money') do
      column 'name', :string, 'Full name of debtor'
      column 'address', :string, 'Address of debtor'
      column 'amount', :float, 'The amount of money borrowed'

      partition 'dated', :string, 'The date money was given'
      partition 'country', :string, 'The country the person resides in'
    end

Then for Hiveserver:

    RBHive.connect('hive.server.address', 10_000) do |connection|
      connection.create_table(table)
    end

Or Hiveserver2:

    RBHive.tcli_connect('hive.server.address', 10_000) do |connection|
      connection.create_table(table)
    end

### Modifying table schema

    table = TableSchema.new('person', 'List of people that owe me money') do
      column 'name', :string, 'Full name of debtor'
      column 'address', :string, 'Address of debtor'
      column 'amount', :float, 'The amount of money borrowed'
      column 'new_amount', :float, 'The new amount this person somehow convinced me to give them'

      partition 'dated', :string, 'The date money was given'
      partition 'country', :string, 'The country the person resides in'
    end

Then for Hiveserver:

    RBHive.connect('hive.server.address') do |connection|
      connection.replace_columns(table)
    end

Or Hiveserver2:

    RBHive.tcli_connect('hive.server.address') do |connection|
      connection.replace_columns(table)
    end

### Setting properties

You can set various properties for Hive tasks, some of which change how they run. Consult the Apache
Hive documentation and Hadoop's documentation for the various properties that can be set.
For example, you can set the map-reduce job's priority with the following:

    connection.set("mapred.job.priority", "VERY_HIGH")

### Inspecting tables

#### Hiveserver

    RBHive.connect('hive.hadoop.forward.co.uk', 10_000) {|connection|
      result = connection.fetch("describe some_table")
      puts result.column_names.inspect
      puts result.first.inspect
    }

#### Hiveserver2

    RBHive.tcli_connect('hive.hadoop.forward.co.uk', 10_000) {|connection|
      result = connection.fetch("describe some_table")
      puts result.column_names.inspect
      puts result.first.inspect
    }

## Testing

We use RBHive against Hive 0.10, 0.11 and 0.12, and have tested the BufferedTransport and
HTTPClientTransport. We use it against both Hiveserver and Hiveserver2 with success.

We have _not_ tested the SaslClientTransport, and would welcome reports
on whether it works correctly.

## Contributing

We welcome contributions, issues and pull requests. If there's a feature missing in RBHive that you need, or you
think you've found a bug, please do not hesitate to create an issue.

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
using namespace llvm;

extern "C"
{
    void LLVMAddAddressSanitizerFunctionPass( LLVMPassManagerRef PM )
    {
        unwrap( PM )->add( createAddressSanitizerFunctionPass( ) );
    }

    void LLVMAddAddressSanitizerModulePass( LLVMPassManagerRef PM )
    {
        unwrap( PM )->add( createAddressSanitizerModulePass( ) );
    }

    void LLVMAddThreadSanitizerPass( LLVMPassManagerRef PM )
    {
        unwrap( PM )->add( createThreadSanitizerPass( ) );
    }

    void LLVMAddMemorySanitizerPass( LLVMPassManagerRef PM )
    {
        unwrap( PM )->add( createMemorySanitizerPass( ) );
    }

    void LLVMAddDataFlowSanitizerPass( LLVMPassManagerRef PM, const char *ABIListFile )
    {
        unwrap( PM )->add( createDataFlowSanitizerPass( ABIListFile ) );
    }
}


text:
from unittest import TestCase

from openarticlegauge import models
from openarticlegauge import config
import json, redis, time

ARCHIVE = []
@classmethod
def mock_bulk(cls, bibjson_list):
    global ARCHIVE
    ARCHIVE += bibjson_list

@classmethod
def mock_bulk_blocked(cls, bibjson_list):
    global ARCHIVE
    ARCHIVE.append(bibjson_list)

@classmethod
def mock_pull(cls, identifier):
    return None

class TestWorkflow(TestCase):

    def setUp(self):
        global ARCHIVE
        ARCHIVE = []
        self.buffering = config.BUFFERING
        self.bulk = models.Record.bulk
        self.pull = models.Record.pull

    def tearDown(self):
        global ARCHIVE
        ARCHIVE = []
        config.BUFFERING = self.buffering
        models.Record.bulk = self.bulk
        models.Record.pull = self.pull
        client = redis.StrictRedis(host=config.REDIS_BUFFER_HOST, port=config.REDIS_BUFFER_PORT, db=config.REDIS_BUFFER_DB)
        client.delete("id_doi:123")
        client.delete("id_doi:456")
        client.delete("id_doi:789")
        client.delete("flush_buffer_lock")

    def test_01_resultset_init(self):
        rs = models.ResultSet()
        assert rs.requested == 0
        assert len(rs.results) == 0
        assert len(rs.errors) == 0
        assert len(rs.processing) == 0

        ids = [{"id" : "1"}, {"id" : "2"}, {"id" : "3"}]
        rs = models.ResultSet(ids)
        assert rs.requested == 3
        assert len(rs.results) == 0
        assert len(rs.errors) == 0
        assert len(rs.processing) == 0

    def test_02_resultset_results(self):
        ids = [{"id" : "1"}, {"id" : "2"}, {"id" : "3"}]
        rs = models.ResultSet(ids)

        result = {
                    "identifier" : {"id" : "1", "type" : "doi", "canonical" : "doi:1"},
                    "provider" : { "url" : ["http://www.hindawi.com/article"]},
                    "bibjson" : {"title" :  "my title"}
                 }
        record = models.MessageObject(record=result)
        rs.add_result_record(record)

        assert rs.requested == 3
        assert len(rs.results) == 1
        assert len(rs.errors) == 0
        assert len(rs.processing) == 0

        bibjson = rs.results[0]
        assert bibjson.has_key("title")
        assert bibjson["title"] == "my title"
        assert bibjson.has_key("identifier")
        assert len(bibjson["identifier"]) == 1
        assert bibjson["identifier"][0].has_key("id")
        assert bibjson["identifier"][0].has_key("type")
        assert bibjson["identifier"][0].has_key("canonical")

    def test_03_resultset_errors(self):
        ids = [{"id" : "1"}, {"id" : "2"}, {"id" : "3"}]
        rs = models.ResultSet(ids)

        result = {
                    "identifier" : {"id" : "1", "type" : "doi", "canonical" : "doi:1"},
                    "provider" : {"url" : ["http://www.hindawi.com/article"]},
                    "error" : "broken"
                 }
        record = models.MessageObject(record=result)
        rs.add_result_record(record)

        assert rs.requested == 3
        assert len(rs.results) == 0
        assert len(rs.errors) == 1
        assert len(rs.processing) == 0

        error = rs.errors[0]
        assert error.has_key("error")
        assert error["error"] == "broken"
        assert error.has_key("identifier")
        assert error["identifier"].has_key("id")

    def test_04_resultset_processing(self):
        ids = [{"id" : "1"}, {"id" : "2"}, {"id" : "3"}]
        rs = models.ResultSet(ids)

        result = {
                    "identifier" : {"id" : "1", "type" : "doi", "canonical" : "doi:1"},
                    "provider" : {"url" : ["http://www.hindawi.com/article"]},
                    "queued" : True
                 }
        record = models.MessageObject(record=result)
        rs.add_result_record(record)

        assert rs.requested == 3
        assert len(rs.results) == 0
        assert len(rs.errors) == 0
        assert len(rs.processing) == 1

        queued = rs.processing[0]
        assert queued.has_key("identifier")
        assert queued["identifier"].has_key("id")

    def test_05_resultset_mixed(self):
        ids = [{"id" : "1"}, {"id" : "2"}, {"id" : "3"}, {"id" : "4"}]
        rs = models.ResultSet(ids)

        results = []
        results.append({
                    "identifier" : {"id" : "1", "type" : "doi", "canonical" : "doi:1"},
                    "provider" : {"url" : ["http://www.hindawi.com/article"]},
                    "bibjson" : {"title" :  "my title"}
                 })

        results.append({
                    "identifier" : {"id" : "2", "type" : "doi", "canonical" : "doi:2"},
                    "provider" : { "url" : ["http://www.hindawi.com/article"]},
                    "error" : "broken"
                 })

        results.append({
                    "identifier" : {"id" : "3", "type" : "doi", "canonical" : "doi:3"},
                    "provider" : { "url" : ["http://www.hindawi.com/article"]},
                    "queued" : True
                 })

        results.append({
                "identifier" : {"id" : "4", "type" : "doi", "canonical" : "doi:4"},
                "provider" : {"url" : ["http://www.hindawi.com/hello"]},
                "bibjson" : {"title" :  "another title"}
            })

        for result in results:
            record = models.MessageObject(record=result)
            rs.add_result_record(record)

        assert rs.requested == 4
        assert len(rs.results) == 2
        assert len(rs.errors) == 1
        assert len(rs.processing) == 1

        assert rs.results[0]['title'] in ["my title", "another title"]

    def test_06_resultset_json(self):
        ids = [{"id" : "1"}, {"id" : "2"}, {"id" : "3"}, {"id" : "4"}]
        rs = models.ResultSet(ids)

        results = []
        results.append({
                    "identifier" : {"id" : "1", "type" : "doi", "canonical" : "doi:1"},
                    "provider" : {"url" : ["http://www.hindawi.com/article"]},
                    "bibjson" : {"title" :  "my title"}
                 })

        results.append({
                    "identifier" : {"id" : "2", "type" : "doi", "canonical" : "doi:2"},
                    "provider" : {"url" : ["http://www.hindawi.com/article"]},
                    "error" : "broken"
                 })

        results.append({
                    "identifier" : {"id" : "3", "type" : "doi", "canonical" : "doi:3"},
                    "provider" : {"url" : ["http://www.hindawi.com/article"]},
                    "queued" : True
                 })

        results.append({
                "identifier" : {"id" : "4", "type" : "doi", "canonical" : "doi:4"},
                "provider" : { "url" : ["http://www.hindawi.com/hello"]},
                "bibjson" : {"title" :  "another title"}
            })

        for result in results:
            record = models.MessageObject(record=result)
            rs.add_result_record(record)

        j = rs.json()
        obj = json.loads(j)

        assert obj['requested'] == 4
        assert len(obj['results']) == 2
        assert len(obj['errors']) == 1
        assert len(obj['processing']) == 1

    def test_07_store_with_buffering(self):
        config.BUFFERING = True

        record = {"identifier" : [{"canonical" : "doi:123"}]}
        models.Record.store(record)

        client = redis.StrictRedis(host=config.REDIS_BUFFER_HOST, port=config.REDIS_BUFFER_PORT, db=config.REDIS_BUFFER_DB)
        s = client.get("id_doi:123")
        assert s is not None

        obj = json.loads(s)
        assert obj["identifier"][0]["canonical"] == "doi:123"

    def test_08_check_archive_with_buffering(self):
        config.BUFFERING = True

        record = {"identifier" : [{"canonical" : "doi:123"}]}
        models.Record.store(record)

        obj = models.Record.check_archive("doi:123")
        assert obj["identifier"][0]["canonical"] == "doi:123"

    def test_09_record_flush_buffer(self):
        config.BUFFERING = True
        models.Record.bulk = mock_bulk
        models.Record.pull = mock_pull
        global ARCHIVE

        # first check that it returns False if there's nothing to process
        result = models.Record.flush_buffer()
        assert not result

        # load some records into the buffer
        records = [
            {"identifier" : [{"canonical" : "doi:123"}]},
            {"identifier" : [{"canonical" : "doi:456"}]}
        ]
        for record in records:
            models.Record.store(record)

        # run the flush buffer and check that it executes successfully
        result = models.Record.flush_buffer()
        assert result

        # check that the 2 items in the buffer are now in the archive
        assert len(ARCHIVE) == 2, ARCHIVE
        for record in ARCHIVE:
            assert record['identifier'][0]['canonical'] in ["doi:123", "doi:456"]

        # check that the buffer is empty
        obj1 = models.Record.check_archive("doi:123")
        obj2 = models.Record.check_archive("doi:456")
        assert obj1 is None, obj1
        assert obj2 is None, obj2

    def test_10_record_flush_buffer_timeouts(self):
        config.BUFFERING = True
        models.Record.bulk = mock_bulk
        models.Record.pull = mock_pull
        global ARCHIVE

        # load some records into the buffer
        records = [
            {"identifier" : [{"canonical" : "doi:123"}]},
            {"identifier" : [{"canonical" : "doi:456"}]}
        ]
        for record in records:
            models.Record.store(record)

        # run the flush buffer and check that it executes successfully with a 30 second timeout
        result = models.Record.flush_buffer(key_timeout=30)
        assert result

        # check that the 2 items in the buffer are now in the archive
        assert len(ARCHIVE) == 2, ARCHIVE
        for record in ARCHIVE:
            assert record['identifier'][0]['canonical'] in ["doi:123", "doi:456"]

        # check that the items are also still in the buffer
        obj1 = models.Record.check_archive("doi:123")
        obj2 = models.Record.check_archive("doi:456")
        assert obj1['identifier'][0]['canonical'] in ["doi:123", "doi:456"]
        assert obj2['identifier'][0]['canonical'] in ["doi:123", "doi:456"]

    def test_11_record_flush_buffer_block_sizes(self):
        config.BUFFERING = True
        models.Record.bulk = mock_bulk_blocked
        models.Record.pull = mock_pull
        global ARCHIVE

        # load some records into the buffer
        records = [
            {"identifier" : [{"canonical" : "doi:123"}]},
            {"identifier" : [{"canonical" : "doi:456"}]},
            {"identifier" : [{"canonical" : "doi:789"}]}
        ]
        for record in records:
            models.Record.store(record)

        # run the flush buffer and check that it executes successfully with a block size of 2
        result = models.Record.flush_buffer(block_size=2)
        assert result

        assert len(ARCHIVE) == 2, ARCHIVE # the archive in this case is a list of lists, and there should be 2 lists
        assert len(ARCHIVE[0]) == 2 # the first block should have been 2 long
        assert len(ARCHIVE[1]) == 1 # the second block should have been 1 long

        # slightly convuluted way of checking that each identifier is in the archive exactly once
        canonicals = []
        for record in ARCHIVE[0]:
            assert record['identifier'][0]['canonical'] in ["doi:123", "doi:456", "doi:789"]
            canonicals.append(record['identifier'][0]['canonical'])
        assert ARCHIVE[1][0]['identifier'][0]['canonical'] in ["doi:123", "doi:456", "doi:789"]
        canonicals.append(ARCHIVE[1][0]['identifier'][0]['canonical'])

        assert "doi:123" in canonicals
        assert "doi:456" in canonicals
        assert "doi:789" in canonicals

    def test_12_celery_flush_buffer_no_buffering(self):
        config.BUFFERING = False
        result = models.flush_buffer()
        assert not result

    def test_13_celery_flush_buffer_prelocked(self):
        config.BUFFERING = True

        # manually set a lock on the process
        client = redis.StrictRedis(host=config.REDIS_BUFFER_HOST, port=config.REDIS_BUFFER_PORT, db=config.REDIS_BUFFER_DB)
        client.set("flush_buffer_lock", "lock")

        result = models.flush_buffer()
        assert not result

    def test_14_celery_flush_buffer_success(self):
        config.BUFFERING = True
        config.BUFFER_GRACE_PERIOD = 30
        config.BUFFER_BLOCK_SIZE = 2
        models.Record.bulk = mock_bulk_blocked
        models.Record.pull = mock_pull
        global ARCHIVE

        # load some records into the buffer
        records = [
            {"identifier" : [{"canonical" : "doi:123"}]},
            {"identifier" : [{"canonical" : "doi:456"}]},
            {"identifier" : [{"canonical" : "doi:789"}]}
        ]
        for record in records:
            models.Record.store(record)

        result = models.flush_buffer()
        assert result

        # check that everything got archived
        assert len(ARCHIVE) == 2, ARCHIVE # the archive in this case is a list of lists, and there should be 2 lists
        assert len(ARCHIVE[0]) == 2 # the first block should have been 2 long
        assert len(ARCHIVE[1]) == 1 # the second block should have been 1 long

        # check that the things are still in the buffer
        obj1 = models.Record.check_archive("doi:123")
        obj2 = models.Record.check_archive("doi:456")
        obj3 = models.Record.check_archive("doi:789")
        assert obj1['identifier'][0]['canonical'] in ["doi:123", "doi:456", "doi:789"]
        assert obj2['identifier'][0]['canonical'] in ["doi:123", "doi:456", "doi:789"]
        assert obj3['identifier'][0]['canonical'] in ["doi:123", "doi:456", "doi:789"]

        # check that the lock is still set
        client = redis.StrictRedis(host=config.REDIS_BUFFER_HOST, port=config.REDIS_BUFFER_PORT, db=config.REDIS_BUFFER_DB)
        lock = client.get("flush_buffer_lock")
        assert lock is not None

    def test_15_celery_flush_buffer_trip_lock(self):
        config.BUFFERING = True
        config.BUFFER_GRACE_PERIOD = 2
        config.BUFFER_BLOCK_SIZE = 2
        models.Record.bulk = mock_bulk_blocked
        models.Record.pull = mock_pull
        global ARCHIVE

        # load some records into the buffer
        records = [
            {"identifier" : [{"canonical" : "doi:123"}]},
            {"identifier" : [{"canonical" : "doi:456"}]},
            {"identifier" : [{"canonical" : "doi:789"}]}
        ]
        for record in records:
            models.Record.store(record)

        # run the thing the first time
        result = models.flush_buffer()
        assert result

        # now straight away run it a second time, which should trip the lock
        result2 = models.flush_buffer()
        assert not result2

        # now wait until the lock should be released and try again
        time.sleep(2.1)
        result3 = models.flush_buffer()
        assert result3

    def test_16_message_object_init(self):
        mo = models.MessageObject()
        assert mo.record == {}

        mo = models.MessageObject(bid="1234")
        assert mo.record["identifier"]["id"] == "1234"

        mo = models.MessageObject(bid={"id" : "abc", "type" : "doi"})
        assert mo.record["identifier"]["id"] == "abc"
        assert mo.record["identifier"]["type"] == "doi"

        mo = models.MessageObject(record={"key" : "value"})
        assert "key" in mo.record
        assert mo.record["key"] == "value"

        mo = models.MessageObject(bibjson={"license" : "blah"})
        assert "bibjson" in mo.record
        assert "license" in mo.record["bibjson"]
        assert mo.record["bibjson"]["license"] == "blah"

    def test_17_message_object_getset(self):
        mo = models.MessageObject()
        mo.id = "1234"
        mo.identifier_type = "doi"
        mo.canonical = "doi:1234"
        mo.queued = True
        mo.set_provider_doi("doi:4321")
        mo.add_provider_url("http://1")
        mo.add_provider_urls(["http://2", "http://3"])
        mo.error = "oops"
        mo.add_license_object({"title" : "l1"})
        mo.add_license(title="l2")
        mo.set_licensed_flag()

        assert mo.identifier is not None
        assert mo.id == "1234"
        assert mo.has_id()
        assert mo.identifier_type == "doi"
        assert mo.has_type()
        assert mo.canonical == "doi:1234"
        assert mo.queued
        assert mo.provider is not None
        assert mo.has_provider()
        assert mo.provider_doi == "doi:4321"
        assert len(mo.provider_urls) == 3
        assert "http://1" in mo.provider_urls
        assert "http://2" in mo.provider_urls
        assert "http://3" in mo.provider_urls
        assert mo.bibjson is not None
        assert mo.has_bibjson()
        assert mo.has_error()
        assert mo.error == "oops"
        assert mo.was_licensed()
        assert mo.has_license()
        assert len(mo.license) == 2

        mo.remove_bibjson()
        mo.set_licensed_flag()
        assert mo.bibjson is None
        assert not mo.has_bibjson()
        assert not mo.was_licensed()
        assert len(mo.license) == 0

    def test_18_message_object_merge(self):
        mo = models.MessageObject()
        mo.add_license(title="l1")

        bibjson = {"license" : [{"title" : "l2"}]}
        mo.merge(bibjson)

        assert len(mo.license) == 2
        count = 0
        for l in mo.license:
            assert l.get("title") in ["l1", "l2"]
            if l.get("title") == "l1": count += 1
        assert count == 1

    def test_19_message_object_backend(self):
        mo = models.MessageObject()
        mo.add_license(title="l1")
        record = mo.prep_for_backend()

        assert isinstance(record, dict)
        assert "bibjson" not in record
        assert "licensed" in record
        assert record.get("licensed", False)


text:
import Auth0Lock from 'auth0-lock'
import { push } from 'react-router-redux'

export const secureRoute = (auth) => {
  return (nextstate, replace) => {
    if (!auth.loggedIn()) {
      replace({ pathname: '/login' })
    }
  }
}

const authService = (clientId, domain, ctorOptions) => {
  const TOKEN_KEY = 'id_token'
  const lock = new Auth0Lock(clientId, domain, ctorOptions)

  const login = () => {
    lock.show()
  }

  const getToken = () => {
    return localStorage.getItem(TOKEN_KEY)
  }

  const loggedIn = () => {
    return !!getToken()
  }

  const setToken = (idToken) => {
    localStorage.setItem(TOKEN_KEY, idToken)
  }

  const logout = () => {
    localStorage.removeItem(TOKEN_KEY)
  }

  const doAuthentication = (authResult) => {
    setToken(authResult.idToken)
    push('/')
  }

  lock.on('authenticated', doAuthentication)

  const getProfile = () => {
    return new Promise((resolve, reject) => {
      lock.getProfile(getToken(), (err, profile) => {
        if (err) {
          reject(err)
        } else {
          resolve(profile)
        }
      })
    })
  }

  return {
    login,
    loggedIn,
    logout,
    getToken,
    getProfile
  }
}

export default authService


text:
To refer to these instructions while editing the flow, open [the github page](https://github.com/ot4i/app-connect-templates/tree/master/resources/markdown/Send%20a%20Microsoft%20Teams%20message%20when%20a%20new%20product%20is%20created%20in%20Microsoft%20Dynamics_instructions.md) (opens in a new window).

1.	Click **Create flow** to start using the template.
2.	Connect to the following accounts by using your credentials:
    -	**Microsoft Dynamics 365 for Sales**
    - **Microsoft Teams**
3.	To start the flow, in the banner, open the options menu [⋮] and click **Start flow**.

The flow is started when a new product is created in Microsoft Dynamics 365 for Sales


text:
using Microsoft.Phone.Controls;

namespace ArcGISWindowsPhoneSDK
{
    public partial class MapProgressBarSimple : PhoneApplicationPage
    {
        public MapProgressBarSimple()
        {
            InitializeComponent();
        }
    }
}