Example usage for java.io InputStream close

List of usage examples for java.io InputStream close

Introduction

In this page you can find the example usage for java.io InputStream 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:SWTBrowserDemo.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    shell.setText(getResourceString("window.title"));
    InputStream stream = SWTBrowserDemo.class.getResourceAsStream(iconLocation);
    Image icon = new Image(display, stream);
    shell.setImage(icon);/*from  w  ww  .j a v a 2 s  .  c  o  m*/
    try {
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    SWTBrowserDemo app = new SWTBrowserDemo(shell, true);
    app.setShellDecoration(icon, true);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    icon.dispose();
    app.dispose();
    display.dispose();
}

From source file:org.fcrepo.server.utilities.ServerUtility.java

/**
 * Command-line entry point to reload policies. Takes 3 args: protocol user
 * pass//from   w w  w.  j  av  a  2s . c o  m
 */
public static void main(String[] args) {

    if (args.length < 1) {
        System.out.println("Parameters:  method arg1 arg2 arg3 etc");
        System.out.println("");
        System.out.println("Methods:");
        System.out.println("    reloadpolicies");
        System.out.println("    migratedatastreamcontrolgroup");
        System.exit(0);
    }

    String method = args[0].toLowerCase();

    if (method.equals("reloadpolicies")) {
        if (args.length == 4) {
            try {
                reloadPolicies(args[1], args[2], args[3]);
                System.out.println("SUCCESS: Policies have been reloaded");
                System.exit(0);
            } catch (Throwable th) {
                th.printStackTrace();
                System.err.println("ERROR: Reloading policies failed; see above");
                System.exit(1);
            }
        } else {
            System.err.println("ERROR: Three arguments required: " + "http|https username password");
            System.exit(1);
        }

    } else if (method.equals("migratedatastreamcontrolgroup")) {

        // too many args
        if (args.length > 10) {
            System.err.println("ERROR: too many arguments provided");
            System.exit(1);
        }

        // too few
        if (args.length < 7) {

            System.err.println("ERROR: insufficient arguments provided.  Arguments are: ");
            System.err.println("    protocol [http|https]"); // 1; 0 is method
            System.err.println("    user"); // 2
            System.err.println("    password"); // 3
            System.err.println("    pid - either"); // 4
            System.err.println("        a single pid, eg demo:object");
            System.err.println("        list of pids separated by commas, eg demo:object1,demo:object2");
            System.err.println("        name of file containing pids, eg file:///path/to/file");
            System.err.println("    dsid - either"); // 5
            System.err.println("        a single datastream id, eg DC");
            System.err.println("        list of ids separated by commas, eg DC,RELS-EXT");
            System.err.println("    controlGroup - target control group (note only M is implemented)"); // 6
            System.err.println(
                    "    addXMLHeader - add an XML header to the datastream [true|false, default false]"); // 7
            System.err.println("    reformat - reformat the XML [true|false, default false]"); // 8
            System.err.println(
                    "    setMIMETypeCharset - add charset=UTF-8 to the MIMEType [true|false, default false]"); // 9
            System.exit(1);
        }

        try {
            // optional args
            boolean addXMLHeader = getArgBoolean(args, 7, false);
            boolean reformat = getArgBoolean(args, 8, false);
            boolean setMIMETypeCharset = getArgBoolean(args, 9, false);
            ;

            InputStream is = modifyDatastreamControlGroup(args[1], args[2], args[3], args[4], args[5], args[6],
                    addXMLHeader, reformat, setMIMETypeCharset);

            IOUtils.copy(is, System.out);
            is.close();

            System.out.println("SUCCESS: Datastreams modified");
            System.exit(0);

        } catch (Throwable th) {
            th.printStackTrace();
            System.err.println("ERROR: migrating datastream control group failed; see above");
            System.exit(1);
        }

    } else {
        System.err.println("ERROR: unrecognised method " + method);
        System.exit(1);
    }
}

From source file:com.leixl.easyframework.action.httpclient.TestHttpPost.java

public static void main(String[] args) {

    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("uid", 1);
    paramMap.put("desc",
            "?????");
    paramMap.put("payStatus", 1);

    //HttpConnUtils.postHttpContent(URL, paramMap);

    //HttpClient/*from www. j  a  va  2s.c  o  m*/
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(URL);
    // ??
    NameValuePair[] data = { new NameValuePair("uid", "1"),
            new NameValuePair("desc",
                    "?????"),
            new NameValuePair("payStatus", "1") };
    // ?postMethod
    postMethod.setRequestBody(data);
    // postMethod
    int statusCode;
    try {
        statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK) {
            StringBuffer contentBuffer = new StringBuffer();
            InputStream in = postMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in, postMethod.getResponseCharSet()));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                contentBuffer.append(inputLine);
                System.out.println("input line:" + inputLine);
                contentBuffer.append("/n");
            }
            in.close();

        } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // ???
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                System.out.println("The page was redirected to:" + location);
            } else {
                System.err.println("Location field value is null.");
            }
        }
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:net.securnetwork.itebooks.downloader.EbookDownloader.java

