text:
package org.ethereum.facade;

import java.net.InetAddress;
import java.util.concurrent.BlockingQueue;

import org.ethereum.core.Block;
import org.ethereum.listener.EthereumListener;
import org.ethereum.manager.WorldManager;
import org.ethereum.net.client.ClientPeer;
import org.ethereum.net.client.PeerData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * www.ethereumJ.com
 *
 * @author: Roman Mandeleil
 * Created on: 27/07/2014 09:12
 */

public class EthereumImpl implements Ethereum {

    private static final Logger logger = LoggerFactory.getLogger("facade");

    public EthereumImpl() {}

    /**
     * Find a peer but not this one
     * @param peerData - peer to exclude
     * @return online peer
     * @throws InterruptedException
     */
    @Override
    public PeerData findPeer(PeerData peerData) throws InterruptedException {

        logger.info("Looking for online peers...");

        final EthereumListener listener = WorldManager.getInstance().getListener();
        if (listener != null) {
            listener.trace("Looking for online peer");
        }

        WorldManager.getInstance().startPeerDiscovery();

        final BlockingQueue<PeerData> peers = WorldManager.getInstance().getPeers();

        PeerData peer = null;

        while ((peer = peers.take()) != null) { // it blocks until a peer is available.

            if (peer.isOnline() && !peer.equals(peerData)){

                logger.info("Found peer: {}", peer.toString());

                if (listener != null)
                    listener.trace(String.format("Found online peer: [ %s ]", peer.toString()));

                return peer;
            }
        }
        return null;
    }

    @Override
    public PeerData findPeer() throws InterruptedException {
        return findPeer(null);
    }

    @Override
    public void stopPeerDiscover(){
        WorldManager.getInstance().stopPeerDiscover();
    }

    @Override
    public void connect(InetAddress addr, int port){
        connect(addr.getHostName(), port);
    }

    @Override
    public void connect(String ip, int port){

        logger.info("Connecting to: {}:{}", ip, port);
        new ClientPeer().connect(ip,
                port);
    }

    @Override
    public Block getBlockByIndex(long index){
        Block block = WorldManager.getInstance().getBlockchain().getByNumber(index);
        return block;
    }

    @Override
    public long getBlockChainSize(){
        return WorldManager.getInstance().getBlockchain().getSize();
    }

    @Override
    public void addListener(EthereumListener listener) {
        WorldManager.getInstance().addListener(listener);
    }

    @Override
    public void loadBlockChain() {
        WorldManager.getInstance().loadBlockchain();
    }
}


text:
TOOLS=$(dirname $0)

#Try to work out which physical disk the boot device is
boot_disk=$(grep boot /etc/mtab | grep -o sd[a-z])

NUMBER_OF_PARTITIONS=3
LABEL_PREFIX='data'

#Try to autodetect RAID parameters
source $TOOLS/detect-raid-parameters.sh

if [[ "$RAID_LEVEL" == "" ]]; then
  echo "ERROR: RAID Level was not detected"
  exit 1
fi

if [[ "$RAID_STRIPE_SIZE" == "" ]]; then
  echo "ERROR: RAID Stripe Size was not detected"
  exit 1
fi

if [[ "$RAID_DRIVE_COUNT" == "" ]]; then
  echo "ERROR: RAID Drive Count was not detected"
  exit 1
fi

# Discount parity drives
RAID_DRIVE_COUNT=$(($RAID_DRIVE_COUNT - ($RAID_LEVEL - 4)))

# Assemble XFS creation options
XFS_OPTS="-f -l version=2 -i size=1024 -n size=65536 -d su=${RAID_STRIPE_SIZE}k,sw=${RAID_DRIVE_COUNT}"

echo " INFO: XFS creation parameters have been set to '$XFS_OPTS'"

function pause {
  echo -n " INFO: Pausing for 5 seconds: "
  for i in 5 4 3 2 1; do
    echo -n "$i.."
    sleep 1
  done
  echo "0"
}

if [[ ! -z $boot_disk ]]; then
  #Find physical disks that aren't the boot disk
  data_disk="$(grep -o sd[a-z]$ /proc/partitions | grep -v $boot_disk)"

  #Count found disks
  data_disk_count="$(echo $data_disk | wc -w)"

  echo " INFO: Boot disk appears to be $boot_disk"

  #Only proceed if we find one data disk, assume that anything else is an error
  if [[ $data_disk_count -eq 1 ]]; then
    echo " INFO: Data disk appears to be $data_disk"

    boot_disk_size=$(parted /dev/$boot_disk unit MB print | grep ^Disk | grep -o '[0-9]\+')
    data_disk_size=$(parted /dev/$data_disk unit MB print | grep ^Disk | grep -o '[0-9]\+')

    echo " INFO: Boot disk appears to be ${boot_disk_size}MB in size"
    echo " INFO: Data disk appears to be ${data_disk_size}MB in size"

    #Don't proceed unless data disk is the big one, this is a failsafe in-case we somehow chose the OS disks
    if [[ $boot_disk_size -lt $data_disk_size ]]; then
      echo "   OK: Boot disk is smaller than data disk, continuing."

      #Calculate partiton size, we are ok with rounding errors at the MB level
      partition_size=$(($data_disk_size / $NUMBER_OF_PARTITIONS))

      echo " INFO: Will make $NUMBER_OF_PARTITIONS partitions of ${partition_size}MB, Ok to continue? (yes)"
      s=""
      echo -n "> "
      read s

      if [[ $s == "yes" ]]; then
        # Re-create partition table
        parted -s /dev/$data_disk mklabel gpt

        # Create partitions
        for i in $(seq 1 $NUMBER_OF_PARTITIONS); do
          p_start=$((partition_size * ($i - 1)))
          # Always start first partition at 1MB to ensure partitions are aligned with underlying storage stripes
          if [[ $i -eq 1 ]]; then
            p_start=1
          fi
          p_end=$(($p_start + partition_size - 2))
          echo " INFO: Creating partition $i from ${p_start}MB to ${p_end}MB"
          parted -s -a optimal /dev/$data_disk mkpart data ${p_start}Mb ${p_end}Mb
        done

        pause

        # Create filesystems with standard options
        for i in $(seq 1 $NUMBER_OF_PARTITIONS); do
          echo " INFO: Creating XFS filesystem for data$i on /dev/${data_disk}${i}"
          mkfs.xfs $XFS_OPTS -L $LABEL_PREFIX$i /dev/${data_disk}${i}
        done

        echo " INFO: Requesting kernel re-read of partition table on /dev/${data_disk}"
        partprobe /dev/${data_disk}

        echo "   OK: Partitioning completed, have a nice day"
      else
        echo "ERROR: User aborted."
      fi

    else
      echo "ERROR: Boot disk is larger than data disk, aborting."
      exit 1
    fi

  else
    echo "ERROR: $data_disk_count data disks found"
    echo "$data_disk"
    exit 1
  fi

else
  echo "ERROR: Could not determine boot disk"
  exit 1
fi

redpajama_set_name: RedPajamaGithub


text:
package com.iluwatar.eda.framework;

/**
 * This interface can be implemented to handle different types of messages. Every handler is
 * responsible for a single of type message
 *
 * @param <E> Handler can handle events of type E
 */
public interface Handler<E extends Event> {

  /**
   * The onEvent method should implement and handle behavior related to the event. This can be as
   * simple as calling another service to handle the event on publishing the event on a queue to be
   * consumed by other sub systems.
   *
   * @param event the {@link Event} object to be handled.
   */
  void onEvent(E event);
}


text:
package com.sun.xml.internal.bind.v2.model.core;

import java.util.Map;

import javax.xml.namespace.QName;

/**
 * Property that maps to the following schema fragment.
 *
 *
<xmp>
 * <xs:complexType>
 *   <xs:sequence>
 *     <xs:element name="entry" minOccurs="0" maxOccurs="unbounded">
 *       <xs:complexType>
 *         <xs:sequence>
 *           <xs:element name="key"   type="XXXX"/>
 *           <xs:element name="value" type="YYYY"/>
 *         </xs:sequence>
 *       </xs:complexType>
 *     </xs:element>
 *   </xs:sequence>
 * </xs:complexType>
 * </xmp>

 *
 *

 * This property is used to represent a default binding of a {@link Map} property.
 * ({@link Map} properties with adapters will be represented by {@link ElementPropertyInfo}.)
 *
 *
 *
Design Thinking Led to This

 *

 * I didn't like the idea of adding such a special-purpose {@link PropertyInfo} to a model.
 * The alternative was to implicitly assume an adapter, and have internal representation of
 * the Entry class ready.
 * But the fact that the key type and the value type changes with the parameterization makes
 * it very difficult to have such a class (especially inside Annotation Processing, where we can't even generate
 * classes.)
 *
 * @author Kohsuke Kawaguchi
 */
public interface MapPropertyInfo<T,C> extends PropertyInfo<T,C> {
    /**
     * Gets the wrapper element name.
     *
     * @return
     *      always non-null.
     */
    QName getXmlName();

    /**
     * Returns true if this property is nillable
     * (meaning the absence of the value is treated as nil='true')
     *
     *

     * This method is only used when this property is a collection.
     */
    boolean isCollectionNillable();

    /**
     * Type of the key of the map. K of {@code HashMap<K,V>}
     *
     * @return never null.
     */
    NonElement<T,C> getKeyType();

    /**
     * Type of the value of the map. V of {@code HashMap<K,V>}
     *
     * @return never null.
     */
    NonElement<T,C> getValueType();

    // TODO
    // Adapter<T,C> getKeyAdapter();
    // Adapter<T,C> getValueAdapter();
}


text:
<?php
class permission extends \Eloquent {
    public $table = "permission";

    public static function remove($id)
    {
  	    $obj = permission :: find($id);
  	    if(count($obj) > 0)
  	    {
		    return $obj -> delete();
  	    }
    }

    public static function getOne($id)
    {
  	    return permission::find($id);
    }

    public static function getList()
    {
  	    return permission::get();
    }

    public static function updatepermission($id , $permission)
    {
  	     $obj = permission::getOne($id);
  	     if(count($obj) > 0)
  	     {
   		     $obj -> permission = $permission;
  		     $obj -> save();
  	     }
    }

    public static function insert($permission)
    {
        $obj = new permission();
        $obj -> permission = $permission;
        $obj -> save();
        return $obj -> id;
    }

}


text:
<project>
    <property name="lib.dir"  value="libs"/>

    <path id="classpath">
        <fileset dir="${lib.dir}" includes="**/*.jar"/>
    </path>

    <target name="clean">
        <delete dir="classes"/>
    </target>

    <target name="compile">
        <mkdir dir="classes"/>
        <javac srcdir="src" destdir="classes" classpathref="classpath">
  		<compilerarg value="-Xlint:unchecked"/>
        </javac>
    </target>

    <target name="jar" depends="compile">
        <mkdir dir="jars"/>
        <mkdir dir="jar_tmp"/>

        <copy todir="jar_tmp">
            <fileset dir="classes" includes="**/*.class"/>
        </copy>

	<!-- want to create a single jar - so unjar all the libs we depend and add them to our jar -->
        <unjar dest="jar_tmp">
          <patternset>
              <include name="**/*.class"/>
          </patternset>
          <fileset dir="libs">
            <include name="**/opencsv-2.2.jar"/>
          </fileset>
        </unjar>

        <jar destfile="jars/splunk.jar" basedir="jar_tmp">
		<manifest>
 			<attribute name="DataWrapperClassName" value="com.splunk.udx.MedSplunkForeignDataWrapper" />
                        <attribute name="PluginFactoryClassName" value="com.splunk.udx.PostgresPersonalityFactory" />
                </manifest>
        </jar>
        <delete dir="jar_tmp" />
    </target>

    <!-- Creates an archive (SplunkLucidDb.tgz) including all files/docs needed during a release -->
    <target name="release" depends="jar">
        <delete dir="SplunkLucidDb" />
        <mkdir dir="SplunkLucidDb" />
        <copy file="jars/splunk.jar" todir="SplunkLucidDb/" />
        <copy todir="SplunkLucidDb">
            <fileset dir="build_files"/>
        </copy>
        <tar destfile="SplunkLucidDb.tgz" compression="gzip" >
	  <tarfileset dir="SplunkLucidDb/" prefix="SplunkLucidDb/">
	        <include name="*"/>
	  </tarfileset>
	</tar>
        <delete dir="SplunkLucidDb" />
    </target>

