text:
/* Custom Stylesheet */
/**
 * Use this file to override Materialize files so you can update
 * the core Materialize files in the future
 *
 */

/* NGM MENU */
.ngm-menu {
	width: 280px;
	height: 100%;
	position:fixed;
	overflow: auto;
	left: 0px;
	top: 0px;
	transition: .30s ease-in-out;
}
.shrink{
transform: translateX(-230px);
transition: .30s ease-in-out;
background-color: #2196f3;
}
.ngm-search {
	height: 52px;
	line-height: 52px;
	display:none;
}
.ngm-search .nav-wrapper i {
	height: 52px;
	line-height: 52px;
}
.ngm-search .input-field input[type=search] {
	color: #616161;
	font-weight: 300;
	padding-top: 0px;
}
.ngm-logo {
	margin-top:-10px;
}
.ngm-profile {
	width:100%;
	height:52px;
	font-weight:500;
	padding-top:20px;
	padding-right:90px;
	text-align:right;
	text-transform:lowercase;
	pointer-events:none;
}
.ngm-profile-left{
	width:100%;
	height:52px;
	padding-top:20px;
	padding-left:15px;
	text-align:left;
	text-transform:lowercase;
	pointer-events:none;
}
.ngm-profile-btn {
	height: 68px;
	position:absolute;
	top:95px;
	z-index:9991;
}
.ngm-minimize-flat {
	height: 68px;
	position:absolute;
	top:95px;
	right: 0;
	z-index:9991;
	transition: .30s ease-in-out;
}
.change-position{
	right: 202px;
	transition: .30s ease-in-out;
}
.change-margin{
	margin: 0 50px !important;
}
.ngm-profile-btn-rightoff {
	height: 68px;
	position:absolute;
	top:95px;
	z-index:9991;
	visibility: visible;
}
.ngm-profile-btn-rightoff.direction-left{
	top:110px;
}
.ngm-minimize-flat.direction-left{
	top:110px;
}
.hide-position {
	visibility: hidden;
	transition: visibility 0.2s, ease-in-out;
}
.ngm-profile-icon {
	-moz-transition: all 0.2s linear;
	-webkit-transition: all 0.2s linear;
	transition: all 0.2s linear;
}
.ngm-profile-icon.rotate {
	-ms-transform:rotate(180deg);
	-moz-transform:rotate(180deg);
	-webkit-transform:rotate(180deg);
	transform:rotate(180deg);
}
#xmenu {
  width: 60px;
  height: 45px;
  position: relative;
  -webkit-transform: rotate(0deg);
  -moz-transform: rotate(0deg);
  -o-transform: rotate(0deg);
  transform: rotate(0deg);
  -webkit-transition: .5s ease-in-out;
  -moz-transition: .5s ease-in-out;
  -o-transition: .5s ease-in-out;
  transition: .5s ease-in-out;
  cursor: pointer;
}

 #xmenu span {
  display: block;
  position: absolute;
  height: 2px;
  width: 30%;
  background: #fff;
  left: 33%;
  -webkit-transform: rotate(0deg);
  -moz-transform: rotate(0deg);
  -o-transform: rotate(0deg);
  transform: rotate(0deg);
  -webkit-transition: .25s ease-in-out;
  -moz-transition: .25s ease-in-out;
  -o-transition: .25s ease-in-out;
  transition: .25s ease-in-out;
}

#xmenu span:nth-child(1) {
  top: 22px;
  -webkit-transform-origin: left center;
  -moz-transform-origin: left center;
  -o-transform-origin: left center;
  transform-origin: left center;
}

#xmenu span:nth-child(2) {
  top: 27px;
  -webkit-transform-origin: left center;
  -moz-transform-origin: left center;
  -o-transform-origin: left center;
  transform-origin: left center;
}

#xmenu span:nth-child(3) {
  top: 32px;
  -webkit-transform-origin: left center;
  -moz-transform-origin: left center;
  -o-transform-origin: left center;
  transform-origin: left center;
}

#xmenu.open span:nth-child(1) {
  -webkit-transform: rotate(45deg);
  -moz-transform: rotate(45deg);
  -o-transform: rotate(45deg);
  transform: rotate(45deg);
  top: 20px;
  left: 22px;
}

#xmenu.open span:nth-child(2) {
  width: 0%;
  opacity: 0;
}

