List of usage examples for javax.net.ssl SSLSocketFactory getDefault
public static SocketFactory getDefault()
From source file:Messenger.TorLib.java
/** * This method makes a http GET request for the specified resource to the specified hostname. * It uses the SOCKS proxy to a connection over Tor. * The DNS lookup is also done over Tor. * This method only uses port 443 for SSL. * * @param hostname hostname for target server. * @param port port to connect to./*from ww w. j a v a2s . c om*/ * @param resource resource to lookup with GET request. * @return returns a JSON object. * @throws IOException * @throws JSONException */ public static JSONObject getJSON(String hostname, int port, String resource) throws IOException, JSONException, HttpException { //Create a SSL socket using Tor Socket socket = TorSocket(hostname, port); SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false); sslSocket.setUseClientMode(true); sslSocket.startHandshake(); openSockets.add(sslSocket); //Create the HTTP GET request and push it over the outputstream BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), "UTF8")); wr.write("GET /" + resource + " HTTP/1.0\r\n"); wr.write("Host: " + hostname + "\r\n"); wr.write("\r\n"); wr.flush(); //Listen for a response on the inputstream BufferedReader br = new BufferedReader(new InputStreamReader(sslSocket.getInputStream())); String t; boolean start = false; String output = ""; while ((t = br.readLine()) != null) { if (t.equals("")) { start = true; } if (start) { output = output + t; } } br.close(); wr.close(); sslSocket.close(); System.out.println(output); openSockets.remove(sslSocket); return new JSONObject(output); }
From source file:au.edu.monash.merc.capture.util.httpclient.ssl.StrictSSLProtocolSocketFactory.java
/** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) *//* ww w. j a va 2s. c o m*/ public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sf.createSocket(host, port, clientHost, clientPort); verifyHostname(sslSocket); return sslSocket; }
From source file:com.fluffypeople.managesieve.ManageSieveClient.java
/** * Upgrade connection to TLS. Should be called before authenticating, * especially if you are using the PLAIN scheme. * * @return ManageSieveResponse OK on successful upgrade, NO on error or if * the server doesn't support SSL/* ww w . j a va 2 s . c o m*/ * @throws IOException * @throws ParseException */ public synchronized ManageSieveResponse starttls() throws IOException, ParseException { return starttls((SSLSocketFactory) SSLSocketFactory.getDefault(), true); }
From source file:SocketFetcher.java
/** * Create a socket with the given local address and connected to * the given host and port. Use the specified connection timeout. * If a socket factory is specified, use it. Otherwise, use the * SSLSocketFactory if useSSL is true.//from w ww . j a v a 2 s. com */ private static Socket createSocket(InetAddress localaddr, int localport, String host, int port, int cto, SocketFactory sf, boolean useSSL) throws IOException { Socket socket; if (sf != null) socket = sf.createSocket(); else if (useSSL) socket = SSLSocketFactory.getDefault().createSocket(); else socket = new Socket(); if (localaddr != null) socket.bind(new InetSocketAddress(localaddr, localport)); if (cto >= 0) socket.connect(new InetSocketAddress(host, port), cto); else socket.connect(new InetSocketAddress(host, port)); return socket; }
From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java
/** * Gets the information regarding the roles and their instances * of the deployment. It makes a call to REST API and gets the XML response. * //from ww w . j a va 2 s . c om * @return XML response * @throws IOException */ public StringBuffer getRoleInfoForDeployment() throws IOException { StringBuffer response = new StringBuffer(); System.setProperty("javax.net.ssl.keyStoreType", "pkcs12"); StringBuffer keyStore = new StringBuffer(); keyStore.append(System.getProperty("java.home")); LOGGER.debug("java.home : " + keyStore.toString()); if (keyStore.length() == 0) { keyStore.append(System.getenv("JRE_HOME")); LOGGER.debug("JRE_HOME : " + keyStore.toString()); } keyStore.append(File.separator + "lib\\security\\CloudNinja.pfx"); System.setProperty("javax.net.ssl.keyStore", keyStore.toString()); System.setProperty("javax.net.debug", "ssl"); System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); // form the URL which will return the response // containing info of roles and their instances. StringBuffer strURL = new StringBuffer(host); strURL.append(subscriptionId); strURL.append("/services/hostedservices/"); strURL.append(hostedServiceName); strURL.append("/deploymentslots/"); strURL.append(deploymentType); URL url = new URL(strURL.toString()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(sslSocketFactory); connection.setRequestMethod("GET"); connection.setAllowUserInteraction(false); // set the x-ms-version in header which is a compulsory parameter to get response connection.setRequestProperty("x-ms-version", "2011-10-01"); connection.setRequestProperty("Content-type", "text/xml"); connection.setRequestProperty("accept", "text/xml"); // get the response as input stream InputStream inputStream = connection.getInputStream(); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(streamReader); String string = null; while ((string = bufferedReader.readLine()) != null) { response.append(string); } return response; }
From source file:com.lion328.xenonlauncher.minecraft.api.authentication.yggdrasil.YggdrasilMinecraftAuthenticator.java
private ResponseState sendRequest(String endpoint, String data) throws IOException, YggdrasilAPIException { URL url = new URL(serverURL, endpoint); // HttpURLConnection can only handle 2xx response code for headers // so it need to use HttpCore instead // maybe I could use an alternative like HttpClient // but for lightweight, I think is not a good idea BasicHttpEntity entity = new BasicHttpEntity(); byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); entity.setContent(new ByteArrayInputStream(dataBytes)); entity.setContentLength(dataBytes.length); HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.getFile(), HttpVersion.HTTP_1_1);//from w ww . j a va 2s . co m request.setHeader(new BasicHeader("Host", url.getHost())); request.setHeader(new BasicHeader("Content-Type", "application/json")); request.setHeader(new BasicHeader("Content-Length", Integer.toString(dataBytes.length))); request.setEntity(entity); Socket s; int port = url.getPort(); if (url.getProtocol().equals("https")) { if (port == -1) { port = 443; } s = SSLSocketFactory.getDefault().createSocket(url.getHost(), port); } else { if (port == -1) { port = 80; } s = new Socket(url.getHost(), port); } DefaultBHttpClientConnection connection = new DefaultBHttpClientConnection(8192); connection.bind(s); try { connection.sendRequestHeader(request); connection.sendRequestEntity(request); HttpResponse response = connection.receiveResponseHeader(); connection.receiveResponseEntity(response); if (!response.getFirstHeader("Content-Type").getValue().startsWith("application/json")) { throw new InvalidImplementationException("Invalid content type"); } InputStream stream = response.getEntity().getContent(); StringBuilder sb = new StringBuilder(); int b; while ((b = stream.read()) != -1) { sb.append((char) b); } return new ResponseState(response.getStatusLine().getStatusCode(), sb.toString()); } catch (HttpException e) { throw new IOException(e); } }
From source file:Messenger.TorLib.java
public static void postToURL(String hostname, int port, String postKey, String data) throws IOException { Socket socket = TorSocket(hostname, port); SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false); sslSocket.setUseClientMode(true);//ww w . ja va 2s.c om sslSocket.startHandshake(); String path = "/" + postKey; BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), "UTF8")); wr.write("POST " + path + " HTTP/1.0\r\n"); wr.write("Content-Length: " + data.length() + "\r\n"); wr.write("Content-Type: application/x-www-form-urlencoded\r\n"); wr.write("\r\n"); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(sslSocket.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); sslSocket.close(); }
From source file:mensajes.SmackCcsClient.java
/** * Connects to GCM Cloud Connection Server using the supplied credentials. * * @param senderId Your GCM project number * @param apiKey API Key of your project *//*from ww w . j a v a2s .c o m*/ public void connect(long senderId, String apiKey) throws XMPPException, IOException, SmackException { ConnectionConfiguration config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT); config.setSecurityMode(SecurityMode.enabled); config.setReconnectionAllowed(true); config.setRosterLoadedAtLogin(false); config.setSendPresence(false); config.setSocketFactory(SSLSocketFactory.getDefault()); connection = new XMPPTCPConnection(config); connection.connect(); connection.addConnectionListener(new LoggingConnectionListener()); // Handle incoming packets connection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { logger.log(Level.INFO, "Received: " + packet.toXML()); Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE); String json = gcmPacket.getJson(); try { @SuppressWarnings("unchecked") Map<String, Object> jsonObject = (Map<String, Object>) JSONValue.parseWithException(json); // present for "ack"/"nack", null otherwise Object messageType = jsonObject.get("message_type"); if (messageType == null) { // Normal upstream data message handleUpstreamMessage(jsonObject); // Send ACK to CCS String messageId = (String) jsonObject.get("message_id"); String from = (String) jsonObject.get("from"); String ack = createJsonAck(from, messageId); send(ack); } else if ("ack".equals(messageType.toString())) { // Process Ack handleAckReceipt(jsonObject); } else if ("nack".equals(messageType.toString())) { // Process Nack handleNackReceipt(jsonObject); } else if ("control".equals(messageType.toString())) { // Process control message handleControlMessage(jsonObject); } else { logger.log(Level.WARNING, "Unrecognized message type (%s)", messageType.toString()); } } catch (ParseException e) { logger.log(Level.SEVERE, "Error parsing JSON " + json, e); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to process packet", e); } } }, new PacketTypeFilter(Message.class)); // Log all outgoing packets connection.addPacketInterceptor(new PacketInterceptor() { @Override public void interceptPacket(Packet packet) { logger.log(Level.INFO, "Sent: {0}", packet.toXML()); } }, new PacketTypeFilter(Message.class)); connection.login(senderId + "@gcm.googleapis.com", apiKey); }
From source file:br.com.ulife.googlexmpp.SmackCcsClient.java
/** * Connects to GCM Cloud Connection Server using the supplied credentials. * * @param username GCM_SENDER_ID@gcm.googleapis.com * @param password API Key// w ww .j a v a 2 s . co m * @throws XMPPException */ public void connect(String username, String password) throws XMPPException { config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT); config.setSecurityMode(SecurityMode.enabled); config.setReconnectionAllowed(true); config.setRosterLoadedAtLogin(false); config.setSendPresence(false); config.setSocketFactory(SSLSocketFactory.getDefault()); // NOTE: Set to true to launch a window with information about packets // sent and received config.setDebuggerEnabled(true); // -Dsmack.debugEnabled=true XMPPConnection.DEBUG_ENABLED = true; connection = new XMPPConnection(config); connection.connect(); connection.addConnectionListener(new ConnectionListener() { @Override public void reconnectionSuccessful() { logger.info("Reconnecting.."); } @Override public void reconnectionFailed(Exception e) { logger.log(Level.INFO, "Reconnection failed.. ", e); } @Override public void reconnectingIn(int seconds) { logger.log(Level.INFO, "Reconnecting in %d secs", seconds); } @Override public void connectionClosedOnError(Exception e) { logger.log(Level.INFO, "Connection closed on error."); } @Override public void connectionClosed() { logger.info("Connection closed."); } }); // Handle incoming packets connection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { logger.log(Level.INFO, "Received: " + packet.toXML()); Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE); String json = gcmPacket.getJson(); try { @SuppressWarnings("unchecked") Map jsonObject = (Map) JSONValue.parseWithException(json); // present for "ack"/"nack", null otherwise Object messageType = jsonObject.get("message_type"); if (messageType == null) { // Normal upstream data message handleIncomingDataMessage(jsonObject); // Send ACK to CCS String messageId = jsonObject.get("message_id").toString(); String from = jsonObject.get("from").toString(); String ack = createJsonAck(from, messageId); send(ack); } else if ("ack".equals(messageType.toString())) { // Process Ack handleAckReceipt(jsonObject); } else if ("nack".equals(messageType.toString())) { // Process Nack handleNackReceipt(jsonObject); } else { logger.log(Level.WARNING, "Unrecognized message type (%s)", messageType.toString()); } } catch (ParseException e) { logger.log(Level.SEVERE, "Error parsing JSON " + json, e); } catch (Exception e) { logger.log(Level.SEVERE, "Couldn't send echo.", e); } } }, new PacketTypeFilter(Message.class)); // Log all outgoing packets connection.addPacketInterceptor(new PacketInterceptor() { @Override public void interceptPacket(Packet packet) { logger.log(Level.INFO, "Sent: {0}", packet.toXML()); } }, new PacketTypeFilter(Message.class)); connection.login(username, password); }
From source file:au.edu.monash.merc.capture.util.httpclient.ssl.StrictSSLProtocolSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the given time limit. * <p>/*from w w w. ja v a 2s . co m*/ * This method employs several techniques to circumvent the limitations of older JREs that do not support connect * timeout. When running in JRE 1.4 or above reflection is used to call Socket#connect(SocketAddress endpoint, int * timeout) method. When executing in older JREs a controller thread is executed. The controller thread attempts to * create a new socket within the given limit of time. If socket constructor does not return until the timeout * expires, the controller terminates and throws an {@link ConnectTimeoutException} * </p> * * @param host * the host name/IP * @param port * the port on the host * @param localAddress * the local host name/IP to bind the socket to * @param localPort * the port on the local machine * @param params * {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException * if an I/O error occurs while creating the socket * @throws UnknownHostException * if the IP address of the host cannot be determined */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); Socket socket = null; SocketFactory socketfactory = SSLSocketFactory.getDefault(); if (timeout == 0) { socket = socketfactory.createSocket(host, port, localAddress, localPort); } else { socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); } verifyHostname((SSLSocket) socket); return socket; }