Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

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

Prototype

public Socket(InetAddress address, int port) throws IOException 

Source Link

Document

Creates a stream socket and connects it to the specified port number at the specified IP address.

Usage

From source file:cf.service.integration.FunctionalTest.java

private static String localIp(String cloudControllerUri) {
    final URI uri = URI.create(cloudControllerUri);
    final int port = uri.getPort() == -1 ? 80 : uri.getPort();
    try (Socket socket = new Socket(uri.getHost(), port)) {
        return socket.getLocalAddress().getHostAddress();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }/* w  w w  . j  a  va  2  s.c  om*/
}

From source file:hudson.util.NoClientBindProtocolSocketFactory.java

/**
 * @see ProtocolSocketFactory#createSocket(java.lang.String,int)
 *///from  w  w w. j a  v  a2 s  .co m
public Socket createSocket(String host, int port) throws IOException, UnknownHostException, IOException {
    Socket socket = null;
    try {
        socket = new Socket(host, port);
    } catch (IOException e) {
        throw e;
    }
    return socket;
}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

public static Element sendGet(ConnectorManager connectorManager, String servletPath,
        Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }//from  ww w.  j a  va  2  s.  c  om

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            String target = connectorManager.getUrl() + servletPath;
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);

                if (firstParam) {
                    target += "?";
                    firstParam = false;
                } else {
                    target += "&";
                }
                target += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", target);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (Exception e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.oneandone.sushi.fs.webdav.WebdavRoot.java

public synchronized WebdavConnection allocate() throws IOException {
    int size;/* w ww .j a  va  2s  . c o  m*/

    allocated++;
    size = pool.size();
    if (size > 0) {
        return pool.remove(size - 1);
    } else {
        Socket socket;

        if ("https".equals(host.getSchemeName())) {
            socket = SSLSocketFactory.getDefault().createSocket(host.getHostName(), host.getPort());
        } else {
            socket = new Socket(host.getHostName(), host.getPort());
        }
        return WebdavConnection.open(socket, params);
    }
}

From source file:org.jmxtrans.embedded.samples.graphite.GraphiteDataInjector.java

public void exportMetrics(TimeSeries timeSeries) throws IOException {
    System.out.println("Export '" + timeSeries.getKey() + "' to " + graphiteHost + " with prefix '"
            + graphiteMetricPrefix + "'");
    Socket socket = new Socket(graphiteHost, graphitePort);
    OutputStream outputStream = socket.getOutputStream();

    if (generateDataPointsFile) {
        JFreeChart chart = ChartFactory.createXYLineChart("Purchase", "date", "Amount",
                new TimeSeriesCollection(timeSeries), PlotOrientation.VERTICAL, true, true, false);
        // chart.getXYPlot().setRenderer(new XYSplineRenderer(60));

        File file = new File("/tmp/" + timeSeries.getKey() + ".png");
        ChartUtilities.saveChartAsPNG(file, chart, 1200, 800);
        System.out.println("Exported " + file.getAbsolutePath());

        String pickleFileName = "/tmp/" + timeSeries.getKey().toString() + ".pickle";
        System.out.println("Generate " + pickleFileName);
        outputStream = new TeeOutputStream(outputStream, new FileOutputStream(pickleFileName));
    }/*  w  ww.ja va2 s .  c om*/

    PyList list = new PyList();

    for (int i = 0; i < timeSeries.getItemCount(); i++) {
        if (debug)
            System.out.println(new DateTime(timeSeries.getDataItem(i).getPeriod().getStart()) + "\t"
                    + timeSeries.getDataItem(i).getValue().intValue());
        String metricName = graphiteMetricPrefix + timeSeries.getKey().toString();
        int time = (int) TimeUnit.SECONDS.convert(timeSeries.getDataItem(i).getPeriod().getStart().getTime(),
                TimeUnit.MILLISECONDS);
        int value = timeSeries.getDataItem(i).getValue().intValue();

        list.add(new PyTuple(new PyString(metricName), new PyTuple(new PyInteger(time), new PyInteger(value))));

        if (list.size() >= batchSize) {
            System.out.print("-");
            rateLimiter.acquire(list.size());
            sendDataPoints(outputStream, list);
        }
    }

    // send last data points
    if (!list.isEmpty()) {
        rateLimiter.acquire(list.size());
        sendDataPoints(outputStream, list);
    }

    Flushables.flushQuietly(outputStream);
    Closeables.close(outputStream, true);
    try {
        socket.close();
    } catch (Exception e) {
        // swallow exception
        e.printStackTrace();
    }

    System.out.println();
    System.out.println("Exported " + timeSeries.getKey() + ": " + timeSeries.getItemCount() + " items");
}

From source file:denkgear.DenkGear.java