</project>


text:
define(["dojo/_base/declare",
        "dojo/_base/lang",
        "app/common/Templated",
        "dojo/text!./templates/MapPanel.html",
        "dojo/i18n!../nls/resources",
        "dojo/sniff",
        "dojo/dom-style",
        "dojo/dom-geometry"],
function(declare, lang, Templated, template, i18n, has, domStyle, domGeometry) {

  var oThisClass = declare([Templated], {

    i18n: i18n,
    templateString: template,

    mapWasInitialized: false,

    postCreate: function() {
      this.inherited(arguments);
    },

    addToMap: function(params) {
      var mapWindow  = this.mapFrameNode.contentWindow;
      if (mapWindow && typeof mapWindow.addToMapListener === "function") {
        mapWindow.addToMapListener(params);
      }
    },

    ensureMap: function(urlParams) {
      var url = "./viewer/index.html"; // TODO config this?
      if (!this.mapWasInitialized) {
        this.mapWasInitialized = true;
        if (urlParams) {
          var sProp = null, oProp = null, props = urlParams;
          for (sProp in props) {
            if (props.hasOwnProperty(sProp)) {
              oProp = props[sProp];
              if (typeof oProp !== "undefined" && oProp !== null) {
                if (url.indexOf("?") === -1) url += "?";
                else url += "&";
                url += sProp+"="+encodeURIComponent(oProp);
              }
            }
          }
        }
        //console.warn("viewerUrl",url);
        this.mapFrameNode.src = url;
      }
    }

  });

  return oThisClass;
});


text: ({"loadingState":"Zavádzanie...","errorState":"Nastala chyba"})


text:
same_timestamp="03120812"
changed_timestamp="03120813"

# Remove mirrored files.
rm generated/files/mirror_remove/foo.txt
rm generated/files/mirror_remove/symlink
touch -m -t "$changed_timestamp" generated/files/mirror_remove

rm generated/files/mirror_remove_time/foo.txt
touch -m -t "$same_timestamp" generated/files/mirror_remove_time

# Remove tracked files.
rm generated/files/track_remove/foo.txt
touch -m -t "$changed_timestamp" generated/files/track_remove


text:
package com.qiita.nimzo6689.jcalc.state;

import com.qiita.nimzo6689.jcalc.CalcContext;
import com.qiita.nimzo6689.jcalc.CalcModel;
import com.qiita.nimzo6689.jcalc.code.CalcNumber;
import com.qiita.nimzo6689.jcalc.code.Operator;
import java.math.BigDecimal;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 *
 * @author nimzo6689
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@ToString
public class RegisterAState implements ICalcState {

    private static final RegisterAState INSTANCE = new RegisterAState();

    public static RegisterAState getInstance() {
        return INSTANCE;
    }

    @Override
    public void onInputNumber(CalcContext context, CalcNumber number, CalcModel model) {
        model.setDisplay(number.appendNumberTo(model.getDisplay()));
    }

    @Override
    public void onInputOperator(CalcContext context, Operator operator, CalcModel model) {
        model.setRegisterA(model.getDisplayToBicDecimal());
        model.setOperator(operator);

        context.changeCalcStateTo(OperatorState.getInstance());
    }

    @Override
    public void onInputEqual(CalcContext context, CalcModel model) {
        context.changeCalcStateTo(ResultState.getInstance());
    }

    @Override
    public void onInputClear(CalcContext context, CalcModel model) {
        model.setRegisterA(BigDecimal.ZERO);
        model.setDisplay(CalcNumber.ZERO.getNumber());
    }

    @Override
    public void onInputSign(CalcModel model) {
        BigDecimal number = model.getDisplayToBicDecimal();
        if (number != BigDecimal.ZERO) {
            model.setDisplay(number.negate().toPlainString());
        }
    }
}


text:
package com.xtremelabs.robolectric.shadows;

import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Filter;
import android.widget.Filterable;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static com.xtremelabs.robolectric.Robolectric.shadowOf;
import static org.junit.Assert.assertTrue;

@RunWith(WithTestDefaultsRunner.class)
public class AutoCompleteTextViewTest {
    private AutoCompleteTextView autoCompleteTextView;

    @Before
    public void setUp() throws Exception {
        autoCompleteTextView = new AutoCompleteTextView(new Activity());
    }

    @Test
    public void shouldReturnAdapter() throws Exception {
        autoCompleteTextView.setAdapter(new AutoCompleteAdapter(1));
        assertTrue(shadowOf(autoCompleteTextView).getAdapter() instanceof AutoCompleteAdapter);
    }

    @Test
    public void shouldReturnItemClickListener() throws Exception {
        autoCompleteTextView.setOnItemClickListener(new AutoCompleteOnItemClickListener());
        assertTrue(shadowOf(autoCompleteTextView).getOnItemClickListener() instanceof AutoCompleteOnItemClickListener);
    }

    public static class AutoCompleteAdapter extends CountingAdapter implements Filterable {

        public AutoCompleteAdapter(int itemCount) {
            super(itemCount);
        }

        @Override
        public Filter getFilter() {
            return null;
        }
    }

    public static class AutoCompleteOnItemClickListener implements AdapterView.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        }
    }
}


text:
// <copyright file="ILockCleanupTask.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>

using JetBrains.Annotations;

namespace FubarDev.WebDavServer.Locking
{
    /// <summary>
    /// An interface for a background task that removes expired locks
    /// </summary>
    public interface ILockCleanupTask
    {
        /// <summary>
        /// Adds a lock to be tracked by this cleanup task.
        /// </summary>
        /// <param name="lockManager">The lock manager that created this active lock.</param>
        /// <param name="activeLock">The active lock to track</param>
        void Add([NotNull] ILockManager lockManager, [NotNull] IActiveLock activeLock);

        /// <summary>
        /// Removes the active lock so that it isn't tracked any more by this cleanup task.
        /// </summary>
        /// <param name="activeLock">The active lock to remove</param>
        void Remove([NotNull] IActiveLock activeLock);
    }
}


text:
import {frameRatio} from './calc';
import log from './logger';

export {setFrame, maximize, toggleMaximized};

interface FrameCache {
	screen: Rectangle;
	window: Rectangle;
	maximized?: {
		screen: Rectangle;
		window: Rectangle;
	};
}

const frameCache: Map<number, FrameCache> = new Map();

Event.on('windowDidClose', (win: Window) => {
	// Cleanup references to unmaximized window frames.
	frameCache.delete(win.hash());
});

function unmaximizedFrame(win: Window): Rectangle {
	let c = frameCache.get(win.hash());
	if (!c) {
		c = {
			screen: win.screen().flippedVisibleFrame(),
			window: win.frame(),
		};
	}
	const ratio = frameRatio(c.screen, win.screen().flippedVisibleFrame());
	return ratio(c.window);
}

function objEqual(a: {[key: string]: any}, b: {[key: string]: any}): boolean {
	if (typeof a !== 'object') {
		return a === b;
	}
	if (Object.keys(a).length !== Object.keys(b).length) {
		return false;
	}
	for (const key of Object.keys(a)) {
		if (typeof a[key] === 'object') {
			if (!objEqual(a[key], b[key])) {
				return false;
			}
		}
		if (a[key] !== b[key]) {
			return false;
		}
	}
	return true;
}

function isMaximized(win: Window): boolean {
	const cache = frameCache.get(win.hash());
	if (!cache || !cache.maximized) {
		return false;
	}

	log(win.frame(), cache.maximized.window);

	return (
		objEqual(win.screen().flippedVisibleFrame(), cache.maximized.screen) &&
		objEqual(win.frame(), cache.maximized.window)
	);
}

function toggleMaximized(win: Window): boolean {
	if (isMaximized(win)) {
		return setFrame(win, unmaximizedFrame(win));
	}
	return maximize(win);
}

function setFrame(win: Window, frame: Rectangle): boolean {
	const ok = win.setFrame(frame);
	if (ok) {
		frameCache.delete(win.hash());
	}
	return ok;
}

function maximize(win: Window): boolean {
	const previous = {
		screen: win.screen().flippedVisibleFrame(),
		window: win.frame(),
	};
	const ok = win.maximize();
	const id = win.hash();
	frameCache.set(id, {
		...previous,
		maximized: {
			screen: win.screen().flippedVisibleFrame(),
			window: win.frame(),
		},
	});
	return ok;
}


text:
{% extends "base.html" %}

{% block contents %}

      Welcome, {{username}} | Back | Logout

    <form method="post">

Edit Post

Subject

        <input type="text" name="subject" value="{{subject}}">

Blog

        <textarea name="content">{{content}}</textarea>

{{error}}

        <input class="submit" type="submit" value="Submit">
        <button class="submit" type="button" onclick="window.history.go(-1)" > Cancel </button>

    </form>

{% endblock %}


text:
from scriptine.misc import dry_guard, options
from scriptine import path

def test_guard():

    @dry_guard
    def guarded_func(foo):
        return True

    assert guarded_func('hello')

    options.dry = True
    assert not guarded_func('hello')

def test_path_guard():

    options.dry = True

    path('/tmp/foobarbaz.txt').install('hello', chmod=0644)

def teardown_module():
    options.dry = False


text:
package com.intellij.openapi.vcs.changes;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.util.concurrency.Semaphore;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.atomic.AtomicBoolean;

public class Waiter extends Task.Modal {
  private static final Logger LOG = Logger.getInstance(Waiter.class);

  @NotNull private final Runnable myRunnable;
  @NotNull private final AtomicBoolean myStarted = new AtomicBoolean();
  @NotNull private final Semaphore mySemaphore = new Semaphore();

  public Waiter(@NotNull Project project, @NotNull Runnable runnable, String title, boolean cancellable) {
    super(project, VcsBundle.message("change.list.manager.wait.lists.synchronization", title), cancellable);
    myRunnable = runnable;
    mySemaphore.down();
    setCancelText("Skip");
  }

  public void run(@NotNull ProgressIndicator indicator) {
    indicator.setIndeterminate(true);
    indicator.setText2(VcsBundle.message("commit.wait.util.synched.text"));

    if (!myStarted.compareAndSet(false, true)) {
      LOG.error("Waiter running under progress being started again.");
    }
    else {
      while (!mySemaphore.waitFor(500)) {
        indicator.checkCanceled();
      }
    }
  }

  @Override
  public void onCancel() {
    onSuccess();
  }

  @Override
  public void onSuccess() {
    // Be careful with changes here as "Waiter.onSuccess()" is explicitly invoked from "FictiveBackgroundable"
    if (!myProject.isDisposed()) {
      myRunnable.run();
      ChangesViewManager.getInstance(myProject).scheduleRefresh();
    }
  }

