text:
package com.yahoo.pulsar.broker.service;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.matches;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import javax.naming.AuthenticationException;

import org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback;
import org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback;
import org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback;
import org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback;
import org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback;
import org.apache.bookkeeper.mledger.ManagedCursor;
import org.apache.bookkeeper.mledger.ManagedLedger;
import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
import org.apache.bookkeeper.mledger.ManagedLedgerException;
import org.apache.bookkeeper.mledger.ManagedLedgerFactory;
import org.apache.bookkeeper.mledger.impl.PositionImpl;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.ZooKeeper;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.yahoo.pulsar.broker.PulsarService;
import com.yahoo.pulsar.broker.ServiceConfiguration;
import com.yahoo.pulsar.broker.authentication.AuthenticationDataCommand;
import com.yahoo.pulsar.broker.authentication.AuthenticationService;
import com.yahoo.pulsar.broker.authorization.AuthorizationManager;
import com.yahoo.pulsar.broker.cache.ConfigurationCacheService;
import com.yahoo.pulsar.broker.namespace.NamespaceService;
import com.yahoo.pulsar.broker.service.ServerCnx.State;
import com.yahoo.pulsar.broker.service.persistent.PersistentTopic;
import com.yahoo.pulsar.broker.service.utils.ClientChannelHelper;
import com.yahoo.pulsar.common.api.Commands;
import com.yahoo.pulsar.common.api.proto.PulsarApi.AuthMethod;
import com.yahoo.pulsar.common.api.proto.PulsarApi.CommandAck.AckType;
import com.yahoo.pulsar.common.api.proto.PulsarApi.CommandConnected;
import com.yahoo.pulsar.common.api.proto.PulsarApi.CommandError;
import com.yahoo.pulsar.common.api.proto.PulsarApi.CommandProducerSuccess;
import com.yahoo.pulsar.common.api.proto.PulsarApi.CommandSendReceipt;
import com.yahoo.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType;
import com.yahoo.pulsar.common.api.proto.PulsarApi.CommandSuccess;
import com.yahoo.pulsar.common.api.proto.PulsarApi.MessageMetadata;
import com.yahoo.pulsar.common.api.proto.PulsarApi.ProtocolVersion;
import com.yahoo.pulsar.common.api.proto.PulsarApi.ServerError;
import com.yahoo.pulsar.common.naming.DestinationName;
import com.yahoo.pulsar.common.naming.ServiceUnitId;
import com.yahoo.pulsar.common.policies.data.AuthAction;
import com.yahoo.pulsar.common.policies.data.Policies;
import com.yahoo.pulsar.zookeeper.ZooKeeperDataCache;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 */
@Test
public class ServerCnxTest {
    private EmbeddedChannel channel;
    private ServiceConfiguration svcConfig;
    private ServerCnx serverCnx;
    private BrokerService brokerService;
    private ManagedLedgerFactory mlFactoryMock;
    private ClientChannelHelper clientChannelHelper;
    private PulsarService pulsar;
    private ConfigurationCacheService configCacheService;
    private NamespaceService namespaceService;
    private final int currentProtocolVersion = ProtocolVersion.values()[ProtocolVersion.values().length - 1]
            .getNumber();

    private final String successTopicName = "persistent://prop/use/ns-abc/successTopic";
    private final String failTopicName = "persistent://prop/use/ns-abc/failTopic";
    private final String nonOwnedTopicName = "persistent://prop/use/ns-abc/success-not-owned-topic";
    private final String successSubName = "successSub";
    private final String nonExistentTopicName = "persistent://nonexistent-prop/nonexistent-cluster/nonexistent-namespace/successNonExistentTopic";
    private final String topicWithNonLocalCluster = "persistent://prop/usw/ns-abc/successTopic";

    @BeforeMethod
    public void setup() throws Exception {
        svcConfig = spy(new ServiceConfiguration());
        pulsar = spy(new PulsarService(svcConfig));
        svcConfig.setKeepAliveIntervalSeconds(inSec(1, TimeUnit.SECONDS));
        svcConfig.setBacklogQuotaCheckEnabled(false);
        doReturn(svcConfig).when(pulsar).getConfiguration();

        doReturn("use").when(svcConfig).getClusterName();

        mlFactoryMock = mock(ManagedLedgerFactory.class);
        doReturn(mlFactoryMock).when(pulsar).getManagedLedgerFactory();

        ZooKeeper mockZk = mock(ZooKeeper.class);
        doReturn(mockZk).when(pulsar).getZkClient();

        configCacheService = mock(ConfigurationCacheService.class);
        @SuppressWarnings("unchecked")
        ZooKeeperDataCache<Policies> zkDataCache = mock(ZooKeeperDataCache.class);
        doReturn(zkDataCache).when(configCacheService).policiesCache();
        doReturn(configCacheService).when(pulsar).getConfigurationCache();

        brokerService = spy(new BrokerService(pulsar));
        doReturn(brokerService).when(pulsar).getBrokerService();

        namespaceService = mock(NamespaceService.class);
        doReturn(namespaceService).when(pulsar).getNamespaceService();
        doReturn(true).when(namespaceService).isServiceUnitOwned(any(ServiceUnitId.class));
        doReturn(true).when(namespaceService).isServiceUnitActive(any(DestinationName.class));

        setupMLAsyncCallbackMocks();

        clientChannelHelper = new ClientChannelHelper();
    }

    private int inSec(int time, TimeUnit unit) {
        return (int) TimeUnit.SECONDS.convert(time, unit);
    }

    @AfterMethod
    public void teardown() throws Exception {
        serverCnx.close();
        channel.close();
        pulsar.close();
        brokerService.close();
    }

