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.alphabetbloc.accessmrs.tasks.CheckConnectivityTask.java

protected DataInputStream getServerStream() throws Exception {

    HttpPost request = new HttpPost(mServer);
    request.setEntity(new OdkAuthEntity());
    HttpResponse response = httpClient.execute(request);
    response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    responseEntity.getContentLength();//from  w w w.  ja  va  2s.  c  o  m

    DataInputStream zdis = new DataInputStream(new GZIPInputStream(responseEntity.getContent()));

    int status = zdis.readInt();
    if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
        zdis.close();
        throw new IOException("Access denied. Check your username and password.");
    } else if (status <= 0 || status >= HttpURLConnection.HTTP_BAD_REQUEST) {
        zdis.close();
        throw new IOException("Connection Failed. Please Try Again.");
    } else {
        assert (status == HttpURLConnection.HTTP_OK); // success
        return zdis;
    }
}

From source file:es.urjc.mctwp.image.impl.analyze.AnalyzeImagePlugin.java

private boolean checkFormat(File file) throws IOException {
    boolean result = false;

    if (file != null) {
        DataInputStream stream = new DataInputStream(new FileInputStream(file));
        int check = stream.readInt();
        stream.close();

        result = (check == 0x15c) || (swap(check) == 0x15c);
    }/*from   w  ww .  ja  v a  2s . c o m*/

    return result;
}

From source file:com.krikelin.spotifysource.AppInstaller.java

public void installJar() throws IOException, SAXException, ParserConfigurationException {

    java.util.jar.JarFile jar = new java.util.jar.JarFile(app_jar);
    // Get manifest
    java.util.Enumeration<JarEntry> enu = jar.entries();
    while (enu.hasMoreElements()) {
        JarEntry elm = enu.nextElement();
        if (elm.getName().equals("SpotifyAppManifest.xml")) {
            DataInputStream dis = new DataInputStream(jar.getInputStream(elm));
            Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(dis);
            dis.close();
            // Get package name
            String package_name = d.getDocumentElement().getAttribute("package");

            addPackage(package_name, "packages");
            // Get all activities
            NodeList activities = d.getElementsByTagName("activity");
            for (int i = 0; i < activities.getLength(); i++) {
                Element activity = (Element) activities.item(i);
                String name = activity.getAttribute("name"); // Get the name
                // Append the previous name if it starts with .
                if (name.startsWith(".")) {
                    name = name.replace(".", "");

                }//  w w  w.  j a v a2  s  .  c om
                if (!name.startsWith(package_name)) {
                    name = package_name + "." + name;

                }
                //addPackage(name,"activities");
                NodeList intentFilters = activity.getElementsByTagName("intent-filter");
                for (int j = 0; j < intentFilters.getLength(); j++) {
                    NodeList actions = ((Element) intentFilters.item(0)).getElementsByTagName("action");
                    for (int k = 0; k < actions.getLength(); k++) {
                        String action_name = ((Element) actions.item(k)).getAttribute("name");
                        addPackage(name, "\\activities\\" + action_name);
                    }

                }
            }
            copyFile(app_jar.getAbsolutePath(), SPContainer.EXTENSION_DIR + "\\jar\\" + package_name + ".jar");
            // Runtime.getRuntime().exec("copy \""+app_jar+"\" \""+SPContainer.EXTENSION_DIR+"\\jar\\"+package_name+".jar\"");

        }
    }

}

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

/**
 * Main method.// w w w  .j av  a 2 s . co m
 */
boolean run(String[] args) throws ClassNotFoundException, IOException, InterruptedException {
    if (args.length < 1) {
        System.out.println("Usage: IsolationRunner <path>/job.xml " + "<optional-user-name>");
        return false;
    }
    File jobFilename = new File(args[0]);
    if (!jobFilename.exists() || !jobFilename.isFile()) {
        System.out.println(jobFilename + " is not a valid job file.");
        return false;
    }
    String user;
    if (args.length > 1) {
        user = args[1];
    } else {
        user = UserGroupInformation.getCurrentUser().getShortUserName();
    }
    JobConf conf = new JobConf(new Path(jobFilename.toString()));
    conf.setUser(user);
    TaskAttemptID taskId = TaskAttemptID.forName(conf.get("mapred.task.id"));
    if (taskId == null) {
        System.out.println("mapred.task.id not found in configuration;" + " job.xml is not a task config");
    }
    boolean isMap = conf.getBoolean("mapred.task.is.map", true);
    if (!isMap) {
        System.out.println("Only map tasks are supported.");
        return false;
    }
    int partition = conf.getInt("mapred.task.partition", 0);

    // setup the local and user working directories
    FileSystem local = FileSystem.getLocal(conf);
    LocalDirAllocator lDirAlloc = new LocalDirAllocator("mapred.local.dir");
    Path workDirName;
    boolean workDirExists = lDirAlloc.ifExists(MRConstants.WORKDIR, conf);
    if (workDirExists) {
        workDirName = TaskRunner.formWorkDir(lDirAlloc, conf);
    } else {
        workDirName = lDirAlloc.getLocalPathForWrite(MRConstants.WORKDIR, conf);
    }

    local.setWorkingDirectory(new Path(workDirName.toString()));

    FileSystem.get(conf).setWorkingDirectory(conf.getWorkingDirectory());

    // set up a classloader with the right classpath
    ClassLoader classLoader = makeClassLoader(conf, new File(workDirName.toString()));
    Thread.currentThread().setContextClassLoader(classLoader);
    conf.setClassLoader(classLoader);

    // split.dta file is used only by IsolationRunner. The file can now be in
    // any of the configured local disks, so use LocalDirAllocator to find out
    // where it is.
    Path localMetaSplit = new LocalDirAllocator("mapred.local.dir").getLocalPathToRead(
            TaskTracker.getLocalSplitFile(conf.getUser(), taskId.getJobID().toString(), taskId.toString()),
            conf);
    DataInputStream splitFile = FileSystem.getLocal(conf).open(localMetaSplit);
    TaskSplitIndex splitIndex = new TaskSplitIndex();
    splitIndex.readFields(splitFile);
    splitFile.close();
    Task task = new MapTask(jobFilename.toString(), taskId, partition, splitIndex, 1);
    task.setConf(conf);
    task.run(conf, new FakeUmbilical());
    return true;
}

