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:com.gisgraphy.test.GeolocTestHelper.java

public static boolean isFileContains(File file, String text) {
    if (file == null) {
        throw new IllegalArgumentException("can not check a null file");
    }//from   w ww  . j a  v a  2s . c  o m
    if (!file.exists()) {
        throw new IllegalArgumentException("can not check a file that does not exists");
    }
    if (!file.isFile()) {
        throw new IllegalArgumentException("can only check file, not directory");
    }
    FileInputStream fstream = null;
    DataInputStream in = null;
    try {
        fstream = new FileInputStream(file);
        in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            if (strLine.contains(text)) {
                return true;
            }
        }
    } catch (Exception e) {// Catch exception if any
        throw new IllegalArgumentException(
                "an exception has occured durind the assertion of " + text + " in " + file.getAbsolutePath());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (fstream != null) {
            try {
                fstream.close();
            } catch (IOException e) {
            }
        }
    }
    return false;
}

From source file:com.gisgraphy.test.GeolocTestHelper.java

public static int countLinesInFileThatStartsWith(File file, String text) {
    int count = 0;
    if (file == null) {
        throw new IllegalArgumentException("can not check a null file");
    }//from  w  ww .j a  v a2  s  .co m
    if (!file.exists()) {
        throw new IllegalArgumentException("can not check a file that does not exists");
    }
    if (!file.isFile()) {
        throw new IllegalArgumentException("can only check file, not directory");
    }
    FileInputStream fstream = null;
    DataInputStream in = null;
    try {
        fstream = new FileInputStream(file);
        in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            if (strLine.trim().startsWith(text)) {
                count++;
            }
        }
    } catch (Exception e) {// Catch exception if any
        throw new IllegalArgumentException(
                "an exception has occured durind the assertion of " + text + " in " + file.getAbsolutePath());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (fstream != null) {
            try {
                fstream.close();
            } catch (IOException e) {
            }
        }
    }
    return count;
}

From source file:org.apache.helix.tools.ClusterSetup.java

private static byte[] readFile(String filePath) throws IOException {
    File file = new File(filePath);

    int size = (int) file.length();
    byte[] bytes = new byte[size];
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    int read = 0;
    int numRead = 0;
    while (read < bytes.length && (numRead = dis.read(bytes, read, bytes.length - read)) >= 0) {
        read = read + numRead;//from   w w w .j a va2  s  .c om
    }
    dis.close();
    return bytes;
}

From source file:org.freeeed.search.web.controller.CaseFileDownloadController.java

@Override
public ModelAndView execute() {
    HttpSession session = this.request.getSession(true);
    SolrSessionObject solrSession = (SolrSessionObject) session
            .getAttribute(WebConstants.WEB_SESSION_SOLR_OBJECT);

    if (solrSession == null || solrSession.getSelectedCase() == null) {
        return new ModelAndView(WebConstants.CASE_FILE_DOWNLOAD);
    }//  w w w.java  2s  .c  o m

    Case selectedCase = solrSession.getSelectedCase();

    String action = (String) valueStack.get("action");

    log.debug("Action called: " + action);

    File toDownload = null;
    boolean htmlMode = false;

    String docPath = (String) valueStack.get("docPath");
    String uniqueId = (String) valueStack.get("uniqueId");

    try {
        if ("exportNative".equals(action)) {
            toDownload = caseFileService.getNativeFile(selectedCase.getName(), docPath, uniqueId);

        } else if ("exportImage".equals(action)) {
            toDownload = caseFileService.getImageFile(selectedCase.getName(), docPath, uniqueId);
        } else if ("exportHtml".equals(action)) {
            toDownload = caseFileService.getHtmlFile(selectedCase.getName(), docPath, uniqueId);
            htmlMode = true;
        } else if ("exportHtmlImage".equals(action)) {
            toDownload = caseFileService.getHtmlImageFile(selectedCase.getName(), docPath);
            htmlMode = true;
        } else if ("exportNativeAll".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);

            toDownload = caseFileService.getNativeFiles(selectedCase.getName(), docs);

        } else if ("exportNativeAllFromSource".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);

            String source = (String) valueStack.get("source");
            try {
                source = URLDecoder.decode(source, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            }

            toDownload = caseFileService.getNativeFilesFromSource(source, docs);
        } else if ("exportImageAll".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);
            toDownload = caseFileService.getImageFiles(selectedCase.getName(), docs);
        }
    } catch (Exception e) {
        log.error("Problem sending cotent", e);
        valueStack.put("error", true);
    }

    if (toDownload != null) {
        try {
            int length = 0;
            ServletOutputStream outStream = response.getOutputStream();
            String mimetype = "application/octet-stream";
            if (htmlMode) {
                mimetype = "text/html";
            }

            response.setContentType(mimetype);
            response.setContentLength((int) toDownload.length());
            String fileName = toDownload.getName();

            if (!htmlMode) {
                // sets HTTP header
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            }

            byte[] byteBuffer = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(toDownload));

            // reads the file's bytes and writes them to the response stream
            while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
                outStream.write(byteBuffer, 0, length);
            }

            in.close();
            outStream.close();
        } catch (Exception e) {
            log.error("Problem sending cotent", e);
            valueStack.put("error", true);
        }
    } else {
        valueStack.put("error", true);
    }

    return new ModelAndView(WebConstants.CASE_FILE_DOWNLOAD);
}

From source file:org.apache.hama.bsp.BSPApplicationMaster.java