#xmenu.open span:nth-child(3) {
  -webkit-transform: rotate(-45deg);
  -moz-transform: rotate(-45deg);
  -o-transform: rotate(-45deg);
  transform: rotate(-45deg);
  top: 33px;
  left: 22px;
}
.icon-arrow{
		transition: .30s ease-in-out;
}
.rotate-icon{
		transform:rotate(180deg);
		transition: .30s ease-in-out;
}
.sub-menu:hover{
	background-color: #eee;
}
/* menu icon size */
i.smedium {
  font-size: 3rem;
}
.ngm-profile-menu-content {
	display: none;
  width: 280px;
  position: absolute;
  top: 158.667px;
  left: 0px;
  opacity: 1;
  overflow: hidden;
}
.ngm-profile-menu-content li {
	/*padding-top: 15px;*/
	/*height: 100px;*/
	/*text-align: center;	*/
}
.collection .collection-item {
	font-weight: 300;
	/*border-bottom: none;*/
}
.collection a.collection-item:not(.active):hover {
	font-weight: 400;
}
.collection .collection-item.active {
	font-weight: 400;
  background-color: #b2dfdb;
}
.collapsible-header {
	font-weight: 400;
	font-size: 1.1rem;
	margin-top: 5px;
	border-bottom: none;
}
.collapsible-body{
	overflow: auto;
	max-height: 360px !important;
	padding: 0px !important;
}
.minim{
	padding-left: 0 !important ;
	transition: .15s ease-in-out;
}
/* .minim > .container{
	margin: 0 10%;
} */
.minim > .container > .expand.row{
	width: 105%;
}
.nav-wrapper > .input-field label.active{
	transform: translateY(13px) scale(1);
	transform-origin: 0 0;
}

/* mobile */
.sidenav li.mobile > a > i{
	color: #fff;
}

.sidenav li.mobile > a{
	width: 100%;
}

