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:com.duroty.application.mail.actions.AttachmentAction.java

/**
 * DOCUMENT ME!/*ww w . ja v a  2s.c o m*/
 *
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @throws ServletException DOCUMENT ME!
 * @throws IOException DOCUMENT ME!
 */
protected void doDownload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DataInputStream in = null;
    ByteArrayInputStream bais = null;
    ServletOutputStream op = null;

    try {
        String mid = request.getParameter("mid");
        String part = request.getParameter("part");

        Mail filesInstance = getMailInstance(request);

        MailPartObj obj = filesInstance.getAttachment(mid, part);

        int length = 0;
        op = response.getOutputStream();

        String mimetype = obj.getContentType();

        //
        //  Set the response and go!
        //
        //  Yes, I know that the RFC says 'attachment'.  Unfortunately, IE has a typo
        //  in it somewhere, and Netscape seems to accept this typing as well.
        //
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) obj.getSize());
        response.setHeader("Content-Disposition", "attachement; filename=\"" + obj.getName() + "\"");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");

        //
        //  Stream to the requester.
        //
        byte[] bbuf = new byte[1024];
        bais = new ByteArrayInputStream(obj.getAttachent());
        in = new DataInputStream(bais);

        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            op.write(bbuf, 0, length);
        }
    } catch (Exception ex) {
    } finally {
        try {
            op.flush();
        } catch (Exception ex) {
        }

        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(op);
    }
}

From source file:com.igormaznitsa.jhexed.renders.svg.SVGImage.java

public SVGImage(final InputStream in, final boolean packed) throws IOException {
    final DataInputStream din = in instanceof DataInputStream ? (DataInputStream) in : new DataInputStream(in);
    if (packed) {
        final byte[] packedImageData = new byte[din.readInt()];
        IOUtils.readFully(din, packedImageData);
        this.originalNonParsedImageData = Utils.unpackArray(packedImageData);
    } else {//  w  w  w.  j a v a 2  s.c om
        this.originalNonParsedImageData = readFullInputStream(din);
    }
    this.quality = din.readBoolean();

    this.svgGraphicsNode = loadDiagramFromStream(new ByteArrayInputStream(this.originalNonParsedImageData),
            this.documentSize);
}

From source file:com.duroty.application.files.actions.DownloadFileAction.java

/**
 * DOCUMENT ME!/* w  w w  .j  a v a  2s. c  o m*/
 *
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @throws ServletException DOCUMENT ME!
 * @throws IOException DOCUMENT ME!
 */
protected void doDownload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DataInputStream in = null;
    ByteArrayInputStream bais = null;
    ServletOutputStream op = null;

    try {
        String mid = request.getParameter("mid");
        String part = request.getParameter("part");

        Files filesInstance = getFilesInstance(request);

        MailPartObj obj = filesInstance.getAttachment(mid, part);

        int length = 0;
        op = response.getOutputStream();

        String mimetype = obj.getContentType();

        //
        //  Set the response and go!
        //
        //  Yes, I know that the RFC says 'attachment'.  Unfortunately, IE has a typo
        //  in it somewhere, and Netscape seems to accept this typing as well.
        //
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) obj.getSize());
        response.setHeader("Content-Disposition", "attachement; filename=\"" + obj.getName() + "\"");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");

        //
        //  Stream to the requester.
        //
        byte[] bbuf = new byte[1024];
        bais = new ByteArrayInputStream(obj.getAttachent());
        in = new DataInputStream(bais);

        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            op.write(bbuf, 0, length);
        }
    } catch (Exception ex) {
    } finally {
        try {
            op.flush();
        } catch (Exception ex) {
        }

        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(op);
    }
}

From source file:com.openhr.UploadFile.java

