text:
#ifndef WINBITMAP_H
#define WINBITMAP_H

#include "MapPlotter.h"
#include "PixelBox.h"

namespace isab {

/* header for a TGA (TARGA) File */
typedef struct
{
   uint8 numCharsID;
   uint8 colorMapType;
   uint8 imageType;
   uint8 colorMapSpec[5];
   uint16 xOrig;
   uint16 yOrig;
   uint16 imageWidth;
   uint16 imageHeight;
   uint8 bitsPerPixel;
   uint8 imageDesc;
} TGAHEADER;

typedef struct
{
   uint8 red;
   uint8 green;
   uint8 blue;
} PIXEL;

class WinBitmap : public BitMap
{
   /** data **/
   private:
      /* the bitmap */
      HBITMAP m_bmp;
      /* the mask */
      HBITMAP m_mask;

      /* the old bitmap from the DC */
      HBITMAP m_oldBmp;

      /* it's DC */
      HDC m_dc;

      /* dimensions of bitmap */
      int32 m_width, m_height;

      /* flag which indicates whether the BMP is maked or not */
      bool m_isMasked;

      /// The color map.
      std::vector<PIXEL> m_colorMap;

      PixelBox m_visibleRect;

   /** methods **/
   private:
      /* private constructor */
      WinBitmap();

      /* second-phase constructor */
      bool construct(const byte* dataBuf, uint32 nbrBytes, int dpiCorrectionFactor);

      /**
       *    Help method.
       *    Reads the color map data if any is present.
       *    @param   tgaHeader   The tga header.
       *    @param   colorData   Pointer to the color map data.
       *    @return  How much colormap data that has been read, i.e.
       *             how much the colorData should be increased in order
       *             to point at the color data instead of at the color
       *             map.
       */
      int readColorMapData( const TGAHEADER& tgaHeader,
                            const byte* colorData );

       /* Calculates the visible rectangle for the image */
      PixelBox calculateVisibleRect(HDC dc, int nWidth, int nHeight);

   public:
      /* allocator */
      static WinBitmap* allocate(const byte* dataBuf, uint32 nbrBytes, int dpiCorrectionFactor);

      /* destructor */
      ~WinBitmap();

      /* gets width of bitmap */
      int32 width() const
      {
         return(m_width);
      }

      /* gets height of bitmap */
      int32 height() const
      {
         return(m_height);
      }

      /* gets the handle to the DC */
      HDC getDC() const
      {
         return(m_dc);
      }

      /* gets the mask bitmap */
      HBITMAP getMask() const
      {
         return(m_mask);
      }

      HBITMAP getHandle() const
      {
         return m_bmp;
      }

      /* returns true, if the image is masked, false otherwise */
      bool isMasked() const
      {
         return(m_isMasked);
      }

      /* gets the visible rect of the bitmap */
      PixelBox GetVisibleRect() const;
};

};

#endif


text:
package com.android.server.print;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Process;
import android.os.RemoteException;
import android.os.UserHandle;
import android.print.IPrintDocumentAdapter;
import android.print.IPrintJobStateChangeListener;
import android.print.IPrintManager;
import android.print.IPrinterDiscoveryObserver;
import android.print.PrintAttributes;
import android.print.PrintJobId;
import android.print.PrintJobInfo;
import android.print.PrinterId;
import android.printservice.PrintServiceInfo;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.SparseArray;

