text:
<?php

namespace Drupal\Tests\Core\Routing;

use Drupal\accept_header_routing_test\Routing\AcceptHeaderMatcher;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;

/**
 * Confirm that the mime types partial matcher is functioning properly.
 *
 * @group Routing
 */
class AcceptHeaderMatcherTest extends UnitTestCase {

  /**
   * A collection of shared fixture data for tests.
   *
   * @var \Drupal\Tests\Core\Routing\RoutingFixtures
   */
  protected $fixtures;

  /**
   * The matcher object that is going to be tested.
   *
   * @var \Drupal\accept_header_routing_test\Routing\AcceptHeaderMatcher
   */
  protected $matcher;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    $this->fixtures = new RoutingFixtures();
    $this->matcher = new AcceptHeaderMatcher();
  }

  /**
   * Provides data for the Accept header filtering test.
   *
   * @see Drupal\Tests\Core\Routing\AcceptHeaderMatcherTest::testAcceptFiltering()
   */
  public function acceptFilterProvider() {
    return [
      // Check that JSON routes get filtered and prioritized correctly.
      ['application/json, text/xml;q=0.9', 'json', 'route_c', 'route_e'],
      // Tests a JSON request with alternative JSON MIME type Accept header.
      ['application/x-json, text/xml;q=0.9', 'json', 'route_c', 'route_e'],
      // Tests a standard HTML request.
      ['text/html, text/xml;q=0.9', 'html', 'route_e', 'route_c'],
    ];
  }

  /**
   * Tests that requests using Accept headers get filtered correctly.
   *
   * @param string $accept_header
   *   The HTTP Accept header value of the request.
   * @param string $format
   *   The request format.
   * @param string $included_route
   *   The route name that should survive the filter and be ranked first.
   * @param string $excluded_route
   *   The route name that should be filtered out during matching.
   *
   * @dataProvider acceptFilterProvider
   */
  public function testAcceptFiltering($accept_header, $format, $included_route, $excluded_route) {
    $collection = $this->fixtures->sampleRouteCollection();

    $request = Request::create('path/two', 'GET');
    $request->headers->set('Accept', $accept_header);
    $request->setRequestFormat($format);
    $routes = $this->matcher->filter($collection, $request);
    $this->assertCount(4, $routes, 'The correct number of routes was found.');
    $this->assertNotNull($routes->get($included_route), "Route $included_route was found when matching $accept_header.");
    $this->assertNull($routes->get($excluded_route), "Route $excluded_route was not found when matching $accept_header.");
    foreach ($routes as $name => $route) {
      $this->assertEquals($name, $included_route, "Route $included_route is the first one in the collection when matching $accept_header.");
      break;
    }
  }

  /**
   * Confirms that the AcceptHeaderMatcher throws an exception for no-route.
   */
  public function testNoRouteFound() {
    // Remove the sample routes that would match any method.
    $routes = $this->fixtures->sampleRouteCollection();
    $routes->remove('route_a');
    $routes->remove('route_b');
    $routes->remove('route_c');
    $routes->remove('route_d');

    $request = Request::create('path/two', 'GET');
    $request->headers->set('Accept', 'application/json, text/xml;q=0.9');
    $request->setRequestFormat('json');
    $this->expectException(NotAcceptableHttpException::class);
    $this->expectExceptionMessage('No route found for the specified formats application/json text/xml');
    $this->matcher->filter($routes, $request);
  }

}


text:
package org.osgi.framework;

/**
 * A service exception used to indicate that a service problem occurred.
 *
 *

 * A {@code ServiceException} object is created by the Framework or service
 * implementation to denote an exception condition in the service. A type code
 * is used to identify the exception type for future extendability. Service
 * implementations may also create subclasses of {@code ServiceException}. When
 * subclassing, the subclass should set the type to {@link #SUBCLASSED} to
 * indicate that {@code ServiceException} has been subclassed.
 *
 *

 * This exception conforms to the general purpose exception chaining mechanism.
 *
 * @author $Id$
 * @since 1.5
 */

public class ServiceException extends RuntimeException {
	static final long		serialVersionUID	= 3038963223712959631L;

	/**
	 * Type of service exception.
	 */
	private final int		type;

	/**
	 * No exception type is unspecified.
	 */
	public static final int	UNSPECIFIED			= 0;
	/**
	 * The service has been unregistered.
	 */
	public static final int	UNREGISTERED		= 1;
	/**
	 * The service factory produced an invalid service object.
	 */
	public static final int	FACTORY_ERROR		= 2;
	/**
	 * The service factory threw an exception.
	 */
	public static final int	FACTORY_EXCEPTION	= 3;
	/**
	 * The exception is a subclass of ServiceException. The subclass should be
	 * examined for the type of the exception.
	 */
	public static final int	SUBCLASSED			= 4;
	/**
	 * An error occurred invoking a remote service.
	 */
	public static final int	REMOTE				= 5;
	/**
	 * The service factory resulted in a recursive call to itself for the
	 * requesting bundle.
	 *
	 * @since 1.6
	 */
	public static final int	FACTORY_RECURSION	= 6;
	/**
	 * An asynchronous operation was unable to obtain the service.
	 *
	 * @since 1.8
	 */
	public static final int	ASYNC_ERROR			= 7;

	/**
	 * Creates a {@code ServiceException} with the specified message and
	 * exception cause.
	 *
	 * @param msg The associated message.
	 * @param cause The cause of this exception.
	 */
	public ServiceException(String msg, Throwable cause) {
		this(msg, UNSPECIFIED, cause);
	}

	/**
	 * Creates a {@code ServiceException} with the specified message.
	 *
	 * @param msg The message.
	 */
	public ServiceException(String msg) {
		this(msg, UNSPECIFIED);
	}

	/**
	 * Creates a {@code ServiceException} with the specified message, type and
	 * exception cause.
	 *
	 * @param msg The associated message.
	 * @param type The type for this exception.
	 * @param cause The cause of this exception.
	 */
	public ServiceException(String msg, int type, Throwable cause) {
		super(msg, cause);
		this.type = type;
	}

	/**
	 * Creates a {@code ServiceException} with the specified message and type.
	 *
	 * @param msg The message.
	 * @param type The type for this exception.
	 */
	public ServiceException(String msg, int type) {
		super(msg);
		this.type = type;
	}

