List of usage examples for java.net Socket Socket
public Socket(InetAddress address, int port) throws IOException
From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java
public static Element sendGet(String openSearchServerURLStr, Map<String, String> paramsMap) { if (paramsMap == null) { paramsMap = new HashMap<String, String>(); }/*from ww w .j a va2 s . co m*/ 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, CharSetUtils.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 openSearchServerURL = new URL(openSearchServerURLStr); String host = openSearchServerURL.getHost(); int port = openSearchServerURL.getPort(); if (port == -1) { port = 80; } HttpHost httpHost = new HttpHost(host, port); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost); try { boolean firstParam = true; for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) { String paramName = (String) it.next(); String paramValue = (String) paramsMap.get(paramName); if (paramValue != null) { try { paramValue = URLEncoder.encode(paramValue, CharSetUtils.ISO_8859_1); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } if (firstParam) { openSearchServerURLStr += "?"; firstParam = false; } else { openSearchServerURLStr += "&"; } openSearchServerURLStr += paramName + "=" + paramValue; } if (!conn.isOpen()) { Socket socket = new Socket(host, port); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", openSearchServerURLStr); 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 (RuntimeException e) { LOGGER.severe("Error caused by text : " + entityText); throw e; } } finally { conn.close(); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:net.sbbi.upnp.ServicesEventing.java
/** * Register state variable events notification for a device service * @param service the service to register with * @param handler the registrant object//from w w w . j a v a 2 s . c om * @param subscriptionDuration subscription time in seconds, -1 for infinite time * @return an ServiceEventSubscription object instance containing all the required info or null if no subscription done * @throws IOException if some IOException error happens during coms with the device */ public ServiceEventSubscription registerEvent(UPNPService service, ServiceEventHandler handler, int subscriptionDuration) throws IOException { URL eventingLoc = service.getEventSubURL(); if (eventingLoc != null) { if (!inService) startServicesEventingThread(); String duration = Integer.toString(subscriptionDuration); if (subscriptionDuration == -1) { duration = "infinite"; } Subscription sub = lookupSubscriber(service, handler); if (sub != null) { // allready registered let's try to unregister it unRegister(service, handler); } StringBuffer packet = new StringBuffer(64); packet.append("SUBSCRIBE ").append(eventingLoc.getFile()).append(" HTTP/1.1\r\n"); packet.append("HOST: ").append(eventingLoc.getHost()).append(":").append(eventingLoc.getPort()) .append("\r\n"); packet.append("CALLBACK: <http://").append(InetAddress.getLocalHost().getHostAddress()).append(":") .append(daemonPort).append("").append(eventingLoc.getFile()).append(">\r\n"); packet.append("NT: upnp:event\r\n"); packet.append("Connection: close\r\n"); packet.append("TIMEOUT: Second-").append(duration).append("\r\n\r\n"); Socket skt = new Socket(eventingLoc.getHost(), eventingLoc.getPort()); skt.setSoTimeout(30000); // 30 secs timeout according to the specs if (log.isDebugEnabled()) log.debug(packet); OutputStream out = skt.getOutputStream(); out.write(packet.toString().getBytes()); out.flush(); InputStream in = skt.getInputStream(); StringBuffer data = new StringBuffer(); int readen = 0; byte[] buffer = new byte[256]; while ((readen = in.read(buffer)) != -1) { data.append(new String(buffer, 0, readen)); } in.close(); out.close(); skt.close(); if (log.isDebugEnabled()) log.debug(data.toString()); if (data.toString().trim().length() > 0) { HttpResponse resp = new HttpResponse(data.toString()); if (resp.getHeader().startsWith("HTTP/1.1 200 OK")) { String sid = resp.getHTTPHeaderField("SID"); String actualTimeout = resp.getHTTPHeaderField("TIMEOUT"); int durationTime = 0; // actualTimeout = Second-xxx or Second-infinite if (!actualTimeout.equalsIgnoreCase("Second-infinite")) { durationTime = Integer.parseInt(actualTimeout.substring(7)); } sub = new Subscription(); sub.handler = handler; sub.sub = new ServiceEventSubscription(service.getServiceType(), service.getServiceId(), service.getEventSubURL(), sid, skt.getInetAddress(), durationTime); synchronized (registered) { registered.add(sub); } return sub.sub; } } } return null; }
From source file:UniqueInstance.java
/** * Envoie un message l'instance de l'application dj ouverte. *//*from ww w .j a va2 s . c o m*/ private void send() { PrintWriter pw = null; try { /* On se connecte sur la machine locale. */ Socket socket = new Socket("localhost", port); /* On dfinit un PrintWriter pour crire sur la sortie de la socket. */ pw = new PrintWriter(socket.getOutputStream()); /* On crit le message sur la socket. */ pw.write(message); } catch (IOException e) { Logger.getLogger("UniqueInstance").warning("criture sur flux de sortie de la socket chou."); } finally { if (pw != null) { pw.close(); } } }
From source file:com.csipsimple.wizards.impl.MondotalkCreate.java
private boolean retrieveCaptcha() { String ip;/* w ww. j av a2 s . co m*/ try { Socket socket = new Socket("api001.mondotalk.com", 80); ip = socket.getLocalAddress().toString(); } catch (Exception e) { Log.e(THIS_FILE, "Can't get local ip address", e); ip = "127.0.0.1"; } try { // No SOAP lib.... bourrinage ! String requestURL = "https://api001.mondotalk.com/webservices/captcha.php"; HttpPost httpPost = new HttpPost(requestURL); httpPost.addHeader("SOAPAction", "\"Captcha\""); httpPost.addHeader("Content-Type", "text/xml"); // prepare POST body String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<SOAP-ENV:Envelope " + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " + " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"" + " xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" " + " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"" + " xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\" >" + "<SOAP-ENV:Body>" + "<Captcha SOAP-ENC:root=\"1\">" + "<v1 xsi:type=\"xsd:string\">" + API_KEY + "</v1>" + "<v2 xsi:type=\"xsd:string\">" + ip + "</v2>" + "<v3 xsi:type=\"xsd:string\">520</v3>" + "<v4 xsi:type=\"xsd:string\">200</v4>" + "</Captcha>" + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>"; // set POST body HttpEntity entity; entity = new StringEntity(body); httpPost.setEntity(entity); HttpClient httpClient = new DefaultHttpClient(); // Create a response handler HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { InputStreamReader isr = new InputStreamReader(httpResponse.getEntity().getContent()); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { if (!TextUtils.isEmpty(line)) { Matcher matcher = soapResultPattern.matcher(line); if (matcher.matches()) { String strValue = matcher.group(1).trim(); if (!TextUtils.isEmpty(strValue)) { String[] strValues = strValue.split("\\|"); if (strValues.length > 1) { captchaUrl = strValues[0]; captchaKey = strValues[1]; } } break; } } } if (TextUtils.isEmpty(captchaKey)) { return false; } Log.d(THIS_FILE, "Captcha retrieved " + captchaKey + " and " + captchaUrl); captchaBitmap = BitmapFactory.decodeStream((new URL(captchaUrl)).openConnection().getInputStream()); mHander.sendEmptyMessage(MSG_CAPTCHA_LOADED); } else { Log.e(THIS_FILE, "Something went wrong while retrieving the captcha webservice "); } } catch (Exception e) { Log.e(THIS_FILE, "Something went wrong while retrieving the captcha", e); } return false; }
From source file:com.adito.jdbc.hsqldb.EmbeddedHSQLDBServer.java
void waitForServerToStop() { if (serverMode) { Socket s = null;/*from w w w. j a v a 2 s. c o m*/ String addr = server.getAddress().equals("0.0.0.0") ? "127.0.0.1" : server.getAddress(); if (log.isInfoEnabled()) log.info("Waiting for HSQLDB to stop accepting connections on " + addr + ":" + server.getPort()); int i = 0; for (; i < 30; i++) { try { s = new Socket(addr, server.getPort()); try { s.close(); } catch (Exception e) { e.printStackTrace(); } s = null; try { Thread.sleep(1000); } catch (InterruptedException ie) { } } catch (IOException ioe) { break; } finally { if (s != null) { try { s.close(); } catch (Exception e) { } s = null; } } } if (i == 30) { throw new IllegalStateException("The HSQLDB server has not stopped after 30 seconds."); } else { if (log.isInfoEnabled()) log.info("HSQLDB is now stopped."); } } }
From source file:edu.berkeley.sparrow.examples.BBackend.java
private void launchBatching() { try {/*from w w w . j a va 2 s.c o m*/ Socket toClient = new Socket(appClientAdress, appClientPortNumber); batchingPr = new Batching(batchingDelay, toClient, LOG); batchingTh = new Thread(batchingPr); batchingTh.start(); } catch (UnknownHostException e) { LOG.error("LaunchBatching - Unknown Host"); e.printStackTrace(); } catch (IOException e) { LOG.error("LaunchBatching - IOException"); e.printStackTrace(); } }
From source file:org.alfresco.webservice.util.ContentUtils.java
/** * Streams content into the repository. Once done a content details string is returned and this can be used to update * a content property in a CML statement. * // w ww. j av a 2s .c om * @param file the file to stream into the repository * @param host the host name of the destination repository * @param port the port name of the destination repository * @param webAppName the name of the target web application (default 'alfresco') * @param mimetype the mimetype of the file, ignored if null * @param encoding the encoding of the file, ignored if null * @return the content data that can be used to set the content property in a CML statement */ @SuppressWarnings("deprecation") public static String putContent(File file, String host, int port, String webAppName, String mimetype, String encoding) { String result = null; try { String url = "/" + webAppName + "/upload/" + URLEncoder.encode(file.getName(), "UTF-8") + "?ticket=" + AuthenticationUtils.getTicket(); if (mimetype != null) { url = url + "&mimetype=" + mimetype; } if (encoding != null) { url += "&encoding=" + encoding; } String request = "PUT " + url + " HTTP/1.1\n" + "Cookie: JSESSIONID=" + AuthenticationUtils.getAuthenticationDetails().getSessionId() + ";\n" + "Content-Length: " + file.length() + "\n" + "Host: " + host + ":" + port + "\n" + "Connection: Keep-Alive\n" + "\n"; // Open sockets and streams Socket socket = new Socket(host, port); DataOutputStream os = new DataOutputStream(socket.getOutputStream()); DataInputStream is = new DataInputStream(socket.getInputStream()); try { if (socket != null && os != null && is != null) { // Write the request header os.writeBytes(request); // Stream the content onto the server InputStream fileInputStream = new FileInputStream(file); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = fileInputStream.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); byteCount += bytesRead; } os.flush(); fileInputStream.close(); // Read the response and deal with any errors that might occur boolean firstLine = true; String responseLine; while ((responseLine = is.readLine()) != null) { if (firstLine == true) { if (responseLine.contains("200") == true) { firstLine = false; } else if (responseLine.contains("401") == true) { throw new RuntimeException( "Content could not be uploaded because invalid credentials have been supplied."); } else if (responseLine.contains("403") == true) { throw new RuntimeException( "Content could not be uploaded because user does not have sufficient privileges."); } else { throw new RuntimeException( "Error returned from upload servlet (" + responseLine + ")"); } } else if (responseLine.contains("contentUrl") == true) { result = responseLine; break; } } } } finally { try { // Close the streams and socket if (os != null) { os.close(); } if (is != null) { is.close(); } if (socket != null) { socket.close(); } } catch (Exception e) { throw new RuntimeException("Error closing sockets and streams", e); } } } catch (Exception e) { throw new RuntimeException("Error writing content to repository server", e); } return result; }
From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java
@Test public void testReadTimeout() throws IOException, InterruptedException { SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder() .withConfig(SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111) .withNbServiceConfig(NbServiceConfig.Builder.builder().withIoTaskTimeoutMs(10l) .withIoTaskTimeoutCheckPeriodMs(2l).withSelectorTimeoutMs(2l).build()) .build())//from w ww.j a v a 2 s.c o m .withConnectorFactory(TcpConnectorFactory.Builder.builder() .withConnectedSocketTask(new TcpConnectTestHandler()).build()) .build(); simpleNbServer.start(); String message1 = "this is message1"; try { Socket socket = new Socket("localhost", 1111); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); out.write((message1 + '\n').getBytes(StandardCharsets.UTF_8)); reader.readLine(); // message1 Thread.sleep(100); String nextLine = null; try { out.write((message1 + '\n').getBytes(StandardCharsets.UTF_8)); nextLine = reader.readLine(); } catch (SocketException e) { } Assert.assertNull(nextLine); } finally { simpleNbServer.shutdown(); } }
From source file:com.ctsim.dmi.App.java
private void initConnection1() { Iterator<String> keys; String key;// www . j ava 2s . c o m boolean isRegiester = false; parser = new JSONParser(); try { socket = new Socket("192.168.1.10", 2510); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); while (true) { if (0 < socket.getInputStream().available()) { try { jsonObj = (JSONObject) parser.parse(in.readLine()); keys = jsonObj.keySet().iterator(); while (keys.hasNext()) { key = keys.next(); switch (key) { case "IS_TURNON": isTurnOn = (boolean) jsonObj.get("IS_TURNON"); if (!isTurnOn) { atpStatus = 0; } break; case "DISABLE_BUTTON": isReqBttnYARD = false; isReqBttnMCS = false; isReqBttnAUTO = false; isReqBttnATB = false; break; case "REQ_MODE": int value = (int) (long) jsonObj.get("REQ_MODE"); switch (value) { case 1: isReqBttnYARD = true; break; case 3: isReqBttnMCS = true; break; case 4: isReqBttnAUTO = true; break; case 5: isReqBttnATB = true; break; } break; case "SPEED": try { speed = (double) jsonObj.get(key); } catch (Exception ex) { } break; case "ATP_BRAKE": handleATPBrake((int) (long) jsonObj.get("ATP_BRAKE")); break; case "NON_ATP_BRAKE": handleNonATPBrake((boolean) jsonObj.get("NON_ATP_BRAKE")); break; case "TARGET_DISTANCE": handleTargetDistance((double) jsonObj.get("TARGET_DISTANCE")); break; case "TARGET_DISTANCE_ACTUAL": handleTargetDistanceActual((double) jsonObj.get("TARGET_DISTANCE_ACTUAL")); break; case "CEILING_SPEED": handleCeilingSpeed((double) jsonObj.get("CEILING_SPEED")); break; case "ATP_STATUS": handleATOStatus((int) (long) jsonObj.get("ATP_STATUS")); break; case "ATENNA_STATUS": handleAtennaStatus((int) (long) jsonObj.get("ATENNA_STATUS")); break; case "DOOR_INDICATOR": handleDoorIndicator((int) (long) jsonObj.get("DOOR_INDICATOR")); break; case "DOOR_STATUS": handleDoorStatus((boolean) jsonObj.get("DOOR_STATUS")); break; case "SKIPSTOP_STATUS": handleSkipStopStatus((int) (long) jsonObj.get("SKIPSTOP_STATUS")); break; case "DWELL": handleDwell((int) (long) jsonObj.get("DWELL")); break; case "MODE": handleMode((int) (long) jsonObj.get("MODE")); break; } } } catch (ParseException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } else if (!isRegiester) { // assign session id out.println("SESSIONID=DMI"); out.flush(); isRegiester = true; } else { while (!outQueue.isEmpty()) { msg = outQueue.poll(); out.println(msg); out.flush(); } } } } catch (IOException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:hudson.os.windows.ManagedWindowsServiceLauncher.java
public void launch(final SlaveComputer computer, final TaskListener listener) throws IOException, InterruptedException { try {/* ww w. j av a 2s.c om*/ PrintStream logger = listener.getLogger(); logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingTo(computer.getName())); JIDefaultAuthInfoImpl auth = createAuth(); JISession session = JISession.createSession(auth); session.setGlobalSocketTimeout(60000); SWbemServices services = WMI.connect(session, computer.getName()); String path = computer.getNode().getRemoteFS(); SmbFile remoteRoot = new SmbFile( "smb://" + computer.getName() + "/" + path.replace('\\', '/').replace(':', '$') + "/", createSmbAuth()); Win32Service slaveService = services.getService("hudsonslave"); if (slaveService == null) { logger.println(Messages.ManagedWindowsServiceLauncher_InstallingSlaveService()); if (!DotNet.isInstalled(2, 0, computer.getName(), auth)) { // abort the launch logger.println(Messages.ManagedWindowsServiceLauncher_DotNetRequired()); return; } if (!remoteRoot.exists()) remoteRoot.mkdirs(); // copy exe logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveExe()); copyAndClose(getClass().getResource("/windows-service/hudson.exe").openStream(), new SmbFile(remoteRoot, "hudson-slave.exe").getOutputStream()); copySlaveJar(logger, remoteRoot); // copy hudson-slave.xml logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveXml()); String xml = WindowsSlaveInstaller.generateSlaveXml("javaw.exe", "-tcp %BASE%\\port.txt"); copyAndClose(new ByteArrayInputStream(xml.getBytes("UTF-8")), new SmbFile(remoteRoot, "hudson-slave.xml").getOutputStream()); // install it as a service logger.println(Messages.ManagedWindowsServiceLauncher_RegisteringService()); Document dom = new SAXReader().read(new StringReader(xml)); Win32Service svc = services.Get("Win32_Service").cast(Win32Service.class); int r = svc.Create(dom.selectSingleNode("/service/id").getText(), dom.selectSingleNode("/service/name").getText(), path + "\\hudson-slave.exe", Win32OwnProcess, 0, "Manual", true); if (r != 0) { listener.error("Failed to create a service: " + svc.getErrorMessage(r)); return; } slaveService = services.getService("hudsonslave"); } else { copySlaveJar(logger, remoteRoot); } logger.println(Messages.ManagedWindowsServiceLauncher_StartingService()); slaveService.start(); // wait until we see the port.txt, but don't do so forever logger.println(Messages.ManagedWindowsServiceLauncher_WaitingForService()); SmbFile portFile = new SmbFile(remoteRoot, "port.txt"); for (int i = 0; !portFile.exists(); i++) { if (i >= 30) { listener.error(Messages.ManagedWindowsServiceLauncher_ServiceDidntRespond()); return; } Thread.sleep(1000); } int p = readSmbFile(portFile); // connect logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingToPort(p)); final Socket s = new Socket(computer.getName(), p); // ready computer.setChannel(new BufferedInputStream(new SocketInputStream(s)), new BufferedOutputStream(new SocketOutputStream(s)), listener.getLogger(), new Listener() { public void onClosed(Channel channel, IOException cause) { afterDisconnect(computer, listener); } }); } catch (SmbException e) { e.printStackTrace(listener.error(e.getMessage())); } catch (JIException e) { if (e.getErrorCode() == 5) // access denied error e.printStackTrace(listener.error(Messages.ManagedWindowsServiceLauncher_AccessDenied())); else e.printStackTrace(listener.error(e.getMessage())); } catch (DocumentException e) { e.printStackTrace(listener.error(e.getMessage())); } }