text:
try:
    import unittest2 as unittest
except ImportError:
    import unittest  # noqa

from functools import partial
from six.moves import range
import sys
from threading import Thread, Event
import time

from cassandra import ConsistencyLevel, OperationTimedOut
from cassandra.cluster import NoHostAvailable, ConnectionShutdown, Cluster
from cassandra.io.asyncorereactor import AsyncoreConnection
from cassandra.protocol import QueryMessage
from cassandra.connection import Connection
from cassandra.policies import WhiteListRoundRobinPolicy, HostStateListener
from cassandra.pool import HostConnectionPool

from tests import is_monkey_patched
from tests.integration import use_singledc, PROTOCOL_VERSION, get_node, CASSANDRA_IP, local

try:
    from cassandra.io.libevreactor import LibevConnection
except ImportError:
    LibevConnection = None

def setup_module():
    use_singledc()

class ConnectionTimeoutTest(unittest.TestCase):

    def setUp(self):
        self.defaultInFlight = Connection.max_in_flight
        Connection.max_in_flight = 2
        self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, load_balancing_policy=
                            WhiteListRoundRobinPolicy([CASSANDRA_IP]))
        self.session = self.cluster.connect()

    def tearDown(self):
        Connection.max_in_flight = self.defaultInFlight
        self.cluster.shutdown()

    def test_in_flight_timeout(self):
        """
        Test to ensure that connection id fetching will block when max_id is reached/

        In previous versions of the driver this test will cause a
        NoHostAvailable exception to be thrown, when the max_id is restricted

        @since 3.3
        @jira_ticket PYTHON-514
        @expected_result When many requests are run on a single node connection acquisition should block
        until connection is available or the request times out.

        @test_category connection timeout
        """
        futures = []
        query = '''SELECT * FROM system.local'''
        for i in range(100):
            futures.append(self.session.execute_async(query))

        for future in futures:
            future.result()

class TestHostListener(HostStateListener):
    host_down = None

    def on_down(self, host):
        host_down = host

class HeartbeatTest(unittest.TestCase):
    """
    Test to validate failing a heartbeat check doesn't mark a host as down

    @since 3.3
    @jira_ticket PYTHON-286
    @expected_result host should not be marked down when heartbeat fails

    @test_category connection heartbeat
    """

    def setUp(self):
        self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, idle_heartbeat_interval=1)
        self.session = self.cluster.connect(wait_for_all_pools=True)

    def tearDown(self):
        self.cluster.shutdown()

    @local
    def test_heart_beat_timeout(self):
        # Setup a host listener to ensure the nodes don't go down
        test_listener = TestHostListener()
        host = "127.0.0.1"
        node = get_node(1)
        initial_connections = self.fetch_connections(host, self.cluster)
        self.assertNotEqual(len(initial_connections), 0)
        self.cluster.register_listener(test_listener)
        # Pause the node
        try:
            node.pause()
            # Wait for connections associated with this host go away
            self.wait_for_no_connections(host, self.cluster)
            # Resume paused node
        finally:
            node.resume()
        # Run a query to ensure connections are re-established
        current_host = ""
        count = 0
        while current_host != host and count < 100:
            rs = self.session.execute_async("SELECT * FROM system.local", trace=False)
            rs.result()
            current_host = str(rs._current_host)
            count += 1
            time.sleep(.1)
        self.assertLess(count, 100, "Never connected to the first node")
        new_connections = self.wait_for_connections(host, self.cluster)
        self.assertIsNone(test_listener.host_down)
        # Make sure underlying new connections don't match previous ones
        for connection in initial_connections:
            self.assertFalse(connection in new_connections)

    def fetch_connections(self, host, cluster):
        # Given a cluster object and host grab all connection associated with that host
        connections = []
        holders = cluster.get_connection_holders()
        for conn in holders:
            if host == str(getattr(conn, 'host', '')):
                if isinstance(conn, HostConnectionPool):
                    if conn._connections is not None and len(conn._connections) > 0:
                        connections.append(conn._connections)
                else:
                    if conn._connection is not None:
                        connections.append(conn._connection)
        return connections

    def wait_for_connections(self, host, cluster):
        retry = 0
        while(retry < 300):
            retry += 1
            connections = self.fetch_connections(host, cluster)
            if len(connections) is not 0:
                return connections
            time.sleep(.1)
        self.fail("No new connections found")

    def wait_for_no_connections(self, host, cluster):
        retry = 0
        while(retry < 100):
            retry += 1
            connections = self.fetch_connections(host, cluster)
            if len(connections) is 0:
                return
            time.sleep(.5)
        self.fail("Connections never cleared")

class ConnectionTests(object):

    klass = None

    def setUp(self):
        self.klass.initialize_reactor()

    def get_connection(self, timeout=5):
        """
        Helper method to solve automated testing issues within Jenkins.
        Officially patched under the 2.0 branch through
        17998ef72a2fe2e67d27dd602b6ced33a58ad8ef, but left as is for the
        1.0 branch due to possible regressions for fixing an
        automated testing edge-case.
        """
        conn = None
        e = None
        for i in range(5):
            try:
                contact_point = CASSANDRA_IP
                conn = self.klass.factory(host=contact_point, timeout=timeout, protocol_version=PROTOCOL_VERSION)
                break
            except (OperationTimedOut, NoHostAvailable, ConnectionShutdown) as e:
                continue

        if conn:
            return conn
        else:
            raise e

    def test_single_connection(self):
        """
        Test a single connection with sequential requests.
        """
        conn = self.get_connection()
        query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1"
        event = Event()

        def cb(count, *args, **kwargs):
            count += 1
            if count >= 10:
                conn.close()
                event.set()
            else:
                conn.send_msg(
                    QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE),
                    request_id=0,
                    cb=partial(cb, count))

        conn.send_msg(
            QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE),
            request_id=0,
            cb=partial(cb, 0))
        event.wait()

    def test_single_connection_pipelined_requests(self):
        """
        Test a single connection with pipelined requests.
        """
        conn = self.get_connection()
        query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1"
        responses = [False] * 100
        event = Event()

        def cb(response_list, request_num, *args, **kwargs):
            response_list[request_num] = True
            if all(response_list):
                conn.close()
                event.set()

        for i in range(100):
            conn.send_msg(
                QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE),
                request_id=i,
                cb=partial(cb, responses, i))

        event.wait()

    def test_multiple_connections(self):
        """
        Test multiple connections with pipelined requests.
        """
        conns = [self.get_connection() for i in range(5)]
        events = [Event() for i in range(5)]
        query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1"

        def cb(event, conn, count, *args, **kwargs):
            count += 1
            if count >= 10:
                conn.close()
                event.set()
            else:
                conn.send_msg(
                    QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE),
                    request_id=count,
                    cb=partial(cb, event, conn, count))

        for event, conn in zip(events, conns):
            conn.send_msg(
                QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE),
                request_id=0,
                cb=partial(cb, event, conn, 0))

        for event in events:
            event.wait()

    def test_multiple_threads_shared_connection(self):
        """
        Test sharing a single connections across multiple threads,
        which will result in pipelined requests.
        """
        num_requests_per_conn = 25
        num_threads = 5
        event = Event()

        conn = self.get_connection()
        query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1"

        def cb(all_responses, thread_responses, request_num, *args, **kwargs):
            thread_responses[request_num] = True
            if all(map(all, all_responses)):
                conn.close()
                event.set()

        def send_msgs(all_responses, thread_responses):
            for i in range(num_requests_per_conn):
                qmsg = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE)
                with conn.lock:
                    request_id = conn.get_request_id()
                conn.send_msg(qmsg, request_id, cb=partial(cb, all_responses, thread_responses, i))

        all_responses = []
        threads = []
        for i in range(num_threads):
            thread_responses = [False] * num_requests_per_conn
            all_responses.append(thread_responses)
            t = Thread(target=send_msgs, args=(all_responses, thread_responses))
            threads.append(t)

        for t in threads:
            t.start()

        for t in threads:
            t.join()

        event.wait()

    def test_multiple_threads_multiple_connections(self):
        """
        Test several threads, each with their own Connection and pipelined
        requests.
        """
        num_requests_per_conn = 25
        num_conns = 5
        events = [Event() for i in range(5)]

        query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1"

        def cb(conn, event, thread_responses, request_num, *args, **kwargs):
            thread_responses[request_num] = True
            if all(thread_responses):
                conn.close()
                event.set()

        def send_msgs(conn, event):
            thread_responses = [False] * num_requests_per_conn
            for i in range(num_requests_per_conn):
                qmsg = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE)
                with conn.lock:
                    request_id = conn.get_request_id()
                conn.send_msg(qmsg, request_id, cb=partial(cb, conn, event, thread_responses, i))

            event.wait()

        threads = []
        for i in range(num_conns):
            conn = self.get_connection()
            t = Thread(target=send_msgs, args=(conn, events[i]))
            threads.append(t)

        for t in threads:
            t.start()

        for t in threads:
            t.join()

    def test_connect_timeout(self):
        # Underlying socket implementations don't always throw a socket timeout even with min float
        # This can be timing sensitive, added retry to ensure failure occurs if it can
        max_retry_count = 10
        exception_thrown = False
        for i in range(max_retry_count):
            start = time.time()
            try:
                conn = self.get_connection(timeout=sys.float_info.min)
                conn.close()
            except Exception as e:
                end = time.time()
                self.assertAlmostEqual(start, end, 1)
                exception_thrown = True
                break
        self.assertTrue(exception_thrown)

class AsyncoreConnectionTests(ConnectionTests, unittest.TestCase):

    klass = AsyncoreConnection

    def setUp(self):
        if is_monkey_patched():
            raise unittest.SkipTest("Can't test asyncore with monkey patching")
        ConnectionTests.setUp(self)

class LibevConnectionTests(ConnectionTests, unittest.TestCase):

    klass = LibevConnection

    def setUp(self):
        if is_monkey_patched():
            raise unittest.SkipTest("Can't test libev with monkey patching")
        if LibevConnection is None:
            raise unittest.SkipTest(
                'libev does not appear to be installed properly')
        ConnectionTests.setUp(self)