.mobile-btn{
	opacity: 1 !important;
	transform: scale(1) translateY(0px) translateX(0px) !important;
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using IVsDebugName = Microsoft.VisualStudio.TextManager.Interop.IVsDebugName;
using IVsEnumBSTR = Microsoft.VisualStudio.TextManager.Interop.IVsEnumBSTR;
using IVsTextBuffer = Microsoft.VisualStudio.TextManager.Interop.IVsTextBuffer;
using RESOLVENAMEFLAGS = Microsoft.VisualStudio.TextManager.Interop.RESOLVENAMEFLAGS;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
{
    internal abstract partial class AbstractLanguageService<TPackage, TLanguageService>
    {
        internal sealed class VsLanguageDebugInfo : IVsLanguageDebugInfo
        {
            private readonly Guid _languageId;
            private readonly TLanguageService _languageService;
            private readonly ILanguageDebugInfoService? _languageDebugInfo;
            private readonly IBreakpointResolutionService? _breakpointService;
            private readonly IProximityExpressionsService? _proximityExpressionsService;
            private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor;

            public VsLanguageDebugInfo(
                Guid languageId,
                TLanguageService languageService,
                HostLanguageServices languageServiceProvider,
                IUIThreadOperationExecutor uiThreadOperationExecutor)
            {
                Contract.ThrowIfNull(languageService);
                Contract.ThrowIfNull(languageServiceProvider);

                _languageId = languageId;
                _languageService = languageService;
                _languageDebugInfo = languageServiceProvider.GetService<ILanguageDebugInfoService>();
                _breakpointService = languageServiceProvider.GetService<IBreakpointResolutionService>();
                _proximityExpressionsService = languageServiceProvider.GetService<IProximityExpressionsService>();
                _uiThreadOperationExecutor = uiThreadOperationExecutor;
            }

            public int GetLanguageID(IVsTextBuffer pBuffer, int iLine, int iCol, out Guid pguidLanguageID)
            {
                pguidLanguageID = _languageId;
                return VSConstants.S_OK;
            }

            public int GetLocationOfName(string pszName, out string? pbstrMkDoc, out VsTextSpan pspanLocation)
            {
                pbstrMkDoc = null;
                pspanLocation = default;
                return VSConstants.E_NOTIMPL;
            }

            public int GetNameOfLocation(IVsTextBuffer pBuffer, int iLine, int iCol, out string? pbstrName, out int piLineOffset)
            {
                using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetNameOfLocation, CancellationToken.None))
                {
                    string? name = null;
                    var lineOffset = 0;

                    if (_languageDebugInfo != null)
                    {
                        _uiThreadOperationExecutor.Execute(
                            title: ServicesVSResources.Debugger,
                            defaultDescription: ServicesVSResources.Determining_breakpoint_location,
                            allowCancellation: true,
                            showProgress: false,
                            action: waitContext =>
                            {
                                var cancellationToken = waitContext.UserCancellationToken;
                                var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer);
                                if (textBuffer != null)
                                {
                                    var nullablePoint = textBuffer.CurrentSnapshot.TryGetPoint(iLine, iCol);
                                    if (nullablePoint.HasValue)
                                    {
                                        var point = nullablePoint.Value;
                                        var document = point.Snapshot.GetOpenDocumentInCurrentContextWithChanges();

                                        if (document != null)
                                        {
                                            // NOTE(cyrusn): We have to wait here because the debuggers'
                                            // GetNameOfLocation is a blocking call.  In the future, it
                                            // would be nice if they could make it async.
                                            var debugLocationInfo = _languageDebugInfo.GetLocationInfoAsync(document, point, cancellationToken).WaitAndGetResult(cancellationToken);

                                            if (!debugLocationInfo.IsDefault)
                                            {
                                                name = debugLocationInfo.Name;
                                                lineOffset = debugLocationInfo.LineOffset;
                                            }
                                        }
                                    }
                                }
                            });

                        if (name != null)
                        {
                            pbstrName = name;
                            piLineOffset = lineOffset;
                            return VSConstants.S_OK;
                        }
                    }

                    // Note(DustinCa): Docs say that GetNameOfLocation should return S_FALSE if a name could not be found.
                    // Also, that's what the old native code does, so we should do it here.
                    pbstrName = null;
                    piLineOffset = 0;
                    return VSConstants.S_FALSE;
                }
            }

            public int GetProximityExpressions(IVsTextBuffer pBuffer, int iLine, int iCol, int cLines, out IVsEnumBSTR? ppEnum)
            {
                // NOTE(cyrusn): cLines is ignored.  This is to match existing dev10 behavior.
                using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetProximityExpressions, CancellationToken.None))
                {
                    VsEnumBSTR? enumBSTR = null;

                    if (_proximityExpressionsService != null)
                    {
                        _uiThreadOperationExecutor.Execute(
                            title: ServicesVSResources.Debugger,
                            defaultDescription: ServicesVSResources.Determining_autos,
                            allowCancellation: true,
                            showProgress: false,
                            action: context =>
                        {
                            var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer);

                            if (textBuffer != null)
                            {
                                var snapshot = textBuffer.CurrentSnapshot;
                                var nullablePoint = snapshot.TryGetPoint(iLine, iCol);
                                if (nullablePoint.HasValue)
                                {
                                    var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
                                    if (document != null)
                                    {
                                        var point = nullablePoint.Value;
                                        var proximityExpressions = _proximityExpressionsService.GetProximityExpressionsAsync(document, point.Position, context.UserCancellationToken).WaitAndGetResult(context.UserCancellationToken);

                                        if (proximityExpressions != null)
                                        {
                                            enumBSTR = new VsEnumBSTR(proximityExpressions);
                                        }
                                    }
                                }
                            }
                        });
                    }

                    ppEnum = enumBSTR;
                    return ppEnum != null ? VSConstants.S_OK : VSConstants.E_FAIL;
                }
            }

            public int IsMappedLocation(IVsTextBuffer pBuffer, int iLine, int iCol)
                => VSConstants.E_NOTIMPL;

            public int ResolveName(string pszName, uint dwFlags, out IVsEnumDebugName? ppNames)
            {
                using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ResolveName, CancellationToken.None))
                {
                    // In VS, this method frequently get's called with an empty string to test if the language service
                    // supports this method (some language services, like F#, implement IVsLanguageDebugInfo but don't
                    // implement this method).  In that scenario, there's no sense doing work, so we'll just return
                    // S_FALSE (as the old VB language service did).
                    if (string.IsNullOrEmpty(pszName))
                    {
                        ppNames = null;
                        return VSConstants.S_FALSE;
                    }

                    VsEnumDebugName? enumName = null;
                    _uiThreadOperationExecutor.Execute(
                        title: ServicesVSResources.Debugger,
                        defaultDescription: ServicesVSResources.Resolving_breakpoint_location,
                        allowCancellation: true,
                        showProgress: false,
                        action: waitContext =>
                    {
                        var cancellationToken = waitContext.UserCancellationToken;
                        if (dwFlags == (uint)RESOLVENAMEFLAGS.RNF_BREAKPOINT)
                        {
                            var solution = _languageService.Workspace.CurrentSolution;

                            // NOTE(cyrusn): We have to wait here because the debuggers' ResolveName
                            // call is synchronous.  In the future it would be nice to make it async.
                            if (_breakpointService != null)
                            {
                                var breakpoints = _breakpointService.ResolveBreakpointsAsync(solution, pszName, cancellationToken).WaitAndGetResult(cancellationToken);
                                var debugNames = breakpoints.Select(bp => CreateDebugName(bp, solution, cancellationToken)).WhereNotNull().ToList();

                                enumName = new VsEnumDebugName(debugNames);
                            }
                        }
                    });

                    ppNames = enumName;
                    return ppNames != null ? VSConstants.S_OK : VSConstants.E_NOTIMPL;
                }
            }

            private IVsDebugName CreateDebugName(BreakpointResolutionResult breakpoint, Solution solution, CancellationToken cancellationToken)
            {
                var document = breakpoint.Document;
                var filePath = _languageService.Workspace.GetFilePath(document.Id);
                var text = document.GetTextSynchronously(cancellationToken);
                var span = text.GetVsTextSpanForSpan(breakpoint.TextSpan);
                // If we're inside an Venus code nugget, we need to map the span to the surface buffer.
                // Otherwise, we'll just use the original span.
                if (!span.TryMapSpanFromSecondaryBufferToPrimaryBuffer(solution.Workspace, document.Id, out var mappedSpan))
                {
                    mappedSpan = span;
                }

                return new VsDebugName(breakpoint.LocationNameOpt, filePath, mappedSpan);
            }

            public int ValidateBreakpointLocation(IVsTextBuffer pBuffer, int iLine, int iCol, VsTextSpan[] pCodeSpan)
            {
                using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation, CancellationToken.None))
                {
                    var result = VSConstants.E_NOTIMPL;
                    _uiThreadOperationExecutor.Execute(
                        title: ServicesVSResources.Debugger,
                        defaultDescription: ServicesVSResources.Validating_breakpoint_location,
                        allowCancellation: true,
                        showProgress: false,
                        action: waitContext =>
                    {
                        result = ValidateBreakpointLocationWorker(pBuffer, iLine, iCol, pCodeSpan, waitContext.UserCancellationToken);
                    });

                    return result;
                }
            }

            private int ValidateBreakpointLocationWorker(
                IVsTextBuffer pBuffer,
                int iLine,
                int iCol,
                VsTextSpan[] pCodeSpan,
                CancellationToken cancellationToken)
            {
                if (_breakpointService == null)
                {
                    return VSConstants.E_FAIL;
                }

                var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer);
                if (textBuffer != null)
                {
                    var snapshot = textBuffer.CurrentSnapshot;
                    var nullablePoint = snapshot.TryGetPoint(iLine, iCol);
                    if (nullablePoint == null)
                    {
                        // The point disappeared between sessions. Do not allow a breakpoint here.
                        return VSConstants.E_FAIL;
                    }

                    var document = snapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken);
                    if (document != null)
                    {
                        var point = nullablePoint.Value;
                        var length = 0;
                        if (pCodeSpan != null && pCodeSpan.Length > 0)
                        {
                            // If we have a non-empty span then it means that the debugger is asking us to adjust an
                            // existing span.  In Everett we didn't do this so we had some good and some bad
                            // behavior.  For example if you had a breakpoint on: "int i = 1;" and you changed it to "int
                            // i = 1, j = 2;", then the breakpoint wouldn't adjust.  That was bad.  However, if you had the
                            // breakpoint on an open or close curly brace then it would always "stick" to that brace
                            // which was good.
                            //
                            // So we want to keep the best parts of both systems.  We want to appropriately "stick"
                            // to tokens and we also want to adjust spans intelligently.
                            //
                            // However, it turns out the latter is hard to do when there are parse errors in the
                            // code.  Things like missing name nodes cause a lot of havoc and make it difficult to
                            // track a closing curly brace.
                            //
                            // So the way we do this is that we default to not intelligently adjusting the spans
                            // while there are parse errors.  But when there are no parse errors then the span is
                            // adjusted.
                            var initialBreakpointSpan = snapshot.GetSpan(pCodeSpan[0]);
                            if (initialBreakpointSpan.Length > 0 && document.SupportsSyntaxTree)
                            {
                                var tree = document.GetSyntaxTreeSynchronously(cancellationToken);
                                Contract.ThrowIfNull(tree);
                                if (tree.GetDiagnostics(cancellationToken).Any(d => d.Severity == DiagnosticSeverity.Error))
                                {
                                    // Keep the span as is.
                                    return VSConstants.S_OK;
                                }
                            }

                            // If a span is provided, and the requested position falls in that span, then just
                            // move the requested position to the start of the span.
                            // Length will be used to determine if we need further analysis, which is only required when text spans multiple lines.
                            if (initialBreakpointSpan.Contains(point))
                            {
                                point = initialBreakpointSpan.Start;
                                length = pCodeSpan[0].iEndLine > pCodeSpan[0].iStartLine ? initialBreakpointSpan.Length : 0;
                            }
                        }

                        // NOTE(cyrusn): we need to wait here because ValidateBreakpointLocation is
                        // synchronous.  In the future, it would be nice for the debugger to provide
                        // an async entry point for this.
                        var breakpoint = _breakpointService.ResolveBreakpointAsync(document, new TextSpan(point.Position, length), cancellationToken).WaitAndGetResult(cancellationToken);
                        if (breakpoint == null)
                        {
                            // There should *not* be a breakpoint here.  E_FAIL to let the debugger know
                            // that.
                            return VSConstants.E_FAIL;
                        }

                        if (breakpoint.IsLineBreakpoint)
                        {
                            // Let the debugger take care of this. They'll put a line breakpoint
                            // here. This is useful for when the user does something like put a
                            // breakpoint in inactive code.  We want to allow this as they might
                            // just have different defines during editing versus debugging.

                            // TODO(cyrusn): Do we need to set the pCodeSpan in this case?
                            return VSConstants.E_NOTIMPL;
                        }

                        // There should be a breakpoint at the location passed back.
                        if (pCodeSpan != null && pCodeSpan.Length > 0)
                        {
                            pCodeSpan[0] = breakpoint.TextSpan.ToSnapshotSpan(snapshot).ToVsTextSpan();
                        }

                        return VSConstants.S_OK;
                    }
                }

                return VSConstants.E_NOTIMPL;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace http2 {
namespace test {

// HpackStringDecoder methods require a listener that implements the methods
// below, but it is NOT necessary to extend this class because the methods
// are templates.
class QUICHE_EXPORT_PRIVATE HpackStringDecoderListener {
 public:
  virtual ~HpackStringDecoderListener() {}

  // Called at the start of decoding an HPACK string. The encoded length of the
  // string is |len| bytes, which may be zero. The string is Huffman encoded
  // if huffman_encoded is true, else it is plain text (i.e. the encoded length
  // is then the plain text length).
  virtual void OnStringStart(bool huffman_encoded, size_t len) = 0;

  // Called when some data is available, or once when the string length is zero
  // (to simplify the decoder, it doesn't have a special case for len==0).
  virtual void OnStringData(const char* data, size_t len) = 0;

  // Called after OnStringData has provided all of the encoded bytes of the
  // string.
  virtual void OnStringEnd() = 0;
};

class QUICHE_EXPORT_PRIVATE HpackStringDecoderVLoggingListener
    : public HpackStringDecoderListener {
 public:
  HpackStringDecoderVLoggingListener() : wrapped_(nullptr) {}
  explicit HpackStringDecoderVLoggingListener(
      HpackStringDecoderListener* wrapped)
      : wrapped_(wrapped) {}
  ~HpackStringDecoderVLoggingListener() override {}

  void OnStringStart(bool huffman_encoded, size_t len) override;
  void OnStringData(const char* data, size_t len) override;
  void OnStringEnd() override;

 private:
  HpackStringDecoderListener* const wrapped_;
};

}  // namespace test
}  // namespace http2