@Override
public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();//www  . j  a  va2 s .  com
        return map.findForward("masteradmin");
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);

                // Read the file object contents and parse it and store it in the repos
                FileInputStream fstream = new FileInputStream(storeFile);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
                Company comp = null;
                Branch branch = null;
                Calendar currDtCal = Calendar.getInstance();

                // Zero out the hour, minute, second, and millisecond
                currDtCal.set(Calendar.HOUR_OF_DAY, 0);
                currDtCal.set(Calendar.MINUTE, 0);
                currDtCal.set(Calendar.SECOND, 0);
                currDtCal.set(Calendar.MILLISECOND, 0);

                Date now = currDtCal.getTime();

                //Read File Line By Line
                while ((strLine = br.readLine()) != null) {
                    System.out.print("Processing line - " + strLine);

                    String[] lineColumns = strLine.split(COMMA);

                    if (lineColumns.length < 16) {
                        br.close();
                        in.close();
                        fstream.close();
                        throw new Exception("The required columns are missing in the line - " + strLine);
                    }

                    // Format is - 
                    // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,BankName,BankBranch,RoutingNo,AccountNo,NetPay,Currency,
                    // residenttype,TaxAmount,EmployerSS,EmployeeSS
                    if (comp == null || comp.getId() != Integer.parseInt(lineColumns[0])) {
                        List<Company> comps = CompanyFactory.findById(Integer.parseInt(lineColumns[0]));

                        if (comps != null && comps.size() > 0) {
                            comp = comps.get(0);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("Unable to get the details of the company");
                        }

                        // Check for licenses
                        List<Licenses> compLicenses = LicenseFactory.findByCompanyId(comp.getId());
                        for (Licenses lis : compLicenses) {
                            if (lis.getActive() == 1) {
                                Date endDate = lis.getTodate();
                                if (!isLicenseActive(now, endDate)) {
                                    br.close();
                                    in.close();
                                    fstream.close();

                                    // License has expired and throw an error
                                    throw new Exception("License has expired");

                                    //TODO remove the below code and enable above
                                    /*List<Branch> branches = BranchFactory.findByCompanyId(comp.getId());
                                    String branchName = lineColumns[1];
                                    if(branches != null && !branches.isEmpty()) {
                                      for(Branch bb: branches) {
                                         if(branchName.equalsIgnoreCase(bb.getName())) {
                                            branch = bb;
                                            break;
                                         }
                                      }
                                              
                                      if(branch == null) {
                                         Branch bb = new Branch();
                                    bb.setName(branchName);
                                    bb.setAddress("NA");
                                    bb.setCompanyId(comp);
                                            
                                    BranchFactory.insert(bb);
                                            
                                    List<Branch> lbranches = BranchFactory.findByName(branchName);
                                    branch = lbranches.get(0);
                                      }
                                    }*/
                                    //TODO
                                } else {
                                    // License enddate is valid, so lets check the key.
                                    String compName = comp.getName();
                                    String licenseKeyStr = LicenseValidator.formStringToEncrypt(compName,
                                            endDate);
                                    if (LicenseValidator.encryptAndCompare(licenseKeyStr,
                                            lis.getLicensekey())) {
                                        // License key is valid, so proceed.
                                        List<Branch> branches = BranchFactory.findByCompanyId(comp.getId());
                                        String branchName = lineColumns[1];
                                        if (branches != null && !branches.isEmpty()) {
                                            for (Branch bb : branches) {
                                                if (branchName.equalsIgnoreCase(bb.getName())) {
                                                    branch = bb;
                                                    break;
                                                }
                                            }

                                            if (branch == null) {
                                                Branch bb = new Branch();
                                                bb.setName(branchName);
                                                bb.setAddress("NA");
                                                bb.setCompanyId(comp);

                                                BranchFactory.insert(bb);

                                                List<Branch> lbranches = BranchFactory.findByName(branchName);
                                                branch = lbranches.get(0);
                                            }
                                        }
                                        break;
                                    } else {
                                        br.close();
                                        in.close();
                                        fstream.close();

                                        throw new Exception("License is tampered. Contact Support.");
                                    }
                                }
                            }
                        }
                    }

                    // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,DeptName,BankName,BankBranch,RoutingNo,AccountNo,NetPay,currency,TaxAmt,emprSS,empess,basesalary                       
                    CompanyPayroll compPayroll = new CompanyPayroll();
                    compPayroll.setBranchId(branch);
                    compPayroll.setEmployeeId(lineColumns[2]);
                    compPayroll.setEmpFullName(lineColumns[3]);
                    compPayroll.setEmpNationalID(lineColumns[4]);
                    compPayroll.setDeptName(lineColumns[5]);
                    compPayroll.setBankName(lineColumns[6]);
                    compPayroll.setBankBranch(lineColumns[7]);
                    compPayroll.setRoutingNo(lineColumns[8]);
                    compPayroll.setAccountNo(lineColumns[9]);
                    compPayroll.setNetPay(Double.parseDouble(lineColumns[10]));
                    compPayroll.setCurrencySym(lineColumns[11]);
                    compPayroll.setResidentType(lineColumns[12]);
                    compPayroll.setTaxAmount(Double.parseDouble(lineColumns[13]));
                    compPayroll.setEmprSocialSec(Double.parseDouble(lineColumns[14]));
                    compPayroll.setEmpeSocialSec(Double.parseDouble(lineColumns[15]));
                    compPayroll.setBaseSalary(Double.parseDouble(lineColumns[16]));
                    compPayroll.setProcessedDate(now);
                    CompanyPayrollFactory.insert(compPayroll);
                }

                //Close the input stream
                br.close();
                in.close();
                fstream.close();
            }
        }
        System.out.println("Upload has been done successfully!");
    } catch (Exception ex) {
        System.out.println("There was an error: " + ex.getMessage());
        ex.printStackTrace();
    }

    return map.findForward("MasterHome");
}

