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.ephesoft.dcma.filebound.FileBoundExporter.java

@SuppressWarnings("deprecation")
private String fetchDocNameMapping(final String docName, final String batchClassIdentifier) {
    String returnValue = "";
    final String filePath = batchSchemaService.getBaseFolderLocation() + File.separator + batchClassIdentifier
            + File.separator + FileBoundConstants.MAPPING_FOLDER_NAME + File.separator
            + FileBoundConstants.PROPERTY_FILE_NAME;
    DataInputStream dataInputStream = null;
    FileInputStream fileInputStream = null;
    try {//from  w  ww  .  j  av  a  2s .c  o m
        fileInputStream = new FileInputStream(filePath);
        dataInputStream = new DataInputStream(fileInputStream);
        String eachLine = dataInputStream.readLine();
        while (eachLine != null) {
            if (eachLine.length() > 0) {
                final String[] keyValue = eachLine.split(FileBoundConstants.MAPPING_SEPERATOR);
                if (keyValue != null && keyValue.length > 0 && keyValue[0].equalsIgnoreCase(docName)) {
                    returnValue = keyValue[1];
                    break;
                }
            }
            eachLine = dataInputStream.readLine();
        }
    } catch (IOException e) {
        LOGGER.error("Error occured in reading from properties file.");
    } finally {
        try {
            if (dataInputStream != null) {
                dataInputStream.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException e) {
            LOGGER.debug("DataInputStream cannot be closed.");
        }
    }
    return returnValue;
}

From source file:bobs.is.compress.sevenzip.SevenZFile.java

private StartHeader readStartHeader(final long startHeaderCrc) throws IOException {
    final StartHeader startHeader = new StartHeader();
    DataInputStream dataInputStream = null;
    try {//from   ww  w .j av a2  s.  com
        dataInputStream = new DataInputStream(new CRC32VerifyingInputStream(
                new BoundedRandomAccessFileInputStream(file, 20), 20, startHeaderCrc));
        startHeader.nextHeaderOffset = Long.reverseBytes(dataInputStream.readLong());
        startHeader.nextHeaderSize = Long.reverseBytes(dataInputStream.readLong());
        startHeader.nextHeaderCrc = 0xffffFFFFL & Integer.reverseBytes(dataInputStream.readInt());
        return startHeader;
    } finally {
        if (dataInputStream != null) {
            dataInputStream.close();
        }
    }
}

From source file:com.tealeaf.NativeShim.java

public String loadSourceFile(String url) {
    TeaLeafOptions options = context.getOptions();
    String sourceString = null;/*from w ww  .  j a  v a  2  s  .c  om*/
    if (options.isDevelop() && options.get("forceURL", false)) {
        // load native.js from the file system
        // read file in
        String path = resourceManager.getStorageDirectory();
        String result = null;
        DataInputStream in = null;
        try {
            File f = new File(path + url);
            byte[] buffer = new byte[(int) f.length()];
            in = new DataInputStream(new FileInputStream(f));
            in.readFully(buffer);
            result = new String(buffer);
        } catch (FileNotFoundException e) {
            logger.log("Error loading", url, "from", path);
            logger.log("File not found!");
            throw new RuntimeException("File not found in loadSourceFile");
        } catch (IOException e) {
            throw new RuntimeException("IO problem in fileToString", e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                logger.log(e);
            }
        }
        sourceString = result;

    } else {
        sourceString = resourceManager.getFileContents(url);
    }
    return sourceString;
}

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 v a  2  s .co m
 */
@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();
        }
    }
}

From source file:org.apache.hama.monitor.ZKCollector.java

