Example usage for java.io DataInputStream read

List of usage examples for java.io DataInputStream read

Introduction

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

Prototype

public final int read(byte b[]) throws IOException 

Source Link

Document

Reads some number of bytes from the contained input stream and stores them into the buffer array b.

Usage

From source file:org.vasanti.controller.DropZoneFileUpload.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(ImagefileUploadPath, request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            ServletOutputStream op = response.getOutputStream();
            response.setContentType(getMimeType(file));
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, bytes);
            }/*www  . j a  v a  2  s  .  c o m*/

            in.close();
            op.flush();
            op.close();
        }
    } //        else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
      //            File file = new File(request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile"));
      //            if (file.exists()) {
      //                file.delete(); // TODO:check and report success
      //            }
      //       } 
    else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = new File(ImagefileUploadPath, request.getParameter("getthumb"));
        if (file.exists()) {
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    BufferedImage thumb = Scalr.resize(im, 75);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:org.kurento.repository.test.RangePutTests.java

protected void uploadFileWithSeqPUTs(RepositoryHttpRecorder recorder, File fileToUpload,
        RepositoryItem repositoryItem) throws Exception {

    recorder.setAutoTerminationTimeout(500000);
    String url = recorder.getURL();

    DataInputStream is = null;

    try {//from   w w w.  jav a 2s  .  c  o m

        is = new DataInputStream(new FileInputStream(fileToUpload));

        int sentBytes = 0;

        byte[] info = new byte[40000];

        int readBytes;

        int numRequest = 0;

        while ((readBytes = is.read(info)) != -1) {

            ResponseEntity<String> response = putContent(url, Arrays.copyOf(info, readBytes), sentBytes);

            sentBytes += readBytes;

            log.info(numRequest + ": " + response.toString());

            assertEquals("Returned response: " + response.getBody(), HttpStatus.OK, response.getStatusCode());

            if (numRequest == 3) {

                // Simulating retry

                response = putContent(url, Arrays.copyOf(info, readBytes), sentBytes - readBytes);

                log.info(numRequest + ": " + response.toString());

                assertEquals("Returned response: " + response.getBody(), HttpStatus.OK,
                        response.getStatusCode());

            } else if (numRequest == 4) {

                // Simulating retry with new data

                byte[] newInfo = new byte[500];
                int newReadBytes = is.read(newInfo);

                response = putContent(url,
                        concat(Arrays.copyOf(info, readBytes), Arrays.copyOf(newInfo, newReadBytes)),
                        sentBytes - readBytes);

                sentBytes += newReadBytes;

                log.info(numRequest + ": " + response.toString());

                assertEquals("Returned response: " + response.getBody(), HttpStatus.OK,
                        response.getStatusCode());

            } else if (numRequest == 5) {

                // Simulating send ahead data

                response = putContent(url, Arrays.copyOf(info, readBytes), sentBytes + 75000);

                log.info(numRequest + ": " + response.toString());

                assertEquals("Returned response: " + response.getBody(), HttpStatus.NOT_IMPLEMENTED,
                        response.getStatusCode());

            }

            numRequest++;
        }

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }

        recorder.stop();
    }
}

From source file:org.fao.geonet.utils.Xml.java

/**
 * Reads file into byte array, detects charset and converts from this  
   * charset to UTF8//w  ww.j ava 2 s .  c om
 *
 * @param file file to decode and convert to UTF8
 * @return
 * @throws IOException
 * @throws CharacterCodingException
 */