	/**
	 * Returns the type for this exception or {@code UNSPECIFIED} if the type
	 * was unspecified or unknown.
	 *
	 * @return The type of this exception.
	 */
	public int getType() {
		return type;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.di.crm.sfa.service;

import java.util.*;

import com.di.crm.sfa.domain.Action;

public class ActionServiceImpl implements ActionService {

	private final int MAX_ACTIONS_PAGE = 10;

	public List<Action> searchPaging(List<String> actionRowIds, int start, int end) {
		List<Action> searchActions = new LinkedList<Action>();
		if ((start <= 0 || end <= 0) || (end - start > MAX_ACTIONS_PAGE))
			return searchActions;

		return searchActions;
	}

	public Action search(String rowId) {

		return null;
	}

}


text:
class Portal::CollaborationPolicy < ApplicationPolicy
end


text:
import ddt
import mock
from oslo_serialization import jsonutils
import six
import webob

from manila.api.openstack import api_version_request as api_version
from manila.api.v2 import share_snapshots
from manila.common import constants
from manila import context
from manila import db
from manila import exception
from manila import policy
from manila.share import api as share_api
from manila import test
from manila.tests.api.contrib import stubs
from manila.tests.api import fakes
from manila.tests import db_utils
from manila.tests import fake_share
from manila import utils

MIN_MANAGE_SNAPSHOT_API_VERSION = '2.12'

def get_fake_manage_body(share_id=None, provider_location=None,
                         driver_options=None, **kwargs):
    fake_snapshot = {
        'share_id': share_id,
        'provider_location': provider_location,
        'driver_options': driver_options,
        'user_id': 'fake_user_id',
        'project_id': 'fake_project_id',
    }
    fake_snapshot.update(kwargs)
    return {'snapshot': fake_snapshot}

@ddt.ddt
class ShareSnapshotAPITest(test.TestCase):
    """Share Snapshot API Test."""

    def setUp(self):
        super(self.__class__, self).setUp()
        self.controller = share_snapshots.ShareSnapshotsController()

        self.mock_object(share_api.API, 'get', stubs.stub_share_get)
        self.mock_object(share_api.API, 'get_all_snapshots',
                         stubs.stub_snapshot_get_all_by_project)
        self.mock_object(share_api.API, 'get_snapshot',
                         stubs.stub_snapshot_get)
        self.mock_object(share_api.API, 'snapshot_update',
                         stubs.stub_snapshot_update)
        self.snp_example = {
            'share_id': 100,
            'size': 12,
            'force': False,
            'display_name': 'updated_snapshot_name',
            'display_description': 'updated_snapshot_description',
        }

    @ddt.data('1.0', '2.16', '2.17')
    def test_snapshot_create(self, version):
        self.mock_object(share_api.API, 'create_snapshot',
                         stubs.stub_snapshot_create)

        body = {
            'snapshot': {
                'share_id': 'fakeshareid',
                'force': False,
                'name': 'displaysnapname',
                'description': 'displaysnapdesc',
            }
        }
        req = fakes.HTTPRequest.blank('/snapshots', version=version)

        res_dict = self.controller.create(req, body)

        expected = fake_share.expected_snapshot(version=version, id=200)

        self.assertEqual(expected, res_dict)

    @ddt.data(0, False)
    def test_snapshot_create_no_support(self, snapshot_support):
        self.mock_object(share_api.API, 'create_snapshot')
        self.mock_object(
            share_api.API,
            'get',
            mock.Mock(return_value={'snapshot_support': snapshot_support}))
        body = {
            'snapshot': {
                'share_id': 100,
                'force': False,
                'name': 'fake_share_name',
                'description': 'fake_share_description',
            }
        }
        req = fakes.HTTPRequest.blank('/snapshots')

        self.assertRaises(
            webob.exc.HTTPUnprocessableEntity,
            self.controller.create, req, body)

        self.assertFalse(share_api.API.create_snapshot.called)

    def test_snapshot_create_no_body(self):
        body = {}
        req = fakes.HTTPRequest.blank('/snapshots')
        self.assertRaises(webob.exc.HTTPUnprocessableEntity,
                          self.controller.create,
                          req,
                          body)

    def test_snapshot_delete(self):
        self.mock_object(share_api.API, 'delete_snapshot',
                         stubs.stub_snapshot_delete)
        req = fakes.HTTPRequest.blank('/snapshots/200')
        resp = self.controller.delete(req, 200)
        self.assertEqual(202, resp.status_int)

    def test_snapshot_delete_nofound(self):
        self.mock_object(share_api.API, 'get_snapshot',
                         stubs.stub_snapshot_get_notfound)
        req = fakes.HTTPRequest.blank('/snapshots/200')
        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.delete,
                          req,
                          200)

    @ddt.data('2.0', '2.16', '2.17')
    def test_snapshot_show(self, version):
        req = fakes.HTTPRequest.blank('/snapshots/200', version=version)
        expected = fake_share.expected_snapshot(version=version, id=200)

        res_dict = self.controller.show(req, 200)

        self.assertEqual(expected, res_dict)