    @Test(timeOut = 30000)
    public void testConnectCommand() throws Exception {
        resetChannel();
        assertTrue(channel.isActive());
        assertEquals(serverCnx.getState(), State.Start);

        // test server response to CONNECT
        ByteBuf clientCommand = Commands.newConnect("none", "");
        channel.writeInbound(clientCommand);

        assertEquals(serverCnx.getState(), State.Connected);
        assertTrue(getResponse() instanceof CommandConnected);
        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testConnectCommandWithEnum() throws Exception {
        resetChannel();
        assertTrue(channel.isActive());
        assertEquals(serverCnx.getState(), State.Start);

        // test server response to CONNECT
        ByteBuf clientCommand = Commands.newConnect(AuthMethod.AuthMethodNone, "");
        channel.writeInbound(clientCommand);

        assertEquals(serverCnx.getState(), State.Connected);
        assertTrue(getResponse() instanceof CommandConnected);
        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testConnectCommandWithProtocolVersion() throws Exception {
        resetChannel();
        assertTrue(channel.isActive());
        assertEquals(serverCnx.getState(), State.Start);

        // test server response to CONNECT
        ByteBuf clientCommand = Commands.newConnect("none", "");
        channel.writeInbound(clientCommand);

        assertEquals(serverCnx.getState(), State.Connected);
        CommandConnected response = (CommandConnected) getResponse();
        assertEquals(response.getProtocolVersion(), currentProtocolVersion);
        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testKeepAlive() throws Exception {
        resetChannel();
        assertTrue(channel.isActive());
        assertEquals(serverCnx.getState(), State.Start);

        // test server response to CONNECT
        ByteBuf clientCommand = Commands.newConnect("none", "");
        channel.writeInbound(clientCommand);

        assertEquals(serverCnx.getState(), State.Connected);
        CommandConnected response = (CommandConnected) getResponse();
        assertEquals(response.getProtocolVersion(), currentProtocolVersion);

        // Connection will be closed in 2 seconds, in the meantime give chance to run the cleanup logic
        for (int i = 0; i < 3; i++) {
            channel.runPendingTasks();
            Thread.sleep(1000);
        }

        assertFalse(channel.isActive());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testKeepAliveNotEnforcedWithOlderClients() throws Exception {
        resetChannel();
        assertTrue(channel.isActive());
        assertEquals(serverCnx.getState(), State.Start);

        // test server response to CONNECT
        ByteBuf clientCommand = Commands.newConnect("none", "", ProtocolVersion.v0.getNumber());
        channel.writeInbound(clientCommand);

        assertEquals(serverCnx.getState(), State.Connected);
        CommandConnected response = (CommandConnected) getResponse();
        // Server is responding with same version as client
        assertEquals(response.getProtocolVersion(), ProtocolVersion.v0.getNumber());

        // Connection will *not* be closed in 2 seconds
        for (int i = 0; i < 3; i++) {
            channel.runPendingTasks();
            Thread.sleep(1000);
        }
        assertTrue(channel.isActive());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testKeepAliveBeforeHandshake() throws Exception {
        resetChannel();
        assertTrue(channel.isActive());
        assertEquals(serverCnx.getState(), State.Start);

        // test server doesn't received a CONNECT command and should close the connection after timeout

        // Connection will be closed in 2 seconds, in the meantime give chance to run the cleanup logic
        for (int i = 0; i < 3; i++) {
            channel.runPendingTasks();
            Thread.sleep(1000);
        }

        assertFalse(channel.isActive());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testConnectCommandWithAuthenticationPositive() throws Exception {
        AuthenticationService authenticationService = mock(AuthenticationService.class);
        doReturn(authenticationService).when(brokerService).getAuthenticationService();
        doReturn("appid1").when(authenticationService).authenticate(new AuthenticationDataCommand(Mockito.anyString()),
                Mockito.anyString());
        doReturn(true).when(brokerService).isAuthenticationEnabled();

        resetChannel();
        assertTrue(channel.isActive());
        assertEquals(serverCnx.getState(), State.Start);

        // test server response to CONNECT
        ByteBuf clientCommand = Commands.newConnect("none", "");
        channel.writeInbound(clientCommand);

        assertEquals(serverCnx.getState(), State.Connected);
        assertTrue(getResponse() instanceof CommandConnected);
        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testConnectCommandWithAuthenticationNegative() throws Exception {
        AuthenticationException e = new AuthenticationException();
        AuthenticationService authenticationService = mock(AuthenticationService.class);
        doReturn(authenticationService).when(brokerService).getAuthenticationService();
        doThrow(e).when(authenticationService).authenticate(new AuthenticationDataCommand(Mockito.anyString()),
                Mockito.anyString());
        doReturn(true).when(brokerService).isAuthenticationEnabled();

        resetChannel();
        assertTrue(channel.isActive());
        assertEquals(serverCnx.getState(), State.Start);

        // test server response to CONNECT
        ByteBuf clientCommand = Commands.newConnect("none", "");
        channel.writeInbound(clientCommand);

        assertEquals(serverCnx.getState(), State.Start);
        assertTrue(getResponse() instanceof CommandError);
        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testProducerCommand() throws Exception {
        resetChannel();
        setChannelConnected();

        // test PRODUCER success case
        ByteBuf clientCommand = Commands.newProducer(successTopicName, 1 /* producer id */, 1 /* request id */,
                "prod-name");
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandProducerSuccess);

        PersistentTopic topicRef = (PersistentTopic) brokerService.getTopicReference(successTopicName);

        assertNotNull(topicRef);
        assertEquals(topicRef.getProducers().size(), 1);

        // test PRODUCER error case
        clientCommand = Commands.newProducer(failTopicName, 2, 2, "prod-name-2");
        channel.writeInbound(clientCommand);

        assertTrue(getResponse() instanceof CommandError);
        assertNull(brokerService.getTopicReference(failTopicName));

        channel.finish();
        assertEquals(topicRef.getProducers().size(), 0);
    }

    @Test(timeOut = 30000)
    public void testProducerOnNotOwnedTopic() throws Exception {
        resetChannel();
        setChannelConnected();

        // Force the case where the broker doesn't own any topic
        doReturn(false).when(namespaceService).isServiceUnitActive(any(DestinationName.class));

        // test PRODUCER failure case
        ByteBuf clientCommand = Commands.newProducer(nonOwnedTopicName, 1 /* producer id */, 1 /* request id */,
                "prod-name");
        channel.writeInbound(clientCommand);

        Object response = getResponse();
        assertEquals(response.getClass(), CommandError.class);

        CommandError errorResponse = (CommandError) response;
        assertEquals(errorResponse.getError(), ServerError.ServiceNotReady);

        assertNull(brokerService.getTopicReference(nonOwnedTopicName));

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testProducerCommandWithAuthorizationPositive() throws Exception {
        AuthorizationManager authorizationManager = mock(AuthorizationManager.class);
        doReturn(true).when(authorizationManager).canProduce(Mockito.any(), Mockito.any());
        doReturn(authorizationManager).when(brokerService).getAuthorizationManager();
        doReturn(true).when(brokerService).isAuthenticationEnabled();
        resetChannel();
        setChannelConnected();

        // test PRODUCER success case
        ByteBuf clientCommand = Commands.newProducer(successTopicName, 1 /* producer id */, 1 /* request id */,
                "prod-name");
        channel.writeInbound(clientCommand);
        assertEquals(getResponse().getClass(), CommandProducerSuccess.class);

        PersistentTopic topicRef = (PersistentTopic) brokerService.getTopicReference(successTopicName);

        assertNotNull(topicRef);
        assertEquals(topicRef.getProducers().size(), 1);

        channel.finish();
        assertEquals(topicRef.getProducers().size(), 0);
    }

    @SuppressWarnings("unchecked")
    @Test(timeOut = 30000)
    public void testNonExistentTopic() throws Exception {
        ZooKeeperDataCache<Policies> zkDataCache = mock(ZooKeeperDataCache.class);
        ConfigurationCacheService configCacheService = mock(ConfigurationCacheService.class);
        doReturn(configCacheService).when(pulsar).getConfigurationCache();
        doReturn(zkDataCache).when(configCacheService).policiesCache();
        doThrow(new NoNodeException()).when(zkDataCache).get(matches(".*nonexistent.*"));

        AuthorizationManager authorizationManager = spy(new AuthorizationManager(svcConfig, configCacheService));
        doReturn(authorizationManager).when(brokerService).getAuthorizationManager();
        doReturn(true).when(brokerService).isAuthorizationEnabled();
        doReturn(false).when(authorizationManager).isSuperUser(Mockito.anyString());

        // Test producer creation
        resetChannel();
        setChannelConnected();
        ByteBuf newProducerCmd = Commands.newProducer(nonExistentTopicName, 1 /* producer id */, 1 /* request id */,
                "prod-name");
        channel.writeInbound(newProducerCmd);
        assertTrue(getResponse() instanceof CommandError);
        channel.finish();

        // Test consumer creation
        resetChannel();
        setChannelConnected();
        ByteBuf newSubscribeCmd = Commands.newSubscribe(nonExistentTopicName, //
                successSubName, 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(newSubscribeCmd);
        assertTrue(getResponse() instanceof CommandError);
    }

    @Test(timeOut = 30000)
    public void testClusterAccess() throws Exception {
        AuthorizationManager authorizationManager = spy(new AuthorizationManager(svcConfig, configCacheService));
        doReturn(authorizationManager).when(brokerService).getAuthorizationManager();
        doReturn(true).when(brokerService).isAuthorizationEnabled();
        doReturn(false).when(authorizationManager).isSuperUser(Mockito.anyString());
        doReturn(true).when(authorizationManager).checkPermission(any(DestinationName.class), Mockito.anyString(),
                any(AuthAction.class));

        resetChannel();
        setChannelConnected();
        ByteBuf clientCommand = Commands.newProducer(successTopicName, 1 /* producer id */, 1 /* request id */,
                "prod-name");
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandProducerSuccess);

        resetChannel();
        setChannelConnected();
        clientCommand = Commands.newProducer(topicWithNonLocalCluster, 1 /* producer id */, 1 /* request id */,
                "prod-name");
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandError);
    }

    @Test(timeOut = 30000)
    public void testNonExistentTopicSuperUserAccess() throws Exception {
        AuthorizationManager authorizationManager = spy(new AuthorizationManager(svcConfig, configCacheService));
        doReturn(authorizationManager).when(brokerService).getAuthorizationManager();
        doReturn(true).when(brokerService).isAuthorizationEnabled();
        doReturn(true).when(authorizationManager).isSuperUser(Mockito.anyString());

        // Test producer creation
        resetChannel();
        setChannelConnected();
        ByteBuf newProducerCmd = Commands.newProducer(nonExistentTopicName, 1 /* producer id */, 1 /* request id */,
                "prod-name");
        channel.writeInbound(newProducerCmd);
        assertTrue(getResponse() instanceof CommandProducerSuccess);

        PersistentTopic topicRef = (PersistentTopic) brokerService.getTopicReference(nonExistentTopicName);
        assertNotNull(topicRef);
        assertEquals(topicRef.getProducers().size(), 1);
        channel.finish();

        // Test consumer creation
        resetChannel();
        setChannelConnected();
        ByteBuf newSubscribeCmd = Commands.newSubscribe(nonExistentTopicName, //
                successSubName, 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(newSubscribeCmd);
        topicRef = (PersistentTopic) brokerService.getTopicReference(nonExistentTopicName);
        assertNotNull(topicRef);
        assertTrue(topicRef.getSubscriptions().containsKey(successSubName));
        assertTrue(topicRef.getPersistentSubscription(successSubName).getDispatcher().isConsumerConnected());
        assertTrue(getResponse() instanceof CommandSuccess);
    }

    public void testProducerCommandWithAuthorizationNegative() throws Exception {
        AuthorizationManager authorizationManager = mock(AuthorizationManager.class);
        doReturn(false).when(authorizationManager).canProduce(Mockito.any(), Mockito.any());
        doReturn(authorizationManager).when(brokerService).getAuthorizationManager();
        doReturn(true).when(brokerService).isAuthenticationEnabled();
        doReturn(true).when(brokerService).isAuthorizationEnabled();
        resetChannel();
        setChannelConnected();

        ByteBuf clientCommand = Commands.newProducer(successTopicName, 1 /* producer id */, 1 /* request id */, null);
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandError);

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testSendCommand() throws Exception {
        resetChannel();
        setChannelConnected();

        ByteBuf clientCommand = Commands.newProducer(successTopicName, 1 /* producer id */, 1 /* request id */,
                "prod-name");
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandProducerSuccess);

        // test SEND success
        MessageMetadata messageMetadata = MessageMetadata.newBuilder().setPublishTime(System.currentTimeMillis())
                .setProducerName("prod-name").setSequenceId(0).build();
        ByteBuf data = Unpooled.buffer(1024);

        clientCommand = Commands.newSend(1, 0, 1, messageMetadata, data);
        channel.writeInbound(Unpooled.copiedBuffer(clientCommand));
        clientCommand.release();

        assertTrue(getResponse() instanceof CommandSendReceipt);
        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testUseSameProducerName() throws Exception {
        resetChannel();
        setChannelConnected();

        String producerName = "my-producer";

        ByteBuf clientCommand1 = Commands.newProducer(successTopicName, 1 /* producer id */, 1 /* request id */,
                producerName);
        channel.writeInbound(clientCommand1);
        assertTrue(getResponse() instanceof CommandProducerSuccess);

        ByteBuf clientCommand2 = Commands.newProducer(successTopicName, 2 /* producer id */, 2 /* request id */,
                producerName);
        channel.writeInbound(clientCommand2);
        assertTrue(getResponse() instanceof CommandError);

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testRecreateSameProducer() throws Exception {
        resetChannel();
        setChannelConnected();

        // Recreating a producer with the same id should succeed

        String producerName = "my-producer";

        ByteBuf createProducer1 = Commands.newProducer(successTopicName, 1 /* producer id */, 1 /* request id */,
                producerName);
        channel.writeInbound(createProducer1);

        // Producer create succeeds
        Object response = getResponse();
        assertEquals(response.getClass(), CommandProducerSuccess.class);
        assertEquals(((CommandProducerSuccess) response).getRequestId(), 1);

        ByteBuf createProducer2 = Commands.newProducer(successTopicName, 1 /* producer id */, 2 /* request id */,
                producerName);
        channel.writeInbound(createProducer2);

        // 2nd producer create succeeds as well
        response = getResponse();
        assertEquals(response.getClass(), CommandProducerSuccess.class);
        assertEquals(((CommandProducerSuccess) response).getRequestId(), 2);

        // We should not receive response for 1st producer, since it was cancelled by the close
        assertTrue(channel.outboundMessages().isEmpty());
        assertTrue(channel.isActive());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testSubscribeMultipleTimes() throws Exception {
        resetChannel();
        setChannelConnected();

        Object response;

        // Sending multiple subscribe commands for the same consumer should succeed

        ByteBuf subscribe1 = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(subscribe1);

        // 1st subscribe succeeds
        response = getResponse();
        assertEquals(response.getClass(), CommandSuccess.class);
        assertEquals(((CommandSuccess) response).getRequestId(), 1);

        ByteBuf subscribe2 = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 2 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(subscribe2);

        // 2nd subscribe succeeds
        response = getResponse();
        assertEquals(response.getClass(), CommandSuccess.class);
        assertEquals(((CommandSuccess) response).getRequestId(), 2);

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testCreateProducerTimeout() throws Exception {
        resetChannel();
        setChannelConnected();

        // In a create producer timeout from client side we expect to see this sequence of commands :
        // 1. create producer
        // 2. close producer (when the timeout is triggered, which may be before the producer was created on the broker
        // 3. create producer (triggered by reconnection logic)

        // These operations need to be serialized, to allow the last create producer to finally succeed
        // (There can be more create/close pairs in the sequence, depending on the client timeout

        String producerName = "my-producer";

        ByteBuf createProducer1 = Commands.newProducer(successTopicName, 1 /* producer id */, 1 /* request id */,
                producerName);
        channel.writeInbound(createProducer1);

        ByteBuf closeProducer = Commands.newCloseProducer(1 /* producer id */, 2 /* request id */ );
        channel.writeInbound(closeProducer);

        ByteBuf createProducer2 = Commands.newProducer(successTopicName, 1 /* producer id */, 3 /* request id */,
                producerName);
        channel.writeInbound(createProducer2);

        // Close succeeds
        Object response = getResponse();
        assertEquals(response.getClass(), CommandSuccess.class);
        assertEquals(((CommandSuccess) response).getRequestId(), 2);

        // 2nd producer fails to create
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 3);

        // We should not receive response for 1st producer, since it was cancelled by the close
        assertTrue(channel.outboundMessages().isEmpty());
        assertTrue(channel.isActive());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testCreateProducerMultipleTimeouts() throws Exception {
        resetChannel();
        setChannelConnected();

        // In a create producer timeout from client side we expect to see this sequence of commands :
        // 1. create producer
        // 2. close producer (when the timeout is triggered, which may be before the producer was created on the broker
        // 3. create producer (triggered by reconnection logic)

        // These operations need to be serialized, to allow the last create producer to finally succeed
        // (There can be more create/close pairs in the sequence, depending on the client timeout

        String producerName = "my-producer";

        ByteBuf createProducer1 = Commands.newProducer(successTopicName, 1 /* producer id */, 1 /* request id */,
                producerName);
        channel.writeInbound(createProducer1);

        ByteBuf closeProducer1 = Commands.newCloseProducer(1 /* producer id */, 2 /* request id */ );
        channel.writeInbound(closeProducer1);

        ByteBuf createProducer2 = Commands.newProducer(successTopicName, 1 /* producer id */, 3 /* request id */,
                producerName);
        channel.writeInbound(createProducer2);

        ByteBuf createProducer3 = Commands.newProducer(successTopicName, 1 /* producer id */, 4 /* request id */,
                producerName);
        channel.writeInbound(createProducer3);

        ByteBuf createProducer4 = Commands.newProducer(successTopicName, 1 /* producer id */, 5 /* request id */,
                producerName);
        channel.writeInbound(createProducer4);

        // Close succeeds
        Object response = getResponse();
        assertEquals(response.getClass(), CommandSuccess.class);
        assertEquals(((CommandSuccess) response).getRequestId(), 2);

        // 1st producer it's not acked

        // 2nd producer fails
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 3);

        // 3rd producer fails
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 4);

        // 4nd producer fails
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 5);

        Thread.sleep(100);

        // We should not receive response for 1st producer, since it was cancelled by the close
        assertTrue(channel.outboundMessages().isEmpty());
        assertTrue(channel.isActive());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testCreateProducerBookieTimeout() throws Exception {
        resetChannel();
        setChannelConnected();

        // In a create producer timeout from client side we expect to see this sequence of commands :
        // 1. create a failure producer which will timeout creation after 100msec
        // 2. close producer
        // 3. Recreate producer (triggered by reconnection logic)
        // 4. Wait till the timeout of 1, and create producer again.

        // These operations need to be serialized, to allow the last create producer to finally succeed
        // (There can be more create/close pairs in the sequence, depending on the client timeout

        String producerName = "my-producer";

        ByteBuf createProducer1 = Commands.newProducer(failTopicName, 1 /* producer id */, 1 /* request id */,
                producerName);
        channel.writeInbound(createProducer1);

        ByteBuf closeProducer = Commands.newCloseProducer(1 /* producer id */, 2 /* request id */ );
        channel.writeInbound(closeProducer);

        ByteBuf createProducer2 = Commands.newProducer(successTopicName, 1 /* producer id */, 3 /* request id */,
                producerName);
        channel.writeInbound(createProducer2);

        // Close succeeds
        Object response = getResponse();
        assertEquals(response.getClass(), CommandSuccess.class);
        assertEquals(((CommandSuccess) response).getRequestId(), 2);

        // 2nd producer fails
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 3);

        // Wait till the failtopic timeout interval
        Thread.sleep(200);
        ByteBuf createProducer3 = Commands.newProducer(successTopicName, 1 /* producer id */, 4 /* request id */,
                producerName);
        channel.writeInbound(createProducer3);

        // 3rd producer succeeds
        response = getResponse();
        assertEquals(response.getClass(), CommandProducerSuccess.class);
        assertEquals(((CommandProducerSuccess) response).getRequestId(), 4);

        Thread.sleep(100);

        // We should not receive response for 1st producer, since it was cancelled by the close
        assertTrue(channel.outboundMessages().isEmpty());
        assertTrue(channel.isActive());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testSubscribeTimeout() throws Exception {
        resetChannel();
        setChannelConnected();

        // In a subscribe timeout from client side we expect to see this sequence of commands :
        // 1. Subscribe
        // 2. close consumer (when the timeout is triggered, which may be before the consumer was created on the broker)
        // 3. Subscribe (triggered by reconnection logic)

        // These operations need to be serialized, to allow the last subscribe operation to finally succeed
        // (There can be more subscribe/close pairs in the sequence, depending on the client timeout

        ByteBuf subscribe1 = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(subscribe1);

        ByteBuf closeConsumer = Commands.newCloseConsumer(1 /* consumer id */, 2 /* request id */ );
        channel.writeInbound(closeConsumer);

        ByteBuf subscribe2 = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 3 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(subscribe2);

        ByteBuf subscribe3 = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 4 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(subscribe3);

        ByteBuf subscribe4 = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 5 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(subscribe4);

        Object response;

        // Close succeeds
        response = getResponse();
        assertEquals(response.getClass(), CommandSuccess.class);
        assertEquals(((CommandSuccess) response).getRequestId(), 2);

        // All other subscribe should fail
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 3);

        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 4);

        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 5);

        Thread.sleep(100);

        // We should not receive response for 1st producer, since it was cancelled by the close
        assertTrue(channel.outboundMessages().isEmpty());
        assertTrue(channel.isActive());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testSubscribeBookieTimeout() throws Exception {
        resetChannel();
        setChannelConnected();

        // In a subscribe timeout from client side we expect to see this sequence of commands :
        // 1. Subscribe against failtopic which will fail after 100msec
        // 2. close consumer
        // 3. Resubscribe (triggered by reconnection logic)
        // 4. Wait till the timeout of 1, and subscribe again.

        // These operations need to be serialized, to allow the last subscribe operation to finally succeed
        // (There can be more subscribe/close pairs in the sequence, depending on the client timeout

        ByteBuf subscribe1 = Commands.newSubscribe(failTopicName, //
                successSubName, 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(subscribe1);

        ByteBuf closeConsumer = Commands.newCloseConsumer(1 /* consumer id */, 2 /* request id */ );
        channel.writeInbound(closeConsumer);

        ByteBuf subscribe2 = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 3 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(subscribe2);

        Object response;

        // Close succeeds
        response = getResponse();
        assertEquals(response.getClass(), CommandSuccess.class);
        assertEquals(((CommandSuccess) response).getRequestId(), 2);

        // Subscribe fails
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 3);

        // Wait till the failtopic timeout interval
        Thread.sleep(200);

        ByteBuf subscribe3 = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 4 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(subscribe3);

        // Subscribe succeeds
        response = getResponse();
        assertEquals(response.getClass(), CommandSuccess.class);
        assertEquals(((CommandSuccess) response).getRequestId(), 4);

        Thread.sleep(100);

        // We should not receive response for 1st producer, since it was cancelled by the close
        assertTrue(channel.outboundMessages().isEmpty());
        assertTrue(channel.isActive());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testSubscribeCommand() throws Exception {
        final String failSubName = "failSub";

        resetChannel();
        setChannelConnected();
        doReturn(false).when(brokerService).isAuthenticationEnabled();
        doReturn(false).when(brokerService).isAuthorizationEnabled();
        // test SUBSCRIBE on topic and cursor creation success
        ByteBuf clientCommand = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandSuccess);

        PersistentTopic topicRef = (PersistentTopic) brokerService.getTopicReference(successTopicName);

        assertNotNull(topicRef);
        assertTrue(topicRef.getSubscriptions().containsKey(successSubName));
        assertTrue(topicRef.getPersistentSubscription(successSubName).getDispatcher().isConsumerConnected());

        // test SUBSCRIBE on topic creation success and cursor failure
        clientCommand = Commands.newSubscribe(successTopicName, failSubName, 2, 2, SubType.Exclusive,
                "test" /*
                        * consumer name
                        */);
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandError);

        // test SUBSCRIBE on topic creation failure
        clientCommand = Commands.newSubscribe(failTopicName, successSubName, 3, 3, SubType.Exclusive,
                "test" /*
                        * consumer name
                        */);
        channel.writeInbound(clientCommand);
        assertEquals(getResponse().getClass(), CommandError.class);

        // Server will not close the connection
        assertTrue(channel.isOpen());

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testSubscribeCommandWithAuthorizationPositive() throws Exception {
        AuthorizationManager authorizationManager = mock(AuthorizationManager.class);
        doReturn(true).when(authorizationManager).canConsume(Mockito.any(), Mockito.any());
        doReturn(authorizationManager).when(brokerService).getAuthorizationManager();
        doReturn(true).when(brokerService).isAuthenticationEnabled();
        doReturn(true).when(brokerService).isAuthorizationEnabled();
        resetChannel();
        setChannelConnected();

        // test SUBSCRIBE on topic and cursor creation success
        ByteBuf clientCommand = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(clientCommand);

        assertTrue(getResponse() instanceof CommandSuccess);

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testSubscribeCommandWithAuthorizationNegative() throws Exception {
        AuthorizationManager authorizationManager = mock(AuthorizationManager.class);
        doReturn(false).when(authorizationManager).canConsume(Mockito.any(), Mockito.any());
        doReturn(authorizationManager).when(brokerService).getAuthorizationManager();
        doReturn(true).when(brokerService).isAuthenticationEnabled();
        doReturn(true).when(brokerService).isAuthorizationEnabled();

        resetChannel();
        setChannelConnected();

        // test SUBSCRIBE on topic and cursor creation success
        ByteBuf clientCommand = Commands.newSubscribe(successTopicName, //
                successSubName, 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandError);

        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testAckCommand() throws Exception {
        resetChannel();
        setChannelConnected();

        ByteBuf clientCommand = Commands.newSubscribe(successTopicName, successSubName, 1 /* consumer id */,
                1 /*
                   * request id
                   */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandSuccess);

        PositionImpl pos = new PositionImpl(0, 0);

        clientCommand = Commands.newAck(1 /* consumer id */, pos.getLedgerId(), pos.getEntryId(), AckType.Individual,
                null);
        channel.writeInbound(clientCommand);

        // verify nothing is sent out on the wire after ack
        assertNull(channel.outboundMessages().peek());
        channel.finish();
    }

    @Test(timeOut = 30000)
    public void testFlowCommand() throws Exception {
        resetChannel();
        setChannelConnected();

        ByteBuf clientCommand = Commands.newSubscribe(successTopicName, successSubName, //
                1 /* consumer id */, 1 /* request id */, SubType.Exclusive, "test" /* consumer name */);
        channel.writeInbound(clientCommand);
        assertTrue(getResponse() instanceof CommandSuccess);

        clientCommand = Commands.newFlow(1 /* consumer id */, 1 /* message permits */);
        channel.writeInbound(clientCommand);

        // cursor is mocked
        // verify nothing is sent out on the wire after ack
        assertNull(channel.outboundMessages().peek());
        channel.finish();
    }

    private void resetChannel() throws Exception {
        int MaxMessageSize = 5 * 1024 * 1024;
        if (channel != null && channel.isActive()) {
            serverCnx.close();
            channel.close().get();
        }
        serverCnx = new ServerCnx(brokerService);
        channel = new EmbeddedChannel(new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4), serverCnx);
    }

    private void setChannelConnected() throws Exception {
        Field channelState = ServerCnx.class.getDeclaredField("state");
        channelState.setAccessible(true);
        channelState.set(serverCnx, State.Connected);
    }

    private Object getResponse() throws Exception {
        // Wait at most for 10s to get a response
        final long sleepTimeMs = 10;
        final long iterations = TimeUnit.SECONDS.toMillis(10) / sleepTimeMs;
        for (int i = 0; i < iterations; i++) {
            if (!channel.outboundMessages().isEmpty()) {
                Object outObject = channel.outboundMessages().remove();
                return clientChannelHelper.getCommand(outObject);
            } else {
                Thread.sleep(sleepTimeMs);
            }
        }

        throw new IOException("Failed to get response from socket within 10s");
    }

    private void setupMLAsyncCallbackMocks() {
        final ManagedLedger ledgerMock = mock(ManagedLedger.class);
        final ManagedCursor cursorMock = mock(ManagedCursor.class);

        doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();

        // call openLedgerComplete with ledgerMock on ML factory asyncOpen
        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                Thread.sleep(100);
                ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerComplete(ledgerMock, null);
                return null;
            }
        }).when(mlFactoryMock).asyncOpen(matches(".*success.*"), any(ManagedLedgerConfig.class),
                any(OpenLedgerCallback.class), anyObject());

        // call openLedgerFailed on ML factory asyncOpen
        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                Thread.sleep(100);
                new Thread(() -> {
                    ((OpenLedgerCallback) invocationOnMock.getArguments()[2])
                            .openLedgerFailed(new ManagedLedgerException("Managed ledger failure"), null);
                }).start();

                return null;
            }
        }).when(mlFactoryMock).asyncOpen(matches(".*fail.*"), any(ManagedLedgerConfig.class),
                any(OpenLedgerCallback.class), anyObject());

        // call addComplete on ledger asyncAddEntry
        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                ((AddEntryCallback) invocationOnMock.getArguments()[1]).addComplete(new PositionImpl(-1, -1),
                        invocationOnMock.getArguments()[2]);
                return null;
            }
        }).when(ledgerMock).asyncAddEntry(any(ByteBuf.class), any(AddEntryCallback.class), anyObject());

        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                ((OpenCursorCallback) invocationOnMock.getArguments()[1]).openCursorComplete(cursorMock, null);
                return null;
            }
        }).when(ledgerMock).asyncOpenCursor(matches(".*success.*"), any(OpenCursorCallback.class), anyObject());

        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                ((OpenCursorCallback) invocationOnMock.getArguments()[1])
                        .openCursorFailed(new ManagedLedgerException("Managed ledger failure"), null);
                return null;
            }
        }).when(ledgerMock).asyncOpenCursor(matches(".*fail.*"), any(OpenCursorCallback.class), anyObject());

        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                ((DeleteCursorCallback) invocationOnMock.getArguments()[1]).deleteCursorComplete(null);
                return null;
            }
        }).when(ledgerMock).asyncDeleteCursor(matches(".*success.*"), any(DeleteCursorCallback.class), anyObject());

        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                ((DeleteCursorCallback) invocationOnMock.getArguments()[1])
                        .deleteCursorFailed(new ManagedLedgerException("Managed ledger failure"), null);
                return null;
            }
        }).when(ledgerMock).asyncDeleteCursor(matches(".*fail.*"), any(DeleteCursorCallback.class), anyObject());

        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                ((CloseCallback) invocationOnMock.getArguments()[0]).closeComplete(null);
                return null;
            }
        }).when(cursorMock).asyncClose(any(CloseCallback.class), anyObject());

        doReturn(successSubName).when(cursorMock).getName();
    }

    private static final Logger log = LoggerFactory.getLogger(ServerCnxTest.class);
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.paulgray.lmsrest.discussion;