#endif  // QUICHE_HTTP2_HPACK_DECODER_HPACK_STRING_DECODER_LISTENER_H_


text:
<?php

namespace Muffin\Webservice\Test\test_app\Webservice;

use Muffin\Webservice\Model\Resource;
use Muffin\Webservice\Pagination;
use Muffin\Webservice\Query;
use Muffin\Webservice\ResultSet;
use Muffin\Webservice\Schema;
use Muffin\Webservice\Webservice\WebserviceInterface;

class StaticWebservice implements WebserviceInterface
{

    public function execute(Query $query, array $options = [])
    {
        return new ResultSet([
            new Resource([
                'id' => 1,
                'title' => 'Hello World'
            ]),
            new Resource([
                'id' => 2,
                'title' => 'New ORM'
            ]),
            new Resource([
                'id' => 3,
                'title' => 'Webservices'
            ])
        ], new Pagination(['count' => 3]));
    }

    public function describe($endpoint)
    {
        return new Schema($endpoint, [
           'id' => [
               'type' => 'integer'
           ],
            'title' => [
                'type' => 'string'
            ]
        ]);
    }
}


text:
package org.apache.wicket.core.request.mapper;

import org.apache.wicket.Application;
import org.apache.wicket.RequestListenerInterface;
import org.apache.wicket.core.util.lang.WicketObjects;
import org.apache.wicket.request.IRequestMapper;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.Url.QueryParameter;
import org.apache.wicket.request.component.IRequestablePage;
import org.apache.wicket.request.mapper.AbstractMapper;
import org.apache.wicket.request.mapper.info.PageComponentInfo;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.string.Strings;

