Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

In this page you can find the example usage for java.net Socket getOutputStream.

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:com.symbian.driver.plugins.reboot.Activator.java

/**
 * @param switchState//from   ww  w . j  a v a  2  s .c o m
 * @throws IOException
 */
private synchronized void switchOp(String switchState) throws IOException {
    LOGGER.log(Level.INFO, "Activator::switchOp");

    // Alternative being "TelnetSwitch"
    if (method.compareToIgnoreCase("PortTalk") == 0)// ATX power
    {
        String state = switchState == "2" ? "OFF" : "ON";
        File hardwareSwitchFile = JarUtils.extractResource(Activator.class, "/resource/HardwareSwitch.exe");
        if (hardwareSwitchFile.isFile()) {
            Process p = Runtime.getRuntime()
                    .exec("cmd.exe /c " + hardwareSwitchFile.getAbsolutePath() + " " + state);
            BufferedReader iBufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String lOutput = null;
            StringBuffer iOutputBuffer = new StringBuffer();
            while ((lOutput = iBufferedReader.readLine()) != null) {
                lOutput += System.getProperty("line.separator");
                iOutputBuffer.append(lOutput);
                // Parse for errors and redirect to appropriate buffer.
            }
            LOGGER.info(iOutputBuffer.toString());
        } else {
            LOGGER.warning(hardwareSwitchFile.getAbsolutePath() + " was not found");
        }
    } else {

        String responseLine = "";
        String[] states = { "User Name :", "Password  :", "Control Console", "Device Manager",
                "Outlet Management", "Outlet Control/Configuration", "Outlet " + outletNo, "Control Outlet",
                "Immediate Off", "Press <ENTER> to continue..." };

        String[] answers = { userName, password, "1", "2", "1", outletNo, "1", switchState, "YES", "\n" };

        Socket sock = new Socket(hostAddr, 23);
        PrintWriter dataToTelnetServer = new PrintWriter(sock.getOutputStream(), true);
        BufferedReader dataFromTelnetServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        // start the state machine...
        int state = 0;
        long lastStateChng = System.currentTimeMillis();
        while (state < states.length) {
            while (dataFromTelnetServer.ready()) {
                char nextChar = (char) dataFromTelnetServer.read();
                responseLine += nextChar;
            }
            LOGGER.log(Level.FINE, responseLine);
            if (responseLine.contains(states[state])) // sort of on
            {

                LOGGER.log(Level.FINE, "answers[" + state + "]:" + answers[state]);
                dataToTelnetServer.println(answers[state]);
                state++;
                lastStateChng = System.currentTimeMillis();
                continue;
            }
            if ((System.currentTimeMillis() - lastStateChng) > 10000) {
                // too much time since last change of state...
                // we have lost the connection...
                LOGGER.log(Level.SEVERE, "Lost telnet connection");
                break;
            }
        }
        responseLine = "";
        dataToTelnetServer.flush();
        dataToTelnetServer.close();
        dataFromTelnetServer.close();
        sock.close();
    }
}

From source file:org.openmrs.module.pacsintegration.component.HL7ListenerComponentTest.java

@Test
public void shouldCreateTwoReportsIfBodyDifferent() throws Exception {

    ModuleActivator activator = new PacsIntegrationActivator();
    activator.started();/*from  ww w. j  av a2  s  .  c  om*/
    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 message1 = "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|||||||Test&Goodrich&Mark&&&&||||20130228170556\r"
                + "OBX|1|TX|127689^SOME_X-RAY||Clinical Indication: ||||||F\r";

        String message2 = "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|||||||Test&Goodrich&Mark&&&&||||20130228170556\r"
                + "OBX|1|TX|127689^SOME_X-RAY||Another 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());

        writer.print(header);
        writer.print(message1);
        writer.print(trailer + "\r");
        writer.flush();

        writer.print(header);
        writer.print(message2);
        writer.print(trailer + "\r");
        writer.flush();

        Thread.sleep(2000);

        encounters = encounterService.getEncounters(patient, null, null, null, null,
                Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()), null, null,
                null, false);
        assertThat(encounters.size(), is(2));

    } finally {
        activator.stopped();
    }

}

From source file:org.openmrs.module.pacsintegration.component.HL7ListenerComponentTest.java

