Example usage for java.io DataInputStream DataInputStream

List of usage examples for java.io DataInputStream DataInputStream

Introduction

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

Prototype

public DataInputStream(InputStream in) 

Source Link

Document

Creates a DataInputStream that uses the specified underlying InputStream.

Usage

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

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

    HttpResponse httpResponse = null;/*from w  ww.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:edu.umn.cs.spatialHadoop.mapreduce.RTreeRecordReader3.java

public void initialize(InputSplit split, Configuration conf) throws IOException, InterruptedException {
    LOG.info("Open a SpatialRecordReader to split: " + split);
    FileSplit fsplit = (FileSplit) split;
    this.path = fsplit.getPath();
    this.start = fsplit.getStart();
    this.end = this.start + split.getLength();
    this.fs = this.path.getFileSystem(conf);
    this.directIn = fs.open(this.path);
    codec = new CompressionCodecFactory(conf).getCodec(this.path);

    if (codec != null) {
        // Input is compressed, create a decompressor to decompress it
        decompressor = CodecPool.getDecompressor(codec);
        if (codec instanceof SplittableCompressionCodec) {
            // A splittable compression codec, can seek to the desired input pos
            final SplitCompressionInputStream cIn = ((SplittableCompressionCodec) codec).createInputStream(
                    directIn, decompressor, start, end, SplittableCompressionCodec.READ_MODE.BYBLOCK);
            in = new DataInputStream(cIn);
            start = cIn.getAdjustedStart();
            end = cIn.getAdjustedEnd();/* w ww  .  j  av a 2 s .  c o  m*/
            // take pos from compressed stream as we adjusted both start and end
            // to match with the compressed file
            filePosition = cIn;
        } else {
            // Non-splittable input, need to start from the beginning
            CompressionInputStream cIn = codec.createInputStream(directIn, decompressor);
            in = new DataInputStream(cIn);
            filePosition = cIn;
        }
    } else {
        // Non-compressed file, seek to the desired position and use this stream
        // to get the progress and position
        directIn.seek(start);
        in = directIn;
        filePosition = directIn;
    }
    byte[] signature = new byte[8];
    in.readFully(signature);
    if (!Arrays.equals(signature, SpatialSite.RTreeFileMarkerB)) {
        throw new RuntimeException("Incorrect signature for RTree");
    }
    this.stockShape = (V) OperationsParams.getShape(conf, "shape");

    if (conf.get(SpatialInputFormat3.InputQueryRange) != null) {
        // Retrieve the input query range to apply on all records
        this.inputQueryRange = OperationsParams.getShape(conf, SpatialInputFormat3.InputQueryRange);
        this.inputQueryMBR = this.inputQueryRange.getMBR();
    }

    // Check if there is an associated global index to read cell boundaries
    GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, path.getParent());
    if (gindex == null) {
        cellMBR = new Partition();
        cellMBR.invalidate();
    } else {
        // Set from the associated partition in the global index
        for (Partition p : gindex) {
            if (p.filename.equals(this.path.getName()))
                cellMBR = p;
        }
    }
}

From source file:com.cloudera.impala.security.DelegationTokenSecretManager.java

public DelegationTokenIdentifier tokenIdentifierFromTokenString(String tokenStr) throws IOException {
    Token<DelegationTokenIdentifier> token = tokenFromString(tokenStr);
    DelegationTokenIdentifier d = new DelegationTokenIdentifier();
    d.readFields(new DataInputStream(new ByteArrayInputStream(token.getIdentifier())));
    return d;//  w  ww .  java 2 s. c om
}

From source file:gobblin.runtime.mapreduce.GobblinWorkUnitsInputFormatTest.java

@Test
public void testSplit() throws Exception {
    List<String> paths = Lists.newArrayList("/path1", "/path2");
    GobblinWorkUnitsInputFormat.GobblinSplit split = new GobblinWorkUnitsInputFormat.GobblinSplit(paths);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    split.write(new DataOutputStream(os));

    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    GobblinWorkUnitsInputFormat.GobblinSplit deserSplit = new GobblinWorkUnitsInputFormat.GobblinSplit();
    deserSplit.readFields(new DataInputStream(is));

    Assert.assertEquals(split, deserSplit);
}

From source file:dbseer.old.middleware.MiddlewareSocket.java

public synchronized boolean connect(String ip, int port) throws IOException {
    this.ip = ip;
    this.port = port;
    socket = new Socket();
    InetSocketAddress address = new InetSocketAddress(ip, port);
    try {/*from w  w w .  j a v a  2s.com*/
        socket.connect(address, MIDDLEWARE_CONNECT_TIMEOUT);
        socket.setSoTimeout(MIDDLEWARE_SOCKET_TIMEOUT);
        input = new DataInputStream(socket.getInputStream());
        output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
        isConnected = true;
    } catch (Exception e) {
        DBSeerExceptionHandler.handleException(e);
        return false;
    }
    return true;
}

