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:de.tudarmstadt.ukp.dkpro.core.io.bincas.BinaryCasReader.java

@Override
public void getNext(CAS aCAS) throws IOException, CollectionException {
    Resource res = nextFile();//from  www .j ava 2  s .  com
    InputStream is = null;
    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());
        BufferedInputStream bis = new BufferedInputStream(is);

        TypeSystemImpl ts = null;

        // Check if this is original UIMA CAS format or DKPro Core format
        bis.mark(10);
        DataInputStream dis = new DataInputStream(bis);
        byte[] dkproHeader = new byte[] { 'D', 'K', 'P', 'r', 'o', '1' };
        byte[] header = new byte[dkproHeader.length];
        dis.read(header);

        // If it is DKPro Core format, read the type system
        if (Arrays.equals(header, dkproHeader)) {
            ObjectInputStream ois = new ObjectInputStream(bis);
            CASMgrSerializer casMgrSerializer = (CASMgrSerializer) ois.readObject();
            ts = casMgrSerializer.getTypeSystem();
            ts.commit();
        } else {
            bis.reset();
        }

        if (ts == null) {
            // Check if this is a UIMA binary CAS stream
            byte[] uimaHeader = new byte[] { 'U', 'I', 'M', 'A' };

            byte[] header4 = new byte[uimaHeader.length];
            System.arraycopy(header, 0, header4, 0, header4.length);

            if (header4[0] != 'U') {
                ArrayUtils.reverse(header4);
            }

            // If it is not a UIMA binary CAS stream, assume it is output from
            // SerializedCasWriter
            if (!Arrays.equals(header4, uimaHeader)) {
                ObjectInputStream ois = new ObjectInputStream(bis);
                CASCompleteSerializer serializer = (CASCompleteSerializer) ois.readObject();
                deserializeCASComplete(serializer, (CASImpl) aCAS);
            } else {
                // Since there was no type system, it must be type 0 or 4
                deserializeCAS(aCAS, bis);
            }
        } else {
            // Only format 6 can have type system information
            deserializeCAS(aCAS, bis, ts, null);
        }
    } catch (ResourceInitializationException e) {
        throw new IOException(e);
    } catch (ClassNotFoundException e) {
        throw new IOException(e);
    } finally {
        closeQuietly(is);
    }
}

From source file:com.symbian.driver.remoting.master.TestResultSet.java

/**
 * Purpose : To open the zip file and read the contents into a byte array.
 * This will embed the bytes into this object
 * //from  www .j a  va  2s  .  c o m
 * @throws IOException
 */
public void Embed() throws IOException {

    // Create stream to file
    FileInputStream lFis = new FileInputStream(zipFileName);
    DataInputStream lDis = new DataInputStream(lFis);

    // Create the buffer
    contents = new byte[MAX_SIZE];

    // Read contents into byte array
    numberOfBytes = new Integer(lDis.read(contents));

    // Close the stream
    lFis.close();
    lDis.close();
}

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  www  . j ava2s.c om
        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:p2p.project.p2pnode.Test.java