/**
 * Program main method./*from   w  ww.  j  a v a 2  s.c  o  m*/
 * 
 * @param args the program arguments
 */
public static void main(String[] args) {
    if (validateArguments(args)) {
        int start = MIN_EBOOK_INDEX;
        int end = getLastEbookIndex();
        String destinationFolder = null;
        // Check if resume mode
        if (args.length == 1 && args[0].equals(RESUME_ARG)) {
            start = Integer.parseInt(prefs.get(LAST_SAVED_EBOOK_PREF, MIN_EBOOK_INDEX - 1 + "")) + 1; //$NON-NLS-1$
            destinationFolder = prefs.get(OUTPUT_FOLDER_PREF, null);
        } else {
            destinationFolder = getDestinationFolder(args);
        }

        if (destinationFolder == null) {
            System.err.println(Messages.getString("EbookDownloader.NoDestinationFolderFound")); //$NON-NLS-1$
            return;
        } else {
            // Possibly fix the destination folder path
            destinationFolder = destinationFolder.replace("\\", "/");
            if (!destinationFolder.endsWith("/")) {
                destinationFolder += "/";
            }
            prefs.put(OUTPUT_FOLDER_PREF, destinationFolder);
        }

        if (args.length == 3) {
            start = getStartIndex(args);
            end = getEndIndex(args);
        }
        try {
            for (int i = start; i <= end; i++) {
                String ebookPage = BASE_EBOOK_URL + i + SLASH;
                Source sourceHTML = new Source(new URL(ebookPage));
                List<Element> allTables = sourceHTML.getAllElements(HTMLElementName.TABLE);
                Element detailsTable = allTables.get(0);
                // Try to build an info bean for the ebook
                String bookTitle = EbookPageParseUtils.getTitle(detailsTable);
                if (bookTitle != null) {
                    EbookInfo ebook = createEbookInfo(bookTitle, i, detailsTable);
                    String filename = destinationFolder + Misc.getValidFilename(ebook.getTitle(),
                            ebook.getSubTitle(), ebook.getYear(), ebook.getFileFormat());
                    System.out.print(MessageFormat.format(Messages.getString("EbookDownloader.InfoDownloading"), //$NON-NLS-1$
                            new Object[] { ebook.getSiteId() }));
                    try {
                        URL ebookPageURL = new URL(ebook.getDownloadLink());
                        HttpURLConnection con = (HttpURLConnection) ebookPageURL.openConnection();
                        con.setRequestMethod("GET");
                        con.setRequestProperty("Referer", ebookPage);
                        InputStream conIS = con.getInputStream();
                        FileUtils.copyInputStreamToFile(conIS, new File(filename));
                        System.out.println(Messages.getString("EbookDownloader.DownloadingOK")); //$NON-NLS-1$
                        prefs.put(LAST_SAVED_EBOOK_PREF, i + ""); //$NON-NLS-1$
                        conIS.close();
                    } catch (Exception e) {
                        System.out.println(Messages.getString("EbookDownloader.DownloadingKO")); //$NON-NLS-1$
                    }
                }
            }

        } catch (Exception e) {
            System.err.println(Messages.getString("EbookDownloader.FatalError")); //$NON-NLS-1$
            e.printStackTrace();
        }
    } else {
        printHelp();
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    OutputStream fos = new BufferedOutputStream(new FileOutputStream("filename.ps"));

    DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
    InputStream is = new BufferedInputStream(new FileInputStream("filename.gif"));
    StreamPrintServiceFactory[] factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,
            DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());

    StreamPrintService service = factories[0].getPrintService(fos);
    DocPrintJob job = service.createPrintJob();
    Doc doc = new SimpleDoc(is, flavor, null);

    PrintJobWatcher pjDone = new PrintJobWatcher(job);

    job.print(doc, null);//w ww.  j a  v  a 2s .c o m

    pjDone.waitForDone();

    is.close();
}

From source file:com.openx.oauthdemo.Demo.java

/** 
 * Main class. OX3 with OAuth demo/*from  www. j a  v  a  2s . com*/
 * @param args 
 */