    def test_snapshot_show_nofound(self):
        self.mock_object(share_api.API, 'get_snapshot',
                         stubs.stub_snapshot_get_notfound)
        req = fakes.HTTPRequest.blank('/snapshots/200')
        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.show,
                          req, '200')

    def test_snapshot_list_summary(self):
        self.mock_object(share_api.API, 'get_all_snapshots',
                         stubs.stub_snapshot_get_all_by_project)
        req = fakes.HTTPRequest.blank('/snapshots')
        res_dict = self.controller.index(req)
        expected = {
            'snapshots': [
                {
                    'name': 'displaysnapname',
                    'id': 2,
                    'links': [
                        {
                            'href': 'http://localhost/v1/fake/'
                                    'snapshots/2',
                            'rel': 'self'
                        },
                        {
                            'href': 'http://localhost/fake/snapshots/2',
                            'rel': 'bookmark'
                        }
                    ],
                }
            ]
        }
        self.assertEqual(expected, res_dict)

    def _snapshot_list_summary_with_search_opts(self, use_admin_context):
        search_opts = fake_share.search_opts()
        # fake_key should be filtered for non-admin
        url = '/snapshots?fake_key=fake_value'
        for k, v in search_opts.items():
            url = url + '&' + k + '=' + v
        req = fakes.HTTPRequest.blank(url, use_admin_context=use_admin_context)

        snapshots = [
            {'id': 'id1', 'display_name': 'n1', 'status': 'fake_status', },
            {'id': 'id2', 'display_name': 'n2', 'status': 'fake_status', },
            {'id': 'id3', 'display_name': 'n3', 'status': 'fake_status', },
        ]
        self.mock_object(share_api.API, 'get_all_snapshots',
                         mock.Mock(return_value=snapshots))

        result = self.controller.index(req)

        search_opts_expected = {
            'display_name': search_opts['name'],
            'status': search_opts['status'],
            'share_id': search_opts['share_id'],
        }
        if use_admin_context:
            search_opts_expected.update({'fake_key': 'fake_value'})
        share_api.API.get_all_snapshots.assert_called_once_with(
            req.environ['manila.context'],
            sort_key=search_opts['sort_key'],
            sort_dir=search_opts['sort_dir'],
            search_opts=search_opts_expected,
        )
        self.assertEqual(1, len(result['snapshots']))
        self.assertEqual(snapshots[1]['id'], result['snapshots'][0]['id'])
        self.assertEqual(
            snapshots[1]['display_name'], result['snapshots'][0]['name'])

    def test_snapshot_list_summary_with_search_opts_by_non_admin(self):
        self._snapshot_list_summary_with_search_opts(use_admin_context=False)

    def test_snapshot_list_summary_with_search_opts_by_admin(self):
        self._snapshot_list_summary_with_search_opts(use_admin_context=True)

    def _snapshot_list_detail_with_search_opts(self, use_admin_context):
        search_opts = fake_share.search_opts()
        # fake_key should be filtered for non-admin
        url = '/shares/detail?fake_key=fake_value'
        for k, v in search_opts.items():
            url = url + '&' + k + '=' + v
        req = fakes.HTTPRequest.blank(url, use_admin_context=use_admin_context)

        snapshots = [
            {
                'id': 'id1',
                'display_name': 'n1',
                'status': 'fake_status',
                'aggregate_status': 'fake_status',
            },
            {
                'id': 'id2',
                'display_name': 'n2',
                'status': 'someotherstatus',
                'aggregate_status': 'fake_status',
                'share_id': 'fake_share_id',
            },
            {
                'id': 'id3',
                'display_name': 'n3',
                'status': 'fake_status',
                'aggregate_status': 'fake_status',
            },
        ]

        self.mock_object(share_api.API, 'get_all_snapshots',
                         mock.Mock(return_value=snapshots))

        result = self.controller.detail(req)

        search_opts_expected = {
            'display_name': search_opts['name'],
            'status': search_opts['status'],
            'share_id': search_opts['share_id'],
        }
        if use_admin_context:
            search_opts_expected.update({'fake_key': 'fake_value'})
        share_api.API.get_all_snapshots.assert_called_once_with(
            req.environ['manila.context'],
            sort_key=search_opts['sort_key'],
            sort_dir=search_opts['sort_dir'],
            search_opts=search_opts_expected,
        )
        self.assertEqual(1, len(result['snapshots']))
        self.assertEqual(snapshots[1]['id'], result['snapshots'][0]['id'])
        self.assertEqual(
            snapshots[1]['display_name'], result['snapshots'][0]['name'])
        self.assertEqual(
            snapshots[1]['aggregate_status'], result['snapshots'][0]['status'])
        self.assertEqual(
            snapshots[1]['share_id'], result['snapshots'][0]['share_id'])

    def test_snapshot_list_detail_with_search_opts_by_non_admin(self):
        self._snapshot_list_detail_with_search_opts(use_admin_context=False)

    def test_snapshot_list_detail_with_search_opts_by_admin(self):
        self._snapshot_list_detail_with_search_opts(use_admin_context=True)

    @ddt.data('2.0', '2.16', '2.17')
    def test_snapshot_list_detail(self, version):
        env = {'QUERY_STRING': 'name=Share+Test+Name'}
        req = fakes.HTTPRequest.blank('/snapshots/detail', environ=env,
                                      version=version)
        expected_s = fake_share.expected_snapshot(version=version, id=2)
        expected = {'snapshots': [expected_s['snapshot']]}

        res_dict = self.controller.detail(req)

        self.assertEqual(expected, res_dict)

    @ddt.data('2.0', '2.16', '2.17')
    def test_snapshot_updates_display_name_and_description(self, version):
        snp = self.snp_example
        body = {"snapshot": snp}
        req = fakes.HTTPRequest.blank('/snapshot/1', version=version)

        res_dict = self.controller.update(req, 1, body)

        self.assertEqual(snp["display_name"], res_dict['snapshot']["name"])

        if (api_version.APIVersionRequest(version) <=
                api_version.APIVersionRequest('2.16')):
            self.assertNotIn('user_id', res_dict['snapshot'])
            self.assertNotIn('project_id', res_dict['snapshot'])
        else:
            self.assertIn('user_id', res_dict['snapshot'])
            self.assertIn('project_id', res_dict['snapshot'])

    def test_share_update_invalid_key(self):
        snp = self.snp_example
        body = {"snapshot": snp}

        req = fakes.HTTPRequest.blank('/snapshot/1')
        res_dict = self.controller.update(req, 1, body)

        self.assertNotEqual(snp["size"], res_dict['snapshot']["size"])

    def test_access_list(self):
        share = db_utils.create_share(mount_snapshot_support=True)
        snapshot = db_utils.create_snapshot(
            status=constants.STATUS_AVAILABLE, share_id=share['id'])

        expected = []

        self.mock_object(share_api.API, 'get',
                         mock.Mock(return_value=share))
        self.mock_object(share_api.API, 'get_snapshot',
                         mock.Mock(return_value=snapshot))
        self.mock_object(share_api.API, 'snapshot_access_get_all',
                         mock.Mock(return_value=expected))

        id = 'fake_snap_id'
        req = fakes.HTTPRequest.blank('/snapshots/%s/action' % id,
                                      version='2.32')

        actual = self.controller.access_list(req, id)

        self.assertEqual(expected, actual['snapshot_access_list'])

    def test_allow_access(self):
        share = db_utils.create_share(mount_snapshot_support=True)
        snapshot = db_utils.create_snapshot(
            status=constants.STATUS_AVAILABLE, share_id=share['id'])

        access = {
            'id': 'fake_id',
            'access_type': 'ip',
            'access_to': '1.1.1.1',
            'state': 'new',
        }

        get = self.mock_object(share_api.API, 'get',
                               mock.Mock(return_value=share))
        get_snapshot = self.mock_object(share_api.API, 'get_snapshot',
                                        mock.Mock(return_value=snapshot))
        allow_access = self.mock_object(share_api.API, 'snapshot_allow_access',
                                        mock.Mock(return_value=access))
        body = {'allow_access': access}
        req = fakes.HTTPRequest.blank('/snapshots/%s/action' % snapshot['id'],
                                      version='2.32')

        actual = self.controller.allow_access(req, snapshot['id'], body)

        self.assertEqual(access, actual['snapshot_access'])
        get.assert_called_once_with(utils.IsAMatcher(context.RequestContext),
                                    share['id'])
        get_snapshot.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext), snapshot['id'])
        allow_access.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext), snapshot,
            access['access_type'], access['access_to'])

    def test_allow_access_data_not_found_exception(self):
        share = db_utils.create_share(mount_snapshot_support=True)
        snapshot = db_utils.create_snapshot(
            status=constants.STATUS_AVAILABLE, share_id=share['id'])
        req = fakes.HTTPRequest.blank('/snapshots/%s/action' % snapshot['id'],
                                      version='2.32')
        body = {}

        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.allow_access, req,
                          snapshot['id'], body)

    def test_allow_access_exists_exception(self):
        share = db_utils.create_share(mount_snapshot_support=True)
        snapshot = db_utils.create_snapshot(
            status=constants.STATUS_AVAILABLE, share_id=share['id'])
        req = fakes.HTTPRequest.blank('/snapshots/%s/action' % snapshot['id'],
                                      version='2.32')
        access = {
            'id': 'fake_id',
            'access_type': 'ip',
            'access_to': '1.1.1.1',
            'state': 'new',
        }
        msg = "Share snapshot access exists."

        get = self.mock_object(share_api.API, 'get', mock.Mock(
            return_value=share))
        get_snapshot = self.mock_object(share_api.API, 'get_snapshot',
                                        mock.Mock(return_value=snapshot))
        allow_access = self.mock_object(
            share_api.API, 'snapshot_allow_access', mock.Mock(
                side_effect=exception.ShareSnapshotAccessExists(msg)))

        body = {'allow_access': access}

        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.allow_access, req,
                          snapshot['id'], body)

        get.assert_called_once_with(utils.IsAMatcher(context.RequestContext),
                                    share['id'])
        get_snapshot.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext), snapshot['id'])
        allow_access.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext), snapshot,
            access['access_type'], access['access_to'])

    def test_allow_access_share_without_mount_snap_support(self):
        share = db_utils.create_share(mount_snapshot_support=False)
        snapshot = db_utils.create_snapshot(
            status=constants.STATUS_AVAILABLE, share_id=share['id'])

        access = {
            'id': 'fake_id',
            'access_type': 'ip',
            'access_to': '1.1.1.1',
            'state': 'new',
        }

        get_snapshot = self.mock_object(share_api.API, 'get_snapshot',
                                        mock.Mock(return_value=snapshot))
        get = self.mock_object(share_api.API, 'get',
                               mock.Mock(return_value=share))

        body = {'allow_access': access}
        req = fakes.HTTPRequest.blank('/snapshots/%s/action' % snapshot['id'],
                                      version='2.32')

        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.allow_access, req,
                          snapshot['id'], body)

        get.assert_called_once_with(utils.IsAMatcher(context.RequestContext),
                                    share['id'])
        get_snapshot.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext), snapshot['id'])

    def test_allow_access_empty_parameters(self):
        share = db_utils.create_share(mount_snapshot_support=True)
        snapshot = db_utils.create_snapshot(
            status=constants.STATUS_AVAILABLE, share_id=share['id'])

        access = {'id': 'fake_id',
                  'access_type': '',
                  'access_to': ''}

        body = {'allow_access': access}
        req = fakes.HTTPRequest.blank('/snapshots/%s/action' % snapshot['id'],
                                      version='2.32')

        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.allow_access, req,
                          snapshot['id'], body)

    def test_deny_access(self):
        share = db_utils.create_share(mount_snapshot_support=True)
        snapshot = db_utils.create_snapshot(
            status=constants.STATUS_AVAILABLE, share_id=share['id'])
        access = db_utils.create_snapshot_access(
            share_snapshot_id=snapshot['id'])

        get = self.mock_object(share_api.API, 'get',
                               mock.Mock(return_value=share))
        get_snapshot = self.mock_object(share_api.API, 'get_snapshot',
                                        mock.Mock(return_value=snapshot))
        access_get = self.mock_object(share_api.API, 'snapshot_access_get',
                                      mock.Mock(return_value=access))
        deny_access = self.mock_object(share_api.API, 'snapshot_deny_access')

        body = {'deny_access': {'access_id': access.id}}
        req = fakes.HTTPRequest.blank('/snapshots/%s/action' % snapshot['id'],
                                      version='2.32')

        resp = self.controller.deny_access(req, snapshot['id'], body)

        self.assertEqual(202, resp.status_int)
        get.assert_called_once_with(utils.IsAMatcher(context.RequestContext),
                                    share['id'])
        get_snapshot.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext), snapshot['id'])
        access_get.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext),
            body['deny_access']['access_id'])
        deny_access.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext), snapshot, access)

    def test_deny_access_data_not_found_exception(self):
        share = db_utils.create_share(mount_snapshot_support=True)
        snapshot = db_utils.create_snapshot(
            status=constants.STATUS_AVAILABLE, share_id=share['id'])
        req = fakes.HTTPRequest.blank('/snapshots/%s/action' % snapshot['id'],
                                      version='2.32')
        body = {}

        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.deny_access, req,
                          snapshot['id'], body)

    def test_deny_access_access_rule_not_found(self):
        share = db_utils.create_share(mount_snapshot_support=True)
        snapshot = db_utils.create_snapshot(
            status=constants.STATUS_AVAILABLE, share_id=share['id'])
        access = db_utils.create_snapshot_access(
            share_snapshot_id=snapshot['id'])
        wrong_access = {
            'access_type': 'fake_type',
            'access_to': 'fake_IP',
            'share_snapshot_id': 'fake_id'
        }

        get = self.mock_object(share_api.API, 'get',
                               mock.Mock(return_value=share))
        get_snapshot = self.mock_object(share_api.API, 'get_snapshot',
                                        mock.Mock(return_value=snapshot))
        access_get = self.mock_object(share_api.API, 'snapshot_access_get',
                                      mock.Mock(return_value=wrong_access))

        body = {'deny_access': {'access_id': access.id}}
        req = fakes.HTTPRequest.blank('/snapshots/%s/action' % snapshot['id'],
                                      version='2.32')

        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.deny_access, req, snapshot['id'],
                          body)
        get.assert_called_once_with(utils.IsAMatcher(context.RequestContext),
                                    share['id'])
        get_snapshot.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext), snapshot['id'])
        access_get.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext),
            body['deny_access']['access_id'])

