text:
package org.apache.wicket.settings;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.wicket.response.filter.IResponseFilter;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.time.Duration;

/**
 * Class for request related settings
 *

 * bufferResponse  (defaults to true) - True if the application should buffer responses. This
 * does require some additional memory, but helps keep exception displays accurate because the whole
 * rendering process completes before the page is sent to the user, thus aRequestCycleSettingsing the possibility of
 * a partially rendered page.
 *

 * renderStrategy - Sets in what way the render part of a request is handled. Basically,
 * there are two different options:
 *

 *
Direct, IRequestCycleSettings.RenderStrategy.ONE_PASS_RENDER. Everything is handled in one
 * physical request. This is efficient, and is the best option if you want to do sophisticated
 * clustering. It does not however, shield you from what is commonly known as the Double submit
 * problem

 *
Using a redirect. This follows the pattern as described at the
 * serverside  and that is commonly known as Redirect after post. Wicket takes it one step
 * further to do any rendering after a redirect, so that not only form submits are shielded from the
 * double submit problem, but also the IRequestListener handlers (that could be e.g. a link that
 * deletes a row). With this pattern, you have two options to choose from:
 *

 *
IRequestCycleSettings.RenderStrategy.REDIRECT_TO_RENDER. This option first handles the
 * 'action' part of the request, which is either page construction (bookmarkable pages or the home
 * page) or calling a IRequestListener handler, such as Link.onClick. When that part is done, a
 * redirect is issued to the render part, which does all the rendering of the page and its
 * components. Be aware  that this may mean, depending on whether you access any
 * models in the action part of the request, that attachment and detachment of some models is done
 * twice for a request.

 *
IRequestCycleSettings.RenderStrategy.REDIRECT_TO_BUFFER. This option handles both the action-
 * and the render part of the request in one physical request, but instead of streaming the result
 * to the browser directly, it is kept in memory, and a redirect is issued to get this buffered
 * result (after which it is immediately removed). This option currently is the default render
 * strategy, as it shields you from the double submit problem, while being more efficient and less
 * error prone regarding to detachable models.

 *

 * Note: In rare cases the strategies involving redirect may lose session data! For example: if
 * after the first phase of the strategy the server node fails without having the chance to
 * replicate the session then the second phase will be executed on another node and the whole
 * process will be restarted and thus anything stored in the first phase will be lost with the
 * failure of the server node. For similar reasons it is recommended to use sticky sessions when
 * using redirect strategies.

 *

 *
 *

 * More documentation is available about each setting in the setter method for the property.
 *
 * @author Jonathan Locke
 * @author Chris Turner
 * @author Eelco Hillenius
 * @author Juergen Donnerstag
 * @author Johan Compagner
 * @author Igor Vaynberg (ivaynberg)
 * @author Martijn Dashorst
 * @author James Carman
 */
public class RequestCycleSettings
{
	/**
	 * Enum type for different render strategies
	 */
	public static enum RenderStrategy {
		/**
		 * All logical parts of a request (the action and render part) are handled within the same
		 * request.
		 *

		 * This strategy is more efficient than the 'REDIRECT_TO_RENDER' strategy, and doesn't have
		 * some of the potential problems of it, it also does not solve the double submit problem.
		 * It is however the best option to use when you want to do sophisticated (non-sticky
		 * session) clustering.
		 *

		 */
		ONE_PASS_RENDER,

		/**
		 * All logical parts of a request (the action and render part) are handled within the same
		 * request, but instead of streaming the render result to the browser directly, the result
		 * is cached on the server. A client side redirect command is issued to the browser
		 * specifically to render this request.
		 */
		REDIRECT_TO_BUFFER,

		/**
		 * The render part of a request (opposed to the 'action part' which is either the
		 * construction of a bookmarkable page or the execution of a IRequestListener handler) is
		 * handled by a separate request by issuing a redirect request to the browser. This is
		 * commonly known as the 'redirect after submit' pattern, though in our case, we use it for
		 * GET and POST requests instead of just the POST requests.
		 *

		 * This pattern solves the 'refresh' problem. While it is a common feature of browsers to
		 * refresh/ reload a web page, this results in problems in many dynamic web applications.
		 * For example, when you have a link with an event handler that e.g. deletes a row from a
		 * list, you usually want to ignore refresh requests after that link is clicked on. By using
		 * this strategy, the refresh request only results in the re-rendering of the page without
		 * executing the event handler again.
		 *

		 *

		 * Though it solves the refresh problem, it introduces potential problems, as the request
		 * that is logically one, are actually two separate request. Not only is this less
		 * efficient, but this also can mean that within the same request attachment/ detachment of
		 * models is done twice (in case you use models in the bookmarkable page constructors and
		 * IRequestListener handlers). If you use this strategy, you should be aware of this
		 * possibility, and should also be aware that for one logical request, actually two
		 * instances of RequestCycle are created and processed.
		 *

		 *

		 * Also, even with this strategy set, it is ignored for instances of
		 * {@link org.apache.wicket.core.request.handler.BookmarkableListenerInterfaceRequestHandler},
		 * because otherwise they wouldn't be bookmarkable.
		 *

		 */
		REDIRECT_TO_RENDER
	}

	/** True if the response should be buffered */
	private boolean bufferResponse = true;

	/**
	 * Whether Wicket should try to get extensive client info by redirecting to
	 * {@link org.apache.wicket.markup.html.pages.BrowserInfoPage a page that polls for client
	 * capabilities}. False by default.
	 */
	private boolean gatherExtendedBrowserInfo = false;

	/**
	 * The render strategy, defaults to 'REDIRECT_TO_BUFFER'. This property influences the default
	 * way in how a logical request that consists of an 'action' and a 'render' part is handled, and
	 * is mainly used to have a means to circumvent the 'refresh' problem.
	 */
	private RequestCycleSettings.RenderStrategy renderStrategy = RenderStrategy.REDIRECT_TO_BUFFER;

	/** List of {@link IResponseFilter}s. */
	private List<IResponseFilter> responseFilters;

	/**
	 * In order to do proper form parameter decoding it is important that the response and the
	 * following request have the same encoding. see
	 * http://www.crazysquirrel.com/computing/general/form-encoding.jspx for additional information.
	 */
	private String responseRequestEncoding = "UTF-8";

	/**
	 * The time that a request will by default be waiting for the previous request to be handled
	 * before giving up. Defaults to one minute.
	 */
	private Duration timeout = Duration.ONE_MINUTE;

	private int exceptionRetryCount = 10;

// ****************************************************************************
// IRequestCycleSettings Implementation
// ****************************************************************************

	/**
	 * Adds a response filter to the list. Filters are evaluated in the order they have been added.
	 *
	 * @param responseFilter
	 *            The {@link IResponseFilter} that is added
	 * @return {@code this} object for chaining
	 */
	public RequestCycleSettings addResponseFilter(IResponseFilter responseFilter)
	{
		if (responseFilters == null)
		{
			responseFilters = new ArrayList<>(3);
		}
		responseFilters.add(responseFilter);
		return this;
	}

	/**
	 * Decides whether to buffer the response's headers until the end of the request processing.
	 * The buffering is needed if the application makes use of
	 * {@link org.apache.wicket.Component#setResponsePage(org.apache.wicket.request.component.IRequestablePage)} or
	 * {@link org.apache.wicket.request.flow.ResetResponseException}
	 *
	 * @return {@code true} if the application should buffer the response's headers.
	 */
	public boolean getBufferResponse()
	{
		return bufferResponse;
	}