@Test
public void shouldNotImportORM_001MessageWithDuplicateOrderNumber() throws Exception {

    ModuleActivator activator = new PacsIntegrationActivator();
    activator.started();/*from  ww  w  . jav  a  2  s .  co  m*/
    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.getRadiologyStudyEncounterType()), null, null, null,
            false);
    assertThat(encounters.size(), is(0)); // sanity check

    try {

        String message = "MSH|^~\\&|HMI||RAD|REPORTS|20130228174643||ORM^O01|RTS01CE16057B105AC0|P|2.3|\r"
                + "PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" + "ORC|\r"
                + "OBR|1||0000001297|127689^SOME_X-RAY|||20130228170350||||||||||||MBL^CR||||||P|||||||&Goodrich&Mark&&&&||||20130228170350\r"
                + "OBX|1|RP|||||||||F\r" + "OBX|2|TX|EventType^EventType|1|REVIEWED\r"
                + "OBX|3|CN|Technologist^Technologist|1|1435^Duck^Donald\r"
                + "OBX|4|TX|ExamRoom^ExamRoom|1|100AcreWoods\r"
                + "OBX|5|TS|StartDateTime^StartDateTime|1|20111009215317\r"
                + "OBX|6|TS|StopDateTime^StopDateTime|1|20111009215817\r"
                + "OBX|7|TX|ImagesAvailable^ImagesAvailable|1|1\r"
                + "ZDS|2.16.840.1.113883.3.234.1.3.101.1.2.1013.2011.15607503.2^HMI^Application^DICOM\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());

        // send the message twice
        for (int i = 0; i < 2; i++) {
            writer.print(header);
            writer.print(message);
            writer.print(trailer + "\r");
            writer.flush();
        }

        Thread.sleep(2000);

        // confirm that only one encounter has been created
        encounters = encounterService.getEncounters(patient, null, null, null, null,
                Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()), null, null,
                null, false);
        assertThat(encounters.size(), is(1));

    } finally {
        activator.stopped();
    }

}

From source file:org.openmrs.module.pacsintegration.component.HL7ListenerComponentTest.java

@Test
public void shouldListenForAndParseORM_001Message() throws Exception {

    ModuleActivator activator = new PacsIntegrationActivator();
    activator.started();/*from  w ww .  jav a  2 s  .c o m*/
    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.getRadiologyStudyEncounterType()), null, null, null,
            false);
    assertThat(encounters.size(), is(0)); // sanity check

    try {

        String message = "MSH|^~\\&|HMI||RAD|REPORTS|20130228174643||ORM^O01|RTS01CE16057B105AC0|P|2.3|\r"
                + "PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" + "ORC|\r"
                + "OBR|1||0000001297|127689^SOME_X-RAY|||20130228170350||||||||||||MBL^CR||||||P|||||||&Goodrich&Mark&&&&^||||20130228170350\r"
                + "OBX|1|RP|||||||||F\r" + "OBX|2|TX|EventType^EventType|1|REVIEWED\r"
                + "OBX|3|CN|Technologist^Technologist|1|1435^Duck^Donald\r"
                + "OBX|4|TX|ExamRoom^ExamRoom|1|100AcreWoods\r"
                + "OBX|5|TS|StartDateTime^StartDateTime|1|20111009215317\r"
                + "OBX|6|TS|StopDateTime^StopDateTime|1|20111009215817\r"
                + "OBX|7|TX|ImagesAvailable^ImagesAvailable|1|1\r"
                + "ZDS|2.16.840.1.113883.3.234.1.3.101.1.2.1013.2011.15607503.2^HMI^Application^DICOM\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 study 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.getRadiologyStudyEncounterType()), null, null,
                null, false);
        assertThat(encounters.size(), is(1));
        assertThat(encounters.get(0).getObs().size(), is(3));

        // confirm that the proper ack is sent out
        String response = reader.readLine();
        assertThat(response, containsString("|ACK|"));
    } finally {
        activator.stopped();
    }

}

From source file:io.github.gsteckman.rpi_rest.SubscriptionManager.java

/**
 * Sends the provided message to the host and port specified in the URL object.
 * //  ww w.  j av  a  2 s  .  co m
 * @param url
 *            Provides the host and port to which the message is sent via TCP.
 * @param message
 *            The message to send, including all headers and message body.
 * @throws IOException
 *             If an exception occured writing to the socket.
 */
private void sendNotify(final URL url, final String message) throws IOException {
    Socket sock = new Socket(url.getHost(), url.getPort());
    OutputStreamWriter out = new OutputStreamWriter(sock.getOutputStream());
    out.write(message);
    out.close();
    sock.close();
}

From source file:info.varden.irclinqed.dcc.FileSendThread.java

@Override
public void onIPSelected(String ipAddress) {
    try {//  w  w w .  java 2s  . c  o  m
        if (!this.file.exists()) {
            return;
        }
        this.server = new ServerSocket(0);
        this.server.setSoTimeout(60000);
        DCCRequestPacket packet = null;
        String filename = this.file.getName();
        if (filename.split(" ").length > 1) {
            filename = "\"" + filename + "\"";
        }
        if (this.thread instanceof IRCThread) {
            packet = new DCCRequestPacket(this.il, (IRCThread) this.thread, this.target, DCCType.SEND, filename,
                    ipAddress, server.getLocalPort(), this.totalSize);
        } else if (this.thread instanceof DCCThread) {
            VirtualIRCThread thrd = new VirtualIRCThread(this.il, (DCCThread) this.thread);
            packet = new DCCRequestPacket(this.il, thrd, this.target, DCCType.SEND, filename, ipAddress,
                    server.getLocalPort(), this.totalSize);
        } else {
            this.server.close();
            return;
        }
        packet.send();
        if (this.cancel) {
            this.server.close();
            return;
        }
        this.message = "Waiting for connection...";
        Socket s = this.server.accept();
        this.overlay.unload();
        this.gfp = new GuiFileProgress(this.il, this);
        this.il.guiQueue.add(this.gfp);
        InputStream i = new FileInputStream(this.file);
        this.cos = new CountingOutputStream(s.getOutputStream());
        byte[] buff = new byte[1024];
        int k = -1;
        while ((k = i.read(buff)) > -1 && !this.cancel) {
            this.cos.write(buff, 0, k);
            s.getInputStream().read(new byte[4]);
        }
        s.shutdownInput();
        s.shutdownOutput();
        s.close();
        this.server.close();
        i.close();
        this.gfp.unload();
    } catch (SocketTimeoutException e) {
        this.overlay.unload();
        Util.extractUtil(this.thread).writeToChat(MessageType.DCC_ERROR, "File send timed out.");
    } catch (IOException e) {
        e.printStackTrace();
    }
    this.overlay.unload();
}