@Override
public MetricsRecord harvest() throws Exception {
    final String path = this.reference.get().path;
    final ZooKeeper zk = this.reference.get().zk;
    LOG.debug("Searching " + path + " in zookeeper.");
    Stat stat = zk.exists(path, false);/* w ww  .j ava  2s  .c om*/
    if (null == stat)
        return null; // no need to collect data.
    List<String> children = zk.getChildren(path, false);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Leaves size is " + children.size() + " total znodes in list: " + children);
    }

    // TODO: metrics record contains multiple metrics (1 to many)
    // data is stored under zk e.g. /path/to/metrics/jvm/...
    // within jvm folder metrics is stored in a form of name, value pair
    final MetricsRecord record = reference.get().record;
    if (null != children) {
        for (String child : children) {
            LOG.info("metrics -> " + child);
            // <metricsName_d> indicates data type is double
            String dataType = suffix(child);
            byte[] dataInBytes = zk.getData(path + "/" + child, false, stat);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Data length (in byte): " + dataInBytes.length);
            }
            DataInputStream input = null;
            try {
                String name = removeSuffix(child);
                input = new DataInputStream(new ByteArrayInputStream(dataInBytes));
                if ("d".equals(dataType)) {
                    double dv = input.readDouble();
                    LOG.info("metrics " + name + " value:" + dv);
                    record.add(new Metric<Double>(name, dv));
                } else if ("f".equals(dataType)) {
                    float fv = input.readFloat();
                    LOG.info("metrics " + name + " value:" + fv);
                    record.add(new Metric<Float>(name, fv));
                } else if ("i".equals(dataType)) {
                    int iv = input.readInt();
                    LOG.info("metrics " + name + " value:" + iv);
                    record.add(new Metric<Integer>(name, iv));
                } else if ("l".equals(dataType)) {
                    long lv = input.readLong();
                    LOG.info("metrics " + name + " value:" + lv);
                    record.add(new Metric<Long>(name, lv));
                } else if ("b".equals(dataType)) {
                    LOG.info("metrics" + name + " value:" + Arrays.toString(dataInBytes));
                    record.add(new Metric<byte[]>(name, dataInBytes));
                } else {
                    LOG.warn("Unkown data type for metrics name: " + child);
                }
            } finally {
                input.close();
            }
        }
    }
    return record;
}

From source file:org.apache.hadoop.mapred.TestShuffleHandler.java

@Test(timeout = 10000)
public void testKeepAlive() throws Exception {
    final ArrayList<Throwable> failures = new ArrayList<Throwable>(1);
    Configuration conf = new Configuration();
    conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0);
    conf.setBoolean(ShuffleHandler.SHUFFLE_CONNECTION_KEEP_ALIVE_ENABLED, true);
    // try setting to -ve keep alive timeout.
    conf.setInt(ShuffleHandler.SHUFFLE_CONNECTION_KEEP_ALIVE_TIME_OUT, -100);
    final LastSocketAddress lastSocketAddress = new LastSocketAddress();

    ShuffleHandler shuffleHandler = new ShuffleHandler() {
        @Override/*w ww.j a  va  2s  . c o  m*/
        protected Shuffle getShuffle(final Configuration conf) {
            // replace the shuffle handler with one stubbed for testing
            return new Shuffle(conf) {
                @Override
                protected MapOutputInfo getMapOutputInfo(String base, String mapId, int reduce, String user)
                        throws IOException {
                    return null;
                }

                @Override
                protected void verifyRequest(String appid, ChannelHandlerContext ctx, HttpRequest request,
                        HttpResponse response, URL requestUri) throws IOException {
                }

                @Override
                protected void populateHeaders(List<String> mapIds, String jobId, String user, int reduce,
                        HttpRequest request, HttpResponse response, boolean keepAliveParam,
                        Map<String, MapOutputInfo> infoMap) throws IOException {
                    // Send some dummy data (populate content length details)
                    ShuffleHeader header = new ShuffleHeader("attempt_12345_1_m_1_0", 5678, 5678, 1);
                    DataOutputBuffer dob = new DataOutputBuffer();
                    header.write(dob);
                    dob = new DataOutputBuffer();
                    for (int i = 0; i < 100000; ++i) {
                        header.write(dob);
                    }

                    long contentLength = dob.getLength();
                    // for testing purpose;
                    // disable connectinKeepAliveEnabled if keepAliveParam is available
                    if (keepAliveParam) {
                        connectionKeepAliveEnabled = false;
                    }

                    super.setResponseHeaders(response, keepAliveParam, contentLength);
                }

                @Override
                protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch, String user,
                        String mapId, int reduce, MapOutputInfo info) throws IOException {
                    lastSocketAddress.setAddress(ch.getRemoteAddress());
                    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

                    // send a shuffle header and a lot of data down the channel
                    // to trigger a broken pipe
                    ShuffleHeader header = new ShuffleHeader("attempt_12345_1_m_1_0", 5678, 5678, 1);
                    DataOutputBuffer dob = new DataOutputBuffer();
                    header.write(dob);
                    ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
                    dob = new DataOutputBuffer();
                    for (int i = 0; i < 100000; ++i) {
                        header.write(dob);
                    }
                    return ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
                }

                @Override
                protected void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
                    if (failures.size() == 0) {
                        failures.add(new Error());
                        ctx.getChannel().close();
                    }
                }

                @Override
                protected void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) {
                    if (failures.size() == 0) {
                        failures.add(new Error());
                        ctx.getChannel().close();
                    }
                }
            };
        }
    };
    shuffleHandler.init(conf);
    shuffleHandler.start();

    String shuffleBaseURL = "http://127.0.0.1:"
            + shuffleHandler.getConfig().get(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY);
    URL url = new URL(shuffleBaseURL + "/mapOutput?job=job_12345_1&reduce=1&" + "map=attempt_12345_1_m_1_0");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
    conn.connect();
    DataInputStream input = new DataInputStream(conn.getInputStream());
    Assert.assertEquals(HttpHeaders.KEEP_ALIVE, conn.getHeaderField(HttpHeaders.CONNECTION));
    Assert.assertEquals("timeout=1", conn.getHeaderField(HttpHeaders.KEEP_ALIVE));
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    ShuffleHeader header = new ShuffleHeader();
    header.readFields(input);
    byte[] buffer = new byte[1024];
    while (input.read(buffer) != -1) {
    }
    SocketAddress firstAddress = lastSocketAddress.getSocketAddres();
    input.close();

    // For keepAlive via URL
    url = new URL(shuffleBaseURL + "/mapOutput?job=job_12345_1&reduce=1&"
            + "map=attempt_12345_1_m_1_0&keepAlive=true");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
    conn.connect();
    input = new DataInputStream(conn.getInputStream());
    Assert.assertEquals(HttpHeaders.KEEP_ALIVE, conn.getHeaderField(HttpHeaders.CONNECTION));
    Assert.assertEquals("timeout=1", conn.getHeaderField(HttpHeaders.KEEP_ALIVE));
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    header = new ShuffleHeader();
    header.readFields(input);
    input.close();
    SocketAddress secondAddress = lastSocketAddress.getSocketAddres();
    Assert.assertNotNull("Initial shuffle address should not be null", firstAddress);
    Assert.assertNotNull("Keep-Alive shuffle address should not be null", secondAddress);
    Assert.assertEquals("Initial shuffle address and keep-alive shuffle " + "address should be the same",
            firstAddress, secondAddress);

}

