Java Code Examples for javax.net.SocketFactory#getDefault()

The following examples show how to use javax.net.SocketFactory#getDefault() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GraphiteSenderProvider.java    From graylog-plugin-metrics-reporter with GNU General Public License v3.0 6 votes vote down vote up
@Override
public GraphiteSender get() {
    HostAndPort hostAndPort = configuration.getAddress();
    String host = hostAndPort.getHost();
    int port = hostAndPort.getPortOrDefault(2003);

    switch (configuration.getProtocol()) {
        case PICKLE:
            return new PickledGraphite(
                    host,
                    port,
                    SocketFactory.getDefault(),
                    configuration.getCharset(),
                    configuration.getPickleBatchSize());
        case TCP:
            return new Graphite(host, port, SocketFactory.getDefault(), configuration.getCharset());
        case UDP:
            return new GraphiteUDP(host, port);
        default:
            throw new IllegalArgumentException("Unknown Graphite protocol \"" + configuration.getProtocol() + "\"");
    }
}
 
Example 2
Source File: NetUtils.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Get the default socket factory as specified by the configuration
 * parameter <tt>hadoop.rpc.socket.factory.default</tt>
 * 
 * @param conf the configuration
 * @return the default socket factory as specified in the configuration or
 *         the JVM default socket factory if the configuration does not
 *         contain a default socket factory property.
 */
public static SocketFactory getDefaultSocketFactory(Configuration conf) {

  String propValue = conf.get(
      CommonConfigurationKeysPublic.HADOOP_RPC_SOCKET_FACTORY_CLASS_DEFAULT_KEY,
      CommonConfigurationKeysPublic.HADOOP_RPC_SOCKET_FACTORY_CLASS_DEFAULT_DEFAULT);
  if ((propValue == null) || (propValue.length() == 0))
    return SocketFactory.getDefault();

  return getSocketFactoryFromProperty(conf, propValue);
}
 
Example 3
Source File: WebSocketConnection.java    From smartcoins-wallet with MIT License 5 votes vote down vote up
public void startConnection() {
    try {
        String host = mWebSocketURI.getHost();
        int port = mWebSocketURI.getPort();

        if (port == -1) {
            if (mWebSocketURI.getScheme().equals(WSS_URI_SCHEME)) {
                port = 443;
            } else {
                port = 80;
            }
        }

        SocketFactory factory = null;
        if (mWebSocketURI.getScheme().equalsIgnoreCase(WSS_URI_SCHEME)) {
            factory = SSLCertificateSocketFactory.getDefault();
        } else {
            factory = SocketFactory.getDefault();
        }

        // Do not replace host string with InetAddress or you lose automatic host name verification
        this.mSocket = factory.createSocket(host, port);
    } catch (IOException e) {
        this.mFailureMessage = e.getLocalizedMessage();
    }

    synchronized (this) {
        notifyAll();
    }
}
 
Example 4
Source File: NetUtils.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Get the default socket factory as specified by the configuration
 * parameter <tt>hadoop.rpc.socket.factory.default</tt>
 * 
 * @param conf the configuration
 * @return the default socket factory as specified in the configuration or
 *         the JVM default socket factory if the configuration does not
 *         contain a default socket factory property.
 */
public static SocketFactory getDefaultSocketFactory(Configuration conf) {

  String propValue = conf.get(
      CommonConfigurationKeysPublic.HADOOP_RPC_SOCKET_FACTORY_CLASS_DEFAULT_KEY,
      CommonConfigurationKeysPublic.HADOOP_RPC_SOCKET_FACTORY_CLASS_DEFAULT_DEFAULT);
  if ((propValue == null) || (propValue.length() == 0))
    return SocketFactory.getDefault();

  return getSocketFactoryFromProperty(conf, propValue);
}
 
Example 5
Source File: ClientConnectionBuilder.java    From j60870 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a client connection builder that can be used to connect to the given address.
 *
 * @param address the address to connect to
 */
public ClientConnectionBuilder(InetAddress address) {
    this.address = address;
    this.port = DEFAULT_PORT;

    this.localAddr = null;

    this.socketFactory = SocketFactory.getDefault();
}
 
