Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:org.jasig.portlet.cms.model.security.ClamAVAntiVirus.java

private String sendSocket(final Socket socket, final String command) throws Exception {
    String answer = null;/*  ww w.  j a va  2  s.  c o  m*/
    BufferedReader reader = null;
    PrintWriter writer = null;

    try {
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

        writer.println(command);
        writer.flush();

        answer = reader.readLine();
        if (answer != null)
            answer = answer.trim();

    } finally {
        try {
            if (reader != null)
                reader.close();
        } catch (final IOException e) {
            logger.error(e.getMessage(), e);
        }

        if (writer != null)
            writer.close();
    }
    return answer;
}

From source file:com.supernovapps.audio.jstreamsourcer.ShoutcastV1Test.java

@Test
public void testConnect() throws IOException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.replay(sockMock);//  w  w w .j av  a2  s .c o  m

    shoutcast.start(sockMock);

    String expected = "password1\n";
    expected += "content-type: " + shoutcast.getStreamInfo(Sourcer.CONTENT_TYPE) + "\n";
    expected += "icy-genre: " + shoutcast.getStreamInfo(Sourcer.ICY_GENRE) + "\n";
    expected += "icy-pub: " + shoutcast.getStreamInfo(Sourcer.ICY_PUB) + "\n";
    expected += "icy-name: " + shoutcast.getStreamInfo(Sourcer.ICY_NAME) + "\n";
    expected += "icy-url: " + shoutcast.getStreamInfo(Sourcer.ICY_URL) + "\n";
    expected += "icy-br: " + String.valueOf(bitrate) + "\n\n";

    String http = new String(out.toByteArray());
    Assert.assertEquals(expected, http);
}

From source file:com.cloud.utils.crypt.EncryptionSecretKeyChecker.java

public void check(Properties dbProps) throws IOException {
    String encryptionType = dbProps.getProperty("db.cloud.encryption.type");

    s_logger.debug("Encryption Type: " + encryptionType);

    if (encryptionType == null || encryptionType.equals("none")) {
        return;//from   ww w .j a v  a  2 s .c o m
    }

    if (s_useEncryption) {
        s_logger.warn("Encryption already enabled, is check() called twice?");
        return;
    }

    s_encryptor.setAlgorithm("PBEWithMD5AndDES");
    String secretKey = null;

    SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig();

    if (encryptionType.equals("file")) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(s_keyFile);
        if (is == null) {
            is = this.getClass().getClassLoader().getResourceAsStream(s_altKeyFile);
        }
        if (is == null) { //This is means we are not able to load key file from the classpath.
            throw new CloudRuntimeException(
                    s_keyFile + " File containing secret key not found in the classpath: ");
        }
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(is));
            secretKey = in.readLine();
            //Check for null or empty secret key
        } catch (IOException e) {
            throw new CloudRuntimeException("Error while reading secret key from: " + s_keyFile, e);
        } finally {
            IOUtils.closeQuietly(in);
        }

        if (secretKey == null || secretKey.isEmpty()) {
            throw new CloudRuntimeException("Secret key is null or empty in file " + s_keyFile);
        }

    } else if (encryptionType.equals("env")) {
        secretKey = System.getenv(s_envKey);
        if (secretKey == null || secretKey.isEmpty()) {
            throw new CloudRuntimeException("Environment variable " + s_envKey + " is not set or empty");
        }
    } else if (encryptionType.equals("web")) {
        ServerSocket serverSocket = null;
        int port = 8097;
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException ioex) {
            throw new CloudRuntimeException("Error initializing secret key reciever", ioex);
        }
        s_logger.info("Waiting for admin to send secret key on port " + port);
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            throw new CloudRuntimeException("Accept failed on " + port);
        }
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        if ((inputLine = in.readLine()) != null) {
            secretKey = inputLine;
        }
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    } else {
        throw new CloudRuntimeException("Invalid encryption type: " + encryptionType);
    }

    stringConfig.setPassword(secretKey);
    s_encryptor.setConfig(stringConfig);
    s_useEncryption = true;
}

From source file:demo.socket.pool.SocketsPool.java

