Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:com.fluffypeople.managesieve.ManageSieveClient.java

private void setupAfterConnect(Socket sock) throws IOException {
    sock.setSoTimeout(socketTimeout);/*from w w w  . j  av  a  2  s  .co m*/
    byteStream = new BufferedInputStream(sock.getInputStream());
    in = new StreamTokenizer(new InputStreamReader(byteStream, UTF8));
    setupTokenizer();
    out = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
}

From source file:net.sbbi.upnp.ServicesEventing.java

/**
 * Unregisters events notifications from a service
 * @param service the service that need to be unregistered
 * @param handler the handler that registered for this service
 * @return true if unregistered false otherwise ( the given handler never registred for the given service )
 * @throws IOException if some IOException error happens during coms with the device
 *//*  w ww.j  a va 2 s  . c o m*/
public boolean unRegister(UPNPService service, ServiceEventHandler handler) throws IOException {

    URL eventingLoc = service.getEventSubURL();

    if (eventingLoc != null) {

        Subscription sub = lookupSubscriber(service, handler);
        if (sub != null) {
            synchronized (registered) {
                registered.remove(sub);
            }
            if (registered.size() == 0) {
                stopServicesEventingThread();
            }

            StringBuffer packet = new StringBuffer(64);
            packet.append("UNSUBSCRIBE  ").append(eventingLoc.getFile()).append(" HTTP/1.1\r\n");
            packet.append("HOST: ").append(eventingLoc.getHost()).append(":").append(eventingLoc.getPort())
                    .append("\r\n");
            packet.append("SID: ").append(sub.sub.getSID()).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")) {
                    return true;
                }
            }
        }
    }
    return false;
}

From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java

public MatcherKState requestState(InetAddress host, int port, String id)
        throws JSONException, InterruptedException, IOException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;

    while (client == null || !client.isConnected()) {
        try {/*from   w  w w .  j a va2 s  .  c  o m*/
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                logger.error(e.getMessage());
                client.close();
                throw new IOException();
            } else {
                trials -= 1;
            }
        }
    }

    JSONObject json = new JSONObject();
    json.put("id", id);

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(json.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);

    String response = reader.readLine();
    client.close();

    return new MatcherKState(new JSONObject(response), new MatcherFactory(TrackerControl.getServer().getMap()));
}

From source file:com.photon.maven.plugins.android.AbstractEmulatorMojo.java

/**
 * Sends a user command to the running emulator via its telnet interface.
 *
 * @param port The emulator's telnet port.
 * @param command The command to execute on the emulator's telnet interface.
 * @return Whether sending the command succeeded.
 *//*from  www. j  a va2  s  . c o m*/
private boolean sendEmulatorCommand(
        //final Launcher launcher, 
        //final PrintStream logger,
        final int port, final String command) {
    Callable<Boolean> task = new Callable<Boolean>() {
        public Boolean call() throws IOException {
            Socket socket = null;
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                socket = new Socket("127.0.0.1", port);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                if (in.readLine() == null) {
                    return false;
                }

                out.write(command);
                out.write("\r\n");
            } finally {
                try {
                    out.close();
                    in.close();
                    socket.close();
                } catch (Exception e) {
                    // Do nothing
                }
            }

            return true;
        }

        private static final long serialVersionUID = 1L;
    };

    boolean result = false;
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Boolean> future = executor.submit(task);
        result = future.get();
    } catch (Exception e) {
        getLog().error(String.format("Failed to execute emulator command '%s': %s", command, e));
    }

    return result;
}

From source file:edu.cmu.ark.AnalysisUtilities.java