From source file:com.android.unit_tests.CheckinProviderTest.java

@MediumTest
public void testCrashReport() throws Exception {
    long start = System.currentTimeMillis();
    ContentResolver r = getContext().getContentResolver();

    // Log a test (fake) crash report.
    Checkin.reportCrash(r, new CrashData("Test", "Test Activity", new BuildData("Test Build", "123", start),
            new ThrowableData(new RuntimeException("Test Exception"))));

    // Crashes aren't indexed; go through them all to find the one we added.
    Cursor c = r.query(Checkin.Crashes.CONTENT_URI, null, null, null, null);

    Uri uri = null;//from ww  w  . j  av a2 s  .  c o m
    while (c.moveToNext()) {
        String coded = c.getString(c.getColumnIndex(Checkin.Crashes.DATA));
        byte[] bytes = Base64.decodeBase64(coded.getBytes());
        CrashData crash = new CrashData(new DataInputStream(new ByteArrayInputStream(bytes)));

        // Should be exactly one recently added "Test" crash.
        if (crash.getId().equals("Test") && crash.getTime() > start) {
            assertEquals("Test Activity", crash.getActivity());
            assertEquals("Test Build", crash.getBuildData().getFingerprint());
            assertEquals("Test Exception", crash.getThrowableData().getMessage());

            assertNull(uri);
            uri = ContentUris.withAppendedId(Checkin.Crashes.CONTENT_URI,
                    c.getInt(c.getColumnIndex(Checkin.Crashes._ID)));
        }
    }
    assertNotNull(uri);
    c.close();

    // Update the "logs" column.
    ContentValues values = new ContentValues();
    values.put(Checkin.Crashes.LOGS, "Test Logs");
    assertEquals(1, r.update(uri, values, null, null));

    c = r.query(uri, null, null, null, null);
    assertTrue(c.moveToNext());
    String logs = c.getString(c.getColumnIndex(Checkin.Crashes.LOGS));
    assertEquals("Test Logs", logs);
    c.deleteRow();
    c.close();

    c.requery();
    assertFalse(c.moveToNext());
    c.close();
}

From source file:XmlUtils.java

public static Document parse(URL url) throws DocumentException, IOException {
    URLConnection urlConnection;/*from  w  w w .java 2  s . com*/
    DataInputStream inStream;
    urlConnection = url.openConnection();
    ((HttpURLConnection) urlConnection).setRequestMethod("GET");

    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(false);
    urlConnection.setUseCaches(false);
    inStream = new DataInputStream(urlConnection.getInputStream());

    byte[] bytes = new byte[1024];
    int read;
    StringBuilder builder = new StringBuilder();
    while ((read = inStream.read(bytes)) >= 0) {
        String readed = new String(bytes, 0, read, "UTF-8");
        builder.append(readed);
    }
    SAXReader reader = new SAXReader();

    XmlUtils.createIgnoreErrorHandler(reader);
    //        InputSource inputSource = new InputSource(new InputStreamReader(inStream, "UTF-8"));
    //        inputSource.setEncoding("UTF-8");
    Document dom = reader.read(new StringReader(builder.toString()));
    inStream.close();
    //        new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("retrieval.xml"), "UTF-8")
    return dom;
}

From source file:m3.classe.M3ClassLoader.java

private DataInputStream getStreamFromJar(String name, File path) throws MAKException {
    if (!this.m_zipProblems.contains(path)) {
        try {/*  w  ww.j a va  2 s . com*/
            DataInputStream dis = null;
            ZipFile file = new ZipFile(path);
            ZipEntry entry = file.getEntry(name.replace('.', '/') + '.' + "class");
            if (entry == null) {
                entry = file.getEntry(name.replace('.', '/') + '.' + "properties");
            }
            if (entry != null)
                ;
            return new DataInputStream(file.getInputStream(entry));
        } catch (IOException e) {
            Ressource.logger.warn("Failed to get " + name + " from jar " + path
                    + " - MAK will try again using another method", e);
            this.m_zipProblems.add(path);
        }
    }
    return getStreamFromJar2(name, path);
}

From source file:com.hernandez.rey.crypto.TripleDES.java

/**
 * Read a TripleDES secret key from the specified file
 * /*from   w w  w. j a va  2  s  .  co  m*/
 * @param keyFile key file to read
 * @return secret key appropriate for encryption/decryption with 3DES
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws InvalidKeySpecException
 */
public static SecretKey readKey(final File keyFile)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    // Read the raw bytes from the keyfile
    final DataInputStream in = new DataInputStream(new FileInputStream(keyFile));
    final byte[] rawkey = new byte[(int) keyFile.length()];
    in.readFully(rawkey);
    in.close();

    // Convert the raw bytes to a secret key like this
    final DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
    final SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
    final SecretKey key = keyfactory.generateSecret(keyspec);
    return key;
}