  public void done() {
    mySemaphore.up();
  }
}


text:
package com.hyq.interceptor;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hyq.domain.Privilege;
import com.hyq.domain.User;
import com.hyq.service.PrivilegeService;

/**
 * 权限拦截器
 * @author HYQ
 * 因为要把权限拦截放在登录拦截后面,所以这个拦截的是已经登录了的请求
 *
 */
public class PrivilegeInterceptor implements HandlerInterceptor
{
	@Autowired
	private PrivilegeService privilegeService;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		//ServletContext application = request.getServletContext();
	//	ApplicationContext ac =  WebApplicationContextUtils.getWebApplicationContext(application);
	//	PrivilegeService privilegeService = (PrivilegeService) ac.getBean("privilegeService");
	//
		System.out.println(privilegeService);

		//获取所有的  权限列表 AllPlist  ------------事先加载到application中
		List<String> urls = privilegeService.getAllUrl();

		//获取当前访问路径,并做处理
		String uri = request.getRequestURI();
		String realUri = "";

		// 如果带有? 则先去掉问号
		int questionPoint = uri.indexOf("?");
		if (questionPoint > -1) {
			uri = uri.substring(0, questionPoint);
		}

		// 去掉.action
		int pointPos = uri.indexOf(".action");
		if (pointPos > -1) {
			uri = uri.substring(0, pointPos);
		}

		// 去掉项目名
		String root = request.getContextPath();
		if (uri.indexOf(root) > -1) {
			 realUri = uri.substring(root.length());
		}
		//如果不在 AllPlist中,说明这个路径不需要控制,放行
		if(!urls.contains(realUri))
		{
			return true;
		}else//else 在列表中,说明要控制
		{

			//获取当前用户
			User currentUser = (User) request.getSession().getAttribute("currentUser");
			//获取当前用户的  自身权限列表      ------------------这个也需要事先加载
			List<String> userUrls = privilegeService.getUsersPrivilegeUrlByUserId(currentUser.getId());

			//如果自身权限列表为空,则表示无权限
			if(userUrls == null || userUrls.size()<1)
			{
				response.sendRedirect(request.getContextPath()+"/noPrivilege.jsp");
				return false;
			}

			//判断当前访问的路径是否在权限列表中
			for(String url : userUrls)
			{
				//如果在,放行
				if(urls.contains(url))
				{
					return true;
				}else{//如果不在,拦截,跳转到没有权限页面
					response.sendRedirect("/noPrivilege.jsp");
					return false;
				}
			}
		}
		return true;

		//另一种 思考方式:
		//if(有权限)  放行
		//else 拦截

		//把逻辑减少到  只需要关系判断是否有权限就行了
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}


text:
package tinysvg

import (
	"bytes"
	"errors"
	"fmt"
	"strconv"
	"strings"
)

const (
	TRANSPARENT = 0.0
	OPAQUE      = 1.0
)

type (
	Vec2 struct {
		X, Y float64
	}
	Pos    Vec2
	Radius Vec2
	Size   struct {
		W, H float64
	}
	Color struct {
		R int     // red, 0..255
		G int     // green, 0..255
		B int     // blue, 0..255
		A float64 // alpha, 0.0..1.0
		N string  // name (optional, will override the above values)
	}
	Font struct {
		Family string
		Size   int
	}
)

var ErrPair = errors.New("position pairs must be exactly two comma separated numbers")

// Create a new TinySVG document, where the width and height is defined in pixels, using the "px" suffix
func NewTinySVG(w, h int) (*Document, *Tag) {
	page := NewDocument([]byte(""), []byte(`<?xml version="1.0" encoding="UTF-8"?>`))
	svg := page.root.AddNewTag([]byte("svg"))
	svg.AddAttrib("xmlns", []byte("http://www.w3.org/2000/svg"))
	svg.AddAttrib("version", []byte("1.2"))
	svg.AddAttrib("baseProfile", []byte("tiny"))
	svg.AddAttrib("viewBox", []byte(fmt.Sprintf("%d %d %d %d", 0, 0, w, h)))
	svg.AddAttrib("width", []byte(fmt.Sprintf("%dpx", w)))
	svg.AddAttrib("height", []byte(fmt.Sprintf("%dpx", h)))
	return page, svg
}

// NewTinySVG2 creates new TinySVG 1.2 image. Pos and Size defines the viewbox
func NewTinySVG2(p *Pos, s *Size) (*Document, *Tag) {
	// No page title is needed when building an SVG tag tree
	page := NewDocument([]byte(""), []byte(`<?xml version="1.0" encoding="UTF-8"?>`))

	// No longer needed for TinySVG 1.2. See: https://www.w3.org/TR/SVGTiny12/intro.html#defining
	// <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">

	// Add the root tag
	svg := page.root.AddNewTag([]byte("svg"))
	svg.AddAttrib("xmlns", []byte("http://www.w3.org/2000/svg"))
	svg.AddAttrib("version", []byte("1.2"))
	svg.AddAttrib("baseProfile", []byte("tiny"))
	svg.AddAttrib("viewBox", []byte(fmt.Sprintf("%f %f %f %f", p.X, p.Y, s.W, s.H)))
	return page, svg
}

func f2b(x float64) []byte {
	fs := fmt.Sprintf("%f", x)
	// Drop ".0" if the number ends with that
	if strings.HasSuffix(fs, ".0") {
		return []byte(fs[:len(fs)-2])
	}
	// Drop ".000000" if the number ends with that
	if strings.HasSuffix(fs, ".000000") {
		return []byte(fs[:len(fs)-7])
	}
	return []byte(fs)
}

// Rect a rectangle, given x and y position, width and height.
// No color is being set.
func (svg *Tag) Rect2(p *Pos, s *Size, c *Color) *Tag {
	rect := svg.AddNewTag([]byte("rect"))
	rect.AddAttrib("x", f2b(p.X))
	rect.AddAttrib("y", f2b(p.Y))
	rect.AddAttrib("width", f2b(s.W))
	rect.AddAttrib("height", f2b(s.H))
	rect.Fill2(c)
	return rect
}

// RoundedRect2 a rectangle, given x and y position, width and height.
// No color is being set.
func (svg *Tag) RoundedRect2(p *Pos, r *Radius, s *Size, c *Color) *Tag {
	rect := svg.AddNewTag([]byte("rect"))
	rect.AddAttrib("x", f2b(p.X))
	rect.AddAttrib("y", f2b(p.Y))
	rect.AddAttrib("rx", f2b(r.X))
	rect.AddAttrib("ry", f2b(r.Y))
	rect.AddAttrib("width", f2b(s.W))
	rect.AddAttrib("height", f2b(s.H))
	rect.Fill2(c)
	return rect
}

// Text adds text. No color is being set
func (svg *Tag) Text2(p *Pos, f *Font, message string, c *Color) *Tag {
	text := svg.AddNewTag([]byte("text"))
	text.AddAttrib("x", f2b(p.X))
	text.AddAttrib("y", f2b(p.Y))
	text.AddAttrib("font-family", []byte(f.Family))
	text.AddAttrib("font-size", []byte(strconv.Itoa(f.Size)))
	text.Fill2(c)
	text.AddContent([]byte(message))
	return text
}

// Circle adds a circle, given a position, radius and color
func (svg *Tag) Circle2(p *Pos, radius int, c *Color) *Tag {
	circle := svg.AddNewTag([]byte("circle"))
	circle.AddAttrib("cx", f2b(p.X))
	circle.AddAttrib("cy", f2b(p.Y))
	circle.AddAttrib("r", []byte(strconv.Itoa(radius)))
	circle.Fill2(c)
	return circle
}

// Circle adds a circle, given a position, radius and color
func (svg *Tag) Circlef(p *Pos, radius float64, c *Color) *Tag {
	circle := svg.AddNewTag([]byte("circle"))
	circle.AddAttrib("cx", f2b(p.X))
	circle.AddAttrib("cy", f2b(p.Y))
	circle.AddAttrib("r", f2b(radius))
	circle.Fill2(c)
	return circle
}

// Ellipse adds an ellipse with a given position (x,y) and radius (rx, ry).
func (svg *Tag) Ellipse2(p *Pos, r *Radius, c *Color) *Tag {
	ellipse := svg.AddNewTag([]byte("ellipse"))
	ellipse.AddAttrib("cx", f2b(p.X))
	ellipse.AddAttrib("cy", f2b(p.Y))
	ellipse.AddAttrib("rx", f2b(r.X))
	ellipse.AddAttrib("ry", f2b(r.Y))
	ellipse.Fill2(c)
	return ellipse
}

// Line adds a line from (x1, y1) to (x2, y2) with a given stroke width and color
func (svg *Tag) Line2(p1, p2 *Pos, thickness int, c *Color) *Tag {
	line := svg.AddNewTag([]byte("line"))
	line.AddAttrib("x1", f2b(p1.X))
	line.AddAttrib("y1", f2b(p1.Y))
	line.AddAttrib("x2", f2b(p2.X))
	line.AddAttrib("y2", f2b(p2.Y))
	line.Thickness(thickness)
	line.Stroke2(c)
	return line
}

// Triangle adds a colored triangle
func (svg *Tag) Triangle2(p1, p2, p3 *Pos, c *Color) *Tag {
	triangle := svg.AddNewTag([]byte("path"))
	triangle.AddAttrib("d", []byte(fmt.Sprintf("M %f %f L %f %f L %f %f L %f %f", p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y, p1.X, p1.Y)))
	triangle.Fill2(c)
	return triangle
}

// Poly2 adds a colored path with 4 points
func (svg *Tag) Poly2(p1, p2, p3, p4 *Pos, c *Color) *Tag {
	poly4 := svg.AddNewTag([]byte("path"))
	poly4.AddAttrib("d", []byte(fmt.Sprintf("M %f %f L %f %f L %f %f L %f %f L %f %f", p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y, p4.X, p4.Y, p1.X, p1.Y)))
	poly4.Fill2(c)
	return poly4
}

// Fill selects the fill color that will be used when drawing
func (svg *Tag) Fill2(c *Color) {
	// If no color name is given and the color is transparent, don't set a fill color
	if (c == nil) || (len(c.N) == 0 && c.A == TRANSPARENT) {
		return
	}
	svg.AddAttrib("fill", c.Bytes())
}

// Stroke selects the stroke color that will be used when drawing
func (svg *Tag) Stroke2(c *Color) {
	// If no color name is given and the color is transparent, don't set a stroke color
	if (c == nil) || (len(c.N) == 0 && c.A == TRANSPARENT) {
		return
	}
	svg.AddAttrib("stroke", c.Bytes())
}

// RGBBytes converts r, g and b (integers in the range 0..255)
// to a color string on the form "#nnnnnn".
func RGBBytes(r, g, b int) []byte {
	rs := strconv.FormatInt(int64(r), 16)
	gs := strconv.FormatInt(int64(g), 16)
	bs := strconv.FormatInt(int64(b), 16)
	if len(rs) == 1 {
		rs = "0" + rs
	}
	if len(gs) == 1 {
		gs = "0" + gs
	}
	if len(bs) == 1 {
		bs = "0" + bs
	}
	return []byte("#" + rs + gs + bs)
}

// RGBABytes converts integers r, g and b (the color) and also
// a given alpha (opacity) to a color-string on the form
// "rgba(255, 255, 255, 1.0)".
func RGBABytes(r, g, b int, a float64) []byte {
	return []byte(fmt.Sprintf("rgba(%d, %d, %d, %f)", r, g, b, a))
}