public ParseResult parseSentence(String sentence) {
    String result = "";
    //System.err.println(sentence);
    //see if a parser socket server is available
    int port = new Integer(GlobalProperties.getProperties().getProperty("parserServerPort", "5556"));
    String host = "127.0.0.1";
    Socket client;
    PrintWriter pw;//w ww  . j a va2  s  .c  o  m
    BufferedReader br;
    String line;
    Tree parse = null;
    double parseScore = Double.MIN_VALUE;

    try {
        client = new Socket(host, port);

        pw = new PrintWriter(client.getOutputStream());
        br = new BufferedReader(new InputStreamReader(client.getInputStream()));
        pw.println(sentence);
        pw.flush(); //flush to complete the transmission

        while ((line = br.readLine()) != null) {
            //if(!line.matches(".*\\S.*")){
            //        System.out.println();
            //}
            if (br.ready()) {
                line = line.replaceAll("\n", "");
                line = line.replaceAll("\\s+", " ");
                result += line + " ";
            } else {
                parseScore = new Double(line);
            }
        }

        br.close();
        pw.close();
        client.close();

        if (parse == null) {
            parse = readTreeFromString("(ROOT (. .))");
            parseScore = -99999.0;
        }

        if (GlobalProperties.getDebug())
            System.err.println("result (parse):" + result);
        parse = readTreeFromString(result);
        return new ParseResult(true, parse, parseScore);

    } catch (Exception ex) {
        if (GlobalProperties.getDebug())
            System.err.println("Could not connect to parser server.");
        //ex.printStackTrace();
    }

    System.err.println("parsing:" + sentence);

    //if socket server not available, then use a local parser object
    if (parser == null) {
        try {
            Options op = new Options();
            String serializedInputFileOrUrl = GlobalProperties.getProperties().getProperty("parserGrammarFile",
                    "config" + File.separator + "englishFactored.ser.gz");
            parser = new LexicalizedParser(serializedInputFileOrUrl, op);
            int maxLength = new Integer(GlobalProperties.getProperties().getProperty("parserMaxLength", "40"))
                    .intValue();
            parser.setMaxLength(maxLength);
            parser.setOptionFlags("-outputFormat", "oneline");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    try {
        if (parser.parse(sentence)) {
            parse = parser.getBestParse();

            //remove all the parent annotations (this is a hacky way to do it)
            String ps = parse.toString().replaceAll("\\[[^\\]]+/[^\\]]+\\]", "");
            parse = AnalysisUtilities.getInstance().readTreeFromString(ps);

            parseScore = parser.getPCFGScore();
            return new ParseResult(true, parse, parseScore);
        }
    } catch (Exception e) {
    }

    parse = readTreeFromString("(ROOT (. .))");
    parseScore = -99999.0;
    return new ParseResult(false, parse, parseScore);
}

From source file:MedArkRef.AnalysisUtilities.java

public arkref.parsestuff.AnalysisUtilities.ParseResult parseSentence(String sentence) {
    String result = "";
    //System.err.println(sentence);
    //see if a parser socket server is available
    int port = new Integer(GlobalProperties.getProperties().getProperty("parserServerPort", "5556"));
    String host = "127.0.0.1";
    Socket client;
    PrintWriter pw;/* www .  ja  va2  s  .  c o  m*/
    BufferedReader br;
    String line;
    Tree parse = null;
    double parseScore = Double.MIN_VALUE;

    try {
        client = new Socket(host, port);

        pw = new PrintWriter(client.getOutputStream());
        br = new BufferedReader(new InputStreamReader(client.getInputStream()));
        pw.println(sentence);
        pw.flush(); //flush to complete the transmission

        while ((line = br.readLine()) != null) {
            //if(!line.matches(".*\\S.*")){
            //        System.out.println();
            //}
            if (br.ready()) {
                line = line.replaceAll("\n", "");
                line = line.replaceAll("\\s+", " ");
                result += line + " ";
            } else {
                parseScore = new Double(line);
            }
        }

        br.close();
        pw.close();
        client.close();

        if (parse == null) {
            parse = readTreeFromString("(ROOT (. .))");
            parseScore = -99999.0;
        }

        if (GlobalProperties.getDebug())
            System.err.println("result (parse):" + result);
        parse = readTreeFromString(result);
        return new arkref.parsestuff.AnalysisUtilities.ParseResult(true, parse, parseScore);

    } catch (Exception ex) {
        if (GlobalProperties.getDebug())
            System.err.println("Could not connect to parser server.");
        //ex.printStackTrace();
    }

    System.err.println("parsing:" + sentence);

    //if socket server not available, then use a local parser object
    if (parser == null) {
        try {
            Options op = new Options();
            String serializedInputFileOrUrl = GlobalProperties.getProperties().getProperty("parserGrammarFile",
                    "config" + File.separator + "englishFactored.ser.gz");
            parser = new LexicalizedParser(serializedInputFileOrUrl, op);
            int maxLength = new Integer(GlobalProperties.getProperties().getProperty("parserMaxLength", "40"))
                    .intValue();
            parser.setMaxLength(maxLength);
            parser.setOptionFlags("-outputFormat", "oneline");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    try {
        if (parser.parse(sentence)) {
            parse = parser.getBestParse();

            //remove all the parent annotations (this is a hacky way to do it)
            String ps = parse.toString().replaceAll("\\[[^\\]]+/[^\\]]+\\]", "");
            parse = AnalysisUtilities.getInstance().readTreeFromString(ps);

            parseScore = parser.getPCFGScore();
            return new arkref.parsestuff.AnalysisUtilities.ParseResult(true, parse, parseScore);
        }
    } catch (Exception e) {
    }

    parse = readTreeFromString("(ROOT (. .))");
    parseScore = -99999.0;
    return new arkref.parsestuff.AnalysisUtilities.ParseResult(false, parse, parseScore);
}

From source file:org.apache.accumulo.minicluster.MiniAccumuloCluster.java

/**
 * Starts Accumulo and Zookeeper processes. Can only be called once.
 * //from   w  w w  .  ja v a  2s.co m
 * @throws IllegalStateException
 *           if already started
 */
public void start() throws IOException, InterruptedException {

    if (!initialized) {

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    MiniAccumuloCluster.this.stop();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    if (zooKeeperProcess == null) {
        zooKeeperProcess = exec(ZooKeeperServerMain.class, ServerType.ZOOKEEPER, zooCfgFile.getAbsolutePath());
    }

    if (!initialized) {
        // sleep a little bit to let zookeeper come up before calling init, seems to work better
        while (true) {
            try {
                Socket s = new Socket("localhost", config.getZooKeeperPort());
                s.getOutputStream().write("ruok\n".getBytes());
                s.getOutputStream().flush();
                byte buffer[] = new byte[100];
                int n = s.getInputStream().read(buffer);
                if (n == 4 && new String(buffer, 0, n).equals("imok"))
                    break;
            } catch (Exception e) {
                UtilWaitThread.sleep(250);
            }
        }
        Process initProcess = exec(Initialize.class, "--instance-name", config.getInstanceName(), "--password",
                config.getRootPassword());
        int ret = initProcess.waitFor();
        if (ret != 0) {
            throw new RuntimeException("Initialize process returned " + ret + ". Check the logs in "
                    + config.getLogDir() + " for errors.");
        }
        initialized = true;
    }
    synchronized (tabletServerProcesses) {
        for (int i = tabletServerProcesses.size(); i < config.getNumTservers(); i++) {
            tabletServerProcesses.add(exec(TabletServer.class, ServerType.TABLET_SERVER));
        }
    }
    int ret = 0;
    for (int i = 0; i < 5; i++) {
        ret = exec(Main.class, SetGoalState.class.getName(), MasterGoalState.NORMAL.toString()).waitFor();
        if (ret == 0)
            break;
        UtilWaitThread.sleep(1000);
    }
    if (ret != 0) {
        throw new RuntimeException("Could not set master goal state, process returned " + ret
                + ". Check the logs in " + config.getLogDir() + " for errors.");
    }
    if (masterProcess == null) {
        masterProcess = exec(Master.class, ServerType.MASTER);
    }
    if (config.shouldRunGC()) {
        gcProcess = exec(SimpleGarbageCollector.class, ServerType.GARBAGE_COLLECTOR);
    }
}

From source file:com.isecpartners.gizmo.HttpRequest.java

public boolean readRequest(Socket clientSock) {
    StringBuffer contents = new StringBuffer();

    try {/* www.j ava 2 s  . com*/
        InputStream input = clientSock.getInputStream();

        contents = readMessage(input);

        if (contents == null) {
            return false;
        }

        setContentEncodings(contents);
        this.interrimContents = contents.toString();
        this.sock = clientSock;

        this.header = contents.substring(0, contents.indexOf("\r\n"));

        workingContents = new StringBuffer(this.interrimContents.toString());

        if (header.contains("CONNECT") && GizmoView.getView().intercepting()) {
            handle_connect_protocol();
            if (!GizmoView.getView().config().terminateSSL()) {
                return false;
            }
            this.header = workingContents.substring(0, workingContents.indexOf("\r\n"));
        }
        if (GizmoView.getView().intercepting()) {
            if (header.contains("http")) {
                url = header.substring(header.indexOf("http"), header.indexOf("HTTP") - 1);
            } else {
                url = header.substring(header.indexOf("/"), header.indexOf("HTTP") - 1);
            }
            if (url.contains("//")) {
                host = url.substring(url.indexOf("//") + 2, url.indexOf("/", url.indexOf("//") + 2));
            } else {
                String upper = workingContents.toString().toUpperCase();
                int host_start = upper.indexOf("HOST:") + 5;
                host = workingContents.substring(host_start, upper.indexOf("\n", host_start)).trim();
            }
        }

        this.addContents(workingContents.toString());

    } catch (Exception e) {
        return false;
    }

    return true;
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestBlockReplacement.java

private boolean replaceBlock(Block block, DatanodeInfo source, DatanodeInfo sourceProxy,
        DatanodeInfo destination) throws IOException {
    Socket sock = new Socket();
    sock.connect(NetUtils.createSocketAddr(destination.getName()), HdfsConstants.READ_TIMEOUT);
    sock.setKeepAlive(true);/*from  w  w w.  ja v a 2s.  c o  m*/
    // sendRequest
    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION);
    out.writeByte(DataTransferProtocol.OP_REPLACE_BLOCK);
    out.writeLong(block.getBlockId());
    out.writeLong(block.getGenerationStamp());
    Text.writeString(out, source.getStorageID());
    sourceProxy.write(out);
    BlockTokenSecretManager.DUMMY_TOKEN.write(out);
    out.flush();
    // receiveResponse
    DataInputStream reply = new DataInputStream(sock.getInputStream());

    short status = reply.readShort();
    if (status == DataTransferProtocol.OP_STATUS_SUCCESS) {
        return true;
    }
    return false;
}