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:org.commoncrawl.service.listcrawler.CacheManager.java

/** initiailizeActiveLog - init local cache log 
 * /* w  ww. ja  v  a  2 s . com*/
 * 
 * **/
private void initializeActiveLog() throws IOException {

    File activeLogPath = getActiveLogFilePath();

    if (!activeLogPath.exists()) {
        DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(activeLogPath));
        try {
            _header = initializeEmptyLogFile(outputStream);
        } finally {
            outputStream.close();
        }
    } else {
        _header = new LocalLogFileHeader();

        DataInputStream inputStream = new DataInputStream(new FileInputStream(activeLogPath));

        try {
            _header.readHeader(inputStream);
        } finally {
            inputStream.close();
        }

        if (_header._itemCount != 0) {
            loadCache(activeLogPath, _header);
        }
    }
}

From source file:org.akaza.openclinica.control.core.SecureController.java

License:asdf

public void dowloadFile(File f, String contentType) throws Exception {

    response.setHeader("Content-disposition", "attachment; filename=\"" + f.getName() + "\";");
    response.setContentType("text/xml");
    response.setHeader("Pragma", "public");

    ServletOutputStream op = response.getOutputStream();

    DataInputStream in = null;
    try {//from   w w w.j a va 2s  .  c  o  m
        response.setContentType("text/xml");
        response.setHeader("Pragma", "public");
        response.setContentLength((int) f.length());

        byte[] bbuf = new byte[(int) f.length()];
        in = new DataInputStream(new FileInputStream(f));
        int length;
        while (in != null && (length = in.read(bbuf)) != -1) {
            op.write(bbuf, 0, length);
        }

        in.close();
        op.flush();
        op.close();
    } catch (Exception ee) {
        ee.printStackTrace();
    } finally {
        if (in != null) {
            in.close();
        }
        if (op != null) {
            op.close();
        }
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteData(String requestUrl, String requestMethod, String requestBody,
        CallbackContext callbackContext) {
    try {/*from ww  w  .  j  av a  2  s. co m*/
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            callbackContext.success(responseBody);
        } else {
            callbackContext.error("Fail to get the response, response code: " + responseCode
                    + ", response message: " + responseMessage);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.alphabetbloc.accessmrs.services.SyncManager.java

public String readObsFile(File tempFile, SyncResult syncResult) {

    if (tempFile == null)
        return "error";

    try {// w  ww.j  a v a 2 s .c  o  m

        DataInputStream dis = new DataInputStream(new FileInputStream(tempFile));

        if (dis != null) {
            DbProvider dbHelper = DbProvider.openDb();
            // open db and clean entries
            dbHelper.delete(DataModel.PATIENTS_TABLE, DataModel.KEY_CLIENT_CREATED + " IS NULL", null);
            dbHelper.delete(DataModel.OBSERVATIONS_TABLE, null, null);

            insertPatients(dis);
            addSyncStep(mContext.getString(R.string.sync_updating_data), false); // 70%
            insertObservations(dis);

            try {
                addSyncStep(mContext.getString(R.string.sync_updating_data), false); // 90%
                // (doubled
                // due
                // to
                // slow
                // speed)
                insertPatientForms(dis);
            } catch (EOFException e) {
                // do nothing for EOFExceptions in this case
                if (App.DEBUG)
                    Log.v(TAG, "No SmartForms available on server");
            }

            dis.close();
        }

        updateAccessMrsObs();
        addSyncStep(mContext.getString(R.string.sync_updating_data), false); // 100%

    } catch (Exception e) {
        e.printStackTrace();
        ++syncResult.stats.numIoExceptions;
        return e.getLocalizedMessage();
    }

    return null;
}

From source file:IndexService.IndexServer.java

public boolean setindexstatus(String indexloc, int status) {
    if (!testmode) {
        Path indexpath = new Path(indexloc);
        try {/*from  w  ww.j av a  2s . c  om*/
            String dbname = indexpath.getParent().getParent().getName();
            if (dbname.endsWith(".db")) {
                dbname = dbname.substring(0, dbname.lastIndexOf(".db"));
            }
            return db.setIndexStatus(dbname, indexpath.getParent().getName(), indexpath.getName(), status);
        } catch (HiveException e1) {
            e1.printStackTrace();
            return false;
        }
    } else {
        try {
            ArrayList<IndexItemStatus> statuss = new ArrayList<IndexItemStatus>();
            File file = new File("indexconf");
            boolean exist = false;
            if (file.exists()) {
                DataInputStream dis = new DataInputStream(new FileInputStream(file));
                int num = dis.readInt();
                for (int i = 0; i < num; i++) {
                    IndexItemStatus itemstatus = new IndexItemStatus();
                    itemstatus.read(dis);
                    if (itemstatus.indexlocation.equals(indexloc)) {
                        itemstatus.status = status;
                        exist = true;
                    }
                    statuss.add(itemstatus);
                }
                dis.close();

                DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
                dos.writeInt(statuss.size());
                for (IndexItemStatus indexItemStatus : statuss) {
                    indexItemStatus.write(dos);
                }
                dos.close();
            }
            if (exist)
                return true;
            return false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

From source file:br.org.indt.ndg.servlets.PostResults.java

private String Decompress(HttpServletRequest request) {
    DataInputStream dis = null;
    DataInputStream objIn = null;
    ByteArrayOutputStream baos = null;
    String result = null;/*from   w w w .j av  a  2s. com*/

    try {
        dis = new DataInputStream(request.getInputStream());
        baos = new ByteArrayOutputStream();

        int length, uncomplength = 0;
        int data = 0;

        uncomplength = dis.readInt();
        length = dis.readInt();

        for (int i = 0; i < length; i++) {
            data = dis.read();
            baos.write((byte) data);
        }

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ZInputStream zIn = new ZInputStream(bais);
        objIn = new DataInputStream(zIn);

        byte[] bytes = new byte[uncomplength];
        objIn.readFully(bytes);

        result = new String(bytes, ENCODING);

        log.info("Compressed length: " + length + " bytes");
        log.info("Decompressed length: " + result.getBytes().length + " bytes");

        zIn.close();
        dis.close();
        baos.close();
        objIn.close();
    } catch (EOFException e) {
        servletError = true;
        log.error(e);
    } catch (IOException e) {
        servletError = true;
        log.error(e);
    } catch (Exception e) {
        servletError = true;
        log.error(e);
    }

    return result;
}

From source file:com.lenovo.h2000.services.LicenseServiceImpl.java

@Override
public String upload(String filePath, Map<String, String> headers) throws Exception {
    _logger.info("calling LicenseServiceImpl.upload function");
    Map<String, String> params = new HashMap<String, String>();

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(
            HttpConfig.parseBaseUrl(headers) + "license/import" + "?" + TypeUtil.mapToString(params));// new HttpPost("http://localhost:3002/license/import");

    String responseBody = "";
    DataInputStream in = null;
    try {/* w  w  w . ja v  a 2  s.  c o  m*/
        _logger.info("filePath" + filePath);
        File file = new File(filePath);
        in = new DataInputStream(new FileInputStream(filePath));
        byte[] bufferOut = new byte[(int) file.length()];

        int bytes = 0;
        int i = 0;
        int len = (int) (1024 > file.length() ? file.length() : 1024);
        while ((bytes = in.read(bufferOut, i, len)) > 0) {
            if (bytes < 1024)
                break;
            else {
                len = (int) (file.length() - bytes);
                i += bytes;
            }
        }

        ByteArrayEntity requestEntity = new ByteArrayEntity(bufferOut);
        requestEntity.setContentEncoding("UTF-8");
        requestEntity.setContentType("application/octet-stream");
        httpPost.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(httpPost);
        response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
        HttpEntity responseEntity = response.getEntity();
        responseBody = EntityUtils.toString(responseEntity);

        if (file.isFile() && file.exists()) {
            file.delete();
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost ClientProtocolException with " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost IOException with " + e.getMessage());
    } finally {
        httpClient.close();
        if (in != null) {
            in.close();
        }
    }
    return responseBody;
}

From source file:org.commoncrawl.service.listcrawler.CrawlHistoryManager.java

/**
 * initiailizeActiveLog - init local cache log
 * /*from  w  ww  .  j a v a  2 s. c  o m*/
 * 
 * **/
private void initializeActiveLog() throws IOException {

    File activeLogPath = getActiveLogFilePath();

    if (!activeLogPath.exists()) {
        DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(activeLogPath));
        try {
            _header = initializeEmptyLogFile(outputStream);
        } finally {
            outputStream.close();
        }
    } else {
        _header = new LocalLogFileHeader();

        DataInputStream inputStream = new DataInputStream(new FileInputStream(activeLogPath));

        try {
            _header.readHeader(inputStream);
        } finally {
            inputStream.close();
        }

        if (_header._itemCount != 0) {
            _localLogItems = loadLocalLogItemMap();
        }
    }
}

From source file:com.quattroresearch.antibody.SequenceFileReader.java

/**
 * Parses .gp Files <p> Parses all chains found in a gp-formatted file (usually one). Sequence can be upper- or
 * lower-case letters, chainname is the filename.
 * /*from  w  w  w .j  a va  2  s .c  o m*/
 * @param file .gp-File to parse
 * @return (List of chainnames, List of chainsequences)
 */
private List<String>[] readGPFile(File file) {
    List<String> foundNames = new ArrayList<String>();
    List<String> foundChains = new ArrayList<String>();
    try {
        FileInputStream fis = new FileInputStream(file);
        DataInputStream in = new DataInputStream(fis);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        StringBuilder buildChain = new StringBuilder();
        Pattern startofSequence = Pattern.compile("^ORIGIN.*");
        Pattern dataline = Pattern.compile("^(\\s*[A-Z]{2,}\\s{3,})|(//).*");
        Pattern chain = Pattern.compile("^\\s*\\d+\\s+([A-Za-z ]+)$");
        boolean readSequence = false;
        Matcher matcher;

        // extract all Chains from file
        while ((strLine = br.readLine()) != null) {
            matcher = startofSequence.matcher(strLine);
            if (matcher.matches()) {
                readSequence = true;
            }

            if (readSequence) {
                matcher = chain.matcher(strLine.replaceAll("\\*", ""));
                if (matcher.matches()) {
                    buildChain.append(matcher.group(1).replaceAll(" ", ""));
                }

                matcher = dataline.matcher(strLine);
                if (matcher.matches()) {
                    foundChains.add(buildChain.toString().toUpperCase());
                    buildChain = new StringBuilder();
                    readSequence = false;
                }
            }
        }

        String filename = FilenameUtils.removeExtension(file.getName());
        if (foundChains.size() == 1) {
            foundNames.add(filename);
        } else {
            for (int i = 0; i < foundChains.size(); i++) {
                foundNames.add(filename + String.valueOf(i));
            }
        }

        in.close();
    } catch (IOException x) {
        System.err.format("IOException: %s%n", x);
    }

    List<String>[] result = new List[2];
    result[0] = foundNames;
    result[1] = foundChains;

    return result;
}

From source file:com.jivesoftware.os.amza.service.replication.http.endpoints.AmzaReplicationRestEndpoints.java

@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/ackBatch")
public Response ackBatch(InputStream is) {
    try {//ww  w  . j  av a2  s .  c  o m

        DataInputStream in = new DataInputStream(is);
        try {

            while (in.readByte() == 1) {

                int length = in.readShort();
                byte[] bytes = new byte[length];
                in.readFully(bytes);
                VersionedPartitionName versionedPartitionName = amzaInterner.internVersionedPartitionName(bytes,
                        0, length);

                length = in.readShort();
                bytes = new byte[length];
                in.readFully(bytes);
                RingMember ringMember = amzaInterner.internRingMember(bytes, 0, length);

                long takeSessionId = in.readLong();
                long takeSharedKey = in.readLong();
                long txId = in.readLong();
                long leadershipToken = in.readLong();

                amzaInstance.rowsTaken(ringMember, takeSessionId, takeSharedKey, versionedPartitionName, txId,
                        leadershipToken);

            }

            if (in.readByte() == 1) {
                int length = in.readShort();
                byte[] bytes = new byte[length];
                in.readFully(bytes);
                RingMember ringMember = amzaInterner.internRingMember(bytes, 0, length);

                long takeSessionId = in.readLong();
                long takeSharedKey = in.readLong();

                amzaInstance.pong(ringMember, takeSessionId, takeSharedKey);
            }

            return Response.ok(conf.asByteArray(Boolean.TRUE)).build();

        } finally {
            try {
                in.close();
            } catch (Exception x) {
                LOG.error("Failed to close input stream", x);
            }
        }

    } catch (Exception x) {
        LOG.warn("Failed ackBatch", x);
        return ResponseHelper.INSTANCE.errorResponse("Failed ackBatch.", x);
    } finally {
        amzaStats.pongsReceived.increment();
    }
}