// RGBA creates a new Color with the given red, green and blue values.
// The colors are in the range 0..255
func RGB(r, g, b int) *Color {
	return &Color{r, g, b, OPAQUE, ""}
}

// RGBA creates a new Color with the given red, green, blue and alpha values.
// Alpha is between 0 and 1, the rest are 0..255.
// For the alpha value, 0 is transparent and 1 is opaque.
func RGBA(r, g, b int, a float64) *Color {
	return &Color{r, g, b, a, ""}
}

// ColorByName creates a new Color with a given name, like "blue"
func ColorByName(name string) *Color {
	return &Color{N: name}
}

// NewColor is the same as ColorByName
func NewColor(name string) *Color {
	return ColorByName(name)
}

// String returns the color as an RGB (#1234FF) string
// or as an RGBA (rgba(0, 1, 2 ,3)) string.
func (c *Color) Bytes() []byte {
	// Return an empty string if nil
	if c == nil {
		return make([]byte, 0)
	}
	// Return the name, if specified
	if len(c.N) != 0 {
		return []byte(c.N)
	}
	// Return a regular RGB string if alpha is 1.0
	if c.A == OPAQUE {
		// Generate a rgb string
		return RGBBytes(c.R, c.G, c.B)
	}
	// Generate a rgba string if alpha is < 1.0
	return RGBABytes(c.R, c.G, c.B, c.A)
}

// --- Convenience functions and functions for backward compatibility ---

func NewTinySVGi(x, y, w, h int) (*Document, *Tag) {
	return NewTinySVG2(&Pos{float64(x), float64(y)}, &Size{float64(w), float64(h)})
}

func NewTinySVGf(x, y, w, h float64) (*Document, *Tag) {
	return NewTinySVG2(&Pos{x, y}, &Size{w, h})
}

// AddRect adds a rectangle, given x and y position, width and height.
// No color is being set.
func (svg *Tag) AddRect(x, y, w, h int) *Tag {
	return svg.Rect2(&Pos{float64(x), float64(y)}, &Size{float64(w), float64(h)}, nil)
}

// AddRoundedRect adds a rectangle, given x and y position, radius x, radius y, width and height.
// No color is being set.
func (svg *Tag) AddRoundedRect(x, y, rx, ry, w, h int) *Tag {
	return svg.RoundedRect2(&Pos{float64(x), float64(y)}, &Radius{float64(rx), float64(ry)}, &Size{float64(w), float64(h)}, nil)
}

// AddRectf adds a rectangle, given x and y position, width and height.
// No color is being set.
func (svg *Tag) AddRectf(x, y, w, h float64) *Tag {
	return svg.Rect2(&Pos{x, y}, &Size{w, h}, nil)
}

// AddRoundedRectf adds a rectangle, given x and y position, radius x, radius y, width and height.
// No color is being set.
func (svg *Tag) AddRoundedRectf(x, y, rx, ry, w, h float64) *Tag {
	return svg.RoundedRect2(&Pos{x, y}, &Radius{rx, ry}, &Size{w, h}, nil)
}

// AddText adds text. No color is being set
func (svg *Tag) AddText(x, y, fontSize int, fontFamily, text string) *Tag {
	return svg.Text2(&Pos{float64(x), float64(y)}, &Font{fontFamily, fontSize}, text, nil)
}

// Box adds a rectangle, given x and y position, width, height and color
func (svg *Tag) Box(x, y, w, h int, color string) *Tag {
	return svg.Rect2(&Pos{float64(x), float64(y)}, &Size{float64(w), float64(h)}, ColorByName(color))
}

// AddCircle adds a circle Add a circle, given a position (x, y) and a radius.
// No color is being set.
func (svg *Tag) AddCircle(x, y, radius int) *Tag {
	return svg.Circle2(&Pos{float64(x), float64(y)}, radius, nil)
}

// AddCirclef adds a circle Add a circle, given a position (x, y) and a radius.
// No color is being set.
func (svg *Tag) AddCirclef(x, y, radius float64) *Tag {
	return svg.Circlef(&Pos{x, y}, radius, nil)
}

// AddEllipse adds an ellipse with a given position (x,y) and radius (rx, ry).
// No color is being set.
func (svg *Tag) AddEllipse(x, y, rx, ry int) *Tag {
	return svg.Ellipse2(&Pos{float64(x), float64(y)}, &Radius{float64(rx), float64(ry)}, nil)
}

// AddEllipsef adds an ellipse with a given position (x,y) and radius (rx, ry).
// No color is being set.
func (svg *Tag) AddEllipsef(x, y, rx, ry float64) *Tag {
	return svg.Ellipse2(&Pos{x, y}, &Radius{rx, ry}, nil)
}

// Line adds a line from (x1, y1) to (x2, y2) with a given stroke width and color
func (svg *Tag) Line(x1, y1, x2, y2, thickness int, color string) *Tag {
	return svg.Line2(&Pos{float64(x1), float64(y1)}, &Pos{float64(x2), float64(y2)}, thickness, ColorByName(color))
}

// Triangle adds a colored triangle
func (svg *Tag) Triangle(x1, y1, x2, y2, x3, y3 int, color string) *Tag {
	return svg.Triangle2(&Pos{float64(x1), float64(y1)}, &Pos{float64(x2), float64(y2)}, &Pos{float64(x3), float64(y3)}, ColorByName(color))
}

// Poly4 adds a colored path with 4 points
func (svg *Tag) Poly4(x1, y1, x2, y2, x3, y3, x4, y4 int, color string) *Tag {
	return svg.Poly2(&Pos{float64(x1), float64(y1)}, &Pos{float64(x2), float64(y2)}, &Pos{float64(x3), float64(y3)}, &Pos{float64(x4), float64(y4)}, ColorByName(color))
}

// Circle adds a circle, given x and y position, radius and color
func (svg *Tag) Circle(x, y, radius int, color string) *Tag {
	return svg.Circle2(&Pos{float64(x), float64(y)}, radius, ColorByName(color))
}

// Ellipse adds an ellipse, given x and y position, radiuses and color
func (svg *Tag) Ellipse(x, y, xr, yr int, color string) *Tag {
	return svg.Ellipse2(&Pos{float64(x), float64(y)}, &Radius{float64(xr), float64(yr)}, ColorByName(color))
}

// Fill selects the fill color that will be used when drawing
func (svg *Tag) Fill(color string) {
	svg.AddAttrib("fill", []byte(color))
}

// ColorBytes converts r, g and b (integers in the range 0..255)
// to a color string on the form "#nnnnnn".
func ColorBytes(r, g, b int) []byte {
	return RGB(r, g, b).Bytes()
}

// ColorBytesAlpha converts integers r, g and b (the color) and also
// a given alpha (opacity) to a color-string on the form
// "rgba(255, 255, 255, 1.0)".
func ColorBytesAlpha(r, g, b int, a float64) []byte {
	return RGBA(r, g, b, a).Bytes()
}

// Pixel creates a rectangle that is 1 wide with the given color.
// Note that the size of the "pixel" depends on how large the viewBox is.
func (svg *Tag) Pixel(x, y, r, g, b int) *Tag {
	return svg.Rect2(&Pos{float64(x), float64(y)}, &Size{1.0, 1.0}, RGB(r, g, b))
}

// AlphaDot creates a small circle that can be transparent.
// Takes a position (x, y) and a color (r, g, b, a).
func (svg *Tag) AlphaDot(x, y, r, g, b int, a float32) *Tag {
	return svg.Circle2(&Pos{float64(x), float64(y)}, 1, RGBA(r, g, b, float64(a)))
}

// Dot adds a small colored circle.
// Takes a position (x, y) and a color (r, g, b).
func (svg *Tag) Dot(x, y, r, g, b int) *Tag {
	return svg.Circle2(&Pos{float64(x), float64(y)}, 1, RGB(r, g, b))
}

// Text adds text, with a color
func (svg *Tag) Text(x, y, fontSize int, fontFamily, text, color string) *Tag {
	return svg.Text2(&Pos{float64(x), float64(y)}, &Font{fontFamily, fontSize}, text, ColorByName(color))
}

// ---------------------------------

const (
	YES  = 0
	NO   = 1
	AUTO = 2
)

type YesNoAuto int

// Create a new Yes/No/Auto struct. If auto is true, it overrides the yes value.
func NewYesNoAuto(yes bool, auto bool) YesNoAuto {
	if auto {
		return AUTO
	}
	if yes {
		return YES
	}
	return NO
}

func (yna YesNoAuto) Bytes() []byte {
	switch yna {
	case YES:
		return []byte("true")
	case AUTO:
		return []byte("auto")
	default:
		return []byte("false")
	}
}

// Focusable sets the "focusable" attribute to either true, false or auto
// If "auto" is true, it overrides the value of "yes".
func (svg *Tag) Focusable(yes bool, auto bool) {
	svg.AddAttrib("focusable", NewYesNoAuto(yes, auto).Bytes())
}

// Thickness sets the stroke-width attribute
func (svg *Tag) Thickness(thickness int) {
	svg.AddAttrib("stroke-width", []byte(strconv.Itoa(thickness)))
}

// Polyline adds a set of connected straight lines, an open shape
func (svg *Tag) Polyline(points []*Pos, c *Color) *Tag {
	polyline := svg.AddNewTag([]byte("polyline"))
	var buf bytes.Buffer
	lastIndex := len(points) - 1
	for i, p := range points {
		buf.Write(f2b(p.X))
		buf.WriteByte(',')
		buf.Write(f2b(p.Y))
		if i != lastIndex {
			buf.WriteByte(' ')
		}
	}
	polyline.AddAttrib("points", buf.Bytes())
	return polyline
}

// Polygon adds a set of connected straight lines, a closed shape
func (svg *Tag) Polygon(points []*Pos, c *Color) *Tag {
	polygon := svg.AddNewTag([]byte("polygon"))
	var buf bytes.Buffer
	lastIndex := len(points) - 1
	for i, p := range points {
		buf.Write(f2b(p.X))
		buf.WriteByte(',')
		buf.Write(f2b(p.Y))
		if i != lastIndex {
			buf.WriteByte(' ')
		}
	}
	polygon.AddAttrib("points", buf.Bytes())
	polygon.Fill2(c)
	return polygon
}

func NewPos(xString, yString string) (*Pos, error) {
	x, err := strconv.ParseFloat(xString, 64)
	if err != nil {
		return nil, err
	}
	y, err := strconv.ParseFloat(yString, 64)
	if err != nil {
		return nil, err
	}
	return &Pos{x, y}, nil
}

func NewPosf(x, y float64) *Pos {
	return &Pos{x, y}
}

func PointsFromString(pointString string) ([]*Pos, error) {
	points := make([]*Pos, 0)
	for _, positionPair := range strings.Split(pointString, " ") {
		elements := strings.Split(positionPair, ",")
		if len(elements) != 2 {
			return nil, ErrPair
		}
		p, err := NewPos(elements[0], elements[1])
		if err != nil {
			return nil, err
		}
		points = append(points, p)
	}
	return points, nil
}

// Describe can be used for adding a description to the SVG header
func (svg *Tag) Describe(description string) {
	desc := svg.AddNewTag([]byte("desc"))
	desc.AddContent([]byte(description))
}


