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:sit.web.client.HttpHelper.java

public HTTPResponse doHttpUrlConnectionRequest(URL url, String method, String contentType, byte[] payload,
        String unamePword64) throws MalformedURLException, ProtocolException, IOException, URISyntaxException {

    if (payload == null) { //make sure payload is initialized
        payload = new byte[0];
    }/*from w  w  w.  ja  v  a 2  s  .c o m*/

    boolean isHTTPS = url.getProtocol().equalsIgnoreCase("https");
    HttpURLConnection connection;

    if (isHTTPS) {
        connection = (HttpsURLConnection) url.openConnection();
    } else {
        connection = (HttpURLConnection) url.openConnection();
    }

    connection.setRequestMethod(method);
    connection.setRequestProperty("Host", url.getHost());
    connection.setRequestProperty("Content-Type", contentType);
    connection.setRequestProperty("Content-Length", String.valueOf(payload.length));

    if (isHTTPS) {
        connection.setRequestProperty("Authorization", "Basic " + unamePword64);
    }

    Logger.getLogger(HttpHelper.class.getName()).log(Level.FINER,
            "trying to connect:\n" + method + " " + url + "\nhttps:" + isHTTPS + "\nContentType:" + contentType
                    + "\nContent-Length:" + String.valueOf(payload.length));

    connection.setDoInput(true);
    if (payload.length > 0) {
        // open up the output stream of the connection
        connection.setDoOutput(true);
        FilterOutputStream output = new FilterOutputStream(connection.getOutputStream());

        // write out the data
        output.write(payload);
        output.close();
    }

    HTTPResponse response = new HTTPResponse(method + " " + url.toString(), payload, Charset.defaultCharset()); //TODO forward charset ot this method

    response.code = connection.getResponseCode();
    response.message = connection.getResponseMessage();

    Logger.getLogger(HttpHelper.class.getName()).log(Level.FINE,
            "received response: " + response.message + " with code: " + response.code);

    if (response.code != 500) {
        byte[] buffer = new byte[20480];

        ByteBuilder bytes = new ByteBuilder();

        // get ready to read the response from the cgi script
        DataInputStream input = new DataInputStream(connection.getInputStream());
        boolean done = false;
        while (!done) {
            int readBytes = input.read(buffer);
            done = (readBytes == -1);

            if (!done) {
                bytes.append(buffer, readBytes);
            }
        }
        input.close();
        response.reply = bytes.toString(Charset.defaultCharset());
    }
    return response;
}

From source file:ANNFileDetect.EncogTestClass.java

