Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

In this page you can find the example usage for java.net Socket getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:com.citruspay.enquiry.gateway.AXISGatewayConnector.java

public String connect(String vpcHost, String queryParameters, EnquiryRequest request) {

    boolean useSSL = false;
    String fileName = "";

    // determine if SSL encryption is being used
    if (vpcHost.substring(0, 8).equalsIgnoreCase("HTTPS://")) {
        useSSL = true;/*from w  w  w.  j a va  2 s  .  c om*/
        // remove 'HTTPS://' from host URL
        vpcHost = vpcHost.substring(8);
        // get the filename from the last section of vpc_URL
        fileName = vpcHost.substring(vpcHost.lastIndexOf("/"));
        // get the IP address of the VPC machine
        vpcHost = vpcHost.substring(0, vpcHost.lastIndexOf("/"));
    }

    try {
        Socket socket = null;
        if (useSSL) {
            socket = getSocket(vpcHost, vpc_Port);
            // use next block of code if NOT using SSL encryption
        } else {
            socket = new Socket(vpcHost, vpc_Port);
        }
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();

        os.write(prepareCompleteQueryString(fileName, queryParameters).getBytes());
        String res = new String(readAll(is));

        // check if a successful connection
        if (res.indexOf("200") < 0) {
            throw new IOException("Connection Refused - " + res);
        }

        if (res.indexOf("404 Not Found") > 0) {
            throw new IOException("File Not Found Error - " + res);
        }

        int resIndex = res.indexOf("\r\n\r\n");
        String body = res.substring(resIndex + 4, res.length());
        return body;

    } catch (IOException ioe) {
    }
    return StringUtils.EMPTY;
}

From source file:com.sshtools.j2ssh.agent.SshAgentSocketListener.java

/**
 * Starts the agent listener thread//from  w  w w . j a v a2 s  .  c  o  m
 */
public void start() {
    thread = new Thread(new Runnable() {
        public void run() {
            try {
                Socket socket;

                System.setProperty("sshtools.agent", location);

                state.setValue(StartStopState.STARTED);

                while ((socket = server.accept()) != null) {
                    SshAgentConnection agentClient = new SshAgentConnection(keystore, socket.getInputStream(),
                            socket.getOutputStream());
                }

                thread = null;
            } catch (IOException ex) {
                log.info("The agent listener closed: " + ex.getMessage());
            } finally {
                state.setValue(StartStopState.STOPPED);
            }
        }
    });

    thread.start();
}

From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java