	/**
	 * Gets whether Wicket should try to get extensive client info by redirecting to
	 * {@link org.apache.wicket.markup.html.pages.BrowserInfoPage a page that polls for client capabilities}. This method is used by the
	 * default implementation of {@link org.apache.wicket.Session#getClientInfo()}, so if that method is
	 * overridden, there is no guarantee this method will be taken into account.
	 *
	 * @return Whether to gather extensive client info
	 */
	public boolean getGatherExtendedBrowserInfo()
	{
		return gatherExtendedBrowserInfo;
	}

	/**
	 * Gets in what way the render part of a request is handled.
	 *
	 * @return the render strategy
	 */
	public RequestCycleSettings.RenderStrategy getRenderStrategy()
	{
		return renderStrategy;
	}

	/**
	 * @return an unmodifiable list of added response filters, null if none
	 */
	public List<IResponseFilter> getResponseFilters()
	{
		if (responseFilters == null)
		{
			return null;
		}
		else
		{
			return Collections.unmodifiableList(responseFilters);
		}
	}

	/**
	 * In order to do proper form parameter encoding it is important that the response and the
	 * subsequent request stipulate a common character encoding.
	 *
	 * possible form encodings and their problems:
	 *
	 *

	 *
application/x-
	 * www-form-urlencoded

	 *
multipart/form-data

	 *

	 *
	 * wicket now uses multipart/form-data for it's forms.
	 *
	 * @return The request and response encoding
	 */
	public String getResponseRequestEncoding()
	{
		return responseRequestEncoding;
	}

	/**
	 * Gets the time that a request will by default be waiting for the previous request to be
	 * handled before giving up.
	 *
	 * @return The time out
	 */
	public Duration getTimeout()
	{
		return timeout;
	}

	/**
	 * Sets a flag whether the application should buffer the response's headers until the end
	 * of the request processing. The buffering is needed if the application makes use of
	 * {@link org.apache.wicket.Component#setResponsePage(org.apache.wicket.request.component.IRequestablePage)}
	 * or {@link org.apache.wicket.request.flow.ResetResponseException}
	 *
	 * @param bufferResponse
	 *            {@code true} if the application should buffer response's headers.
	 * @return {@code this} object for chaining
	 */
	public RequestCycleSettings setBufferResponse(boolean bufferResponse)
	{
		this.bufferResponse = bufferResponse;
		return this;
	}

	/**
	 * Sets whether Wicket should try to get extensive client info by redirecting to
	 * {@link org.apache.wicket.markup.html.pages.BrowserInfoPage a page that polls for client capabilities}. This method is used by the
	 * default implementation of {@link org.apache.wicket.Session#getClientInfo()}, so if that method is
	 * overridden, there is no guarantee this method will be taken into account.
	 *
	 *

	 * WARNING:  though this facility should work transparently in most cases, it
	 * is recommended that you trigger the roundtrip to get the browser info somewhere where it
	 * hurts the least. The roundtrip will be triggered the first time you call
	 * {@link org.apache.wicket.Session#getClientInfo()} for a session, and after the roundtrip a new request with the
	 * same info (url, post parameters) is handled. So rather than calling this in the middle of an
	 * implementation of a form submit method, which would result in the code of that method before
	 * the call to {@link org.apache.wicket.Session#getClientInfo()} to be executed twice, you best call
	 * {@link org.apache.wicket.Session#getClientInfo()} e.g. in a page constructor or somewhere else where you didn't
	 * do a lot of processing first.
	 *

	 *
	 * @param gatherExtendedBrowserInfo
	 *            Whether to gather extensive client info
	 * @return {@code this} object for chaining
	 */
	public RequestCycleSettings setGatherExtendedBrowserInfo(boolean gatherExtendedBrowserInfo)
	{
		this.gatherExtendedBrowserInfo = gatherExtendedBrowserInfo;
		return this;
	}

	/**
	 * Sets in what way the render part of a request is handled. Basically, there are two different
	 * options:
	 *

	 *
Direct, ApplicationSettings.ONE_PASS_RENDER. Everything is handled in one physical
	 * request. This is efficient, and is the best option if you want to do sophisticated
	 * clustering. It does not however, shield you from what is commonly known as the Double
	 * submit problem

	 *
Using a redirect. This follows the pattern as described at
	 * the serverside  and that is commonly known as Redirect after post. Wicket takes it one
	 * step further to do any rendering after a redirect, so that not only form submits are shielded
	 * from the double submit problem, but also the IRequestListener handlers (that could be e.g. a
	 * link that deletes a row). With this pattern, you have two options to choose from:
	 *

	 *
ApplicationSettings.REDIRECT_TO_RENDER. This option first handles the 'action' part of
	 * the request, which is either page construction (bookmarkable pages or the home page) or
	 * calling a IRequestListener handler, such as Link.onClick. When that part is done, a redirect
	 * is issued to the render part, which does all the rendering of the page and its components.
	 * Be aware  that this may mean, depending on whether you access any models in
	 * the action part of the request, that attachment and detachment of some models is done twice
	 * for a request.

	 *
ApplicationSettings.REDIRECT_TO_BUFFER. This option handles both the action- and the
	 * render part of the request in one physical request, but instead of streaming the result to
	 * the browser directly, it is kept in memory, and a redirect is issue to get this buffered
	 * result (after which it is immediately removed). This option currently is the default render
	 * strategy, as it shields you from the double submit problem, while being more efficient and
	 * less error prone regarding to detachable models.

	 *

	 *
	 * @param renderStrategy
	 *            the render strategy that should be used by default.
	 * @return {@code this} object for chaining
	 */
	public RequestCycleSettings setRenderStrategy(RequestCycleSettings.RenderStrategy renderStrategy)
	{
		this.renderStrategy = renderStrategy;
		return this;
	}

	/**
	 * In order to do proper form parameter decoding it is important that the response and the
	 * following request have the same encoding. see
	 * http://www.crazysquirrel.com/computing/general/form-encoding.jspx for additional information.
	 *
	 * Default encoding: UTF-8
	 *
	 * @param encoding
	 *            The request and response encoding to be used.
	 * @return {@code this} object for chaining
	 */
	public RequestCycleSettings setResponseRequestEncoding(final String encoding)
	{
		Args.notNull(encoding, "encoding");
		this.responseRequestEncoding = encoding;
		return this;
	}

	/**
	 * Sets the time that a request will by default be waiting for the previous request to be
	 * handled before giving up.
	 *
	 * @param timeout
	 * @return {@code this} object for chaining
	 */
	public RequestCycleSettings setTimeout(Duration timeout)
	{
		Args.notNull(timeout, "timeout");
		this.timeout = timeout;
		return this;
	}

	/**
	 * Sets how many attempts Wicket will make to render the exception request handler before
	 *         giving up.
	 * @param retries
	 *      the number of attempts
	 * @return {@code this} object for chaining
	 */
	public RequestCycleSettings setExceptionRetryCount(int retries)
	{
		this.exceptionRetryCount = retries;
		return this;
	}