private PooledSocketConn createConn(boolean printLog) throws IOException {

    Socket s = new Socket(host, port);
    if (socketSoTimeout != null)
        s.setSoTimeout(socketSoTimeout);

    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    if (printLog)
        log.info("Connected to " + host + ":" + port + "." + " Pool props [" + "maxActiveConnections="
                + poolMaximumActiveConnections + ", maxIdleConnections=" + poolMaximumIdleConnections
                + ", maxCheckoutTime=" + poolMaximumCheckoutTime + ", timeToWait=" + poolTimeToWait + "]");
    return new PooledSocketConn(s, is, os, this);
}

From source file:com.supernovapps.audio.jstreamsourcer.ShoutcastV1Test.java

@Test
public void testUpdateMetadata() throws IOException, URISyntaxException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("HTTP OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.expect(sockMock.isConnected()).andReturn(true);
    EasyMock.replay(sockMock);/*from w ww  . j av a 2s  .c om*/

    shoutcast.start(sockMock);

    HttpUriRequest request = shoutcast.getUpdateMetadataRequest("song", "artist", "album");
    Assert.assertEquals(shoutcast.getHost(), request.getURI().getHost());
    Assert.assertEquals(shoutcast.getPort(), request.getURI().getPort());

    HashMap<String, String> paramsMap = getParams(request);
    Assert.assertEquals("album song artist", paramsMap.get("song"));
}

From source file:com.supernovapps.audio.jstreamsourcer.IcecastTest.java

@Test
public void testConnectSuccess() throws IOException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("HTTP OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.expect(sockMock.isConnected()).andReturn(true);
    EasyMock.replay(sockMock);/*from w w w.j  a  v  a  2s .  co m*/

    boolean started = icecast.start(sockMock);

    Assert.assertTrue(started);
    Assert.assertTrue(icecast.isStarted());
}

From source file:WebServer.java

/**
 * WebServer constructor./*from ww w . ja  v  a 2s  .c  om*/
 */