Example 6
Source File: ThetaM15.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
private static SocketFactory getWifiSocketFactory(final Context context) {
    SocketFactory socketFactory = SocketFactory.getDefault();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !isGalaxyDevice()) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network[] allNetwork = cm.getAllNetworks();
        for (Network network : allNetwork) {
            NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(network);
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                socketFactory = network.getSocketFactory();
            }
        }
    }
    return socketFactory;
}
 
Example 7
Source File: NetworkAbstractionTests.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private MessageWriteTarget openConnection(SocketAddress addr, ProtobufConnection<TwoWayChannelMessage> parser) throws Exception {
    if (clientType == 0 || clientType == 1) {
        channels.openConnection(addr, parser);
        if (parser.writeTarget.get() == null)
            Thread.sleep(100);
        return parser.writeTarget.get();
    } else if (clientType == 2)
        return new NioClient(addr, parser, 100);
    else if (clientType == 3)
        return new BlockingClient(addr, parser, 100, SocketFactory.getDefault(), null);
    else
        throw new RuntimeException();
}
 
Example 8
Source File: NetworkAbstractionTests.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private MessageWriteTarget openConnection(SocketAddress addr, ProtobufConnection<TwoWayChannelMessage> parser) throws Exception {
    if (clientType == 0 || clientType == 1) {
        channels.openConnection(addr, parser);
        if (parser.writeTarget.get() == null)
            Thread.sleep(100);
        return parser.writeTarget.get();
    } else if (clientType == 2)
        return new NioClient(addr, parser, 100);
    else if (clientType == 3)
        return new BlockingClient(addr, parser, 100, SocketFactory.getDefault(), null);
    else
        throw new RuntimeException();
}
 
Example 9
Source File: Utils.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Use standard socket implementation.
 *
 * @param options url options
 * @param host host to connect
 * @return socket
 * @throws IOException in case of error establishing socket.
 */
public static Socket standardSocket(Options options, String host) throws IOException {
  SocketFactory socketFactory;
  String socketFactoryName = options.socketFactory;
  if (socketFactoryName != null) {
    try {
      @SuppressWarnings("unchecked")
      Class<? extends SocketFactory> socketFactoryClass =
          (Class<? extends SocketFactory>) Class.forName(socketFactoryName);
      if (socketFactoryClass != null) {
        Constructor<? extends SocketFactory> constructor = socketFactoryClass.getConstructor();
        socketFactory = constructor.newInstance();
        if (socketFactoryClass.isInstance(ConfigurableSocketFactory.class)) {
          ((ConfigurableSocketFactory) socketFactory).setConfiguration(options, host);
        }
        return socketFactory.createSocket();
      }
    } catch (Exception exp) {
      throw new IOException(
          "Socket factory failed to initialized with option \"socketFactory\" set to \""
              + options.socketFactory
              + "\"",
          exp);
    }
  }
  socketFactory = SocketFactory.getDefault();
  return socketFactory.createSocket();
}
 
Example 10
Source File: TestWithNetworkConnections.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
protected InboundMessageQueuer connect(Peer peer, VersionMessage versionMessage) throws Exception {
    checkArgument(versionMessage.hasBlockChain());
    final AtomicBoolean doneConnecting = new AtomicBoolean(false);
    final Thread thisThread = Thread.currentThread();
    peer.addDisconnectedEventListener(new PeerDisconnectedEventListener() {
        @Override
        public void onPeerDisconnected(Peer p, int peerCount) {
            synchronized (doneConnecting) {
                if (!doneConnecting.get())
                    thisThread.interrupt();
            }
        }
    });
    if (clientType == ClientType.NIO_CLIENT_MANAGER || clientType == ClientType.BLOCKING_CLIENT_MANAGER)
        channels.openConnection(new InetSocketAddress("127.0.0.1", 2000), peer);
    else if (clientType == ClientType.NIO_CLIENT)
        new NioClient(new InetSocketAddress("127.0.0.1", 2000), peer, 100);
    else if (clientType == ClientType.BLOCKING_CLIENT)
        new BlockingClient(new InetSocketAddress("127.0.0.1", 2000), peer, 100, SocketFactory.getDefault(), null);
    else
        throw new RuntimeException();
    // Claim we are connected to a different IP that what we really are, so tx confidence broadcastBy sets work
    InboundMessageQueuer writeTarget = newPeerWriteTargetQueue.take();
    writeTarget.peer = peer;
    // Complete handshake with the peer - send/receive version(ack)s, receive bloom filter
    checkState(!peer.getVersionHandshakeFuture().isDone());
    writeTarget.sendMessage(versionMessage);
    writeTarget.sendMessage(new VersionAck());
    try {
        checkState(writeTarget.nextMessageBlocking() instanceof VersionMessage);
        checkState(writeTarget.nextMessageBlocking() instanceof VersionAck);
        peer.getVersionHandshakeFuture().get();
        synchronized (doneConnecting) {
            doneConnecting.set(true);
        }
        Thread.interrupted(); // Clear interrupted bit in case it was set before we got into the CS
    } catch (InterruptedException e) {
        // We were disconnected before we got back version/verack
    }
    return writeTarget;
}
 