private BSPApplicationMaster(String[] args) throws Exception {
    if (args.length != 1) {
        throw new IllegalArgumentException();
    }/*from   w ww.j a  v  a 2  s.c  om*/

    this.jobFile = args[0];
    this.localConf = new YarnConfiguration();
    this.jobConf = getSubmitConfiguration(jobFile);
    fs = FileSystem.get(jobConf);

    this.applicationName = jobConf.get("bsp.job.name", "<no bsp job name defined>");
    if (applicationName.isEmpty()) {
        this.applicationName = "<no bsp job name defined>";
    }

    this.appAttemptId = getApplicationAttemptId();

    this.yarnRPC = YarnRPC.create(localConf);
    this.clock = new SystemClock();
    this.startTime = clock.getTime();

    this.jobId = new BSPJobID(appAttemptId.toString(), 0);

    this.hostname = BSPNetUtils.getCanonicalHostname();
    this.clientPort = BSPNetUtils.getFreePort(12000);

    // start our synchronization service
    startSyncServer();

    startRPCServers();

    /*
     * Make sure that this executes after the start the RPC servers, because we
     * are readjusting the configuration.
     */

    rewriteSubmitConfiguration(jobFile, jobConf);

    String jobSplit = jobConf.get("bsp.job.split.file");
    splits = null;
    if (jobSplit != null) {
        DataInputStream splitFile = fs.open(new Path(jobSplit));
        try {
            splits = BSPJobClient.readSplitFile(splitFile);
        } finally {
            splitFile.close();
        }
    }

    this.amrmRPC = getYarnRPCConnection(localConf);
    registerApplicationMaster(amrmRPC, hostname, clientPort, "http://localhost:8080");
}

From source file:net.mohatu.bloocoin.miner.RegCustom.java

private void register() {
    try {//from www .ja v a  2 s  .c  om
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            JOptionPane.showMessageDialog(Main.scrollPane,
                    "Registration failed.\nCheck your network connection", "Registration Failed",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:it.evilsocket.dsploit.core.System.java

private static void preloadVendors() {
    if (mVendors == null) {
        try {/*from  www.  j a v  a 2  s. c om*/
            mVendors = new HashMap<String, String>();
            FileInputStream fstream = new FileInputStream(
                    mContext.getFilesDir().getAbsolutePath() + "/tools/nmap/nmap-mac-prefixes");
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("#") == false && line.isEmpty() == false) {
                    String[] tokens = line.split(" ", 2);

                    if (tokens.length == 2)
                        mVendors.put(tokens[0], tokens[1]);
                }
            }

            in.close();
        } catch (Exception e) {
            errorLogging(TAG, e);
        }
    }
}

From source file:com.sshtools.appframework.ui.IconStore.java

private Icon get(String name, int size, String cacheKey, FileObject file)
        throws FileSystemException, IOException {
    Icon icon;/* w  ww .  j  a  v  a  2s  .com*/
    if (file.getName().getBaseName().toLowerCase().endsWith(".svg")) {
        InputStream in = file.getContent().getInputStream();
        try {
            icon = new SVGIcon(name + "-" + size, in, size, size);
        } finally {
            in.close();
        }
    } else {
        DataInputStream din = new DataInputStream(file.getContent().getInputStream());
        try {
            byte[] imgData = new byte[(int) file.getContent().getSize()];
            din.readFully(imgData);
            icon = new ImageIcon(imgData);
        } finally {
            din.close();
        }
    }
    if (icon.getIconWidth() != size && icon instanceof ImageIcon) {
        Image img = ((ImageIcon) icon).getImage();
        img = img.getScaledInstance(size, size, Image.SCALE_SMOOTH);
        icon = new ImageIcon(img);
    }
    cache.put(cacheKey, icon);
    return icon;
}

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;//from  ww  w . j  a  va2  s . co  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:org.apache.hadoop.hdfs.tools.DelegationTokenFetcher.java

/**
 * Utility method to obtain a delegation token over http
 * @param nnHttpAddr Namenode http addr, such as http://namenode:50070
 *///  www. j  av a 2  s.  co  m
static public Credentials getDTfromRemote(String nnAddr, String renewer) throws IOException {
    DataInputStream dis = null;
    InetSocketAddress serviceAddr = NetUtils.createSocketAddr(nnAddr);

    try {
        StringBuffer url = new StringBuffer();
        if (renewer != null) {
            url.append(nnAddr).append(GetDelegationTokenServlet.PATH_SPEC).append("?")
                    .append(GetDelegationTokenServlet.RENEWER).append("=").append(renewer);
        } else {
            url.append(nnAddr).append(GetDelegationTokenServlet.PATH_SPEC);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Retrieving token from: " + url);
        }
        URL remoteURL = new URL(url.toString());
        SecurityUtil.fetchServiceTicket(remoteURL);
        URLConnection connection = remoteURL.openConnection();

        InputStream in = connection.getInputStream();
        Credentials ts = new Credentials();
        dis = new DataInputStream(in);
        ts.readFields(dis);
        for (Token<?> token : ts.getAllTokens()) {
            token.setKind(HftpFileSystem.TOKEN_KIND);
            SecurityUtil.setTokenService(token, serviceAddr);
        }
        return ts;
    } catch (Exception e) {
        throw new IOException("Unable to obtain remote token", e);
    } finally {
        if (dis != null)
            dis.close();
    }
}