protected void start() {
    ServerSocket s;

    System.out.println("Webserver starting up on port 80");
    System.out.println("(press ctrl-c to exit)");
    try {
        // create the main server socket
        s = new ServerSocket(80);
    } catch (Exception e) {
        System.out.println("Error: " + e);
        return;
    }

    System.out.println("Waiting for connection");
    for (;;) {
        try {
            // wait for a connection
            Socket remote = s.accept();
            // remote is now the connected socket
            System.out.println("Connection, sending data.");
            BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
            PrintWriter out = new PrintWriter(remote.getOutputStream());

            // read the data sent. We basically ignore it,
            // stop reading once a blank line is hit. This
            // blank line signals the end of the client HTTP
            // headers.
            String str = ".";
            while (!str.equals(""))
                str = in.readLine();

            // Send the response
            // Send the headers
            out.println("HTTP/1.0 200 OK");
            out.println("Content-Type: text/html");
            out.println("Server: Bot");
            // this blank line signals the end of the headers
            out.println("");
            // Send the HTML page
            out.println("<H1>Welcome to the Ultra Mini-WebServer</H2>");
            out.flush();
            remote.close();
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}

From source file:ru.codemine.ccms.counters.kondor.KondorClient.java

private File ftpDownload(Shop shop) {
    String login = settingsService.getCountersKondorFtpLogin();
    String pass = settingsService.getCountersKondorFtpPassword();
    String ip = shop.getProvider().getIp();
    String tmpFileName = settingsService.getStorageRootPath()
            + DateTime.now().toString("YYYYMMdd-s" + shop.getId());
    try {/*from   w ww  .  jav  a2s.  c  o  m*/
        log.debug("Starting ftp session...");

        Socket manageSocket = new Socket();
        manageSocket.connect(new InetSocketAddress(ip, 21), 3000);
        BufferedReader in = new BufferedReader(new InputStreamReader(manageSocket.getInputStream()));
        PrintWriter out = new PrintWriter(manageSocket.getOutputStream(), true);
        String ftpAnswer;

        ftpAnswer = in.readLine();
        log.debug("FTP greetings: " + ftpAnswer);

        out.println("USER " + login);
        ftpAnswer = in.readLine();
        log.debug("FTP USER command responce: " + ftpAnswer);

        out.println("PASS " + pass);
        String afterAuth = in.readLine();
        log.debug("FTP PASS command responce: " + afterAuth);

        out.println("PASV");
        String pasvResponce = in.readLine();
        log.debug("FTP: PASV command responce: " + pasvResponce);

        if (pasvResponce.startsWith("227 (")) {
            pasvResponce = pasvResponce.substring(5);
            List<String> parsedPasv = new ArrayList<>(Arrays.asList(pasvResponce.split(",")));
            String p4 = parsedPasv.get(4);
            String p5 = parsedPasv.get(5).replace(")", "");
            int port = Integer.parseInt(p4) * 256 + Integer.parseInt(p5);

            log.debug("FTP: Recieved port: " + port);

            Socket dataSocket = new Socket();
            dataSocket.connect(new InetSocketAddress(ip, port), 3000);
            InputStream dataIn = dataSocket.getInputStream();
            FileOutputStream dataOut = new FileOutputStream(tmpFileName);

            out.println("RETR total.dbf");
            ftpAnswer = in.readLine();
            log.debug("FTP RETR command responce: " + ftpAnswer);

            IOUtils.copy(dataIn, dataOut);

            dataOut.flush();
            dataOut.close();
            dataSocket.close();
        } else {
            if (afterAuth.startsWith("530")) {
                log.warn(
                        "     ?, : "
                                + shop.getName());

            } else {
                log.warn(
                        " ?     PASV, : "
                                + shop.getName());
            }

        }

        out.println("QUIT");
        ftpAnswer = in.readLine();
        log.debug("FTP QUIT command responce: " + ftpAnswer);

        manageSocket.close();
    } catch (Exception e) {
        log.warn(
                "?   ? ?   "
                        + shop.getName() + ",  : " + e.getMessage());
    }

    return new File(tmpFileName);
}

From source file:com.supernovapps.audio.jstreamsourcer.IcecastTest.java

@Test
public void testUpdateMetadata() throws IOException, URISyntaxException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("HTTP OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.expect(sockMock.isConnected()).andReturn(true);
    EasyMock.replay(sockMock);/*from  ww w.  j a va 2s .com*/

    icecast.start(sockMock);

    HttpUriRequest request = icecast.getUpdateMetadataRequest("song", "artist", "album");
    Assert.assertEquals(icecast.getHost(), request.getURI().getHost());
    Assert.assertEquals(icecast.getPort(), request.getURI().getPort());

    HashMap<String, String> paramsMap = getParams(request);
    Assert.assertEquals(icecast.getPath(), paramsMap.get("mount"));
    Assert.assertEquals("updinfo", paramsMap.get("mode"));
    Assert.assertEquals("album song artist", paramsMap.get("song"));
}

From source file:com.supernovapps.audio.jstreamsourcer.IcecastTest.java

@Test
public void testConnect() throws IOException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("HTTP OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.replay(sockMock);/*from  w w  w. j  a v a2 s . c  o m*/

    icecast.start(sockMock);

    String expected = "SOURCE /stream1 HTTP/1.0\n";
    expected += "Authorization: Basic dXNlcm5hbWUxOnBhc3N3b3JkMQ==\n";
    expected += "User-Agent: " + Sourcer.USER_AGENT + "\n";
    expected += "icy-notice1: " + Sourcer.USER_AGENT + "\n";
    expected += "content-type: " + icecast.getStreamInfo(Sourcer.CONTENT_TYPE) + "\n";
    expected += "icy-genre: " + icecast.getStreamInfo(Sourcer.ICY_GENRE) + "\n";
    expected += "icy-pub: " + icecast.getStreamInfo(Sourcer.ICY_PUB) + "\n";
    expected += "icy-name: " + icecast.getStreamInfo(Sourcer.ICY_NAME) + "\n";
    expected += "icy-url: " + icecast.getStreamInfo(Sourcer.ICY_URL) + "\n";
    expected += "icy-br: " + String.valueOf(bitrate) + "\n\n";

    String http = new String(out.toByteArray());
    Assert.assertEquals(expected, http);
}