From source file:de.berber.kindle.annotator.lib.KindleAnnotationReader.java

/**
 * Reads the pdr file and extracts all annotation information.
 * // ww w . j a va2s .  co  m
 * @return A list of annotations.
 */
public @Nonnull List<Annotation> read() {
    final List<Annotation> result = new LinkedList<Annotation>();

    if (!pdrFile.exists()) {
        return result;
    }

    if (!pdrFile.canRead()) {
        LOG.error("Cannnot read PDR-file " + pdrFile);
        return result;
    }

    try {
        fileStream = new FileInputStream(pdrFile);
        pdrStream = new DataInputStream(fileStream);

        final int magic = readUnsigned32();
        if (magic != MAGIC_VALUE) {
            LOG.error("Magic file header is wrong " + Integer.toHexString(magic));
            return result;
        }

        writeDebug("[Magic String]\n");

        skipBytes(1);
        @SuppressWarnings("unused")
        int lastOpenedPage = readUnsigned32();
        writeDebug("\n[Last opened page]\n");

        int numberOfBookmarks = readUnsigned32();
        LOG.info("Number of bookmarks " + numberOfBookmarks);

        for (int i = 0; i < numberOfBookmarks; ++i) {
            skipBytes(1); // skipping unknown data
            int page = pdrStream.readInt(); // reading page number
            writeDebug(" [page]");
            readPascalString(); // page name
            writeDebug(" [page name]\n");

            result.add(new Bookmark(cc, page));
        }

        skipBytes(20); // skipping unknown data

        final int numberOfMarkings = pdrStream.readInt();
        LOG.info("Number of markings " + numberOfMarkings);
        writeDebug("\n[Number of markings " + numberOfMarkings + "]\n");

        for (int i = 0; i < numberOfMarkings; ++i) {
            // read start
            skipBytes(1); // skipping unknown data
            int page1 = pdrStream.readInt(); // reading page number
            writeDebug(" [page]");
            readPascalString(); // page name
            writeDebug(" [page name]");
            readPascalString(); // skipping pdfloc entry
            writeDebug(" [pdfloc] ");
            writeDebug("[" + pdrStream.readFloat() + "]");
            // skipBytes(4); // skipping unknown data
            double x1 = pdrStream.readDouble(), // start x
                    y1 = pdrStream.readDouble(); // start y
            writeDebug(" [x1]");
            writeDebug(" [y1]");

            // read end
            int page2 = pdrStream.readInt(); // reading page number
            writeDebug(" [page]");
            readPascalString(); // page name
            writeDebug(" [page name]");
            readPascalString(); // skipping pdfloc entry
            writeDebug(" [pdfloc] ");
            writeDebug("[" + pdrStream.readFloat() + "]");
            // qskipBytes(4); // skipping unknown data
            double x2 = pdrStream.readDouble(), // end x
                    y2 = pdrStream.readDouble(); // end y
            writeDebug(" [x2]");
            writeDebug(" [y2] ");
            skipBytes(2); // skipping unknown data
            writeDebug("\n");

            result.add(new Marking(cc, page1, x1, y1, page2, x2, y2));
        }

        int numberOfComments = pdrStream.readInt();
        LOG.info("Number of comments " + numberOfComments);
        writeDebug("\n[Number of comments " + numberOfComments + "]\n");

        for (int i = 0; i < numberOfComments; ++i) {
            skipBytes(1); // skipping unknown data
            int page = pdrStream.readInt(); // reading page number
            writeDebug(" [page]");
            readPascalString(); // page name
            writeDebug(" [page name]");
            double x = pdrStream.readDouble(), // reading x
                    y = pdrStream.readDouble(); // reading y
            writeDebug(" [x]");
            writeDebug(" [y]");

            readPascalString(); // skipping pdfloc entry
            writeDebug(" [pdfloc]");
            String content = readPascalString(); // reading comment
            writeDebug(" [content]\n");

            result.add(new Comment(cc, page, x, y, content));
        }

        int finalEntry = readUnsigned32();

        writeDebug("\n[Final entry " + finalEntry + "]");

        LOG.info("Number of available bytes " + pdrStream.available());
    } catch (FileNotFoundException e) {
        LOG.error("Cannot find pdr-file " + pdrFile);
    } catch (IOException e) {
        LOG.error("IO error occured while reading " + pdrFile);
    } finally {
        closePdrStream();
        closeDebugStream();
    }

    mergeAnnotations(result);

    return result;
}

From source file:com.wso2telco.util.FileUtil.java

/**
 * Read fully into var.// w  w w  . ja v a 2  s . c  om
 *
 * @param fullpath the fullpath
 * @return the string
 */