Example 11
Source File: DnsUpdateWriterModule.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Provides
static SocketFactory provideSocketFactory() {
  return SocketFactory.getDefault();
}
 
Example 12
Source File: WebSocketClient.java    From Leanplum-Android-SDK with Apache License 2.0 4 votes vote down vote up
public void connect() {
  if (mThread != null && mThread.isAlive()) {
    return;
  }

  mThread = new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        int port = (mURI.getPort() != -1) ? mURI.getPort() : (isSecure() ? 443 : 80);

        String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
        if (!TextUtils.isEmpty(mURI.getQuery())) {
          path += "?" + mURI.getQuery();
        }

        URI origin = null;
        try {
          origin = new URI(mURI.getScheme(), "//" + mURI.getHost(), null);
        } catch (URISyntaxException e) {
          Util.handleException(e);
        }

        SocketFactory factory;
        try {
          factory = isSecure() ? getSSLSocketFactory() : SocketFactory.getDefault();
        } catch (GeneralSecurityException e) {
          Util.handleException(e);
          return;
        }
        try {
          mSocket = factory.createSocket(mURI.getHost(), port);
        } catch (IOException e) {
          Util.handleException(e);
        }

        PrintWriter out = new PrintWriter(mSocket.getOutputStream());
        out.print("GET " + path + " HTTP/1.1\r\n");
        out.print("Upgrade: websocket\r\n");
        out.print("Connection: Upgrade\r\n");
        out.print("Host: " + mURI.getHost() + "\r\n");
        out.print("Origin: " + (origin != null ? origin.toString() : "unknown") + "\r\n");
        out.print("Sec-WebSocket-Key: " + createSecret() + "\r\n");
        out.print("Sec-WebSocket-Version: 13\r\n");
        if (mExtraHeaders != null) {
          for (NameValuePair pair : mExtraHeaders) {
            out.print(String.format("%s: %s\r\n", pair.getName(), pair.getValue()));
          }
        }
        out.print("\r\n");
        out.flush();

        HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream());

        // Read HTTP response status line.

        StatusLine statusLine = parseStatusLine(readLine(stream));

        if (statusLine == null) {
          throw new HttpException("Received no reply from server.");
        } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
          throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        // Read HTTP response headers.
        String line;
        while (!TextUtils.isEmpty(line = readLine(stream))) {
          Header header = parseHeader(line);
          if (header.getName().equals("Sec-WebSocket-Accept")) {
            // FIXME: Verify the response...
          }
        }

        mListener.onConnect();

        // Now decode websocket frames.
        mParser.start(stream);

      } catch (EOFException ex) {
        Log.d("WebSocket EOF!", ex);
        mListener.onDisconnect(0, "EOF");

      } catch (SSLException ex) {
        // Connection reset by peer
        Log.d("Websocket SSL error!", ex);
        mListener.onDisconnect(0, "SSL");

      } catch (Exception e) {
        mListener.onError(e);
      }
    }
  });
  mThread.start();
}
 
