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:IntSort.java

public void readStream() {
    try {/*w  w  w . jav  a 2s. co m*/
        // Careful: Make sure this is big enough!
        // Better yet, test and reallocate if necessary      
        byte[] recData = new byte[50];

        // Read from the specified byte array
        ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);

        // Read Java data types from the above byte array
        DataInputStream strmDataType = new DataInputStream(strmBytes);

        if (rs.getNumRecords() > 0) {
            ComparatorInt comp = new ComparatorInt();

            int i = 1;
            RecordEnumeration re = rs.enumerateRecords(null, comp, false);
            while (re.hasNextElement()) {
                // Get data into the byte array          
                rs.getRecord(re.nextRecordId(), recData, 0);

                // Read back the data types      
                System.out.println("Record #" + i++);

                System.out.println("Name: " + strmDataType.readUTF());
                System.out.println("Dog: " + strmDataType.readBoolean());
                System.out.println("Rank: " + strmDataType.readInt());
                System.out.println("--------------------");

                // Reset so read starts at beginning of array 
                strmBytes.reset();
            }

            comp.compareIntClose();

            // Free enumerator
            re.destroy();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:de.hybris.platform.jobs.RemoveItemsJobPerformableTest.java

@Test
public void testClearSavedValuesFalseStreamPerformedJob() {
    final MediaModel mediaPk = new MediaModel();
    final DataInputStream dis = new DataInputStream(buildUpStream("pika", "poka", "nuka"));

    Mockito.when(mediaService.getStreamFromMedia(mediaPk)).thenReturn(dis);

    final RemoveItemsCronJobModel cronJob = new RemoveItemsCronJobModel();
    cronJob.setItemPKs(mediaPk); //null item pk media
    cronJob.setCreateSavedValues(Boolean.FALSE);

    PerformResult result = null;/*from  ww  w  .  j a v  a 2s .co m*/
    try {
        TestUtils.disableFileAnalyzer("Expected error logs inside ");
        result = performable.perform(cronJob);
    } finally {
        TestUtils.enableFileAnalyzer();
    }

    //TODO uncomment when we operate on models only
    Assert.assertEquals(0, cronJob.getItemsRefused().intValue());
    Assert.assertEquals(0, cronJob.getItemsDeleted().intValue());
    Assert.assertEquals(CronJobResult.FAILURE, result.getResult());
    Assert.assertEquals(CronJobStatus.FINISHED, result.getStatus());

    Mockito.verify(sessionService, Mockito.times(1)).removeAttribute("is.hmc.session");
    Mockito.verify(modelService, Mockito.never()).remove(Mockito.any(PK.class));
}

From source file:com.ikon.omr.OMRHelper.java

/**
 * process//from  ww w.  j a  v a2  s .  c  om
 */
public static Map<String, String> process(File fileToProcess, long omId) throws IOException, OMRException,
        DatabaseException, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException,
        MissingParameterException, WrongParameterException {
    Map<String, String> values = new HashMap<String, String>();
    Omr omr = OmrDAO.getInstance().findByPk(omId);
    InputStream asc = new ByteArrayInputStream(omr.getAscFileContent());
    InputStream config = new ByteArrayInputStream(omr.getConfigFileContent());
    InputStream fields = new ByteArrayInputStream(omr.getFieldsFileContent());

    if (asc != null && asc.available() > 0 && config != null && config.available() > 0 && fields != null
            && fields.available() > 0) {
        Gray8Image grayimage = ImageUtil.readImage(fileToProcess.getCanonicalPath());
        if (grayimage == null) {
            throw new OMRException("Not able to process the image as gray image");
        }

        ImageManipulation image = new ImageManipulation(grayimage);
        image.locateConcentricCircles();
        image.readConfig(config);
        image.readFields(fields);
        image.readAscTemplate(asc);
        image.searchMarks();
        File dataFile = FileUtils.createTempFile();
        image.saveData(dataFile.getCanonicalPath());

        // Parse data file

        FileInputStream dfStream = new FileInputStream(dataFile);
        DataInputStream in = new DataInputStream(dfStream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        while ((strLine = br.readLine()) != null) {
            // format key=value ( looking for first = )
            String key = "";
            String value = "";

            if (strLine.contains("=")) {
                key = strLine.substring(0, strLine.indexOf("="));
                value = strLine.substring(strLine.indexOf("=") + 1);
                value = value.trim();
            }

            if (!key.equals("")) {
                if (value.equals("")) {
                    IOUtils.closeQuietly(br);
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(dfStream);
                    IOUtils.closeQuietly(asc);
                    IOUtils.closeQuietly(config);
                    IOUtils.closeQuietly(fields);
                    throw new OMRException("Empty value");
                }

                if (omr.getProperties().contains(key)) {
                    values.put(key, value);
                }
            }
        }

        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(dfStream);
        IOUtils.closeQuietly(asc);
        IOUtils.closeQuietly(config);
        IOUtils.closeQuietly(fields);
        FileUtils.deleteQuietly(dataFile);
        return values;
    } else {
        throw new OMRException("Error asc, config or fields files not found");
    }
}

From source file:edu.umd.JBizz.BooleanRetrievalCompressed.java

private ArrayListWritable<PairOfInts> fetchPostings(String term) throws IOException {
    Text key = new Text();
    //PairOfWritables<IntWritable, ArrayListWritable<PairOfInts>> value =
    //new PairOfWritables<IntWritable, ArrayListWritable<PairOfInts>>();
    ArrayListWritable<PairOfInts> poi = new ArrayListWritable<PairOfInts>();
    BytesWritable value = new BytesWritable();
    PairOfInts pair = new PairOfInts();
    key.set(term);/*  ww w.  jav  a2s .  c  om*/
    index.get(key, value);
    byte[] vals = value.getBytes();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(vals));
    int j = 0;
    int i = 0;
    int sentinel = 0;
    while (sentinel == 0) {
        j = WritableUtils.readVInt(dis);
        i = WritableUtils.readVInt(dis);
        if (i == 0 || j == 0) {
            sentinel = 1;
        } else {
            pair.set(j, i);
            poi.add(new PairOfInts(j, i));
        }
    }
    return poi;
}

From source file:com.netflix.aegisthus.input.AegSplit.java

public InputStream getInput(Configuration conf) throws IOException {
    FileSystem fs = path.getFileSystem(conf);
    FSDataInputStream fileIn = fs.open(path);
    InputStream dis = new DataInputStream(new BufferedInputStream(fileIn));
    if (compressed) {
        FSDataInputStream cmIn = fs.open(compressedPath);
        compressionMetadata = new CompressionMetadata(new BufferedInputStream(cmIn), end - start);
        dis = new CompressionInputStream(dis, compressionMetadata);
        end = compressionMetadata.getDataLength();
    }//from ww  w.j ava  2 s. c o  m
    return dis;
}

From source file:de.unisb.cs.st.javaslicer.traceResult.TraceResult.java

public TraceResult(File filename) throws IOException {
    final MultiplexedFileReader file = new MultiplexedFileReader(filename);
    if (file.getStreamIds().size() < 2)
        throw new IOException("corrupted data");
    final MultiplexInputStream readClassesStream = file.getInputStream(0);
    if (readClassesStream == null)
        throw new IOException("corrupted data");
    PushbackInputStream pushBackInput = new PushbackInputStream(
            new BufferedInputStream(new GZIPInputStream(readClassesStream, 512), 512), 1);
    final DataInputStream readClassesInputStream = new DataInputStream(pushBackInput);
    final ArrayList<ReadClass> readClasses0 = new ArrayList<ReadClass>();
    final StringCacheInput stringCache = new StringCacheInput();
    int testRead;
    while ((testRead = pushBackInput.read()) != -1) {
        pushBackInput.unread(testRead);/*from w ww  .j av  a 2 s  . c o  m*/
        readClasses0.add(ReadClass.readFrom(readClassesInputStream, stringCache));
    }
    readClasses0.trimToSize();
    Collections.sort(readClasses0);
    this.readClasses = readClasses0;
    this.instructions = getInstructionArray(readClasses0);

    final MultiplexInputStream threadTracersStream = file.getInputStream(1);
    if (threadTracersStream == null)
        throw new IOException("corrupted data");
    pushBackInput = new PushbackInputStream(
            new BufferedInputStream(new GZIPInputStream(threadTracersStream, 512), 512), 1);
    final DataInputStream threadTracersInputStream = new DataInputStream(pushBackInput);

    final ArrayList<ThreadTraceResult> threadTraces0 = new ArrayList<ThreadTraceResult>();
    while ((testRead = pushBackInput.read()) != -1) {
        pushBackInput.unread(testRead);
        threadTraces0.add(ThreadTraceResult.readFrom(threadTracersInputStream, this, file));
    }
    threadTraces0.trimToSize();
    Collections.sort(threadTraces0);
    this.threadTraces = threadTraces0;
}

From source file:ca.hec.commons.utils.MergePropertiesUtils.java

/**
 * Merge newProps to mainProps.//from   ww w.ja  v  a 2  s.c o  m
        
 * NOTE: The idea is that we want to write out the properties in exactly the same order, for future comparison purposes.
 * 
 * @param newPropertiesFile
 * @param newProps
 * @return nb of properties from main props file.
 */
public static void merge(File newPropertiesFile, Properties updatedProps) throws Exception {
    /**
     * 1) Read line by line of the new PropertiesFile (Sakai 2.9.1)
     *  For each line: extract property
     *  check if we have a match one in the propToMerge 
     *    - if no, then rewrite the same line
     *    - if yes: - if same value, rewrite the same line 
     *              - if different value, rewrite the prop with the new value
     *              - For both cases, delete the key from newProperties.
     *              
     *  2) At the end, write the remaining list of propToMerge at
     *     the end of mainProp
     */

    try {

        int nbPropsInMain = 0;
        int nbPropsChanged = 0;
        int nbPropsSimilar = 0;
        int nbPropsNotInNew = 0;

        // Open the file that is the first
        // command line parameter
        FileInputStream fstream = new FileInputStream(newPropertiesFile);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        LineWithContinuation lineIn;

        // Read File Line By Line
        while ((lineIn = LineWithContinuation.readLineWithContinuation(br)) != null) {

            KeyValue keyValue = extractKeyValue(lineIn.getFullLine());

            // May be a comment line, or blank line, or not a line containing key & property pair (we expect "key = value" line).
            // Simply echo the line back.
            if (keyValue == null) {
                System.out.println(lineIn.getFullLine());
                continue;
            }

            nbPropsInMain++;

            String key = keyValue.key;
            //System.out.println(key);

            String newValue = updatedProps.getProperty(key);
            String valueEscaped = unescapeJava(keyValue.value);

            if (newValue != null) {
                if (!newValue.equals(valueEscaped)) {
                    String newLine = composeNewPropLine(key, StringEscapeUtils.escapeJava(newValue));
                    System.out.println(newLine);
                    nbPropsChanged++;
                } else {
                    System.out.println(lineIn.getLineWithReturn());
                    nbPropsSimilar++;
                }

                // remove the key from newProps because it is used
                updatedProps.remove(key);
            } else {
                System.out.println(lineIn.getLineWithReturn());
                nbPropsNotInNew++;
            }
        }

        // Close the input stream
        in.close();

        System.out.println("\n\n### " + nbPropsInMain + " properties in SAKAI 11 (" + nbPropsChanged
                + " changed, " + nbPropsSimilar + " props with same value in both versions, " + nbPropsNotInNew
                + " not in 2.9.1)");

    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
        throw e;
    }
}

From source file:org.thoughtcrime.securesms.mms.MmsCommunication.java

protected static byte[] parseResponse(HttpEntity entity) throws IOException {
    if (entity == null || entity.getContentLength() == 0)
        throw new IOException("Null response");

    byte[] responseBytes = new byte[(int) entity.getContentLength()];
    DataInputStream dataInputStream = new DataInputStream(entity.getContent());
    dataInputStream.readFully(responseBytes);
    dataInputStream.close();//from   w  w  w  .  j  a  va 2s.c om

    entity.consumeContent();
    return responseBytes;
}

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
 * /*  w  ww.j  a  va 2  s . c om*/
 * @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:com.criptext.socket.DarkStarSocketClient.java

/**
 * @see DarkStarClient#connect()/*from   w  w  w.  jav  a2s.c o  m*/
 *
 * @throws java.io.IOException
 */
public void connect() throws IOException {

    //s = (SocketConnection) Connector.open("socket://" + this.host + ":" + this.port+"?"+ConnectionType.getConnectionString(), Connector.READ_WRITE);
    try {
        s = new Socket(this.host, this.port);
        s.setReceiveBufferSize(2048 * 2048);
        s.setSendBufferSize(2048 * 2048);
        //Log.d("DarkStarSocketClient - connect", "creando socket s:"+ s+"host"+this.host+"port"+this.port);

    } catch (Exception e) {
        System.out.println(e.toString());
    }

    DataInputStream in = new DataInputStream(s.getInputStream());
    //Log.d("DarkStarSocketClient - connect", "definiendo in: "+in);
    DataOutputStream out = new DataOutputStream(s.getOutputStream());
    //Log.d("DarkStarSocketClient - connect", "definiendo out: "+out);

    reader = new InputReader(this, in);
    //Log.d("DarkStarSocketClient - connect", "reader: "+reader);
    writer = new OutputWriter(this, out);
    //Log.d("DarkStarSocketClient - connect", "writer: "+writer);
    new Thread(reader).start();
    //Log.d("DarkStarSocketClient - connect", "Empezar hilo reader");
    new Thread(writer).start();
    //Log.d("DarkStarSocketClient - connect", "Empezar hilo writer");

    //give the threads some time to set-up (should be done in a better way)
    try {
        //Log.d("DarkStarSocketClient - connect", "Empieza suspension del hilo durante 1000 (s)");
        Thread.sleep(1000);
        //Log.d("DarkStarSocketClient - connect", "Terminaron los 1000 (s) de la suspension del hilo");
    } catch (InterruptedException ex) {
        //Log.d("DarkStarSocketClient - connect", "Exception: "+ex);
        ex.printStackTrace();
    }
}