import java.util.Date;
import net.paulgray.lmsrest.course.Course;

/**
 *
 * @author pfgray
 */
public class DiscussionBoard {

    protected String id;
    protected String title;
    protected String description;
    protected Date lastEdited;
    protected Boolean available;
    protected Date endDate;

    protected Course course;

    public Boolean getAvailable() {
        return available;
    }

    public void setAvailable(Boolean available) {
        this.available = available;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Date getStartDate() {
        return lastEdited;
    }

    public void setStartDate(Date startDate) {
        this.lastEdited = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getLastEdited() {
        return lastEdited;
    }

    public void setLastEdited(Date lastEdited) {
        this.lastEdited = lastEdited;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

}

redpajama_set_name: RedPajamaGithub


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.269
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace C0DEC0RE.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("C0DEC0RE.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Enterprise Library Data Access Application Block.
        /// </summary>
        internal static string BlockName {
            get {
                return ResourceManager.GetString("BlockName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Object builder has no strategies..
        /// </summary>
        internal static string BuilderHasNoStrategies {
            get {
                return ResourceManager.GetString("BuilderHasNoStrategies", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to [{0}] {1} / {2} :: {3}.
        /// </summary>
        internal static string BuilderStrategyTraceBuildUp {
            get {
                return ResourceManager.GetString("BuilderStrategyTraceBuildUp", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to [{0}] {1} :: {2}.
        /// </summary>
        internal static string BuilderStrategyTraceTearDown {
            get {
                return ResourceManager.GetString("BuilderStrategyTraceTearDown", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to [BuilderBase] Finished BuildUp on {0} with ID {1}.
        /// </summary>
        internal static string BuildUpFinished {
            get {
                return ResourceManager.GetString("BuildUpFinished", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to [BuilderBase] Starting BuildUp on {0} with ID {1}.
        /// </summary>
        internal static string BuildUpStarting {
            get {
                return ResourceManager.GetString("BuildUpStarting", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Calling constructor({0}).
        /// </summary>
        internal static string CallingConstructor {
            get {
                return ResourceManager.GetString("CallingConstructor", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Calling method {0}({1}).
        /// </summary>
        internal static string CallingMethod {
            get {
                return ResourceManager.GetString("CallingMethod", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Calling IBuilderAware.OnBuiltUp().
        /// </summary>
        internal static string CallingOnBuiltUp {
            get {
                return ResourceManager.GetString("CallingOnBuiltUp", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Calling IBuilderAware.OnTearingDown().
        /// </summary>
        internal static string CallingOnTearingDown {
            get {
                return ResourceManager.GetString("CallingOnTearingDown", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Setting property {0}({1}).
        /// </summary>
        internal static string CallingProperty {
            get {
                return ResourceManager.GetString("CallingProperty", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Can not create an instance of type '{0}'..
        /// </summary>
        internal static string CannotCreateInstanceOfType {
            get {
                return ResourceManager.GetString("CannotCreateInstanceOfType", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to In class '{0}', cannot inject value on property '{1}' because it is read-only..
        /// </summary>
        internal static string CannotInjectReadOnlyProperty {
            get {
                return ResourceManager.GetString("CannotInjectReadOnlyProperty", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Commands Executed/sec is the rate at which database commands were executed..
        /// </summary>
        internal static string CommandExecutedCounterHelpResource {
            get {
                return ResourceManager.GetString("CommandExecutedCounterHelpResource", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Commands Failed/sec is tha rate at which database commands failed to execute..
        /// </summary>
        internal static string CommandFailedCounterHelpResource {
            get {
                return ResourceManager.GetString("CommandFailedCounterHelpResource", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to A configuration failure occurred while creating database '{0}'..
        /// </summary>
        internal static string ConfigurationFailureCreatingDatabase {
            get {
                return ResourceManager.GetString("ConfigurationFailureCreatingDatabase", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Connections Failed/sec is the rate at which database connections failed to open..
        /// </summary>
        internal static string ConnectionFailedCounterHelpResource {
            get {
                return ResourceManager.GetString("ConnectionFailedCounterHelpResource", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Connections Opened/sec is the rate at which database connections were opened..
        /// </summary>
        internal static string ConnectionOpenedCounterHelpResource {
            get {
                return ResourceManager.GetString("ConnectionOpenedCounterHelpResource", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Enterprise Library Data Performance Counter Instances.
        /// </summary>
        internal static string CounterCategoryHelpResourceName {
            get {
                return ResourceManager.GetString("CounterCategoryHelpResourceName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Could not locate dependency "{0}"..
        /// </summary>
        internal static string DependencyMissing {
            get {
                return ResourceManager.GetString("DependencyMissing", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The connection string used was "{0}"..
        /// </summary>
        internal static string ErrorConnectionFailedExtraInformation {
            get {
                return ResourceManager.GetString("ErrorConnectionFailedExtraInformation", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The error occurred using the "{0}" database instance while attempting to open the database connection..
        /// </summary>
        internal static string ErrorConnectionFailedMessage {
            get {
                return ResourceManager.GetString("ErrorConnectionFailedMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The exception that occured was: {0}.
        /// </summary>
        internal static string EventLogEntryExceptionTemplate {
            get {
                return ResourceManager.GetString("EventLogEntryExceptionTemplate", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to An error occurred in application {0} in the {1}..
        /// </summary>
        internal static string EventLogEntryHeaderTemplate {
            get {
                return ResourceManager.GetString("EventLogEntryHeaderTemplate", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type '{0}' does not derive from IDictionary..
        /// </summary>
        internal static string ExceptionArgumentShouldDeriveFromIDictionary {
            get {
                return ResourceManager.GetString("ExceptionArgumentShouldDeriveFromIDictionary", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type '{0}' does not derive from IList..
        /// </summary>
        internal static string ExceptionArgumentShouldDeriveFromIList {
            get {
                return ResourceManager.GetString("ExceptionArgumentShouldDeriveFromIList", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The [Assembler] attribute is not set in the configuration object type {0}..
        /// </summary>
        internal static string ExceptionAssemblerAttributeNotSet {
            get {
                return ResourceManager.GetString("ExceptionAssemblerAttributeNotSet", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The assembler configured for type {0} has type {2} which is not compatible with type {1}..
        /// </summary>
        internal static string ExceptionAssemblerTypeNotCompatible {
            get {
                return ResourceManager.GetString("ExceptionAssemblerTypeNotCompatible", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The base ConfigurationSourceElement configuration type can not be used as a concrete configuration element..
        /// </summary>
        internal static string ExceptionBaseConfigurationSourceElementIsInvalid {
            get {
                return ResourceManager.GetString("ExceptionBaseConfigurationSourceElementIsInvalid", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The AssemblyQualifiedTypeNameConverter can only convert values of type '{0}'..
        /// </summary>
        internal static string ExceptionCanNotConvertType {
            get {
                return ResourceManager.GetString("ExceptionCanNotConvertType", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The command must be a SqlCommand..
        /// </summary>
        internal static string ExceptionCommandNotSqlCommand {
            get {
                return ResourceManager.GetString("ExceptionCommandNotSqlCommand", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The section {0} could not be saved because the file does not exist..
        /// </summary>
        internal static string ExceptionConfigurationFileNotFound {
            get {
                return ResourceManager.GetString("ExceptionConfigurationFileNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The configuration file {0} could not be found..
        /// </summary>
        internal static string ExceptionConfigurationLoadFileNotFound {
            get {
                return ResourceManager.GetString("ExceptionConfigurationLoadFileNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The configuration object for type '{0}' with name '{1}' has type '{2}' which is does not implement ICustomProviderData..
        /// </summary>
        internal static string ExceptionConfigurationObjectIsNotCustomProviderData {
            get {
                return ResourceManager.GetString("ExceptionConfigurationObjectIsNotCustomProviderData", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The concrete type for polymorphic object named '{1}' in hierarchy {2} is not defined in configuration object {0}..
        /// </summary>
        internal static string ExceptionConfigurationObjectWithTypeDoesNotHaveTypeSet {
            get {
                return ResourceManager.GetString("ExceptionConfigurationObjectWithTypeDoesNotHaveTypeSet", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The configuration source section is not found in the application configuration file..
        /// </summary>
        internal static string ExceptionConfigurationSourceSectionNotFound {
            get {
                return ResourceManager.GetString("ExceptionConfigurationSourceSectionNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The [CustomFactory] attribute was not found on type {0} while processing request for id '{1}'..
        /// </summary>
        internal static string ExceptionCustomFactoryAttributeNotFound {
            get {
                return ResourceManager.GetString("ExceptionCustomFactoryAttributeNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The database type {0} for the name {1} does not have the required [DatabaseAssembler] attribute required to build the database object..
        /// </summary>
        internal static string ExceptionDatabaseTypeDoesNotHaveAssemblerAttribute {
            get {
                return ResourceManager.GetString("ExceptionDatabaseTypeDoesNotHaveAssemblerAttribute", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The database type {0} does not have the required ConfigurationElementType attribute..
        /// </summary>
        internal static string ExceptionDatabaseTypeDoesNotHaveRequiredConfigurationTypeAttribute {
            get {
                return ResourceManager.GetString("ExceptionDatabaseTypeDoesNotHaveRequiredConfigurationTypeAttribute", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to There was an error raising an event in .
        /// </summary>
        internal static string ExceptionEventRaisingFailed {
            get {
                return ResourceManager.GetString("ExceptionEventRaisingFailed", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The method with signature {0} is not a valid factory method to build type {1}..
        /// </summary>
        internal static string ExceptionFactoryMethodHasInvalidReturnType {
            get {
                return ResourceManager.GetString("ExceptionFactoryMethodHasInvalidReturnType", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type '{0}' cannot be resolved. Please verify the spelling is correct or that the full type name is provided..
        /// </summary>
        internal static string ExceptionInvalidType {
            get {
                return ResourceManager.GetString("ExceptionInvalidType", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The number of parameters does not match number of values for stored procedure..
        /// </summary>
        internal static string ExceptionMessageParameterMatchFailure {
            get {
                return ResourceManager.GetString("ExceptionMessageParameterMatchFailure", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to At least one command must be initialized.
        /// </summary>
        internal static string ExceptionMessageUpdateDataSetArgumentFailure {
            get {
                return ResourceManager.GetString("ExceptionMessageUpdateDataSetArgumentFailure", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Failed to update row .
        /// </summary>
        internal static string ExceptionMessageUpdateDataSetRowFailure {
            get {
                return ResourceManager.GetString("ExceptionMessageUpdateDataSetRowFailure", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The configuration could not be found for name '{0}' in factory {1}..
        /// </summary>
        internal static string ExceptionNamedConfigurationNotFound {
            get {
                return ResourceManager.GetString("ExceptionNamedConfigurationNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type {0} does not contain the ConfigurationElementTypeAttribute..
        /// </summary>
        internal static string ExceptionNoConfigurationElementAttribute {
            get {
                return ResourceManager.GetString("ExceptionNoConfigurationElementAttribute", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The requested database {0} is not defined in configuration..
        /// </summary>
        internal static string ExceptionNoDatabaseDefined {
            get {
                return ResourceManager.GetString("ExceptionNoDatabaseDefined", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type {0} does not have a public method annotated as an injection target as required by the use of injection..
        /// </summary>
        internal static string ExceptionNoMethodAnnotatedForInjectionFound {
            get {
                return ResourceManager.GetString("ExceptionNoMethodAnnotatedForInjectionFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The requested database {0} does not have provider name set in the connection string..
        /// </summary>
        internal static string ExceptionNoProviderDefinedForConnectionString {
            get {
                return ResourceManager.GetString("ExceptionNoProviderDefinedForConnectionString", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type {0} does not have a static method with a TargetConstructorAttribuite suitable to create an object of type {1}..
        /// </summary>
        internal static string ExceptionNoSuitableFactoryMethodFound {
            get {
                return ResourceManager.GetString("ExceptionNoSuitableFactoryMethodFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type attribute does not exist on the element {0}..
        /// </summary>
        internal static string ExceptionNoTypeAttribute {
            get {
                return ResourceManager.GetString("ExceptionNoTypeAttribute", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The value can not be null or an empty string..
        /// </summary>
        internal static string ExceptionNullOrEmptyString {
            get {
                return ResourceManager.GetString("ExceptionNullOrEmptyString", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Parameter discovery is not supported for connections using GenericDatabase. You must specify the parameters explicitly, or configure the connection to use a type deriving from Database that supports parameter discovery..
        /// </summary>
        internal static string ExceptionParameterDiscoveryNotSupportedOnGenericDatabase {
            get {
                return ResourceManager.GetString("ExceptionParameterDiscoveryNotSupportedOnGenericDatabase", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The parameter '{0}' for injection target '{1}' in type '{2}' is missing the injection interpretation attribute..
        /// </summary>
        internal static string ExceptionParameterNotAnnotatedForInjection {
            get {
                return ResourceManager.GetString("ExceptionParameterNotAnnotatedForInjection", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The performance counter '{0}' in category '{1}' is redefined in type {2} with a different configuration..
        /// </summary>
        internal static string ExceptionPerformanceCounterRedefined {
            get {
                return ResourceManager.GetString("ExceptionPerformanceCounterRedefined", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to e {2}..
        /// </summary>
        internal static string ExceptionPropertyNotFound {
            get {
                return ResourceManager.GetString("ExceptionPropertyNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type {0} does not contain the ConfigurationDataRetrievalAttribute required to resolve named references..
        /// </summary>
        internal static string ExceptionRetrievalAttributeNotFound {
            get {
                return ResourceManager.GetString("ExceptionRetrievalAttributeNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Could not retrieve parameter value. The property {0} does not exist for type {1}..
        /// </summary>
        internal static string ExceptionSourcePropertyDoesNotExist {
            get {
                return ResourceManager.GetString("ExceptionSourcePropertyDoesNotExist", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The value can not be null or string or empty..
        /// </summary>
        internal static string ExceptionStringNullOrEmpty {
            get {
                return ResourceManager.GetString("ExceptionStringNullOrEmpty", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The system configuration source is not defined in the configuration file..
        /// </summary>
        internal static string ExceptionSystemSourceNotDefined {
            get {
                return ResourceManager.GetString("ExceptionSystemSourceNotDefined", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The table name array used to map results to user-specified table names cannot be empty..
        /// </summary>
        internal static string ExceptionTableNameArrayEmpty {
            get {
                return ResourceManager.GetString("ExceptionTableNameArrayEmpty", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The type {0} from configuration could not be created..
        /// </summary>
        internal static string ExceptionTypeCouldNotBeCreated {
            get {
                return ResourceManager.GetString("ExceptionTypeCouldNotBeCreated", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Type {0} is not an implementation of ICustomFactory for CustomFactoryAttribute..
        /// </summary>
        internal static string ExceptionTypeNotCustomFactory {
            get {
                return ResourceManager.GetString("ExceptionTypeNotCustomFactory", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Type {0} is not an implementation of IDatabaseAssembler for DatabaseAssemblerAttribute..
        /// </summary>
        internal static string ExceptionTypeNotDatabaseAssembler {
            get {
                return ResourceManager.GetString("ExceptionTypeNotDatabaseAssembler", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Type {0} is not an implementation of IConfigurationNameMapper for ConfigurationNameMapperAttribute..
        /// </summary>
        internal static string ExceptionTypeNotNameMapper {
            get {
                return ResourceManager.GetString("ExceptionTypeNotNameMapper", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Type {0} is not an implementation of IConfigurationDataRetriever for ConfigurationDataRetrievalAttribute..
        /// </summary>
        internal static string ExceptionTypeNotRetriever {
            get {
                return ResourceManager.GetString("ExceptionTypeNotRetriever", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The expected type '{0}' was not provided..
        /// </summary>
        internal static string ExceptionUnexpectedType {
            get {
                return ResourceManager.GetString("ExceptionUnexpectedType", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to File Configuration Source.
        /// </summary>
        internal static string FileConfigurationSourceName {
            get {
                return ResourceManager.GetString("FileConfigurationSourceName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Too many dependency injection attributes defined on {0}.{1}..
        /// </summary>
        internal static string InvalidAttributeCombination {
            get {
                return ResourceManager.GetString("InvalidAttributeCombination", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Invalid enumeration value..
        /// </summary>
        internal static string InvalidEnumerationValue {
            get {
                return ResourceManager.GetString("InvalidEnumerationValue", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to An item with the given key is already present in the dictionary..
        /// </summary>
        internal static string KeyAlreadyPresentInDictionary {
            get {
                return ResourceManager.GetString("KeyAlreadyPresentInDictionary", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Missing policy to build {0} named '{1}'..
        /// </summary>
        internal static string MissingPolicyNamed {
            get {
                return ResourceManager.GetString("MissingPolicyNamed", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Missing policy to build unnamed {0}..
        /// </summary>
        internal static string MissingPolicyUnnamed {
            get {
                return ResourceManager.GetString("MissingPolicyUnnamed", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Could not find an appropriately matching constructor..
        /// </summary>
        internal static string NoAppropriateConstructor {
            get {
                return ResourceManager.GetString("NoAppropriateConstructor", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Password,pwd.
        /// </summary>
        internal static string Password {
            get {
                return ResourceManager.GetString("Password", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Registered as singleton.
        /// </summary>
        internal static string SingletonRegistered {
            get {
                return ResourceManager.GetString("SingletonRegistered", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Returning existing singleton.
        /// </summary>
        internal static string SingletonReturned {
            get {
                return ResourceManager.GetString("SingletonReturned", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to System Configuration Source.
        /// </summary>
        internal static string SystemConfigurationSourceName {
            get {
                return ResourceManager.GetString("SystemConfigurationSourceName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to [BuilderBase] Finished TearDown on {0}.
        /// </summary>
        internal static string TearDownFinished {
            get {
                return ResourceManager.GetString("TearDownFinished", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to [BuilderBase] Starting TearDown on {0}.
        /// </summary>
        internal static string TearDownStarting {
            get {
                return ResourceManager.GetString("TearDownStarting", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Mapped to {0} / {1}.
        /// </summary>
        internal static string TypeMapped {
            get {
                return ResourceManager.GetString("TypeMapped", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to While resolving dependencies for {2}, the provided type {1} is not compatible with {0}..
        /// </summary>
        internal static string TypeNotCompatible {
            get {
                return ResourceManager.GetString("TypeNotCompatible", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to User id,uid.
        /// </summary>
        internal static string UserName {
            get {
                return ResourceManager.GetString("UserName", resourceCulture);
            }
        }
    }
}


text:
(function() {
  var DocsParser, Promise, fs, logger, path;

  logger = require('../logger');

  Promise = require('bluebird');

  fs = Promise.promisifyAll(require('fs'));

  path = require('path');

  // Creates a link to the documentation on the corresponding GitHub Pages page.
  module.exports = DocsParser = (function() {
    class DocsParser {
      // Creates a new DocsParser
      // @param (options) [Object] An optional set of options
      // @option options encoding [String] Encoding for reading the file ['utf-8']
      // @option options docFile [String] Documentation entry point ['index.html']
      // @option options branch [String] The branch to use for the documentation ['master']
      constructor(options) {
        var base, base1, base2, ref, ref1;
        this.options = options;
        if (this.options == null) {
          this.options = {};
        }
        if ((base = this.options).encoding == null) {
          base.encoding = 'utf-8';
        }
        if ((base1 = this.options).branch == null) {
          base1.branch = (ref = (ref1 = this.options.git) != null ? ref1.branch : void 0) != null ? ref : 'master';
        }
        if ((base2 = this.options).docFile == null) {
          base2.docFile = 'index.html';
        }
      }

      // Check whether a documentation exists, it is in /docs and the repo uses github.
      // If all conditions are true, create a link to the documentation via GitHub Pages.
      // @param pkg [Object] package.json data
      // @returns [Promise<Object>] Documentation information [string]
      run(pkg) {
        var docDir, ref;
        logger.info("Creating documentation info");
        if (pkg.git == null) {
          logger.debug(" Not adding documentation due to missing git repo info");
          return Promise.resolve(null);
        }
        docDir = (ref = pkg.directories) != null ? ref.doc : void 0;
        if (!docDir) {
          logger.debug(" Not adding documentation due to missing directories/doc entry");
          return Promise.resolve(null);
        }
        if (docDir !== 'docs') {
          logger.debug(" Not adding documentation because it isn't in docs folder " + "and therefore incompatible with GitHub Pages");
          return Promise.resolve(null);
        }
        return Promise.resolve("https://" + pkg.git.user + ".github.io/" + pkg.git.repo + "/");
      }

    };

    // @property [String] The name of this component
    DocsParser.name = "DocsParser";

    return DocsParser;

  }).call(this);

}).call(this);


text:
import { Environment } from './environment';
import { SymbolTable } from '@glimmer/interfaces';
import { CompiledProgram } from './compiled/blocks';
import { Maybe, Option } from '@glimmer/util';
import { Ops } from '@glimmer/wire-format';

import {
  BaselineSyntax,
  Layout,
  InlineBlock,
  compileStatement
} from './scanner';

import {
  ComponentBuilder as IComponentBuilder,
  DynamicDefinition,
  StaticDefinition
} from './opcode-builder';

import {
  compileArgs,
  compileBaselineArgs
} from './syntax/functions';

import {
  FunctionExpression
} from './compiled/expressions/function';

import OpcodeBuilderDSL from './compiled/opcodes/builder';

import * as Component from './component/interfaces';

import * as WireFormat from '@glimmer/wire-format';

export interface CompilableLayout {
  compile(builder: Component.ComponentLayoutBuilder): void;
}

export function compileLayout(compilable: CompilableLayout, env: Environment): CompiledProgram {
  let builder = new ComponentLayoutBuilder(env);

  compilable.compile(builder);

  return builder.compile();
}

class ComponentLayoutBuilder implements Component.ComponentLayoutBuilder {
  private inner: WrappedBuilder | UnwrappedBuilder;

  constructor(public env: Environment) {}

  wrapLayout(layout: Layout) {
    this.inner = new WrappedBuilder(this.env, layout);
  }

  fromLayout(layout: Layout) {
    this.inner = new UnwrappedBuilder(this.env, layout);
  }

  compile(): CompiledProgram {
    return this.inner.compile();
  }

  get tag(): Component.ComponentTagBuilder {
    return this.inner.tag;
  }

  get attrs(): Component.ComponentAttrsBuilder {
    return this.inner.attrs;
  }
}

class WrappedBuilder {
  public tag = new ComponentTagBuilder();
  public attrs = new ComponentAttrsBuilder();

  constructor(public env: Environment, private layout: Layout) {}

  compile(): CompiledProgram {
    //========DYNAMIC
    //        PutValue(TagExpr)
    //        Test
    //        JumpUnless(BODY)
    //        OpenDynamicPrimitiveElement
    //        DidCreateElement
    //        ...attr statements...
    //        FlushElement
    // BODY:  Noop
    //        ...body statements...
    //        PutValue(TagExpr)
    //        Test
    //        JumpUnless(END)
    //        CloseElement
    // END:   Noop
    //        DidRenderLayout
    //        Exit
    //
    //========STATIC
    //        OpenPrimitiveElementOpcode
    //        DidCreateElement
    //        ...attr statements...
    //        FlushElement
    //        ...body statements...
    //        CloseElement
    //        DidRenderLayout
    //        Exit

    let { env, layout } = this;

    let symbolTable = layout.symbolTable;
    let b = builder(env, layout.symbolTable);

    b.startLabels();

    let dynamicTag = this.tag.getDynamic();
    let staticTag: Maybe<string>;

    if (dynamicTag) {
      b.putValue(dynamicTag);
      b.test('simple');
      b.jumpUnless('BODY');
      b.openDynamicPrimitiveElement();
      b.didCreateElement();
      this.attrs['buffer'].forEach(statement => compileStatement(statement, b));
      b.flushElement();
      b.label('BODY');
    } else if (staticTag = this.tag.getStatic()) {
      b.openPrimitiveElement(staticTag);
      b.didCreateElement();
      this.attrs['buffer'].forEach(statement => compileStatement(statement, b));
      b.flushElement();
    }

    b.preludeForLayout(layout);

    layout.statements.forEach(statement => compileStatement(statement, b));

    if (dynamicTag) {
      b.putValue(dynamicTag);
      b.test('simple');
      b.jumpUnless('END');
      b.closeElement();
      b.label('END');
    } else if (staticTag) {
      b.closeElement();
    }

    b.didRenderLayout();
    b.stopLabels();

    return new CompiledProgram(b.start, b.end, symbolTable.size);
  }
}

function isOpenElement(value: BaselineSyntax.AnyStatement): value is (BaselineSyntax.OpenPrimitiveElement | WireFormat.Statements.OpenElement) {
  let type = value[0];
  return type === Ops.OpenElement || type === Ops.OpenPrimitiveElement;
}

class UnwrappedBuilder {
  public attrs = new ComponentAttrsBuilder();

  constructor(public env: Environment, private layout: Layout) {}

  get tag(): Component.ComponentTagBuilder {
    throw new Error('BUG: Cannot call `tag` on an UnwrappedBuilder');
  }

  compile(): CompiledProgram {
    let { env, layout } = this;

    let b = builder(env, layout.symbolTable);

    b.startLabels();

    b.preludeForLayout(layout);

    let attrs = this.attrs['buffer'];
    let attrsInserted = false;

    for (let i = 0; i < layout.statements.length; i++) {
      let statement = layout.statements[i];
      if (!attrsInserted && isOpenElement(statement)) {
        b.openComponentElement(statement[1]);
        b.didCreateElement();
        b.shadowAttributes();
        attrs.forEach(statement => compileStatement(statement, b));
        attrsInserted = true;
      } else {
        compileStatement(statement, b);
      }
    }

    b.didRenderLayout();
    b.stopLabels();

    return new CompiledProgram(b.start, b.end, layout.symbolTable.size);
  }
}

class ComponentTagBuilder implements Component.ComponentTagBuilder {
  public isDynamic: Option<boolean> = null;
  public isStatic: Option<boolean> = null;
  public staticTagName: Option<string> = null;
  public dynamicTagName: Option<BaselineSyntax.AnyExpression> = null;

  getDynamic(): Maybe<BaselineSyntax.AnyExpression> {
    if (this.isDynamic) {
      return this.dynamicTagName;
    }
  }

  getStatic(): Maybe<string> {
    if (this.isStatic) {
      return this.staticTagName;
    }
  }

  static(tagName: string) {
    this.isStatic = true;
    this.staticTagName = tagName;
  }

  dynamic(tagName: FunctionExpression<string>) {
    this.isDynamic = true;
    this.dynamicTagName = [Ops.Function, tagName];
  }
}

class ComponentAttrsBuilder implements Component.ComponentAttrsBuilder {
  private buffer: WireFormat.Statements.Attribute[] = [];

  static(name: string, value: string) {
    this.buffer.push([Ops.StaticAttr, name, value, null]);
  }

  dynamic(name: string, value: FunctionExpression<string>) {
    this.buffer.push([Ops.DynamicAttr, name, [Ops.Function, value], null]);
  }
}

export class ComponentBuilder implements IComponentBuilder {
  private env: Environment;

  constructor(private builder: OpcodeBuilderDSL) {
    this.env = builder.env;
  }

  static(definition: StaticDefinition, args: BaselineSyntax.Args, _symbolTable: SymbolTable, shadow: InlineBlock) {
    this.builder.unit(b => {
      b.putComponentDefinition(definition);
      b.openComponent(compileBaselineArgs(args, b), shadow);
      b.closeComponent();
    });
  }

  dynamic(definitionArgs: BaselineSyntax.Args, definition: DynamicDefinition, args: BaselineSyntax.Args, _symbolTable: SymbolTable, shadow: InlineBlock) {
    this.builder.unit(b => {
      b.putArgs(compileArgs(definitionArgs[0], definitionArgs[1], b));
      b.putValue([Ops.Function, definition]);
      b.test('simple');
      b.enter('BEGIN', 'END');
      b.label('BEGIN');
      b.jumpUnless('END');
      b.putDynamicComponentDefinition();
      b.openComponent(compileBaselineArgs(args, b), shadow);
      b.closeComponent();
      b.label('END');
      b.exit();
    });
  }
}

export function builder<S extends SymbolTable>(env: Environment, symbolTable: S) {
  return new OpcodeBuilderDSL(symbolTable, env);
}


text:
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}

module Data.Yaml where

import qualified Data.Aeson    as A
import qualified Data.JSString as JSS
import qualified Data.Text     as T
import           GHCJS.Marshal
import           GHCJS.Types

decodeYaml :: A.FromJSON a => T.Text -> IO (Maybe a)
decodeYaml t = do
  let x = y_load (JSS.pack $ T.unpack $ t)
  y <- fromJSVal x
  case A.fromJSON <$> y of
    Just (A.Success v) -> return v
    _                  -> return Nothing

#ifdef __GHCJS__
foreign import javascript unsafe "jsyaml.load($1)" y_load :: JSString -> JSVal
#else
y_load = error "y_load only supported by ghcjs"
#endif


text:
strands_movebase
================

A repository for all the STRANDS-augmented movebase, including 3D obstacle avoidance, etc. Relies on scitos_2d_navigation if it is configured to only use laser scan input for navigation, https://github.com/strands-project/scitos_2d_navigation.

# Usage

  * `roslaunch strands_movebase movebase.launch map:=/path/to/map.yaml`
  * To be able to use this package you have to create a map with gmapping. This can be run with `rosrun gmapping slam_gmapping`, save the map with `rosrun map_server map_saver`.
  * Each launch file takes the argument `map` which is the path to the map saved with gmapping.
  * Optionally, provide a `no_go_map`, the path to a map annotated with no-go areas.
  * If you do not want to launch it with the 3d obstacle avoidance, provide the additional argument `with_camera:=false`.
  * Provide `camera=camera_namespace` if you have an OpenNI camera publishing on another namespace than the default `chest_xtion`.

If you run with the camera option, be sure that you have a depth camera publishing on the `camera_namespace` topic. The camera also needs a valid TF transform connecting it to `base_link`. For more details on the Strands solution, see https://github.com/strands-project/strands_movebase/calibrate_chest.


text:
import React, { Component } from 'react';
import List from './List';
import ListStore from './ListStore';

const listStore = new ListStore();
export default  () => (
    <List store={listStore}/>
)


text:
stacks/api.js

      1 new Api(this, "api", {

      2  routes: {

      3    "POST /graphql": {

      4      type: "graphql",

      5      function: "src/graphql.main"

      6    }

      7  }

      8})


text:
package com.miaotu.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

/**
 * Created by Jayden on 2015/5/25.
 */
public class DatingTourAdapter extends BaseAdapter{
    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        return null;
    }
}


text:
/**
 * @private
 * @hide
 */
const proto = Object.create(null, {
  constructor: {
    value: undefined,
    enumerable: false,
    writable: true,
  },
});

// eslint-disable-next-line @typescript-eslint/no-empty-function
function EmptyObject() {}
EmptyObject.prototype = proto;

/**
 * @private
 * @hide
 */
export default EmptyObject as unknown as { new (): Record<string, unknown> };


text:
import AppDispatcher from '../dispatchers/AppDispatcher';
import { EventEmitter } from 'events';
import AppConstants from '../constants/AppConstants';

const eventName = 'change';

export class AppStore extends EventEmitter {
  /**
 * Class to hold the AppStore cla.ss
 * @extends EventEmittert
 */
  constructor() {
    super();
    this.state = {
      sources: [],
      articles: []
    }
    this.dispatchToken = AppDispatcher.register(this.dispatcherCallback.bind(this));
    this.setSources = this.setSources.bind(this);
    this.setArticles = this.setArticles.bind(this);
  }
  emitChange(eventName) {
    this.emit(eventName);
  }

  setSources(source) {
    /**
   * The method that for handling sources change
   * @return {object} sets the state based on value
   */
    this.state.sources = source;
    this.emitChange(eventName);
  }
  getSource() {
    return this.state.sources;
  }

  setArticles(article) {
    console.log("set articles", this.state.articles)
    /**
   * The method that for handling articles change
   * @return {object} sets the state based on value
   */
    this.state.articles = article;
    this.emitChange(eventName);
  }
  getArticle() {
    console.log("get", this.state.articles)
    return this.state.articles;
  }
  addChangeListener(callback) {
    this.on(eventName, callback);
  }

  removeChangeListener(callback) {
    this.removeListener(eventName, callback);
  }

  dispatcherCallback(action) {
    switch (action.actionType) {
      case 'GET_ARTICLES':
        this.setArticles(action.data);
        break;
      case 'GET_SOURCES':
        this.setSources(action.data);
    }

    return true;
  }
}

const instantiatedStore = new AppStore()

export default new AppStore();