text:
<?xml version="1.0" encoding="utf-8"?>
<View xmlns="http://schemas.mediachase.com/ecf/view">
	<ListViewUI>
		<Grid>
			<add>
				<Columns>
					<Column columnType="CheckBox" />
					<Column headingText="{SharedStrings:Name}" id="name" width="300" columnType="HyperLink" allowSorting="true" dataNavigateUrlFields="CampaignId" dataNavigateUrlFormatString="javascript:CSManagementClient.ChangeView('Marketing', 'Campaign-Edit','campaignid={0}');" dataTextFields="Name" dataTextFormatString="{0}" dataField="name" permissions="marketing:campaigns:mng:edit" />
					<Column width="150" columnType="DateTime" allowSorting="true" dataField="StartDate" headingText="{SharedStrings:Starts}" />
					<Column width="150" columnType="DateTime" allowSorting="true" dataField="EndDate" headingText="{SharedStrings:Ends}" />
					<Column width="50" allowSorting="true" dataField="IsActive" headingText="{SharedStrings:Is_Active}" />
					<Column width="150" columnType="DateTime" allowSorting="true" dataField="Modified" headingText="{SharedStrings:Last_Modified}" />
					<Column width="150" columnType="DateTime" allowSorting="true" dataField="Created" headingText="{SharedStrings:Created}" />
				</Columns>
			</add>
		</Grid>
		<Toolbar>
			<add>
				<Button id="NewCampaign" text="{SharedStrings:New_Campaign}" imageUrl="~/Apps/Shell/styles/Images/new.png" commandName="cmdMarketingCampaignNew" permissions="marketing:campaigns:mng:create"/>
				<Splitter id="ActionsSplitter"/>
				<Menu id="MoreActionsSplitButton" text="{SharedStrings:More_Actions}" imageUrl="~/Apps/Shell/styles/Images/toolbar/newtask.gif" permissions="marketing:campaigns:mng:delete">
					<Button id="DeleteSelected" text="{SharedStrings:Delete_Selected}" imageUrl="~/Apps/Shell/styles/Images/toolbar/delete.gif" commandName="cmdMarketingCampaignDelete" permissions="marketing:campaigns:mng:delete" />
				</Menu>
			</add>
		</Toolbar>

		<Commands>
			<add>
				<Command id="cmdMarketingCampaignNew">
					<CommandType>ClientAction</CommandType>
					<ClientScript>CSMarketingClient.NewCampaign()</ClientScript>
					<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.PermissionEnableHandler, Mediachase.ConsoleManager" />
				</Command>
				<Command id="cmdMarketingCampaignDelete">
					<EnableHandler type="Mediachase.Commerce.Manager.CommandHandlers.CommonEnableHandler, Mediachase.ConsoleManager" />
					<BeforeClientScript>Toolbar_GridHasItemsSelected</BeforeClientScript>
					<ConfirmationText>{CommerceManager:DeleteSelectedItemsConfirmation}</ConfirmationText>
					<CommandType>ServerAction</CommandType>
					<Handler type="Mediachase.Commerce.Manager.Marketing.CommandHandlers.CampaignDeleteHandler, Mediachase.ConsoleManager" />
					<UpdatePanelIds>panelMainListView</UpdatePanelIds>
				</Command>
			</add>
		</Commands>
	</ListViewUI>
	<ViewConfig>
		<setAttributes id="Campaign-List" controlUrl="Marketing/CampaignList.ascx" permissions="marketing:campaigns:mng:view" help="Campaigns" />
	</ViewConfig>
</View>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.shindig.gadgets.servlet;

import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isA;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.auth.SecurityTokenCodec;
import org.apache.shindig.auth.SecurityTokenException;
import org.apache.shindig.common.EasyMockTestCase;
import org.apache.shindig.common.servlet.HttpUtil;
import org.apache.shindig.common.uri.Uri;
import org.apache.shindig.common.util.FakeTimeSource;
import org.apache.shindig.gadgets.Gadget;
import org.apache.shindig.gadgets.GadgetContext;
import org.apache.shindig.gadgets.GadgetException;
import org.apache.shindig.gadgets.GadgetException.Code;
import org.apache.shindig.gadgets.RenderingContext;
import org.apache.shindig.gadgets.admin.ContainerAdminData;
import org.apache.shindig.gadgets.admin.FeatureAdminData;
import org.apache.shindig.gadgets.admin.FeatureAdminData.Type;
import org.apache.shindig.gadgets.admin.GadgetAdminData;
import org.apache.shindig.gadgets.admin.GadgetAdminStore;
import org.apache.shindig.gadgets.features.ApiDirective;
import org.apache.shindig.gadgets.features.FeatureRegistry;
import org.apache.shindig.gadgets.features.FeatureRegistry.FeatureBundle;
import org.apache.shindig.gadgets.features.FeatureRegistryProvider;
import org.apache.shindig.gadgets.http.HttpResponse;
import org.apache.shindig.gadgets.http.HttpResponseBuilder;
import org.apache.shindig.gadgets.js.JsException;
import org.apache.shindig.gadgets.js.JsRequest;
import org.apache.shindig.gadgets.js.JsRequestBuilder;
import org.apache.shindig.gadgets.js.JsResponseBuilder;
import org.apache.shindig.gadgets.js.JsServingPipeline;
import org.apache.shindig.gadgets.process.ProcessingException;
import org.apache.shindig.gadgets.servlet.GadgetsHandlerApi.Feature;
import org.apache.shindig.gadgets.uri.JsUriManager;
import org.apache.shindig.gadgets.uri.JsUriManager.JsUri;
import org.apache.shindig.gadgets.uri.ProxyUriManager;
import org.apache.shindig.gadgets.uri.ProxyUriManager.ProxyUri;
import org.apache.shindig.protocol.conversion.BeanDelegator;
import org.apache.shindig.protocol.conversion.BeanFilter;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;

public class GadgetsHandlerServiceTest extends EasyMockTestCase {

  private static final String TOKEN = "<token data>";
  private static final String OWNER = "<owner>";
  private static final String VIEWER = "<viewer>";
  private static final String CONTAINER = "container";
  private static final Long CURRENT_TIME_MS = 123L;
  private static final Long SPEC_REFRESH_INTERVAL_MS = 456L;
  private static final Long METADATA_EXPIRY_TIME_MS = CURRENT_TIME_MS + SPEC_REFRESH_INTERVAL_MS;
  private static final Long TOKEN_EXPIRY_TIME_MS = CURRENT_TIME_MS + 789L;
  private static final Uri RESOURCE = Uri.parse("http://example.com/data");
  private static final String FALLBACK = "http://example.com/data2";
  private static final String RPC_SERVICE_1 = "rcp_service_1";
  private static final String RPC_SERVICE_2 = "rpc_service_2";

  private final BeanDelegator delegator = new BeanDelegator(GadgetsHandlerService.API_CLASSES,
          GadgetsHandlerService.ENUM_CONVERSION_MAP);

  private final FakeTimeSource timeSource = new FakeTimeSource(CURRENT_TIME_MS);
  private final FeatureRegistry mockRegistry = mock(FeatureRegistry.class);
  private final FakeProcessor processor = new FakeProcessor(mockRegistry);
  private final FakeIframeUriManager urlGenerator = new FakeIframeUriManager();
  private final ProxyUriManager proxyUriManager = mock(ProxyUriManager.class);
  private final JsUriManager jsUriManager = mock(JsUriManager.class);
  private final ProxyHandler proxyHandler = mock(ProxyHandler.class);
  private final CajaContentRewriter cajaContentRewriter = mock(CajaContentRewriter.class);
  private final JsServingPipeline jsPipeline = mock(JsServingPipeline.class);
  private final JsRequestBuilder jsRequestBuilder = new JsRequestBuilder(jsUriManager, null);
  private final GadgetAdminStore gadgetAdminStore = mock(GadgetAdminStore.class);

  private FakeSecurityTokenCodec tokenCodec;
  private GadgetsHandlerService gadgetHandler;
  private GadgetsHandlerService gadgetHandlerWithAdmin;
  private FeatureRegistryProvider featureRegistryProvider;

  @Before
  public void setUp() {
    tokenCodec = new FakeSecurityTokenCodec();
    GadgetAdminData gadgetAdminData = new GadgetAdminData(
            new FeatureAdminData(Sets.newHashSet(FakeProcessor.FEATURE2, FakeProcessor.FEATURE3),
                    Type.WHITELIST));
    ContainerAdminData containerAdminData = new ContainerAdminData();
    containerAdminData.addGadgetAdminData(FakeProcessor.SPEC_URL4.toString(), gadgetAdminData);
    featureRegistryProvider = new FeatureRegistryProvider() {
      public FeatureRegistry get(String repository) throws GadgetException {
        return mockRegistry;
      }
    };
    gadgetHandler = new GadgetsHandlerService(timeSource, processor, urlGenerator, tokenCodec,
            proxyUriManager, jsUriManager, proxyHandler, jsPipeline, jsRequestBuilder,
            SPEC_REFRESH_INTERVAL_MS, new BeanFilter(), cajaContentRewriter, gadgetAdminStore,
            featureRegistryProvider, new ModuleIdManagerImpl());
    gadgetHandlerWithAdmin = new GadgetsHandlerService(timeSource, processor, urlGenerator,
            tokenCodec, proxyUriManager, jsUriManager, proxyHandler, jsPipeline, jsRequestBuilder,
            SPEC_REFRESH_INTERVAL_MS, new BeanFilter(), cajaContentRewriter, gadgetAdminStore,
            featureRegistryProvider, new ModuleIdManagerImpl());
  }

  // Next test verify that the API data classes are configured correctly.
  // The mapping is done using reflection in runtime, so this test verify mapping is complete
  // this test will prevent from not intended change to the API.
  // DO NOT REMOVE TEST
  @Test
  public void testHandlerDataDelegation() throws Exception {
    delegator.validate();
  }

  private void setupMockGadgetAdminStore(boolean isAllowed) {
    EasyMock.expect(gadgetAdminStore.checkFeatureAdminInfo(EasyMock.isA(Gadget.class)))
    .andReturn(isAllowed).anyTimes();
  }

  @SuppressWarnings("unchecked")
  private void setupMockRegistry(List<String> features) {
    EasyMock.expect(mockRegistry.getFeatures(EasyMock.isA(Collection.class)))
            .andReturn(Lists.newArrayList(features)).anyTimes();
    FeatureBundle featureBundle = createMockFeatureBundle();
    FeatureRegistry.LookupResult lr = createMockLookupResult(ImmutableList.of(featureBundle));
    EasyMock.expect(
            mockRegistry.getFeatureResources(isA(GadgetContext.class),
                    eq(Lists.newArrayList(features)), EasyMock.<List<String>> isNull()))
            .andReturn(lr).anyTimes();
    replay();
  }

  private FeatureBundle createMockFeatureBundle() {
    FeatureBundle result = createMock(FeatureBundle.class);
    expect(result.getApis(ApiDirective.Type.RPC, false)).andReturn(
            Lists.newArrayList(RPC_SERVICE_1, RPC_SERVICE_2)).anyTimes();
    replay(result);
    return result;
  }

  private FeatureRegistry.LookupResult createMockLookupResult(List<FeatureBundle> featureBundles) {
    FeatureRegistry.LookupResult result = createMock(FeatureRegistry.LookupResult.class);
    EasyMock.expect(result.getBundles()).andReturn(featureBundles).anyTimes();
    replay(result);
    return result;
  }