From source file:HttpPOSTMIDlet.java

private String requestUsingGET(String URLString) throws IOException {
    HttpConnection hpc = null;/*from w  w w  .  j a v a2 s .c  om*/
    DataInputStream dis = null;
    DataOutputStream dos = null;

    boolean newline = false;
    String content = "";
    try {
        hpc = (HttpConnection) Connector.open(defaultURL);
        hpc.setRequestMethod(HttpConnection.POST);
        hpc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
        hpc.setRequestProperty("Content-Language", "zh-tw");
        hpc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        hpc.setRequestProperty("Content-Length", String.valueOf(URLString.length()));

        dos = new DataOutputStream(hpc.openOutputStream());
        dos.write(URLString.getBytes());
        dos.flush();

        InputStreamReader xdis = new InputStreamReader(hpc.openInputStream());

        int character;
        while ((character = xdis.read()) != -1) {
            if ((char) character == '\\') {
                newline = true;
                continue;
            } else {
                if ((char) character == 'n' && newline) {
                    content += "\n";
                    newline = false;
                } else if (newline) {
                    content += "\\" + (char) character;
                    newline = false;
                } else {
                    content += (char) character;
                    newline = false;
                }
            }

        }
        if (hpc != null)
            hpc.close();
        if (dis != null)
            dis.close();
    } catch (IOException e2) {
    }

    return content;
}

From source file:org.eclipse.kura.linux.net.iptables.LinuxFirewall.java

public ArrayList<String> readFileLinebyLine(String sourceFile) {
    ArrayList<String> destination = new ArrayList<String>();
    DataInputStream in = null;
    BufferedReader br = null;//  w  ww .  j  a  v  a 2  s.c o m

    try {
        // Open the file that is the first command line parameter
        FileInputStream fstream = new FileInputStream(sourceFile);

        // Get the object of DataInputStream
        in = new DataInputStream(fstream);
        br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        int i = 0;

        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console
            destination.add(i, strLine);
            i = i + 1;
        }

        // Close the input stream
        in.close();
    } catch (FileNotFoundException e) {// Catch exception if any
        s_logger.error("the file: " + sourceFile + " does not exist", e);
    } catch (IOException ioe) {
        s_logger.error("IOException while trying to open: " + sourceFile, ioe);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                s_logger.error("I/O Exception while closing DataInputStream!", ex);
            }
        }
        if (br != null) {
            try {
                br.close();
            } catch (IOException ex) {
                s_logger.error("I/O Exception while closing BufferedReader!", ex);
            }
        }
    }

    s_logger.trace("size of destination is" + destination.size());
    return destination;
}

From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java

/**
 * Load the current set of tokens from the token file. If reading the tokens
 * fails or the token file does not exist, tokens will be generated on
 * demand.//from  w ww . j a va  2 s.com
 */
