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:org.openxdata.server.servlet.WMDownloadServlet.java

private void downloadStudies(HttpServletResponse response) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    formDownloadService.downloadStudies(dos, "", "");
    baos.flush();//from w ww  .  j  a v a  2 s .  co m
    dos.flush();
    byte[] data = baos.toByteArray();
    baos.close();
    dos.close();

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    PrintWriter out = response.getWriter();
    out.println("<StudyList>");

    try {
        @SuppressWarnings("unused")
        byte size = dis.readByte(); //reads the size of the studies

        while (true) {
            String value = "<study id=\"" + dis.readInt() + "\" name=\"" + dis.readUTF() + "\"/>";
            out.println(value);
        }
    } catch (EOFException exe) {
        //exe.printStackTrace();
    }
    out.println("</StudyList>");
    out.flush();
    dis.close();
}

From source file:com.app.server.util.FarmWarFileTransfer.java

public void setState(InputStream input) throws Exception {
    List<String> list = (List<String>) Util.objectFromStream(new DataInputStream(input));
    synchronized (state) {
        state.clear();//from  w w w  .jav  a  2 s.  c  o m
        state.addAll(list);
    }
    //log.info("received state (" + list.size() + " messages in chat history):");
    for (String str : list) {
        log.info(str);
    }
}

From source file:io.cloudslang.content.database.utils.SQLUtils.java

public static List<String> readFromFile(String fileName) {
    final List<String> lines = new ArrayList<>();

    try (final FileInputStream fstream = new FileInputStream(new File(fileName));
            final DataInputStream in = new DataInputStream(fstream);
            final InputStreamReader inputStreamReader = new InputStreamReader(in);
            final BufferedReader br = new BufferedReader(inputStreamReader)) {

        String strLine;/*from  ww w.j  a  v a  2 s  .  c  o  m*/
        StringBuilder aString = new StringBuilder();
        int i = 0;
        boolean youAreInAMultiLineComment = false;
        while ((strLine = br.readLine()) != null) {
            //ignore multi line comments
            if (youAreInAMultiLineComment) {
                if (strLine.contains("*/")) {
                    int indx = strLine.indexOf("*/");
                    strLine = strLine.substring(indx + 2);
                    youAreInAMultiLineComment = false;
                } else {
                    continue;
                }
            }

            if (strLine.contains("/*")) {
                int indx = strLine.indexOf("/*");
                String firstPart = strLine.substring(0, indx);
                String secondPart = strLine.substring(indx + 2);
                strLine = firstPart;
                youAreInAMultiLineComment = true;

                if (secondPart.contains("*/")) { //the comment starts and ends in the middle of the line
                    indx = secondPart.indexOf("*/");
                    secondPart = secondPart.substring(indx + 2);
                    youAreInAMultiLineComment = false;
                    strLine += secondPart;
                }
            }

            //ignore one line comments
            if (strLine.contains("--")) {
                int indx = strLine.indexOf("--");
                strLine = strLine.substring(0, indx);
            }

            //ignore empty lines
            if (0 == strLine.length()) {
                continue;
            }

            //consider if a SQL statement is separated in different lines. eg,
            //create table employee(
            //  first varchar(15));
            //if a sql command finishes in one line, add in commands
            if (strLine.endsWith(SEMI_COLON)) {
                //get rid of ';',otherwise the operation will fail on Oracle database
                int indx = strLine.indexOf(SEMI_COLON, 0);
                strLine = strLine.substring(0, indx);
                //if the command has only one line
                if (i == 0) {
                    lines.add(strLine);
                }
                //if the command has multiple lines
                else {
                    aString.append(strLine);
                    lines.add(aString.toString());
                    aString = new StringBuilder();
                    i = 0;
                }
            } else {//if a line doesn't finish with a ';', it means the sql commands is not finished
                aString.append(strLine).append(" ");
                i++;
            }
        }
    } catch (Exception e) {
        e.printStackTrace(); //todo
        return Collections.emptyList();
    }
    return lines;
}

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

@Test
public void testNotAllSkipofDeletedAndRefused() {
    final PK one = PK.createFixedUUIDPK(102, 1);
    final PK two = PK.createFixedUUIDPK(102, 2);
    final PK three = PK.createFixedUUIDPK(102, 3);

    final MediaModel mediaPk = new MediaModel();
    final DataInputStream dis = new DataInputStream(buildUpStream(one, two, three));

    Mockito.when(model.getItemPKs()).thenReturn(mediaPk);
    Mockito.when(mediaService.getStreamFromMedia(mediaPk)).thenReturn(dis);
    Mockito.when(model.getItemsRefused()).thenReturn(Integer.valueOf(1));
    Mockito.when(model.getItemsDeleted()).thenReturn(Integer.valueOf(1));

    iterator.init(model);/*from  w ww .  j  a va 2 s  .  c  o m*/

    Assert.assertTrue("Not all iterations should be skipped ", iterator.hasNext());
    Assert.assertEquals("Should only return last element ", three, iterator.next());
    Assert.assertFalse("Now all iterations should be skipped ", iterator.hasNext());
}