/**
 * Convenience class for implementing page/components related encoders.
 *
 * @author Matej Knopp
 */
public abstract class AbstractComponentMapper extends AbstractMapper implements IRequestMapper
{
	/**
	 * Construct.
	 */
	public AbstractComponentMapper()
	{
	}

	protected IMapperContext getContext()
	{
		return Application.get().getMapperContext();
	}

	/**
	 * Converts the specified listener interface to String.
	 *
	 * @param listenerInterface
	 * @return listenerInterface name as string
	 */
	protected String requestListenerInterfaceToString(RequestListenerInterface listenerInterface)
	{
		Args.notNull(listenerInterface, "listenerInterface");

		return getContext().requestListenerInterfaceToString(listenerInterface);
	}

	/**
	 * Creates listener interface from the specified string
	 *
	 * @param interfaceName
	 * @return listener interface
	 */
	protected RequestListenerInterface requestListenerInterfaceFromString(String interfaceName)
	{
		Args.notEmpty(interfaceName, "interfaceName");

		return getContext().requestListenerInterfaceFromString(interfaceName);
	}

	/**
	 * Extracts the {@link PageComponentInfo} from the URL. The {@link PageComponentInfo} is encoded
	 * as the very first query parameter and the parameter consists of name only (no value).
	 *
	 * @param url
	 *
	 * @return PageComponentInfo instance if one was encoded in URL, null otherwise.
	 */
	protected PageComponentInfo getPageComponentInfo(final Url url)
	{
		return MapperUtils.getPageComponentInfo(url);
	}

	/**
	 * Encodes the {@link PageComponentInfo} instance as the first query string parameter to the
	 * URL.
	 *
	 * @param url
	 * @param info
	 */
	protected void encodePageComponentInfo(Url url, PageComponentInfo info)
	{
		Args.notNull(url, "url");

		if (info != null)
		{
			String s = info.toString();
			if (!Strings.isEmpty(s))
			{
				QueryParameter parameter = new QueryParameter(s, "");
				url.getQueryParameters().add(parameter);
			}
		}
	}

	/**
	 * Loads page class with given name.
	 *
	 * @param name
	 * @return class
	 */
	protected Class<? extends IRequestablePage> getPageClass(String name)
	{
		String cleanedClassName = cleanClassName(name);
		return WicketObjects.resolveClass(cleanedClassName);
	}