text:
$(document).ready(function() {
	// store the json file url in url
	var url = players.json;
	// Use the jQuery method getJSON() to first get and parse the JSON file to an [] of {}'s
	// Then passes the returned parsed [] to as the parameter in the callback function(param)
	$.getJSON(url, function(response) {
		// Declared an empty string template var to hold html
		var template = '';
		// Then to iterate through each {} in the response [] I would use the jQuery .each() method
		// Takes the response [] as an arg then the callback () is passed the index and values of each {}
		$.each(response, function(index, player) {
			// Concats all the html elements needed in addition to giving each objects property val
			template += '
' +
				'
' +
					'' +
					'
' +
						'
' + player.name + ' #' + player.number + '
' +
						'
Position: ' + player.position + '
' +
						'
Age: ' + player.age + '
' +
						'
Experince: ' + player.experience + ' year(s)
' +
						'
College: ' + player.college + '
' +
					'
' +
				'
' +
			'
';
		});
		// Function selects the html element with the id of output gives the value of the template var
		$('#output').html(template);
	});
});

// ===================================================================================================

// Create a new http request object
var request = new XMLHttpRequest();

// Onreadeystatechange method Will run whenever a change in state occurs
request.onreadystatechange = function() {
	// When the readyState property returns a 4 it will run execute the given code
	if (request.readyState === 4) {
		// Will execute if the status property is 200 (O.K.)
		if (request.status === 200) {
			// Stores the parsed Json string(Now an Array Object) in players
			var players = JSON.parse(request.responseText),
					template = '';
			// Iterates through each item of players[]
			for (var i = 0; i < players.length; i++) {
				// Each []index (which is an {}) is passed in the player
				player = players[i];
				// Concats all the html elements needed in addition to giving each objects property val
				template += '
' +
					'
' +
						'' +
						'
' +
							'
' + player.name + ' #' + player.number + '
' +
							'
Position: ' + player.position + '
' +
							'
Age: ' + player.age + '
' +
							'
Experince: ' + player.experience + ' year(s)
' +
							'
College: ' + player.college + '
' +
						'
' +
					'
' +
				'
';
			}
			// Grabs the target element by # and stores the finished template within the terget element
			document.getElementById('output').innerHTML = template;
		}
	}
};

// The open method takes tow parameters (this creates the request)
// 1) http method 'GET' to send the request for data to server
// 2) the url that points to the file you want
request.open('GET', 'players.json');

// Sends out the request to the server
request.send();


text:
package com.facebook.buck.cxx;

import com.facebook.buck.core.model.FlavorDomain;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.CxxPlatformUtils;

public class CxxTestUtils {
  public static FlavorDomain<CxxPlatform> createDefaultPlatforms() {
    return FlavorDomain.of("C/C++ Platform", CxxPlatformUtils.DEFAULT_PLATFORM);
  }
}


text:
#include <stdint.h>
#include <string>
#include <set>

#include "application_manager/commands/mobile/set_global_properties_request.h"

#include "gtest/gtest.h"
#include "application_manager/commands/command_request_test.h"
#include "application_manager/mock_application.h"
#include "application_manager/mock_application_manager.h"
#include "application_manager/mock_message_helper.h"
#include "application_manager/event_engine/event.h"
#include "application_manager/mock_hmi_interface.h"

namespace test {
namespace components {
namespace commands_test {
namespace mobile_commands_test {
namespace set_global_properties_request {

namespace am = application_manager;
using am::commands::SetGlobalPropertiesRequest;
using am::commands::CommandImpl;
using am::commands::MessageSharedPtr;
using am::MockMessageHelper;
using am::CommandsMap;
using utils::custom_string::CustomString;
using ::utils::SharedPtr;
using ::testing::_;
using ::testing::Mock;
using ::testing::Return;
using ::testing::ReturnRef;

namespace {
const int32_t kCommandId = 1;
const uint32_t kAppId = 1u;
const uint32_t kCmdId = 1u;
const uint32_t kConnectionKey = 1u;
const std::string kText = "one";
const uint32_t kPosition = 1u;
}  // namespace

class SetGlobalPropertiesRequestTest
    : public CommandRequestTest<CommandsTestMocks::kIsNice> {
 public:
  SetGlobalPropertiesRequestTest()
      : mock_message_helper_(*MockMessageHelper::message_helper_mock())
      , mock_app_(CreateMockApp()) {}

  MessageSharedPtr CreateFullParamsUISO() {
    MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);
    (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;
    smart_objects::SmartObject menu_params =
        smart_objects::SmartObject(smart_objects::SmartType_Map);
    menu_params[am::strings::position] = 10;
    menu_params[am::strings::menu_name] = "LG";

    smart_objects::SmartObject msg_params =
        smart_objects::SmartObject(smart_objects::SmartType_Map);
    msg_params[am::strings::cmd_id] = kCmdId;
    msg_params[am::strings::menu_params] = menu_params;
    msg_params[am::strings::app_id] = kAppId;
    msg_params[am::strings::cmd_icon] = 1;
    msg_params[am::strings::cmd_icon][am::strings::value] = "10";
    msg_params[am::strings::vr_help_title] = "vr_help_title";
    msg_params[am::strings::vr_help][0][am::strings::text] = "vr_help";
    msg_params[am::strings::vr_help][0][am::strings::position] = 1u;
    msg_params[am::strings::help_prompt][0][am::strings::text] = "help_promt";
    (*msg)[am::strings::msg_params] = msg_params;

    return msg;
  }

  MessageSharedPtr CreateMsgParams() {
    MessageSharedPtr msg = CreateMessage();
    (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;
    (*msg)[am::strings::msg_params][am::strings::app_id] = kAppId;
    return msg;
  }

  void VRArraySetupHelper(MessageSharedPtr msg,
                          SmartObject& vr_help_title,
                          SmartObject& vr_help_array) {
    (*msg)[am::strings::msg_params][am::strings::vr_help_title] = vr_help_title;
    vr_help_array[0] = SmartObject(smart_objects::SmartType_Map);
    vr_help_array[0][am::strings::text] = kText;
    vr_help_array[0][am::strings::position] = kPosition;
    (*msg)[am::strings::msg_params][am::strings::vr_help] = vr_help_array;
  }

  void OnEventUISetupHelper(MessageSharedPtr msg,
                            SharedPtr<SetGlobalPropertiesRequest> command) {
    SmartObject vr_help_title("yes");
    SmartObject vr_help_array(smart_objects::SmartType_Array);
    VRArraySetupHelper(msg, vr_help_title, vr_help_array);
    EXPECT_CALL(mock_message_helper_,
                VerifyImageVrHelpItems(vr_help_array, _, _))
        .WillOnce((Return(mobile_apis::Result::SUCCESS)));
    EXPECT_CALL(app_mngr_,
                RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
    EXPECT_CALL(*mock_app_, set_vr_help_title(vr_help_title));
    EXPECT_CALL(*mock_app_, set_vr_help(vr_help_array));
    EXPECT_CALL(*mock_app_, vr_help_title()).WillOnce(Return(&vr_help_title));
    EXPECT_CALL(*mock_app_, vr_help()).WillOnce(Return(&vr_help_array));
    EXPECT_CALL(*mock_app_, set_menu_title(_)).Times(0);
    EXPECT_CALL(*mock_app_, set_menu_icon(_)).Times(0);
    EXPECT_CALL(*mock_app_, set_keyboard_props(_)).Times(0);
    EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId));

    command->Run();
  }

  void OnEventTTSSetupHelper(MessageSharedPtr msg,
                             SharedPtr<SetGlobalPropertiesRequest> command) {
    SmartObject help_prompt(smart_objects::SmartType_Array);
    help_prompt[0][am::strings::text] = "Help_Prompt_One";
    (*msg)[am::strings::msg_params][am::strings::help_prompt] = help_prompt;
    SmartObject timeout_prompt(smart_objects::SmartType_Array);
    timeout_prompt[0][am::strings::text] = "Timeout_Prompt_One";
    (*msg)[am::strings::msg_params][am::strings::timeout_prompt] =
        timeout_prompt;

    EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
    EXPECT_CALL(app_mngr_,
                RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
    SmartObject vr_help_title("title");
    EXPECT_CALL(*mock_app_, vr_help_title()).WillOnce(Return(&vr_help_title));
    EXPECT_CALL(*mock_app_, set_help_prompt(help_prompt));
    EXPECT_CALL(*mock_app_, help_prompt()).WillOnce(Return(&help_prompt));
    EXPECT_CALL(*mock_app_, set_timeout_prompt(timeout_prompt));
    EXPECT_CALL(*mock_app_, timeout_prompt()).WillOnce(Return(&timeout_prompt));
    EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId));

    command->Run();
  }

  void EmptyExpectationsSetupHelper() {
    EXPECT_CALL(*mock_app_, set_vr_help_title(_)).Times(0);
    EXPECT_CALL(*mock_app_, set_vr_help(_)).Times(0);
    EXPECT_CALL(*mock_app_, vr_help_title()).Times(0);
    EXPECT_CALL(*mock_app_, vr_help()).Times(0);
    EXPECT_CALL(*mock_app_, set_menu_title(_)).Times(0);
    EXPECT_CALL(*mock_app_, set_menu_icon(_)).Times(0);
    EXPECT_CALL(*mock_app_, set_keyboard_props(_)).Times(0);
    EXPECT_CALL(*mock_app_, app_id()).Times(0);
  }

  void ExpectInvalidData() {
    EXPECT_CALL(app_mngr_,
                ManageMobileCommand(
                    MobileResultCodeIs(mobile_apis::Result::INVALID_DATA),
                    am::commands::Command::ORIGIN_SDL));
  }

  void ExpectVerifyImageVrHelpSuccess(SmartObject& smart_obj) {
    EXPECT_CALL(app_mngr_, application(kConnectionKey))
        .WillOnce(Return(mock_app_));
    EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(smart_obj, _, _))
        .WillOnce(Return(mobile_apis::Result::SUCCESS));
    EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(_)).Times(0);
  }

  void ExpectVerifyImageVrHelpUnsuccess() {
    EXPECT_CALL(app_mngr_, application(kConnectionKey))
        .WillOnce(Return(mock_app_));
    EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
    EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(_)).Times(0);
  }

  void ExpectVerifyImageSuccess(SmartObject& smart_obj) {
    EXPECT_CALL(app_mngr_, application(kConnectionKey))
        .WillOnce(Return(mock_app_));
    EXPECT_CALL(mock_message_helper_, VerifyImage(smart_obj, _, _))
        .WillOnce(Return(mobile_apis::Result::SUCCESS));
    EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(_)).Times(0);
  }

  void SetUp() OVERRIDE {
    ON_CALL(app_mngr_, application(kConnectionKey))
        .WillByDefault(Return(mock_app_));
    ON_CALL(*mock_app_, app_id()).WillByDefault(Return(kConnectionKey));
    ON_CALL(mock_hmi_interfaces_,
            GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
        .WillByDefault(Return(am::HmiInterfaces::STATE_AVAILABLE));
  }

  void TearDown() OVERRIDE {
    Mock::VerifyAndClearExpectations(&mock_message_helper_);
  }

  void ResultCommandExpectations(MessageSharedPtr msg,
                                 const std::string& info) {
    EXPECT_EQ((*msg)[am::strings::msg_params][am::strings::success].asBool(),
              true);
    EXPECT_EQ(
        (*msg)[am::strings::msg_params][am::strings::result_code].asInt(),
        static_cast<int32_t>(hmi_apis::Common_Result::UNSUPPORTED_RESOURCE));
    EXPECT_EQ((*msg)[am::strings::msg_params][am::strings::info].asString(),
              info);
  }

  void ExpectationsHmiInterface_Run() {
    EXPECT_CALL(
        mock_hmi_interfaces_,
        GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
        .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_UI));
    EXPECT_CALL(
        mock_hmi_interfaces_,
        GetInterfaceFromFunction(hmi_apis::FunctionID::TTS_SetGlobalProperties))
        .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_TTS));
    ON_CALL(mock_hmi_interfaces_,
            GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
        .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
    ON_CALL(mock_hmi_interfaces_,
            GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_TTS))
        .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
  }
  sync_primitives::Lock lock_;
  MockMessageHelper& mock_message_helper_;
  MockAppPtr mock_app_;
};

