Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /* ************************************************************************
  #
  #  DivConq
  #
  #  http://divconq.com/
  #
  #  Copyright:
  #    Copyright 2014 eTimeline, LLC. All rights reserved.
  #
 #  License:
 #    See the license.txt file in the project's top-level directory for details.
 #
 #  Authors:
 #    * Andy White
 #
 ************************************************************************ */
 package divconq.api;
 
 
 
 
 public class HyperSession extends ApiSession {
 	protected ClientInfo info = null;
 	protected ApiSslContextFactory sslfac = null;
     
 	protected ClientHandler handler = null;
 
 	protected HashMap<StringUploadPutHandleruploadstreams = new HashMap<>();
 	protected HashMap<StringDownloadHandlerdownloadstreams = new HashMap<>();
 	
 	public ClientInfo getInfo() {
 		return this.;
 	}
 	
 		return this.;
 	}
 
     public void init(XElement config) {
     	// run only once even if call multiple times
 		if (this. != null)
 			return;
 
 		if (config == null)
 			return;
         
         this. = new ClientInfo();
         this..loadConfig(config);
         this.. = .;
         
         this. = new ApiSslContextFactory();
         this..init(config);
         
         this. = UserContext.allocateGuest();
 	}
 	
 	public OperationResult connect() {
 		
 		// only ever one connection for now
		if (this. != null)
			return or;
		this. = new ClientHandler(thisthis.);
			this.allocateWsChannel(this.or);
		else
        
        return or;
    }
	public Channel allocateHttpChannel(final ChannelHandler handlerOperationResult or) {
		final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();
        Bootstrap b = new Bootstrap();
        
        b.group(..getEventLoopGroup())
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel chthrows Exception {
                 ChannelPipeline pipeline = ch.pipeline();
                 
                 if (HyperSession.this..isSecurel()) {
                	 SslHandler sh = new SslHandler(HyperSession.this..getClientEngine());
                	 sslready.set(sh.handshakeFuture());
                	 pipeline.addLast("ssl"sh);
                 }
	    	        
    	        pipeline.addLast("decoder"new HttpResponseDecoder());
    	        pipeline.addLast("encoder"new HttpRequestEncoder());
    	        
    	        // TODO maybe
    	        //pipeline.addLast("deflater", new HttpContentCompressor());
                 
                 pipeline.addLast("handler"handler);
             }
         });
        or.info("Web Client connecting");
        
        try {
        	// must wait here to make sure we don't release connectLock too soon
        	// we want channel init (above) to complete before we try connect again
        	ChannelFuture f = b.connect(this..getAddress()).sync();
        	
        	if (!f.isSuccess()) {
            	or.error(1, "Web Client unable to successfully connect: " + f.cause());
        	}
        	
        	// it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent
        	// that lets wait for the handshake to be done for sure
        	if (sslready.get() != null) {
        		Future<Channelsf = sslready.get().sync();
            	
            	if (!sf.isSuccess()) {
                	or.error(1, "Web Client unable to securely connect: " + sf.cause());
            	}
        	}
        	
        	if (handler instanceof ClientHandler
        		((ClientHandler)handler).waitConnect();
        	
        	return f.channel();
        }
        catch (InterruptedException x) {
        	or.error(1, "Web Client interrupted while connecting: " + x);
        }
        catch (Exception x) {
        	or.error(1, "Web Client unable to connect: " + x);
        }
        
        return null;
	}
	public Channel allocateWsChannel(final ChannelHandler handlerOperationResult or) {
		final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();
        Bootstrap b = new Bootstrap();
        
        b.group(..getEventLoopGroup())
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel chthrows Exception {
     	        HttpHeaders customHeaders = new DefaultHttpHeaders();
    	        customHeaders.add("x-DivConq-Mode"..getResources().getMode());
    	        
                 WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(HyperSession.this..getUri(), .nullfalsecustomHeaders);
                 
                 ChannelPipeline pipeline = ch.pipeline();
                 
                 if (HyperSession.this..isSecurel()) {
                	 SslHandler sh = new SslHandler(HyperSession.this..getClientEngine());
                	 sslready.set(sh.handshakeFuture());
                	 pipeline.addLast("ssl"sh);
                 }
	    	        
                 pipeline.addLast("http-codec"new HttpClientCodec());
                 pipeline.addLast("aggregator"new HttpObjectAggregator(65536));
                 pipeline.addLast("ws-handler"new WebSocketClientProtocolHandler(handshaker));
                 
                 pipeline.addLast("handler"handler);
                 
                 /*
                 pipeline.addLast("handler", new SimpleChannelInboundHandler<Object>() {
					@Override
					protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
						System.out.println("read: " + msg);
					}
                	 
				    @Override
				    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
				    	super.userEventTriggered(ctx, evt);
				    	
				    	Logger.debug("ue: " + evt);
				    }
                 });
                 */
             }
         });
        or.info("Web Client connecting");
        
        try {
        	// must wait here to make sure we don't release connectLock too soon
        	// we want channel init (above) to complete before we try connect again
        	ChannelFuture f = b.connect(this..getAddress()).sync();
        	
        	if (!f.isSuccess()) {
            	or.error(1, "Web Client unable to successfully connect: " + f.cause());
        	}
        	
        	// it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent
        	// that lets wait for the handshake to be done for sure
        	if (sslready.get() != null) {
        		Future<Channelsf = sslready.get().sync();
            	
            	if (!sf.isSuccess()) {
                	or.error(1, "Web Client unable to securely connect: " + sf.cause());
            	}
        	}
        	
        	if (handler instanceof ClientHandler
        		((ClientHandler)handler).waitConnect();
        	
        	return f.channel();
        }
        catch (InterruptedException x) {
        	or.error(1, "Web Client interrupted while connecting: " + x);
        }
        catch (Exception x) {
        	or.error(1, "Web Client unable to connect: " + x);
        }
        
        return null;
	}
	public void stopped() {
		if (this. != null)
			this..close();
	}
	public void receiveMessage(final Message msg) {
		// throw this work into another thread so socket reader can go back to work		
			public void run(TaskRun task) {
				String to = msg.getFieldAsString("Service");
				if ("Replies".equals(to)) 
				else
			}
		});
	}
	public void sendForgetMessage(Message msg) {
    	msg.setField("RespondTag""SendForget");
		if (this.connect().hasErrors()) 
			return;
    	this..send(msg);
	}
	public void sendMessage(final Message msgfinal ServiceResult callback) {
		OperationResult or = this.connect();
		callback.copyMessages(or);;
		if (callback.hasErrors()) {
			callback.complete();
			return;
		}
    	
		this..registerForReplySerial(msgcallback);
    	this..send(msg);
    }
	public void abortStream(String channelid) {
		UploadPutHandler uphandler = this..get(channelid);
		if (uphandler != null)
			uphandler.closeDest();
		DownloadHandler dhandler = this..get(channelid);
		if (dhandler != null)
			dhandler.closeSource();
	}
	public void sendStream(ScatteringByteChannel inlong sizelong offsetString chanidOperationCallback callback) {
		// we also have UploadMultipartPostHandler...much slower
		UploadPutHandler uphandler = new UploadPutHandler();
		this..put(chaniduphandler);
		uphandler.start(thisinchanidthis..getCookies(), sizeoffsetcallback);
	}
	public void receiveStream(WritableByteChannel outlong sizelong offsetString chanidOperationCallback callback) {
		DownloadHandler dhandler = new DownloadHandler();
		this..put(chaniddhandler);
		dhandler.start(thisoutchanidthis..getCookies(), sizeoffsetcallback);
	}
	public void freeDataChannel(String channelidOperationCallback callback) {
		this..remove(channelid);
		this..remove(channelid);
		super.freeDataChannel(channelidcallback);
	}
New to GrepCode? Check out our FAQ X