	/**
	 * Cleans the class name from any extra information that may be there.
	 *
	 * @param className
	 *              The raw class name parsed from the url
	 * @return The cleaned class name
	 */
	protected String cleanClassName(String className)
	{
		Args.notEmpty(className, "className");

		if (Strings.indexOf(className, ';') > -1)
		{
			// remove any path parameters set manually by the user. WICKET-5500
			className = Strings.beforeFirst(className, ';');
		}

		return className;
	}

	/**
	 * {@inheritDoc}
	 *
	 * Removes the first query parameter only if {@link PageComponentInfo#parse(String)} returns
	 * non-null instance
	 */
	@Override
	protected void removeMetaParameter(final Url urlCopy)
	{
		if (MapperUtils.parsePageComponentInfoParameter(urlCopy.getQueryParameters().get(0)) != null)
		{
			urlCopy.getQueryParameters().remove(0);
		}
	}

}


text:
package org.yagel.monitor.utils;

import org.apache.commons.lang3.time.DateUtils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DataUtils {

  /**
   * @param date
   * @return aggregated year and month values of given date field. Month is counted from 0
   * <p/>
   * For example:
   * If date is 2015-02-03 then return value will be 201501
   */
  public static int joinYearMonthValues(Date date) {
    Calendar calendar = DateUtils.toCalendar(date);
    return joinYearMonthValues(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH));
  }

  public static int joinYearMonthValues(int year, int month) {
    return year * 100 + month;
  }

  public static Date getYesterday(Date currentDate) {
    return DateUtils.addDays(currentDate, -1);
  }

  public static boolean isToday(LocalDateTime localDateTime) {
    return localDateTime.getDayOfYear() == LocalDateTime.now().getDayOfYear();
  }

  public static Date asDate(LocalDate localDate) {
    return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
  }

  public static Date asDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
  }

  public static LocalDate asLocalDate(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
  }

  public static LocalDateTime asLocalDateTime(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
  }

  public static List<Integer> getMonthNumbersInDateFrame(Date startDate, Date endDate) {
    List<Integer> dates = new ArrayList<>();

    LocalDateTime start = asLocalDateTime(startDate);
    LocalDateTime end = asLocalDateTime(endDate);

    while (start.isBefore(end) || start.equals(end)) {
      dates.add(start.getMonthValue());
      start = start.plusMonths(1);
    }
    return dates;

  }

  public static List<Date[]> splitDatesIntoMonths(Date from, Date to) throws IllegalArgumentException {

    List<Date[]> dates = new ArrayList<>();

    LocalDateTime dFrom = asLocalDateTime(from);
    LocalDateTime dTo = asLocalDateTime(to);

    if (dFrom.compareTo(dTo) >= 0) {
      throw new IllegalArgumentException("Provide a to-date greater than the from-date");
    }

    while (dFrom.compareTo(dTo) < 0) {
      // check if current time frame is last
      boolean isLastTimeFrame = dFrom.getMonthValue() == dTo.getMonthValue() && dFrom.getYear() == dTo.getYear();

      // define day of month based on timeframe. if last - take boundaries from end date, else end of month and date
      int dayOfMonth = isLastTimeFrame ? dTo.getDayOfMonth() : dFrom.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
      LocalTime time = isLastTimeFrame ? dTo.toLocalTime() : LocalTime.MAX;

      // build timeframe
      Date[] dar = new Date[2];
      dar[0] = asDate(dFrom);
      dar[1] = asDate(dFrom.withDayOfMonth(dayOfMonth).toLocalDate().atTime(time));

      // add current timeframe
      dates.add(dar);

      // jump to beginning of next month
      dFrom = dFrom.plusMonths(1).withDayOfMonth(1).toLocalDate().atStartOfDay();
    }

    return dates;

  }

}


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>5. Testing — RESThub 1.1.3 documentation</title>

    <link rel="stylesheet" href="static/resthub.css" type="text/css" />
    <link rel="stylesheet" href="static/pygments.css" type="text/css" />

    <link rel="top" title="RESThub 1.1.3 documentation" href="index.html" />
    <link rel="next" title="6. OAuth2 based AuthN/AuthZ" href="oauth2.html" />
    <link rel="prev" title="4. Web functionalities" href="web.html" />

Navigation

          index

          next |

          previous |

RESThub 1.1.3 documentation »

5. Testing¶

5.1. Base class for your tests¶

RESThub provides generic classes in order to make testing easier.

Generic test classes :

AbstractTest: base class for your non transactional Spring aware unit tests

AbstractTransactionalTest : base class for your transactional unit tests, preconfigure Spring test framework

AbstractTransactionAwareTest: base class for your transaction aware unit tests

AbstractWebTest : base class for your unit test that need to run and embedded servlet container

CRUD testing of generic DAO, Service or Controller class

AbstractDaoTest: generic DAO unit test

AbstractServiceTest: generic service unit test

AbstractControllerTest: generic controller unit test (direct java testing)

