001: /*
002: * Copyright 1999-2004 The Apache Software Foundation
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: */
016:
017: package org.apache.tomcat.util.net;
018:
019: import java.io.IOException;
020: import java.io.InputStream;
021: import java.net.Socket;
022:
023: /**
024: *
025: */
026: public class TcpConnection { // implements Endpoint {
027: /**
028: * Maxium number of times to clear the socket input buffer.
029: */
030: static int MAX_SHUTDOWN_TRIES = 20;
031:
032: public TcpConnection() {
033: }
034:
035: // -------------------- Properties --------------------
036:
037: PoolTcpEndpoint endpoint;
038: Socket socket;
039:
040: public static void setMaxShutdownTries(int mst) {
041: MAX_SHUTDOWN_TRIES = mst;
042: }
043:
044: public void setEndpoint(PoolTcpEndpoint endpoint) {
045: this .endpoint = endpoint;
046: }
047:
048: public PoolTcpEndpoint getEndpoint() {
049: return endpoint;
050: }
051:
052: public void setSocket(Socket socket) {
053: this .socket = socket;
054: }
055:
056: public Socket getSocket() {
057: return socket;
058: }
059:
060: public void recycle() {
061: endpoint = null;
062: socket = null;
063: }
064:
065: // Another frequent repetition
066: public static int readLine(InputStream in, byte[] b, int off,
067: int len) throws IOException {
068: if (len <= 0) {
069: return 0;
070: }
071: int count = 0, c;
072:
073: while ((c = in.read()) != -1) {
074: b[off++] = (byte) c;
075: count++;
076: if (c == '\n' || count == len) {
077: break;
078: }
079: }
080: return count > 0 ? count : -1;
081: }
082:
083: // Usefull stuff - avoid having it replicated everywhere
084: public static void shutdownInput(Socket socket) throws IOException {
085: try {
086: InputStream is = socket.getInputStream();
087: int available = is.available();
088: int count = 0;
089:
090: // XXX on JDK 1.3 just socket.shutdownInput () which
091: // was added just to deal with such issues.
092:
093: // skip any unread (bogus) bytes
094: while (available > 0 && count++ < MAX_SHUTDOWN_TRIES) {
095: is.skip(available);
096: available = is.available();
097: }
098: } catch (NullPointerException npe) {
099: // do nothing - we are just cleaning up, this is
100: // a workaround for Netscape \n\r in POST - it is supposed
101: // to be ignored
102: }
103: }
104: }
|