public AuthenticateUserOpImpl(Connection con, ExecutablePool pool) {
      super(MessageType.USER_CREDENTIAL_MESSAGE, 1);
      byte[] credentialBytes = null;
      // TODO this is not a valid way to create a member ID
      DistributedMember server =
          new InternalDistributedMember(
              con.getSocket().getInetAddress(), con.getSocket().getPort(), false);
      DistributedSystem sys = InternalDistributedSystem.getConnectedInstance();
      String authInitMethod =
          sys.getProperties().getProperty(DistributionConfig.SECURITY_CLIENT_AUTH_INIT_NAME);
      Properties tmpSecurityProperties = sys.getSecurityProperties();

      // LOG: following passes the DS API LogWriters into the security API
      Properties credentials =
          HandShake.getCredentials(
              authInitMethod,
              tmpSecurityProperties,
              server,
              false,
              (InternalLogWriter) sys.getLogWriter(),
              (InternalLogWriter) sys.getSecurityLogWriter());

      getMessage().setEarlyAck(Message.MESSAGE_HAS_SECURE_PART);
      HeapDataOutputStream heapdos = new HeapDataOutputStream(Version.CURRENT);
      try {
        DataSerializer.writeProperties(credentials, heapdos);
        credentialBytes = ((ConnectionImpl) con).getHandShake().encryptBytes(heapdos.toByteArray());
      } catch (Exception e) {
        throw new ServerOperationException(e);
      } finally {
        heapdos.close();
      }
      getMessage().addBytesPart(credentialBytes);
    }
 private void createCache(Properties props) throws Exception {
   DistributedSystem ds = getSystem(props);
   assertNotNull(ds);
   ds.disconnect();
   ds = getSystem(props);
   cache = CacheFactory.create(ds);
   assertNotNull(cache);
 }
 private void createClientCache(Properties props, ClientCacheFactory ccf) throws Exception {
   DistributedSystem ds = getSystem(props);
   assertNotNull(ds);
   ds.disconnect();
   ClientCache cc = ccf.create();
   setSystem(props, cc.getDistributedSystem());
   cache = (Cache) cc;
   assertNotNull(cache);
 }
 /**
  * create cache
  *
  * @return
  * @throws Exception
  */
 private Cache createCache() throws Exception {
   Properties props = new Properties();
   DistributedSystem ds = getSystem(props);
   ds.disconnect();
   ds = getSystem(props);
   Cache cache = null;
   cache = CacheFactory.create(ds);
   if (cache == null) {
     throw new Exception("CacheFactory.create() returned null ");
   }
   return cache;
 }
  public static byte[] initializeAndGetDSIdentity(DistributedSystem sys) {
    byte[] client_side_identity = null;
    if (sys == null) {
      // DistributedSystem is required now before handshaking -Kirk
      throw new IllegalStateException(
          LocalizedStrings
              .ClientProxyMembershipID_ATTEMPTING_TO_HANDSHAKE_WITH_CACHESERVER_BEFORE_CREATING_DISTRIBUTEDSYSTEM_AND_CACHE
              .toLocalizedString());
    }
    // if (system != sys)
    {
      // DS already exists... make sure it's for current DS connection
      systemMemberId = sys.getDistributedMember();
      try {
        HeapDataOutputStream hdos = new HeapDataOutputStream(256, Version.CURRENT);
        DataSerializer.writeObject(systemMemberId, hdos);
        client_side_identity = hdos.toByteArray();
      } catch (IOException ioe) {
        throw new InternalGemFireException(
            LocalizedStrings.ClientProxyMembershipID_UNABLE_TO_SERIALIZE_IDENTITY
                .toLocalizedString(),
            ioe);
      }

      system = sys;
    }
    return client_side_identity;
  }
 /**
  * Reads an object from a <code>DataInput</code>.
  *
  * @throws IOException If this serializer cannot read an object from <code>in</code>.
  * @throws ClassNotFoundException If the class for an object being restored cannot be found.
  * @see #toData
  */
 @Override
 public void fromData(DataInput in) throws IOException, ClassNotFoundException {
   // Note: does not call super.fromData what a HACK
   _operation = EnumListenerEvent.getEnumListenerEvent(in.readByte());
   int instantiatorCount = in.readInt(); // is byte suficient for this ?
   this.serializedInstantiators = new byte[instantiatorCount][];
   for (int i = 0; i < instantiatorCount; i++) {
     this.serializedInstantiators[i] = DataSerializer.readByteArray(in);
   }
   _membershipId = ClientProxyMembershipID.readCanonicalized(in);
   _eventIdentifier = (EventID) DataSerializer.readObject(in);
   DistributedSystem ds = InternalDistributedSystem.getAnyInstance();
   if (ds != null) {
     _logger = ds.getLogWriter().convertToLogWriterI18n();
   }
 }
 @Before
 public void setUp() throws Exception {
   Properties p = new Properties();
   p.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
   p.setProperty(DistributionConfig.OFF_HEAP_MEMORY_SIZE_NAME, "1m");
   this.ds = DistributedSystem.connect(p);
   this.cache = (GemFireCacheImpl) CacheFactory.create(this.ds);
   logger.info(addExpectedAbove);
   logger.info(addExpectedBelow);
 }
 private static CommandManager startGemFire() {
   Properties pr = new Properties();
   pr.put("jmx-manager", "true");
   pr.put("jmx-manager-start", "true");
   DistributedSystem ds = DistributedSystem.connect(pr);
   Cache cache = new CacheFactory().create();
   GemFireCacheImpl impl = (GemFireCacheImpl) cache;
   ManagementService service = ManagementService.getManagementService(cache);
   CommandManager manager = CommandManager.getExisting();
   return manager;
 }
    @Override
    protected void sendMessage(Connection cnx) throws Exception {
      HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);
      byte[] secureBytes = null;
      hdos.writeLong(cnx.getConnectionID());
      if (this.securityProperties != null) {
        byte[] credentialBytes = null;
        // TODO this is not a valid way to create a member ID
        DistributedMember server =
            new InternalDistributedMember(
                cnx.getSocket().getInetAddress(), cnx.getSocket().getPort(), false);
        DistributedSystem sys = InternalDistributedSystem.getConnectedInstance();
        String authInitMethod =
            sys.getProperties().getProperty(DistributionConfig.SECURITY_CLIENT_AUTH_INIT_NAME);

        Properties credentials =
            HandShake.getCredentials(
                authInitMethod,
                this.securityProperties,
                server,
                false,
                (InternalLogWriter) sys.getLogWriter(),
                (InternalLogWriter) sys.getSecurityLogWriter());
        HeapDataOutputStream heapdos = new HeapDataOutputStream(Version.CURRENT);
        try {
          DataSerializer.writeProperties(credentials, heapdos);
          credentialBytes =
              ((ConnectionImpl) cnx).getHandShake().encryptBytes(heapdos.toByteArray());
        } finally {
          heapdos.close();
        }
        getMessage().addBytesPart(credentialBytes);
      }
      try {
        secureBytes = ((ConnectionImpl) cnx).getHandShake().encryptBytes(hdos.toByteArray());
      } finally {
        hdos.close();
      }
      getMessage().setSecurePart(secureBytes);
      getMessage().send(false);
    }
 /**
  * Creates a new cache that uses the configured distributed system. If a connected distributed
  * system already exists it will be used if it is compatible with the properties on this factory.
  * Otherwise a a distributed system will be created with the configured properties. If a cache
  * already exists it will be returned.
  *
  * <p>If the cache does need to be created it will also be initialized from cache.xml if it
  * exists.
  *
  * @return the created or already existing singleton cache
  * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file.
  * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing
  *     the cache.
  * @throws CacheWriterException If a <code>CacheWriterException</code> is thrown while
  *     initializing the cache.
  * @throws GatewayException If a <code>GatewayException</code> is thrown while initializing the
  *     cache.
  * @throws RegionExistsException If the declarative caching XML file describes a region that
  *     already exists (including the root region).
  * @throws ManagementException If the jmx manager can not be initialized.
  * @since 6.5
  */
 public Cache create()
     throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException {
   synchronized (CacheFactory.class) {
     DistributedSystem ds = null;
     if (this.dsProps.isEmpty()) {
       // any ds will do
       ds = InternalDistributedSystem.getConnectedInstance();
     }
     if (ds == null) {
       ds = DistributedSystem.connect(this.dsProps);
     }
     return create(ds, true, cacheConfig);
   }
 }
 public static void closeCache() {
   try {
     if (cache != null && !cache.isClosed()) {
       cache.close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   try {
     if (ds != null) ds.disconnect();
   } catch (Exception e) {
     getLogWriter().fine("Error in disconnecting from Distributed System");
   }
 }
  /** Creates and starts the server instance */
  private int createServer() {
    CacheServer server = null;
    try {
      Properties p = new Properties();
      // make it a loner
      p.put("mcast-port", "0");
      p.put("locators", "");

      this.system = DistributedSystem.connect(p);
      this.cache = CacheFactory.create(system);
      server = this.cache.addCacheServer();
      int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
      server.setMaximumTimeBetweenPings(TIME_BETWEEN_PINGS);
      server.setMaxThreads(getMaxThreads());
      server.setPort(port);
      server.start();
    } catch (Exception e) {
      e.printStackTrace();
      fail("Failed to create server");
    }
    return server.getPort();
  }
  public static void main(String[] args) throws Exception {

    Properties props = new Properties();
    props.setProperty("name", "CqServer");
    props.setProperty("log-level", "warning");

    System.out.println("\nConnecting to the distributed system and creating the cache.");
    DistributedSystem ds = DistributedSystem.connect(props);
    Cache cache = CacheFactory.create(ds);

    // Create region.
    AttributesFactory factory = new AttributesFactory();
    factory.setDataPolicy(DataPolicy.REPLICATE);
    factory.setScope(Scope.DISTRIBUTED_ACK);
    Region testRegion = cache.createRegion("test-cq", factory.create());
    System.out.println("Test region, " + testRegion.getFullPath() + ", created in cache.");

    // Start Cache Server.
    CacheServer server = cache.addCacheServer();
    server.setPort(40404);
    server.setNotifyBySubscription(true);
    server.start();

    System.out.println("Waiting for signal");
    // wait for signal
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    bufferedReader.readLine();

    System.out.println("Received signal");

    testRegion.put("one", 1);
    testRegion.put("two", 2);
    testRegion.put("three", 3);

    System.out.println("Waiting for shutdown");
    bufferedReader.readLine();
  }
  public void testSimpleOutOfOffHeapMemoryMemberDisconnects() {
    final DistributedSystem system = getSystem();
    final Cache cache = getCache();
    final DistributionManager dm =
        (DistributionManager) ((InternalDistributedSystem) system).getDistributionManager();

    Region<Object, Object> region =
        cache.createRegionFactory(getRegionShortcut()).setOffHeap(true).create(getRegionName());
    OutOfOffHeapMemoryException ooohme;
    try {
      Object value = new byte[1024];
      for (int i = 0; true; i++) {
        region.put("key-" + i, value);
      }
    } catch (OutOfOffHeapMemoryException e) {
      ooohme = e;
    }
    assertNotNull(ooohme);

    with()
        .pollInterval(100, TimeUnit.MILLISECONDS)
        .await()
        .atMost(10, TimeUnit.SECONDS)
        .until(() -> cache.isClosed() && !system.isConnected() && dm.isClosed());

    // wait for cache instance to be nulled out
    with()
        .pollInterval(100, TimeUnit.MILLISECONDS)
        .await()
        .atMost(10, TimeUnit.SECONDS)
        .until(
            () ->
                GemFireCacheImpl.getInstance() == null
                    && InternalDistributedSystem.getAnyInstance() == null);

    assertNull(GemFireCacheImpl.getInstance());

    // verify system was closed out due to OutOfOffHeapMemoryException
    assertFalse(system.isConnected());
    InternalDistributedSystem ids = (InternalDistributedSystem) system;
    try {
      ids.getDistributionManager();
      fail(
          "InternalDistributedSystem.getDistributionManager() should throw DistributedSystemDisconnectedException");
    } catch (DistributedSystemDisconnectedException expected) {
      assertRootCause(expected, OutOfOffHeapMemoryException.class);
    }

    // verify dm was closed out due to OutOfOffHeapMemoryException
    assertTrue(dm.isClosed());
    try {
      dm.throwIfDistributionStopped();
      fail(
          "DistributionManager.throwIfDistributionStopped() should throw DistributedSystemDisconnectedException");
    } catch (DistributedSystemDisconnectedException expected) {
      assertRootCause(expected, OutOfOffHeapMemoryException.class);
    }

    // verify cache was closed out due to OutOfOffHeapMemoryException
    assertTrue(cache.isClosed());
    try {
      cache.getCancelCriterion().checkCancelInProgress(null);
      fail(
          "GemFireCacheImpl.getCancelCriterion().checkCancelInProgress should throw DistributedSystemDisconnectedException");
    } catch (DistributedSystemDisconnectedException expected) {
      assertRootCause(expected, OutOfOffHeapMemoryException.class);
    }
  }