public static void main(String[] args) {
    String apiKey, apiSecret, loginUrl, username, password, domain, path, requestTokenUrl, accessTokenUrl,
            realm, authorizeUrl;
    String propertiesFile = "default.properties";

    // load params from the properties file
    Properties defaultProps = new Properties();
    InputStream in = null;
    try {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        in = cl.getResourceAsStream(propertiesFile);
        if (in != null) {
            defaultProps.load(in);
        }
    } catch (IOException ex) {
        System.out.println("The properties file was not found!");
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                System.out.println("IO Error closing the properties file");
                return;
            }
        }
    }

    if (defaultProps.isEmpty()) {
        System.out.println("The properties file was not loaded!");
        return;
    }

    apiKey = defaultProps.getProperty("apiKey");
    apiSecret = defaultProps.getProperty("apiSecret");
    loginUrl = defaultProps.getProperty("loginUrl");
    username = defaultProps.getProperty("username");
    password = defaultProps.getProperty("password");
    domain = defaultProps.getProperty("domain");
    path = defaultProps.getProperty("path");
    requestTokenUrl = defaultProps.getProperty("requestTokenUrl");
    accessTokenUrl = defaultProps.getProperty("accessTokenUrl");
    realm = defaultProps.getProperty("realm");
    authorizeUrl = defaultProps.getProperty("authorizeUrl");

    // log in to the server
    Client cl = new Client(apiKey, apiSecret, loginUrl, username, password, domain, path, requestTokenUrl,
            accessTokenUrl, realm, authorizeUrl);
    try {
        // connect to the server
        cl.OX3OAuth();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "UTF-8 support needed for OAuth", ex);
    } catch (IOException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "IO file reading error", ex);
    } catch (Exception ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "API issue", ex);
    }

    // now lets make a call to the api to check 
    String json;
    try {
        json = cl.getHelper().callOX3Api(domain, path, "account");
    } catch (IOException ex) {
        System.out.println("There was an error calling the API");
        return;
    }

    System.out.println("JSON response: " + json);

    Gson gson = new Gson();
    int[] accounts = gson.fromJson(json, int[].class);

    if (accounts.length > 0) {
        // let's get a single account
        try {
            json = cl.getHelper().callOX3Api(domain, path, "account", accounts[0]);
        } catch (IOException ex) {
            System.out.println("There was an error calling the API");
            return;
        }

        System.out.println("JSON response: " + json);

        OX3Account account = gson.fromJson(json, OX3Account.class);

        System.out.println("Account id: " + account.getId() + " name: " + account.getName());
    }
}

From source file:com.lxf.spider.client.ClientConnectionRelease.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from  w w w .ja v  a  2 s  .  c  o  m
        HttpGet httpget = new HttpGet("http://localhost/");

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            // to bother about connection release
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                    // do something useful with the response
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.zhch.example.commons.http.v4_5.ClientConnectionRelease.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*w  w w.  j  a v  a 2  s  . c om*/
        HttpGet httpget = new HttpGet("http://httpbin.org/get");

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            // to bother about connection release
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                    // do something useful with the response
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.http.ClientConnectionRelease.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   ww  w  .  j  ava 2s .c o m*/
        HttpGet httpget = new HttpGet("http://www.apache.org/");

        // Execute HTTP request
        System.out.println("executing request " + httpget.getURI());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            // to bother about connection release
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                    // do something useful with the response
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.tsavo.trade.TradeBot.java

public static void main(String[] args)
        throws InterruptedException, EngineException, AudioException, EngineStateError, PropertyVetoException,
        KeyManagementException, NoSuchAlgorithmException, ExchangeException, NotAvailableFromExchangeException,
        NotYetImplementedForExchangeException, IOException {
    //initSSL(); // Setup the SSL certificate to interact with mtgox over
    // secure http.

    //System.setProperty("org.joda.money.CurrencyUnitDataProvider", "org.joda.money.CryptsyCurrencyUnitDataProvider");
    Portfolio portfolio = new Portfolio();
    File dest = new File("portfolio.json");
    if (dest.exists()) {
        InputStream file;
        try {/*  w  w w  .j a va 2 s . c  om*/
            file = new FileInputStream(dest);
            InputStream buffer = new BufferedInputStream(file);
            // ObjectInput input;
            // input = new ObjectInputStream(buffer);
            ObjectMapper mapper = new ObjectMapper();
            portfolio = mapper.readValue(buffer, Portfolio.class);
            file.close();
            // input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Finder finder = new Finder(portfolio);
    System.out.println("System initialized successfully. Looking for opportunities...");
    while (true) {
        finder.run();
        Thread.sleep(10000);
    }
}