@ddt.ddt
class ShareSnapshotAdminActionsAPITest(test.TestCase):

    def setUp(self):
        super(self.__class__, self).setUp()
        self.controller = share_snapshots.ShareSnapshotsController()
        self.flags(rpc_backend='manila.openstack.common.rpc.impl_fake')
        self.admin_context = context.RequestContext('admin', 'fake', True)
        self.member_context = context.RequestContext('fake', 'fake')

        self.resource_name = self.controller.resource_name
        self.manage_request = fakes.HTTPRequest.blank(
            '/snapshots/manage', use_admin_context=True,
            version=MIN_MANAGE_SNAPSHOT_API_VERSION)
        self.snapshot_id = 'fake'
        self.unmanage_request = fakes.HTTPRequest.blank(
            '/snapshots/%s/unmanage' % self.snapshot_id,
            use_admin_context=True,
            version=MIN_MANAGE_SNAPSHOT_API_VERSION)

    def _get_context(self, role):
        return getattr(self, '%s_context' % role)

    def _setup_snapshot_data(self, snapshot=None, version='2.7'):
        if snapshot is None:
            share = db_utils.create_share()
            snapshot = db_utils.create_snapshot(
                status=constants.STATUS_AVAILABLE, share_id=share['id'])
        req = fakes.HTTPRequest.blank('/v2/fake/snapshots/%s/action' %
                                      snapshot['id'], version=version)
        return snapshot, req

    def _reset_status(self, ctxt, model, req, db_access_method,
                      valid_code, valid_status=None, body=None, version='2.7'):
        if float(version) > 2.6:
            action_name = 'reset_status'
        else:
            action_name = 'os-reset_status'
        if body is None:
            body = {action_name: {'status': constants.STATUS_ERROR}}
        req.method = 'POST'
        req.headers['content-type'] = 'application/json'
        req.headers['X-Openstack-Manila-Api-Version'] = version
        req.body = six.b(jsonutils.dumps(body))
        req.environ['manila.context'] = ctxt

        resp = req.get_response(fakes.app())

        # validate response code and model status
        self.assertEqual(valid_code, resp.status_int)

        if valid_code == 404:
            self.assertRaises(exception.NotFound,
                              db_access_method,
                              ctxt,
                              model['id'])
        else:
            actual_model = db_access_method(ctxt, model['id'])
            self.assertEqual(valid_status, actual_model['status'])

    @ddt.data(*fakes.fixture_reset_status_with_different_roles)
    @ddt.unpack
    def test_snapshot_reset_status_with_different_roles(self, role, valid_code,
                                                        valid_status, version):
        ctxt = self._get_context(role)
        snapshot, req = self._setup_snapshot_data(version=version)

        self._reset_status(ctxt, snapshot, req, db.share_snapshot_get,
                           valid_code, valid_status, version=version)

    @ddt.data(
        ({'os-reset_status': {'x-status': 'bad'}}, '2.6'),
        ({'reset_status': {'x-status': 'bad'}}, '2.7'),
        ({'os-reset_status': {'status': 'invalid'}}, '2.6'),
        ({'reset_status': {'status': 'invalid'}}, '2.7'),
    )
    @ddt.unpack
    def test_snapshot_invalid_reset_status_body(self, body, version):
        snapshot, req = self._setup_snapshot_data(version=version)

        self._reset_status(self.admin_context, snapshot, req,
                           db.share_snapshot_get, 400,
                           constants.STATUS_AVAILABLE, body, version=version)

    def _force_delete(self, ctxt, model, req, db_access_method, valid_code,
                      version='2.7'):
        if float(version) > 2.6:
            action_name = 'force_delete'
        else:
            action_name = 'os-force_delete'
        req.method = 'POST'
        req.headers['content-type'] = 'application/json'
        req.headers['X-Openstack-Manila-Api-Version'] = version
        req.body = six.b(jsonutils.dumps({action_name: {}}))
        req.environ['manila.context'] = ctxt

        resp = req.get_response(fakes.app())

        # Validate response
        self.assertEqual(valid_code, resp.status_int)

    @ddt.data(*fakes.fixture_force_delete_with_different_roles)
    @ddt.unpack
    def test_snapshot_force_delete_with_different_roles(self, role, resp_code,
                                                        version):
        ctxt = self._get_context(role)
        snapshot, req = self._setup_snapshot_data(version=version)

        self._force_delete(ctxt, snapshot, req, db.share_snapshot_get,
                           resp_code, version=version)

    def test_snapshot_force_delete_missing(self):
        ctxt = self._get_context('admin')
        snapshot, req = self._setup_snapshot_data(snapshot={'id': 'fake'})

        self._force_delete(ctxt, snapshot, req, db.share_snapshot_get, 404)

    @ddt.data(
        {},
        {'snapshots': {}},
        {'snapshot': get_fake_manage_body(share_id='xxxxxxxx')},
        {'snapshot': get_fake_manage_body(provider_location='xxxxxxxx')}
    )
    def test_snapshot_manage_invalid_body(self, body):
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        self.assertRaises(webob.exc.HTTPUnprocessableEntity,
                          self.controller.manage,
                          self.manage_request,
                          body)
        self.mock_policy_check.assert_called_once_with(
            self.manage_request.environ['manila.context'],
            self.resource_name, 'manage_snapshot')

    @ddt.data(
        {'version': '2.12',
         'data': get_fake_manage_body(name='foo', display_description='bar')},
        {'version': '2.12',
         'data': get_fake_manage_body(display_name='foo', description='bar')},
        {'version': '2.17',
         'data': get_fake_manage_body(display_name='foo', description='bar')},
        {'version': '2.17',
         'data': get_fake_manage_body(name='foo', display_description='bar')},
    )
    @ddt.unpack
    def test_snapshot_manage(self, version, data):
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        data['snapshot']['share_id'] = 'fake'
        data['snapshot']['provider_location'] = 'fake_volume_snapshot_id'
        data['snapshot']['driver_options'] = {}
        return_snapshot = fake_share.fake_snapshot(
            create_instance=True, id='fake_snap',
            provider_location='fake_volume_snapshot_id')
        self.mock_object(
            share_api.API, 'manage_snapshot', mock.Mock(
                return_value=return_snapshot))
        share_snapshot = {
            'share_id': 'fake',
            'provider_location': 'fake_volume_snapshot_id',
            'display_name': 'foo',
            'display_description': 'bar',
        }

        req = fakes.HTTPRequest.blank(
            '/snapshots/manage', use_admin_context=True, version=version)

        actual_result = self.controller.manage(req, data)

        actual_snapshot = actual_result['snapshot']
        share_api.API.manage_snapshot.assert_called_once_with(
            mock.ANY, share_snapshot, data['snapshot']['driver_options'])
        self.assertEqual(return_snapshot['id'],
                         actual_result['snapshot']['id'])
        self.assertEqual('fake_volume_snapshot_id',
                         actual_result['snapshot']['provider_location'])

        if (api_version.APIVersionRequest(version) >=
                api_version.APIVersionRequest('2.17')):
            self.assertEqual(return_snapshot['user_id'],
                             actual_snapshot['user_id'])
            self.assertEqual(return_snapshot['project_id'],
                             actual_snapshot['project_id'])
        else:
            self.assertNotIn('user_id', actual_snapshot)
            self.assertNotIn('project_id', actual_snapshot)
        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name,
            'manage_snapshot')

    @ddt.data(exception.ShareNotFound(share_id='fake'),
              exception.ShareSnapshotNotFound(snapshot_id='fake'),
              exception.ManageInvalidShareSnapshot(reason='error'),
              exception.InvalidShare(reason='error'))
    def test_manage_exception(self, exception_type):
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        body = get_fake_manage_body(
            share_id='fake', provider_location='fake_volume_snapshot_id',
            driver_options={})
        self.mock_object(
            share_api.API, 'manage_snapshot', mock.Mock(
                side_effect=exception_type))

        http_ex = webob.exc.HTTPNotFound

        if (isinstance(exception_type, exception.ManageInvalidShareSnapshot)
                or isinstance(exception_type, exception.InvalidShare)):
            http_ex = webob.exc.HTTPConflict

        self.assertRaises(http_ex,
                          self.controller.manage,
                          self.manage_request, body)
        self.mock_policy_check.assert_called_once_with(
            self.manage_request.environ['manila.context'],
            self.resource_name, 'manage_snapshot')

    @ddt.data('1.0', '2.6', '2.11')
    def test_manage_version_not_found(self, version):
        body = get_fake_manage_body(
            share_id='fake', provider_location='fake_volume_snapshot_id',
            driver_options={})
        fake_req = fakes.HTTPRequest.blank(
            '/snapshots/manage', use_admin_context=True,
            version=version)

        self.assertRaises(exception.VersionNotFoundForAPIMethod,
                          self.controller.manage,
                          fake_req, body)

    def test_snapshot_unmanage_share_server(self):
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        share = {'status': constants.STATUS_AVAILABLE, 'id': 'bar_id',
                 'share_server_id': 'fake_server_id'}
        self.mock_object(share_api.API, 'get', mock.Mock(return_value=share))
        snapshot = {'status': constants.STATUS_AVAILABLE, 'id': 'foo_id',
                    'share_id': 'bar_id'}
        self.mock_object(share_api.API, 'get_snapshot',
                         mock.Mock(return_value=snapshot))

        self.assertRaises(webob.exc.HTTPForbidden,
                          self.controller.unmanage,
                          self.unmanage_request,
                          snapshot['id'])
        self.controller.share_api.get_snapshot.assert_called_once_with(
            self.unmanage_request.environ['manila.context'], snapshot['id'])
        self.controller.share_api.get.assert_called_once_with(
            self.unmanage_request.environ['manila.context'], share['id'])
        self.mock_policy_check.assert_called_once_with(
            self.unmanage_request.environ['manila.context'],
            self.resource_name, 'unmanage_snapshot')

    def test_snapshot_unmanage_replicated_snapshot(self):
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        share = {'status': constants.STATUS_AVAILABLE, 'id': 'bar_id',
                 'has_replicas': True}
        self.mock_object(share_api.API, 'get', mock.Mock(return_value=share))
        snapshot = {'status': constants.STATUS_AVAILABLE, 'id': 'foo_id',
                    'share_id': 'bar_id'}
        self.mock_object(share_api.API, 'get_snapshot',
                         mock.Mock(return_value=snapshot))

        self.assertRaises(webob.exc.HTTPConflict,
                          self.controller.unmanage,
                          self.unmanage_request,
                          snapshot['id'])
        self.controller.share_api.get_snapshot.assert_called_once_with(
            self.unmanage_request.environ['manila.context'], snapshot['id'])
        self.controller.share_api.get.assert_called_once_with(
            self.unmanage_request.environ['manila.context'], share['id'])
        self.mock_policy_check.assert_called_once_with(
            self.unmanage_request.environ['manila.context'],
            self.resource_name, 'unmanage_snapshot')

    @ddt.data(*constants.TRANSITIONAL_STATUSES)
    def test_snapshot_unmanage_with_transitional_state(self, status):
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        share = {'status': constants.STATUS_AVAILABLE, 'id': 'bar_id'}
        self.mock_object(share_api.API, 'get', mock.Mock(return_value=share))
        snapshot = {'status': status, 'id': 'foo_id', 'share_id': 'bar_id'}
        self.mock_object(
            self.controller.share_api, 'get_snapshot',
            mock.Mock(return_value=snapshot))
        self.assertRaises(
            webob.exc.HTTPForbidden,
            self.controller.unmanage, self.unmanage_request, snapshot['id'])

        self.controller.share_api.get_snapshot.assert_called_once_with(
            self.unmanage_request.environ['manila.context'], snapshot['id'])
        self.controller.share_api.get.assert_called_once_with(
            self.unmanage_request.environ['manila.context'], share['id'])
        self.mock_policy_check.assert_called_once_with(
            self.unmanage_request.environ['manila.context'],
            self.resource_name, 'unmanage_snapshot')

    def test_snapshot_unmanage(self):
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        share = {'status': constants.STATUS_AVAILABLE, 'id': 'bar_id',
                 'host': 'fake_host'}
        self.mock_object(share_api.API, 'get', mock.Mock(return_value=share))
        snapshot = {'status': constants.STATUS_AVAILABLE, 'id': 'foo_id',
                    'share_id': 'bar_id'}
        self.mock_object(share_api.API, 'get_snapshot',
                         mock.Mock(return_value=snapshot))
        self.mock_object(share_api.API, 'unmanage_snapshot', mock.Mock())

        actual_result = self.controller.unmanage(self.unmanage_request,
                                                 snapshot['id'])

        self.assertEqual(202, actual_result.status_int)
        self.controller.share_api.get_snapshot.assert_called_once_with(
            self.unmanage_request.environ['manila.context'], snapshot['id'])
        share_api.API.unmanage_snapshot.assert_called_once_with(
            mock.ANY, snapshot, 'fake_host')
        self.mock_policy_check.assert_called_once_with(
            self.unmanage_request.environ['manila.context'],
            self.resource_name, 'unmanage_snapshot')

    def test_unmanage_share_not_found(self):
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        self.mock_object(
            share_api.API, 'get', mock.Mock(
                side_effect=exception.ShareNotFound(share_id='fake')))
        snapshot = {'status': constants.STATUS_AVAILABLE, 'id': 'foo_id',
                    'share_id': 'bar_id'}
        self.mock_object(share_api.API, 'get_snapshot',
                         mock.Mock(return_value=snapshot))
        self.mock_object(share_api.API, 'unmanage_snapshot', mock.Mock())

        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.unmanage,
                          self.unmanage_request, 'foo_id')
        self.mock_policy_check.assert_called_once_with(
            self.unmanage_request.environ['manila.context'],
            self.resource_name, 'unmanage_snapshot')

    def test_unmanage_snapshot_not_found(self):
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        share = {'status': constants.STATUS_AVAILABLE, 'id': 'bar_id'}
        self.mock_object(share_api.API, 'get', mock.Mock(return_value=share))
        self.mock_object(
            share_api.API, 'get_snapshot', mock.Mock(
                side_effect=exception.ShareSnapshotNotFound(
                    snapshot_id='foo_id')))
        self.mock_object(share_api.API, 'unmanage_snapshot', mock.Mock())

        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.unmanage,
                          self.unmanage_request, 'foo_id')
        self.mock_policy_check.assert_called_once_with(
            self.unmanage_request.environ['manila.context'],
            self.resource_name, 'unmanage_snapshot')

    @ddt.data('1.0', '2.6', '2.11')
    def test_unmanage_version_not_found(self, version):
        snapshot_id = 'fake'
        fake_req = fakes.HTTPRequest.blank(
            '/snapshots/%s/unmanage' % snapshot_id,
            use_admin_context=True,
            version=version)

        self.assertRaises(exception.VersionNotFoundForAPIMethod,
                          self.controller.unmanage,
                          fake_req, 'fake')