public static String ReadFullyIntoVar(String fullpath) {

    String result = "";

    try {
        FileInputStream file = new FileInputStream(fullpath);
        DataInputStream in = new DataInputStream(file);
        byte[] b = new byte[in.available()];
        in.readFully(b);
        in.close();
        result = new String(b, 0, b.length, "Cp850");
    } catch (Exception e) {
        log.error("Read fully into var Error" + e);
    }
    return result;
}

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

private List<MediaModel> createAndAddMediaToFolder(final int numOfMedia, final MediaFolderModel folder) {
    final List<MediaModel> result = new ArrayList<MediaModel>();

    for (int i = 0; i < numOfMedia; i++) {
        final String code = RandomStringUtils.randomAlphabetic(5);
        final MediaModel media = createEmptyMediaModelInFolder(code, folder);
        mediaService.setStreamForMedia(media, new DataInputStream(new ByteArrayInputStream(code.getBytes())));
        modelService.save(media);// w  ww . j a  v  a 2 s . c o  m
        assertThat(media.getDataPK())
                .overridingErrorMessage("media PK: " + media.getPk() + ", index: " + i + " has no dataPK")
                .isNotNull();
        MediaDataAssert.assertThat(media).hasDirDepthEqualTo(Integer.valueOf(0));
        result.add(media);
    }
    return result;
}

From source file:com.android.internal.location.GpsXtraDownloader.java

protected static byte[] doDownload(String url, boolean isProxySet, String proxyHost, int proxyPort) {
    AndroidHttpClient client = null;//from  w  w w  .ja va 2  s.c o m
    try {
        client = AndroidHttpClient.newInstance("Android");
        HttpUriRequest req = new HttpGet(url);

        if (isProxySet) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            ConnRouteParams.setDefaultProxy(req.getParams(), proxy);
        }

        req.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");

        req.addHeader("x-wap-profile",
                "http://www.openmobilealliance.org/tech/profiles/UAPROF/ccppschema-20021212#");

        HttpResponse response = client.execute(req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            Log.d(TAG, "HTTP error: " + status.getReasonPhrase());
            return null;
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Unexpected IOException.", e);
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (Exception e) {
        Log.d(TAG, "error " + e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:genepi.db.DatabaseUpdater.java

public static String readFileAsStringFile(String filename, String minVersion, String maxVersion)
        throws java.io.IOException, URISyntaxException {

    InputStream is = new FileInputStream(filename);

    DataInputStream in = new DataInputStream(is);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;/* www. j a  v  a2  s .  c  o m*/
    StringBuilder builder = new StringBuilder();
    boolean reading = false;
    while ((strLine = br.readLine()) != null) {

        if (strLine.startsWith("--")) {

            String version = strLine.replace("--", "").trim();
            reading = (compareVersion(version, minVersion) > 0 && compareVersion(version, maxVersion) <= 0);
            if (reading) {
                log.info("Loading update for version " + version);
            }

        }

        if (reading) {
            builder.append("\n");
            builder.append(strLine);
        }
    }

    in.close();

    return builder.toString();
}

From source file:com.pronoiahealth.olhie.server.rest.TVServiceImpl.java

/**
 * @see com.pronoiahealth.olhie.server.rest.TVService#getVideo(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.String,
 *      javax.servlet.ServletContext)//w  w w.  j  a va  2s  . c  om
 */
@Override
@GET
@Path("/tv/{uniqueNumb}/{programRef}")
// @Produces({"application/pdf", "application/octet-stream", "text/html"})
@Produces({ "application/octet-stream" })
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR, SecurityRoleEnum.REGISTERED,
        SecurityRoleEnum.ANONYMOUS })
public InputStream getVideo(@Context HttpServletRequest request, @Context HttpServletResponse response,
        @PathParam("programRef") String programRef, @Context ServletContext context)
        throws ServletException, IOException, FileDownloadException {
    DataInputStream in = null;
    try {
        // Get the file contents
        File programFile = findFile(programRef);
        if (programFile == null) {
            throw new FileDownloadException(String.format("Could not find file for id %s", programRef));
        }

        String fileName = programRef.substring(programRef.lastIndexOf("|"));
        String mimetype = context.getMimeType(fileName);
        // Base64 unencode
        byte[] fileBytes = FileUtils.readFileToByteArray(programFile);

        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");

        // No image caching
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // response.setContentLength(fileBytes.length);
        // response.setHeader("Content-Disposition", "inline; filename="
        // + fileName);

        in = new DataInputStream(new ByteArrayInputStream(fileBytes));
        return in;
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);

        if (e instanceof FileDownloadException) {
            throw (FileDownloadException) e;
        } else {
            throw new FileDownloadException(e);
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
}