import com.android.internal.R;
import com.android.internal.content.PackageMonitor;
import com.android.internal.os.BackgroundThread;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public final class PrintManagerService extends IPrintManager.Stub {

    private static final char COMPONENT_NAME_SEPARATOR = ':';

    private static final String EXTRA_PRINT_SERVICE_COMPONENT_NAME =
            "EXTRA_PRINT_SERVICE_COMPONENT_NAME";

    private final Object mLock = new Object();

    private final Context mContext;

    private final SparseArray<UserState> mUserStates = new SparseArray<UserState>();

    private int mCurrentUserId = UserHandle.USER_OWNER;

    public PrintManagerService(Context context) {
        mContext = context;
        registerContentObservers();
        registerBoradcastReceivers();
    }

    public void systemRuning() {
        BackgroundThread.getHandler().post(new Runnable() {
            @Override
            public void run() {
                final UserState userState;
                synchronized (mLock) {
                    userState = getCurrentUserStateLocked();
                    userState.updateIfNeededLocked();
                }
                // This is the first time we switch to this user after boot, so
                // now is the time to remove obsolete print jobs since they
                // are from the last boot and no application would query them.
                userState.removeObsoletePrintJobs();
            }
        });
    }

    @Override
    public Bundle print(String printJobName, IPrintDocumentAdapter adapter,
            PrintAttributes attributes, String packageName, int appId, int userId) {
        final int resolvedAppId = resolveCallingAppEnforcingPermissions(appId);
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        String resolvedPackageName = resolveCallingPackageNameEnforcingSecurity(packageName);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            return userState.print(printJobName, adapter, attributes,
                    resolvedPackageName, resolvedAppId);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public List<PrintJobInfo> getPrintJobInfos(int appId, int userId) {
        final int resolvedAppId = resolveCallingAppEnforcingPermissions(appId);
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            return userState.getPrintJobInfos(resolvedAppId);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public PrintJobInfo getPrintJobInfo(PrintJobId printJobId, int appId, int userId) {
        final int resolvedAppId = resolveCallingAppEnforcingPermissions(appId);
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            return userState.getPrintJobInfo(printJobId, resolvedAppId);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void cancelPrintJob(PrintJobId printJobId, int appId, int userId) {
        final int resolvedAppId = resolveCallingAppEnforcingPermissions(appId);
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.cancelPrintJob(printJobId, resolvedAppId);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void restartPrintJob(PrintJobId printJobId, int appId, int userId) {
        final int resolvedAppId = resolveCallingAppEnforcingPermissions(appId);
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.restartPrintJob(printJobId, resolvedAppId);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public List<PrintServiceInfo> getEnabledPrintServices(int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            return userState.getEnabledPrintServices();
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public List<PrintServiceInfo> getInstalledPrintServices(int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            return userState.getInstalledPrintServices();
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void createPrinterDiscoverySession(IPrinterDiscoveryObserver observer,
            int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.createPrinterDiscoverySession(observer);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void destroyPrinterDiscoverySession(IPrinterDiscoveryObserver observer,
            int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.destroyPrinterDiscoverySession(observer);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void startPrinterDiscovery(IPrinterDiscoveryObserver observer,
            List<PrinterId> priorityList, int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.startPrinterDiscovery(observer, priorityList);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void stopPrinterDiscovery(IPrinterDiscoveryObserver observer, int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.stopPrinterDiscovery(observer);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void validatePrinters(List<PrinterId> printerIds, int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.validatePrinters(printerIds);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void startPrinterStateTracking(PrinterId printerId, int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.startPrinterStateTracking(printerId);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void stopPrinterStateTracking(PrinterId printerId, int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.stopPrinterStateTracking(printerId);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void addPrintJobStateChangeListener(IPrintJobStateChangeListener listener,
            int appId, int userId) throws RemoteException {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final int resolvedAppId = resolveCallingAppEnforcingPermissions(appId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.addPrintJobStateChangeListener(listener, resolvedAppId);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void removePrintJobStateChangeListener(IPrintJobStateChangeListener listener,
            int userId) {
        final int resolvedUserId = resolveCallingUserEnforcingPermissions(userId);
        final UserState userState;
        synchronized (mLock) {
            userState = getOrCreateUserStateLocked(resolvedUserId);
        }
        final long identity = Binder.clearCallingIdentity();
        try {
            userState.removePrintJobStateChangeListener(listener);
        } finally {
            Binder.restoreCallingIdentity(identity);
        }
    }

    @Override
    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
                != PackageManager.PERMISSION_GRANTED) {
            pw.println("Permission Denial: can't dump PrintManager from from pid="
                    + Binder.getCallingPid()
                    + ", uid=" + Binder.getCallingUid());
            return;
        }

        synchronized (mLock) {
            pw.println("PRINT MANAGER STATE (dumpsys print)");
            final int userStateCount = mUserStates.size();
            for (int i = 0; i < userStateCount; i++) {
                UserState userState = mUserStates.get(i);
                userState.dump(fd, pw, "");
                pw.println();
            }
        }
    }

    private void registerContentObservers() {
        final Uri enabledPrintServicesUri = Settings.Secure.getUriFor(
                Settings.Secure.ENABLED_PRINT_SERVICES);

        ContentObserver observer = new ContentObserver(BackgroundThread.getHandler()) {
            @Override
            public void onChange(boolean selfChange, Uri uri) {
                if (enabledPrintServicesUri.equals(uri)) {
                    synchronized (mLock) {
                        UserState userState = getCurrentUserStateLocked();
                        userState.updateIfNeededLocked();
                    }
                }
            }
        };

        mContext.getContentResolver().registerContentObserver(enabledPrintServicesUri,
                false, observer, UserHandle.USER_ALL);
    }

    private void registerBoradcastReceivers() {
        PackageMonitor monitor = new PackageMonitor() {
            @Override
            public boolean onPackageChanged(String packageName, int uid, String[] components) {
                synchronized (mLock) {
                    UserState userState = getOrCreateUserStateLocked(getChangingUserId());
                    Iterator<ComponentName> iterator = userState.getEnabledServices().iterator();
                    while (iterator.hasNext()) {
                        ComponentName componentName = iterator.next();
                        if (packageName.equals(componentName.getPackageName())) {
                            userState.updateIfNeededLocked();
                            return true;
                        }
                    }
                }
                return false;
            }

            @Override
            public void onPackageRemoved(String packageName, int uid) {
                synchronized (mLock) {
                    UserState userState = getOrCreateUserStateLocked(getChangingUserId());
                    Iterator<ComponentName> iterator = userState.getEnabledServices().iterator();
                    while (iterator.hasNext()) {
                        ComponentName componentName = iterator.next();
                        if (packageName.equals(componentName.getPackageName())) {
                            iterator.remove();
                            persistComponentNamesToSettingLocked(
                                    Settings.Secure.ENABLED_PRINT_SERVICES,
                                    userState.getEnabledServices(), getChangingUserId());
                            userState.updateIfNeededLocked();
                            return;
                        }
                    }
                }
            }

            @Override
            public boolean onHandleForceStop(Intent intent, String[] stoppedPackages,
                    int uid, boolean doit) {
                synchronized (mLock) {
                    UserState userState = getOrCreateUserStateLocked(getChangingUserId());
                    boolean stoppedSomePackages = false;
                    Iterator<ComponentName> iterator = userState.getEnabledServices().iterator();
                    while (iterator.hasNext()) {
                        ComponentName componentName = iterator.next();
                        String componentPackage = componentName.getPackageName();
                        for (String stoppedPackage : stoppedPackages) {
                            if (componentPackage.equals(stoppedPackage)) {
                                if (!doit) {
                                    return true;
                                }
                                stoppedSomePackages = true;
                                break;
                            }
                        }
                    }
                    if (stoppedSomePackages) {
                        userState.updateIfNeededLocked();
                    }
                    return false;
                }
            }

            @Override
            public void onPackageAdded(String packageName, int uid) {
                Intent intent = new Intent(android.printservice.PrintService.SERVICE_INTERFACE);
                intent.setPackage(packageName);

                List<ResolveInfo> installedServices = mContext.getPackageManager()
                        .queryIntentServicesAsUser(intent, PackageManager.GET_SERVICES,
                                getChangingUserId());

                if (installedServices == null) {
                    return;
                }

                final int installedServiceCount = installedServices.size();
                for (int i = 0; i < installedServiceCount; i++) {
                    ServiceInfo serviceInfo = installedServices.get(i).serviceInfo;
                    ComponentName component = new ComponentName(serviceInfo.packageName,
                            serviceInfo.name);
                    String label = serviceInfo.loadLabel(mContext.getPackageManager()).toString();
                    showEnableInstalledPrintServiceNotification(component, label,
                            getChangingUserId());
                }
            }

            private void persistComponentNamesToSettingLocked(String settingName,
                    Set<ComponentName> componentNames, int userId) {
                StringBuilder builder = new StringBuilder();
                for (ComponentName componentName : componentNames) {
                    if (builder.length() > 0) {
                        builder.append(COMPONENT_NAME_SEPARATOR);
                    }
                    builder.append(componentName.flattenToShortString());
                }
                Settings.Secure.putStringForUser(mContext.getContentResolver(),
                        settingName, builder.toString(), userId);
            }
        };

        // package changes
        monitor.register(mContext, BackgroundThread.getHandler().getLooper(),
                UserHandle.ALL, true);

        // user changes
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
        intentFilter.addAction(Intent.ACTION_USER_REMOVED);

        mContext.registerReceiverAsUser(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (Intent.ACTION_USER_SWITCHED.equals(action)) {
                    switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
                } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
                    removeUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
                }
            }
        }, UserHandle.ALL, intentFilter, null, BackgroundThread.getHandler());
    }

    private UserState getCurrentUserStateLocked() {
        return getOrCreateUserStateLocked(mCurrentUserId);
    }

    private UserState getOrCreateUserStateLocked(int userId) {
        UserState userState = mUserStates.get(userId);
        if (userState == null) {
            userState = new UserState(mContext, userId, mLock);
            mUserStates.put(userId, userState);
        }
        return userState;
    }

    private void switchUser(int newUserId) {
        UserState userState;
        synchronized (mLock) {
            if (newUserId == mCurrentUserId) {
                return;
            }
            mCurrentUserId = newUserId;
            userState = mUserStates.get(mCurrentUserId);
            if (userState == null) {
                userState = getCurrentUserStateLocked();
                userState.updateIfNeededLocked();
            } else {
                userState.updateIfNeededLocked();
            }
        }
        // This is the first time we switch to this user after boot, so
        // now is the time to remove obsolete print jobs since they
        // are from the last boot and no application would query them.
        userState.removeObsoletePrintJobs();
    }

    private void removeUser(int removedUserId) {
        synchronized (mLock) {
            UserState userState = mUserStates.get(removedUserId);
            if (userState != null) {
                userState.destroyLocked();
                mUserStates.remove(removedUserId);
            }
        }
    }

    private int resolveCallingAppEnforcingPermissions(int appId) {
        final int callingUid = Binder.getCallingUid();
        if (callingUid == 0 || callingUid == Process.SYSTEM_UID
                || callingUid == Process.SHELL_UID) {
            return appId;
        }
        final int callingAppId = UserHandle.getAppId(callingUid);
        if (appId == callingAppId) {
            return appId;
        }
        if (mContext.checkCallingPermission(
                "com.android.printspooler.permission.ACCESS_ALL_PRINT_JOBS")
                != PackageManager.PERMISSION_GRANTED) {
            throw new SecurityException("Call from app " + callingAppId + " as app "
                    + appId + " without com.android.printspooler.permission"
                    + ".ACCESS_ALL_PRINT_JOBS");
        }
        return appId;
    }

    private int resolveCallingUserEnforcingPermissions(int userId) {
        final int callingUid = Binder.getCallingUid();
        if (callingUid == 0 || callingUid == Process.SYSTEM_UID
                || callingUid == Process.SHELL_UID) {
            return userId;
        }
        final int callingUserId = UserHandle.getUserId(callingUid);
        if (callingUserId == userId) {
            return userId;
        }
        if (mContext.checkCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL)
                != PackageManager.PERMISSION_GRANTED
            ||  mContext.checkCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS)
                != PackageManager.PERMISSION_GRANTED) {
            if (userId == UserHandle.USER_CURRENT_OR_SELF) {
                return callingUserId;
            }
            throw new SecurityException("Call from user " + callingUserId + " as user "
                + userId + " without permission INTERACT_ACROSS_USERS or "
                + "INTERACT_ACROSS_USERS_FULL not allowed.");
        }
        if (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF) {
            return mCurrentUserId;
        }
        throw new IllegalArgumentException("Calling user can be changed to only "
                + "UserHandle.USER_CURRENT or UserHandle.USER_CURRENT_OR_SELF.");
    }

    private String resolveCallingPackageNameEnforcingSecurity(String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return null;
        }
        String[] packages = mContext.getPackageManager().getPackagesForUid(
                Binder.getCallingUid());
        final int packageCount = packages.length;
        for (int i = 0; i < packageCount; i++) {
            if (packageName.equals(packages[i])) {
                return packageName;
            }
        }
        return null;
    }

    private void showEnableInstalledPrintServiceNotification(ComponentName component,
            String label, int userId) {
        UserHandle userHandle = new UserHandle(userId);

        Intent intent = new Intent(Settings.ACTION_PRINT_SETTINGS);
        intent.putExtra(EXTRA_PRINT_SERVICE_COMPONENT_NAME, component.flattenToString());

        PendingIntent pendingIntent = PendingIntent.getActivityAsUser(mContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT, null, userHandle);

        Notification.Builder builder = new Notification.Builder(mContext)
                .setSmallIcon(R.drawable.ic_print)
                .setContentTitle(mContext.getString(R.string.print_service_installed_title, label))
                .setContentText(mContext.getString(R.string.print_service_installed_message))
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setShowWhen(true);

        NotificationManager notificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);

        String notificationTag = getClass().getName() + ":" + component.flattenToString();
        notificationManager.notifyAsUser(notificationTag, 0, builder.build(),
                userHandle);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Tokenizer;

use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @internal
 *
 * @covers \PhpCsFixer\Tokenizer\Token
 */
final class TokenTest extends TestCase
{
    /**
     * @param mixed $input
     *
     * @dataProvider provideConstructorValidationCases
     */
    public function testConstructorValidation($input)
    {
        $this->expectException(\InvalidArgumentException::class);

        new Token($input);
    }

    public function provideConstructorValidationCases()
    {
        return [
            [null],
            [123],
            [new \stdClass()],
            [['asd', 'asd']],
            [[null, 'asd']],
            [[new \stdClass(), 'asd']],
            [[T_WHITESPACE, null]],
            [[T_WHITESPACE, 123]],
            [[T_WHITESPACE, '']],
            [[T_WHITESPACE, new \stdClass()]],
        ];
    }

    /**
     * @group legacy
     * @expectedDeprecation PhpCsFixer\Tokenizer\Token::clear is deprecated and will be removed in 3.0.
     */
    public function testClear()
    {
        $token = $this->getForeachToken();
        $token->clear();

        Tokens::setLegacyMode(false);

        static::assertSame('', $token->getContent());
        static::assertNull($token->getId());
        static::assertFalse($token->isArray());
    }

    public function testGetPrototype()
    {
        static::assertSame($this->getBraceTokenPrototype(), $this->getBraceToken()->getPrototype());
        static::assertSame($this->getForeachTokenPrototype(), $this->getForeachToken()->getPrototype());
    }

    public function testIsArray()
    {
        static::assertFalse($this->getBraceToken()->isArray());
        static::assertTrue($this->getForeachToken()->isArray());
    }

    /**
     * @param bool $isCast
     *
     * @dataProvider provideIsCastCases
     */
    public function testIsCast(Token $token, $isCast)
    {
        static::assertSame($isCast, $token->isCast());
    }

    public function provideIsCastCases()
    {
        return [
            [$this->getBraceToken(), false],
            [$this->getForeachToken(), false],
            [new Token([T_ARRAY_CAST, '(array)', 1]), true],
            [new Token([T_BOOL_CAST, '(bool)', 1]), true],
            [new Token([T_DOUBLE_CAST, '(double)', 1]), true],
            [new Token([T_INT_CAST, '(int)', 1]), true],
            [new Token([T_OBJECT_CAST, '(object)', 1]), true],
            [new Token([T_STRING_CAST, '(string)', 1]), true],
            [new Token([T_UNSET_CAST, '(unset)', 1]), true],
        ];
    }

    /**
     * @param bool $isClassy
     *
     * @dataProvider provideIsClassyCases
     */
    public function testIsClassy(Token $token, $isClassy)
    {
        static::assertSame($isClassy, $token->isClassy());
    }

    public function provideIsClassyCases()
    {
        return [
            [$this->getBraceToken(), false],
            [$this->getForeachToken(), false],
            [new Token([T_CLASS, 'class', 1]), true],
            [new Token([T_INTERFACE, 'interface', 1]), true],
            [new Token([T_TRAIT, 'trait', 1]), true],
        ];
    }

    /**
     * @param bool $isComment
     *
     * @dataProvider provideIsCommentCases
     */
    public function testIsComment(Token $token, $isComment)
    {
        static::assertSame($isComment, $token->isComment());
    }

    public function provideIsCommentCases()
    {
        return [
            [$this->getBraceToken(), false],
            [$this->getForeachToken(), false],
            [new Token([T_COMMENT, '/* comment */', 1]), true],
            [new Token([T_DOC_COMMENT, '/** docs */', 1]), true],
        ];
    }

    /**
     * @group legacy
     * @expectedDeprecation PhpCsFixer\Tokenizer\Token::isEmpty is deprecated and will be removed in 3.0.
     */
    public function testIsEmpty()
    {
        $braceToken = $this->getBraceToken();
        static::assertFalse($braceToken->isEmpty());

        $emptyToken = new Token('');
        static::assertTrue($emptyToken->isEmpty());

        $whitespaceToken = new Token([T_WHITESPACE, ' ']);
        static::assertFalse($whitespaceToken->isEmpty());
    }

    public function testIsGivenKind()
    {
        $braceToken = $this->getBraceToken();
        $foreachToken = $this->getForeachToken();

        static::assertFalse($braceToken->isGivenKind(T_FOR));
        static::assertFalse($braceToken->isGivenKind(T_FOREACH));
        static::assertFalse($braceToken->isGivenKind([T_FOR]));
        static::assertFalse($braceToken->isGivenKind([T_FOREACH]));
        static::assertFalse($braceToken->isGivenKind([T_FOR, T_FOREACH]));

        static::assertFalse($foreachToken->isGivenKind(T_FOR));
        static::assertTrue($foreachToken->isGivenKind(T_FOREACH));
        static::assertFalse($foreachToken->isGivenKind([T_FOR]));
        static::assertTrue($foreachToken->isGivenKind([T_FOREACH]));
        static::assertTrue($foreachToken->isGivenKind([T_FOR, T_FOREACH]));
    }

    public function testIsKeywords()
    {
        static::assertTrue($this->getForeachToken()->isKeyword());
        static::assertFalse($this->getBraceToken()->isKeyword());
    }

    /**
     * @param ?int   $tokenId
     * @param string $content
     * @param bool   $isConstant
     *
     * @dataProvider provideMagicConstantCases
     */
    public function testIsMagicConstant($tokenId, $content, $isConstant = true)
    {
        $token = new Token(
            null === $tokenId ? $content : [$tokenId, $content]
        );

        static::assertSame($isConstant, $token->isMagicConstant());
    }

    public function provideMagicConstantCases()
    {
        $cases = [
            [T_CLASS_C, '__CLASS__'],
            [T_DIR, '__DIR__'],
            [T_FILE, '__FILE__'],
            [T_FUNC_C, '__FUNCTION__'],
            [T_LINE, '__LINE__'],
            [T_METHOD_C, '__METHOD__'],
            [T_NS_C, '__NAMESPACE__'],
            [T_TRAIT_C, '__TRAIT__'],
        ];

        foreach ($cases as $case) {
            $cases[] = [$case[0], strtolower($case[1])];
        }

        foreach ([$this->getForeachToken(), $this->getBraceToken()] as $token) {
            $cases[] = [$token->getId(), $token->getContent(), false];
            $cases[] = [$token->getId(), strtolower($token->getContent()), false];
        }

        return $cases;
    }

    /**
     * @param bool $isNativeConstant
     *
     * @dataProvider provideIsNativeConstantCases
     */
    public function testIsNativeConstant(Token $token, $isNativeConstant)
    {
        static::assertSame($isNativeConstant, $token->isNativeConstant());
    }

    public function provideIsNativeConstantCases()
    {
        return [
            [$this->getBraceToken(), false],
            [$this->getForeachToken(), false],
            [new Token([T_STRING, 'null', 1]), true],
            [new Token([T_STRING, 'false', 1]), true],
            [new Token([T_STRING, 'true', 1]), true],
            [new Token([T_STRING, 'tRuE', 1]), true],
            [new Token([T_STRING, 'TRUE', 1]), true],
        ];
    }

    /**
     * @param bool        $isWhitespace
     * @param null|string $whitespaces
     *
     * @dataProvider provideIsWhitespaceCases
     */
    public function testIsWhitespace(Token $token, $isWhitespace, $whitespaces = null)
    {
        if (null !== $whitespaces) {
            static::assertSame($isWhitespace, $token->isWhitespace($whitespaces));
        } else {
            static::assertSame($isWhitespace, $token->isWhitespace(null));
            static::assertSame($isWhitespace, $token->isWhitespace());
        }
    }

    public function provideIsWhitespaceCases()
    {
        return [
            [$this->getBraceToken(), false],
            [$this->getForeachToken(), false],
            [new Token(' '), true],
            [new Token("\t "), true],
            [new Token("\t "), false, ' '],
            [new Token([T_WHITESPACE, "\r", 1]), true],
            [new Token([T_WHITESPACE, "\0", 1]), true],
            [new Token([T_WHITESPACE, "\x0B", 1]), true],
            [new Token([T_WHITESPACE, "\n", 1]), true],
            [new Token([T_WHITESPACE, "\n", 1]), false, " \t"],
        ];
    }

    /**
     * @param mixed       $prototype
     * @param null|int    $expectedId
     * @param null|string $expectedContent
     * @param null|bool   $expectedIsArray
     * @param null|string $expectedExceptionClass
     *
     * @dataProvider provideCreatingTokenCases
     */
    public function testCreatingToken($prototype, $expectedId, $expectedContent, $expectedIsArray, $expectedExceptionClass = null)
    {
        if ($expectedExceptionClass) {
            $this->expectException($expectedExceptionClass);
        }

        $token = new Token($prototype);
        static::assertSame($expectedId, $token->getId());
        static::assertSame($expectedContent, $token->getContent());
        static::assertSame($expectedIsArray, $token->isArray());
    }

    public function provideCreatingTokenCases()
    {
        return [
            [[T_FOREACH, 'foreach'], T_FOREACH, 'foreach', true],
            ['(', null, '(', false],
            [123, null, null, null, \InvalidArgumentException::class],
            [false, null, null, null, \InvalidArgumentException::class],
            [null, null, null, null, \InvalidArgumentException::class],
        ];
    }

    public function testEqualsDefaultIsCaseSensitive()
    {
        $token = new Token([T_FUNCTION, 'function', 1]);

        static::assertTrue($token->equals([T_FUNCTION, 'function']));
        static::assertFalse($token->equals([T_FUNCTION, 'Function']));
    }

    /**
     * @param bool               $equals
     * @param array|string|Token $other
     * @param bool               $caseSensitive
     *
     * @dataProvider provideEqualsCases
     */
    public function testEquals(Token $token, $equals, $other, $caseSensitive = true)
    {
        static::assertSame($equals, $token->equals($other, $caseSensitive));
    }

    public function provideEqualsCases()
    {
        $brace = $this->getBraceToken();
        $function = new Token([T_FUNCTION, 'function', 1]);

        return [
            [$brace, false, '!'],
            [$brace, false, '!', false],
            [$brace, true, '('],
            [$brace, true, '(', false],
            [$function, false, '('],
            [$function, false, '(', false],

            [$function, false, [T_NAMESPACE]],
            [$function, false, [T_NAMESPACE], false],
            [$function, false, [T_VARIABLE, 'function']],
            [$function, false, [T_VARIABLE, 'function'], false],
            [$function, false, [T_VARIABLE, 'Function']],
            [$function, false, [T_VARIABLE, 'Function'], false],
            [$function, true, [T_FUNCTION]],
            [$function, true, [T_FUNCTION], false],
            [$function, true, [T_FUNCTION, 'function']],
            [$function, true, [T_FUNCTION, 'function'], false],
            [$function, false, [T_FUNCTION, 'Function']],
            [$function, true, [T_FUNCTION, 'Function'], false],
            [$function, false, [T_FUNCTION, 'junction'], false],

            [$function, true, new Token([T_FUNCTION, 'function'])],
            [$function, false, new Token([T_FUNCTION, 'Function'])],
            [$function, true, new Token([T_FUNCTION, 'Function']), false],

            // if it is an array any additional field is checked too
            [$function, false, [T_FUNCTION, 'function', 'unexpected']],
        ];
    }

    public function testEqualsAnyDefaultIsCaseSensitive()
    {
        $token = new Token([T_FUNCTION, 'function', 1]);

        static::assertTrue($token->equalsAny([[T_FUNCTION, 'function']]));
        static::assertFalse($token->equalsAny([[T_FUNCTION, 'Function']]));
    }

    /**
     * @param bool $equalsAny
     * @param bool $caseSensitive
     *
     * @dataProvider provideEqualsAnyCases
     */
    public function testEqualsAny($equalsAny, array $other, $caseSensitive = true)
    {
        $token = new Token([T_FUNCTION, 'function', 1]);

        static::assertSame($equalsAny, $token->equalsAny($other, $caseSensitive));
    }

    public function provideEqualsAnyCases()
    {
        $brace = $this->getBraceToken();
        $foreach = $this->getForeachToken();

        return [
            [false, []],
            [false, [$brace]],
            [false, [$brace, $foreach]],
            [true, [$brace, $foreach, [T_FUNCTION]]],
            [true, [$brace, $foreach, [T_FUNCTION, 'function']]],
            [false, [$brace, $foreach, [T_FUNCTION, 'Function']]],
            [true, [$brace, $foreach, [T_FUNCTION, 'Function']], false],
            [false, [[T_VARIABLE, 'junction'], [T_FUNCTION, 'junction']], false],
        ];
    }

    /**
     * @param bool       $isKeyCaseSensitive
     * @param array|bool $caseSensitive
     * @param int        $key
     *
     * @dataProvider provideIsKeyCaseSensitiveCases
     */
    public function testIsKeyCaseSensitive($isKeyCaseSensitive, $caseSensitive, $key)
    {
        static::assertSame($isKeyCaseSensitive, Token::isKeyCaseSensitive($caseSensitive, $key));
    }

    public function provideIsKeyCaseSensitiveCases()
    {
        return [
            [true, true, 0],
            [true, true, 1],
            [true, [], 0],
            [true, [true], 0],
            [true, [false, true], 1],
            [true, [false, true, false], 1],
            [true, [false], 10],

            [false, false, 10],
            [false, [false], 0],
            [false, [true, false], 1],
            [false, [true, false, true], 1],
            [false, [1 => false], 1],
        ];
    }

    /**
     * @group legacy
     * @expectedDeprecation PhpCsFixer\Tokenizer\Token::isChanged is deprecated and will be removed in 3.0.
     */
    public function testIsChanged()
    {
        $token = new Token([T_WHITESPACE, ' ']);
        static::assertFalse($token->isChanged());
    }

    /**
     * @param null|string $expected
     * @param int         $id
     *
     * @dataProvider provideTokenGetNameCases
     */
    public function testTokenGetNameForId($expected, $id)
    {
        static::assertSame($expected, Token::getNameForId($id));
    }

    public function provideTokenGetNameCases()
    {
        return [
            [
                null,
                -1,
            ],
            [
                'T_CLASS',
                T_CLASS,
            ],
            [
                'CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE',
                CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE,
            ],
        ];
    }

    /**
     * @param null|string $expected
     *
     * @dataProvider provideGetNameCases
     */
    public function testGetName(Token $token, $expected = null)
    {
        static::assertSame($expected, $token->getName());
    }

    public function provideGetNameCases()
    {
        yield [
            new Token([T_FUNCTION, 'function', 1]),
            'T_FUNCTION',
        ];

        yield [
            new Token(')'),
            null,
        ];

        yield [
            new Token(''),
            null,
        ];
    }

    /**
     * @dataProvider provideToArrayCases
     */
    public function testToArray(Token $token, array $expected)
    {
        static::assertSame($expected, $token->toArray());
    }

    public function provideToArrayCases()
    {
        yield [
            new Token([T_FUNCTION, 'function', 1]),
            [
                'id' => T_FUNCTION,
                'name' => 'T_FUNCTION',
                'content' => 'function',
                'isArray' => true,
                'changed' => false,
            ],
        ];

        yield [
            new Token(')'),
            [
                'id' => null,
                'name' => null,
                'content' => ')',
                'isArray' => false,
                'changed' => false,
            ],
        ];

        yield [
            new Token(''),
            [
                'id' => null,
                'name' => null,
                'content' => '',
                'isArray' => false,
                'changed' => false,
            ],
        ];
    }

    private function getBraceToken()
    {
        return new Token($this->getBraceTokenPrototype());
    }

    private function getBraceTokenPrototype()
    {
        return '(';
    }

    private function getForeachToken()
    {
        return new Token($this->getForeachTokenPrototype());
    }

    private function getForeachTokenPrototype()
    {
        static $prototype = [T_FOREACH, 'foreach'];

        return $prototype;
    }
}


text:
var fs = require('fs');

function addLicenseTextToFile(licenseText, destination) {
  if (!destination) {
    throw new Error('destination file path is required as 2nd argument');
  }

  fs.writeFileSync(
    destination,
    `/**
  @license
  ${licenseText}
 **/
${fs.readFileSync(`${destination}`).toString()}
`
  );
}

function addLicenseToFile(license, destination) {
  if (!license) {
    throw new Error('license path is required as 1st argument');
  }

  addLicenseTextToFile(fs.readFileSync(license).toString(), destination);
}

module.exports = {
  addLicenseToFile: addLicenseToFile,
  addLicenseTextToFile: addLicenseTextToFile,
};


text:
var binding = require('binding').Binding.create('declarativeContent');

var utils = require('utils');
var validate = require('schemaUtils').validate;
var canonicalizeCompoundSelector =
    requireNative('css_natives').CanonicalizeCompoundSelector;
var setIcon = require('setIcon').setIcon;

binding.registerCustomHook( function(api) {
  var declarativeContent = api.compiledApi;

  // Returns the schema definition of type |typeId| defined in |namespace|.
  function getSchema(typeId) {
    return utils.lookup(api.schema.types,
                        'id',
                        'declarativeContent.' + typeId);
  }

  // Helper function for the constructor of concrete datatypes of the
  // declarative content API.
  // Makes sure that |this| contains the union of parameters and
  // {'instanceType': 'declarativeContent.' + typeId} and validates the
  // generated union dictionary against the schema for |typeId|.
  function setupInstance(instance, parameters, typeId) {
    for (var key in parameters) {
      if ($Object.hasOwnProperty(parameters, key)) {
        instance[key] = parameters[key];
      }
    }
    instance.instanceType = 'declarativeContent.' + typeId;
    var schema = getSchema(typeId);
    validate([instance], [schema]);
  }

  function canonicalizeCssSelectors(selectors) {
    for (var i = 0; i < selectors.length; i++) {
      var canonicalizedSelector = canonicalizeCompoundSelector(selectors[i]);
      if (canonicalizedSelector == '') {
        throw new Error(
            'Element of \'css\' array must be a ' +
            'list of valid compound selectors: ' +
            selectors[i]);
      }
      selectors[i] = canonicalizedSelector;
    }
  }

  // Setup all data types for the declarative content API.
  declarativeContent.PageStateMatcher = function(parameters) {
    setupInstance(this, parameters, 'PageStateMatcher');
    if ($Object.hasOwnProperty(this, 'css')) {
      canonicalizeCssSelectors(this.css);
    }
  };
  declarativeContent.ShowPageAction = function(parameters) {
    setupInstance(this, parameters, 'ShowPageAction');
  };
  declarativeContent.RequestContentScript = function(parameters) {
    setupInstance(this, parameters, 'RequestContentScript');
  };
  // TODO(rockot): Do not expose this in M39 stable. Making this restriction
  // possible will take some extra work. See http://crbug.com/415315
  declarativeContent.SetIcon = function(parameters) {
    setIcon(parameters, function (data) {
      setupInstance(this, data, 'SetIcon');
    }.bind(this));
  };
});

exports.binding = binding.generate();


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2018 Kantega AS
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.kantega.reststop</groupId>
        <artifactId>reststop-parent</artifactId>
        <version>3.12-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <groupId>org.kantega.reststop.test</groupId>
    <artifactId>reststop-hello-world</artifactId>

    <dependencies>
        <dependency>
            <groupId>${project.parent.groupId}</groupId>
            <artifactId>reststop-api</artifactId>
            <scope>provided</scope>
            <version>${project.parent.version}</version>
        </dependency>

        <dependency>
            <groupId>${project.parent.groupId}</groupId>
            <artifactId>reststop-servlet-api</artifactId>
            <scope>provided</scope>
            <version>${project.parent.version}</version>
        </dependency>

        <dependency>
            <groupId>${project.parent.groupId}</groupId>
            <artifactId>reststop-jaxrs-api</artifactId>
            <scope>provided</scope>
            <version>${project.parent.version}</version>
        </dependency>

        <dependency>
            <groupId>${project.parent.groupId}</groupId>
            <artifactId>reststop-jaxws-api</artifactId>
            <version>${project.parent.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>${project.parent.groupId}</groupId>
            <artifactId>reststop-wicket-plugin</artifactId>
            <version>${project.parent.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>${project.parent.groupId}</groupId>
            <artifactId>reststop-springmvc-plugin</artifactId>
            <version>${project.parent.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>${project.parent.groupId}</groupId>
            <artifactId>reststop-annotation-processor</artifactId>
            <version>${project.parent.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>${project.parent.groupId}</groupId>
                <artifactId>reststop-maven-plugin</artifactId>
                <version>${project.parent.version}</version>
                <configuration>
                    <path>dev</path>
                    <applicationName>helloworld</applicationName>
                    <plugins>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-springmvc-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-servlet-deploy-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-metrics-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-metrics-servlets-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-cxf-metrics-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-jaxrs-metrics-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-jaxrs-api</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-jaxws-api</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-statistics-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-security-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>javax.validation</groupId>
                            <artifactId>validation-api</artifactId>
                            <version>1.1.0.Final</version>
                        </plugin>
                        <plugin>
                            <groupId>org.kantega.reststop</groupId>
                            <artifactId>reststop-assets-plugin</artifactId>
                            <version>${project.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-jersey-plugin</artifactId>
                            <version>${project.parent.version}</version>
                            <dependencies>
                                <dependency>
                                    <groupId>org.glassfish.jersey.ext</groupId>
                                    <artifactId>jersey-bean-validation</artifactId>
                                    <version>${jersey.version}</version>
                                    <exclusions>
                                        <exclusion>
                                            <groupId>javax.ws.rs</groupId>
                                            <artifactId>javax.ws.rs-api</artifactId>
                                        </exclusion>
                                    </exclusions>
                                </dependency>
                            </dependencies>
                        </plugin>

                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-cxf-logging-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>

                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-cxf-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>

                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-wicket-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-wsdl-test-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-jetty-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                        <plugin>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-jetty-websockets-plugin</artifactId>
                            <version>${project.parent.version}</version>
                        </plugin>
                    </plugins>
                    <containerDependencies>
                        <!--<dependency>
                            <groupId>ch.qos.logback</groupId>
                            <artifactId>logback-classic</artifactId>
                            <version>1.1.3</version>
                        </dependency>-->
                        <dependency>
                            <groupId>org.slf4j</groupId>
                            <artifactId>slf4j-api</artifactId>
                            <version>${slf4j.version}</version>
                        </dependency>
                        <dependency>
                            <groupId>org.slf4j</groupId>
                            <artifactId>slf4j-simple</artifactId>
                            <version>${slf4j.version}</version>
                        </dependency>
                        <dependency>
                            <groupId>${project.parent.groupId}</groupId>
                            <artifactId>reststop-servlet-api</artifactId>
                            <version>${project.parent.version}</version>
                        </dependency>
                        <dependency>
                            <groupId>javax.servlet</groupId>
                            <artifactId>javax.servlet-api</artifactId>
                            <version>3.1.0</version>
                        </dependency>
                        <dependency>
                            <groupId>javax.websocket</groupId>
                            <artifactId>javax.websocket-api</artifactId>
                            <version>1.0</version>
                        </dependency>
                    </containerDependencies>
                </configuration>
                <executions>
                    <execution>
                        <id>mark-source-dir</id>
                        <goals>
                            <goal>mark-source-dir</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>conf-doc</id>
                        <goals>
                            <goal>conf-doc</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>start</id>
                        <goals>
                            <goal>boot-start</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>stop</id>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>dist</id>
                        <goals>
                            <goal>dist</goal>
                        </goals>
                        <configuration>
                            <container>bootstrap</container>
                            <resources>
                                <resource>
                                    <directory>${basedir}/src/install/</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.16</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>${maven-deploy-plugin.version}</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>JDK9+</id>
            <activation>
                <jdk>[9,)</jdk>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <configuration>
                            <argLine>--add-modules=java.xml.bind,java.xml.ws</argLine>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
from application import *
from connection import *

import time
import datetime
import uuid

def Instantiate(appName='unknown'):
    log.info("TicTacToeManagerApplication -- Instantiate")
    app = TicTacToeManagerApplication(appName)
    return app

class TicTacToeManagerApplication(Application):
    def __init__(self, name='unknown'):
        Application.__init__(self, name)

        self.Games = {}

        self.CommandMap["startGame"] = self.StartGame
        self.CommandMap["stopGame"] = self.StopGame
        self.CommandMap["joinGame"] = self.JoinGame

    def Run(self):
        log.info("TicTacToeManagerApplication now running.")

        Application.Run(self, self._Run)

        log.info("TicTacToeManagerApplication DONE running.")

    def _Run(self):
        #Update all game instances
        completedGames = []

        for (guid, game) in self.Games.items():
            if game.Complete:
                completedGames.append(guid)
            elif not game.Paused:
                try:
                    game.Update(0)
                except:
                    log.info("TicTacToeManagerApplication game had an exception during Update(). Killing that instance.")
                    game.Complete = True

        for guid in completedGames:
            self.StopGame(guid)

    def StartGame(self):
        game = Game(self)
        log.info("TicTacToeManagerApplication starting game %s" % game.GUID)
        self.Games[game.GUID] = game
        return "gameGUID|" + game.GUID

    def StopGame(self, guid):
        log.info("TicTacToeManagerApplication stopping game %s" % guid)
        game = self.Games.pop(guid, None)
        if not game == None:
            try:
                game.Stop()
            except:
                log.info("TicTacToeManagerApplication got an exception when stopping a game instance. Finishing it off.")
            finally:
                del game

    def JoinGame(self, guid, playerNum='1'):
        log.info("TicTacToeManagerApplication trying to let client join game %s" % guid)
        if guid in self.Games:
            game = self.Games[guid]
            if game.AddPlayer(self.CommandConnectionContext, playerNum):
                #Let the game instance deal with the connection
                clientIndex = self.Clients.index(self.CommandConnectionContext)
                self.Clients.pop(clientIndex)

class Game():
    def __init__(self, application):
        self.GUID = uuid.uuid4().hex
        self.Application = application
        self.Player1 = None
        self.Player2 = None

        self.Paused = False
        self.Complete = False

        self.Turn = 1
        self.TurnComplete = False
        #0,1,2
        #3,4,5
        #6,7,8
        self.Board = [0,0,0,0,0,0,0,0,0]
        self.Winner = 0

        self.CommandMap = {}
        self.CommandMap["place"] = self.PlacePiece

    def AddPlayer(self, connection, playerNum='1'):
        if playerNum == '1' and self.Player1 == None:
            log.info("TicTacToe Game %s added player 1" % self.GUID)
            self.Player1 = connection
            self.Player1.SendCommand("joinedGame|" + self.GUID + "|1")
            self.Player1.SendCommand("board|" + repr(self.Board))
        elif playerNum == '2' and self.Player2 == None:
            log.info("TicTacToe Game %s added player 2" % self.GUID)
            self.Player2 = connection
            self.Player2.SendCommand("joinedGame|" + self.GUID + "|2")
            self.Player2.SendCommand("board|" + repr(self.Board))

            #throttle player 2 by default, they don't go first
            self.Player2.Throttled = True
        else:
            return False

        return True

    def RemovePlayer(self, playerNum='1'):
        if playerNum == '1' and not self.Player1 == None:
            self.Player1.Connected = False
            self.Player1 = None
        elif playerNum == '2' and not self.Player2 == None:
            self.Player2.Connected = False
            self.Player2 = None

        if self.Player1 == None and self.Player2 == None:
            self.Complete = True

    def Stop(self):
        self.RemovePlayer('1')
        self.RemovePlayer('2')

    def Update(self, deltaT):
        if self.Player1 != None and not self.Player1.Connected:
            self.Complete = True
        elif self.Player2 != None and not self.Player2.Connected:
            self.Complete = True

        self.HandleTurn()

    def SendBoardState(self):
        self.Player1.SendCommand("board|" + repr(self.Board))
        self.Player2.SendCommand("board|" + repr(self.Board))

    def GameWon(self):
        self.Complete = True
        self.Player1.SendCommand("gameOver|" + str(self.Winner))
        self.Player2.SendCommand("gameOver|" + str(self.Winner))

    def GameDraw(self):
        self.Complete = True
        self.Player1.SendCommand("gameOver|0")
        self.Player2.SendCommand("gameOver|0")

    def NotifyPiecePlaced(self, position, player):
        self.Player1.SendCommand("placed|" + str(position) + "|" + str(player))
        self.Player2.SendCommand("placed|" + str(position) + "|" + str(player))

    def HandleTurn(self):
        if self.Turn == 1:
            self.ProcessTurn(self.Player1)
            if self.TurnComplete:
                self.Player1.Throttled = True
                self.Player2.Throttled = False
                self.Turn = 2
                self.TurnComplete = False
                self.SendBoardState()
        else:
            self.ProcessTurn(self.Player2)
            if self.TurnComplete:
                self.Player2.Throttled = True
                self.Player1.Throttled = False
                self.Turn = 1
                self.TurnComplete = False
                self.SendBoardState()

    def ProcessTurn(self, connection):
        try:
            receivedCommand = connection.GetNextCommand()

            if receivedCommand != None:
                commandResult = self.ProcessCommand(receivedCommand)

                if commandResult != None:
                    connection.SendCommand(commandResult)
        except:
            pass

    def ProcessCommand(self, command):
        parts = command.split('|')

        if parts[0] in self.CommandMap:
            args = parts[1:]
            result = self.CommandMap[parts[0]](*args)
            log.info('TicTacToe instance - Command %s returned %s' % (command, result))
            return result
        else:
            log.info('TicTacToe instance - Unknown command %s' % (command))
            return None

    def CheckRow(self, a, b, c):
        x = self.Board[a] + self.Board[b] + self.Board[c]
        if x == 9:
            self.Winner = 1
            return True
        elif x == 15:
            self.Winner = 2
            return True
        else:
            return False

    def PlacePiece(self, position):
        pos = int(position)
        if pos >= 0 and pos <= 8:
            if self.Board[pos] == 0:
                if self.Turn == 1:
                    #player 1 places 3's
                    self.Board[pos] = 3
                    self.NotifyPiecePlaced(pos, 1)
                else:
                    #player 2 places 5's
                    self.Board[pos] = 5
                    self.NotifyPiecePlaced(pos, 2)

                self.TurnComplete = True

                #Win?
                if self.CheckRow(0, 1, 2) or self.CheckRow(3, 4, 5) or self.CheckRow(6, 7, 8) or self.CheckRow(0, 3, 6) or self.CheckRow(1, 4, 7) or self.CheckRow(2, 5, 8) or self.CheckRow(0, 4, 8) or self.CheckRow(2, 4, 6):
                    self.GameWon()
                #Draw? Lowest possible full board count is 5*3 + 4*5
                elif reduce(lambda x, y: x + y, self.Board) >= 35:
                    self.GameDraw()


text:
import Ember from "ember";

function _parentObjectCheck(obj) {
  for(var k in obj) {
    if(k === "parentObj") {
      obj[k] = null;
    }
    else if(Ember.typeOf(obj[k]) === "instance") {
      _parentObjectCheck(obj);
    }
  }
}

export default Ember.Test.registerHelper("parentObjectCheck", function (app, obj) {
  _parentObjectCheck(obj);
});


text:
package com.structurizr.configuration;

/**
 * Represents a user, and the role-based access they have to a workspace.
 */
public final class User {

    private String username;
    private Role role;

    User() {
    }

    User(String username, Role role) {
        setUsername(username);
        setRole(role);
    }

    /**
     * Gets the username (e.g. e-mail address).
     *
     * @return  the username, as a String
     */
    public String getUsername() {
        return username;
    }

    void setUsername(String username) {
        this.username = username;
    }

    /**
     * Gets the role.
     *
     * @return  a Role enum
     */
    public Role getRole() {
        return role;
    }

    void setRole(Role role) {
        this.role = role;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        return username.equals(user.username);
    }

    @Override
    public int hashCode() {
        return username.hashCode();
    }

    @Override
    public String toString() {
        return "User {" +
                "username='" + username + '\'' +
                ", role=" + role +
                '}';
    }

}