From source file:org.motechproject.mobile.web.OXDFormDownloadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*ww w .ja  v  a  2s . co m*/
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
@RequestMapping(method = RequestMethod.POST)
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Get our raw input and output streams
    InputStream input = request.getInputStream();
    OutputStream output = response.getOutputStream();

    // Wrap the streams for compression
    ZOutputStream zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION);

    // Wrap the streams so we can use logical types
    DataInputStream dataInput = new DataInputStream(input);
    DataOutputStream dataOutput = new DataOutputStream(zOutput);

    try {

        // Read the common submission data from mobile phone
        String name = dataInput.readUTF();
        String password = dataInput.readUTF();
        String serializer = dataInput.readUTF();
        String locale = dataInput.readUTF();

        byte action = dataInput.readByte();

        // TODO: add authentication, possible M6 enhancement

        log.info("downloading: name=" + name + ", password=" + password + ", serializer=" + serializer
                + ", locale=" + locale + ", action=" + action);

        EpihandyXformSerializer serObj = new EpihandyXformSerializer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Perform the action specified by the mobile phone
        try {
            if (action == ACTION_DOWNLOAD_STUDY_LIST) {
                serObj.serializeStudies(baos, studyService.getStudies());
            } else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS) {

                serObj.serializeUsers(baos, userService.getUsers());

                int studyId = dataInput.readInt();
                String studyName = studyService.getStudyName(studyId);
                List<String> studyForms = formService.getStudyForms(studyId);

                serObj.serializeForms(baos, studyForms, studyId, studyName);

            }
        } catch (Exception e) {
            dataOutput.writeByte(RESPONSE_ERROR);
            throw new ServletException("failed to serialize data", e);
        }

        // Write out successful upload response
        dataOutput.writeByte(RESPONSE_SUCCESS);
        dataOutput.write(baos.toByteArray());
        response.setStatus(HttpServletResponse.SC_OK);

    } finally {
        // Should always do this
        dataOutput.flush();
        zOutput.finish();
        response.flushBuffer();
    }
}

From source file:net.morphbank.mbsvc3.webservices.RestServiceExcelUpload.java

private ArrayList<String> outputReport(String report, ArrayList<String> reportContent) {
    File file = new File(folderPath + report);
    FileInputStream input;/*  w w  w.j a  va  2 s  .  c  o  m*/
    BufferedReader reader;
    DataInputStream dis;
    String line;
    try {
        input = new FileInputStream(file);
        dis = new DataInputStream(input);
        reader = new BufferedReader(new InputStreamReader(dis));
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            reportContent.add(line);
        }
        input.close();
        dis.close();
        reader.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return reportContent;
}

From source file:Version2LicenseDecoder.java