	/**
	 * @return How many times will Wicket attempt to render the exception request handler before
	 *         giving up.
	 */
	public int getExceptionRetryCount()
	{
		return exceptionRetryCount;
	}
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Routing;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using System.Web.OData.Formatter.Deserialization;
using System.Web.OData.Formatter.Serialization;
using System.Web.OData.Routing;
using System.Web.OData.TestCommon;
using System.Web.OData.TestCommon.Models;
using Microsoft.OData.Core;
using Microsoft.OData.Core.UriParser.Semantic;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Library;
using Microsoft.TestCommon;
using Moq;
using Newtonsoft.Json.Linq;
using ODataPath = System.Web.OData.Routing.ODataPath;

namespace System.Web.OData.Formatter
{
    public class ODataMediaTypeFormatterTests : MediaTypeFormatterTestBase<ODataMediaTypeFormatter>
    {
        [Fact]
        public void Ctor_ThrowsArgumentNull_PayloadKinds()
        {
            Assert.ThrowsArgumentNull(
                () => new ODataMediaTypeFormatter(payloadKinds: null),
                "payloadKinds");
        }

        [Fact]
        public void Ctor_ThrowsArgumentNull_DeserializerProvider()
        {
            ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider();
            ODataPayloadKind[] payloadKinds = new ODataPayloadKind[0];

            Assert.ThrowsArgumentNull(
                () => new ODataMediaTypeFormatter(deserializerProvider: null, serializerProvider: serializerProvider, payloadKinds: payloadKinds),
                "deserializerProvider");
        }

        [Fact]
        public void Ctor_ThrowsArgumentNull_SerializerProvider()
        {
            ODataDeserializerProvider deserializerProvider = new DefaultODataDeserializerProvider();
            ODataPayloadKind[] payloadKinds = new ODataPayloadKind[0];

            Assert.ThrowsArgumentNull(
                () => new ODataMediaTypeFormatter(deserializerProvider, serializerProvider: null, payloadKinds: payloadKinds),
                "serializerProvider");
        }

        [Fact]
        public void CopyCtor_ThrowsArgumentNull_Request()
        {
            ODataMediaTypeFormatter formatter = new ODataMediaTypeFormatter(new ODataPayloadKind[0]);
            Assert.ThrowsArgumentNull(
                () => new ODataMediaTypeFormatter(formatter, version: ODataVersion.V4, request: null),
                "request");
        }

        [Fact]
        public void CopyCtor_ThrowsArgumentNull_Formatter()
        {
            Assert.ThrowsArgumentNull(
                () => new ODataMediaTypeFormatter(formatter: null, version: ODataVersion.V4, request: new HttpRequestMessage()),
                "formatter");
        }

        [Fact]
        public void WriteToStreamAsyncReturnsODataRepresentation()
        {
            // Arrange
            ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();
            modelBuilder.EntitySet<WorkItem>("WorkItems");
            IEdmModel model = modelBuilder.GetEdmModel();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/WorkItems(10)");
            HttpConfiguration configuration = new HttpConfiguration();
            string routeName = "Route";
            configuration.MapODataServiceRoute(routeName, null, model);
            request.SetConfiguration(configuration);
            request.ODataProperties().Model = model;
            IEdmEntitySet entitySet = model.EntityContainer.EntitySets().Single();
            request.ODataProperties().Path = new ODataPath(new EntitySetPathSegment(entitySet), new KeyValuePathSegment("10"));
            request.ODataProperties().RouteName = routeName;

            ODataMediaTypeFormatter formatter = CreateFormatterWithJson(model, request, ODataPayloadKind.Entry);

            // Act
            ObjectContent<WorkItem> content = new ObjectContent<WorkItem>(
                (WorkItem)TypeInitializer.GetInstance(SupportedTypes.WorkItem), formatter);

            // Assert
            JsonAssert.Equal(Resources.WorkItemEntry, content.ReadAsStringAsync().Result);
        }

        [Theory]
        [InlineData("prefix", "http://localhost/prefix")]
        [InlineData("{a}", "http://localhost/prefix")]
        [InlineData("{a}/{b}", "http://localhost/prefix/prefix2")]
        public void WriteToStreamAsync_ReturnsCorrectBaseUri(string routePrefix, string baseUri)
        {
            IEdmModel model = new ODataConventionModelBuilder().GetEdmModel();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, baseUri);
            HttpConfiguration configuration = new HttpConfiguration();
            string routeName = "Route";
            configuration.MapODataServiceRoute(routeName, routePrefix, model);
            request.SetConfiguration(configuration);
            request.ODataProperties().Model = model;
            request.ODataProperties().Path = new ODataPath();
            request.ODataProperties().RouteName = routeName;
            HttpRouteData routeData = new HttpRouteData(new HttpRoute());
            routeData.Values.Add("a", "prefix");
            routeData.Values.Add("b", "prefix2");
            request.SetRouteData(routeData);

            ODataMediaTypeFormatter formatter = CreateFormatterWithJson(model, request, ODataPayloadKind.ServiceDocument);
            var content = new ObjectContent<ODataServiceDocument>(new ODataServiceDocument(), formatter);

            string actualContent = content.ReadAsStringAsync().Result;

            Assert.Contains("\"@odata.context\":\"" + baseUri + "/$metadata\"", actualContent);
        }

        [Fact]
        public void WriteToStreamAsync_Throws_WhenBaseUriCannotBeGenerated()
        {
            IEdmModel model = new ODataConventionModelBuilder().GetEdmModel();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/");
            HttpConfiguration configuration = new HttpConfiguration();
            configuration.Routes.MapHttpRoute("OData", "{param}");
            request.SetConfiguration(configuration);
            request.ODataProperties().Model = model;
            request.ODataProperties().Path = new ODataPath();
            request.ODataProperties().RouteName = "OData";

            ODataMediaTypeFormatter formatter = CreateFormatter(model, request, ODataPayloadKind.ServiceDocument);
            var content = new ObjectContent<ODataServiceDocument>(new ODataServiceDocument(), formatter);

            Assert.Throws<SerializationException>(
                () => content.ReadAsStringAsync().Result,
                "The ODataMediaTypeFormatter was unable to determine the base URI for the request. The request must be processed by an OData route for the OData formatter to serialize the response.");
        }

        [Theory]
        [InlineData(null, null, "4.0")]
        [InlineData("1.0", null, "4.0")]
        [InlineData("2.0", null, "4.0")]
        [InlineData("3.0", null, "4.0")]
        [InlineData(null, "1.0", "4.0")]
        [InlineData(null, "2.0", "4.0")]
        [InlineData(null, "3.0", "4.0")]
        [InlineData("1.0", "1.0", "4.0")]
        [InlineData("1.0", "2.0", "4.0")]
        [InlineData("1.0", "3.0", "4.0")]
        public void SetDefaultContentHeaders_SetsRightODataServiceVersion(string requestDataServiceVersion, string requestMaxDataServiceVersion, string expectedDataServiceVersion)
        {
            HttpRequestMessage request = new HttpRequestMessage();
            if (requestDataServiceVersion != null)
            {
                request.Headers.TryAddWithoutValidation("OData-Version", requestDataServiceVersion);
            }
            if (requestMaxDataServiceVersion != null)
            {
                request.Headers.TryAddWithoutValidation("OData-MaxVersion", requestMaxDataServiceVersion);
            }

            HttpContentHeaders contentHeaders = new StringContent("").Headers;

            CreateFormatterWithoutRequest()
            .GetPerRequestFormatterInstance(typeof(int), request, MediaTypeHeaderValue.Parse("application/xml"))
            .SetDefaultContentHeaders(typeof(int), contentHeaders, MediaTypeHeaderValue.Parse("application/xml"));

            IEnumerable<string> headervalues;
            Assert.True(contentHeaders.TryGetValues("OData-Version", out headervalues));
            Assert.Equal(new string[] { expectedDataServiceVersion }, headervalues);
        }

