List of usage examples for java.nio.channels SocketChannel isOpen
public final boolean isOpen()
From source file:morphy.service.SocketConnectionService.java
private synchronized void onNewInput(SocketChannel channel) { if (!channel.isOpen()) return;// ww w. j a va 2 s .c om try { if (channel.isConnected()) { SocketChannelUserSession session = socketToSession.get(channel.socket()); if (session == null) { if (LOG.isErrorEnabled()) { LOG.error("Received a read on a socket not being managed. This is likely a bug."); } disposeSocketChannel(channel); } else { synchronized (session.getInputBuffer()) { String message = readMessage(channel); if (message != null && message.equals(MSG_TIMESEAL_OK)) { // Don't need to do anything. This was just the timeseal init string. } else if (message == null && channel.isOpen()) { session.disconnect(); } else if (message == null) { session.disconnect(); } else if (message.length() > 0) { /*if (!socketInputForCmd.containsKey(channel.socket())) { socketInputForCmd.put(channel.socket(), new StringBuilder()); } int c = (int)message.charAt(0); if (c != 10 && c != 13) { socketInputForCmd.get(channel.socket()).append(message); //LOG.info(c); } else { message = socketInputForCmd.get(channel.socket()).toString(); socketInputForCmd.put(channel.socket(), new StringBuilder()); LOG.info("Read: " + session.getUser().getUserName() + " \"" + message + "\""); } LOG.info(c + " " + socketInputForCmd.get(channel.socket()));*/ boolean expandAliases = true; if (message.startsWith("$$")) { message = message.substring(2); expandAliases = false; } else { session.touchLastReceivedTime(); session.getUser().getUserVars().getVariables().put("busy", ""); expandAliases = true; } session.getInputBuffer().append(message); if (session.getInputBuffer().indexOf("\n") != -1) { LOG.info("Read: " + session.getUser().getUserName() + " \"" + message + "\""); } int carrageReturnIndex = -1; while ((carrageReturnIndex = session.getInputBuffer().indexOf("\n")) != -1) { String command = session.getInputBuffer().substring(0, carrageReturnIndex).trim(); session.getInputBuffer().delete(0, carrageReturnIndex + 1); if (session .getCurrentState() == SocketChannelUserSession.UserSessionState.LOGIN_NEED_PASSWORD) { handlePasswordPromptText(session, command); } else if (command.equals("") || command.equals("\n") || command.equals("\n\r")) { session.send(""); } else if (session .getCurrentState() == SocketChannelUserSession.UserSessionState.LOGIN_NEED_USERNAME) { handleLoginPromptText(session, command); } else { if (expandAliases) { CommandService.getInstance().processCommandAndCheckAliases(command, session); } else { CommandService.getInstance().processCommand(command, session); } } } } } } } } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error("Error reading socket channel or processing command ", t); } } }
From source file:hornet.framework.clamav.service.ClamAVCheckService.java
/** * Ouverture de la socket./*from w w w . ja v a 2 s. c om*/ * * @return la socket * @throws ClamAVException * the clam av exception */ private SocketChannel openSocket() throws ClamAVException { SocketChannel channel = null; try { // Rcuperation de la socket depuis le pool channel = this.socketPool.borrowObject(); if (!channel.isOpen()) { channel = SocketChannel.open(); } if (!channel.isConnected()) { channel.configureBlocking(true); channel.connect(new InetSocketAddress(this.clamAVServer, this.clamAVPort)); } } catch (final Exception e) { ClamAVCheckService.LOGGER.error("Unable to borrow socket from pool", e); throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e); } return channel; }
From source file:com.buaa.cfs.net.SocketIOWithTimeout.java
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout. * * @param channel - this should be a {@link SelectableChannel} * @param endpoint//from w ww . java 2 s .co m * * @throws IOException * @see SocketChannel#connect(SocketAddress) */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (Time.now() + timeout) : 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) { throw new SocketTimeoutException( timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) { } throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
From source file:de.kapsi.net.daap.nio.DaapServerNIO.java
/** * Accept an icoming connection//from w ww.ja v a 2s. c o m * * @throws IOException */ private void processAccept(SelectionKey sk) throws IOException { if (!sk.isValid()) return; ServerSocketChannel ssc = (ServerSocketChannel) sk.channel(); SocketChannel channel = ssc.accept(); if (channel == null) return; if (channel.isOpen() && accept(channel.socket().getInetAddress())) { channel.configureBlocking(false); DaapConnection connection = new DaapConnectionNIO(this, channel); SelectionKey key = channel.register(selector, SelectionKey.OP_READ, connection); } else { try { channel.close(); } catch (IOException err) { LOG.error("SocketChannel.close()", err); } } }
From source file:eu.stratosphere.nephele.net.SocketIOWithTimeout.java
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout. * // w w w . jav a2 s .co m * @see SocketChannel#connect(SocketAddress) * @param channel * - this should be a {@link SelectableChannel} * @param endpoint * @throws IOException */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) { throw new SocketTimeoutException( timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) { } throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
From source file:morphy.service.SocketConnectionService.java
protected synchronized String readMessage(SocketChannel channel) { try {//from w w w . ja va2s . co m ByteBuffer buffer = ByteBuffer.allocate(maxCommunicationSizeBytes); int charsRead = -1; try { charsRead = channel.read(buffer); } catch (IOException cce) { if (channel.isOpen()) { channel.close(); if (LOG.isInfoEnabled()) { LOG.info("Closed channel " + channel); } } } if (charsRead == -1) { return null; } else if (charsRead > 0) { buffer.flip(); Charset charset = Charset.forName(Morphy.getInstance().getMorphyPreferences() .getString(PreferenceKeys.SocketConnectionServiceCharEncoding)); SocketChannelUserSession socketChannelUserSession = socketToSession.get(channel.socket()); byte[] bytes = buffer.array(); buffer.position(0); System.out.println("IN: " + new String(bytes).trim()); if (looksLikeTimesealInit(bytes)) { if (socketChannelUserSession.usingTimeseal == false) { // First time? socketChannelUserSession.usingTimeseal = true; return MSG_TIMESEAL_OK; } } if (socketChannelUserSession.usingTimeseal) { /* * Clients may pass multiple Timeseal-encoded messages at once. * We need to parse each separated message to Timeseal decoder as necessary. */ byte[] bytesToDecode = Arrays.copyOfRange(bytes, 0, charsRead - 1 /* \n or 10 */); byte[][] splitBytes = TimesealCoder.splitBytes(bytesToDecode, (byte) 10); buffer = ByteBuffer.allocate(bytesToDecode.length); buffer.position(0); for (int i = 0; i < splitBytes.length; i++) { byte[] splitBytesToDecode = splitBytes[i]; TimesealParseResult parseResult = timesealCoder.decode(splitBytesToDecode); if (parseResult != null) { System.out.println(parseResult.getTimestamp()); parseResult.setMessage(parseResult.getMessage() + "\n"); System.out.println(parseResult.getMessage()); buffer.put(parseResult.getMessage().getBytes(charset)); } } //buffer.position(0); buffer.flip(); } CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(buffer); String message = charBuffer.toString(); return message; //System.out.println(message); //return ""; } else { return ""; } } catch (Throwable t) { if (LOG.isErrorEnabled()) LOG.error("Error reading SocketChannel " + channel.socket().getLocalAddress(), t); return null; } }
From source file:org.openhab.binding.tcp.AbstractSocketChannelBinding.java
/** * {@inheritDoc}/*from w w w.ja v a2s .co m*/ */ protected void internalReceiveCommand(String itemName, Command command) { P provider = findFirstMatchingBindingProvider(itemName); if (provider == null) { logger.warn("cannot find matching binding provider [itemName={}, command={}]", itemName, command); return; } if (command != null) { List<Command> commands = provider.getQualifiedCommands(itemName, command); for (Command someCommand : commands) { Channel theChannel = null; if (useAddressMask && (((P) provider).getHost(itemName, someCommand).equals("*") || ((P) provider).getPortAsString(itemName, someCommand).equals("*"))) { theChannel = channels.get(itemName, someCommand, ((P) provider).getDirection(itemName, someCommand), ((P) provider).getHost(itemName, someCommand), ((P) provider).getPortAsString(itemName, someCommand)); } else { theChannel = channels.get(itemName, someCommand, ((P) provider).getDirection(itemName, someCommand), new InetSocketAddress(provider.getHost(itemName, someCommand), provider.getPort(itemName, someCommand))); } SocketChannel theSocketChannel = null; if (theChannel != null) { theSocketChannel = theChannel.channel; } if (theSocketChannel != null) { boolean result = internalReceiveChanneledCommand(itemName, someCommand, theChannel, command.toString()); if (!theSocketChannel.isConnected() && !(useAddressMask && (((P) provider).getHost(itemName, someCommand).equals("*") || ((P) provider).getPortAsString(itemName, someCommand).equals("*")))) { logger.warn( "The channel for {} has a connection problem. Data will queued to the new channel when it is successfully set up.", theChannel.remote); if (!theSocketChannel.isConnectionPending() || !theSocketChannel.isOpen()) { Scheduler scheduler = null; try { scheduler = StdSchedulerFactory.getDefaultScheduler(); } catch (SchedulerException e1) { logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage()); } JobDataMap map = new JobDataMap(); map.put("Channel", theChannel); map.put("Binding", this); JobDetail job = newJob(ReconnectJob.class) .withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()) .usingJobData(map).build(); Trigger trigger = newTrigger() .withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()) .startNow().build(); try { if (job != null && trigger != null) { if (!theChannel.isReconnecting) { theChannel.isReconnecting = true; scheduler.scheduleJob(job, trigger); } } } catch (SchedulerException e) { logger.error( "An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage()); } } } if (result) { List<Class<? extends State>> stateTypeList = provider.getAcceptedDataTypes(itemName, someCommand); State newState = createStateFromString(stateTypeList, command.toString()); if (newState != null) { eventPublisher.postUpdate(itemName, newState); } } } else { logger.error("there is no channel that services [itemName={}, command={}]", itemName, command); } } } }