Example 13
Source File: TesterAjpNonBlockingClient.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testNonBlockingWrite() throws Exception {

    SocketFactory factory = SocketFactory.getDefault();
    Socket s = factory.createSocket("localhost", 80);

    ByteChunk result = new ByteChunk();
    OutputStream os = s.getOutputStream();
    os.write(("GET /examples/servlets/nonblocking/numberwriter HTTP/1.1\r\n" +
            "Host: localhost\r\n" +
            "Connection: close\r\n" +
            "\r\n").getBytes(StandardCharsets.ISO_8859_1));
    os.flush();

    InputStream is = s.getInputStream();
    byte[] buffer = new byte[8192];

    int read = 0;
    int readSinceLastPause = 0;
    while (read != -1) {
        read = is.read(buffer);
        if (read > 0) {
            result.append(buffer, 0, read);
        }
        readSinceLastPause += read;
        if (readSinceLastPause > 40000) {
            readSinceLastPause = 0;
            Thread.sleep(500);
        }
    }

    os.close();
    is.close();
    s.close();

    // Validate the result
    String resultString = result.toString();
    log.info("Client read " + resultString.length() + " bytes");

    System.out.println(resultString);

    Assert.assertTrue(resultString.contains("00000000000000010000"));
}
 
Example 14
Source File: BlockingClientManager.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public BlockingClientManager() {
    socketFactory = SocketFactory.getDefault();
}
 
Example 15
Source File: MagicKernelManager.java    From beakerx with Apache License 2.0 4 votes vote down vote up
private void initClientServer() {
  this.clientServer = new ClientServer(port, GatewayServer.defaultAddress(), pythonPort,
          GatewayServer.defaultAddress(), GatewayServer.DEFAULT_CONNECT_TIMEOUT,
          GatewayServer.DEFAULT_READ_TIMEOUT, ServerSocketFactory.getDefault(), SocketFactory.getDefault(), null);
}
 
Example 16
Source File: TCPNetSyslogWriter.java    From syslog4j-graylog2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected SocketFactory obtainSocketFactory() {
    return SocketFactory.getDefault();
}
 
Example 17
Source File: WebSocketClient.java    From Yahala-Messenger with MIT License 4 votes vote down vote up
public void connect() {
    if (mThread != null && mThread.isAlive()) {
        return;
    }

    mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String secret = createSecret();

                int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getScheme().equals("wss") ? 443 : 80);

                String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
                if (!TextUtils.isEmpty(mURI.getQuery())) {
                    path += "?" + mURI.getQuery();
                }

                String originScheme = mURI.getScheme().equals("wss") ? "https" : "http";
                URI origin = new URI(originScheme, "//" + mURI.getHost(), null);

                SocketFactory factory = mURI.getScheme().equals("wss") ? getSSLSocketFactory() : SocketFactory.getDefault();
                mSocket = factory.createSocket(mURI.getHost(), port);

                PrintWriter out = new PrintWriter(mSocket.getOutputStream());
                out.print("GET " + path + " HTTP/1.1\r\n");
                out.print("Upgrade: websocket\r\n");
                out.print("Connection: Upgrade\r\n");
                out.print("Host: " + mURI.getHost() + "\r\n");
                out.print("Origin: " + origin.toString() + "\r\n");
                out.print("Sec-WebSocket-Key: " + secret + "\r\n");
                out.print("Sec-WebSocket-Version: 13\r\n");
                if (mExtraHeaders != null) {
                    for (NameValuePair pair : mExtraHeaders) {
                        out.print(String.format("%s: %s\r\n", pair.getName(), pair.getValue()));
                    }
                }
                out.print("\r\n");
                out.flush();

                HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream());

                // Read HTTP response status line.
                StatusLine statusLine = parseStatusLine(readLine(stream));
                if (statusLine == null) {
                    throw new HttpException("Received no reply from server.");
                } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
                    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
                }

                // Read HTTP response headers.
                String line;
                boolean validated = false;

                while (!TextUtils.isEmpty(line = readLine(stream))) {
                    Header header = parseHeader(line);
                    if (header.getName().equals("Sec-WebSocket-Accept")) {
                        String expected = createSecretValidation(secret);
                        String actual = header.getValue().trim();

                        if (!expected.equals(actual)) {
                            throw new HttpException("Bad Sec-WebSocket-Accept header value.");
                        }

                        validated = true;
                    }
                }

                if (!validated) {
                    throw new HttpException("No Sec-WebSocket-Accept header.");
                }

                mListener.onConnect();

                // Now decode websocket frames.
                mParser.start(stream);

            } catch (EOFException ex) {
                Log.d(TAG, "WebSocket EOF!", ex);
                mListener.onDisconnect(0, "EOF");

            } catch (SSLException ex) {
                // Connection reset by peer
                Log.d(TAG, "Websocket SSL error!", ex);
                mListener.onDisconnect(0, "SSL");

            } catch (Exception ex) {
                mListener.onError(ex);
            }
        }
    });
    mThread.start();
}
 