From source file:org.freeeed.ep.web.controller.FileDownloadController.java

@Override
public ModelAndView execute() {
    String result = (String) valueStack.get("file");
    String resultFile = workDir + File.separator + result;

    File toDownload = new File(resultFile);

    try {/*from   ww w.j a  va2 s .c  o m*/
        int length = 0;
        ServletOutputStream outStream = response.getOutputStream();
        String mimetype = "application/octet-stream";

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

        // 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);
    }

    return new ModelAndView(WebConstants.DOWNLOAD_RESULT);
}

From source file:org.esupportail.papercut.services.PayBoxService.java

public void setDerPayboxPublicKeyFile(String derPayboxPublicKeyFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    org.springframework.core.io.Resource derPayboxPublicKeyRessource = new ClassPathResource(
            derPayboxPublicKeyFile);//  w  w  w .j  a  va2s.c o m
    InputStream fis = derPayboxPublicKeyRessource.getInputStream();
    DataInputStream dis = new DataInputStream(fis);
    byte[] pubKeyBytes = new byte[fis.available()];
    dis.readFully(pubKeyBytes);
    fis.close();
    dis.close();
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKeyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    this.payboxPublicKey = kf.generatePublic(x509EncodedKeySpec);
}

From source file:com.datatorrent.stram.FSRecoveryHandler.java

public String readConnectUri() throws IOException {
    byte[] bytes;

    DataInputStream in = fs.open(heartbeatPath);
    try {/*from www . j  a  va  2s.  c om*/
        bytes = IOUtils.toByteArray(in);
    } finally {
        in.close();
    }

    String uri = new String(bytes);
    LOG.debug("Connect address: {} from {} ", uri, heartbeatPath);
    return uri;
}

From source file:net.mms_projects.copy_it.server.push.android.GCMRunnable.java

public void run() {
    try {/*from w ww  .j a  v a2s. c o m*/
        URL url = new URL(GCM_URL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(POST);
        conn.setRequestProperty(CONTENT_TYPE, Page.ContentTypes.JSON_TYPE);
        conn.setRequestProperty(AUTHORIZATION, KEY);
        final String output_json = full.toString();
        System.err.println("Input json: " + output_json);
        conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(output_json.length()));
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream outputstream = new DataOutputStream(conn.getOutputStream());
        outputstream.writeBytes(output_json);
        outputstream.close();
        DataInputStream input = new DataInputStream(conn.getInputStream());
        StringBuilder builder = new StringBuilder(input.available());
        for (int c = input.read(); c != -1; c = input.read())
            builder.append((char) c);
        input.close();
        output = new JSONObject(builder.toString());
        System.err.println("Output json: " + output.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.cassandra.db.migration.SerializationsTest.java

@Test
public void testRead() throws IOException, ConfigurationException {
    if (AbstractSerializationsTester.EXECUTE_WRITES)
        testWrite();/*from  w  w w .  ja  v  a 2  s. c o m*/

    for (int i = 0; i < ksCount; i++) {
        String tableName = "Keyspace" + (i + 1);
        DataInputStream in = getInput("db.migration." + tableName + ".bin");
        byte[] raw = Base64.decodeBase64(in.readUTF().getBytes());
        org.apache.cassandra.db.migration.avro.Migration obj = new org.apache.cassandra.db.migration.avro.Migration();
        SerDeUtils.deserializeWithSchema(ByteBuffer.wrap(raw), obj);
        in.close();
    }
}

From source file:org.apache.giraph.comm.TestMessageStores.java

private <S extends MessageStore<IntWritable, IntWritable>> S doCheckpoint(
        MessageStoreFactory<IntWritable, IntWritable, S> messageStoreFactory, S messageStore)
        throws IOException {
    File file = new File(directory, "messageStoreTest");
    if (file.exists()) {
        file.delete();/*from w w  w  . j  a  v  a  2s. co  m*/
    }
    file.createNewFile();
    DataOutputStream out = new DataOutputStream(new BufferedOutputStream((new FileOutputStream(file))));
    messageStore.write(out);
    out.close();

    messageStore = messageStoreFactory.newStore();

    DataInputStream in = new DataInputStream(new BufferedInputStream((new FileInputStream(file))));
    messageStore.readFields(in);
    in.close();
    file.delete();

    return messageStore;
}