public synchronized static byte[] convertFileToUTF8ByteArray(File file)
        throws IOException, CharacterCodingException {
    FileInputStream in = null;
    DataInputStream inStream = null;
    try {
        in = new FileInputStream(file);
        inStream = new DataInputStream(in);
        byte[] buf = new byte[(int) file.length()];
        int nrRead = inStream.read(buf);

        UniversalDetector detector = new UniversalDetector(null);
        detector.handleData(buf, 0, nrRead);
        detector.dataEnd();

        String encoding = detector.getDetectedCharset();
        detector.reset();
        if (encoding != null) {
            if (!encoding.equals(ENCODING)) {
                Log.error(Log.JEEVES, "Detected character set " + encoding + ", converting to UTF-8");
                return convertByteArrayToUTF8ByteArray(buf, encoding);
            }
        }
        return buf;
    } finally {
        if (in != null) {
            IOUtils.closeQuietly(in);
        }
        if (inStream != null) {
            IOUtils.closeQuietly(inStream);
        }
    }
}

From source file:org.openmrs.module.odkconnector.serialization.web.PatientWebConnectorTest.java

@Test
public void serialize_shouldDisplayAllPatientInformation() throws Exception {

    // compose url
    URL u = new URL(SERVER_URL + "/module/odkconnector/download/patients.form");

    // setup http url connection
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setDoOutput(true);/*  w w  w.  jav  a  2s .c o m*/
    connection.setRequestMethod("POST");
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);
    connection.addRequestProperty("Content-type", "application/octet-stream");

    // write auth details to connection
    DataOutputStream outputStream = new DataOutputStream(new GZIPOutputStream(connection.getOutputStream()));
    outputStream.writeUTF("admin");
    outputStream.writeUTF("test");
    outputStream.writeBoolean(true);
    outputStream.writeInt(2);
    outputStream.writeInt(1);
    outputStream.close();

    DataInputStream inputStream = new DataInputStream(new GZIPInputStream(connection.getInputStream()));
    Integer responseStatus = inputStream.readInt();

    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

    int count = 0;
    byte[] buffer = new byte[1024];
    while ((count = inputStream.read(buffer)) > 0) {
        arrayOutputStream.write(buffer, 0, count);
    }
    arrayOutputStream.close();
    inputStream.close();

    File file = new File("/home/nribeka/connector.data");
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(arrayOutputStream.toByteArray());
    fos.close();

    inputStream = new DataInputStream(new FileInputStream(file));

    if (responseStatus == HttpURLConnection.HTTP_OK) {

        // total number of patients
        Integer patientCounter = inputStream.readInt();
        System.out.println("Patient Counter: " + patientCounter);
        for (int j = 0; j < patientCounter; j++) {
            System.out.println("=================Patient=====================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Family Name: " + inputStream.readUTF());
            System.out.println("Middle Name: " + inputStream.readUTF());
            System.out.println("Last Name: " + inputStream.readUTF());
            System.out.println("Gender: " + inputStream.readUTF());
            System.out.println("Birth Date: " + inputStream.readUTF());
            System.out.println("Identifier: " + inputStream.readUTF());
            System.out.println("Patients: " + j + " out of " + patientCounter);
        }

        Integer obsCounter = inputStream.readInt();
        System.out.println("Observation Counter: " + obsCounter);
        for (int j = 0; j < obsCounter; j++) {
            System.out.println("==================Observation=================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Concept Name: " + inputStream.readUTF());

            byte type = inputStream.readByte();
            if (type == ObsSerializer.TYPE_STRING)
                System.out.println("Value: " + inputStream.readUTF());
            else if (type == ObsSerializer.TYPE_INT)
                System.out.println("Value: " + inputStream.readInt());
            else if (type == ObsSerializer.TYPE_DOUBLE)
                System.out.println("Value: " + inputStream.readDouble());
            else if (type == ObsSerializer.TYPE_DATE)
                System.out.println("Value: " + inputStream.readUTF());
            System.out.println("Time: " + inputStream.readUTF());
            System.out.println("Obs: " + j + " out of: " + obsCounter);
        }
        Integer formCounter = inputStream.readInt();
        System.out.println("Form Counter: " + formCounter);
        for (int j = 0; j < formCounter; j++) {
            System.out.println("==================Observation=================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Concept Name: " + inputStream.readUTF());

            byte type = inputStream.readByte();
            if (type == ObsSerializer.TYPE_STRING)
                System.out.println("Value: " + inputStream.readUTF());
            else if (type == ObsSerializer.TYPE_INT)
                System.out.println("Value: " + inputStream.readInt());
            else if (type == ObsSerializer.TYPE_DOUBLE)
                System.out.println("Value: " + inputStream.readDouble());
            else if (type == ObsSerializer.TYPE_DATE)
                System.out.println("Value: " + inputStream.readUTF());
            System.out.println("Time: " + inputStream.readUTF());
            System.out.println("Form: " + j + " out of: " + formCounter);
        }
    }
    inputStream.close();
}