private void loadTokens() {
    if (tokenFile.isFile() && tokenFile.canRead()) {
        FileInputStream fin = null;
        DataInputStream keyInputStream = null;
        try {
            fin = new FileInputStream(tokenFile);
            keyInputStream = new DataInputStream(fin);
            int newCurrentToken = keyInputStream.readInt();
            long newNextUpdate = keyInputStream.readLong();
            SecretKey[] newKeys = new SecretKey[TOKEN_BUFFER_SIZE];
            for (int i = 0; i < newKeys.length; i++) {
                int isNull = keyInputStream.readInt();
                if (isNull == 1) {
                    int l = keyInputStream.readInt();
                    byte[] b = new byte[l];
                    keyInputStream.read(b);
                    newKeys[i] = new SecretKeySpec(b, HMAC_SHA1);
                } else {
                    newKeys[i] = null;
                }
            }

            // assign the tokes and schedule a next update
            nextUpdate = newNextUpdate;
            currentToken = newCurrentToken;
            currentTokens = newKeys;

        } catch (IOException e) {

            log.error("Failed to load cookie keys " + e.getMessage());

        } finally {

            if (keyInputStream != null) {
                try {
                    keyInputStream.close();
                } catch (IOException e) {
                }
            } else if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                }
            }
        }
    }

    // if there was a failure to read the current tokens, create new ones
    if (currentTokens == null) {
        currentTokens = new SecretKey[TOKEN_BUFFER_SIZE];
        nextUpdate = System.currentTimeMillis();
        currentToken = 0;
    }
}

From source file:org.alfresco.webservice.util.ContentUtils.java

/**
 * Streams content into the repository.  Once done a content details string is returned and this can be used to update 
 * a content property in a CML statement.
 * /*from   w  w w.j av  a2 s. c o  m*/
 * @param file  the file to stream into the repository
 * @param host  the host name of the destination repository
 * @param port  the port name of the destination repository
 * @param webAppName        the name of the target web application (default 'alfresco')
 * @param mimetype the mimetype of the file, ignored if null
 * @param encoding the encoding of the file, ignored if null
 * @return      the content data that can be used to set the content property in a CML statement  
 */
@SuppressWarnings("deprecation")
public static String putContent(File file, String host, int port, String webAppName, String mimetype,
        String encoding) {
    String result = null;

    try {
        String url = "/" + webAppName + "/upload/" + URLEncoder.encode(file.getName(), "UTF-8") + "?ticket="
                + AuthenticationUtils.getTicket();
        if (mimetype != null) {
            url = url + "&mimetype=" + mimetype;
        }
        if (encoding != null) {
            url += "&encoding=" + encoding;
        }

        String request = "PUT " + url + " HTTP/1.1\n" + "Cookie: JSESSIONID="
                + AuthenticationUtils.getAuthenticationDetails().getSessionId() + ";\n" + "Content-Length: "
                + file.length() + "\n" + "Host: " + host + ":" + port + "\n" + "Connection: Keep-Alive\n"
                + "\n";

        // Open sockets and streams
        Socket socket = new Socket(host, port);
        DataOutputStream os = new DataOutputStream(socket.getOutputStream());
        DataInputStream is = new DataInputStream(socket.getInputStream());

        try {
            if (socket != null && os != null && is != null) {
                // Write the request header
                os.writeBytes(request);

                // Stream the content onto the server
                InputStream fileInputStream = new FileInputStream(file);
                int byteCount = 0;
                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead = -1;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                    byteCount += bytesRead;
                }
                os.flush();
                fileInputStream.close();

                // Read the response and deal with any errors that might occur
                boolean firstLine = true;
                String responseLine;
                while ((responseLine = is.readLine()) != null) {
                    if (firstLine == true) {
                        if (responseLine.contains("200") == true) {
                            firstLine = false;
                        } else if (responseLine.contains("401") == true) {
                            throw new RuntimeException(
                                    "Content could not be uploaded because invalid credentials have been supplied.");
                        } else if (responseLine.contains("403") == true) {
                            throw new RuntimeException(
                                    "Content could not be uploaded because user does not have sufficient privileges.");
                        } else {
                            throw new RuntimeException(
                                    "Error returned from upload servlet (" + responseLine + ")");
                        }
                    } else if (responseLine.contains("contentUrl") == true) {
                        result = responseLine;
                        break;
                    }
                }
            }
        } finally {
            try {
                // Close the streams and socket
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("Error closing sockets and streams", e);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error writing content to repository server", e);
    }

    return result;
}