001/* 002 * Copyright 2012-2014 Donghwan Kim 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.github.flowersinthesand.portal; 017 018import io.github.flowersinthesand.wes.Action; 019 020import java.io.Serializable; 021 022/** 023 * {@code Sentence} is a series of predicates that a group of socket have to 024 * follow. It makes easy to write one-liner action and uses internally built 025 * actions implementing {@link Serializable} that is typically needed in cluster 026 * environments. Use of {@code Sentence} is preferred to that of action if the 027 * goal is the same. 028 * 029 * @author Donghwan Kim 030 */ 031public class Sentence { 032 033 private final Action<Action<Socket>> serverAction; 034 035 Sentence(Action<Action<Socket>> serverAction) { 036 this.serverAction = serverAction; 037 } 038 039 /** 040 * With respect to sockets, sends a given event without data. 041 */ 042 public Sentence send(String event) { 043 return send(event, null); 044 } 045 046 /** 047 * With respect to sockets, sends a given event with data. 048 */ 049 public Sentence send(String event, Object data) { 050 execute(new SendAction(event, data)); 051 return this; 052 } 053 054 /** 055 * With respect to sockets, closes the session. 056 */ 057 public Sentence close() { 058 execute(new CloseAction()); 059 return this; 060 } 061 062 private void execute(Action<Socket> action) { 063 serverAction.on(action); 064 } 065 066 static interface SerializableAction<T> extends Action<T>, Serializable {} 067 068 static class SendAction implements SerializableAction<Socket> { 069 private static final long serialVersionUID = 2178442626501531717L; 070 final String event; 071 final Object data; 072 073 SendAction(String event, Object data) { 074 this.event = event; 075 this.data = data; 076 } 077 078 @Override 079 public void on(Socket socket) { 080 socket.send(event, data); 081 } 082 } 083 084 static class CloseAction implements SerializableAction<Socket> { 085 private static final long serialVersionUID = 8154281469036373698L; 086 087 @Override 088 public void on(Socket socket) { 089 socket.close(); 090 } 091 } 092 093}