TEST_F(SetGlobalPropertiesRequestTest,
       OnEvent_UIHmiSendSuccess_UNSUPPORTED_RESOURCE) {
  MessageSharedPtr msg_vr = CreateFullParamsUISO();
  (*msg_vr)[am::strings::msg_params][am::strings::vr_commands][0] =
      "vr_command";

  utils::SharedPtr<SetGlobalPropertiesRequest> command =
      CreateCommand<SetGlobalPropertiesRequest>(msg_vr);

  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  const smart_objects::SmartObject* vr_help_title =
      &((*msg_vr)[am::strings::msg_params][am::strings::vr_help_title]);
  const smart_objects::SmartObject* vr_help =
      &((*msg_vr)[am::strings::msg_params][am::strings::vr_help]);
  const smart_objects::SmartObject* vr_help_prompt =
      &((*msg_vr)[am::strings::msg_params][am::strings::help_prompt]);
  ON_CALL(*mock_app_, vr_help_title()).WillByDefault(Return(vr_help_title));
  ON_CALL(*mock_app_, vr_help()).WillByDefault(Return(vr_help));
  ON_CALL(*mock_app_, help_prompt()).WillByDefault(Return(vr_help_prompt));

  ExpectationsHmiInterface_Run();

  MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);
  (*msg)[am::strings::params][am::hmi_response::code] =
      hmi_apis::Common_Result::UNSUPPORTED_RESOURCE;
  (*msg)[am::strings::msg_params][am::strings::cmd_id] = kCommandId;
  (*msg)[am::strings::msg_params][am::strings::info] =
      "UI is not supported by system";

  Event event(hmi_apis::FunctionID::UI_SetGlobalProperties);
  event.set_smart_object(*msg);

  ON_CALL(mock_message_helper_,
          VerifyImageVrHelpItems(
              (*msg_vr)[am::strings::msg_params][am::strings::vr_help], _, _))
      .WillByDefault(Return(mobile_apis::Result::SUCCESS));

  ON_CALL(mock_message_helper_, VerifyImage(_, _, _))
      .WillByDefault(Return(mobile_apis::Result::SUCCESS));

  (*msg_vr)[am::strings::params][am::hmi_response::code] =
      hmi_apis::Common_Result::SUCCESS;
  Event event_vr(hmi_apis::FunctionID::TTS_SetGlobalProperties);
  event_vr.set_smart_object(*msg_vr);

  command->Run();
  command->on_event(event_vr);

  MessageSharedPtr ui_command_result;
  EXPECT_CALL(
      app_mngr_,
      ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL))
      .WillOnce(DoAll(SaveArg<0>(&ui_command_result), Return(true)));

  command->on_event(event);

  ResultCommandExpectations(ui_command_result, "UI is not supported by system");
}

TEST_F(SetGlobalPropertiesRequestTest, OnEvent_SUCCESS_Expect_MessageNotSend) {
  MessageSharedPtr response = CreateMessage(smart_objects::SmartType_Map);
  (*response)[am::strings::params][am::hmi_response::code] =
      hmi_apis::Common_Result::SUCCESS;
  (*response)[am::strings::msg_params][am::strings::info] = "test";

  am::event_engine::Event event(hmi_apis::FunctionID::TTS_SetGlobalProperties);
  event.set_smart_object(*response);

  utils::SharedPtr<SetGlobalPropertiesRequest> command =
      CreateCommand<SetGlobalPropertiesRequest>(response);

  EXPECT_CALL(
      app_mngr_,
      ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL))
      .Times(0);
  command->on_event(event);
}

TEST_F(SetGlobalPropertiesRequestTest,
       OnEvent_UNSUPPORTED_RESOURCE_Expect_false) {
  MessageSharedPtr response = CreateMessage(smart_objects::SmartType_Map);
  (*response)[am::strings::params][am::hmi_response::code] =
      hmi_apis::Common_Result::SUCCESS;
  (*response)[am::strings::params][am::strings::connection_key] =
      kConnectionKey;
  (*response)[am::strings::msg_params][am::strings::info] = "qwe";

  am::event_engine::Event event_tts(
      hmi_apis::FunctionID::TTS_SetGlobalProperties);
  event_tts.set_smart_object(*response);
  am::event_engine::Event event_ui(
      hmi_apis::FunctionID::UI_SetGlobalProperties);
  event_tts.set_smart_object(*response);
  utils::SharedPtr<SetGlobalPropertiesRequest> command =
      CreateCommand<SetGlobalPropertiesRequest>(response);

  ON_CALL(mock_message_helper_, HMIToMobileResult(_))
      .WillByDefault(Return(mobile_apis::Result::UNSUPPORTED_RESOURCE));

  EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(_))
      .WillRepeatedly(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  MessageSharedPtr response_to_mobile;
  EXPECT_CALL(
      app_mngr_,
      ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL))
      .WillOnce(DoAll(SaveArg<0>(&response_to_mobile), Return(true)));

  command->Run();
  command->on_event(event_ui);
  command->on_event(event_tts);

  EXPECT_EQ((*response_to_mobile)[am::strings::msg_params][am::strings::success]
                .asBool(),
            false);
  EXPECT_EQ(
      (*response_to_mobile)[am::strings::msg_params][am::strings::result_code]
          .asInt(),
      static_cast<int32_t>(mobile_apis::Result::INVALID_DATA));
}

TEST_F(SetGlobalPropertiesRequestTest, Run_VRNoMenuAndKeyboard_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));
  EXPECT_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
      .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_UI));

  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  OnEventUISetupHelper(msg, command);
}

