Example usage for java.io DataInputStream close

List of usage examples for java.io DataInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileDownloadServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String operationId = req.getParameter("operationid");

    if (user != null && operationId != null && !operationId.isEmpty()) {

        try {//from w  ww. ja v  a2s.  c  om
            GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient();
            Operation operation = client.getOperationById(operationId);

            File file = new File(operation.getDest());
            if (file.isDirectory()) {
                file = new File(operation.getDest() + "/" + FilenameUtils.getName(operation.getSource()));
            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

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

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();
        } catch (GRIDAClientException ex) {
            logger.error(ex);
        }
    }
}

From source file:nl.systemsgenetics.cellTypeSpecificAlleleSpecificExpression.ReadGenoAndAsFromIndividual.java

/**
 *
 * @param individual_names/*from ww  w .j  a  v  a2  s  .  co m*/
 * @param coupling_location
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 * 
 */

public static HashMap convert_individual_names(String[] individual_names, String coupling_location)
        throws FileNotFoundException, IOException {

    String coupling_loc = coupling_location;

    //This will be filled while reading the file
    ArrayList<String> sample_names_in_file = new ArrayList<String>();
    ArrayList<String> individual_names_in_file = new ArrayList<String>();

    //This will be the one that is later returned
    HashMap ordered_sample_names = new HashMap();

    File coupling_file = new File(coupling_loc);

    FileInputStream fis;
    BufferedInputStream bis;
    DataInputStream dis;

    fis = new FileInputStream(coupling_file);

    // Here BufferedInputStream is added for fast reading.
    bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);

    // dis.available() returns 0 if the file does not have more lines.
    int i = 0;
    while (dis.available() != 0) {

        String[] curr_line = dis.readLine().split("\t");
        individual_names_in_file.add(i, curr_line[0]);
        sample_names_in_file.add(i, curr_line[1]);

        //print the individual al line for checking.
        //System.out.println("line: " + " " + curr_line[0] +" " + curr_line[1] );

    }

    // dispose all the resources after using them.
    fis.close();
    bis.close();
    dis.close();

    i = 0;
    for (String i_name : individual_names) {
        int index = individual_names_in_file.indexOf(i_name);

        if (index >= 0) {
            //We find a name in the genotype folder in the individual names stuff.
            ordered_sample_names.put(sample_names_in_file.get(index), i);
        }
        i++;

    }
    return (ordered_sample_names);

}

From source file:com.cloudera.recordbreaker.analyzer.UnknownTextSchemaDescriptor.java

public UnknownTextSchemaDescriptor(DataDescriptor dd, String schemaRepr, byte[] miscPayload)
        throws IOException {
    super(dd, schemaRepr);
    this.randId = new Random().nextInt();

    // Deserialize the payload string into the parser
    DataInputStream in = new DataInputStream(new ByteArrayInputStream(miscPayload));
    try {//from   w w  w .j  av a  2s . c  o  m
        this.typeTree = InferredType.readType(in);
    } finally {
        in.close();
    }
}

From source file:com.eufar.asmm.server.DownloadFunction.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("DownloadFunction - the function started");
    ServletContext context = getServletConfig().getServletContext();
    request.setCharacterEncoding("UTF-8");
    String dir = context.getRealPath("/tmp");
    ;/*from  w ww  .  j  av  a 2 s .  co  m*/
    String filename = "";
    File fileDir = new File(dir);
    try {
        System.out.println("DownloadFunction - create the file on server");
        filename = request.getParameterValues("filename")[0];
        String xmltree = request.getParameterValues("xmltree")[0];

        // format xml code to pretty xml code
        Document doc = DocumentHelper.parseText(xmltree);
        StringWriter sw = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent(true);
        format.setIndentSize(4);
        XMLWriter xw = new XMLWriter(sw, format);
        xw.write(doc);

        Writer out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(dir + "/" + filename), "UTF-8"));
        out.append(sw.toString());
        out.flush();
        out.close();
    } catch (Exception ex) {
        System.out.println("ERROR during rendering: " + ex);
    }
    try {
        System.out.println("DownloadFunction - send file to user");
        ServletOutputStream out = response.getOutputStream();
        File file = new File(dir + "/" + filename);
        String mimetype = context.getMimeType(filename);
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setHeader("Pragma", "private");
        response.setHeader("Cache-Control", "private, must-revalidate");
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int length;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            out.write(bbuf, 0, length);
        }
        in.close();
        out.flush();
        out.close();
        FileUtils.cleanDirectory(fileDir);
    } catch (Exception ex) {
        System.out.println("ERROR during downloading: " + ex);
    }
    System.out.println("DownloadFunction - file ready to be donwloaded");
}