        [Theory]
        [InlineData(null, null, "application/json; odata.metadata=minimal")]
        [InlineData(null, "utf-8", "application/json; odata.metadata=minimal; charset=utf-8")]
        [InlineData(null, "utf-16", "application/json; odata.metadata=minimal; charset=utf-16")]
        [InlineData("application/json", null, "application/json; odata.metadata=minimal")]
        [InlineData("application/json", "utf-8", "application/json; odata.metadata=minimal; charset=utf-8")]
        [InlineData("application/json", "utf-16", "application/json; odata.metadata=minimal; charset=utf-16")]
        [InlineData("application/json;odata.metadata=minimal", null, "application/json; odata.metadata=minimal")]
        [InlineData("application/json;odata.metadata=minimal", "utf-8", "application/json; odata.metadata=minimal; charset=utf-8")]
        [InlineData("application/json;odata.metadata=minimal", "utf-16", "application/json; odata.metadata=minimal; charset=utf-16")]
        [InlineData("application/json;odata.metadata=full", null, "application/json; odata.metadata=full")]
        [InlineData("application/json;odata.metadata=full", "utf-8", "application/json; odata.metadata=full; charset=utf-8")]
        [InlineData("application/json;odata.metadata=full", "utf-16", "application/json; odata.metadata=full; charset=utf-16")]
        [InlineData("application/json;odata.metadata=none", null, "application/json; odata.metadata=none")]
        [InlineData("application/json;odata.metadata=none", "utf-8", "application/json; odata.metadata=none; charset=utf-8")]
        [InlineData("application/json;odata.metadata=none", "utf-16", "application/json; odata.metadata=none; charset=utf-16")]
        public void SetDefaultContentHeaders_SetsRightContentType(string acceptHeader, string acceptCharset, string contentType)
        {
            // Arrange
            MediaTypeHeaderValue expectedResult = MediaTypeHeaderValue.Parse(contentType);

            // If no accept header is present the content negotiator will pick application/json; odata.metadata=minimal
            // based on CanWriteType
            MediaTypeHeaderValue mediaType = acceptHeader == null ?
                MediaTypeHeaderValue.Parse("application/json; odata.metadata=minimal") :
                MediaTypeHeaderValue.Parse(acceptHeader);

            HttpRequestMessage request = new HttpRequestMessage();
            if (acceptHeader != null)
            {
                request.Headers.TryAddWithoutValidation("Accept", acceptHeader);
            }
            if (acceptCharset != null)
            {
                request.Headers.TryAddWithoutValidation("Accept-Charset", acceptCharset);
                mediaType.CharSet = acceptCharset;
            }

            HttpContentHeaders contentHeaders = new StringContent(String.Empty).Headers;
            contentHeaders.Clear();

            MediaTypeFormatter formatter = ODataMediaTypeFormatters
                .Create()
                .First(f => f.SupportedMediaTypes.Contains(MediaTypeHeaderValue.Parse("application/json")));
            formatter = formatter.GetPerRequestFormatterInstance(typeof(int), request, mediaType);

            // Act
            formatter.SetDefaultContentHeaders(typeof(int), contentHeaders, mediaType);

            // Assert
            Assert.Equal(expectedResult, contentHeaders.ContentType);
        }

        [Fact]
        public void TryGetInnerTypeForDelta_ChangesRefToGenericParameter_ForDeltas()
        {
            Type type = typeof(Delta<Customer>);

            bool success = ODataMediaTypeFormatter.TryGetInnerTypeForDelta(ref type);

            Assert.Same(typeof(Customer), type);
            Assert.True(success);
        }

        [Theory]
        [InlineData(typeof(int))]
        [InlineData(typeof(List<string>))]
        public void TryGetInnerTypeForDelta_ReturnsFalse_ForNonDeltas(Type originalType)
        {
            Type type = originalType;

            bool success = ODataMediaTypeFormatter.TryGetInnerTypeForDelta(ref type);

            Assert.Same(originalType, type);
            Assert.False(success);
        }

        [Fact]
        public override Task WriteToStreamAsync_WhenObjectIsNull_WritesDataButDoesNotCloseStream()
        {
            // Arrange
            ODataMediaTypeFormatter formatter = CreateFormatterWithRequest();
            Mock<Stream> mockStream = new Mock<Stream>();
            mockStream.Setup(s => s.CanWrite).Returns(true);
            HttpContent content = new StringContent(String.Empty);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            // Act
            return formatter.WriteToStreamAsync(typeof(SampleType), null, mockStream.Object, content, null).ContinueWith(
                writeTask =>
                {
                    // Assert (OData formatter doesn't support writing nulls)
                    Assert.Equal(TaskStatus.Faulted, writeTask.Status);
                    Assert.Throws<SerializationException>(() => writeTask.ThrowIfFaulted(), "Cannot serialize a null 'entry'.");
                    mockStream.Verify(s => s.Close(), Times.Never());
                    mockStream.Verify(s => s.BeginWrite(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<AsyncCallback>(), It.IsAny<object>()), Times.Never());
                });
        }

        [Theory]
        [InlineData("Test content", "utf-8", true)]
        [InlineData("Test content", "utf-16", true)]
        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)
        {
            // Arrange
            MediaTypeFormatter formatter = CreateFormatterWithRequest();
            formatter.SupportedEncodings.Add(CreateEncoding(encoding));
            string formattedContent = CreateFormattedContent(content);
            string mediaType = string.Format("application/json; odata.metadata=minimal; charset={0}", encoding);

            // Act & assert
            return ReadContentUsingCorrectCharacterEncodingHelper(
                formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);
        }