text:
 - Update kubectl to the stable version.

### Version 6.1 (Tue November 29 2016 Zihong Zheng <zihongz@google.com>)
 - Support pruning old Deployments.

### Version 6.0 (Fri November 18 2016 Zihong Zheng <zihongz@google.com>)
 - Upgrade Addon Manager to use `kubectl apply`.

### Version 5.2 (Wed October 26 2016 Zihong Zheng <zihongz@google.com>)
 - Added support for ConfigMap and upgraded kubectl version to v1.4.4 (pr #35255)

### Version 5.1 (Mon Jul 4 2016 Marek Grabowski <gmarek@google.com>)
 - Fixed the way addon-manager handles non-namespaced objects

### Version 5 (Fri Jun 24 2016 Jerzy Szczepkowski @jszczepkowski)
 - Added PetSet support to addon manager

### Version 4 (Tue Jun 21 2016 Mike Danese @mikedanese)
 - Increased addon check interval

### Version 3 (Sun Jun 19 2016 Lucas Käldström @luxas)
 - Bumped up addon-manager to v3

### Version 2 (Fri May 20 2016 Lucas Käldström @luxas)
 - Removed deprecated kubectl command, added support for DaemonSets

### Version 1 (Thu May 5 2016 Mike Danese @mikedanese)
 - Run kube-addon-manager in a pod

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/cluster/addons/addon-manager/CHANGELOG.md?pixel)]()