From source file:fr.insalyon.creatis.vip.core.server.rpc.GetFileServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from w w w .  j a v  a  2  s  .c o m
        User user = CoreDAOFactory.getDAOFactory().getUserDAO()
                .getUserBySession(req.getParameter(CoreConstants.COOKIES_SESSION));

        String filepath = req.getParameter("filepath");

        if (filepath != null && !filepath.isEmpty()) {

            File file = new File(Server.getInstance().getWorkflowsPath() + filepath);

            boolean isDir = false;
            if (file.isDirectory()) {
                String zipName = file.getAbsolutePath() + ".zip";
                FolderZipper.zipFolder(file.getAbsolutePath(), zipName);
                filepath = zipName;
                file = new File(zipName);
                isDir = true;
            }

            logger.info("(" + user.getEmail() + ") Downloading file '" + filepath + "'.");
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

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

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();

            if (isDir) {
                FileUtils.deleteQuietly(file);
            }
        }

    } catch (DAOException ex) {
        throw new ServletException(ex);
    }
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/** Read a PKCS 8 format private key. */
private static PrivateKey readPrivateKey(InputStream file) throws IOException, GeneralSecurityException {
    final DataInputStream input = new DataInputStream(file);
    try {//  w  ww .j a  v  a2 s.c o m
        byte[] bytes = new byte[10000];
        int nBytesTotal = 0, nBytes;
        while ((nBytes = input.read(bytes, nBytesTotal, 10000 - nBytesTotal)) != -1) {
            nBytesTotal += nBytes;
        }

        final byte[] bytes2 = new byte[nBytesTotal];
        System.arraycopy(bytes, 0, bytes2, 0, nBytesTotal);
        bytes = bytes2;

        KeySpec spec = decryptPrivateKey(bytes);
        if (spec == null) {
            spec = new PKCS8EncodedKeySpec(bytes);
        }

        try {
            return KeyFactory.getInstance("RSA").generatePrivate(spec);
        } catch (final InvalidKeySpecException ex) {
            return KeyFactory.getInstance("DSA").generatePrivate(spec);
        }
    } finally {
        input.close();
    }
}

From source file:com.cedarsoft.crypt.CertTest.java

@Test
public void testCert() throws Exception {
    DataInputStream inStream = new DataInputStream(getClass().getResource("/test.crt").openStream());

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
    inStream.close();
    assertNotNull(cert);//from  w  w w  .  j  a  v  a 2  s .  c  om

    cert.checkValidity();

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, cert);

    byte[] clear = cipher.doFinal(Base64.decodeBase64(SCRAMBLED.getBytes()));
    assertEquals(PLAINTEXT, new String(clear));
}

From source file:com.zimbra.cs.octosync.PatchInputStream.java