AbstractControllerWebTest: generic controller unit test (via a webapplication running in Jetty embedded)

5.2. Serialization¶

RESThub includes a SerializationHelper class that could be used to test Serialialization and Deserialization of your model classes. For example :

public class WebSampleResourceSerializationTest {
   @Test
   public void testWebSampleResourceJsonSerialization() {
      WebSampleResource resource = new WebSampleResource("testResource");
      String output = SerializationHelper.jsonSerialize(resource);
      Assert.assertTrue(output.contains("testResource"));
   }

   @Test
   public void testWebSampleResourceXmlSerialization() {
      WebSampleResource resource = new WebSampleResource("testResource");
      String output = SerializationHelper.xmlSerialize(resource);
      Assert.assertTrue(output.contains("testResource"));
   }
}

5.3. DBUnit integration¶

5.3.1. Introduction¶

When designing unit tests with a database, you need to manage the state of the database in order to have repeatable tests.

Through RESThub, we offer a simple way to deal with these concerns. But first, let’s just make some clarifications.

5.3.1.1. Why an embedded database is not enough¶

The first step is to use an embedded memory database. Thus, the database is created each time you launch your test suite and you are sure that no existing data can corrupt your tests results. But as your tests are executed, they can alter the state of the database. Any test method changing the database state can break subsequents tests.

At this point, you may think : “Just enclose your test in a transaction and rollback it after the test”. Proceeding this way, you are sure to preserve the database state. But you will also miss all errors that are discovered at commit or flush time. Indeed, JPA providers like Hibernate can cache the SQL instructions they are supposed to send to the database, often until you actually commit the transaction.

You definitively need a way to restore the database state before each test. That’s exactly what DBUnit is made for.

5.3.2. Integrating DBUnit and Spring Test¶

5.3.2.1. Configuration¶

Using plain Spring beans

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

   <bean id="dbunitConfiguration" class="org.resthub.test.dbunit.config.DbUnitConfiguration">
      <property name="databaseConnection" ref="databaseConnection"/>
      <property name="databaseTester" ref="databaseTester"/>
   </bean>

   <bean id="databaseConnection" class="org.resthub.test.dbunit.config.DatabaseConnectionFactory">
      <property name="dataSource" ref="dataSource"/>
   </bean>

   <bean id="databaseTester" class="org.dbunit.DefaultDatabaseTester">
      <constructor-arg ref="databaseConnection"/>
   </bean>

</beans>

Note : databaseTester bean is not mandatory, it is just a helper that you can use in your test to check the database state.

Using the dbunit namespace

The dbunit namespace avoid complicated DBUnit configuration. The configuration below is equivalent to the one just above:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:dbunit="http://www.resthub.org/schema/dbunit"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.resthub.org/schema/dbunit
      http://www.resthub.org/schema/dbunit/resthub-dbunit-1.1.xsd">

   <dbunit:configuration data-source="dataSource"/>

</beans>

That’s it : DBUnit is configured and ready to use in your unit tests.

Including/Excluding tables

Sometimes, you may need to exclude some tables.
Tables inclusion/exclusion is available through the namespace configuration :

<dbunit:configuration data-source="dataSource">
   <dbunit:include-table>user_*</dbunit:include-table>
   <dbunit:include-table>roles</dbunit:include-table>
   <dbunit:exclude-table>quartz_*</dbunit:exclude-table>
<dbunit:configuration/>

You can use the full table name or wildcards : * for any number of characters or ? for just one character.

5.3.2.2. Writing the test case¶

Here is a simple test case:

@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
@TransactionConfiguration(defaultRollback = false)
@InjectDataSet("dataset")
@RunWith(DbUnitSpringJUnit4ClassRunner.class)
public class DBUnitTestCase {

   @Test
   public void testXXX() throws Exception {
      // TODO test something
   }

   @Test
   public void testSomethingThatChangeTheDatabaseState() throws Exception {
      // TODO test something that change the database state
   }

   @Test
   @InjectDataSet("dataset")
   public void testYYY() throws Exception {
      // Another test
   }
}

The main points to remember are :

The test case must use the DbUnitTestExecutionListener in order to activate DBUnit support.

The test class is annotated with @InjectDataSet. Thanks to this annotation, the dataSet named ‘dataset’ is injected one time before the test class.

Because the second test method changes the database state, we choose to inject the dataSet again on the last method.

You can also combine serveral datasets together:

@InjectDataSet({"dataset1", "dataset2"})

5.3.2.3. Writing datasets¶

There are 3 options to create a dataset :

Using a DBUnit flat XML file

Using SQL scripts

Using a custom Spring bean

Lets explore these options.

DBUnit flat XML file

DBUnit has its own XML dataSet file format. You can find more information about this format in DBUnit documentation.

You can declare an XML dataSet using a plain Spring bean declaration :

<bean id="dataset" class="org.resthub.test.dbunit.initializer.FlatXMLDatabaseInitializer">
   <property name="location" value="classpath:datasets/dataset.xml"/>
</bean>

The location attribute use Spring resource syntax.