Example 18
Source File: NetUtils.java    From RDFS with Apache License 2.0 3 votes vote down vote up
/**
 * Get the default socket factory as specified by the configuration
 * parameter <tt>hadoop.rpc.socket.factory.default</tt>
 * 
 * @param conf the configuration
 * @return the default socket factory as specified in the configuration or
 *         the JVM default socket factory if the configuration does not
 *         contain a default socket factory property.
 */
public static SocketFactory getDefaultSocketFactory(Configuration conf) {

  String propValue = conf.get("hadoop.rpc.socket.factory.class.default");
  if ((propValue == null) || (propValue.length() == 0))
    return SocketFactory.getDefault();

  return getSocketFactoryFromProperty(conf, propValue);
}
 
Example 19
Source File: MongoClientConfiguration.java    From mongodb-async-driver with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the socket factory to use in making connections to the MongoDB
 * server. Setting the SocketFactory to null resets the factory to the
 * default.
 * <p>
 * Defaults to {@link SocketFactory#getDefault()
 * SocketFactory.getDefault().}
 * </p>
 * <p>
 * For SSL based connections this can be an appropriately configured
 * {@link javax.net.ssl.SSLSocketFactory}.
 * </p>
 * <p>
 * Other {@link Socket} and {@link InetSocketAddress} implementations with
 * an appropriate {@link SocketFactory} implementation can be used with the
 * driver. The driver only ever calls the
 * {@link SocketFactory#createSocket()} method and then connects the socket
 * passing the server's {@link InetSocketAddress}.
 * </p>
 * <p>
 * See the <a href="http://code.google.com/p/junixsocket">junixsocket
 * Project</a> for an example of a {@link Socket} and
 * {@link InetSocketAddress} implementations for UNIX Domain Sockets that
 * can be wrapped with SocketFactory similar to the following:<blockquote>
 * <code><pre>
 *  public class AFUNIXSocketFactory extends SocketFactory {
 *      public Socket createSocket() throws java.io.IOException {
 *          return new org.newsclub.net.unix.AFUNIXSocket.newInstance();
 *      }
 * 
 *      public Socket createSocket(String host, int port) throws SocketException {
 *          throw new SocketException("AFUNIX socket does not support connections to a host/port");
 *      }
 * 
 *      public Socket createSocket(InetAddress host, int port) throws SocketException {
 *          throw new SocketException("AFUNIX socket does not support connections to a host/port");
 *      }
 * 
 *      public Socket createSocket(String host, int port, InetAddress localHost,
 *              int localPort) throws SocketException {
 *          throw new SocketException("AFUNIX socket does not support connections to a host/port");
 *      }
 * 
 *      public Socket createSocket(InetAddress address, int port,
 *              InetAddress localAddress, int localPort) throws SocketException {
 *          throw new SocketException("AFUNIX socket does not support connections to a host/port");
 *      }
 *  }
 * </pre></code></blockquote>
 * </p>
 *
 * @param socketFactory
 *            The socketFactory value.
 *
 * @see <a href="http://code.google.com/p/junixsocket">junixsocket
 *      Project</a>
 */
public void setSocketFactory(final SocketFactory socketFactory) {
    final SocketFactory old = mySocketFactory;

    if (socketFactory == null) {
        mySocketFactory = SocketFactory.getDefault();
    }
    else {
        mySocketFactory = socketFactory;
    }

    myPropSupport.firePropertyChange("socketFactory", old, mySocketFactory);
}
 
Example 20
Source File: NetUtils.java    From hadoop-gpu with Apache License 2.0 3 votes vote down vote up
/**
 * Get the default socket factory as specified by the configuration
 * parameter <tt>hadoop.rpc.socket.factory.default</tt>
 * 
 * @param conf the configuration
 * @return the default socket factory as specified in the configuration or
 *         the JVM default socket factory if the configuration does not
 *         contain a default socket factory property.
 */
public static SocketFactory getDefaultSocketFactory(Configuration conf) {

  String propValue = conf.get("hadoop.rpc.socket.factory.class.default");
  if ((propValue == null) || (propValue.length() == 0))
    return SocketFactory.getDefault();

  return getSocketFactoryFromProperty(conf, propValue);
}