private InputStream nextInputStream() throws IOException, ServiceException {
    if (!patchReader.hasMoreRecordInfos()) {
        return null;
    }//w w  w  .  j  a va 2 s.  c  o  m

    PatchReader.RecordInfo ri = patchReader.getNextRecordInfo();

    InputStream nextStream = null;

    if (ri.type == PatchReader.RecordType.DATA) {

        log.debug("Patch data, length: " + ri.length);
        nextStream = patchReader.popData();

    } else if (ri.type == PatchReader.RecordType.REF) {

        PatchRef patchRef = patchReader.popRef();
        log.debug("Patch reference " + patchRef);

        if (patchRef.length > MAX_REF_LENGTH) {
            throw new InvalidPatchReferenceException(
                    "referenced data too large: " + patchRef.length + " > " + MAX_REF_LENGTH);
        }

        if (manifest != null) {
            int[] actualRef = blobAccess.getActualReference(patchRef.fileId, patchRef.fileVersion);
            manifest.addReference(actualRef[0], actualRef[1], patchRef.length);
        }

        try {
            InputStream blobIs = blobAccess.getBlobInputStream(patchRef.fileId, patchRef.fileVersion);

            blobIs.skip(patchRef.offset);

            byte[] chunkBuf = new byte[patchRef.length];

            DataInputStream dis = new DataInputStream(blobIs);
            dis.readFully(chunkBuf);
            dis.close();

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(chunkBuf);
            byte[] calcHash = md.digest();

            if (!Arrays.equals(patchRef.hashKey, calcHash)) {
                throw new InvalidPatchReferenceException("refrenced data hash mismatch, actual hash: "
                        + new String(Hex.encodeHex(calcHash)) + "; " + patchRef);
            }

            nextStream = new ByteArrayInputStream(chunkBuf);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            assert false : "SHA-256 must be supported";
        }
    } else {
        assert false : "Invalid record type: " + ri.type;
    }

    assert nextStream != null : "Stream returned here must be non-null";
    return nextStream;
}

From source file:fr.insalyon.creatis.vip.query.server.rpc.FileDownload.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String queryId = req.getParameter("queryid");
    String path = req.getParameter("path");
    String queryName = req.getParameter("name");
    String tab[] = path.split("/");

    if (user != null && queryId != null && !queryId.isEmpty()) {

        try {/*  ww w  .ja v a 2  s.  c om*/

            String k = new String();

            int l = tab.length;
            for (int i = 0; i < l - 1; i++) {
                k += "//" + tab[i];
            }
            File file = new File(k);
            logger.info("that" + k);
            if (file.isDirectory()) {

                file = new File(k + "/" + tab[l - 1]);

            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            //name of the file in servlet download
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + queryName + "_"
                    + getCurrentTimeStamp().toString().replaceAll(" ", "_") + ".txt" + "\"");

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

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();
        } catch (Exception ex) {
            logger.error(ex);
        }

    }
}

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

/**
 * Print the newprops./* w w w  .j  a va2  s  .  com*/
 * Properties that are 'used' already are commented out.
 * 
 * NOTE: The idea is that we want to write out the properties in exactly the same order, for future comparison purposes.
 * 
 * @param newProps
 * @param remainingNewProps New properties that are left, i.e. remaining ones.
 */

private static void printNewProps(File updatedValuesOldPropertiesFile, Properties newProps,
        Properties originalProps) {
    /**
     * Read new props line by line.
     * For each line, extract the prop key
     *   if it is not in the remaining, then it is used. So we write the line, but commented out
     *   otherwise, write the line as is.
     */

    System.out.println(
            "#########################################################################################");
    System.out.println(
            "####################### Personalizations  from 2.9.1-source-modif #######################");

    try {
        // Open the file that contains Sakai 2.8.1 modif personalizations
        FileInputStream fstream = new FileInputStream(updatedValuesOldPropertiesFile);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {

            KeyValue keyValue = extractKeyValue(strLine);

            //if the line does not have the pattern key = value, we skip it 
            if (keyValue == null) {
                continue;
            }

            String key = keyValue.key;

            boolean isNotUsedInNewVersion = (newProps.get(key) == null);
            boolean isNotUsedInOldVersion = (originalProps.get(key) == null);

            // Write out line only if property is a personalized property:it is not used in new version and was not used in old version
            if (isNotUsedInNewVersion && isNotUsedInOldVersion) {
                System.out.println(strLine);
            }
        }
        // Close the input stream
        in.close();

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