        [Theory]
        [InlineData("Test content", "utf-8", true)]
        [InlineData("Test content", "utf-16", true)]
        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)
        {
            // Arrange
            MediaTypeFormatter formatter = CreateFormatterWithRequest();
            formatter.SupportedEncodings.Add(CreateEncoding(encoding));
            string formattedContent = CreateFormattedContent(content);
            string mediaType = string.Format("application/json; odata.metadata=minimal; charset={0}", encoding);

            // Act & assert
            return WriteContentUsingCorrectCharacterEncodingHelper(
                formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);
        }

        [Fact]
        public void ReadFromStreamAsync_ThrowsInvalidOperation_WithoutRequest()
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<Customer>("Customers");
            var formatter = CreateFormatter(builder.GetEdmModel());

            Assert.Throws<InvalidOperationException>(
                () => formatter.ReadFromStreamAsync(typeof(Customer), new MemoryStream(), content: null, formatterLogger: null),
                "The OData formatter requires an attached request in order to deserialize. Controller classes must derive from ODataController or be marked with ODataFormattingAttribute. Custom parameter bindings must call GetPerRequestFormatterInstance on each formatter and use these per-request instances.");
        }

        [Fact]
        public void WriteToStreamAsync_ThrowsInvalidOperation_WithoutRequest()
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<Customer>("Customers");
            var formatter = CreateFormatter(builder.GetEdmModel());

            Assert.Throws<InvalidOperationException>(
                () => formatter.WriteToStreamAsync(typeof(Customer), new Customer(), new MemoryStream(), content: null, transportContext: null),
                "The OData formatter does not support writing client requests. This formatter instance must have an associated request.");
        }

        [Fact]
        public void WriteToStreamAsync_Passes_MetadataLevelToSerializerContext()
        {
            // Arrange
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);
            Mock<ODataSerializer> serializer = new Mock<ODataSerializer>(ODataPayloadKind.Property);
            Mock<ODataSerializerProvider> serializerProvider = new Mock<ODataSerializerProvider>();

            serializerProvider.Setup(p => p.GetODataPayloadSerializer(model, typeof(int), request)).Returns(serializer.Object);
            serializer
                .Setup(s => s.WriteObject(42, typeof(int), It.IsAny<ODataMessageWriter>(),
                    It.Is<ODataSerializerContext>(c => c.MetadataLevel == ODataMetadataLevel.FullMetadata)))
                .Verifiable();

            ODataDeserializerProvider deserializerProvider = new DefaultODataDeserializerProvider();

            var formatter = new ODataMediaTypeFormatter(deserializerProvider, serializerProvider.Object, Enumerable.Empty<ODataPayloadKind>());
            formatter.Request = request;
            HttpContent content = new StringContent("42");
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata.metadata=full");

            // Act
            formatter.WriteToStreamAsync(typeof(int), 42, new MemoryStream(), content, transportContext: null);

            // Assert
            serializer.Verify();
        }

        [Fact]
        public void WriteToStreamAsync_PassesSelectExpandClause_ThroughSerializerContext()
        {
            // Arrange
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);
            SelectExpandClause selectExpandClause =
                new SelectExpandClause(new SelectItem[0], allSelected: true);
            request.ODataProperties().SelectExpandClause = selectExpandClause;

            Mock<ODataSerializer> serializer = new Mock<ODataSerializer>(ODataPayloadKind.Property);
            Mock<ODataSerializerProvider> serializerProvider = new Mock<ODataSerializerProvider>();

            serializerProvider.Setup(p => p.GetODataPayloadSerializer(model, typeof(int), request)).Returns(serializer.Object);
            serializer
                .Setup(s => s.WriteObject(42, typeof(int), It.IsAny<ODataMessageWriter>(),
                    It.Is<ODataSerializerContext>(c => c.SelectExpandClause == selectExpandClause)))
                .Verifiable();

            ODataDeserializerProvider deserializerProvider = new DefaultODataDeserializerProvider();

            var formatter = new ODataMediaTypeFormatter(deserializerProvider, serializerProvider.Object, Enumerable.Empty<ODataPayloadKind>());
            formatter.Request = request;
            HttpContent content = new StringContent("42");
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata.metadata=full");

            // Act
            formatter.WriteToStreamAsync(typeof(int), 42, new MemoryStream(), content, transportContext: null);

            // Assert
            serializer.Verify();
        }

        [Fact]
        public void MessageReaderSettings_Property()
        {
            var formatter = CreateFormatter();

            Assert.NotNull(formatter.MessageReaderSettings);
            Assert.True(formatter.MessageReaderSettings.DisableMessageStreamDisposal);
        }

        [Fact]
        public void MessageWriterSettings_Property()
        {
            var formatter = CreateFormatter();

            Assert.NotNull(formatter.MessageWriterSettings);
            Assert.True(formatter.MessageWriterSettings.DisableMessageStreamDisposal);
            Assert.True(formatter.MessageWriterSettings.AutoComputePayloadMetadataInJson);
        }

        [Fact]
        public void MessageReaderQuotas_Property_RoundTrip()
        {
            var formatter = CreateFormatter();
            formatter.MessageReaderQuotas.MaxNestingDepth = 42;

            Assert.Equal(42, formatter.MessageReaderQuotas.MaxNestingDepth);
        }

        [Fact]
        public void MessageWriterQuotas_Property_RoundTrip()
        {
            var formatter = CreateFormatter();
            formatter.MessageWriterQuotas.MaxNestingDepth = 42;

            Assert.Equal(42, formatter.MessageWriterQuotas.MaxNestingDepth);
        }

        [Fact]
        public void Default_ReceiveMessageSize_Is_MaxedOut()
        {
            var formatter = CreateFormatter();
            Assert.Equal(Int64.MaxValue, formatter.MessageReaderQuotas.MaxReceivedMessageSize);
        }

        [Fact]
        public void MessageReaderQuotas_Is_Passed_To_ODataLib()
        {
            ODataMediaTypeFormatter formatter = CreateFormatter();
            formatter.MessageReaderSettings.MessageQuotas.MaxReceivedMessageSize = 1;

            HttpContent content = new StringContent("{ 'Number' : '42' }");
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            Assert.Throws<ODataException>(
                () => formatter.ReadFromStreamAsync(typeof(int), content.ReadAsStreamAsync().Result, content, formatterLogger: null).Result,
                "The maximum number of bytes allowed to be read from the stream has been exceeded. After the last read operation, a total of 19 bytes has been read from the stream; however a maximum of 1 bytes is allowed.");
        }

        [Fact]
        public void Request_IsPassedThroughDeserializerContext()
        {
            // Arrange
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);
            Mock<ODataEdmTypeDeserializer> deserializer = new Mock<ODataEdmTypeDeserializer>(ODataPayloadKind.Property);
            Mock<ODataDeserializerProvider> deserializerProvider = new Mock<ODataDeserializerProvider>();
            deserializerProvider.Setup(p => p.GetEdmTypeDeserializer(It.IsAny<IEdmTypeReference>())).Returns(deserializer.Object);
            deserializer
                .Setup(d => d.Read(It.IsAny<ODataMessageReader>(), typeof(int), It.Is<ODataDeserializerContext>(c => c.Request == request)))
                .Verifiable();
            ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider();

            var formatter = new ODataMediaTypeFormatter(deserializerProvider.Object, serializerProvider, Enumerable.Empty<ODataPayloadKind>());
            formatter.Request = request;
            HttpContent content = new StringContent("42");
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata.metadata=full");

            // Act
            formatter.ReadFromStreamAsync(typeof(int), new MemoryStream(), content, formatterLogger: null);

            // Assert
            deserializer.Verify();
        }

        public static TheoryDataSet<ODataPath, ODataPayloadKind> CanReadTypeTypesTestData
        {
            get
            {
                CustomersModelWithInheritance model = new CustomersModelWithInheritance();
                EntitySetPathSegment entitySetSegment = new EntitySetPathSegment(model.Customers);
                KeyValuePathSegment keyValueSegment = new KeyValuePathSegment("42");
                NavigationPathSegment navSegment = new NavigationPathSegment(model.Customer.FindProperty("Orders") as IEdmNavigationProperty);
                PropertyAccessPathSegment propertySegment = new PropertyAccessPathSegment(model.Customer.FindProperty("Address") as IEdmStructuralProperty);

                return new TheoryDataSet<ODataPath, ODataPayloadKind>
                {
                    { new ODataPath(entitySetSegment), ODataPayloadKind.Entry }, // POST ~/entityset
                    { new ODataPath(entitySetSegment, keyValueSegment), ODataPayloadKind.Entry }, // PUT ~/entityset(key)
                    { new ODataPath(entitySetSegment, keyValueSegment, navSegment), ODataPayloadKind.Entry }, // PUT ~/entityset(key)/nav
                    { new ODataPath(entitySetSegment, keyValueSegment, propertySegment), ODataPayloadKind.Property }
                };
            }
        }

        [Theory]
        [PropertyData("CanReadTypeTypesTestData")]
        public void CanReadType_ForTypeless_ReturnsExpectedResult_DependingOnODataPathAndPayloadKind(ODataPath path, ODataPayloadKind payloadKind)
        {
            // Arrange
            IEnumerable<ODataPayloadKind> allPayloadKinds = Enum.GetValues(typeof(ODataPayloadKind)).Cast<ODataPayloadKind>();
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);
            request.ODataProperties().Path = path;

            var formatterWithGivenPayload = new ODataMediaTypeFormatter(new[] { payloadKind }) { Request = request };
            var formatterWithoutGivenPayload = new ODataMediaTypeFormatter(allPayloadKinds.Except(new[] { payloadKind })) { Request = request };

            // Act & Assert
            Assert.True(formatterWithGivenPayload.CanReadType(typeof(IEdmObject)));
            Assert.False(formatterWithoutGivenPayload.CanReadType(typeof(IEdmObject)));
        }

        public static TheoryDataSet<ODataPayloadKind, Type> CanWriteType_ReturnsExpectedResult_ForEdmObjects_TestData
        {
            get
            {
                Type entityCollectionEdmObjectType = new Mock<IEdmObject>().As<IEnumerable<IEdmEntityObject>>().Object.GetType();
                Type complexCollectionEdmObjectType = new Mock<IEdmObject>().As<IEnumerable<IEdmComplexObject>>().Object.GetType();

                return new TheoryDataSet<ODataPayloadKind, Type>
                {
                    { ODataPayloadKind.Entry , typeof(IEdmEntityObject) },
                    { ODataPayloadKind.Entry , typeof(TypedEdmEntityObject) },
                    { ODataPayloadKind.Feed , entityCollectionEdmObjectType },
                    { ODataPayloadKind.Feed , typeof(IEnumerable<IEdmEntityObject>) },
                    { ODataPayloadKind.Property , typeof(IEdmComplexObject) },
                    { ODataPayloadKind.Property , typeof(TypedEdmComplexObject) },
                    { ODataPayloadKind.Collection , complexCollectionEdmObjectType },
                    { ODataPayloadKind.Collection , typeof(IEnumerable<IEdmComplexObject>) },
                    { ODataPayloadKind.Property, typeof(NullEdmComplexObject) }
                };
            }
        }

        [Theory]
        [PropertyData("CanWriteType_ReturnsExpectedResult_ForEdmObjects_TestData")]
        public void CanWriteType_ReturnsTrueForEdmObjects_WithRightPayload(ODataPayloadKind payloadKind, Type type)
        {
            // Arrange
            IEnumerable<ODataPayloadKind> allPayloadKinds = Enum.GetValues(typeof(ODataPayloadKind)).Cast<ODataPayloadKind>();
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);

            var formatterWithGivenPayload = new ODataMediaTypeFormatter(new[] { payloadKind }) { Request = request };
            var formatterWithoutGivenPayload = new ODataMediaTypeFormatter(allPayloadKinds.Except(new[] { payloadKind })) { Request = request };

            // Act & Assert
            Assert.True(formatterWithGivenPayload.CanWriteType(type));
            Assert.False(formatterWithoutGivenPayload.CanWriteType(type));
        }

        public static TheoryDataSet<Type> InvalidIEdmObjectImplementationTypes
        {
            get
            {
                return new TheoryDataSet<Type>
                {
                    typeof(IEdmObject),
                    typeof(TypedEdmStructuredObject),
                    new Mock<IEdmObject>().Object.GetType(),
                    new Mock<IEdmObject>().As<IEnumerable<IEdmObject>>().Object.GetType()
                };
            }
        }

        [Theory]
        [PropertyData("InvalidIEdmObjectImplementationTypes")]
        public void CanWriteType_ReturnsFalse_ForInvalidIEdmObjectImplementations_NoMatterThePayload(Type type)
        {
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);
            IEnumerable<ODataPayloadKind> allPayloadKinds = Enum.GetValues(typeof(ODataPayloadKind)).Cast<ODataPayloadKind>();
            var formatter = new ODataMediaTypeFormatter(allPayloadKinds);
            formatter.Request = request;

            var result = formatter.CanWriteType(type);

            Assert.False(result);
        }

        [Fact]
        public void WriteToStreamAsync_ThrowsSerializationException_IfEdmTypeIsNull()
        {
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);
            var formatter = new ODataMediaTypeFormatter(new ODataPayloadKind[0]);
            formatter.Request = request;

            Mock<IEdmObject> edmObject = new Mock<IEdmObject>();

            Assert.Throws<SerializationException>(
                () => formatter
                    .WriteToStreamAsync(typeof(int), edmObject.Object, new MemoryStream(), new Mock<HttpContent>().Object, transportContext: null)
                    .Wait(),
                "The EDM type of the object of type 'Castle.Proxies.IEdmObjectProxy' is null. The EDM type of an IEdmObject cannot be null.");
        }

        [Fact]
        public void WriteToStreamAsync_UsesTheRightEdmSerializer_ForEdmObjects()
        {
            // Arrange
            IEdmEntityTypeReference edmType = new EdmEntityTypeReference(new EdmEntityType("NS", "Name"), isNullable: false);
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);

            Mock<IEdmObject> instance = new Mock<IEdmObject>();
            instance.Setup(e => e.GetEdmType()).Returns(edmType);

            Mock<ODataEdmTypeSerializer> serializer = new Mock<ODataEdmTypeSerializer>(ODataPayloadKind.Entry);
            serializer
                .Setup(s => s.WriteObject(instance.Object, instance.GetType(), It.IsAny<ODataMessageWriter>(), It.IsAny<ODataSerializerContext>()))
                .Verifiable();

            Mock<ODataSerializerProvider> serializerProvider = new Mock<ODataSerializerProvider>();
            serializerProvider.Setup(s => s.GetEdmTypeSerializer(edmType)).Returns(serializer.Object);

            var formatter = new ODataMediaTypeFormatter(new DefaultODataDeserializerProvider(), serializerProvider.Object, new ODataPayloadKind[0]);
            formatter.Request = request;

            // Act
            formatter
                .WriteToStreamAsync(instance.GetType(), instance.Object, new MemoryStream(), new StreamContent(new MemoryStream()), transportContext: null)
                .Wait();

            // Assert
            serializer.Verify();
        }

        [Theory]
        [InlineData(typeof(SingleResult), false)]
        [InlineData(typeof(SingleResult<SampleType>), true)]
        [InlineData(typeof(SingleResult<TypeNotInModel>), false)]
        public void CanWriteType_ReturnsExpectedResult_ForSingleResult(Type type, bool expectedCanWriteTypeResult)
        {
            IEdmModel model = CreateModel();
            HttpRequestMessage request = CreateFakeODataRequest(model);
            ODataMediaTypeFormatter formatter = CreateFormatter(model, request, ODataPayloadKind.Entry);

            Assert.Equal(expectedCanWriteTypeResult, formatter.CanWriteType(type));
        }

        [Fact]
        public void WriteToStreamAsync_SetsMetadataUriWithSelectClause_OnODataWriterSettings()
        {
            // Arrange
            MemoryStream stream = new MemoryStream();
            StreamContent content = new StreamContent(stream);
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            IEdmModel model = CreateModel();
            IEdmSchemaType entityType = model.FindDeclaredType("System.Net.Http.Formatting.SampleType");
            IEdmStructuralProperty property =
                ((IEdmStructuredType)entityType).FindProperty("Number") as IEdmStructuralProperty;
            HttpRequestMessage request = CreateFakeODataRequest(model);
            request.RequestUri = new Uri("http://localhost/sampleTypes?$select=Number");
            request.ODataProperties().SelectExpandClause =
                new SelectExpandClause(
                    new Collection<SelectItem>
                        {
                            new PathSelectItem(new ODataSelectPath(new PropertySegment(property))),
                        },
                    allSelected: false);

            ODataMediaTypeFormatter formatter = CreateFormatter(model, request, ODataPayloadKind.Entry);

            // Act
            formatter.WriteToStreamAsync(typeof(SampleType[]), new SampleType[0], stream, content, transportContext: null);

            // Assert
            stream.Seek(0, SeekOrigin.Begin);
            string result = content.ReadAsStringAsync().Result;
            JObject obj = JObject.Parse(result);
            Assert.Equal("http://localhost/$metadata#sampleTypes(Number)", obj["@odata.context"]);
        }

        [Fact]
        public void ReadFromStreamAsync_UsesRightDeserializerFrom_ODataDeserializerProvider()
        {
            // Arrange
            MemoryStream stream = new MemoryStream();
            StringContent content = new StringContent("42");
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            IEdmModel model = CreateModel();
            HttpRequestMessage request = CreateFakeODataRequest(model);
            Mock<ODataDeserializer> deserializer = new Mock<ODataDeserializer>(ODataPayloadKind.Property);
            deserializer.Setup(d => d.Read(It.IsAny<ODataMessageReader>(), typeof(int), It.IsAny<ODataDeserializerContext>()))
                .Verifiable();

            Mock<ODataDeserializerProvider> provider = new Mock<ODataDeserializerProvider>();
            provider.Setup(p => p.GetODataDeserializer(model, typeof(int), request)).Returns(deserializer.Object);

            // Act
            ODataMediaTypeFormatter formatter = new ODataMediaTypeFormatter(provider.Object,
                new DefaultODataSerializerProvider(), Enumerable.Empty<ODataPayloadKind>());
            formatter.Request = request;

            formatter.ReadFromStreamAsync(typeof(int), stream, content, null);

            // Assert
            deserializer.Verify();
        }

        private static Encoding CreateEncoding(string name)
        {
            if (name == "utf-8")
            {
                return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
            }
            else if (name == "utf-16")
            {
                return new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true);
            }
            else
            {
                throw new ArgumentException("name");
            }
        }

        private static string CreateFormattedContent(string value)
        {
            return string.Format(CultureInfo.InvariantCulture,
                "{{\r\n  \"@odata.context\":\"http://dummy/$metadata#Edm.String\",\"value\":\"{0}\"\r\n}}", value);
        }

        protected override ODataMediaTypeFormatter CreateFormatter()
        {
            return CreateFormatterWithRequest();
        }

        protected override Mock<ODataMediaTypeFormatter> CreateMockFormatter()
        {
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);
            ODataPayloadKind[] payloadKinds = new ODataPayloadKind[] { ODataPayloadKind.Property };
            var formatter = new Mock<ODataMediaTypeFormatter>(payloadKinds) { CallBase = true };
            formatter.Object.Request = request;

            return formatter;
        }

        protected override MediaTypeHeaderValue CreateSupportedMediaType()
        {
            return MediaTypeHeaderValue.Parse("application/json;odata.metadata=full");
        }

        private static ODataMediaTypeFormatter CreateFormatter(IEdmModel model)
        {
            return new ODataMediaTypeFormatter(new ODataPayloadKind[0]);
        }

        private static ODataMediaTypeFormatter CreateFormatter(IEdmModel model, HttpRequestMessage request,
            params ODataPayloadKind[] payloadKinds)
        {
            return new ODataMediaTypeFormatter(payloadKinds) { Request = request };
        }

        private static ODataMediaTypeFormatter CreateFormatterWithoutRequest()
        {
            return CreateFormatter(CreateModel());
        }

        private static ODataMediaTypeFormatter CreateFormatterWithJson(IEdmModel model, HttpRequestMessage request,
            params ODataPayloadKind[] payloadKinds)
        {
            ODataMediaTypeFormatter formatter = CreateFormatter(model, request, payloadKinds);
            formatter.SupportedMediaTypes.Add(ODataMediaTypes.ApplicationJsonODataMinimalMetadata);
            return formatter;
        }

        private static ODataMediaTypeFormatter CreateFormatterWithRequest()
        {
            var model = CreateModel();
            var request = CreateFakeODataRequest(model);
            return CreateFormatter(model, request);
        }

        private static HttpRequestMessage CreateFakeODataRequest(IEdmModel model)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "http://dummy/");
            request.ODataProperties().Model = model;
            HttpConfiguration configuration = new HttpConfiguration();
            configuration.Routes.MapFakeODataRoute();
            request.SetConfiguration(configuration);
            request.ODataProperties().Path =
                new ODataPath(new EntitySetPathSegment(model.EntityContainer.EntitySets().Single()));
            request.SetFakeODataRouteName();
            return request;
        }

        private static IEdmModel CreateModel()
        {
            ODataConventionModelBuilder model = ODataModelBuilderMocks.GetModelBuilderMock<ODataConventionModelBuilder>();
            model.ModelAliasingEnabled = false;
            model.EntityType<SampleType>();
            model.EntitySet<SampleType>("sampleTypes");
            return model.GetEdmModel();
        }

        public override IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes
        {
            get
            {
                return new MediaTypeHeaderValue[0];
            }
        }

        public override IEnumerable<Encoding> ExpectedSupportedEncodings
        {
            get
            {
                return new Encoding[0];
            }
        }

        public override byte[] ExpectedSampleTypeByteRepresentation
        {
            get
            {
                return Encoding.UTF8.GetBytes(
                    "{" +
                        "\"@odata.context\":\"http://localhost/$metadata#sampleTypes/$entity\"," +
                        "\"@odata.type\":\"#System.Net.Http.Formatting.SampleType\"," +
                        "\"@odata.id\":\"http://localhost/sampleTypes(42)\"," +
                        "\"@odata.editLink\":\"http://localhost/sampleTypes(42)\"," +
                        "\"Number\":42" +
                     "}");
            }
        }

        private class TypeNotInModel
        {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Desmodium parvifolium var. macrocarpum Baker

### Remarks
null


text:
/*
 * Component.h
 *
 *  Created on: Feb 19, 2017
 *      Author: Brian Schnepp
 *      License: See 'LICENSE' in root of this repository.
 */

#ifndef COMPONENT_H_
#define COMPONENT_H_

#include <PathToolKit/event/Listener.h>
#include <PathToolKit/themes/Theme.h>
#include <cstdint>
#include <vector>

namespace PathDraw
{
class PaintableShape;
class LayoutManager;
class PfInstance;
class ShapeContainer;
} /* namespace Pathfinder */

namespace PathDraw
{
class PfGraphics;
class Frame;
class Component;

class Component
{
public:
	/** Creates a new component, with no parent. */
	Component();

	/** Creates a component with a parent component, in which this will terminate if the parent does. */
	Component(Component* parent);

	virtual ~Component();

	/**
	 * Gets the children of this component.
	 */
	const std::vector<Component> GetChildren();

	/** Adds a listener to this component, in which it will do something if something is done to the component. */
	void AssignListener(PathEvent::Listener* listener);

	/** Assigns a layout to this component. */
	void AssignLayout(LayoutManager* layout);

	/** Adds a component to this component, as a child. */
	void AddComponent(Component* component);

	/** Adds a component at a specific location as a child. */
	void AddComponent(Component* component, int index);

	/** Remove a component by reference. */
	void RemoveComponent(Component* component);

	/** Removes a component based on it's index. */
	void RemoveComponent(unsigned long long int id);

	/** Grabs a listener. */
	PathEvent::Listener* GetListener(int id);

	/** Grabs a pointer to a vector with all listeners in the component. */
	std::vector<PathEvent::Listener>* GetListeners();

	void RemoveListener(int id);
	void RemoveListener(PathEvent::Listener* listener);

	void OptimizeListeners();

	/** Re-draws all of the content of this component. Should flush before and after calling this. */
	void Repaint();

	/** Re-assigns the sizes of all the content in this component based on the top-level window. Should be called by LayoutManager after window event.*/
	void Refresh();

	/** Reassigns a PfInstance to this component. Note that by default, there is none. This should be called by the PfInstance, so don't worry about this. */
	virtual void AssignInstance(PfInstance* instance);

	Component* GetRootFrame();

	void SetGraphics(PfGraphics* gfx);

	void AddShape(PaintableShape* shape);

	void SetWidth(uint16_t width);
	void SetHeight(uint16_t height);

	void SetParent(Component* component);
	uint32_t GetParentWindow();
	void SetVisible(bool visibile);

	void Create();

	bool GetVisible();
	Component* GetParent();
	void AddChild(Component* component);

	uint16_t GetHeight();
	uint16_t GetWidth();

	uint16_t GetMinHeight();
	uint16_t GetMinWidth();

	uint16_t GetMaxHeight();
	uint16_t GetMaxWidth();

	PfInstance* GetInstance();

	uint32_t GetWindow();

	//Completely gets rid of this component, it's children, and their children recursively.
	void Destroy();

protected:
	virtual void OnGraphicsUpdate(PfGraphics* graphics);

	// TODO: We want to prefer using the heap over the stack as much as we can, so turn these all into pointers...
	// We're awful and manage memory ourselves for some reason, just because pointers are fun.
	/* This component's parent. When parent is killed, all of it's children are killed too. */
	Component* parent;

	uint16_t xpos;
	uint16_t ypos;

	uint16_t width;
	uint16_t height;

	uint16_t minimumwidth;
	uint16_t minimumheight;

	uint16_t maximumwidth;
	uint16_t maximumheight;

	bool visible;
	bool enabled;
	bool valid = false;

	Theme* theme;

	/* Counter for the most recent item. */
	unsigned long long int childrecentid = 0;
	std::vector<Component>* children;
	std::vector<PathEvent::Listener*>* listeners;

	ShapeContainer* container;
	LayoutManager* manager;

	PfInstance* instance;
	PfGraphics* graphics;
	uint32_t window;
};

} /* namespace Pathfinder */

#endif /* COMPONENT_H_ */


text:
package course;

import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;

import org.bson.Document;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Sorts.descending;

public class BlogPostDAO {

    private final MongoCollection<Document> postsCollection;

    public BlogPostDAO(final MongoDatabase blogDatabase) {
        postsCollection = blogDatabase.getCollection("posts");
    }

    public Document findByPermalink(String permalink) {
        Document post = postsCollection.find(eq("permalink", permalink)).first();

        // fix up if a post has no likes
        if (post != null) {
            List<Document> comments = (List<Document>) post.get("comments");
            for (Document comment : comments) {
                if (!comment.containsKey("num_likes")) {
                    comment.put("num_likes", 0);
                }
            }
        }
        return post;
    }

    public List<Document> findByDateDescending(int limit) {
        return postsCollection.find().sort(descending("date"))
                .limit(limit)
                .into(new ArrayList<Document>());
    }

    public List<Document> findByTagDateDescending(final String tag) {
        return postsCollection.find(eq("tags", tag))
                .sort(descending("date"))
                .limit(10)
                .into(new ArrayList<Document>());
    }

    public String addPost(String title, String body, List tags, String username) {
        String permalink = title.replaceAll("\\s", "_"); // whitespace becomes _
        permalink = permalink.replaceAll("\\W", ""); // get rid of non alphanumeric
        permalink = permalink.toLowerCase();

        Document post = new Document("title", title)
                .append("author", username)
                .append("body", body)
                .append("permalink", permalink)
                .append("tags", tags)
                .append("comments", new ArrayList())
                .append("date", new Date());

        postsCollection.insertOne(post);

        return permalink;
    }

    public void addPostComment(final String name, final String email, final String body, final String permalink) {
        Document comment = new Document("author", name)
                .append("body", body);

        if (email != null && !email.isEmpty()) {
            comment.append("email", email);
        }

        postsCollection.updateOne(eq("permalink", permalink),
                new Document("$push", new Document("comments", comment)));
    }

    public void likePost(final String permalink, final int ordinal) {
        //
        //
        // XXX Final Question 4 - work here
        // You must increment the number of likes on the comment in position `ordinal`
        // on the post identified by `permalink`.
        //
        //

        postsCollection.updateOne(eq("permalink", permalink),
                new Document("$inc",
                        new Document("comments." + String.valueOf(ordinal) + ".num_likes", 1)));
    }
}


text:
namespace p0
{
	namespace intermediate
	{
		function_ref::function_ref()
			: m_origin(nullptr)
			, m_function(nullptr)
		{
		}

		function_ref::function_ref(unit const &origin, intermediate::function const &function)
			: m_origin(&origin)
			, m_function(&function)
		{
		}

		unit const &function_ref::origin() const
		{
			assert(is_set());
			assert(m_origin);
			return *m_origin;
		}

		function const &function_ref::function() const
		{
			assert(is_set());
			assert(m_function);
			return *m_function;
		}

		bool function_ref::is_set() const
		{
			return (m_origin != nullptr);
		}

		unit const *function_ref::origin_ptr() const
		{
			return m_origin;
		}

		intermediate::function const *function_ref::function_ptr() const
		{
			return m_function;
		}

		std::pair<unit const *, function const *> to_pair(function_ref const &ref)
		{
			return std::make_pair(ref.origin_ptr(), ref.function_ptr());
		}

		bool operator == (function_ref const &left, function_ref const &right)
		{
			return to_pair(left) == to_pair(right);
		}

		bool operator < (function_ref const &left, function_ref const &right)
		{
			//make std::pair do the work
			return to_pair(left) < to_pair(right);
		}
	}
}

namespace std
{
	std::size_t hash<p0::intermediate::function_ref>::operator()(const p0::intermediate::function_ref &ref) const
	{
		auto const pair = to_pair(ref);
		//unfortunately, std::hash is not specialized for std::pair,
		//so we use boost here
		return boost::hash_value(pair);
	}
}