If you use the namespace, the following configuration is equivalent:

<dbunit:flatxml-dataset id="dataset" location="classpath:datasets/dataset.xml"/>

Custom Spring bean

The custom Spring bean is the most powerful solution. You can initialize the database with any Java code, including JPA , and let the framework create the dataSet by taking a snapshot of the database after your code has been executed.

Here is a simple DatabaseInitializer implementation:

@Named("sampleDataset")
public class SampleDatabaseInitializer implements DatabaseInitializer {

   public static final String ENTITY_REF = "ref";
   public static final String ENTITY_DESCRIPTION = "entity description";

   @PersistenceContext
   private EntityManager entityManager;

   @Override
   @Transactional
   public void initDatabase() throws Exception {
      SampleEntity entity = new SampleEntity();
      entity.setRef(ENTITY_REF);
      entity.setDescription(ENTITY_DESCRIPTION);
      entityManager.persist(entity);
   }
}

Again, the bean name must match the expected dataset name. In this case, the dataset can be referenced by the name “sampleDataset”.

5.3.2.4. Best practices¶

Consider declaring DBUnit and Spring Test annotations on an abstract parent class, and make all your tests inherit from this parent.

Use constants when initializing you dataset with Java code, and reference these constants in your unit tests. Doing so, you will improve the maintenability of your tests.

Table Of Contents

5. Testing

5.1. Base class for your tests

5.2. Serialization

5.3. DBUnit integration

5.3.1. Introduction

5.3.1.1. Why an embedded database is not enough

5.3.2. Integrating DBUnit and Spring Test

5.3.2.1. Configuration

5.3.2.2. Writing the test case

5.3.2.3. Writing datasets

5.3.2.4. Best practices

Related Topics

Documentation overview

Previous: 4. Web functionalities

Next: 6. OAuth2 based AuthN/AuthZ

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

      © Copyright 2011, pullrequest.org.
      Created using Sphinx.


text:
namespace pfc {
	bit_array_var_impl::bit_array_var_impl( const bit_array & source, size_t sourceCount) {
		for(size_t w = source.find_first( true, 0, sourceCount); w < sourceCount; w = source.find_next( true, w, sourceCount ) ) {
			set(w, true);
		}
	}

	bool bit_array_var_impl::get(t_size n) const {
		return m_data.have_item(n);
	}
	t_size bit_array_var_impl::find(bool val,t_size start,t_ssize count) const {
		if (!val) {
			return bit_array::find(false, start, count); //optimizeme.
		} else if (count > 0) {
			const t_size * v = m_data.find_nearest_item<true, true>(start);
			if (v == NULL || *v > start+count) return start + count;
			return *v;
		} else if (count < 0) {
			const t_size * v = m_data.find_nearest_item<true, false>(start);
			if (v == NULL || *v < start+count) return start + count;
			return *v;
		} else return start;
	}

	void bit_array_var_impl::set(t_size n,bool val) {
		if (val) m_data += n;
		else m_data -= n;
	}

	bit_array_flatIndexList::bit_array_flatIndexList() {
		m_content.prealloc( 1024 );
	}

	void bit_array_flatIndexList::add( size_t n ) {
		m_content.append_single_val( n );
	}

	bool bit_array_flatIndexList::get(t_size n) const {
		size_t dummy;
		return _find( n, dummy );
	}
	t_size bit_array_flatIndexList::find(bool val,t_size start,t_ssize count) const {
		if (val == false) {
			// unoptimized but not really used
			return bit_array::find(val, start, count);
		}

		if (count==0) return start;
		else if (count<0) {
			size_t idx;
			if (!_findNearestDown( start, idx ) || m_content[idx] < start+count) return start + count;
			return m_content[idx];
		} else { // count > 0
			size_t idx;
			if (!_findNearestUp( start, idx ) || m_content[idx] > start+count) return start + count;
			return m_content[idx];
		}
	}

	bool bit_array_flatIndexList::_findNearestUp( size_t val, size_t & outIdx ) const {
		size_t idx;
		if (_find( val, idx )) { outIdx = idx; return true; }
		// we have a valid outIdx at where the bsearch gave up
		PFC_ASSERT ( idx == 0 || m_content [ idx - 1 ] < val );
		PFC_ASSERT ( idx == m_content.get_size() || m_content[ idx ] > val );
		if (idx == m_content.get_size()) return false;
		outIdx = idx;
		return true;
	}
	bool bit_array_flatIndexList::_findNearestDown( size_t val, size_t & outIdx ) const {
		size_t idx;
		if (_find( val, idx )) { outIdx = idx; return true; }
		// we have a valid outIdx at where the bsearch gave up
		PFC_ASSERT ( idx == 0 || m_content [ idx - 1 ] < val );
		PFC_ASSERT ( idx == m_content.get_size() || m_content[ idx ] > val );
		if (idx == 0) return false;
		outIdx = idx - 1;
		return true;
	}

	void bit_array_flatIndexList::presort() {
		pfc::sort_t( m_content, pfc::compare_t< size_t, size_t >, m_content.get_size( ) );
	}

}