private double[] readFPfile(String file) {
    double[] tmpdbl = new double[20];
    try {/*from w w  w .  j a  v  a2  s.c  o m*/
        FileInputStream fstream = new FileInputStream(file);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line = "";
        int cnt = 0;
        while ((line = br.readLine()) != null) {
            String[] tmp = line.split(" ");
            tmpdbl[cnt] = (double) Double.parseDouble(tmp[1]);
            cnt++;
            tmpdbl[cnt] = (double) Double.parseDouble(tmp[3]);
            cnt++;
        }
        while (cnt < tmpdbl.length) {
            tmpdbl[cnt] = 0.0;
            cnt++;
        }
        in.close();
    } catch (Exception e) {
        System.err.println("Found exc: " + e.getMessage());
    }
    return tmpdbl;
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Reads in data file//from   w w w .j a va2 s  .co  m
 * @param inFile input file
 */
public static byte[] readFile(File inFile) throws IOException, FileNotFoundException {
    byte[] data = null;
    FileInputStream is = new FileInputStream(inFile);
    DataInputStream dis = new DataInputStream(is);
    data = new byte[dis.available()];
    dis.readFully(data);
    dis.close();
    is.close();
    return data;
}

From source file:org.apache.tajo.storage.rcfile.TestRCFile.java

public void testRCFileHeader(char[] expected, Configuration conf) throws IOException {

    writeTest(fs, 10000, file, bytesArray, conf);
    DataInputStream di = fs.open(file, 10000);
    byte[] bytes = new byte[3];
    di.read(bytes);//from   ww  w  .  j  a v  a  2 s.  co m
    for (int i = 0; i < expected.length; i++) {
        assertTrue("Headers did not match", bytes[i] == expected[i]);
    }
    di.close();
}

From source file:eu.delving.sip.files.ReportFile.java

public ReportFile(File reportFile, File reportIndexFile, File invalidFile, File linkFile, DataSet dataSet,
        String prefix) throws IOException {
    this.reportFile = reportFile;
    this.reportAccess = new RandomAccessFile(this.reportFile, "r");
    this.reportIndexAccess = new RandomAccessFile(reportIndexFile, "r");
    this.linkFile = new LinkFile(linkFile, dataSet, prefix);
    this.dataSet = dataSet;
    this.prefix = prefix;
    int recordCount = (int) (reportIndexAccess.length() / LONG_SIZE);
    recs = new ArrayList<Rec>(recordCount);
    for (int walk = 0; walk < recordCount; walk++)
        recs.add(new Rec(walk));
    DataInputStream invalidIn = new DataInputStream(new FileInputStream(invalidFile));
    int invalidCount = invalidIn.readInt();
    invalidRecs = new ArrayList<Rec>(invalidCount);
    for (int walk = 0; walk < invalidCount; walk++) {
        int recordNumber = invalidIn.readInt();
        invalidRecs.add(recs.get(recordNumber));
    }/*from   ww  w .  j a v a  2  s . c o  m*/
    invalidIn.close();
}

From source file:com.datatorrent.contrib.hdht.HDHTWalManager.java

public void copyPreviousWalFiles(List<PreviousWALDetails> parentWals,
        Set<PreviousWALDetails> alreadyCopiedWals) {
    try {/*from   www .  j a  va 2  s .  c om*/
        PreviousWALDetails parentWal = parentWals.iterator().next();
        // Copy Files to new WAL location
        for (long i = parentWal.getStartPosition().fileId; i <= parentWal.getEndPosition().fileId; i++) {
            DataInputStream in = bfs.getInputStream(parentWal.getWalKey(), WAL_FILE_PREFIX + i);
            DataOutputStream out = bfs.getOutputStream(walKey, WAL_FILE_PREFIX + i);
            IOUtils.copyLarge(in, out);
            in.close();
            out.close();
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer.java

@SuppressWarnings("deprecation")
public void runLocalization(final InetSocketAddress nmAddr) throws IOException, InterruptedException {
    // load credentials
    initDirs(conf, user, appId, lfs, localDirs, userFolder);
    final Credentials creds = new Credentials();
    DataInputStream credFile = null;
    try {//from w w w.java2 s  . c o  m
        // assume credentials in cwd
        // TODO: Fix
        Path tokenPath = new Path(String.format(TOKEN_FILE_NAME_FMT, localizerId));
        credFile = lfs.open(tokenPath);
        creds.readTokenStorageStream(credFile);
        // Explicitly deleting token file.
        lfs.delete(tokenPath, false);
    } finally {
        if (credFile != null) {
            credFile.close();
        }
    }
    // create localizer context
    UserGroupInformation remoteUser = UserGroupInformation.createRemoteUser(user);
    remoteUser.addToken(creds.getToken(LocalizerTokenIdentifier.KIND));
    final LocalizationProtocol nodeManager = remoteUser.doAs(new PrivilegedAction<LocalizationProtocol>() {
        @Override
        public LocalizationProtocol run() {
            return getProxy(nmAddr);
        }
    });

    // create user context
    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
    for (Token<? extends TokenIdentifier> token : creds.getAllTokens()) {
        ugi.addToken(token);
    }

    ExecutorService exec = null;
    try {
        exec = createDownloadThreadPool();
        CompletionService<Path> ecs = createCompletionService(exec);
        localizeFiles(nodeManager, ecs, ugi);
        return;
    } catch (Throwable e) {
        throw new IOException(e);
    } finally {
        try {
            if (exec != null) {
                exec.shutdownNow();
            }
            LocalDirAllocator.removeContext(appCacheDirContextName);
        } finally {
            closeFileSystems(ugi);
        }
    }
}

From source file:org.apache.wookie.WidgetAdminServlet.java

private void doDownload(HttpServletRequest req, HttpServletResponse resp, File f, String original_filename)
        throws IOException {
    int BUFSIZE = 1024;

    // File f = new File(filename);
    int length = 0;
    ServletOutputStream op = resp.getOutputStream();
    ServletContext context = getServletConfig().getServletContext();
    String mimetype = context.getMimeType(f.getAbsolutePath());

    ///*w ww  .ja v  a 2s  .co m*/
    // Set the response and go!
    //
    //
    resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
    resp.setContentLength((int) f.length());
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + original_filename + "\"");

    //
    // Stream to the requester.
    //
    byte[] bbuf = new byte[BUFSIZE];
    DataInputStream in = new DataInputStream(new FileInputStream(f));

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

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

From source file:org.exobel.routerkeygen.ui.Preferences.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void checkCurrentDictionary() throws FileNotFoundException {
    final String myDicFile = PreferenceManager.getDefaultSharedPreferences(getBaseContext())
            .getString(dicLocalPref, null);
    if (myDicFile == null) {
        removeDialog(DIALOG_ASK_DOWNLOAD);
        startService(new Intent(getApplicationContext(), DictionaryDownloadService.class)
                .putExtra(DictionaryDownloadService.URL_DOWNLOAD, PUB_DOWNLOAD));
    } else {// w ww.  j ava2  s . co m
        AsyncTask<Void, Void, Integer> task = new AsyncTask<Void, Void, Integer>() {
            private final static int TOO_ADVANCED = 1;
            private final static int OK = 0;
            private final static int DOWNLOAD_NEEDED = -1;
            private final static int ERROR_NETWORK = -2;
            private final static int ERROR = -3;

            protected void onPreExecute() {
                removeDialog(DIALOG_ASK_DOWNLOAD);
                showDialog(DIALOG_WAIT);
            }

            protected Integer doInBackground(Void... params) {

                // Comparing this version with the online
                // version
                try {
                    HttpURLConnection con = (HttpURLConnection) new URL(PUB_DIC_CFV).openConnection();
                    DataInputStream dis = new DataInputStream(con.getInputStream());

                    byte[] cfvTable = new byte[18];
                    boolean readCorrectly = InputStreamUtils.readFromInput(cfvTable, cfvTable.length, dis);
                    dis.close();
                    con.disconnect();
                    if (!readCorrectly) {
                        return ERROR;
                    }

                    InputStream is = new FileInputStream(myDicFile);
                    byte[] dicVersion = new byte[2];
                    // Check our version
                    readCorrectly = InputStreamUtils.readFromInput(dicVersion, dicVersion.length, is);
                    is.close();
                    if (!readCorrectly) {
                        return ERROR;
                    }
                    int thisVersion, onlineVersion;
                    thisVersion = dicVersion[0] << 8 | dicVersion[1];
                    onlineVersion = cfvTable[0] << 8 | cfvTable[1];

                    if (thisVersion == onlineVersion) {
                        // It is the latest version, but is
                        // it not corrupt?
                        byte[] dicHash = new byte[16];
                        System.arraycopy(cfvTable, 2, dicHash, 0, dicHash.length);
                        if (HashUtils.checkDicMD5(new File(myDicFile).getPath(), dicHash)) {
                            // All is well
                            return OK;
                        }
                    }
                    if (onlineVersion > thisVersion && onlineVersion > MAX_DIC_VERSION) {
                        // Online version is too advanced
                        return TOO_ADVANCED;
                    }
                    return DOWNLOAD_NEEDED;
                } catch (FileNotFoundException e) {
                    return DOWNLOAD_NEEDED;
                } catch (UnknownHostException e) {
                    return ERROR_NETWORK;
                } catch (Exception e) {
                    return ERROR;
                }
            }

            protected void onPostExecute(Integer result) {
                removeDialog(DIALOG_WAIT);
                if (isFinishing())
                    return;
                if (result == null) {
                    showDialog(DIALOG_ERROR);
                    return;
                }
                switch (result) {
                case ERROR:
                    showDialog(DIALOG_ERROR);
                    break;
                case ERROR_NETWORK:
                    Toast.makeText(Preferences.this, R.string.msg_errthomson3g, Toast.LENGTH_SHORT).show();
                    break;
                case DOWNLOAD_NEEDED:
                    startService(new Intent(getApplicationContext(), DictionaryDownloadService.class)
                            .putExtra(DictionaryDownloadService.URL_DOWNLOAD, PUB_DOWNLOAD));
                    break;
                case OK:
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_dic_updated),
                            Toast.LENGTH_SHORT).show();
                    break;
                case TOO_ADVANCED:
                    showDialog(DIALOG_ERROR_TOO_ADVANCED);
                    break;
                }

            }
        };
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
            task.execute();
        } else {
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }
}

From source file:com.datatorrent.contrib.hdht.HDHTWalManager.java

/**
 * Restore state of wal just after last checkpoint. The Apex platform will
 * resend tuple after last operator checkpoint to the WAL, this will result in
 * duplicate tuples in WAL, if we don't restore the WAL just after checkpoint
 * state./*from  ww  w. j a v a  2 s  .com*/
 */
private void truncateWal(WalPosition pos) throws IOException {
    if (pos.offset == 0) {
        return;
    }
    logger.info("recover wal file {}, data valid till offset {}", pos.fileId, pos.offset);
    DataInputStream in = bfs.getInputStream(walKey, WAL_FILE_PREFIX + pos.fileId);
    DataOutputStream out = bfs.getOutputStream(walKey, WAL_FILE_PREFIX + pos.fileId + "-truncate");
    IOUtils.copyLarge(in, out, 0, pos.offset);
    in.close();
    out.close();
    bfs.rename(walKey, WAL_FILE_PREFIX + pos.fileId + "-truncate", WAL_FILE_PREFIX + pos.fileId);
}