private void initThinkgear() {
    System.out.println("##library.name## ##library.prettyVersion## by ##author##");

    try {//from ww  w  .  ja  v a 2s.c o  m
        echoSocket = new Socket(url, port);
        out = new PrintWriter(echoSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
        System.out.println("connect");
        out.println("{\"enableRawOutput\": " + raw + ", \"format\": \"Json\"}\n");
    } catch (UnknownHostException e) {
        System.out.println("Don't know about host: " + url);
        //System.exit(1);
    } catch (IOException e) {
        System.out.println("Couldn't get I/O for " + "the connection to:" + url);
        //System.exit(1);
    }
}

From source file:fr.enseirb.odroidx.videomanager.Uploader.java

public void doUpload(Uri myFile) {
    createNotification();/*from   w ww .ja  v  a2s.c  om*/
    File f = new File(myFile.getPath());
    SendName(f.getName().replace(' ', '-'));
    Log.e(getClass().getSimpleName(), "test: " + f.exists());
    if (f.exists()) {
        Socket s;
        try {
            Log.e(getClass().getSimpleName(), "test: " + server_ip);
            s = new Socket(InetAddress.getByName(server_ip), 5088);// Bug
            // using
            // variable
            // port
            OutputStream fluxsortie = s.getOutputStream();
            int nb_parts = (int) (f.length() / PART_SIZE);

            InputStream in = new BufferedInputStream(new FileInputStream(f));
            ByteArrayOutputStream byte_array = new ByteArrayOutputStream();
            BufferedOutputStream buffer = new BufferedOutputStream(byte_array);

            byte[] to_write = new byte[PART_SIZE];
            for (int i = 0; i < nb_parts; i++) {
                in.read(to_write, 0, PART_SIZE);
                buffer.write(to_write);
                buffer.flush();
                fluxsortie.write(byte_array.toByteArray());
                byte_array.reset();
                if ((i % 250) == 0) {
                    mBuilder.setProgress(nb_parts, i, false);
                    mNotifyManager.notify(NOTIFY_ID, mBuilder.getNotification());
                }
            }
            int remaining = (int) (f.length() - nb_parts * PART_SIZE);
            in.read(to_write, 0, remaining);
            buffer.write(to_write);
            buffer.flush();
            fluxsortie.write(byte_array.toByteArray());
            byte_array.reset();
            buffer.close();
            fluxsortie.close();
            in.close();
            s.close();
        } catch (ConnectException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        } catch (UnknownHostException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = UNKNOWN;
            Log.i(getClass().getSimpleName(), "Unknown host");
            e.printStackTrace();
        } catch (IOException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        }
    }
}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test that we can use a Java system property to configure the protocol
 * version on the agent.// w  w  w.  j av a2  s . c o m
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testSetTo11() throws Exception {
    System.setProperty(ZabbixAgent.PROTOCOL_PROPERTY, "1.1");
    assertEquals("1.1", System.getProperty(ZabbixAgent.PROTOCOL_PROPERTY));

    final Agent agent = new ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(), ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("system.property[java.version]\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    in.read(buffer);

    final String version = System.getProperty("java.version");

    assertEquals(version.charAt(0), buffer[0]);
    assertEquals(version.charAt(1), buffer[1]);
    assertEquals(version.charAt(2), buffer[2]);
    assertEquals(version.charAt(3), buffer[3]);
    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMOMessagePipeline()
        throws URISyntaxException, ClientProtocolException, IOException, InterruptedException {
    System.out.println("MO TEST: Testing MO message pipeline...");

    Thread.sleep(1000);/* w  w w  . ja va 2  s .c  o  m*/

    Thread mavlinkThread = new Thread(new Runnable() {
        public void run() {
            Socket client = null;

            try {
                System.out.printf("MO TEST: Connecting to tcp://%s:%d",
                        InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());
                System.out.println();

                client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

                System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                        config.getMAVLinkPort());
                System.out.println();

                Parser parser = new Parser();
                DataInputStream in = new DataInputStream(client.getInputStream());
                while (true) {
                    MAVLinkPacket packet;
                    do {
                        int c = in.readUnsignedByte();
                        packet = parser.mavlink_parse_char(c);
                    } while (packet == null);

                    System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid);
                    System.out.println();

                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mavlinkThread.start();

    HttpClient httpclient = HttpClients.createDefault();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(InetAddress.getLocalHost().getHostAddress());
    builder.setPort(config.getRockblockPort());
    builder.setPath(config.getHttpContext());

    URI uri = builder.build();
    HttpPost httppost = new HttpPost(uri);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI()));
    params.add(new BasicNameValuePair("momsn", "12345"));
    params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50"));
    params.add(new BasicNameValuePair("iridium_latitude", "52.3867"));
    params.add(new BasicNameValuePair("iridium_longitude", "0.2938"));
    params.add(new BasicNameValuePair("iridium_cep", "9"));
    params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket())));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    System.out.printf("MO TEST: Sending test message to %s", uri.toString());
    System.out.println();

    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() != 200) {
        fail(String.format("RockBLOCK HTTP message handler status code = %d.",
                response.getStatusLine().getStatusCode()));
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream responseStream = entity.getContent();
        try {
            String responseString = IOUtils.toString(responseStream);
            System.out.println(responseString);
        } finally {
            responseStream.close();
        }
    }

    Thread.sleep(1000);

    mavlinkThread.interrupt();
    System.out.println("MO TEST: Complete.");
}

From source file:com.pentaho.ctools.utils.HttpUtils.java

/**
 * The method check if a host is listening in the specified port.
 * //from   ww  w  . ja v a  2 s. co  m
 * @param host - Host name.
 * @param port - Port
 * @return - true is listening in the port, false otherwise.
 */
public static boolean ServerListening(String host, int port) {
    try (Socket s = new Socket(host, port);) {
        return true;
    } catch (Exception e) {
        return false;
    }
}