text:
package org.springsource.loaded.ri;

import java.lang.reflect.Field;
import java.util.List;

import org.springsource.loaded.ReloadableType;

/**
 * Implementation of filed lookup algorithm for Class.getDeclaredField.
 *
 * @author Kris De Volder
 * @since 0.5.0
 */
public class GetDeclaredFieldLookup extends FieldLookup {

	public static Field lookup(ReloadableType rtype, String name) {
		FieldRef ref = lookup(FieldProvider.create(rtype), name);
		if (ref == null) {
			return null;
		}
		return ref.getField();
	}

	private static FieldRef lookup(FieldProvider provider, String name) {
		List<FieldRef> fields = provider.getFields();
		for (FieldRef f : fields) {
			if (f.getName().equals(name)) {
				return f;
			}
		}
		return null;
	}

}


text:
package org.apache.flink.runtime.checkpoint;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.runtime.jobmanager.HighAvailabilityMode;
import org.apache.flink.runtime.util.ZooKeeperUtils;

import org.apache.flink.shaded.curator5.org.apache.curator.framework.CuratorFramework;
import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.shared.SharedCount;
import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.shared.VersionedValue;
import org.apache.flink.shaded.curator5.org.apache.curator.framework.state.ConnectionState;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.concurrent.GuardedBy;

import java.util.Optional;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * {@link CheckpointIDCounter} instances for JobManagers running in {@link
 * HighAvailabilityMode#ZOOKEEPER}.
 *
 *
Each counter creates a ZNode:
 *
 *

 * +----O /flink/checkpoint-counter/<job-id> 1 [persistent]
 * .
 * .
 * .
 * +----O /flink/checkpoint-counter/<job-id> N [persistent]
 *

 *
 *
The checkpoints IDs are required to be ascending (per job). In order to guarantee this in case
 * of job manager failures we use ZooKeeper to have a shared counter across job manager instances.
 */
public class ZooKeeperCheckpointIDCounter implements CheckpointIDCounter {

    private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperCheckpointIDCounter.class);

    /** Curator ZooKeeper client. */
    private final CuratorFramework client;

    /** Path of the shared count. */
    private final String counterPath;

    /** Curator recipe for shared counts. */
    private final SharedCount sharedCount;

    private final LastStateConnectionStateListener connectionStateListener;

    private final Object startStopLock = new Object();

    @GuardedBy("startStopLock")
    private boolean isStarted;

    /**
     * Creates a {@link ZooKeeperCheckpointIDCounter} instance.
     *
     * @param client Curator ZooKeeper client
     */
    public ZooKeeperCheckpointIDCounter(
            CuratorFramework client, LastStateConnectionStateListener connectionStateListener) {
        this.client = checkNotNull(client, "Curator client");
        this.counterPath = ZooKeeperUtils.getCheckpointIdCounterPath();
        this.sharedCount = new SharedCount(client, counterPath, INITIAL_CHECKPOINT_ID);
        this.connectionStateListener = connectionStateListener;
    }

    @Override
    public void start() throws Exception {
        synchronized (startStopLock) {
            if (!isStarted) {
                sharedCount.start();

                client.getConnectionStateListenable().addListener(connectionStateListener);

                isStarted = true;
            }
        }
    }

    @Override
    public void shutdown(JobStatus jobStatus) throws Exception {
        synchronized (startStopLock) {
            if (isStarted) {
                LOG.info("Shutting down.");
                sharedCount.close();

                client.getConnectionStateListenable().removeListener(connectionStateListener);

                if (jobStatus.isGloballyTerminalState()) {
                    LOG.info("Removing {} from ZooKeeper", counterPath);
                    client.delete().deletingChildrenIfNeeded().inBackground().forPath(counterPath);
                }

                isStarted = false;
            }
        }
    }

    @Override
    public long getAndIncrement() throws Exception {
        while (true) {
            checkConnectionState();

            VersionedValue<Integer> current = sharedCount.getVersionedValue();
            int newCount = current.getValue() + 1;

            if (newCount < 0) {
                // overflow and wrap around
                throw new Exception(
                        "Checkpoint counter overflow. ZooKeeper checkpoint counter only supports "
                                + "checkpoints Ids up to "
                                + Integer.MAX_VALUE);
            }

            if (sharedCount.trySetCount(current, newCount)) {
                return current.getValue();
            }
        }
    }

    @Override
    public long get() {
        checkConnectionState();

        return sharedCount.getVersionedValue().getValue();
    }

    @Override
    public void setCount(long newId) throws Exception {
        checkConnectionState();

        if (newId > Integer.MAX_VALUE) {
            throw new IllegalArgumentException(
                    "ZooKeeper checkpoint counter only supports "
                            + "checkpoints Ids up to "
                            + Integer.MAX_VALUE
                            + ", but given value is"
                            + newId);
        }

        sharedCount.setCount((int) newId);
    }

    private void checkConnectionState() {
        final Optional<ConnectionState> optionalLastState = connectionStateListener.getLastState();

        optionalLastState.ifPresent(
                lastState -> {
                    if (lastState != ConnectionState.CONNECTED
                            && lastState != ConnectionState.RECONNECTED) {
                        throw new IllegalStateException("Connection state: " + lastState);
                    }
                });
    }

    @VisibleForTesting
    String getPath() {
        return counterPath;
    }
}