TEST_F(SetGlobalPropertiesRequestTest, Run_VRWithMenuAndKeyboard_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject vr_help_title("yes");
  SmartObject vr_help_array(smart_objects::SmartType_Array);
  VRArraySetupHelper(msg, vr_help_title, vr_help_array);
  (*msg)[am::strings::msg_params][am::strings::vr_help] = vr_help_array;
  SmartObject menu_title("Menu_Title");
  (*msg)[am::strings::msg_params][am::hmi_request::menu_title] = menu_title;
  SmartObject menu_icon(smart_objects::SmartType_Map);
  menu_icon[am::strings::value] = "1";
  (*msg)[am::strings::msg_params][am::hmi_request::menu_icon] = menu_icon;
  SmartObject keyboard_properties(smart_objects::SmartType_Map);
  (*msg)[am::strings::msg_params][am::hmi_request::keyboard_properties] =
      keyboard_properties;

  EXPECT_CALL(mock_message_helper_, VerifyImage(menu_icon, _, _))
      .WillOnce((Return(mobile_apis::Result::SUCCESS)));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(vr_help_array, _, _))
      .WillOnce((Return(mobile_apis::Result::SUCCESS)));
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  EXPECT_CALL(*mock_app_, set_vr_help_title(vr_help_title));
  EXPECT_CALL(*mock_app_, set_vr_help(vr_help_array));
  EXPECT_CALL(*mock_app_, vr_help_title()).WillOnce(Return(&vr_help_title));
  EXPECT_CALL(*mock_app_, vr_help()).WillOnce(Return(&vr_help_array));
  EXPECT_CALL(*mock_app_, set_menu_title(menu_title));
  EXPECT_CALL(*mock_app_, set_menu_icon(menu_icon));
  EXPECT_CALL(*mock_app_, set_keyboard_props(keyboard_properties));
  EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId));

  EXPECT_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
      .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_UI));

  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_VRBrokenMenuIcon_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject vr_help_title("yes");
  (*msg)[am::strings::msg_params][am::strings::vr_help_title] = vr_help_title;
  SmartObject menu_icon(smart_objects::SmartType_Map);
  menu_icon[am::strings::value] = "1";
  (*msg)[am::strings::msg_params][am::hmi_request::menu_icon] = menu_icon;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImage(menu_icon, _, _))
      .WillOnce((Return(mobile_apis::Result::ABORTED)));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(_)).Times(0);
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_VRBrokenVRHelp_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject vr_help_title("yes");
  SmartObject menu_icon(smart_objects::SmartType_Map);
  menu_icon[am::strings::value] = "1";
  (*msg)[am::strings::msg_params][am::hmi_request::menu_icon] = menu_icon;
  SmartObject vr_help_array(smart_objects::SmartType_Array);
  VRArraySetupHelper(msg, vr_help_title, vr_help_array);

  EXPECT_CALL(mock_message_helper_, VerifyImage(menu_icon, _, _))
      .WillOnce((Return(mobile_apis::Result::SUCCESS)));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(vr_help_array, _, _))
      .WillOnce((Return(mobile_apis::Result::ABORTED)));
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(_)).Times(0);
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_VRIncorrectSyntax_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();
  (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;
  (*msg)[am::strings::msg_params][am::strings::app_id] = kAppId;
  SmartObject vr_help_title("wrong syntax string\\n");
  SmartObject menu_icon(smart_objects::SmartType_Map);
  menu_icon[am::strings::value] = "1";
  (*msg)[am::strings::msg_params][am::hmi_request::menu_icon] = menu_icon;
  SmartObject vr_help_array(smart_objects::SmartType_Array);
  VRArraySetupHelper(msg, vr_help_title, vr_help_array);

  EXPECT_CALL(mock_message_helper_, VerifyImage(menu_icon, _, _))
      .WillOnce((Return(mobile_apis::Result::SUCCESS)));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(vr_help_array, _, _))
      .WillOnce((Return(mobile_apis::Result::SUCCESS)));
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(_)).Times(0);
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_VRMissingTitle_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject vr_help_array(smart_objects::SmartType_Array);
  vr_help_array[0] = SmartObject(smart_objects::SmartType_Map);
  vr_help_array[0][am::strings::text] = kText;
  vr_help_array[0][am::strings::position] = kPosition;
  (*msg)[am::strings::msg_params][am::strings::vr_help] = vr_help_array;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(vr_help_array, _, _))
      .WillOnce((Return(mobile_apis::Result::SUCCESS)));
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_VRMissingArray_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject vr_help_title("yes");
  (*msg)[am::strings::msg_params][am::strings::vr_help_title] = vr_help_title;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_VRWrongOrder_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject vr_help_title("yes");
  SmartObject vr_help_array(smart_objects::SmartType_Array);
  VRArraySetupHelper(msg, vr_help_title, vr_help_array);
  vr_help_array[1] = SmartObject(smart_objects::SmartType_Map);
  vr_help_array[1][am::strings::text] = "two";
  vr_help_array[1][am::strings::position] = 3u;
  (*msg)[am::strings::msg_params][am::strings::vr_help] = vr_help_array;

  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(vr_help_array, _, _))
      .WillOnce((Return(mobile_apis::Result::SUCCESS)));
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_NoVR_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject keyboard_properties(smart_objects::SmartType_Map);
  (*msg)[am::strings::msg_params][am::hmi_request::keyboard_properties] =
      keyboard_properties;
  SmartObject menu_title("Menu_Title");
  (*msg)[am::strings::msg_params][am::hmi_request::menu_title] = menu_title;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  SmartObject vr_help_title("Menu_Title");
  EXPECT_CALL(*mock_app_, vr_help_title()).WillOnce(Return(&vr_help_title));
  EXPECT_CALL(*mock_app_, set_menu_title(menu_title));
  EXPECT_CALL(*mock_app_, set_menu_icon(_)).Times(0);
  EXPECT_CALL(*mock_app_, set_keyboard_props(keyboard_properties));
  EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId));

  EXPECT_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
      .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_UI));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_VRCouldNotGenerate_INVALID_DATA) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject keyboard_properties(smart_objects::SmartType_Map);
  (*msg)[am::strings::msg_params][am::hmi_request::keyboard_properties] =
      keyboard_properties;
  SmartObject menu_title("Menu_Title");
  (*msg)[am::strings::msg_params][am::hmi_request::menu_title] = menu_title;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  SmartObject* vr_help_title = NULL;
  CommandsMap commands_map;
  SmartObject empty_msg(smart_objects::SmartType_Map);
  commands_map.insert(std::pair<uint32_t, SmartObject*>(1u, &empty_msg));
  DataAccessor<CommandsMap> accessor(commands_map, lock_);
  EXPECT_CALL(*mock_app_, commands_map()).WillOnce(Return(accessor));
  EXPECT_CALL(*mock_app_, vr_help_title()).WillOnce(Return(vr_help_title));
  EXPECT_CALL(*mock_app_, set_menu_title(_)).Times(0);

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  EXPECT_CALL(
      app_mngr_,
      ManageMobileCommand(MobileResultCodeIs(mobile_apis::Result::INVALID_DATA),
                          am::commands::Command::ORIGIN_SDL));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_NoVRNoDataNoDefault_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject keyboard_properties(smart_objects::SmartType_Map);
  (*msg)[am::strings::msg_params][am::hmi_request::keyboard_properties] =
      keyboard_properties;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  SmartObject vr_help_title(smart_objects::SmartType_Null);
  EXPECT_CALL(*mock_app_, vr_help_title())
      .WillOnce(Return(&vr_help_title))
      .WillOnce(Return(&vr_help_title));

  CommandsMap commands_map;
  DataAccessor<CommandsMap> accessor(commands_map, lock_);
  EXPECT_CALL(*mock_app_, commands_map()).WillOnce(Return(accessor));
  const CustomString name("name");
  EXPECT_CALL(*mock_app_, name()).WillOnce(ReturnRef(name));
  EXPECT_CALL(*mock_app_, set_vr_help_title(SmartObject(name)));
  EXPECT_CALL(*mock_app_, set_menu_title(_)).Times(0);
  EXPECT_CALL(*mock_app_, set_menu_icon(_)).Times(0);
  EXPECT_CALL(*mock_app_, set_keyboard_props(_));
  EXPECT_CALL(*mock_app_, app_id());

  EXPECT_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
      .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_UI));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_NoVRNoDataDefaultCreated_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject keyboard_properties(smart_objects::SmartType_Map);
  (*msg)[am::strings::msg_params][am::hmi_request::keyboard_properties] =
      keyboard_properties;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  SmartObject vr_help_title(smart_objects::SmartType_Null);
  EXPECT_CALL(*mock_app_, vr_help_title())
      .Times(2)
      .WillRepeatedly(Return(&vr_help_title));

  CommandsMap commands_map;
  SmartObject command_text(smart_objects::SmartType_Map);
  commands_map[0] = &command_text;
  (*commands_map[0])[am::strings::vr_commands] = SmartObject("one");
  DataAccessor<CommandsMap> accessor(commands_map, lock_);
  EXPECT_CALL(*mock_app_, commands_map()).WillOnce(Return(accessor));
  EXPECT_CALL(*mock_app_, set_vr_help(_));
  const CustomString name("name");
  EXPECT_CALL(*mock_app_, name()).WillOnce(ReturnRef(name));
  EXPECT_CALL(*mock_app_, set_vr_help_title(SmartObject(name)));
  SmartObject vr_help_array(smart_objects::SmartType_Array);
  EXPECT_CALL(*mock_app_, vr_help()).WillOnce(Return(&vr_help_array));
  EXPECT_CALL(*mock_app_, set_menu_title(_)).Times(0);
  EXPECT_CALL(*mock_app_, set_menu_icon(_)).Times(0);
  EXPECT_CALL(*mock_app_, set_keyboard_props(keyboard_properties));
  EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId));
  EXPECT_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
      .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_UI));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_NoVRNoDataFromSynonyms_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject keyboard_properties(smart_objects::SmartType_Map);
  (*msg)[am::strings::msg_params][am::hmi_request::keyboard_properties] =
      keyboard_properties;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  SmartObject vr_help_title(smart_objects::SmartType_Null);
  EXPECT_CALL(*mock_app_, vr_help_title())
      .Times(2)
      .WillRepeatedly(Return(&vr_help_title));

  CommandsMap commands_map;
  DataAccessor<CommandsMap> accessor(commands_map, lock_);
  EXPECT_CALL(*mock_app_, commands_map()).WillOnce(Return(accessor));
  SmartObject vr_help_array(smart_objects::SmartType_Array);
  vr_help_array[0] = SmartObject(smart_objects::SmartType_Map);
  vr_help_array[0][am::strings::text] = kText;
  vr_help_array[0][am::strings::position] = kPosition;
  SmartObject vr_synonyms(smart_objects::SmartType_Array);
  vr_synonyms[0] = vr_help_array;
  const CustomString name("name");
  EXPECT_CALL(*mock_app_, name()).WillOnce(ReturnRef(name));
  EXPECT_CALL(*mock_app_, set_vr_help_title(SmartObject(name)));
  EXPECT_CALL(*mock_app_, set_menu_title(_)).Times(0);
  EXPECT_CALL(*mock_app_, set_menu_icon(_)).Times(0);
  EXPECT_CALL(*mock_app_, set_keyboard_props(keyboard_properties));
  EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId));
  EXPECT_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
      .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_UI));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_TTSHelpAndTimeout_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject help_prompt(smart_objects::SmartType_Array);
  help_prompt[0][am::strings::text] = "Help_Prompt_One";
  (*msg)[am::strings::msg_params][am::strings::help_prompt] = help_prompt;
  SmartObject timeout_prompt(smart_objects::SmartType_Array);
  timeout_prompt[0][am::strings::text] = "Timeout_Prompt_One";
  (*msg)[am::strings::msg_params][am::strings::timeout_prompt] = timeout_prompt;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  SmartObject vr_help_title("title");
  EXPECT_CALL(*mock_app_, vr_help_title()).WillOnce(Return(&vr_help_title));
  EXPECT_CALL(*mock_app_, set_help_prompt(help_prompt));
  EXPECT_CALL(*mock_app_, help_prompt()).WillOnce(Return(&help_prompt));
  EXPECT_CALL(*mock_app_, set_timeout_prompt(timeout_prompt));
  EXPECT_CALL(*mock_app_, timeout_prompt()).WillOnce(Return(&timeout_prompt));
  EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId));

  EXPECT_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::TTS_SetGlobalProperties))
      .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_TTS));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_TTS))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_TTSOnlyHelp_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject help_prompt(smart_objects::SmartType_Array);
  help_prompt[0][am::strings::text] = "Help_Prompt_One";
  (*msg)[am::strings::msg_params][am::strings::help_prompt] = help_prompt;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  SmartObject vr_help_title("title");
  EXPECT_CALL(*mock_app_, vr_help_title()).WillOnce(Return(&vr_help_title));
  EXPECT_CALL(*mock_app_, set_help_prompt(help_prompt));
  EXPECT_CALL(*mock_app_, help_prompt()).WillOnce(Return(&help_prompt));
  EXPECT_CALL(*mock_app_, set_timeout_prompt(_)).Times(0);
  EXPECT_CALL(*mock_app_, timeout_prompt()).Times(0);
  EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId));
  EXPECT_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::TTS_SetGlobalProperties))
      .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_TTS));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_TTS))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_TTSOnlyTimeout_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject timeout_prompt(smart_objects::SmartType_Array);
  timeout_prompt[0][am::strings::text] = "Timeout_Prompt_One";
  (*msg)[am::strings::msg_params][am::strings::timeout_prompt] = timeout_prompt;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EXPECT_CALL(app_mngr_, RemoveAppFromTTSGlobalPropertiesList(kConnectionKey));
  SmartObject vr_help_title("title");
  EXPECT_CALL(*mock_app_, vr_help_title()).WillOnce(Return(&vr_help_title));
  EXPECT_CALL(*mock_app_, set_help_prompt(_)).Times(0);
  EXPECT_CALL(*mock_app_, help_prompt()).Times(0);
  EXPECT_CALL(*mock_app_, set_timeout_prompt(timeout_prompt));
  EXPECT_CALL(*mock_app_, timeout_prompt()).WillOnce(Return(&timeout_prompt));
  EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId));
  EXPECT_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::TTS_SetGlobalProperties))
      .WillOnce(Return(am::HmiInterfaces::HMI_INTERFACE_TTS));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_TTS))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_TTSIncorrectSyntax_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject timeout_prompt(smart_objects::SmartType_Array);
  timeout_prompt[0][am::strings::text] = "Timeout_Prompt_One\\n";
  (*msg)[am::strings::msg_params][am::strings::timeout_prompt] = timeout_prompt;

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillOnce(Return(mock_app_));
  EXPECT_CALL(mock_message_helper_, VerifyImageVrHelpItems(_, _, _)).Times(0);
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_InvalidHelpPromptText_INVALID_DATA) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject help_prompt(smart_objects::SmartType_Array);
  help_prompt[0][am::strings::text] =
      "invalid help prompt text with empty line in the end\\n";
  (*msg)[am::strings::msg_params][am::strings::help_prompt] = help_prompt;

  ExpectVerifyImageVrHelpUnsuccess();
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  ExpectInvalidData();

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_InvalidVrHelpText_INVALID_DATA) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject vr_help(smart_objects::SmartType_Array);
  vr_help[0][am::strings::text] =
      "invalid vr_help text with empty line in the end\\n";
  (*msg)[am::strings::msg_params][am::strings::vr_help] = vr_help;

  ExpectVerifyImageVrHelpSuccess(vr_help);
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  ExpectInvalidData();

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_InvalidImageValue_INVALID_DATA) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject vr_help(smart_objects::SmartType_Array);
  vr_help[0][am::strings::text] = "vr_help";
  vr_help[0][am::strings::image][am::strings::value] =
      "invalid value text with empty line in the end\\n";
  (*msg)[am::strings::msg_params][am::strings::vr_help] = vr_help;

  ExpectVerifyImageVrHelpSuccess(vr_help);
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  ExpectInvalidData();

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_InvalidMenuIcon_INVALID_DATA) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject menu_icon(smart_objects::SmartType_Array);
  menu_icon[am::strings::value] =
      "invalid menu icon text with empty line in the end\\n";
  (*msg)[am::strings::msg_params][am::strings::menu_icon] = menu_icon;

  ExpectVerifyImageSuccess(menu_icon);
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  ExpectInvalidData();

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_InvalidMenuTitle_INVALID_DATA) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject menu_title(smart_objects::SmartType_Array);
  menu_title = "invalid menu title text with empty line in the end\\n";
  (*msg)[am::strings::msg_params][am::strings::menu_title] = menu_title;

  ExpectVerifyImageVrHelpUnsuccess();
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  ExpectInvalidData();

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest,
       Run_InvalidLimitedCharacterList_INVALID_DATA) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject limited_character_list(smart_objects::SmartType_Array);
  limited_character_list[0] =
      "invalid limited character list text with empty line in the end\\n";
  (*msg)[am::strings::msg_params][am::strings::keyboard_properties]
        [am::strings::limited_character_list] = limited_character_list;

  ExpectVerifyImageVrHelpUnsuccess();
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  ExpectInvalidData();

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest,
       Run_InvalidAutoCompleteText_INVALID_DATA) {
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject auto_complete_text(smart_objects::SmartType_Array);
  auto_complete_text =
      "invalid auto completetext with empty line in the end\\n";
  (*msg)[am::strings::msg_params][am::strings::keyboard_properties]
        [am::strings::auto_complete_text] = auto_complete_text;

  ExpectVerifyImageVrHelpUnsuccess();
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  ExpectInvalidData();

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_NoData_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();

  ExpectVerifyImageVrHelpUnsuccess();
  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, Run_InvalidApp_Canceled) {
  MessageSharedPtr msg = CreateMessage();
  (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;

  ExpectVerifyImageVrHelpUnsuccess();

  EmptyExpectationsSetupHelper();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  command->Run();
}

TEST_F(SetGlobalPropertiesRequestTest, OnEvent_PendingRequest_UNSUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  hmi_apis::Common_Result::eType response_code =
      hmi_apis::Common_Result::SUCCESS;
  (*msg)[am::strings::params][am::hmi_response::code] = response_code;

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  EXPECT_CALL(mock_message_helper_, HMIToMobileResult(_)).Times(0);

  Event event(hmi_apis::FunctionID::UI_SetGlobalProperties);
  event.set_smart_object(*msg);

  command->on_event(event);
}

TEST_F(SetGlobalPropertiesRequestTest, OnEvent_UIAndSuccessResultCode_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  hmi_apis::Common_Result::eType response_code =
      hmi_apis::Common_Result::SUCCESS;
  (*msg)[am::strings::params][am::hmi_response::code] = response_code;

  ON_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
      .WillByDefault(Return(am::HmiInterfaces::HMI_INTERFACE_UI));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));
  OnEventUISetupHelper(msg, command);

  Event event(hmi_apis::FunctionID::UI_SetGlobalProperties);
  event.set_smart_object(*msg);

  EXPECT_CALL(mock_message_helper_, HMIToMobileResult(_))
      .WillOnce(Return(mobile_apis::Result::SUCCESS));

  EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(_))
      .WillRepeatedly(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  EXPECT_CALL(app_mngr_,
              ManageMobileCommand(_, am::commands::Command::ORIGIN_SDL))
      .WillOnce(Return(true));

  command->on_event(event);
}