From source file:jetbrains.exodus.util.ForkSupportIO.java

@NotNull
private Process spawnProcess() throws IOException {
    final Process process = builder.start();
    log.info("Waiting for connection...");
    final Socket connection = serverSocket.accept();
    log.info("Connection received from " + connection.getInetAddress().getHostName());
    log.info("Waiting to receive process Id");
    streamer = new Streamer(connection.getInputStream(), connection.getOutputStream());
    String idString = streamer.readString();
    processId = Integer.parseInt(idString);
    return process;
}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test that by default we have protocol version 1.4.
 * //  www . j  a v  a2  s .  c  o  m
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testDefault() throws Exception {
    final Agent agent = new ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(), ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("system.property[java.version]\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    in.read(buffer);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);
    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:io.fabric8.kubernetes.api.KubernetesHelper.java

public static boolean isServiceSsl(String host, int port, boolean trustAllCerts) {
    try {//  ww  w  .j a v  a2  s .c  o m
        SSLSocketFactory sslsocketfactory = null;
        if (trustAllCerts) {
            sslsocketfactory = KubernetesFactory.TrustEverythingSSLTrustManager.getTrustingSSLSocketFactory();
        } else {
            sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        }

        Socket socket = sslsocketfactory.createSocket();

        // Connect, with an explicit timeout value
        socket.connect(new InetSocketAddress(host, port), 1 * 1000);
        try {

            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();

            // Write a test byte to get a reaction :)
            out.write(1);

            while (in.available() > 0) {
                System.out.print(in.read());
            }

            return true;
        } finally {
            socket.close();
        }
    } catch (SSLHandshakeException e) {
        LOG.error(
                "SSL handshake failed - this probably means that you need to trust the kubernetes root SSL certificate or set the environment variable "
                        + KubernetesFactory.KUBERNETES_TRUST_ALL_CERIFICATES,
                e);
    } catch (SSLProtocolException e) {
        LOG.error("SSL protocol error", e);
    } catch (SSLKeyException e) {
        LOG.error("Bad SSL key", e);
    } catch (SSLPeerUnverifiedException e) {
        LOG.error("Could not verify server", e);
    } catch (SSLException e) {
        LOG.debug("Address does not appear to be SSL-enabled - falling back to http", e);
    } catch (IOException e) {
        LOG.debug("Failed to validate service", e);
    }
    return false;
}

From source file:it.anyplace.sync.client.protocol.rp.RelayClient.java

public RelayConnection openConnectionSessionMode(final SessionInvitation sessionInvitation) throws Exception {
    logger.debug("connecting to relay = {}:{} (session mode)", sessionInvitation.getAddress(),
            sessionInvitation.getPort());
    final Socket socket = new Socket(sessionInvitation.getAddress(), sessionInvitation.getPort());
    RelayDataInputStream in = new RelayDataInputStream(socket.getInputStream());
    RelayDataOutputStream out = new RelayDataOutputStream(socket.getOutputStream());
    try {//  w ww .j a  va  2s. c om
        {
            logger.debug("sending join session request, session key = {}", sessionInvitation.getKey());
            byte[] key = BaseEncoding.base16().decode(sessionInvitation.getKey());
            int lengthOfKey = key.length;
            out.writeHeader(JOIN_SESSION_REQUEST, 4 + lengthOfKey);
            out.writeInt(lengthOfKey);
            out.write(key);
            out.flush();
        }
        {
            logger.debug("reading relay response");
            MessageReader messageReader = in.readMessage();
            checkArgument(messageReader.getType() == RESPONSE);
            Response response = messageReader.readResponse();
            logger.debug("response = {}", response);
            checkArgument(response.getCode() == RESPONSE_SUCCESS_CODE, "response code = %s (%s) expected %s",
                    response.getCode(), response.getMessage(), RESPONSE_SUCCESS_CODE);
            logger.debug("relay connection ready");
        }
        return new RelayConnection() {
            @Override
            public Socket getSocket() {
                return socket;
            }

            @Override
            public boolean isServerSocket() {
                return sessionInvitation.isServerSocket();
            }

        };
    } catch (Exception ex) {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(socket);
        throw ex;
    }
}