  @Test
  public void testGetMetadata() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(FakeProcessor.SPEC_URL,
            CONTAINER, "default", createAuthContext(null, null), ImmutableList.of("*"));
    setupMockGadgetAdminStore(true);
    setupMockRegistry(ImmutableList.<String> of("auth-refresh"));
    GadgetsHandlerApi.MetadataResponse response = gadgetHandler.getMetadata(request);
    assertEquals(FakeIframeUriManager.DEFAULT_IFRAME_URI.toString(), response.getIframeUrl());
    assertTrue(response.getNeedsTokenRefresh());
    assertEquals(1, response.getViews().size());
    assertEquals(FakeProcessor.SPEC_TITLE, response.getModulePrefs().getTitle());
    assertEquals(FakeProcessor.LINK_HREF,
            response.getModulePrefs().getLinks().get(FakeProcessor.LINK_REL).getHref().toString());
    assertEquals(FakeProcessor.LINK_REL,
            response.getModulePrefs().getLinks().get(FakeProcessor.LINK_REL).getRel());
    assertEquals(1, response.getUserPrefs().size());
    assertEquals("up_one", response.getUserPrefs().get("up_one").getDisplayName());
    assertEquals(4, response.getUserPrefs().get("up_one").getOrderedEnumValues().size());
    assertEquals(CURRENT_TIME_MS, response.getResponseTimeMs());
    assertEquals(METADATA_EXPIRY_TIME_MS, response.getExpireTimeMs());
    assertEquals(Sets.newHashSet(RPC_SERVICE_1, RPC_SERVICE_2), response.getRpcServiceIds());
    verify();
  }

  @Test
  public void testFeatureAdminAllowedGadget() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(FakeProcessor.SPEC_URL4,
            CONTAINER, "default", createAuthContext(null, null), ImmutableList.of("*"));
    setupMockGadgetAdminStore(true);
    setupMockRegistry(Lists.newArrayList("example-feature", "example-feature2"));

    GadgetsHandlerApi.MetadataResponse response = gadgetHandlerWithAdmin.getMetadata(request);
    assertEquals(FakeIframeUriManager.DEFAULT_IFRAME_URI.toString(), response.getIframeUrl());
    assertEquals(1, response.getViews().size());
    assertEquals(FakeProcessor.SPEC_TITLE, response.getModulePrefs().getTitle());
    assertEquals(FakeProcessor.LINK_HREF,
            response.getModulePrefs().getLinks().get(FakeProcessor.LINK_REL).getHref().toString());
    assertEquals(FakeProcessor.LINK_REL,
            response.getModulePrefs().getLinks().get(FakeProcessor.LINK_REL).getRel());
    assertEquals(1, response.getUserPrefs().size());
    assertEquals("up_one", response.getUserPrefs().get("up_one").getDisplayName());
    assertEquals(4, response.getUserPrefs().get("up_one").getOrderedEnumValues().size());
    assertEquals(CURRENT_TIME_MS, response.getResponseTimeMs());
    assertEquals(METADATA_EXPIRY_TIME_MS, response.getExpireTimeMs());
    assertEquals(Sets.newHashSet(RPC_SERVICE_1, RPC_SERVICE_2), response.getRpcServiceIds());
    verify();
  }

  @Test(expected = ProcessingException.class)
  public void testFeatureAdminDeniedGadget() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(FakeProcessor.SPEC_URL4,
            CONTAINER, "default", createAuthContext(null, null), ImmutableList.of("*"));
    setupMockGadgetAdminStore(false);
    setupMockRegistry(Lists.newArrayList("example-feature", "example-feature2"));
    gadgetHandlerWithAdmin.getMetadata(request);
  }

  @Test
  public void testGetMetadataOnlyView() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(FakeProcessor.SPEC_URL,
            CONTAINER, null, createAuthContext(null, null), ImmutableList.of("views.*"));
    setupMockRegistry(new ArrayList<String>());
    GadgetsHandlerApi.MetadataResponse response = gadgetHandler.getMetadata(request);
    assertNull(response.getIframeUrl());
    assertNull(response.getUserPrefs());
    assertNull(response.getModulePrefs());
    assertNull(response.getUrl());
    assertEquals(1, response.getViews().size());
    verify();
  }

  @Test(expected = ProcessingException.class)
  public void testGetMetadataNoView() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(FakeProcessor.SPEC_URL3,
            CONTAINER, "invalid_view", createAuthContext(null, null), ImmutableList.of("*"));
    replay();
    gadgetHandler.getMetadata(request);
  }

  @Test(expected = ProcessingException.class)
  public void testGetMetadataNoContainer() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(FakeProcessor.SPEC_URL, null,
            null, createAuthContext(null, null), ImmutableList.of("*"));
    replay();
    gadgetHandler.getMetadata(request);
  }

  @Test(expected = ProcessingException.class)
  public void testGetMetadataNoUrl() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(null, CONTAINER, null,
            createAuthContext(null, null), ImmutableList.of("*"));
    replay();
    gadgetHandler.getMetadata(request);
  }

  @Test(expected = ProcessingException.class)
  public void testGetMetadataNoFields() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(FakeProcessor.SPEC_URL,
            CONTAINER, null, createAuthContext(null, null), null);
    replay();
    gadgetHandler.getMetadata(request);
  }

  @Test(expected = ProcessingException.class)
  public void testGetMetadataBadGadget() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(Uri.parse("unknown"),
            CONTAINER, null, createAuthContext(null, null), null);
    replay();
    gadgetHandler.getMetadata(request);
  }

  @Test
  public void testGetMetadataNoToken() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(FakeProcessor.SPEC_URL,
            CONTAINER, "default", null, ImmutableList.of("*"));
    setupMockGadgetAdminStore(true);
    setupMockRegistry(Lists.newArrayList("auth-refresh"));
    GadgetsHandlerApi.MetadataResponse response = gadgetHandler.getMetadata(request);
    assertEquals(FakeIframeUriManager.DEFAULT_IFRAME_URI.toString(), response.getIframeUrl());
    verify();
  }

  @Test
  public void testGetMetadataWithParams() throws Exception {
    GadgetsHandlerApi.MetadataRequest request = createMetadataRequest(FakeProcessor.SPEC_URL4,
            CONTAINER, "default", createAuthContext(null, null), ImmutableList.of("*"));
    setupMockGadgetAdminStore(true);
    setupMockRegistry(Lists.newArrayList("auth-refresh"));
    GadgetsHandlerApi.MetadataResponse response = gadgetHandler.getMetadata(request);

    Map<String, Feature> features = response.getModulePrefs().getFeatures();
    // make sure that the feature set contains all the features, and no extra features
    // Note that the core feature is automatically included.
    assertTrue(features.containsKey(FakeProcessor.FEATURE1)
            && features.containsKey(FakeProcessor.FEATURE2)
            && features.containsKey(FakeProcessor.FEATURE3) && features.size() == 3);
    Multimap<String, String> params1 = features.get(FakeProcessor.FEATURE2).getParams();
    assertEquals(ImmutableList.of(FakeProcessor.PARAM_VALUE, FakeProcessor.PARAM_VALUE2),
            params1.get(FakeProcessor.PARAM_NAME));
    Multimap<String, String> params2 = features.get(FakeProcessor.FEATURE3).getParams();
    assertEquals(ImmutableList.of(FakeProcessor.PARAM_VALUE3),
            params2.get(FakeProcessor.PARAM_NAME2));

    verify();
  }

  @Test
  public void testGetToken() throws Exception {
    GadgetsHandlerApi.TokenRequest request = createTokenRequest(FakeProcessor.SPEC_URL, CONTAINER,
            createAuthContext(OWNER, VIEWER), ImmutableList.of("*"));
    replay();
    tokenCodec.encodedToken = TOKEN;
    GadgetsHandlerApi.TokenResponse response = gadgetHandler.getToken(request);
    assertEquals(TOKEN, response.getToken());
    assertEquals(CURRENT_TIME_MS, response.getResponseTimeMs());
    assertEquals(TOKEN_EXPIRY_TIME_MS, response.getExpireTimeMs());
    assertEquals(OWNER, tokenCodec.authContext.getOwnerId());
    assertEquals(VIEWER, tokenCodec.authContext.getViewerId());
    assertEquals(CONTAINER, tokenCodec.authContext.getContainer());
    verify();
  }

  @Test(expected = ProcessingException.class)
  public void testGetTokenNoContainer() throws Exception {
    GadgetsHandlerApi.TokenRequest request = createTokenRequest(FakeProcessor.SPEC_URL, null,
            createAuthContext(OWNER, VIEWER), ImmutableList.of("*"));
    replay();
    gadgetHandler.getToken(request);
  }

  @Test(expected = ProcessingException.class)
  public void testGetTokenNoUrl() throws Exception {
    GadgetsHandlerApi.TokenRequest request = createTokenRequest(null, CONTAINER,
            createAuthContext(OWNER, VIEWER), ImmutableList.of("*"));
    replay();
    gadgetHandler.getToken(request);
  }

  @Test(expected = ProcessingException.class)
  public void testGetTokenNoFields() throws Exception {
    GadgetsHandlerApi.TokenRequest request = createTokenRequest(FakeProcessor.SPEC_URL, CONTAINER,
            createAuthContext(OWNER, VIEWER), null);
    replay();
    gadgetHandler.getToken(request);
  }

  @Test(expected = SecurityTokenException.class)
  public void testGetTokenException() throws Exception {
    GadgetsHandlerApi.TokenRequest request = createTokenRequest(FakeProcessor.SPEC_URL, CONTAINER,
            createAuthContext(OWNER, VIEWER), ImmutableList.of("*"));
    replay();
    tokenCodec.exc = new SecurityTokenException("bad data");
    gadgetHandler.getToken(request);
  }

  @Test
  public void testGetTokenNoToken() throws Exception {
    GadgetsHandlerApi.TokenRequest request = createTokenRequest(FakeProcessor.SPEC_URL, CONTAINER,
            null, ImmutableList.of("*"));
    replay();
    tokenCodec.encodedToken = TOKEN;
    GadgetsHandlerApi.TokenResponse response = gadgetHandler.getToken(request);
    assertEquals(TOKEN, response.getToken());
    assertNull(CONTAINER, tokenCodec.authContext);
    verify();
  }

  @Test
  public void testCreateJsResponse() throws Exception {
    Uri jsUri = Uri.parse("http://www.shindig.com/js");
    String content = "content";
    GadgetsHandlerApi.JsResponse jsResponse = gadgetHandler.createJsResponse(null, jsUri, content,
            ImmutableSet.of("*"), null);
    BeanDelegator.validateDelegator(jsResponse);
  }

  @Test
  public void testGetJsUri() throws Exception {
    List<String> fields = ImmutableList.of("jsurl");
    List<String> features = ImmutableList.of("rpc");
    Uri resUri = Uri.parse("server.com/gadgets/js/rpc");
    GadgetsHandlerApi.JsRequest request = createJsRequest(null, CONTAINER, fields, features, null);
    Capture<JsUri> uriCapture = new Capture<JsUri>();
    expect(jsUriManager.makeExternJsUri(capture(uriCapture))).andReturn(resUri);
    replay();

    GadgetsHandlerApi.JsResponse response = gadgetHandler.getJs(request);
    JsUri expectedUri = new JsUri(null, false, false, CONTAINER, null, features, null, null, false,
            false, RenderingContext.GADGET, null, null);
    assertEquals(expectedUri, uriCapture.getValue());
    assertEquals(resUri, response.getJsUrl());
    assertNull(response.getJsContent());
    assertEquals(timeSource.currentTimeMillis() + HttpUtil.getDefaultTtl() * 1000, response
            .getExpireTimeMs().longValue());
    verify();
  }

  @Test(expected = ProcessingException.class)
  public void testJsNoContainer() throws Exception {
    List<String> fields = ImmutableList.of("*");
    GadgetsHandlerApi.JsRequest request = createJsRequest(null, null, fields,
            ImmutableList.of("rpc"), null);
    gadgetHandler.getJs(request);
  }

  @Test
  public void testGetJsData() throws Exception {
    List<String> fields = ImmutableList.of("jscontent");
    List<String> features = ImmutableList.of("rpc");
    Uri resUri = Uri.parse("http://server.com/gadgets/js/rpc");
    Capture<JsUri> uriCapture = new Capture<JsUri>();
    String jsContent = "var a;";
    String onload = "do this";
    String repository = "v01";
    expect(jsUriManager.makeExternJsUri(capture(uriCapture))).andReturn(resUri);
    expect(jsPipeline.execute(EasyMock.isA(JsRequest.class))).andReturn(
            new JsResponseBuilder().appendJs(jsContent, "js").setProxyCacheable(true).build());
    GadgetsHandlerApi.JsRequest request = createJsRequest(FakeProcessor.SPEC_URL.toString(),
            CONTAINER, fields, features, repository);
    expect(request.getOnload()).andStubReturn(onload);
    expect(request.getContext()).andStubReturn(GadgetsHandlerApi.RenderingContext.CONTAINER);
    replay();

    GadgetsHandlerApi.JsResponse response = gadgetHandler.getJs(request);
    JsUri expectedUri = new JsUri(null, false, false, CONTAINER, FakeProcessor.SPEC_URL.toString(),
            features, null, onload, false, false, RenderingContext.CONTAINER, null, repository);
    assertEquals(expectedUri, uriCapture.getValue());
    assertNull(response.getJsUrl());
    assertEquals(jsContent, response.getJsContent());
    assertEquals(timeSource.currentTimeMillis() + HttpUtil.getDefaultTtl() * 1000, response
            .getExpireTimeMs().longValue());
    verify();
  }

  @Test(expected = ProcessingException.class)
  public void testGetJsDataWithException() throws Exception {
    List<String> fields = ImmutableList.of("jscontent");
    List<String> features = ImmutableList.of("unknown");
    Uri resUri = Uri.parse("http://server.com/gadgets/js/foo");
    Capture<JsUri> uriCapture = new Capture<JsUri>();
    expect(jsUriManager.makeExternJsUri(capture(uriCapture))).andReturn(resUri);
    expect(jsPipeline.execute(EasyMock.isA(JsRequest.class))).andThrow(
            new JsException(404, "error"));
    GadgetsHandlerApi.JsRequest request = createJsRequest(FakeProcessor.SPEC_URL.toString(),
            CONTAINER, fields, features, null);
    expect(request.getOnload()).andStubReturn("do this");
    expect(request.getContext()).andStubReturn(GadgetsHandlerApi.RenderingContext.CONTAINER);
    replay();

    gadgetHandler.getJs(request);
  }

  @Test
  public void testCreateProxyUri() throws Exception {
    GadgetsHandlerApi.ImageParams image = mock(GadgetsHandlerApi.ImageParams.class);
    expect(image.getDoNotExpand()).andStubReturn(true);
    expect(image.getHeight()).andStubReturn(120);
    expect(image.getWidth()).andStubReturn(210);
    expect(image.getQuality()).andStubReturn(77);

    GadgetsHandlerApi.ProxyRequest request = mock(GadgetsHandlerApi.ProxyRequest.class);
    expect(request.getContainer()).andStubReturn(CONTAINER);
    expect(request.getUrl()).andStubReturn(RESOURCE);
    expect(request.getRefresh()).andStubReturn(new Integer(333));
    expect(request.getDebug()).andStubReturn(true);
    expect(request.getFallbackUrl()).andStubReturn(FALLBACK);
    expect(request.getGadget()).andStubReturn(FakeProcessor.SPEC_URL.toString());
    expect(request.getIgnoreCache()).andStubReturn(true);
    expect(request.getImageParams()).andStubReturn(image);
    expect(request.getRewriteMimeType()).andStubReturn("image/png");
    expect(request.getSanitize()).andStubReturn(true);
    replay();
    ProxyUri pUri = gadgetHandler.createProxyUri(request);

    ProxyUri expectedUri = new ProxyUri(333, true, true, CONTAINER,
            FakeProcessor.SPEC_URL.toString(), RESOURCE);
    expectedUri.setRewriteMimeType("image/png").setSanitizeContent(true);
    expectedUri.setResize(210, 120, 77, true).setFallbackUrl(FALLBACK);
    assertEquals(pUri, expectedUri);
    verify();
  }

  @Test
  public void testValidateProxyResponse() throws Exception {
    GadgetsHandlerApi.ProxyResponse response = gadgetHandler.createProxyResponse(RESOURCE, null,
            ImmutableSet.<String> of("*"), 1000001L);

    BeanDelegator.validateDelegator(response);
    assertEquals(RESOURCE, response.getProxyUrl());
    assertNull(response.getProxyContent());
  }

  @Test
  public void testCreateProxyResponse() throws Exception {
    HttpResponseBuilder httpResponse = new HttpResponseBuilder();
    httpResponse.setContent("Content");
    httpResponse.addHeader("header", "hval");
    httpResponse.setEncoding(Charset.forName("UTF8"));
    httpResponse.setHttpStatusCode(404);

    GadgetsHandlerApi.ProxyResponse response = gadgetHandler.createProxyResponse(RESOURCE,
            httpResponse.create(), ImmutableSet.<String> of("*"), 1000001L);
    BeanDelegator.validateDelegator(response);
    assertEquals("Content",
            new String(Base64.decodeBase64(response.getProxyContent().getContentBase64())));
    assertEquals(404, response.getProxyContent().getCode());
    assertEquals(2, response.getProxyContent().getHeaders().size());
    assertEquals("Date", response.getProxyContent().getHeaders().get(0).getName());
    assertEquals("header", response.getProxyContent().getHeaders().get(1).getName());
    assertEquals("hval", response.getProxyContent().getHeaders().get(1).getValue());
    assertEquals(1000001L, response.getExpireTimeMs().longValue());
  }

  @Test
  public void testFilterProxyResponse() throws Exception {
    HttpResponse httpResponse = new HttpResponse("data");
    GadgetsHandlerApi.ProxyResponse response = gadgetHandler.createProxyResponse(RESOURCE,
            httpResponse, ImmutableSet.<String> of("proxyurl"), 1000001L);
    assertNull(response.getProxyContent());
    assertEquals(RESOURCE, response.getProxyUrl());
  }

  @Test
  public void testGetProxySimple() throws Exception {
    List<String> fields = ImmutableList.of("proxyurl");
    Uri resUri = Uri.parse("server.com/gadgets/proxy?url=" + RESOURCE);
    GadgetsHandlerApi.ProxyRequest request = createProxyRequest(RESOURCE, CONTAINER, fields);
    Capture<List<ProxyUri>> uriCapture = new Capture<List<ProxyUri>>();
    expect(proxyUriManager.make(capture(uriCapture), EasyMock.anyInt())).andReturn(
            ImmutableList.of(resUri));
    replay();
    GadgetsHandlerApi.ProxyResponse response = gadgetHandler.getProxy(request);
    assertEquals(1, uriCapture.getValue().size());
    ProxyUri pUri = uriCapture.getValue().get(0);
    assertEquals(CONTAINER, pUri.getContainer());
    assertEquals(resUri, response.getProxyUrl());
    assertNull(response.getProxyContent());
    assertEquals(timeSource.currentTimeMillis() + HttpUtil.getDefaultTtl() * 1000, response
            .getExpireTimeMs().longValue());
    verify();
  }

  @Test(expected = ProcessingException.class)
  public void testGetProxyNoContainer() throws Exception {
    List<String> fields = ImmutableList.of("*");
    GadgetsHandlerApi.ProxyRequest request = createProxyRequest(RESOURCE, null, fields);
    gadgetHandler.getProxy(request);
  }

  @Test(expected = ProcessingException.class)
  public void testGetProxyNoResource() throws Exception {
    List<String> fields = ImmutableList.of("*");
    GadgetsHandlerApi.ProxyRequest request = createProxyRequest(null, CONTAINER, fields);
    gadgetHandler.getProxy(request);
  }

  @Test(expected = ProcessingException.class)
  public void testGetProxyNoFields() throws Exception {
    GadgetsHandlerApi.ProxyRequest request = createProxyRequest(RESOURCE, CONTAINER, null);
    gadgetHandler.getProxy(request);
  }

  @Test
  public void testGetProxyData() throws Exception {
    List<String> fields = ImmutableList.of("proxycontent.*");
    Uri resUri = Uri.parse("server.com/gadgets/proxy?url=" + RESOURCE);
    GadgetsHandlerApi.ProxyRequest request = createProxyRequest(RESOURCE, CONTAINER, fields);
    Capture<List<ProxyUri>> uriCapture = new Capture<List<ProxyUri>>();
    expect(proxyUriManager.make(capture(uriCapture), EasyMock.anyInt())).andReturn(
            ImmutableList.of(resUri));
    HttpResponseBuilder builder = new HttpResponseBuilder();
    builder.setExpirationTime(20000).setContent("response");
    HttpResponse httpResponse = builder.create();
    expect(proxyHandler.fetch(EasyMock.isA(ProxyUri.class))).andReturn(httpResponse);
    replay();
    GadgetsHandlerApi.ProxyResponse response = gadgetHandler.getProxy(request);
    assertEquals(1, uriCapture.getValue().size());
    ProxyUri pUri = uriCapture.getValue().get(0);
    assertEquals(CONTAINER, pUri.getContainer());
    assertNull(response.getProxyUrl());
    assertEquals("response",
            new String(Base64.decodeBase64(response.getProxyContent().getContentBase64())));
    assertEquals(20000L, response.getExpireTimeMs().longValue());
    verify();
  }

  @Test
  public void testGetProxyEmptyData() throws Exception {
    List<String> fields = ImmutableList.of("proxycontent.*");
    Uri resUri = Uri.parse("server.com/gadgets/proxy?url=" + RESOURCE);
    GadgetsHandlerApi.ProxyRequest request = createProxyRequest(RESOURCE, CONTAINER, fields);
    Capture<List<ProxyUri>> uriCapture = new Capture<List<ProxyUri>>();
    expect(proxyUriManager.make(capture(uriCapture), EasyMock.anyInt())).andReturn(
            ImmutableList.of(resUri));
    HttpResponse httpResponse = new HttpResponseBuilder().setHttpStatusCode(504).create();
    expect(proxyHandler.fetch(EasyMock.isA(ProxyUri.class))).andReturn(httpResponse);
    replay();
    GadgetsHandlerApi.ProxyResponse response = gadgetHandler.getProxy(request);
    assertEquals(1, uriCapture.getValue().size());
    ProxyUri pUri = uriCapture.getValue().get(0);
    assertEquals(CONTAINER, pUri.getContainer());
    assertNull(response.getProxyUrl());
    assertEquals("", response.getProxyContent().getContentBase64());
    assertEquals(504, response.getProxyContent().getCode());
    verify();
  }

  @Test(expected = ProcessingException.class)
  public void testGetProxyDataFail() throws Exception {
    List<String> fields = ImmutableList.of("proxycontent.*");
    Uri resUri = Uri.parse("server.com/gadgets/proxy?url=" + RESOURCE);
    GadgetsHandlerApi.ProxyRequest request = createProxyRequest(RESOURCE, CONTAINER, fields);
    Capture<List<ProxyUri>> uriCapture = new Capture<List<ProxyUri>>();
    expect(proxyUriManager.make(capture(uriCapture), EasyMock.anyInt())).andReturn(
            ImmutableList.of(resUri));
    new HttpResponse("response");
    expect(proxyHandler.fetch(EasyMock.isA(ProxyUri.class))).andThrow(
            new GadgetException(Code.FAILED_TO_RETRIEVE_CONTENT));
    replay();
    gadgetHandler.getProxy(request);
  }

  @Test
  public void testCreateCajaResponse() throws Exception {
    String goldenEntries[][] = { { "name1", "LINT", "msg1" }, { "name2", "LINT", "msg2" } };
    List<GadgetsHandlerApi.Message> goldenMessages = Lists.newArrayList();

    for (String[] goldenEntry : goldenEntries) {
      GadgetsHandlerApi.Message m = mock(GadgetsHandlerApi.Message.class);
      expect(m.getName()).andReturn(goldenEntry[0]);
      expect(m.getLevel()).andReturn(GadgetsHandlerApi.MessageLevel.valueOf(goldenEntry[1]));
      expect(m.getMessage()).andReturn(goldenEntry[2]);
      goldenMessages.add(m);
    }
    replay();

    Uri jsUri = Uri.parse("http://www.shindig.com/js");
    GadgetsHandlerApi.CajaResponse jsResponse = gadgetHandler.createCajaResponse(jsUri, "html",
            "js", goldenMessages, ImmutableSet.of("*"), null);
    BeanDelegator.validateDelegator(jsResponse);

    assertEquals("html", jsResponse.getHtml());
    assertEquals("js", jsResponse.getJs());
    List<GadgetsHandlerApi.Message> response = jsResponse.getMessages();
    assertEquals(goldenMessages.size(), response.size());
    for (int i = 0; i < response.size(); i++) {
      assertEquals(goldenEntries[i][0], response.get(i).getName());
      assertEquals(goldenEntries[i][1], response.get(i).getLevel().name());
      assertEquals(goldenEntries[i][2], response.get(i).getMessage());
    }
  }

  private GadgetsHandlerApi.AuthContext createAuthContext(String ownerId, String viewerId) {
    GadgetsHandlerApi.AuthContext authContext = mock(GadgetsHandlerApi.AuthContext.class);
    if (ownerId != null) {
      EasyMock.expect(authContext.getOwnerId()).andReturn(ownerId).once();
    }
    if (viewerId != null) {
      EasyMock.expect(authContext.getViewerId()).andReturn(viewerId).once();
    }
    EasyMock.expect(authContext.getExpiresAt()).andReturn(TOKEN_EXPIRY_TIME_MS).anyTimes();
    return authContext;
  }

  private GadgetsHandlerApi.MetadataRequest createMetadataRequest(Uri url, String container,
          String view, GadgetsHandlerApi.AuthContext authContext, List<String> fields) {
    GadgetsHandlerApi.MetadataRequest request = mock(GadgetsHandlerApi.MetadataRequest.class);
    EasyMock.expect(request.getFields()).andReturn(fields).anyTimes();
    EasyMock.expect(request.getView()).andReturn(view).once();
    EasyMock.expect(request.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(request.getContainer()).andReturn(container).anyTimes();
    EasyMock.expect(request.getAuthContext()).andReturn(authContext).once();

    return request;
  }

  private GadgetsHandlerApi.TokenRequest createTokenRequest(Uri url, String container,
          GadgetsHandlerApi.AuthContext authContext, List<String> fields) {
    GadgetsHandlerApi.TokenRequest request = mock(GadgetsHandlerApi.TokenRequest.class);
    EasyMock.expect(request.getFields()).andReturn(fields).anyTimes();
    EasyMock.expect(request.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(request.getContainer()).andReturn(container).anyTimes();
    EasyMock.expect(request.getAuthContext()).andReturn(authContext).once();
    return request;
  }

  private GadgetsHandlerApi.JsRequest createJsRequest(String gadget, String container,
          List<String> fields, List<String> features, String repository) {
    GadgetsHandlerApi.JsRequest request = mock(GadgetsHandlerApi.JsRequest.class);
    EasyMock.expect(request.getFields()).andStubReturn(fields);
    EasyMock.expect(request.getContainer()).andStubReturn(container);
    EasyMock.expect(request.getGadget()).andStubReturn(gadget);
    EasyMock.expect(request.getFeatures()).andStubReturn(features);
    EasyMock.expect(request.getRepository()).andStubReturn(repository);
    return request;
  }

  private GadgetsHandlerApi.ProxyRequest createProxyRequest(Uri url, String container,
          List<String> fields) {
    GadgetsHandlerApi.ProxyRequest request = mock(GadgetsHandlerApi.ProxyRequest.class);
    EasyMock.expect(request.getFields()).andStubReturn(fields);
    EasyMock.expect(request.getContainer()).andStubReturn(container);
    EasyMock.expect(request.getUrl()).andStubReturn(url);
    return request;
  }

  private class FakeSecurityTokenCodec implements SecurityTokenCodec {
    public SecurityToken authContext = null;
    public SecurityTokenException exc = null;
    public String encodedToken = null;

    public String encodeToken(SecurityToken authContext) throws SecurityTokenException {
      this.authContext = authContext;
      if (exc != null) {
        throw exc;
      }
      return encodedToken;
    }

    public SecurityToken createToken(Map<String, String> tokenParameters)
            throws SecurityTokenException {
      if (exc != null) {
        throw exc;
      }
      return authContext;
    }

    public int getTokenTimeToLive() {
      return 0;  // Not used.
    }
  }
}


text:
package com.getbase.android.db.provider;

import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;

import java.util.ArrayList;

public class ContentProviderCrudHandler implements CrudHandler {

  private final ContentProvider contentProvider;

  public ContentProviderCrudHandler(ContentProvider contentProvider) {
    this.contentProvider = contentProvider;
  }

  @Override
  public Cursor query(Uri url, String[] projection, String selection, String[] selectionArgs, String sortOrder) throws RemoteException {
    return contentProvider.query(url, projection, selection, selectionArgs, sortOrder);
  }

  @Override
  public int delete(Uri url, String selection, String[] selectionArgs) throws RemoteException {
    return contentProvider.delete(url, selection, selectionArgs);
  }

  @Override
  public int update(Uri url, ContentValues values, String selection, String[] selectionArgs) throws RemoteException {
    return contentProvider.update(url, values, selection, selectionArgs);
  }

  @Override
  public Uri insert(Uri url, ContentValues initialValues) throws RemoteException {
    return contentProvider.insert(url, initialValues);
  }

  @Override
  public ContentProviderResult[] applyBatch(String authority, ArrayList<ContentProviderOperation> operations) throws RemoteException, OperationApplicationException {
    return contentProvider.applyBatch(operations);
  }
}


text:
// .NAME vtkSphericalDirectionEncoder - A direction encoder based on spherical coordinates
// .SECTION Description
// vtkSphericalDirectionEncoder is a direction encoder which uses spherical
// coordinates for mapping (nx, ny, nz) into an azimuth, elevation pair.
//
// .SECTION see also
// vtkDirectionEncoder

#ifndef __vtkSphericalDirectionEncoder_h
#define __vtkSphericalDirectionEncoder_h

#include "vtkRenderingVolumeModule.h" // For export macro
#include "vtkDirectionEncoder.h"

class VTKRENDERINGVOLUME_EXPORT vtkSphericalDirectionEncoder : public vtkDirectionEncoder
{
public:
  vtkTypeMacro(vtkSphericalDirectionEncoder,vtkDirectionEncoder);
  void PrintSelf( ostream& os, vtkIndent indent );

  // Description:
  // Construct the object. Initialize the index table which will be
  // used to map the normal into a patch on the recursively subdivided
  // sphere.
  static vtkSphericalDirectionEncoder *New();

  // Description:
  // Given a normal vector n, return the encoded direction
  int GetEncodedDirection( float n[3] );

  // Description:
  /// Given an encoded value, return a pointer to the normal vector
  float *GetDecodedGradient( int value );

  // Description:
  // Return the number of encoded directions
  int GetNumberOfEncodedDirections( void ) { return 65536; }

  // Description:
  // Get the decoded gradient table. There are
  // this->GetNumberOfEncodedDirections() entries in the table, each
  // containing a normal (direction) vector. This is a flat structure -
  // 3 times the number of directions floats in an array.
  float *GetDecodedGradientTable( void )
    {
      return &(this->DecodedGradientTable[0]);
    }

protected:
  vtkSphericalDirectionEncoder();
  ~vtkSphericalDirectionEncoder();

  static float DecodedGradientTable[65536*3];

  // Description:
  // Initialize the table at startup
  static void InitializeDecodedGradientTable();
  static int DecodedGradientTableInitialized;

private:
  vtkSphericalDirectionEncoder(const vtkSphericalDirectionEncoder&);  // Not implemented.
  void operator=(const vtkSphericalDirectionEncoder&);  // Not implemented.
};

#endif


text:
layout: page
title: Dorsey - Young Wedding
date: 2016-05-24
author: Sharon Friedman
tags: weekly links, java
status: published
summary: Vivamus vel orci ac augue tincidunt hendrerit. Etiam.
banner: images/banner/people.jpg
booking:
  startDate: 07/31/2016
  endDate: 08/05/2016
  ctyhocn: MIAFLHX
  groupCode: DYW
published: true
---
Pellentesque tempor erat orci. Aliquam erat volutpat. Nulla facilisi. Mauris quis varius dolor, quis faucibus lacus. Donec tristique laoreet nisi, sit amet ullamcorper est maximus accumsan. Nulla malesuada accumsan dolor, ut feugiat quam lacinia id. Vivamus a iaculis sem. Integer imperdiet eget magna vitae viverra. Duis interdum diam feugiat lectus pharetra venenatis. Nulla nec felis egestas, congue urna sed, euismod neque. Vivamus hendrerit massa dolor, vel lacinia augue dapibus non. Etiam placerat sollicitudin sem, nec fringilla nulla sagittis at. Nam vestibulum, ante quis hendrerit molestie, ex magna convallis ante, eu pretium eros lorem in magna.

1 Cras tristique ante quis elementum vehicula
1 Proin ut felis tincidunt, vehicula erat in, porttitor mi
1 Donec ultrices nibh sit amet risus porttitor, a dictum enim tempus.

Nunc maximus turpis risus, at dignissim turpis sodales quis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In fringilla nulla nisi, nec posuere magna consectetur sit amet. Ut varius eros non libero mattis, in fermentum tellus blandit. Morbi pharetra in libero ut molestie. Sed consequat sollicitudin aliquam. Sed pretium efficitur odio, at rutrum lectus imperdiet eu.


text:
package org.wso2.carbon.appmgt.oauth.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.opensaml.xml.util.Base64;
import org.wso2.carbon.appmgt.api.AppManagementException;
import org.wso2.carbon.appmgt.oauth.endpoint.dto.Token;
import org.wso2.carbon.appmgt.impl.AppMConstants;
import org.wso2.carbon.appmgt.impl.dao.AppMDAO;
import org.wso2.carbon.appmgt.impl.dto.SAMLTokenInfoDTO;
import org.wso2.carbon.core.AbstractAdmin;
import org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes;
import org.wso2.carbon.identity.oauth2.dto.*;
import org.apache.axiom.util.base64.Base64Utils;

import javax.cache.Caching;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * OAuth2 Service which is used to issue access tokens upon authorizing by the
 * user and issue/validateGrant access tokens.
 */
@SuppressWarnings("unused")
public class AppManagerOAuth2Service extends AbstractAdmin {

    private static Log log = LogFactory.getLog(AppManagerOAuth2Service.class);

    /**
     * Issue access token in exchange to an Authorization Grant.
     *
     * @param tokenReqDTO OAuth2AccessTokenReqDTO representing the Access Token request
     * @return OAuth2AccessTokenRespDTO representing the Access Token response
     */
    public Token issueAccessToken(OAuth2AccessTokenReqDTO tokenReqDTO) {
        if (log.isDebugEnabled()) {
            log.debug("Access Token Request Received with the Client Id : " + tokenReqDTO.getClientId() +
                              ", Grant Type : " + tokenReqDTO.getGrantType());
        }

        Token accessToken = null;
        try {
            String webAppConsumerKey = tokenReqDTO.getClientId();
            String webAppConsumerSecret = tokenReqDTO.getClientSecret();
            String saml2SsoIssuer = null;

            if (!AppMDAO.webAppKeyPairExist(webAppConsumerKey, webAppConsumerSecret)) {
                throw new Exception("Invalid Credentials");
            }

            saml2SsoIssuer = AppMDAO.getSAML2SSOIssuerByAppConsumerKey(webAppConsumerKey);

            //scope received as samlssoTokenId,apiAlias
            String[] scopes = tokenReqDTO.getScope();
            String samlssoTokenId = null;
            String apiAlias = null;
            if (scopes != null && scopes.length > 0) {
                String scope = scopes[0];
                if (scope != null) {
                    String[] tmp = scope.split(",");
                    samlssoTokenId = tmp[0].trim();
                    apiAlias = tmp[1].trim();
                }
            }

            Map<String, String> registeredAPIs = getRegisteredAPIs(webAppConsumerKey);
            if (isAuthorizedAPI(registeredAPIs, apiAlias)) {
                Map<String, SAMLTokenInfoDTO> encodedSAMLResponseMap = (HashMap<String, SAMLTokenInfoDTO>) Caching.getCacheManager(AppMConstants.SAML2_CONFIG_CACHE_MANAGER)
                        .getCache(AppMConstants.SAML2_CONFIG_CACHE).get(samlssoTokenId);
                String samlResponseOfApp = encodedSAMLResponseMap.get(saml2SsoIssuer).getEncodedSamlToken();
                String decodedSAMLResponse = getSamlAssetionString(new String(Base64.decode(samlResponseOfApp)));
                String encodedSamlAssertion = URLEncoder.encode(Base64.encodeBytes(getSamlAssetionString(decodedSAMLResponse).getBytes()), "UTF-8");

                //consumerKey,consumerSecret,tokenEndpoint
                String tokenEpKeyPair = registeredAPIs.get(apiAlias);
                String[] value = tokenEpKeyPair.split(",");
                String consumerKey = value[0].trim();
                String consumerSecret = value[1].trim();
                String tokenEndPoint = value[2].trim();

                accessToken = getAccessToken(consumerKey, consumerSecret, encodedSamlAssertion, tokenEndPoint);

            } else {
                throw new Exception("API :" + apiAlias + " not registered in webApp");
            }

            return accessToken;
        } catch (Exception e) {
            log.error("Error when issuing the access token. ", e);
            OAuth2AccessTokenRespDTO tokenRespDTO = new OAuth2AccessTokenRespDTO();
            tokenRespDTO.setError(true);
            tokenRespDTO.setErrorCode(OAuth2ErrorCodes.SERVER_ERROR);
            tokenRespDTO.setErrorMsg("Error when issuing the access token");
            return accessToken;
        }
    }

    public Token getAccessToken(String consumerKey, String consumerSecret, String encodedSamlAssertion, String tokenEndPoint) {
        try {
            String applicationToken = consumerKey + ":" + consumerSecret;
            applicationToken = "Basic " + Base64Utils.encode(applicationToken.getBytes()).trim();

            String payload = "grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=" + encodedSamlAssertion;
            // String payload = "grant_type=password&username=" + "admin" + "&password=admin";

            String response = doPost(tokenEndPoint, applicationToken, payload, "application/x-www-form-urlencoded");

            JSONParser parser = new JSONParser();
            Object obj = null;
            try {
                obj = parser.parse(response);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            JSONObject jsonObject = (JSONObject) obj;

            Token token = new Token();
            token.setAccessToken((String) jsonObject.get("access_token"));
            long expiresIn = ((Long) jsonObject.get("expires_in")).intValue();
            token.setExpiresIn(expiresIn);
            token.setRefreshToken((String) jsonObject.get("refresh_token"));
            token.setTokenType((String) jsonObject.get("token_type"));

            return token;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private boolean isAuthorizedAPI(Map<String, String> registeredAPIs, String apiName) throws
                                                                                AppManagementException {
        if (registeredAPIs.containsKey(apiName)) {
            return true;
        }
        return false;
    }

    private Map<String, String> getRegisteredAPIs(String webAppConsumerKey) throws
                                                                            AppManagementException {
        return AppMDAO.getRegisteredAPIs(webAppConsumerKey);
    }

    private boolean isAuthorizedKeyPair() {
        return false;
    }

    public String getResponsePayload(HttpResponse response) throws IOException {
        StringBuffer buffer = new StringBuffer();
        InputStream in = null;
        try {
            if (response.getEntity() != null) {
                in = response.getEntity().getContent();
                int length;
                byte[] tmp = new byte[2048];
                while ((length = in.read(tmp)) != -1) {
                    buffer.append(new String(tmp, 0, length));
                }
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
        }

        return buffer.toString();
    }

    public String doPost(String url, String token, String payload, String contentType)
            throws IOException {
        URL url1;
        HttpURLConnection connection = null;
        String response = null;
        try {
            //Create connection
            url1 = new URL(url);
            connection = (HttpURLConnection) url1.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            connection.setRequestProperty("Authorization", token);
            connection.setRequestProperty("Content-Length", "" +
                    Integer.toString(payload.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(payload);
            wr.flush();
            wr.close();

            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer endpointResponse = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                endpointResponse.append(line);
                endpointResponse.append('\r');
            }

            rd.close();
            response = endpointResponse.toString();
        } catch (Exception e) {
            e.printStackTrace();
            //return null;

        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return response;
    }

    private void addSecurityHeaders(HttpRequest request, String token) {
        if (token != null) {
            request.setHeader(HttpHeaders.AUTHORIZATION, token);
        }
    }

    public String getCookieValue(String cookieString, String cookieName) {
        if (cookieString.length() > 0) {
            int cStart = cookieString.indexOf(cookieName + "=");
            int cEnd;
            if (cStart != -1) {
                cStart = cStart + cookieName.length() + 1;
                cEnd = cookieString.indexOf(";", cStart);
                if (cEnd == -1) {
                    cEnd = cookieString.length();
                }
                return cookieString.substring(cStart, cEnd);
            }
        }
        return "";
    }

    public String getSamlAssetionString(String samlResponse) {
        return samlResponse.substring(samlResponse.indexOf("<saml2:Assertion"),
                                      samlResponse.indexOf("</saml2:Assertion>")) + "</saml2:Assertion>";

    }

}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.bpmn.model;

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

/**
 * @author Tijs Rademakers
 */
public class SendEventServiceTask extends ServiceTask {

    protected String eventType;
    protected String triggerEventType;
    protected boolean sendSynchronously;
    protected List<IOParameter> eventInParameters = new ArrayList<>();
    protected List<IOParameter> eventOutParameters = new ArrayList<>();

    public String getEventType() {
        return eventType;
    }

    public void setEventType(String eventType) {
        this.eventType = eventType;
    }

    public String getTriggerEventType() {
        return triggerEventType;
    }

    public void setTriggerEventType(String triggerEventType) {
        this.triggerEventType = triggerEventType;
    }

    public boolean isSendSynchronously() {
        return sendSynchronously;
    }

    public void setSendSynchronously(boolean sendSynchronously) {
        this.sendSynchronously = sendSynchronously;
    }

    public List<IOParameter> getEventInParameters() {
        return eventInParameters;
    }

    public void setEventInParameters(List<IOParameter> eventInParameters) {
        this.eventInParameters = eventInParameters;
    }

    public List<IOParameter> getEventOutParameters() {
        return eventOutParameters;
    }

    public void setEventOutParameters(List<IOParameter> eventOutParameters) {
        this.eventOutParameters = eventOutParameters;
    }

    @Override
    public SendEventServiceTask clone() {
        SendEventServiceTask clone = new SendEventServiceTask();
        clone.setValues(this);
        return clone;
    }

    public void setValues(SendEventServiceTask otherElement) {
        super.setValues(otherElement);
        setEventType(otherElement.getEventType());
        setTriggerEventType(otherElement.getTriggerEventType());
        setSendSynchronously(otherElement.isSendSynchronously());

        eventInParameters = new ArrayList<>();
        if (otherElement.getEventInParameters() != null && !otherElement.getEventInParameters().isEmpty()) {
            for (IOParameter parameter : otherElement.getEventInParameters()) {
                eventInParameters.add(parameter.clone());
            }
        }

        eventOutParameters = new ArrayList<>();
        if (otherElement.getEventOutParameters() != null && !otherElement.getEventOutParameters().isEmpty()) {
            for (IOParameter parameter : otherElement.getEventOutParameters()) {
                eventOutParameters.add(parameter.clone());
            }
        }
    }
}


text:
//
//  HMAccountTool.h
//  黑马微博
//
//  Created by Kratos on 15/9/20.
//  Copyright (c) 2015年 heima. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "HMAccount.h"
#import "HMBaseTool.h"
#import "HMAccessTokenParam.h"

@interface HMAccountTool : HMBaseTool
//读取账号
+ (void)save:(HMAccount *)account;
//存储账号
+ (HMAccount *)account;

/**
 *  获得accesToken
 *
 *  @param param   <#param description#>
 *  @param sucees  <#sucees description#>
 *  @param failure <#failure description#>
 */
+ (void)accesTokenWithParam:(HMAccessTokenParam *)param sucees:(void (^)(HMAccount *account))sucees failure:(void (^)(NSError *error))failure;
@end


text:
<!DOCTYPE html>

  <title>thinking_style_blog</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="../stylesheets/blog-template.css">

Thinking Style

1.11.2015

      My thinking style is abstract sequential/abstract random. This means that I organize information during reflection and thrive in theoretical and abstract thought. I am going to use this to my adavntage during DBC by implementing these styles when trying to learn new information or taking on a new project. Thinking theoretically is something that will benefit me when writing and learning code. Reflecting on my time during phase-0 I can definitely see how this style of thinking has played to my advantage. Having a growth-mindset is also key to learning quickly and efficiently. Instead of feeling defeated when a failure occurs, I have learned to embrace my errors as new learinng opportunities.


text:
package packages

import (
	"bytes"
)

func bytesGo17() {
	Packages["bytes"]["ContainsRune"] = bytes.ContainsRune
}


text:
/* globals InstanceStatus */
import _ from 'underscore';
import s from 'underscore.string';

RocketChat.models.Uploads = new class extends RocketChat.models._Base {
	constructor() {
		super('uploads');

		this.model.before.insert((userId, doc) => {
			doc.instanceId = InstanceStatus.id();
		});

		this.tryEnsureIndex({ rid: 1 });
		this.tryEnsureIndex({ uploadedAt: 1 });
	}

	findNotHiddenFilesOfRoom(roomId, searchText, limit) {
		const fileQuery = {
			rid: roomId,
			complete: true,
			uploading: false,
			_hidden: {
				$ne: true,
			},
		};

		if (searchText) {
			fileQuery.name = { $regex: new RegExp(RegExp.escape(searchText), 'i') };
		}

		const fileOptions = {
			limit,
			sort: {
				uploadedAt: -1,
			},
			fields: {
				_id: 1,
				userId: 1,
				rid: 1,
				name: 1,
				description: 1,
				type: 1,
				url: 1,
				uploadedAt: 1,
			},
		};

		return this.find(fileQuery, fileOptions);
	}

	insertFileInit(userId, store, file, extra) {
		const fileData = {
			userId,
			store,
			complete: false,
			uploading: true,
			progress: 0,
			extension: s.strRightBack(file.name, '.'),
			uploadedAt: new Date(),
		};

		_.extend(fileData, file, extra);

		if (this.model.direct && this.model.direct.insert != null) {
			file = this.model.direct.insert(fileData);
		} else {
			file = this.insert(fileData);
		}

		return file;
	}

	updateFileComplete(fileId, userId, file) {
		let result;
		if (!fileId) {
			return;
		}

		const filter = {
			_id: fileId,
			userId,
		};

		const update = {
			$set: {
				complete: true,
				uploading: false,
				progress: 1,
			},
		};

		update.$set = _.extend(file, update.$set);

		if (this.model.direct && this.model.direct.update != null) {
			result = this.model.direct.update(filter, update);
		} else {
			result = this.update(filter, update);
		}

		return result;
	}

	deleteFile(fileId) {
		if (this.model.direct && this.model.direct.remove != null) {
			return this.model.direct.remove({ _id: fileId });
		} else {
			return this.remove({ _id: fileId });
		}
	}
};


text:
.class Landroid/widget/Editor$EasyEditPopupWindow;
.super Landroid/widget/Editor$PinnedPopupWindow;
.source "Editor.java"

# interfaces
.implements Landroid/view/View$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/Editor;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "EasyEditPopupWindow"
.end annotation

# static fields
.field private static final POPUP_TEXT_LAYOUT:I = 0x10900d7

# instance fields
.field private mDeleteTextView:Landroid/widget/TextView;

.field private mEasyEditSpan:Landroid/text/style/EasyEditSpan;

.field private mOnDeleteListener:Landroid/widget/Editor$EasyEditDeleteListener;

.field final synthetic this$0:Landroid/widget/Editor;

# direct methods
.method private constructor <init>(Landroid/widget/Editor;)V
    .locals 0

    .prologue
    .line 2101
    iput-object p1, p0, Landroid/widget/Editor$EasyEditPopupWindow;->this$0:Landroid/widget/Editor;

    invoke-direct {p0, p1}, Landroid/widget/Editor$PinnedPopupWindow;-><init>(Landroid/widget/Editor;)V

    return-void
.end method

.method synthetic constructor <init>(Landroid/widget/Editor;Landroid/widget/Editor$1;)V
    .locals 0
    .param p1, "x0"    # Landroid/widget/Editor;
    .param p2, "x1"    # Landroid/widget/Editor$1;

    .prologue
    .line 2101
    invoke-direct {p0, p1}, Landroid/widget/Editor$EasyEditPopupWindow;-><init>(Landroid/widget/Editor;)V

    return-void
.end method

.method static synthetic access$1000(Landroid/widget/Editor$EasyEditPopupWindow;)Landroid/text/style/EasyEditSpan;
    .locals 1
    .param p0, "x0"    # Landroid/widget/Editor$EasyEditPopupWindow;

    .prologue
    .line 2101
    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mEasyEditSpan:Landroid/text/style/EasyEditSpan;

    return-object v0
.end method

.method static synthetic access$1200(Landroid/widget/Editor$EasyEditPopupWindow;Landroid/widget/Editor$EasyEditDeleteListener;)V
    .locals 0
    .param p0, "x0"    # Landroid/widget/Editor$EasyEditPopupWindow;
    .param p1, "x1"    # Landroid/widget/Editor$EasyEditDeleteListener;

    .prologue
    .line 2101
    invoke-direct {p0, p1}, Landroid/widget/Editor$EasyEditPopupWindow;->setOnDeleteListener(Landroid/widget/Editor$EasyEditDeleteListener;)V

    return-void
.end method

.method private setOnDeleteListener(Landroid/widget/Editor$EasyEditDeleteListener;)V
    .locals 0
    .param p1, "listener"    # Landroid/widget/Editor$EasyEditDeleteListener;

    .prologue
    .line 2143
    iput-object p1, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mOnDeleteListener:Landroid/widget/Editor$EasyEditDeleteListener;

    .line 2144
    return-void
.end method

# virtual methods
.method protected clipVertically(I)I
    .locals 0
    .param p1, "positionY"    # I

    .prologue
    .line 2179
    return p1
.end method

.method protected createPopupWindow()V
    .locals 4

    .prologue
    .line 2111
    new-instance v0, Landroid/widget/PopupWindow;

    iget-object v1, p0, Landroid/widget/Editor$EasyEditPopupWindow;->this$0:Landroid/widget/Editor;

    # getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v1}, Landroid/widget/Editor;->access$700(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v1

    invoke-virtual {v1}, Landroid/widget/TextView;->getContext()Landroid/content/Context;

    move-result-object v1

    const/4 v2, 0x0

    const v3, 0x10102c8

    invoke-direct {v0, v1, v2, v3}, Landroid/widget/PopupWindow;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V

    iput-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mPopupWindow:Landroid/widget/PopupWindow;

    .line 2113
    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mPopupWindow:Landroid/widget/PopupWindow;

    const/4 v1, 0x2

    invoke-virtual {v0, v1}, Landroid/widget/PopupWindow;->setInputMethodMode(I)V

    .line 2114
    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mPopupWindow:Landroid/widget/PopupWindow;

    const/4 v1, 0x1

    invoke-virtual {v0, v1}, Landroid/widget/PopupWindow;->setClippingEnabled(Z)V

    .line 2115
    return-void
.end method

.method protected getTextOffset()I
    .locals 2

    .prologue
    .line 2167
    iget-object v1, p0, Landroid/widget/Editor$EasyEditPopupWindow;->this$0:Landroid/widget/Editor;

    # getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v1}, Landroid/widget/Editor;->access$700(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v1

    invoke-virtual {v1}, Landroid/widget/TextView;->getText()Ljava/lang/CharSequence;

    move-result-object v0

    check-cast v0, Landroid/text/Editable;

    .line 2168
    .local v0, "editable":Landroid/text/Editable;
    iget-object v1, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mEasyEditSpan:Landroid/text/style/EasyEditSpan;

    invoke-interface {v0, v1}, Landroid/text/Editable;->getSpanEnd(Ljava/lang/Object;)I

    move-result v1

    return v1
.end method

.method protected getVerticalLocalPosition(I)I
    .locals 1
    .param p1, "line"    # I

    .prologue
    .line 2173
    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->this$0:Landroid/widget/Editor;

    # getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v0}, Landroid/widget/Editor;->access$700(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v0

    invoke-virtual {v0}, Landroid/widget/TextView;->getLayout()Landroid/text/Layout;

    move-result-object v0

    invoke-virtual {v0, p1}, Landroid/text/Layout;->getLineBottom(I)I

    move-result v0

    return v0
.end method

.method public hide()V
    .locals 2

    .prologue
    .line 2157
    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mEasyEditSpan:Landroid/text/style/EasyEditSpan;

    if-eqz v0, :cond_0

    .line 2158
    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mEasyEditSpan:Landroid/text/style/EasyEditSpan;

    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Landroid/text/style/EasyEditSpan;->setDeleteEnabled(Z)V

    .line 2160
    :cond_0
    const/4 v0, 0x0

    iput-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mOnDeleteListener:Landroid/widget/Editor$EasyEditDeleteListener;

    .line 2161
    invoke-super {p0}, Landroid/widget/Editor$PinnedPopupWindow;->hide()V

    .line 2162
    return-void
.end method

.method protected initContentView()V
    .locals 6

    .prologue
    const/4 v5, -0x2

    .line 2119
    new-instance v1, Landroid/widget/LinearLayout;

    iget-object v3, p0, Landroid/widget/Editor$EasyEditPopupWindow;->this$0:Landroid/widget/Editor;

    # getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v3}, Landroid/widget/Editor;->access$700(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v3

    invoke-virtual {v3}, Landroid/widget/TextView;->getContext()Landroid/content/Context;

    move-result-object v3

    invoke-direct {v1, v3}, Landroid/widget/LinearLayout;-><init>(Landroid/content/Context;)V

    .line 2120
    .local v1, "linearLayout":Landroid/widget/LinearLayout;
    const/4 v3, 0x0

    invoke-virtual {v1, v3}, Landroid/widget/LinearLayout;->setOrientation(I)V

    .line 2121
    iput-object v1, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mContentView:Landroid/view/ViewGroup;

    .line 2122
    iget-object v3, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mContentView:Landroid/view/ViewGroup;

    const v4, 0x10806fa

    invoke-virtual {v3, v4}, Landroid/view/ViewGroup;->setBackgroundResource(I)V

    .line 2125
    iget-object v3, p0, Landroid/widget/Editor$EasyEditPopupWindow;->this$0:Landroid/widget/Editor;

    # getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v3}, Landroid/widget/Editor;->access$700(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v3

    invoke-virtual {v3}, Landroid/widget/TextView;->getContext()Landroid/content/Context;

    move-result-object v3

    const-string v4, "layout_inflater"

    invoke-virtual {v3, v4}, Landroid/content/Context;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/LayoutInflater;

    .line 2128
    .local v0, "inflater":Landroid/view/LayoutInflater;
    new-instance v2, Landroid/view/ViewGroup$LayoutParams;

    invoke-direct {v2, v5, v5}, Landroid/view/ViewGroup$LayoutParams;-><init>(II)V

    .line 2131
    .local v2, "wrapContent":Landroid/view/ViewGroup$LayoutParams;
    const v3, 0x10900d7

    const/4 v4, 0x0

    invoke-virtual {v0, v3, v4}, Landroid/view/LayoutInflater;->inflate(ILandroid/view/ViewGroup;)Landroid/view/View;

    move-result-object v3

    check-cast v3, Landroid/widget/TextView;

    iput-object v3, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mDeleteTextView:Landroid/widget/TextView;

    .line 2132
    iget-object v3, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mDeleteTextView:Landroid/widget/TextView;

    invoke-virtual {v3, v2}, Landroid/widget/TextView;->setLayoutParams(Landroid/view/ViewGroup$LayoutParams;)V

    .line 2133
    iget-object v3, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mDeleteTextView:Landroid/widget/TextView;

    const v4, 0x1040467

    invoke-virtual {v3, v4}, Landroid/widget/TextView;->setText(I)V

    .line 2134
    iget-object v3, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mDeleteTextView:Landroid/widget/TextView;

    invoke-virtual {v3, p0}, Landroid/widget/TextView;->setOnClickListener(Landroid/view/View$OnClickListener;)V

    .line 2135
    iget-object v3, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mContentView:Landroid/view/ViewGroup;

    iget-object v4, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mDeleteTextView:Landroid/widget/TextView;

    invoke-virtual {v3, v4}, Landroid/view/ViewGroup;->addView(Landroid/view/View;)V

    .line 2136
    return-void
.end method

.method public onClick(Landroid/view/View;)V
    .locals 2
    .param p1, "view"    # Landroid/view/View;

    .prologue
    .line 2148
    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mDeleteTextView:Landroid/widget/TextView;

    if-ne p1, v0, :cond_0

    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mEasyEditSpan:Landroid/text/style/EasyEditSpan;

    if-eqz v0, :cond_0

    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mEasyEditSpan:Landroid/text/style/EasyEditSpan;

    invoke-virtual {v0}, Landroid/text/style/EasyEditSpan;->isDeleteEnabled()Z

    move-result v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mOnDeleteListener:Landroid/widget/Editor$EasyEditDeleteListener;

    if-eqz v0, :cond_0

    .line 2151
    iget-object v0, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mOnDeleteListener:Landroid/widget/Editor$EasyEditDeleteListener;

    iget-object v1, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mEasyEditSpan:Landroid/text/style/EasyEditSpan;

    invoke-interface {v0, v1}, Landroid/widget/Editor$EasyEditDeleteListener;->onDeleteClick(Landroid/text/style/EasyEditSpan;)V

    .line 2153
    :cond_0
    return-void
.end method

.method public setEasyEditSpan(Landroid/text/style/EasyEditSpan;)V
    .locals 0
    .param p1, "easyEditSpan"    # Landroid/text/style/EasyEditSpan;

    .prologue
    .line 2139
    iput-object p1, p0, Landroid/widget/Editor$EasyEditPopupWindow;->mEasyEditSpan:Landroid/text/style/EasyEditSpan;

    .line 2140
    return-void
.end method


text:
//var SelectionList = Focus.components.list.selection.list.component;
import builder from 'focus-core/component/builder';
let React = require('react');
import type from 'focus-core/component/types';
let assign = require('object-assign');
let omit = require('lodash/object/omit');
let memoryMixin = require('../../list/mixin/memory-scroll');

let MemoryListMixin = {
    mixins: [memoryMixin],

    propTypes: {
        listComponent: type(['func', 'object'])
    },

    /** @inheritdoc */
    render: function renderFormList() {
        var data = this.props.data || [];
        var hasMoreData = data.length > this.state.maxElements;
        var childProps = omit(this.props, ['lineComponent', 'data']);
        return (
            <this.props.listComponent
                ref='list'
                data={this.getDataToUse()}
                hasMoreData={hasMoreData}
                LineComponent={this.props.LineComponent}
                isSelection={false}
                isManualFetch={true}
                fetchNextPage={this.fetchNextPage}
                reference={this.getReference()}
                {...childProps}
                />
        );
    }
};

module.exports = builder(MemoryListMixin);


text:
/*
   TODO: Support for listeners, and perhaps, listeners associated with request paths. HttpMessageHandler.
*/
package com.teletalk.jserver.tcp.http.proxy;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;

import com.teletalk.jserver.SubSystem;
import com.teletalk.jserver.tcp.TcpEndPointIdentifier;
import com.teletalk.jserver.tcp.http.HttpConstants;
import com.teletalk.jserver.tcp.http.HttpRequest;
import com.teletalk.jserver.tcp.http.HttpResponse;
import com.teletalk.jserver.tcp.messaging.Message;
import com.teletalk.jserver.tcp.messaging.MessageDispatchFailedException;
import com.teletalk.jserver.tcp.messaging.MessagingManager;

/**
 * Client interface class used to communicate with a {@link HttpProxy}. To use this class a subclass must be created,
 * which implements the method {@link #handleRequest(HttpRequest)}. This method is called every time a request is
 * received from the proxy.
 *
 * @since 1.2
 *
 * @author Tobias Löfstrand
 */
public class HttpProxyClient extends MessagingManager
{
	/**
	 * Creates a new HttpProxyClient.
	 *
	 * @param parent the parent subsystem of this HttpProxyClient.
	 */
	public HttpProxyClient(SubSystem parent)
	{
		this(parent, "HttpProxyClient");
	}

   /**
    * Creates a new HttpProxyClient.
    *
    * @param parent the parent subsystem of this HttpProxyClient.
    * @param messagingPort the port number of the HTTP proxy.
    */
   public HttpProxyClient(SubSystem parent, int messagingPort)
   {
      this(parent, "HttpProxyClient", messagingPort);
   }

	/**
	 * Creates a new HttpProxyClient.
	 *
	 * @param parent the parent subsystem of this HttpProxyClient.
	 * @param name the name of this HttpProxyClient.
	 */
	public HttpProxyClient(SubSystem parent, String name)
	{
		this(parent, name, (TcpEndPointIdentifier[])null);
	}

   /**
    * Creates a new HttpProxyClient that will attempt to connect to a proxy at the specified address.
    *
    * @param parent the parent subsystem of this HttpProxyClient.
    * @param name the name of this HttpProxyClient.
    * @param messagingPort the port number of the HTTP proxy.
    */
   public HttpProxyClient(SubSystem parent, String name, int messagingPort)
   {
      this(parent, name, new TcpEndPointIdentifier[]{new TcpEndPointIdentifier(messagingPort)});
   }

	/**
	 * Creates a new HttpProxyClient that will attempt to connect to a proxy at the specified address.
	 *
	 * @param parent the parent subsystem of this HttpProxyClient.
	 * @param name the name of this HttpProxyClient.
	 * @param proxyAddress an address to a HTTP proxy.
	 */
	public HttpProxyClient(SubSystem parent, String name, TcpEndPointIdentifier proxyAddress)
	{
		this(parent, name, new TcpEndPointIdentifier[]{proxyAddress});
	}

	/**
	 * Creates a new HttpProxyClient that will attempt to connect to proxies at the specified addresses.
	 *
	 * @param parent the parent subsystem of this HttpProxyClient.
	 * @param name the name of this HttpProxyClient.
	 * @param proxyAddresses addresses to HTTP proxies.
	 */
	public HttpProxyClient(SubSystem parent, String name, TcpEndPointIdentifier[] proxyAddresses)
	{
		super(parent, name, proxyAddresses, null);
	}

	/**
	 * Called when a message is received from the proxy. This method extracts a HttpRequest from the message and
	 * calls the method {@link #handleRequest(HttpRequest)}, and finally returns the response to the proxy.
	 *
	 * @param message the received message.
	 */
	public final void messageReceived(final Message message)
	{
		HttpRequest request = null;
		HttpResponse response = null;

		try
		{
			request = new HttpRequest(message.getBodyAsStream());
			if( super.isDebugMode() ) logDebug("Received request: " + request + ".");

			try
         {
			   response = this.handleRequest(request);
         }
         catch(Throwable t)
         {
            logError("Error occurred while handling request " + request + ".", t);
            response = generateInternalServerErrorResponse("Internal error - " + t);
         }

			InputStream responseInputStream;
			final byte[] responseMessageData = response.getResponseMessage().getBytes(HttpConstants.DEFAULT_CHARACTER_ENCODING);
			final ByteArrayInputStream responseMessageDataInputStream = new ByteArrayInputStream(responseMessageData);

			if( super.isDebugMode() ) logDebug("Returning response (" + response + ") for request: " + request + ".");

			// If the response contains a body
			if( response.length() > 0 )
			{
				// Attempt to get the response body as a stream...
				InputStream bodyInputStream = response.getBodyInputStream();

				if( bodyInputStream == null )
				{
					// ...otherwise get the response body as a byte array
					bodyInputStream = new ByteArrayInputStream(response.getBody());
				}
				// Combine the (byte array) input stream for reading the request message with the stream used to read the request body
				responseInputStream = new SequenceInputStream(responseMessageDataInputStream, bodyInputStream);
			}
			else
			{
				responseInputStream = responseMessageDataInputStream;
			}

			// Send response
			super.dispatchMessageAsync(message.getHeader(), responseInputStream, (responseMessageData.length + response.length()) );
		}
		catch(MessageDispatchFailedException mdfe)
		{
			logWarning("Unable to send response (" + response + ") to request (" + request + ").", mdfe);
		}
		catch(Exception e)
		{
			logError("Error occurred while sending response (" + response + ") to request (" + request + ").", e);
		}
	}

	/**
	 * Method for handling incomming HTTP requests received from the proxy.
	 *
	 * @param request a HTTP request received from a client.
	 *
	 * @return the HTTP response that should be returned to the client (though the proxy) that sent the request.
	 */
	public HttpResponse handleRequest(final HttpRequest request)
   {
      return generateInternalServerErrorResponse("Bad configuration, no request handler found - unable to server request " + request.getPath() + ".");
   }

   /**
    * Generates an error response.
    */
   private HttpResponse generateInternalServerErrorResponse(final String responseMsg)
   {
      HttpResponse rsp;
      String msg;

      msg = "
500 Internal Server Error
";
      msg += responseMsg;
      msg += "";
      rsp = new HttpResponse(500, "Internal server error", msg);
      rsp.setContentType("text/html");

      return rsp;
   }
}


text:
'use strict';
angular.module('com.module.tickets')
  .config(function ($stateProvider) {
    $stateProvider
      .state('app.refunds', {
        abstract: true,
        url: '/refunds',
        templateUrl: 'modules/refunds/views/main.html'
      })
      .state('app.refunds.list', {
        url: '',
        templateUrl: 'modules/refunds/views/list.html',
        controller: 'ticketsCtrl',
          resolve:{
          refunds: function(SER_mcglobalRequests){
            return SER_mcglobalRequests.find().$promise;

          }
        }

      })\
      .state('app.refunds.view', {
        url: '/:id',
        templateUrl: 'modules/refunds/views/view.html',
        controller: 'ticketDetailCtrl',
          resolve:{

          ticket: function(SER_mcglobalRequests, $stateParams){
            console.log('are we running this resolve');
            console.log($stateParams.id);
            return SER_mcglobalRequests.find({"filter":{"where":{"id":$stateParams.id}}}).$promise;
          },

          comments: function(CommentService, $stateParams){
            console.log('are we running this second resolve');
            return CommentService.getComments($stateParams.id);
          }
        }

      })
  });


text:
declare function _V_(id: any, options?: _V_.Options, ready?: () => void): _V_.IPlayer;

declare module _V_ {
    function plugin(name: string, plugin: (options: any) => void): void;

    interface Options {
        techOrder?: string[];
        html5?: Object;
        width?: number;
        height?: number;
        defaultVolume?: number;
        children?: Object;
    }

    export interface IComponent {
        id();
        dispose();
        createEl(type, props): any;
        el();
        addChild(child);
        addChild(child, options);
        children(): any[];
        on(type, fn: () => void);
        off(type, fn: () => void);
        one(type, fn: () => void);
        trigger(type, event?: any);
        show();
        hide();
        width();
        height();
        dimensions(width: number, height: number);
        lockShowing();
        unlockShowing();
        options();
    }

    export class Component implements IComponent {
        constructor(player: any, options?: any);
        id();
        dispose();
        createEl(type, props): any;
        el();
        addChild(child);
        addChild(child, options);
        children(): any[];
        on(type, fn: () => void);
        off(type, fn: () => void);
        one(type, fn: () => void);
        trigger(type, event?: any);
        show();
        hide();
        width();
        height();
        dimensions(width: number, height: number);
        lockShowing();
        unlockShowing();
        options();
    }

    export class Menu extends Component {
        addItem(component);
    }

    export class MenuItem extends Component {
        constructor(player: any, options: any);
    }

    export class Button extends Component {
    }

    export interface IPlayer extends IComponent {
        play();
        currentTime(time?: string);
        src(source?: string);
        techName;
        currentSrc();
        duration(time?: number);
    }

    export class Player extends Component implements IPlayer {
        play();
        currentTime();
        src(source?: string);
        techName;
        currentSrc();
        duration();
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Doc Schema
 */
var DocSchema = new Schema({
	title: {
		type: String,
		default: '',
		required: 'Please fill Doc title',
		trim: true
	},
	description: {
		type: String,
		default: '',
		required: 'Please fill Doc description',
		trim: true
	},
	type: {
		type: String,
		default: '',
		required: 'Please fill Doc type',
		trim: true
	},
	url: {
		type: String,
		default: '',
		required: 'Please fill Doc url',
		trim: true
	},
	thumbnail_image: {
		type: String,
		default: '',
		required: 'Please fill Doc thumbnail_image',
		trim: true
	},
	tags: {
		type: Schema.Types.Mixed,
		default: '',
		trim: true
	},
	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
	viewCount: {
		type: Number,
		default: 0
	}//,
	//to add new schema simply uncomment the default one below and rename the variables.
	//Also uncomment out the comma after the viewCount schema above
	//test: {
		//type: String,
		//default:  ' '
	//}

});

mongoose.model('Doc', DocSchema);


text:
{% extends "base.html" %}
{% block content %}
    {{ block.super }}

 Edit a Product Type Member

    <form class="form-horizontal" action="{%  url 'edit_product_type_member' memberid %}" method="post">{% csrf_token %}
        {% include "dojo/form_fields.html" with form=form %}

                <input class="btn btn-primary" type="submit" value="Submit"/>

    </form>
{% endblock %}


text:
import { Component, Listen, Method, Prop } from '@stencil/core';
import { PickerOptions } from '../../interface';
import { OverlayController, createOverlay, dismissOverlay, getTopOverlay, removeLastOverlay } from '../../utils/overlays';

/** @hidden */
@Component({
  tag: 'ion-picker-controller'
})
export class PickerController implements OverlayController {

  private pickers = new Map<number, HTMLIonPickerElement>();

  @Prop({ context: 'document' }) doc!: Document;

  @Listen('body:ionPickerWillPresent')
  protected pickerWillPresent(ev: any) {
    this.pickers.set(ev.target.overlayId, ev.target);
  }

  @Listen('body:ionPickerWillDismiss')
  @Listen('body:ionPickerDidUnload')
  protected pickerWillDismiss(ev: any) {
    this.pickers.delete(ev.target.overlayId);
  }

  @Listen('body:keyup.escape')
  protected escapeKeyUp() {
    removeLastOverlay(this.pickers);
  }

  /*
   * Create a picker overlay with picker options.
   */
  @Method()
  create(opts?: PickerOptions): Promise<HTMLIonPickerElement | null> {
    return createOverlay(this.doc.createElement('ion-picker'), opts);
  }

  /*
   * Dismiss the open picker overlay.
   */
  @Method()
  dismiss(data?: any, role?: string, pickerId = -1) {
    return dismissOverlay(data, role, this.pickers, pickerId);
  }

  /*
   * Get the most recently opened picker overlay.
   */
  @Method()
  getTop(): HTMLIonPickerElement {
    return getTopOverlay(this.pickers);
  }
}