@Override
public void run() {
    while (true) {
        try {//  w w  w  .  j a  va  2s .c  om
            clientSocket = serverSocket.accept();
            logger.log(Level.SEVERE, "Connected");
            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            byte[] messageByte = new byte[0];
            int bytesRead = 1;
            while (bytesRead > 0) {
                byte[] messagePartByte = new byte[1024];
                bytesRead = in.read(messagePartByte);
                if (bytesRead > 0) {
                    ByteArrayOutputStream tmpOutputStream = new ByteArrayOutputStream();
                    tmpOutputStream.write(messageByte);
                    tmpOutputStream.write(messagePartByte);

                    messageByte = tmpOutputStream.toByteArray();
                }
            }
            in.close();
            clientSocket.close();
            logger.log(Level.SEVERE, "Bytes readed: " + messageByte.length);

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

    }
}

From source file:com.atlassian.extras.decoder.v2.Version2LicenseDecoder.java

private byte[] checkAndGetLicenseText(String licenseContent) {
    try {/*from   www  .j a  v a2s.c  o  m*/
        byte[] decodedBytes = Base64.decodeBase64(licenseContent.getBytes());
        ByteArrayInputStream in = new ByteArrayInputStream(decodedBytes);
        DataInputStream dIn = new DataInputStream(in);
        int textLength = dIn.readInt();
        byte[] licenseText = new byte[textLength];
        dIn.read(licenseText);
        byte[] hash = new byte[dIn.available()];
        dIn.read(hash);
        /*try
        {
        Signature signature = Signature.getInstance("SHA1withDSA");
        signature.initVerify(PUBLIC_KEY);
        signature.update(licenseText);
        if (!signature.verify(hash)) {
            throw new LicenseException("Failed to verify the license.");
        }
        }
        catch (InvalidKeyException e)
        {
        throw new LicenseException(e);
        }
        catch (SignatureException e)
        {
        throw new LicenseException(e);
        }
        catch (NoSuchAlgorithmException e)
        {
        throw new LicenseException(e);
        }*/
        return licenseText;
    } catch (IOException e) {
        throw new LicenseException(e);
    }
}

From source file:com.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request/*from w  ww. ja v a2s .c o m*/
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + 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);
            }

            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(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            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:Version2LicenseDecoder.java

private byte[] checkAndGetLicenseText(String licenseContent) {
    try {//from w w  w .j a v  a 2  s . c  om
        byte[] e = Base64.decodeBase64(licenseContent.getBytes());
        ByteArrayInputStream in = new ByteArrayInputStream(e);
        DataInputStream dIn = new DataInputStream(in);
        int textLength = dIn.readInt();
        byte[] licenseText = new byte[textLength];
        dIn.read(licenseText);
        byte[] hash = new byte[dIn.available()];
        dIn.read(hash);

        try {
            Signature e1 = Signature.getInstance("SHA1withDSA");
            e1.initVerify(PUBLIC_KEY);
            e1.update(licenseText);
            if (!e1.verify(hash)) {
                throw new LicenseException("Failed to verify the license.");
            } else {
                return licenseText;
            }
        } catch (InvalidKeyException var9) {
            throw new LicenseException(var9);
        } catch (SignatureException var10) {
            throw new LicenseException(var10);
        } catch (NoSuchAlgorithmException var11) {
            throw new LicenseException(var11);
        }
    } catch (IOException var12) {
        throw new LicenseException(var12);
    }
}

From source file:com.cloudera.recordbreaker.hive.RegExpSerDe.java

/**
 * <code>initDeserializer</code> sets up the RegExp-specific
 * parts of the SerDe.  In particular, it loads in the regular
 * expressions and corresponding schema descriptions.
 *
 * The patternPayloadJSONFile parameter is a serailized JSON
 * object that contains the schema and regexp info.
 *///ww  w.  ja v a 2 s. c  o m
void initDeserializer(String patternPayloadJSONFile) {
    try {
        DataInputStream in = new DataInputStream(new FileInputStream(new File(patternPayloadJSONFile)));
        byte buf[] = new byte[8096];
        StringBuffer payload = new StringBuffer();
        try {
            int numBytes = in.read(buf);
            while (numBytes >= 0) {
                payload.append(new String(buf, 0, numBytes));
                numBytes = in.read(buf);
            }
        } finally {
            in.close();
        }
        String payloadStr = payload.toString();
        JSONObject jobj = new JSONObject(payloadStr);

        this.patterns = new ArrayList<Pattern>();
        JSONArray patternArray = jobj.getJSONArray("patterns");
        for (int i = 0; i < patternArray.length(); i++) {
            String patternStr = patternArray.getString(i);
            this.patterns.add(Pattern.compile(patternStr));
        }

        this.schemaOptions = new ArrayList<Schema>();
        JSONArray schemaOptionArray = jobj.getJSONArray("schemaoptions");
        for (int i = 0; i < schemaOptionArray.length(); i++) {
            String schemaStr = schemaOptionArray.getString(i);
            this.schemaOptions.add(Schema.parse(schemaStr));
        }
    } catch (UnsupportedEncodingException uee) {
        uee.printStackTrace();
    } catch (IOException iex) {
        iex.printStackTrace();
    } catch (JSONException jse) {
        jse.printStackTrace();
    }
}

From source file:com.nemesis.admin.UploadServlet.java

/**
 * @param request//from   w  ww  .  j a  v  a  2s. c o  m
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 * response)
 *
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = getFile(request, request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            try (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);
                }

                in.close();
                op.flush();
            }
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = getFile(request, 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 = getFile(request, request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            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) {
                    int newWidth = 75;
                    if (request.getParameter("w") != null) {
                        try {
                            newWidth = Integer.parseInt(request.getParameter("w"));
                        } catch (Exception e) {
                            //Se mantiene el valor por defecto de 75
                        }
                    }

                    BufferedImage thumb = Scalr.resize(im, newWidth);
                    if (request.getParameter("h") != null) {
                        try {
                            thumb = Scalr.crop(thumb, newWidth, Integer.parseInt(request.getParameter("h")));
                        } catch (IllegalArgumentException | ImagingOpException e) {
                            //Se mantienen las proporciones.
                        }
                    }

                    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");
                    }
                    try (ServletOutputStream srvos = response.getOutputStream()) {
                        response.setContentLength(os.size());
                        response.setHeader("Content-Disposition",
                                "inline; filename=\"" + file.getName() + "\"");
                        os.writeTo(srvos);
                        srvos.flush();
                    }
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:m3.classe.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 ww  .jav a2  s. c  om
    try {
        while ((len = dis.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        bytes = bos.toByteArray();
    } catch (IOException e) {
        Ressource.logger.error("Failed to get bytes from stream", e);
    } finally {
        IOUtils.closeQuietly(bos);
    }
    return bytes;
}