@Test
public void testWriteClose() throws IOException {
    // Create a task to be executed following the acceptance of a new connection to the server socketChannel.
    // This task is the application entry point.
    // This task will write out the message "Hello and Goodbye" and then close the connection.
    ISocketChannelHandler socketChannelHandler = (nbContext, socket) -> WriteMessageTask.Builder.builder()
            .withByteBuffer(ByteBuffer.allocate(2048)).build()
            .writeMessage("Hello and Goodbye\n".getBytes(StandardCharsets.UTF_8), nbContext, socket,
                    () -> IOUtils.closeQuietly(socket), (e) -> LOG.error("Write failed", e));
    // create the server
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(//from ww  w  .ja  v  a 2 s  .  c om
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            // Here we configure the provider for the listening socketChannel.  In this case,
            // a TCP server socketChannel will be created using the default TcpAcceptedConnectionHandler
            // to handle incoming connections and pass them off to the socketChannelHandler
            .withConnectorFactory(TcpConnectorFactory.Builder.builder()
                    // supply the application entry point
                    .withConnectedSocketTask(socketChannelHandler).build())
            .build();
    try {
        simpleNbServer.start();
        Socket socket = new Socket("localhost", 1111);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        String message = reader.readLine();
        System.out.println("Received message '" + message + "' from the server");
        Assert.assertEquals("Hello and Goodbye", message);
        socket.close();
    } finally {
        simpleNbServer.shutdown();
    }
}

From source file:com.kyne.webby.bukkit.RTKModuleSocket.java

@Override
public void run() {
    LogHelper.info("Webby Socket (BukkitPlugin) is listening on port : " + this.serverSocket.getLocalPort());
    while (!this.serverSocket.isClosed()) {
        //         this.requestCount++;
        Socket clientSocket = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {//  www.ja va  2 s  .  com
            clientSocket = this.serverSocket.accept();
            ois = new ObjectInputStream(clientSocket.getInputStream());
            oos = new ObjectOutputStream(clientSocket.getOutputStream());

            final WebbyLocalData request = (WebbyLocalData) ois.readObject();
            final WebbyLocalData response = this.handleRequest(request);
            oos.writeObject(response);
        } catch (final SocketException e) {
            LogHelper.warn("Socket has been closed. If bukkit is stopping or restarting, this is normal");
        } catch (final IOException e) {
            LogHelper.error("An error occured while waiting for connections", e);
        } catch (final ClassNotFoundException e) {
            LogHelper.error("Unsupported object was sent to Webby ", e);
        } finally {
            IOUtils.closeQuietly(ois);
            IOUtils.closeQuietly(oos);
            IOUtils.closeQuietly(clientSocket);
        }
    }
}

From source file:org.apache.axis2.engine.MessageWithServerTest.java

public void testEchoStringServer() throws Exception {
    InputStream in = cl.getResourceAsStream("soap/soapmessage.txt");

    if (in == null) {
        in = new FileInputStream(System.getProperty("basedir", ".") + "/test-resources/soap/soapmessage.txt");
    }/* w  ww .  j  a  v  a  2  s  .co  m*/

    Socket socket = new Socket("127.0.0.1", UtilServer.TESTING_PORT);
    OutputStream out = socket.getOutputStream();
    byte[] buf = new byte[1024];
    int index;
    while ((index = in.read(buf)) > 0) {
        out.write(buf, 0, index);
    }

    InputStream respose = socket.getInputStream();
    Reader rReader = new InputStreamReader(respose);
    char[] charBuf = new char[1024];
    while ((rReader.read(charBuf)) > 0) {
        log.info(new String(charBuf));
    }

    in.close();
    out.close();

    rReader.close();
    socket.close();
}

From source file:com.meh.CopyProxy.java

private HttpRequest readRequest(Socket client) {
    HttpRequest request = null;/*from   w ww  . java  2 s .  com*/
    InputStream is;
    String firstLine;
    try {
        is = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        firstLine = reader.readLine();
    } catch (IOException e) {
        Log.e(tag, "Error parsing request", e);
        return request;
    }

    if (firstLine == null) {
        Log.i(tag, "Proxy client closed connection without a request.");
        return request;
    }

    StringTokenizer st = new StringTokenizer(firstLine);
    String method = st.nextToken();
    String uri = st.nextToken();
    Log.d(tag, uri);
    String realUri = uri.substring(1);
    Log.d(tag, realUri);
    request = new BasicHttpRequest(method, realUri);
    return request;
}

From source file:net.pms.network.RequestHandler.java

public RequestHandler(Socket socket) throws IOException {
    this.socket = socket;
    this.output = socket.getOutputStream();
    this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

From source file:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnector.java

@Override
public void run() {
    /*/*  w ww  .j a  va  2 s  .com*/
     * Accept a connection and tunnel messages through the proxy system.
     */
    Socket socket = null;
    try {
        Thread toProxyThread;
        Thread fromProxyThread;

        socket = server.accept();
        log.debug("Server accepting to socket " + socket.getInetAddress());
        Connector toProxy = new Connector(socket.getInputStream(), proxyConnection.getOutStream(), bufferSize);
        Connector fromProxy = new Connector(proxyConnection.getInStream(), socket.getOutputStream(),
                bufferSize);

        toProxyThread = new Thread(toProxy, "Client To Proxy");
        fromProxyThread = new Thread(fromProxy, "Client From Proxy");

        toProxyThread.start();
        fromProxyThread.start();

        log.debug("Waiting to finish " + toProxyThread.getName());
        toProxyThread.join();

    } catch (IOException e) {
        String errorMsg = "Problem in creating client to proxy connectors: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } catch (InterruptedException e) {
        String errorMsg = "Client to proxy communication thread interrupted: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } finally {
        if (socket != null) {
            try {
                log.debug("Closing socket " + socket.getInetAddress() + ": " + socket.getPort());
                // Also closes associated streams
                socket.close();
            } catch (IOException ex) {
                log.warn("Unable to close client to proxy socket: " + ex.getMessage());
            }
        }
        if (proxyConnection != null) {
            try {
                log.debug("Closing proxy connection " + proxyConnection.getSocket().getInetAddress() + ": "
                        + proxyConnection.getSocket().getPort());
                proxyConnection.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
        if (server != null) {
            try {
                log.debug("Closing client connection server" + server.getInetAddress() + ": "
                        + server.getLocalPort());
                server.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
    }
}

From source file:org.apache.geode.internal.net.SSLSocketIntegrationTest.java

private Thread startServer(final ServerSocket serverSocket) throws Exception {
    Thread serverThread = new Thread(new MyThreadGroup(this.testName.getMethodName()), () -> {
        try {/*ww  w. jav  a 2  s  .c o m*/
            Socket socket = serverSocket.accept();
            SocketCreatorFactory.getSocketCreatorForComponent(CLUSTER).configureServerSSLSocket(socket);
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            messageFromClient.set((String) ois.readObject());
        } catch (IOException | ClassNotFoundException e) {
            throw new Error(e);
        }
    }, this.testName.getMethodName() + "-server");

    serverThread.start();
    return serverThread;
}

From source file:com.apporiented.hermesftp.cmd.AbstractFtpCmdStor.java

/**
 * Executes the command. This operation acts as a template method calling primitive operations
 * implemented by the sub classes.//  w ww  .  j a v a  2s  .c  o  m
 * 
 * @param unique True, if file that is supposed to be stored may not exist on the remote file
 *            system.
 * @throws FtpCmdException Wrapper class for any exception thrown in the command.
 */
public void execute(boolean unique) throws FtpCmdException {

    /* Get relevant information from context */
    File file = new File(getPathArg());
    int mode = getCtx().getTransmissionMode();
    int struct = getCtx().getStorageStructure();
    int type = getCtx().getDataType();
    String charset = type == DT_ASCII || type == DT_EBCDIC ? getCtx().getCharset() : null;
    long fileOffset = getAndResetFileOffset();
    getTransferRateLimiter().init(getCtx().getMaxUploadRate());

    try {
        /* Check availability and access rights */
        doPerformAccessChecks(unique, file, fileOffset);

        /* Initialize restart markers (block transfer mode) */
        Map<Long, Long> restartMarkers = new HashMap<Long, Long>();
        getCtx().setAttribute(ATTR_RESTART_MARKERS, restartMarkers);

        /* Wrap inbound data stream and call handler method */
        msgOut(MSG150);

        Socket dataSocket = getCtx().getDataSocketProvider().provideSocket();
        InputStream dataIn = dataSocket.getInputStream();
        if (struct == STRUCT_RECORD) {
            RecordReadSupport recordIn = createRecInputStream(dataIn, mode, charset, restartMarkers);
            doStoreRecordData(recordIn, file, fileOffset);
        } else if (struct == STRUCT_FILE) {
            InputStream fileIn = createInputStream(dataIn, mode, restartMarkers, charset);
            doStoreFileData(fileIn, file, fileOffset);
        } else {
            log.error("Unknown data type");
            msgOut(MSG550, "Unsupported data type");
        }
        // TODO delegate event to FtpEventListener
        // getCtx().getEventListener().

    } catch (FtpUniqueConstraintException e) {
        msgOut(MSG553);
    } catch (FtpPermissionException e) {
        msgOut(MSG550_PERM);
    } catch (FtpException e) {
        msgOut(MSG550_MSG, e.getMessage());
        log.warn(e.getMessage());
    } catch (UnsupportedEncodingException e) {
        msgOut(MSG550_MSG, "Unsupported Encoding: " + charset);
        log.error(e.toString());
    } catch (IOException e) {
        msgOut(MSG550);
        log.error(e.toString());
    } catch (RuntimeException e) {
        msgOut(MSG550);
        log.error(e.toString());
    } finally {
        getCtx().closeSockets();
    }
}