text:
app.models = app.models || {};

/**
 * The model for the application configuration
 */
app.models.Config =  (function () {

    var UNITS = {

        metric: {
            mass           : 'kg',
            temperature    : '°C',
            volume         : 'l',
            pressure       : 'bar',
            length         : 'm',
            density        : 'kg/l',
            'mass-fraction': 'kg/kg'
        },

        imperial: {
            mass           : 'lb',
            temperature    : '°F',
            volume         : 'cuft',
            pressure       : 'psi',
            length         : 'ft',
            density        : 'lb/cuft',
            'mass-fraction': 'lb/lb'
        }
    };

    return app.models.BaseModel.extend({

        initialize: function (attributes) {

            this.syncer = app.sync.Syncer.getSync('app.model.Config', 'default');

            // check attributes

            if (this.validateDefined(attributes, ['unitSystem']) || ! UNITS[attributes.unitSystem]) {
                return;
            }

            attributes.units = UNITS[attributes.unitSystem];

            this.set('units', attributes.units);

        },

        defaults : {
            unitSystem: undefined,  // the unit system in 'metric','imperial'
            units: {}               // the unit for each measure
        },

        validate: function (attrs) {
            return this.validateDefined(attrs, ['unitSystem','units']);
        }

    });

})();


text:
<?php
namespace DreamCommerce\LicenseManager\Tests\Symfony2Bundle;

use DreamCommerce\LicenseManagerClientBundle\DependencyInjection\DreamCommerceLicenseManagerClientExtension;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;

class DependencyInjectionTest extends AbstractExtensionTestCase
{
    private $defaultConfig = [
        'api_url' => 'api-url',
        'username' => 'foo',
        'password' => 'bar'
    ];

    /**
     * @test
     */
    public function shouldLoadParameterApiUrlFromConfig()
    {
        $this->load();
        $this->assertContainerBuilderHasParameter('dream_commerce_license_manager.api_url', 'api-url');
    }

    /**
     * @test
     */
    public function shouldLoadParameterUsernameFromConfig()
    {
        $this->load();
        $this->assertContainerBuilderHasParameter('dream_commerce_license_manager.username', 'foo');
    }

    /**
     * @test
     */
    public function shouldLoadParameterPasswordFromConfig()
    {
        $this->load();
        $this->assertContainerBuilderHasParameter('dream_commerce_license_manager.password', 'bar');
    }

    /**
     * @test
     */
    public function shouldAddLicenseManagerClientToContainer()
    {
        $this->load();
        $this->assertContainerBuilderHasService('dream_commerce.license_manager_client', 'DreamCommerce\LicenseManager\LicenseManagerClient');
    }

    protected function getContainerExtensions()
    {
        return [new DreamCommerceLicenseManagerClientExtension ()];
    }

    /**
     * @param array $configurationValues
     */
    protected function load(array $configurationValues = array()) {
        parent::load(array_merge_recursive($this->defaultConfig, $configurationValues));
    }
}


text:
layout: pattern
title: Service Locator
folder: service-locator
permalink: /patterns/service-locator/
categories: Architectural
tags:
 - Game programming
 - Performance
---

## Intent
Encapsulate the processes involved in obtaining a service with a
strong abstraction layer.

## Class diagram
![alt text](./etc/service-locator.png "Service Locator")

## Applicability
The service locator pattern is applicable whenever we want
to locate/fetch various services using JNDI which, typically, is a redundant
and expensive lookup. The service Locator pattern addresses this expensive
lookup by making use of caching techniques ie. for the very first time a
particular service is requested, the service Locator looks up in JNDI, fetched
the relevant service and then finally caches this service object. Now, further
lookups of the same service via Service Locator is done in its cache which
improves the performance of application to great extent.

## Typical Use Case

* When network hits are expensive and time consuming
* Lookups of services are done quite frequently
* Large number of services are being used

## Consequences

* Violates Interface Segregation Principle (ISP) by providing pattern consumers with an access
to a number of services that they don't potentially need.
* Creates hidden dependencies that can break the clients at runtime.

## Credits

* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31)


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/servicedirectory/v1beta1/service.proto

namespace Google\Cloud\ServiceDirectory\V1beta1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * An individual service. A service contains a name and optional metadata.
 * A service must exist before
 * [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] can be
 * added to it.
 *
 * Generated from protobuf message google.cloud.servicedirectory.v1beta1.Service
 */
