Example usage for java.io DataInputStream close

List of usage examples for java.io DataInputStream close

Introduction

In this page you can find the example usage for java.io DataInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.webkey.Ipc.java

public void kill() {
    String pid = null;/*ww  w.  ja v  a 2s  .c  o  m*/
    //      Log.d(TAG,"trying to kill Webkey's service");
    try {
        FileInputStream fstream = new FileInputStream(workDir + "/pid.txt");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        pid = br.readLine();
        br.close();
        in.close();
        fstream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    //      Log.d(TAG,"pid: "+pid);
    try {
        String cmd = "kill -9 " + pid;
        Process p = Runtime.getRuntime().exec(cmd);
        p.waitFor();
        //         Log.d(TAG,"killed the service");
        return;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    for (String pre : new String[] { "/system/bin/", "/system/xbin/", "/system/xbin/bb/", "/system/sbin/" }) {
        try {
            String[] cmd = { pre + "kill", "-9", pid };
            File location = new File(pre);
            Process p = Runtime.getRuntime().exec(cmd, null, location);
            p.waitFor();
            //            Log.d(TAG,"killed the service");
            return;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.apache.hadoop.hbase.codec.TestCellMessageCodec.java

@Test
public void testThree() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CountingOutputStream cos = new CountingOutputStream(baos);
    DataOutputStream dos = new DataOutputStream(cos);
    MessageCodec cmc = new MessageCodec();
    Codec.Encoder encoder = cmc.getEncoder(dos);
    final KeyValue kv1 = new KeyValue(Bytes.toBytes("r"), Bytes.toBytes("f"), Bytes.toBytes("1"),
            Bytes.toBytes("1"));
    final KeyValue kv2 = new KeyValue(Bytes.toBytes("r"), Bytes.toBytes("f"), Bytes.toBytes("2"),
            Bytes.toBytes("2"));
    final KeyValue kv3 = new KeyValue(Bytes.toBytes("r"), Bytes.toBytes("f"), Bytes.toBytes("3"),
            Bytes.toBytes("3"));
    encoder.write(kv1);/*from  w w  w  .  j av a2 s.  co m*/
    encoder.write(kv2);
    encoder.write(kv3);
    encoder.flush();
    dos.close();
    long offset = cos.getCount();
    CountingInputStream cis = new CountingInputStream(new ByteArrayInputStream(baos.toByteArray()));
    DataInputStream dis = new DataInputStream(cis);
    Codec.Decoder decoder = cmc.getDecoder(dis);
    assertTrue(decoder.advance());
    Cell c = decoder.current();
    assertTrue(CellComparator.equals(c, kv1));
    assertTrue(decoder.advance());
    c = decoder.current();
    assertTrue(CellComparator.equals(c, kv2));
    assertTrue(decoder.advance());
    c = decoder.current();
    assertTrue(CellComparator.equals(c, kv3));
    assertFalse(decoder.advance());
    dis.close();
    assertEquals(offset, cis.getCount());
}

From source file:Enrichissement.GraphViz.java

/**
 * Read a DOT graph from a text file./*from  w  w  w . j a  v  a 2s  .  c  o m*/
 * 
 * @param input Input text file containing the DOT graph
 * source.
 */
public void readSource(String input) {
    StringBuilder sb = new StringBuilder();

    try {
        FileInputStream fis = new FileInputStream(input);
        DataInputStream dis = new DataInputStream(fis);
        BufferedReader br = new BufferedReader(new InputStreamReader(dis));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        dis.close();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }

    this.graph = sb;
}

From source file:gobblin.metrics.reporter.KafkaAvroEventReporterWithSchemaRegistryTest.java

@Test
public void test() throws Exception {

    MetricContext context = MetricContext.builder("context").build();

    MockKafkaPusher pusher = new MockKafkaPusher();
    KafkaAvroSchemaRegistry registry = Mockito.mock(KafkaAvroSchemaRegistry.class);
    Mockito.when(registry.register(Mockito.any(Schema.class))).thenAnswer(new Answer<String>() {
        @Override//from  ww w. j a  va  2  s  .  c  o m
        public String answer(InvocationOnMock invocation) throws Throwable {
            return register((Schema) invocation.getArguments()[0]);
        }
    });
    Mockito.when(registry.register(Mockito.any(Schema.class), Mockito.anyString()))
            .thenAnswer(new Answer<String>() {
                @Override
                public String answer(InvocationOnMock invocation) throws Throwable {
                    return register((Schema) invocation.getArguments()[0]);
                }
            });
    KafkaEventReporter kafkaReporter = KafkaAvroEventReporter.forContext(context).withKafkaPusher(pusher)
            .withSchemaRegistry(registry).build("localhost:0000", "topic");

    GobblinTrackingEvent event = new GobblinTrackingEvent(0l, "namespace", "name",
            Maps.<String, String>newHashMap());

    context.submitEvent(event);

    try {
        Thread.sleep(100);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    kafkaReporter.report();

    try {
        Thread.sleep(100);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    byte[] nextMessage = pusher.messageIterator().next();
    DataInputStream is = new DataInputStream(new ByteArrayInputStream(nextMessage));
    Assert.assertEquals(is.readByte(), KafkaAvroSchemaRegistry.MAGIC_BYTE);
    byte[] readId = new byte[20];
    Assert.assertEquals(is.read(readId), 20);
    String readStringId = Hex.encodeHexString(readId);
    Assert.assertTrue(this.schemas.containsKey(readStringId));

    Schema schema = this.schemas.get(readStringId);
    Assert.assertFalse(schema.toString().contains("avro.java.string"));

    is.close();
}

From source file:ee.pri.rl.blog.web.servlet.FileDownloadServlet.java

private void sendFile(String path, String calculatedTag, File directory, HttpServletResponse resp) {
    File file = new File(directory, path);

    String mimeType = getServletContext().getMimeType(path);
    if (mimeType == null) {
        mimeType = "application/octet-stream";
    }/*from w  ww.j  a  v a  2s  . c  o  m*/

    resp.setHeader("ETag", calculatedTag);
    resp.setDateHeader("Date", System.currentTimeMillis());
    resp.setContentType(mimeType);
    resp.setContentLength((int) file.length());
    long liveTime = 3600 * 24 * 30;
    resp.setDateHeader("Expires", System.currentTimeMillis() + liveTime * 1000);
    resp.setHeader("Cache-Control", "public, max-age=" + liveTime);

    try {
        DataInputStream input = new DataInputStream(new FileInputStream(file));
        try {
            IOUtils.copy(input, resp.getOutputStream());
            resp.getOutputStream().flush();
            resp.getOutputStream().close();
        } catch (IOException e) {
            log.warn("Sending " + file + " failed", e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        if (input != null) {
            input.close();
        }
    } catch (IOException e) {
        log.warn("Sending " + file + " failed", e);
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e1) {
            log.warn("Sending response for " + file + " failed");
        }
    }
}

From source file:cn.xiongyihui.wificar.MjpegStream.java

public void run() {
    URI uri = URI.create(mUrl);
    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpResponse httpResponse = null;//ww  w .j  a v a  2 s.  c o  m
    try {
        httpResponse = httpClient.execute(new HttpGet(uri));
    } catch (IOException e) {
        Log.v(TAG, e.getMessage());

        return;
    }

    HttpEntity httpEntity = httpResponse.getEntity();
    String contentType = httpEntity.getContentType().getValue();
    if (!contentType.startsWith(CONTENT_TYPE_PREFIX)) {
        Log.v(TAG, "Content-Type: " + contentType);
        Log.v(TAG, mUrl + " is not MJPEG format");

        return;
    }

    mBoundary = contentType.substring(CONTENT_TYPE_PREFIX.length());

    BufferedInputStream in = null;
    try {
        in = new BufferedInputStream(httpEntity.getContent(), FRAME_MAX_LENGTH);
    } catch (IOException e) {
        Log.v(TAG, e.getMessage());

        return;
    }

    DataInputStream mjpeg = new DataInputStream(in);

    while (mRun) {
        Bitmap bitmap = null;

        try {
            bitmap = readFrame(mjpeg);
        } catch (IOException e) {
            Log.v(TAG, e.getMessage());

            break;
        }

        if (onFrameReadCallback != null) {
            onFrameReadCallback.onFrameRead(bitmap);
        }
    }

    try {
        mjpeg.close();
    } catch (IOException e) {
        Log.v(TAG, e.getMessage());
    }
}

From source file:Networking.Client.java

public void downloadFiles(byte[] bytes, File file, int BufLen) {
    try {//from   w ww  . ja  v  a2s.  c  o  m
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        DataInputStream dis = new DataInputStream(bis);
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buf = new byte[BufLen];
        int read = 0;
        while ((read = dis.read(buf)) != -1) {
            fos.write(buf);
        }
        fos.close();
        dis.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.b5chat.crossfire.web.FaviconServlet.java

private byte[] getImage(String url) {
    try {//from w  w  w .java 2  s  . c  o  m
        // Try to get the fiveicon from the url using an HTTP connection from the pool
        // that also allows to configure timeout values (e.g. connect and get data)
        GetMethod get = new GetMethod(url);
        get.setFollowRedirects(true);
        int response = client.executeMethod(get);
        if (response < 400) {
            // Check that the response was successful. Should we also filter 30* code?
            return get.getResponseBody();
        } else {
            // Remote server returned an error so return null
            return null;
        }
    } catch (IllegalStateException e) {
        // Something failed (probably a method not supported) so try the old stye now
        try {
            URLConnection urlConnection = new URL(url).openConnection();
            urlConnection.setReadTimeout(1000);

            urlConnection.connect();
            DataInputStream di = new DataInputStream(urlConnection.getInputStream());

            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            DataOutputStream out = new DataOutputStream(byteStream);

            int len;
            byte[] b = new byte[1024];
            while ((len = di.read(b)) != -1) {
                out.write(b, 0, len);
            }
            di.close();
            out.flush();

            return byteStream.toByteArray();
        } catch (IOException ioe) {
            // We failed again so return null
            return null;
        }
    } catch (IOException ioe) {
        // We failed so return null
        return null;
    }
}

From source file:com.webkey.Ipc.java

private void readAuthKey() {
    try {//from  w  w  w . j  a v a 2  s.  co  m
        FileInputStream fstream = new FileInputStream(workDir + "/authkey.txt");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        authKey = br.readLine().replaceAll("/r", "").replaceAll("/n", "");
        br.close();
        in.close();
        fstream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
}