List of usage examples for javax.net.ssl SSLSocketFactory getDefault
public static SocketFactory getDefault()
From source file:net.douglasthrift.bigscreenbot.BigScreenBot.java
private BigScreenBot(boolean verbose) { super();/*from www . j ava 2 s . co m*/ this.verbose = verbose; try { settings.load(); remote = new Remote(verbose, settings); } catch (IOException exception) { error(exception, 1); } catch (GeneralSecurityException exception) { error(exception, 1); } setAutoNickChange(true); setFinger("Big Screen Bot"); setMessageDelay(0); setVersion(String.format("Big Screen Bot (%1$s)", System.getProperty("os.name"))); if (settings.getBooleanProperty("ssl", false)) if (settings.getBooleanProperty("verify", true)) setSocketFactory(SSLSocketFactory.getDefault()); else try { setSocketFactory(DummySSLSocketFactory.fromKeyManagers(null)); } catch (GeneralSecurityException exception) { error(exception, 1); } setLogin(System.getProperty("user.name")); setName(settings.getProperty("nick", "bigscreenbot")); setVerbose(verbose); channels = new HashSet<String>(settings.getListProperty("channels", new ArrayList<String>())); for (String admin : settings.getListProperty("admins")) admins.add(compileNickMask(admin)); for (String ban : settings.getListProperty("bans", new ArrayList<String>())) bans.put(ban, compileNickMask(ban)); commands.put("ban", new Command(true, PRIVATE, "[mask...]", "block nick masks from using commands") { @Override public void execute(String channel, String sender, boolean admin, String argument) { String[] arguments = StringUtils.split(argument); if (arguments.length == 0) { listBans(channel, sender); return; } synchronized (bans) { for (String ban : arguments) if (bans.put(ban, compileNickMask(ban)) == null) sendMessage(channel, sender, String.format("banned nick mask (\"%1$s\")", ban)); else sendMessage(channel, sender, String.format("nick mask (\"%1$s\") already banned", ban)); storeBans(channel, sender); } } }); commands.put("googletv", new Command(false, BOTH, "url [device]", "fling url to a Google TV device") { @Override public void execute(final String channel, final String sender, boolean admin, String argument) { final String[] arguments = StringUtils.split(argument, null, 2); if (arguments.length == 0) { help(channel, sender, admin, "googletv"); return; } if (!isValidURL(arguments[0])) { sendMessage(channel, sender, String.format("invalid URL (\"%1$s\")", arguments[0])); return; } if (arguments.length == 2) sendMessage(channel, sender, String.format("flinging URL (\"%1$s\") to device (\"%2$s\")...", arguments[0], arguments[1])); else sendMessage(channel, sender, String.format("flinging URL (\"%1$s\") to device(s)...", arguments[0])); new Thread() { @Override public void run() { if (arguments.length == 2) remote.fling(arguments[1], arguments[0]); else remote.fling(arguments[0]); sendMessage(channel, sender, String.format("flung URL (\"%1$s\") to device(s)", arguments[0])); } }.start(); } }); commands.put("help", new Command(false, PRIVATE, "[command]", "show this help message") { @Override public void execute(String channel, String sender, boolean admin, String arguments) { String argument = null; Command command = null; try { argument = StringUtils.split(arguments, null, 2)[0].toLowerCase(); if (argument.startsWith("!")) argument = argument.substring(1); command = commands.get(argument); } catch (ArrayIndexOutOfBoundsException exception) { } sendMessage(channel, sender, Colors.BOLD + String.format("%1$-11s %2$-23s %3$-15s %4$s", "command", "arguments", "access", "description") + Colors.NORMAL); if (command != null) help(channel, sender, admin, argument, command); else for (Map.Entry<String, Command> nameCommand : commands.entrySet()) help(channel, sender, admin, nameCommand.getKey(), nameCommand.getValue()); } private void help(String channel, String sender, boolean admin, String name, Command command) { boolean unavailable = command.isAdmin() && !admin; String access; switch (command.getAccess()) { case CHANNEL: access = "channel"; break; case PRIVATE: access = "private"; break; case BOTH: default: access = "channel/private"; break; } sendMessage(channel, sender, (unavailable ? Colors.UNDERLINE : "") + String.format("%1$-11s %2$-23s %3$-15s %4$s", name, command.getArguments(), access, command.getDescription()) + (unavailable ? Colors.NORMAL : "")); } }); commands.put("join", new Command(true, PRIVATE, "channel", "join a channel") { @Override public void execute(String channel, String sender, boolean admin, String arguments) { String argument; try { argument = StringUtils.split(arguments, null, 2)[0]; } catch (ArrayIndexOutOfBoundsException exception) { help(channel, sender, admin, "join"); return; } joinChannel(argument); synchronized (channels) { channels.add(argument); storeChannels(channel, sender); } sendMessage(channel, sender, String.format("joined channel (\"%1$s\")", argument)); } }); commands.put("pair", new Command(true, PRIVATE, "[device [code]]", "pair with a Google TV device") { @Override public void execute(final String channel, final String sender, boolean admin, String argument) { final String[] arguments = StringUtils.split(argument, null, 2); switch (arguments.length) { case 0: sendMessage(channel, sender, "searching for devices to pair with..."); new Thread() { @Override public void run() { List<String> devices; devices = remote.listDevices(); if (devices.isEmpty()) { sendMessage(channel, sender, "there are no devices to pair with"); return; } sendMessage(channel, sender, Colors.BOLD + "devices" + Colors.NORMAL); for (String device : devices) sendMessage(channel, sender, device); } }.start(); break; case 1: sendMessage(channel, sender, String.format("starting to pair with device (\"%1$s\")...", arguments[0])); new Thread() { @Override public void run() { try { if (remote.startPairDevice(arguments[0], new Remote.Pairing() { @Override public void prompt() { sendMessage(channel, sender, String.format( "enter the code from the device (\"%1$s\") to finish pairing", arguments[0])); } @Override public void interrupted(InterruptedException exception) { sendMessage(channel, sender, String.format( "pairing with device (\"%1$s\") interrupted", arguments[0])); } })) sendMessage(channel, sender, String.format("paired with device (\"%1$s\")", arguments[0])); } catch (MalformedURLException exception) { sendMessage(channel, sender, String.format("invalid device name (\"%1$s\")", arguments[0])); } catch (UnknownHostException exception) { sendMessage(channel, sender, String.format("could not find device (\"%1$s\")", arguments[0])); } catch (IOException exception) { error(channel, sender, exception); } catch (PoloException exception) { error(channel, sender, exception); } } }.start(); break; default: sendMessage(channel, sender, String.format("finishing pairing with device (\"%1$s\")...", arguments[0])); new Thread() { @Override public void run() { try { if (!remote.finishPairDevice(arguments[0], arguments[1])) sendMessage(channel, sender, String.format( "have not started pairing with device (\"%1$s\")", arguments[0])); } catch (MalformedURLException exception) { sendMessage(channel, sender, String.format("invalid device name (\"%1$s\")", arguments[0])); } } }.start(); } } }); commands.put("part", new Command(true, PRIVATE, "channel [message]", "part from a channel") { @Override public void execute(String channel, String sender, boolean admin, String argument) { String[] arguments = StringUtils.split(argument, null, 2); if (arguments.length == 0) { help(channel, sender, admin, "part"); return; } if (arguments.length == 2) partChannel(arguments[0], arguments[1]); else partChannel(arguments[0]); synchronized (channels) { channels.remove(arguments[0]); storeChannels(channel, sender); } sendMessage(channel, sender, String.format("parted channel (\"%1$s\")", arguments[0])); } }); commands.put("quit", new Command(true, PRIVATE, "[message]", "quit and do not come back") { @Override public void execute(String channel, String sender, boolean admin, String argument) { synchronized (action) { action = Action.QUIT; } quitServer(!argument.isEmpty() ? argument : "oh no!"); } }); commands.put("restart", new Command(true, PRIVATE, "", "quit and join running more up to date code") { @Override public void execute(String channel, String sender, boolean admin, String argument) { synchronized (action) { action = Action.RESTART; } quitServer("restarting"); } }); commands.put("say", new Command(true, PRIVATE, "nick|channel message", "say message to nick or channel") { @Override public void execute(String channel, String sender, boolean admin, String argument) { String[] arguments = StringUtils.split(argument, null, 2); if (arguments.length != 2) { help(channel, sender, admin, "say"); return; } if (arguments[0].equalsIgnoreCase(getNick())) { sendMessage(channel, sender, "nice try"); return; } sendMessage(arguments[0], arguments[1]); sendMessage(channel, sender, String.format("successfully sent message (\"%1$s\") to nick/channel (\"%2$s\")", arguments[1], arguments[0])); } }); commands.put("unban", new Command(true, PRIVATE, "[mask...]", "allow blocked nick masks to use commands again") { @Override public void execute(String channel, String sender, boolean admin, String argument) { String[] arguments = StringUtils.split(argument); if (arguments.length == 0) { listBans(channel, sender); return; } synchronized (bans) { for (String ban : arguments) if (bans.remove(ban) != null) sendMessage(channel, sender, String.format("unbanned nick mask (\"%1$s\")", ban)); else sendMessage(channel, sender, String.format("nick mask (\"%1$s\") already unbanned", ban)); storeBans(channel, sender); } } }); try { connect(settings.getProperty("server"), settings.getIntegerProperty("port", 6667)); } catch (IOException exception) { error(exception, 1); } catch (IrcException exception) { error(exception, 1); } }
From source file:com.microsoft.tfs.core.config.httpclient.internal.DefaultSSLProtocolSocketFactory.java
private SSLSocketFactory getSocketFactory(final HttpConnectionParams params) { if (isEnabled()) { try {/* w ww . ja v a2s .co m*/ SSLSocketFactory socketFactory; if (params.getBooleanParameter(ACCEPT_UNTRUSTED_CERTIFICATES_PARAMETER, false)) { socketFactory = getSelfSignedSocketFactory(params); } else { socketFactory = getStandardSocketFactory(params); } if (socketFactory != null) { return socketFactory; } } catch (final Exception e) { log.warn("Could not create SSL socket factory, falling back to default", e); //$NON-NLS-1$ } } else { log.info("SSLSocketFactory is disabled, falling back to system"); //$NON-NLS-1$ } return (SSLSocketFactory) SSLSocketFactory.getDefault(); }
From source file:org.apache.nutch.protocol.http.HttpResponse.java
/** * Default public constructor.//from ww w . j a v a2 s . c om * * @param http * @param url * @param datum * @throws ProtocolException * @throws IOException */ public HttpResponse(HttpBase http, URL url, CrawlDatum datum) throws ProtocolException, IOException { this.http = http; this.url = url; this.orig = url.toString(); this.base = url.toString(); Scheme scheme = null; if ("http".equals(url.getProtocol())) { scheme = Scheme.HTTP; } else if ("https".equals(url.getProtocol())) { scheme = Scheme.HTTPS; } else { throw new HttpException("Unknown scheme (not http/https) for url:" + url); } if (Http.LOG.isTraceEnabled()) { Http.LOG.trace("fetching " + url); } String path = "".equals(url.getFile()) ? "/" : url.getFile(); // some servers will redirect a request with a host line like // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they // don't want the :80... LOG.info("Fetching " + url.toString()); String host = url.getHost(); int port; String portString; if (url.getPort() == -1) { if (scheme == Scheme.HTTP) { port = 80; } else { port = 443; } portString = ""; } else { port = url.getPort(); portString = ":" + port; } Socket socket = null; try { socket = new Socket(); // create the socket socket.setSoTimeout(http.getTimeout()); // connect String sockHost = http.useProxy(url) ? http.getProxyHost() : host; int sockPort = http.useProxy(url) ? http.getProxyPort() : port; InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort); socket.connect(sockAddr, http.getTimeout()); if (scheme == Scheme.HTTPS) { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true); sslsocket.setUseClientMode(true); // Get the protocols and ciphers supported by this JVM Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols())); Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites())); // Intersect with preferred protocols and ciphers protocols.retainAll(http.getTlsPreferredProtocols()); ciphers.retainAll(http.getTlsPreferredCipherSuites()); sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()])); sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); sslsocket.startHandshake(); socket = sslsocket; } this.conf = http.getConf(); if (sockAddr != null && conf.getBoolean("store.ip.address", false) == true) { headers.add("_ip_", sockAddr.getAddress().getHostAddress()); } // make request OutputStream req = socket.getOutputStream(); StringBuffer reqStr = new StringBuffer("GET "); if (http.useProxy(url)) { reqStr.append(url.getProtocol() + "://" + host + portString + path); } else { reqStr.append(path); } reqStr.append(" HTTP/1.0\r\n"); reqStr.append("Host: "); reqStr.append(host); reqStr.append(portString); reqStr.append("\r\n"); reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n"); String userAgent = http.getUserAgent(); if ((userAgent == null) || (userAgent.length() == 0)) { if (Http.LOG.isErrorEnabled()) { Http.LOG.error("User-agent is not set!"); } } else { reqStr.append("User-Agent: "); reqStr.append(userAgent); reqStr.append("\r\n"); } reqStr.append("Accept-Language: "); reqStr.append(this.http.getAcceptLanguage()); reqStr.append("\r\n"); reqStr.append("Accept: "); reqStr.append(this.http.getAccept()); reqStr.append("\r\n"); if (http.isIfModifiedSinceEnabled() && datum.getModifiedTime() > 0) { reqStr.append("If-Modified-Since: " + HttpDateFormat.toString(datum.getModifiedTime())); reqStr.append("\r\n"); } reqStr.append("\r\n"); // store the request in the metadata? if (conf.getBoolean("store.http.request", false) == true) { headers.add("_request_", reqStr.toString()); } byte[] reqBytes = reqStr.toString().getBytes(); req.write(reqBytes); req.flush(); LOG.info("Processing response.."); PushbackInputStream in = // process response new PushbackInputStream(new BufferedInputStream(socket.getInputStream(), Http.BUFFER_SIZE), Http.BUFFER_SIZE); StringBuffer line = new StringBuffer(); // store the http headers verbatim if (conf.getBoolean("store.http.headers", false) == true) { httpHeaders = new StringBuffer(); } headers.add("nutch.fetch.time", Long.toString(System.currentTimeMillis())); boolean haveSeenNonContinueStatus = false; while (!haveSeenNonContinueStatus) { // parse status code line this.code = parseStatusLine(in, line); if (httpHeaders != null) httpHeaders.append(line).append("\n"); // parse headers parseHeaders(in, line, httpHeaders); haveSeenNonContinueStatus = code != 100; // 100 is "Continue" } if (httpHeaders != null) { headers.add("_response.headers_", httpHeaders.toString()); } String transferEncoding = getHeader(Response.TRANSFER_ENCODING); LOG.info("Transfer Encoding for " + url + ":" + transferEncoding); if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) { readChunkedContent(in, line); } else { readPlainContent(in); } String contentEncoding = getHeader(Response.CONTENT_ENCODING); if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) { content = http.processGzipEncoded(content, url); } else if ("deflate".equals(contentEncoding)) { content = http.processDeflateEncoded(content, url); } else { if (Http.LOG.isTraceEnabled()) { Http.LOG.trace("fetched " + content.length + " bytes from " + url); } } LOG.info("Checking URL:" + url.toString()); //check if url contains google drive string if (url.toString().toLowerCase().contains("https://drive.google.com/")) { //split into two string separated by '=' to get the article id LOG.info("Google Drive URL Detected!"); String[] parts = url.toString().split("="); url = new URL("http://drive.google.com/uc?export=download&id=" + parts[1]); LOG.info("New URL:" + url.toString()); this.http = http; this.url = url; this.orig = url.toString(); this.base = url.toString(); HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url.toString()); int statusCode = client.executeMethod(method); content = method.getResponseBody(); LOG.info("File Size on Drive: " + content.length); // return; } LOG.info("Fetch Bytes: " + content.length + " bytes from " + url); } finally { if (socket != null) socket.close(); } }
From source file:hudson.util.NoClientBindSSLProtocolSocketFactory.java
/** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) *//*ww w. j av a 2s . c o m*/ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return SSLSocketFactory.getDefault().createSocket(host, port); }
From source file:bigbird.benchmark.BenchmarkWorker.java
public void run() { HttpResponse response = null;//w ww .j a v a 2 s . c o m DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); String hostname = targetHost.getHostName(); int port = targetHost.getPort(); if (port == -1) { port = 80; } // Populate the execution context this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost); // this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request); stats.start(); for (int i = 0; i < count; i++) { try { HttpRequest req = requestGenerator.generateRequest(count); if (!conn.isOpen()) { Socket socket = null; if ("https".equals(targetHost.getSchemeName())) { SocketFactory socketFactory = SSLSocketFactory.getDefault(); socket = socketFactory.createSocket(hostname, port); } else { socket = new Socket(hostname, port); } conn.bind(socket, params); } try { // Prepare request this.httpexecutor.preProcess(req, this.httpProcessor, this.context); // Execute request and get a response response = this.httpexecutor.execute(req, conn, this.context); // Finalize response this.httpexecutor.postProcess(response, this.httpProcessor, this.context); } catch (HttpException e) { stats.incWriteErrors(); if (this.verbosity >= 2) { System.err.println("Failed HTTP request : " + e.getMessage()); } continue; } verboseOutput(req, response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { stats.incSuccessCount(); } else { stats.incFailureCount(); continue; } HttpEntity entity = response.getEntity(); String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } long contentlen = 0; if (entity != null) { InputStream instream = entity.getContent(); int l = 0; while ((l = instream.read(this.buffer)) != -1) { stats.incTotalBytesRecv(l); contentlen += l; if (this.verbosity >= 4) { String s = new String(this.buffer, 0, l, charset); System.out.print(s); } } instream.close(); } if (this.verbosity >= 4) { System.out.println(); System.out.println(); } if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) { conn.close(); } stats.setContentLength(contentlen); } catch (IOException ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } } stats.finish(); if (response != null) { Header header = response.getFirstHeader("Server"); if (header != null) { stats.setServerName(header.getValue()); } } try { conn.close(); } catch (IOException ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } }
From source file:org.apache.nutch.protocol.s2jh.HttpResponse.java
public HttpResponse(HttpBase http, URL url, WebPage page) throws ProtocolException, IOException { conf = http.getConf();// w w w. j ava2s . c om this.http = http; this.url = url; Scheme scheme = null; if ("http".equals(url.getProtocol())) { scheme = Scheme.HTTP; } else if ("https".equals(url.getProtocol())) { scheme = Scheme.HTTPS; } else { throw new HttpException("Unknown scheme (not http/https) for url:" + url); } if (Http.LOG.isTraceEnabled()) { Http.LOG.trace("fetching " + url); } String path = "".equals(url.getFile()) ? "/" : url.getFile(); // some servers will redirect a request with a host line like // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they // don't want the :80... String host = url.getHost(); int port; String portString; if (url.getPort() == -1) { if (scheme == Scheme.HTTP) { port = 80; } else { port = 443; } portString = ""; } else { port = url.getPort(); portString = ":" + port; } Socket socket = null; try { socket = new Socket(); // create the socket socket.setSoTimeout(http.getTimeout()); // connect String sockHost = http.useProxy() ? http.getProxyHost() : host; int sockPort = http.useProxy() ? http.getProxyPort() : port; InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort); socket.connect(sockAddr, http.getTimeout()); if (scheme == Scheme.HTTPS) { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true); sslsocket.setUseClientMode(true); // Get the protocols and ciphers supported by this JVM Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols())); Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites())); // Intersect with preferred protocols and ciphers protocols.retainAll(http.getTlsPreferredProtocols()); ciphers.retainAll(http.getTlsPreferredCipherSuites()); sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()])); sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); sslsocket.startHandshake(); socket = sslsocket; } if (sockAddr != null && conf.getBoolean("store.ip.address", false) == true) { String ipString = sockAddr.getAddress().getHostAddress(); // get the ip // address page.getMetadata().put(new Utf8("_ip_"), ByteBuffer.wrap(ipString.getBytes())); } Http.LOG.debug("HTTP fetching: " + url); // make request OutputStream req = socket.getOutputStream(); StringBuffer reqStr = new StringBuffer("GET "); if (http.useProxy()) { reqStr.append(url.getProtocol() + "://" + host + portString + path); } else { reqStr.append(path); } reqStr.append(" HTTP/1.0\r\n"); reqStr.append("Host: "); reqStr.append(host); reqStr.append(portString); reqStr.append("\r\n"); reqStr.append("Accept-Encoding: x-gzip, gzip\r\n"); reqStr.append("Accept: "); reqStr.append(this.http.getAccept()); reqStr.append("\r\n"); String userAgent = http.getUserAgent(); if ((userAgent == null) || (userAgent.length() == 0)) { if (Http.LOG.isErrorEnabled()) { Http.LOG.error("User-agent is not set!"); } } else { reqStr.append("User-Agent: "); reqStr.append(userAgent); reqStr.append("\r\n"); } // if (page.isReadable(WebPage.Field.MODIFIED_TIME.getIndex())) { reqStr.append("If-Modified-Since: " + HttpDateFormat.toString(page.getModifiedTime())); reqStr.append("\r\n"); // } reqStr.append("\r\n"); byte[] reqBytes = reqStr.toString().getBytes(); req.write(reqBytes); req.flush(); PushbackInputStream in = // process response new PushbackInputStream(new BufferedInputStream(socket.getInputStream(), Http.BUFFER_SIZE), Http.BUFFER_SIZE); StringBuffer line = new StringBuffer(); boolean haveSeenNonContinueStatus = false; while (!haveSeenNonContinueStatus) { // parse status code line this.code = parseStatusLine(in, line); // parse headers parseHeaders(in, line); haveSeenNonContinueStatus = code != 100; // 100 is "Continue" } if (!url.toString().endsWith("robots.txt")) { if (readPlainContent(url.toString(), in)) { } else if (readPlainContentByHtmlunit(url)) { } else { readPlainContentByWebDriver(url); } } if (content != null && content.length > 0) { String html = charset == null ? new String(content) : new String(content, charset); //System.out.println("URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html); Http.LOG_HTML.trace("URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html); } // add headers in metadata to row if (page.getHeaders() != null) { page.getHeaders().clear(); } for (String key : headers.names()) { page.getHeaders().put(new Utf8(key), new Utf8(headers.get(key))); } } catch (Exception e) { Http.LOG.error(e.getMessage(), e); } finally { if (socket != null) socket.close(); } }
From source file:hudson.util.NoClientBindSSLProtocolSocketFactory.java
/** * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) */// w w w.ja v a2s.co m public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(socket, host, port, autoClose); }
From source file:com.appunite.websocket.WebSocket.java
/** * This method will be alive until error occur or interrupt was executed. * This method always throws some exception. (not thread safe) * //from w ww . j a v a2s. co m * @param uri * uri of websocket * @throws UnknownHostException * when could not connect to selected host * @throws IOException * thrown when I/O exception occur * @throws WrongWebsocketResponse * thrown when wrong web socket response received * @throws InterruptedException * thrown when interrupt method was invoked */ public void connect(Uri uri) throws IOException, WrongWebsocketResponse, InterruptedException { checkNotNull(uri, "Uri cannot be null"); try { synchronized (mLockObj) { checkState(State.DISCONNECTED.equals(mState), "connect could be called only if disconnected"); SocketFactory factory; if (isSsl(uri)) { factory = SSLSocketFactory.getDefault(); } else { factory = SocketFactory.getDefault(); } mSocket = factory.createSocket(); mState = State.CONNECTING; mLockObj.notifyAll(); } mSocket.connect(new InetSocketAddress(uri.getHost(), getPort(uri))); mInputStream = new WebSocketReader(mSocket.getInputStream()); mOutputStream = new WebSocketWriter(mSocket.getOutputStream()); String secret = generateHandshakeSecret(); writeHeaders(uri, secret); readHandshakeHeaders(secret); } catch (IOException e) { synchronized (mLockObj) { if (State.DISCONNECTING.equals(mState)) { throw new InterruptedException(); } else { throw e; } } } finally { synchronized (mLockObj) { mState = State.DISCONNECTED; mLockObj.notifyAll(); } } try { synchronized (mLockObj) { mState = State.CONNECTED; mLockObj.notifyAll(); } mListener.onConnected(); //noinspection InfiniteLoopStatement for (;;) { doRead(); } } catch (NotConnectedException e) { synchronized (mLockObj) { if (State.DISCONNECTING.equals(mState)) { throw new InterruptedException(); } else { throw new RuntimeException(); } } } catch (IOException e) { synchronized (mLockObj) { if (State.DISCONNECTING.equals(mState)) { throw new InterruptedException(); } else { throw e; } } } finally { synchronized (mLockObj) { while (mWriting != 0) { mLockObj.wait(); } mState = State.DISCONNECTED; mLockObj.notifyAll(); } } }
From source file:com.redhat.lightblue.mongo.config.MongoConfiguration.java
private SocketFactory getSocketFactory() { try {/* w w w . jav a 2 s .c om*/ if (noCertValidation) { LOGGER.warn("Certificate validation is off, don't use this in production"); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); return sc.getSocketFactory(); } else { return SSLSocketFactory.getDefault(); } } catch (KeyManagementException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
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 w w . jav a 2s . 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(host, port); else if (useSSL) socket = SSLSocketFactory.getDefault().createSocket(host, port); else socket = new Socket(host, port); /* * if (localaddr != null) socket.bind(new InetAddress(localaddr, * localport)); if (cto >= 0) socket.connect(new InetSocketAddress(host, * port), cto); else socket.connect(new InetSocketAddress(host, port)); */ return socket; }