class Service extends \Google\Protobuf\Internal\Message
{
    /**
     * Immutable. The resource name for the service in the format
     * `projects/*/locations/*/namespaces/*/services/*`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = IMMUTABLE];
     */
    private $name = '';
    /**
     * Optional. Metadata for the service. This data can be consumed by service
     * clients.
     * Restrictions:
     * *   The entire metadata dictionary may contain up to 2000 characters,
     *     spread accoss all key-value pairs. Metadata that goes beyond this
     *     limit are rejected
     * *   Valid metadata keys have two segments: an optional prefix and name,
     *     separated by a slash (/). The name segment is required and must be 63
     *     characters or less, beginning and ending with an alphanumeric character
     *     ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and
     *     alphanumerics between. The prefix is optional. If specified, the prefix
     *     must be a DNS subdomain: a series of DNS labels separated by dots (.),
     *     not longer than 253 characters in total, followed by a slash (/).
     *     Metadata that fails to meet these requirements are rejected
     * *   The `(*.)google.com/` and `(*.)googleapis.com/` prefixes are reserved
     *     for system metadata managed by Service Directory. If the user tries
     *     to write to these keyspaces, those entries are silently ignored by
     *     the system
     * Note: This field is equivalent to the `annotations` field in the v1 API.
     * They have the same syntax and read/write to the same location in Service
     * Directory.
     *
     * Generated from protobuf field map<string, string> metadata = 2 [(.google.api.field_behavior) = OPTIONAL];
     */
    private $metadata;
    /**
     * Output only. Endpoints associated with this service. Returned on
     * [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. Control plane clients should use
     * [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints].
     *
     * Generated from protobuf field repeated .google.cloud.servicedirectory.v1beta1.Endpoint endpoints = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];
     */
    private $endpoints;
    /**
     * Output only. The timestamp when the service was created.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];
     */
    private $create_time = null;
    /**
     * Output only. The timestamp when the service was last updated. Note: endpoints being
     * created/deleted/updated within the service are not considered service
     * updates for the purpose of this timestamp.
     *
     * Generated from protobuf field .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];
     */
    private $update_time = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Immutable. The resource name for the service in the format
     *           `projects/*/locations/*/namespaces/*/services/*`.
     *     @type array|\Google\Protobuf\Internal\MapField $metadata
     *           Optional. Metadata for the service. This data can be consumed by service
     *           clients.
     *           Restrictions:
     *           *   The entire metadata dictionary may contain up to 2000 characters,
     *               spread accoss all key-value pairs. Metadata that goes beyond this
     *               limit are rejected
     *           *   Valid metadata keys have two segments: an optional prefix and name,
     *               separated by a slash (/). The name segment is required and must be 63
     *               characters or less, beginning and ending with an alphanumeric character
     *               ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and
     *               alphanumerics between. The prefix is optional. If specified, the prefix
     *               must be a DNS subdomain: a series of DNS labels separated by dots (.),
     *               not longer than 253 characters in total, followed by a slash (/).
     *               Metadata that fails to meet these requirements are rejected
     *           *   The `(*.)google.com/` and `(*.)googleapis.com/` prefixes are reserved
     *               for system metadata managed by Service Directory. If the user tries
     *               to write to these keyspaces, those entries are silently ignored by
     *               the system
     *           Note: This field is equivalent to the `annotations` field in the v1 API.
     *           They have the same syntax and read/write to the same location in Service
     *           Directory.
     *     @type array<\Google\Cloud\ServiceDirectory\V1beta1\Endpoint>|\Google\Protobuf\Internal\RepeatedField $endpoints
     *           Output only. Endpoints associated with this service. Returned on
     *           [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. Control plane clients should use
     *           [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints].
     *     @type \Google\Protobuf\Timestamp $create_time
     *           Output only. The timestamp when the service was created.
     *     @type \Google\Protobuf\Timestamp $update_time
     *           Output only. The timestamp when the service was last updated. Note: endpoints being
     *           created/deleted/updated within the service are not considered service
     *           updates for the purpose of this timestamp.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Servicedirectory\V1Beta1\Service::initOnce();
        parent::__construct($data);
    }

    /**
     * Immutable. The resource name for the service in the format
     * `projects/*/locations/*/namespaces/*/services/*`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = IMMUTABLE];
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Immutable. The resource name for the service in the format
     * `projects/*/locations/*/namespaces/*/services/*`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = IMMUTABLE];
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

    /**
     * Optional. Metadata for the service. This data can be consumed by service
     * clients.
     * Restrictions:
     * *   The entire metadata dictionary may contain up to 2000 characters,
     *     spread accoss all key-value pairs. Metadata that goes beyond this
     *     limit are rejected
     * *   Valid metadata keys have two segments: an optional prefix and name,
     *     separated by a slash (/). The name segment is required and must be 63
     *     characters or less, beginning and ending with an alphanumeric character
     *     ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and
     *     alphanumerics between. The prefix is optional. If specified, the prefix
     *     must be a DNS subdomain: a series of DNS labels separated by dots (.),
     *     not longer than 253 characters in total, followed by a slash (/).
     *     Metadata that fails to meet these requirements are rejected
     * *   The `(*.)google.com/` and `(*.)googleapis.com/` prefixes are reserved
     *     for system metadata managed by Service Directory. If the user tries
     *     to write to these keyspaces, those entries are silently ignored by
     *     the system
     * Note: This field is equivalent to the `annotations` field in the v1 API.
     * They have the same syntax and read/write to the same location in Service
     * Directory.
     *
     * Generated from protobuf field map<string, string> metadata = 2 [(.google.api.field_behavior) = OPTIONAL];
     * @return \Google\Protobuf\Internal\MapField
     */
    public function getMetadata()
    {
        return $this->metadata;
    }

    /**
     * Optional. Metadata for the service. This data can be consumed by service
     * clients.
     * Restrictions:
     * *   The entire metadata dictionary may contain up to 2000 characters,
     *     spread accoss all key-value pairs. Metadata that goes beyond this
     *     limit are rejected
     * *   Valid metadata keys have two segments: an optional prefix and name,
     *     separated by a slash (/). The name segment is required and must be 63
     *     characters or less, beginning and ending with an alphanumeric character
     *     ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and
     *     alphanumerics between. The prefix is optional. If specified, the prefix
     *     must be a DNS subdomain: a series of DNS labels separated by dots (.),
     *     not longer than 253 characters in total, followed by a slash (/).
     *     Metadata that fails to meet these requirements are rejected
     * *   The `(*.)google.com/` and `(*.)googleapis.com/` prefixes are reserved
     *     for system metadata managed by Service Directory. If the user tries
     *     to write to these keyspaces, those entries are silently ignored by
     *     the system
     * Note: This field is equivalent to the `annotations` field in the v1 API.
     * They have the same syntax and read/write to the same location in Service
     * Directory.
     *
     * Generated from protobuf field map<string, string> metadata = 2 [(.google.api.field_behavior) = OPTIONAL];
     * @param array|\Google\Protobuf\Internal\MapField $var
     * @return $this
     */
    public function setMetadata($var)
    {
        $arr = GPBUtil::checkMapField($var, \Google\Protobuf\Internal\GPBType::STRING, \Google\Protobuf\Internal\GPBType::STRING);
        $this->metadata = $arr;

        return $this;
    }

    /**
     * Output only. Endpoints associated with this service. Returned on
     * [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. Control plane clients should use
     * [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints].
     *
     * Generated from protobuf field repeated .google.cloud.servicedirectory.v1beta1.Endpoint endpoints = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getEndpoints()
    {
        return $this->endpoints;
    }

    /**
     * Output only. Endpoints associated with this service. Returned on
     * [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. Control plane clients should use
     * [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints].
     *
     * Generated from protobuf field repeated .google.cloud.servicedirectory.v1beta1.Endpoint endpoints = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @param array<\Google\Cloud\ServiceDirectory\V1beta1\Endpoint>|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setEndpoints($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\ServiceDirectory\V1beta1\Endpoint::class);
        $this->endpoints = $arr;

        return $this;
    }

    /**
     * Output only. The timestamp when the service was created.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getCreateTime()
    {
        return $this->create_time;
    }

    public function hasCreateTime()
    {
        return isset($this->create_time);
    }

    public function clearCreateTime()
    {
        unset($this->create_time);
    }

    /**
     * Output only. The timestamp when the service was created.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setCreateTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->create_time = $var;

        return $this;
    }

    /**
     * Output only. The timestamp when the service was last updated. Note: endpoints being
     * created/deleted/updated within the service are not considered service
     * updates for the purpose of this timestamp.
     *
     * Generated from protobuf field .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getUpdateTime()
    {
        return $this->update_time;
    }

    public function hasUpdateTime()
    {
        return isset($this->update_time);
    }

    public function clearUpdateTime()
    {
        unset($this->update_time);
    }

    /**
     * Output only. The timestamp when the service was last updated. Note: endpoints being
     * created/deleted/updated within the service are not considered service
     * updates for the purpose of this timestamp.
     *
     * Generated from protobuf field .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setUpdateTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->update_time = $var;

        return $this;
    }

}


text:
'use strict';

angular.module('myApp.projects', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/projects', {
    templateUrl: 'pages/projects/projects.html',
    controller: 'ProjectsCtrl'
  });
}])

.controller('ProjectsCtrl', function($scope) {

      $scope.form = {
        data: {
          new: 'Beng!'
        },
        settings: {

        }

      }

      $scope.new = 'Finaly is everything working';

});