TEST_F(SetGlobalPropertiesRequestTest, OnEvent_UIAndWarningResultCode_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  hmi_apis::Common_Result::eType response_code =
      hmi_apis::Common_Result::WARNINGS;
  (*msg)[am::strings::params][am::hmi_response::code] = response_code;

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));
  ON_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
      .WillByDefault(Return(am::HmiInterfaces::HMI_INTERFACE_UI));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
  OnEventUISetupHelper(msg, command);

  EXPECT_CALL(mock_message_helper_, HMIToMobileResult(_)).Times(0);

  Event event(hmi_apis::FunctionID::UI_SetGlobalProperties);
  event.set_smart_object(*msg);

  EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(_))
      .WillRepeatedly(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
  EXPECT_CALL(mock_message_helper_, HMIToMobileResult(_))
      .WillOnce(Return(mobile_apis::Result::SUCCESS));
  EXPECT_CALL(app_mngr_,
              ManageMobileCommand(_, am::commands::Command::ORIGIN_SDL))
      .WillOnce(Return(true));

  command->on_event(event);
}

TEST_F(SetGlobalPropertiesRequestTest, OnEvent_InvalidApp_Canceled) {
  MessageSharedPtr msg = CreateMsgParams();
  hmi_apis::Common_Result::eType response_code =
      hmi_apis::Common_Result::WARNINGS;
  (*msg)[am::strings::params][am::hmi_response::code] = response_code;
  ON_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::UI_SetGlobalProperties))
      .WillByDefault(Return(am::HmiInterfaces::HMI_INTERFACE_UI));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  OnEventUISetupHelper(msg, command);
  EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(_))
      .WillRepeatedly(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  EXPECT_CALL(mock_message_helper_, HMIToMobileResult(_))
      .WillOnce(Return(mobile_apis::Result::SUCCESS));

  EXPECT_CALL(app_mngr_, application(kConnectionKey))
      .WillRepeatedly(Return(MockAppPtr()));

  EXPECT_CALL(*mock_app_, UpdateHash()).Times(0);

  Event event(hmi_apis::FunctionID::UI_SetGlobalProperties);
  event.set_smart_object(*msg);

  command->on_event(event);
}

TEST_F(SetGlobalPropertiesRequestTest, OnEvent_InvalidEventID_Canceled) {
  MessageSharedPtr msg = CreateMessage();

  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  EXPECT_CALL(mock_message_helper_, HMIToMobileResult(_)).Times(0);
  EXPECT_CALL(app_mngr_, application(kConnectionKey)).Times(0);
  EXPECT_CALL(*mock_app_, UpdateHash()).Times(0);

  Event event(hmi_apis::FunctionID::TTS_Stopped);
  event.set_smart_object(*msg);

  command->on_event(event);
}

TEST_F(SetGlobalPropertiesRequestTest,
       OnEvent_TTSAndSuccessResultCode_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  hmi_apis::Common_Result::eType response_code =
      hmi_apis::Common_Result::SUCCESS;
  (*msg)[am::strings::params][am::hmi_response::code] = response_code;
  ON_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::TTS_SetGlobalProperties))
      .WillByDefault(Return(am::HmiInterfaces::HMI_INTERFACE_TTS));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_TTS))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  OnEventTTSSetupHelper(msg, command);
  EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(_))
      .WillRepeatedly(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  EXPECT_CALL(app_mngr_,
              ManageMobileCommand(_, am::commands::Command::ORIGIN_SDL))
      .WillOnce(Return(true));

  EXPECT_CALL(mock_message_helper_, HMIToMobileResult(response_code))
      .WillOnce(Return(mobile_apis::Result::SUCCESS));

  Event event(hmi_apis::FunctionID::TTS_SetGlobalProperties);
  event.set_smart_object(*msg);

  command->on_event(event);
}

TEST_F(SetGlobalPropertiesRequestTest,
       OnEvent_TTSAndWarningsResultCode_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  hmi_apis::Common_Result::eType response_code =
      hmi_apis::Common_Result::WARNINGS;
  (*msg)[am::strings::params][am::hmi_response::code] = response_code;
  ON_CALL(
      mock_hmi_interfaces_,
      GetInterfaceFromFunction(hmi_apis::FunctionID::TTS_SetGlobalProperties))
      .WillByDefault(Return(am::HmiInterfaces::HMI_INTERFACE_TTS));
  ON_CALL(mock_hmi_interfaces_,
          GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_TTS))
      .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));
  SharedPtr<SetGlobalPropertiesRequest> command(
      CreateCommand<SetGlobalPropertiesRequest>(msg));

  OnEventTTSSetupHelper(msg, command);

  EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(_))
      .WillRepeatedly(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE));

  EXPECT_CALL(app_mngr_,
              ManageMobileCommand(_, am::commands::Command::ORIGIN_SDL))
      .WillOnce(Return(true));

  EXPECT_CALL(mock_message_helper_, HMIToMobileResult(_))
      .WillOnce(Return(mobile_apis::Result::SUCCESS));

  Event event(hmi_apis::FunctionID::TTS_SetGlobalProperties);
  event.set_smart_object(*msg);

  command->on_event(event);
}

}  // namespace set_global_properties_request
}  // namespace mobile_commands_test
}  // namespace commands_test
}  // namespace components
}  // namespace tests


text:
namespace Spect.Net.EvalParser.SyntaxTree
{
    /// <summary>
    /// This class represents a Z80 register value node
    /// </summary>
    public sealed class Z80RegisterNode : ExpressionNode
    {
        /// <summary>
        /// Register name
        /// </summary>
        public string Register { get; }

        /// <summary>
        /// Retrieves the value of the expression
        /// </summary>
        /// <param name="evalContext">Evaluation context</param>
        /// <returns>Evaluated expression value</returns>
        public override ExpressionValue Evaluate(IExpressionEvaluationContext evalContext)
        {
            var result = evalContext.GetZ80RegisterValue(Register, out var is8Bit);
            SuggestType(is8Bit ? ExpressionValueType.Byte : ExpressionValueType.Word);
            return result;
        }

        /// <summary>
        /// Initializes with the specified register
        /// </summary>
        /// <param name="register">Register name</param>
        public Z80RegisterNode(string register)
        {
            Register = register;
        }

        /// <summary>Returns a string that represents the current object.</summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
            => Register == null ? "" : Register.ToUpper();
    }
}


text:
package mux

import (
	"io"

	"v2ray.com/core/common/buf"
	"v2ray.com/core/common/serial"
)

// ReadMetadata reads FrameMetadata from the given reader.
func ReadMetadata(reader io.Reader) (*FrameMetadata, error) {
	metaLen, err := serial.ReadUint16(reader)
	if err != nil {
		return nil, err
	}
	if metaLen > 512 {
		return nil, newError("invalid metalen ", metaLen).AtError()
	}

	b := buf.NewSize(int32(metaLen))
	defer b.Release()

	if err := b.Reset(buf.ReadFullFrom(reader, int32(metaLen))); err != nil {
		return nil, err
	}
	return ReadFrameFrom(b)
}

// PacketReader is an io.Reader that reads whole chunk of Mux frames every time.
type PacketReader struct {
	reader io.Reader
	eof    bool
}

// NewPacketReader creates a new PacketReader.
func NewPacketReader(reader io.Reader) *PacketReader {
	return &PacketReader{
		reader: reader,
		eof:    false,
	}
}

// ReadMultiBuffer implements buf.Reader.
func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
	if r.eof {
		return nil, io.EOF
	}

	size, err := serial.ReadUint16(r.reader)
	if err != nil {
		return nil, err
	}

	b := buf.NewSize(int32(size))
	if err := b.Reset(buf.ReadFullFrom(r.reader, int32(size))); err != nil {
		b.Release()
		return nil, err
	}
	r.eof = true
	return buf.NewMultiBufferValue(b), nil
}

// StreamReader reads Mux frame as a stream.
type StreamReader struct {
	reader   *buf.BufferedReader
	leftOver int32
}

// NewStreamReader creates a new StreamReader.
func NewStreamReader(reader *buf.BufferedReader) *StreamReader {
	return &StreamReader{
		reader:   reader,
		leftOver: -1,
	}
}

// ReadMultiBuffer implmenets buf.Reader.
func (r *StreamReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
	if r.leftOver == 0 {
		return nil, io.EOF
	}

	if r.leftOver == -1 {
		size, err := serial.ReadUint16(r.reader)
		if err != nil {
			return nil, err
		}
		r.leftOver = int32(size)
	}

	mb, err := r.reader.ReadAtMost(r.leftOver)
	r.leftOver -= mb.Len()
	return mb, err
}