From source file:Networking.Client.java

public void downloadFiles(byte[] bytes, File file, int BufLen) {
    try {// ww w.ja  va  2  s. co 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  .j  a  va 2s.  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:org.apache.hadoop.hbase.HRegionInfo.java

/**
 * Parses an HRegionInfo instance from the passed in stream.  Presumes the HRegionInfo was
 * serialized to the stream with {@link #toDelimitedByteArray()}
 * @param in/*w  ww.  j  a  va 2s  .  c o  m*/
 * @return An instance of HRegionInfo.
 * @throws IOException
 */
public static HRegionInfo parseFrom(final DataInputStream in) throws IOException {
    // I need to be able to move back in the stream if this is not a pb serialization so I can
    // do the Writable decoding instead.
    int pblen = ProtobufUtil.lengthOfPBMagic();
    byte[] pbuf = new byte[pblen];
    if (in.markSupported()) { //read it with mark()
        in.mark(pblen);
    }
    int read = in.read(pbuf); //assumption: if Writable serialization, it should be longer than pblen.
    if (read != pblen)
        throw new IOException("read=" + read + ", wanted=" + pblen);
    if (ProtobufUtil.isPBMagicPrefix(pbuf)) {
        return convert(HBaseProtos.RegionInfo.parseDelimitedFrom(in));
    } else {
        // Presume Writables.  Need to reset the stream since it didn't start w/ pb.
        if (in.markSupported()) {
            in.reset();
            HRegionInfo hri = new HRegionInfo();
            hri.readFields(in);
            return hri;
        } else {
            //we cannot use BufferedInputStream, it consumes more than we read from the underlying IS
            ByteArrayInputStream bais = new ByteArrayInputStream(pbuf);
            SequenceInputStream sis = new SequenceInputStream(bais, in); //concatenate input streams
            HRegionInfo hri = new HRegionInfo();
            hri.readFields(new DataInputStream(sis));
            return hri;
        }
    }
}

From source file:com.dream.library.utils.AbFileUtil.java

/**
 * ??byte[]./*from ww  w  .  j a  va2 s  . c  o  m*/
 *
 * @param imgByte       byte[]
 * @param fileName      ?????.jpg
 * @param type          ???AbConstant
 * @param desiredWidth  
 * @param desiredHeight 
 * @return Bitmap 
 */
public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth,
        int desiredHeight) {
    FileOutputStream fos = null;
    DataInputStream dis = null;
    ByteArrayInputStream bis = null;
    Bitmap bitmap = null;
    File file = null;
    try {
        if (imgByte != null) {

            file = new File(AbDirUtils.getDownloadDir(), fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            int readLength = 0;
            bis = new ByteArrayInputStream(imgByte);
            dis = new DataInputStream(bis);
            byte[] buffer = new byte[1024];

            while ((readLength = dis.read(buffer)) != -1) {
                fos.write(buffer, 0, readLength);
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            fos.flush();

            bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (Exception e) {
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
    return bitmap;
}

From source file:org.kles.m3.M3ClassLoader.java

private byte[] getBytesFromStream(DataInputStream dis) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    byte[] bytes = (byte[]) null;
    int len = 0;//from  w w  w  .j ava  2 s . com
    try {
        while ((len = dis.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        bytes = bos.toByteArray();
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to get bytes from stream", e);
    } finally {
        IOUtils.closeQuietly(bos);
    }
    return bytes;
}