private byte[] checkAndGetLicenseText(String licenseContent) {
    try {/*from w  w  w  .j  a v a 2s. c  o  m*/
        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: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  w w.  j ava2 s  .  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:au.edu.usq.fascinator.harvester.callista.CallistaHarvester.java

/**
 * Harvest the next set of files, and return their Object IDs
 *
 * @return Set<String> The set of object IDs just harvested
 * @throws HarvesterException is there are errors
 */// w ww.ja v  a2  s  . c o  m
@Override
public Set<String> getObjectIdList() throws HarvesterException {
    Set<String> fileObjectIdList = new HashSet<String>();

    // Data streams - get CSV data
    FileInputStream fstream;
    try {
        fstream = new FileInputStream(csvData);
    } catch (FileNotFoundException ex) {
        // We tested for this earlier
        throw new HarvesterException("Could not find file", ex);
    }
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    int i = 0;
    int j = 0;
    boolean stop = false;
    // Line by line from buffered reader
    String line;
    try {
        while ((line = br.readLine()) != null && !stop) {
            // Parse the CSV for this line
            String[][] values;
            try {
                values = CSVParser.parse(new StringReader(line));
            } catch (IOException ex) {
                log.error("Error parsing CSV file", ex);
                throw new HarvesterException("Error parsing CSV file", ex);
            }

            for (String[] columns : values) {
                // Ignore the header row
                if (columns[0].equals("RESEARCHER_ID")) {
                    for (String column : columns) {
                        // Print if debugging
                        //log.debug("HEADING {}: '{}'", j, column);
                        j++;
                    }
                    j = 0;

                    // Store normal data rows
                } else {
                    i++;
                    if (i % 500 == 0) {
                        log.info("Parsing row {}", i);
                    }
                    String rId = columns[0];
                    if (!parsedData.containsKey(rId)) {
                        // New researcher, add an empty list
                        parsedData.put(rId, new ArrayList());
                    }
                    parsedData.get(rId).add(columns);
                }
            }

            // Check our record limit if debugging
            if (limit != -1 && i >= limit) {
                stop = true;
                log.debug("Stopping at debugging limit");
            }
        }
        in.close();
    } catch (IOException ex) {
        log.error("Error reading from CSV file", ex);
        throw new HarvesterException("Error reading from CSV file", ex);
    }
    log.info("Parse complete: {} rows", i);

    // Process parsed data
    i = 0;
    for (String key : parsedData.keySet()) {
        // Create the new record
        JsonConfigHelper json = new JsonConfigHelper();
        JsonConfigHelper packageJson = new JsonConfigHelper();
        packageJson.set("viewId", "default");
        packageJson.set("packageType", "name-authority");
        json.set("id", key);
        json.set("step", "pending");
        json.set("modified", "false");

        List<JsonConfigHelper> authors = new ArrayList();
        for (String[] columns : parsedData.get(key)) {
            try {
                // IDS
                store("studentId", columns[1], json);
                store("employeeId", columns[2], json);
                // Preferred Name exists
                String pName = null;
                if (columns[5] != null && !columns[5].equals("")) {
                    pName = columns[3] + " " + columns[5] + " " + columns[7];
                }
                store("preferedName", pName, json);
                // Name title
                store("nameTitle", columns[3], json);
                // First name
                store("firstName", columns[4], json);
                // Second name
                if (columns[6] != null) {
                    store("secondName", columns[6], json);
                }
                // Surname
                store("surname", columns[7], json);
                // Full name
                String fName = null;
                if (columns[6] != null) {
                    // We have a middle name
                    fName = columns[3] + " " + columns[4] + " " + columns[6] + " " + columns[7];
                } else {
                    fName = columns[3] + " " + columns[4] + " " + columns[7];
                }
                store("fullName", fName, json);
                store("title", fName, json);

                json.set("pageTitle", fName);

                store("description", "Authority record for '" + fName + "'", json);
                packageJson.set("title", fName);
                packageJson.set("description", "Authority record for '" + fName + "'");
                // Email
                store("email", columns[8], json);

                // Author data used in publication
                JsonConfigHelper auth = new JsonConfigHelper();
                auth.set("author", columns[9]);
                auth.set("orgUnitId", columns[11]);
                auth.set("orgUnit", columns[12]);
                auth.set("expiry", columns[13]);
                authors.add(auth);

                // Catch any data mismatches during storage
            } catch (Exception ex) {
                log.error("line: {}", columns);
                log.error("Error parsing record '{}'", key, ex);
            }
        }

        // Add author data
        if (!authors.isEmpty()) {
            // TODO: Work-around for #656
            json.set("authors", "===REPLACE=ME===");
            String list = "[" + StringUtils.join(authors, ",") + "]";
            String jsonString = json.toString();
            jsonString = jsonString.replace("\"===REPLACE=ME===\"", list);
            try {
                json = new JsonConfigHelper(jsonString);
            } catch (IOException ex) {
                json = null;
                log.error("Error parsing json '{}': ", jsonString);
            }
        }

        // Add an empty package manifest
        // TODO: Work-around for #656
        packageJson.set("manifest", "===REPLACE=ME===");
        String jsonString = packageJson.toString();
        jsonString = jsonString.replace("\"===REPLACE=ME===\"", "{}");
        try {
            packageJson = new JsonConfigHelper(jsonString);
        } catch (IOException ex) {
            packageJson = null;
            log.error("Error parsing json '{}': ", jsonString);
        }

        i++;
        if (i % 500 == 0) {
            log.info("Object count: {}", i);
        }
        if (json != null && packageJson != null) {
            try {
                String oid = storeJson(json.toString(), packageJson.toString(), key);
                fileObjectIdList.add(oid);
            } catch (StorageException ex) {
                log.error("Error during storage: ", ex);
            }
        }
    }
    log.info("Object creation complete: {} objects", i);

    return fileObjectIdList;
}

From source file:cn.org.eshow.framwork.util.AbFileUtil.java

/**
 * ??byte[]./*from  w ww .  ja va 2  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(imageDownloadDir + 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;
}