List of usage examples for java.net Socket Socket
public Socket(InetAddress address, int port) throws IOException
From source file:com.sshtools.daemon.forwarding.ForwardingServer.java
public Channel createChannel(String channelType, byte[] requestData) throws InvalidChannelException { if (!channelType.equals(ForwardingSocketChannel.LOCAL_FORWARDING_CHANNEL)) { throw new InvalidChannelException( "The client can only request the " + "opening of a local forwarding channel"); }//from ww w . ja va 2s.c om try { ByteArrayReader bar = new ByteArrayReader(requestData); String hostToConnect = bar.readString(); int portToConnect = (int) bar.readInt(); String originatingHost = bar.readString(); int originatingPort = (int) bar.readInt(); // Get a configuration item for the forwarding ForwardingConfiguration config = getLocalForwardingByAddress(originatingHost, originatingPort); Socket socket = new Socket(hostToConnect, portToConnect); // Create the channel adding it to the active channels ForwardingSocketChannel channel = config.createForwardingSocketChannel(channelType, hostToConnect, portToConnect, originatingHost, originatingPort); channel.bindSocket(socket); return channel; } catch (ForwardingConfigurationException fce) { throw new InvalidChannelException("No valid forwarding configuration was available for the request"); } catch (IOException ioe) { throw new InvalidChannelException( "The channel request data is " + "invalid/or corrupt for channel type " + channelType); } }
From source file:com.sshtools.j2ssh.agent.SshAgentClient.java
/** * Connect a socket to the agent at the location specified. * * @param location the location of the agent, in the form "localhost:port" * * @return the connected socket//from w ww . j ava 2s. c o m * * @throws AgentNotAvailableException if an agent is not available at the * location specified * @throws IOException if an IO error occurs */ public static Socket connectAgentSocket(String location) throws AgentNotAvailableException, IOException { try { if (location == null) { throw new AgentNotAvailableException(); } int idx = location.indexOf(":"); if (idx == -1) { throw new AgentNotAvailableException(); } String host = location.substring(0, idx); int port = Integer.parseInt(location.substring(idx + 1)); Socket socket = new Socket(host, port); return socket; } catch (IOException ex) { throw new AgentNotAvailableException(); } }
From source file:org.openmrs.module.pacsintegration.component.HL7ListenerComponentTest.java
@Test public void shouldListenForAndParseORU_R01Message() throws Exception { ModuleActivator activator = new PacsIntegrationActivator(); activator.started();//from w w w. j a v a 2s . com Context.getService(PacsIntegrationService.class).initializeHL7Listener(); List<Patient> patients = patientService.getPatients(null, "101-6", Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true); assertThat(patients.size(), is(1)); // sanity check Patient patient = patients.get(0); List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()), null, null, null, false); assertThat(encounters.size(), is(0)); // sanity check try { String message = "MSH|^~\\&|HMI|Mirebalais Hospital|RAD|REPORTS|20130228174549||ORU^R01|RTS01CE16055AAF5290|P|2.3|\r" + "PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" + "PV1|1||||||||||||||||||\r" + "OBR|1||0000001297|127689^SOME_X-RAY|||20130228170556||||||||||||MBL^CR||||||F|||||||M123&Goodrich&Mark&&&&||||20130228170556\r" + "OBX|1|TX|127689^SOME_X-RAY||Clinical Indication: ||||||F\r"; Thread.sleep(2000); // give the simple server time to start Socket socket = new Socket("127.0.0.1", 6665); PrintStream writer = new PrintStream(socket.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer.print(header); writer.print(message); writer.print(trailer + "\r"); writer.flush(); Thread.sleep(2000); // confirm that report encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests) encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()), null, null, null, false); assertThat(encounters.size(), is(1)); assertThat(encounters.get(0).getObs().size(), is(4)); // confirm that the proper ack is sent out String response = reader.readLine(); assertThat(response, containsString("|ACK|")); } finally { activator.stopped(); } }
From source file:MailTest.java
/** * Sends the mail message that has been authored in the GUI. */// ww w. jav a 2 s . c o m public void sendMail() { try { Socket s = new Socket(smtpServer.getText(), 25); InputStream inStream = s.getInputStream(); OutputStream outStream = s.getOutputStream(); in = new Scanner(inStream); out = new PrintWriter(outStream, true /* autoFlush */); String hostName = InetAddress.getLocalHost().getHostName(); receive(); send("HELO " + hostName); receive(); send("MAIL FROM: <" + from.getText() + ">"); receive(); send("RCPT TO: <" + to.getText() + ">"); receive(); send("DATA"); receive(); send(message.getText()); send("."); receive(); s.close(); } catch (IOException e) { comm.append("Error: " + e); } }
From source file:jeeves.utils.EMail.java
/** Sends the message to the mail server *//*w w w . ja v a 2 s . c o m*/ public boolean send() throws IOException { Socket socket = new Socket(sMailServer, iPort); try { in = new BufferedReader(new InputStreamReader(new DataInputStream(socket.getInputStream()), Charset.forName(Jeeves.ENCODING))); out = new OutputStreamWriter(new DataOutputStream(socket.getOutputStream()), "ISO-8859-1"); if (lookMailServer()) if (sendData("2", "HELO " + InetAddress.getLocalHost().getHostName() + "\r\n")) if (sendData("2", "MAIL FROM: <" + sFrom + ">\r\n")) if (sendData("2", "RCPT TO: <" + sTo + ">\r\n")) if (sendData("354", "DATA\r\n")) if (sendData("2", buildContent())) if (sendData("2", "QUIT\r\n")) return true; sendData("2", "QUIT\r\n"); } finally { IOUtils.closeQuietly(socket); } return false; }
From source file:com.chigix.bio.proxy.buffer.FixedBufferTest.java
License:asdf
@Test public void testGoogleConnect() { System.out.println("BANKAI"); Socket tmp_socket = null;/*from ww w . j a va 2 s.c o m*/ try { tmp_socket = new Socket("www.google.com", 80); } catch (IOException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } final Socket socket = tmp_socket; new Thread() { @Override public void run() { while (true) { try { int read; System.out.print(read = socket.getInputStream().read()); System.out.print("[" + (char) read + "]"); System.out.print(","); } catch (IOException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } } } }.start(); try { //socket.getOutputStream().write("GET http://www.google.com/ HTTP/1.0\r\nHost: www.google.com\r\nConnection: close\r\n\n".getBytes()); //URI uri = new URI("/?gfe_rd=cr&ei=F07YVIjKBe_98wfq74LICw"); URI uri = new URI("/asdfwef?"); System.out.println(uri.getRawFragment()); System.out.println(uri.getRawPath()); System.out.println(uri.getRawQuery()); System.out.println(uri.getRawSchemeSpecificPart()); socket.getOutputStream() .write(("GET / HTTP/1.0\r\nHost: www.google.com\r\nConnection: close\r\n\r\n").getBytes()); System.out.println("REQUEST SENT"); } catch (IOException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } try { Thread.sleep(50000); } catch (InterruptedException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:TestSecurity.java
/** * put your documentation comment here//from w ww .j a v a2s .c o m * @param req * @param res * @exception ServletException, IOException */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>"); out.println("<BODY>"); out.println("<BIG>Test Security</BIG>"); try { out.println(h2o + "Information..." + h2c); out.println(" Security Manager: " + getSecurityManager().getClass().getName() + p); out.println(" ClassLoader: " + this.getClass().getClassLoader() + p); // weblogic.utils.classloaders.GenericClassLoader gcl = (weblogic.utils.classloaders.GenericClassLoader)this.getClass().getClassLoader(); // gcl.setDebug( true ); out.println(" CodeSource: " + this.getClass().getProtectionDomain().getCodeSource().getLocation() + p); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } /* try { out.println( h2o + "Trying some dangerous J2EE calls..." + h2c ); String hack = request.getParameter( "hack" ); Cookie[] cookies = request.getCookies(); out.println( " -- allowed -- " + p ); int x = 1 + 2 + 3; out.println( hack ); // use it int y = 1 + 2 + 3; out.println( cookies ); // use it String m = "COOKIE: " + cookies[0]; // use it again cookies = new Cookie[10]; // reset it String n = "COOKIE: " + cookies[5]; // use it again } catch( Exception e ) { out.println( " -- rejected -- " + e.getMessage() + p ); } */ try { out.println(h2o + "Attempting file write to d:/Java..." + h2c); File f = new File("d:/Java/blah.txt"); FileWriter fw = new FileWriter(f); fw.write("test\n"); fw.close(); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } try { out.println(h2o + "Attempting file write to d:/Java/TestServlet..." + h2c); File f = new File("d:/Java/TestServlet/blah.txt"); FileWriter fw = new FileWriter(f); fw.write("test\n"); fw.close(); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } try { out.println(h2o + "Attempting file read to c:/Ntdetect..." + h2c); File f = new File("c:/Ntdetect.com"); FileReader fr = new FileReader(f); int c = fr.read(); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } try { out.println(h2o + "Attempting file read to c:/weblogic/weblogic.properties..." + h2c); File f = new File("c:/weblogic/weblogic.properties"); FileReader fr = new FileReader(f); int c = fr.read(); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } try { out.println(h2o + "Attempting to connect to yahoo.com..." + h2c); Socket s = new Socket("yahoo.com", 8080); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } try { out.println(h2o + "Attempting to connect to hacker.com..." + h2c); Socket s = new Socket("hacker.com", 8080); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } try { out.println(h2o + "Attempting to listen on port 37337..." + h2c); ServerSocket s = new ServerSocket(37337); Socket c = s.accept(); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } try { out.println(h2o + "Attempting to listen on port 7001..." + h2c); ServerSocket s = new ServerSocket(7001); Socket c = s.accept(); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } /* try { out.println( h2o + "Attempting native call..." + h2c ); native0( 1 ); out.println( " -- allowed -- " + p ); } catch( Exception e ) { out.println( " -- rejected -- " + e.getMessage() + p ); } */ try { out.println(h2o + "Attempting exec..." + h2c); Runtime.getRuntime().exec("dir"); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } try { out.println(h2o + "Attempting system exit..." + h2c); out.println(" -- allowed -- " + p); } catch (Exception e) { out.println(" -- rejected -- " + e.getMessage() + p); } out.println("</BODY></HTML>"); }
From source file:com.quigley.zabbixj.agent.active.ActiveThread.java
private void requestActiveChecks() throws Exception { if (log.isDebugEnabled()) { log.debug("Requesting a list of active checks from the server."); }/*w w w. j av a 2s .c o m*/ Socket socket = new Socket(serverAddress, serverPort); InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JSONObject request = new JSONObject(); request.put("request", "active checks"); request.put("host", hostName); byte[] buffer = getRequest(request); output.write(buffer); output.flush(); buffer = new byte[10240]; int read = 0; while ((read = input.read(buffer, 0, 10240)) != -1) { baos.write(buffer, 0, read); } socket.close(); JSONObject response = getResponse(baos.toByteArray()); if (response.getString("response").equals("success")) { refreshFromActiveChecksResponse(response); } else { log.warn("Server reported a failure when requesting active checks:" + response.getString("info")); } lastRefresh = System.currentTimeMillis() / 1000; }
From source file:org.jwifisd.transcend.TranscendWiFiSD.java
@Override public void reconnect() { if (!westec.isConnected()) { try {//ww w. j av a2s . c o m startListening(new Socket(ipAddress(), TRANSCEND_EVENTING_PORT)); } catch (IOException e) { LOG.error("TranscendWiFiSD event channel could not reconnect!", e); } } }
From source file:com.spotify.helios.HeliosSoloIT.java
@Test public void testServiceDiscovery() throws Exception { // start a container that runs nginx and registers with SkyDNS final TemporaryJob nginx = jobs.job().image(NGINX).port("http", 80, ports.localPort("http")) .registration("nginx", "http", "http").deploy(); // run a container that does SRV lookup to find the nginx service and then curl's it final TemporaryJob alpine = jobs.job().image(ALPINE).port("nc", 4711, ports.localPort("nc")) .command("sh", "-c", "apk add --update bind-tools " + "&& export SRV=$(dig -t SRV +short _nginx._http.test.$SPOTIFY_DOMAIN) " + "&& export HOST=$(echo $SRV | cut -d' ' -f4) " + "&& export PORT=$(echo $SRV | cut -d' ' -f3) " + "&& nc -lk -p 4711 -e curl http://$HOST:$PORT") .deploy();//www .j av a2 s . co m final HostAndPort alpineAddress = alpine.address("nc"); // Connect to alpine container to get the curl response. If we get back the nginx welcome page // we know that helios properly registered the nginx service in SkyDNS. final Callable<String> socketResponse = () -> { try (final Socket s = new Socket(alpineAddress.getHostText(), alpineAddress.getPort())) { return IOUtils.toString(s.getInputStream()).trim(); } }; // allow a few retries for a delay in the apk install of bind-tools Awaitility.await("alpine container returns nginx welcome").atMost(10, TimeUnit.SECONDS) .until(socketResponse, containsString("Welcome to nginx!")); // also throw in a check to make sure log streaming is working assertThat(new String(logStreamProvider.getStderr(nginx.job().getId())), containsString("nginx")); }