Example usage for java.io InputStreamReader close

List of usage examples for java.io InputStreamReader close

Introduction

In this page you can find the example usage for java.io InputStreamReader close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:org.apache.roller.weblogger.config.WebloggerRuntimeConfig.java

/**
 * Get the runtime configuration definitions XML file as a string.
 *
 * This is basically a convenience method for accessing this file.
 * The file itself contains meta-data about what configuration
 * properties we change at runtime via the UI and how to setup
 * the display for editing those properties.
 *///from ww w  .ja va2s .c  o m
public static String getRuntimeConfigDefsAsString() {

    log.debug("Trying to load runtime config defs file");

    try {
        InputStreamReader reader = new InputStreamReader(
                WebloggerConfig.class.getResourceAsStream(runtime_config));
        StringWriter configString = new StringWriter();

        char[] buf = new char[8196];
        int length = 0;
        while ((length = reader.read(buf)) > 0)
            configString.write(buf, 0, length);

        reader.close();

        return configString.toString();
    } catch (Exception e) {
        log.error("Error loading runtime config defs file", e);
    }

    return "";
}

From source file:eu.eexcess.ddb.recommender.PartnerConnector.java

/**
 * Opens a HTTP connection, gets the response and converts into to a String.
 * //from   w w w .j  a  v  a  2s .  c  o m
 * @param urlStr Servers URL
 * @param properties Keys and values for HTTP request properties
 * @return Servers response
 * @throws IOException  If connection could not be established or response code is !=200
 */
public static String httpGet(String urlStr, HashMap<String, String> properties) throws IOException {
    if (properties == null) {
        properties = new HashMap<String, String>();
    }
    // open HTTP connection with URL
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // set properties if any do exist
    for (String key : properties.keySet()) {
        conn.setRequestProperty(key, properties.get(key));
    }
    // test if request was successful (status 200)
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }
    // buffer the result into a string
    InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
    isr.close();
    conn.disconnect();
    return sb.toString();
}

From source file:com.csipsimple.backup.SipProfileJson.java

/**
 * Restore a sip configuration/*from ww w . ja  va2  s .  c o m*/
 * 
 * @param ctxt
 * @param fileToRestore
 * @return
 */
public static boolean restoreSipConfiguration(Context ctxt, File fileToRestore, String filePassword) {
    if (fileToRestore == null || !fileToRestore.isFile()) {
        return false;
    }

    StringBuffer contentBuf = new StringBuffer();

    try {
        BufferedReader buf;
        String line;
        InputStream is = new FileInputStream(fileToRestore);
        if (!TextUtils.isEmpty(filePassword)) {
            Cipher c;
            try {
                c = Cipher.getInstance("AES");
                SecretKeySpec k = new SecretKeySpec(filePassword.getBytes(), "AES");
                c.init(Cipher.ENCRYPT_MODE, k);
                is = new CipherInputStream(is, c);
            } catch (NoSuchAlgorithmException e) {
                Log.e(THIS_FILE, "NoSuchAlgorithmException :: ", e);
            } catch (NoSuchPaddingException e) {
                Log.e(THIS_FILE, "NoSuchPaddingException :: ", e);
            } catch (InvalidKeyException e) {
                Log.e(THIS_FILE, "InvalidKeyException :: ", e);
            }
        }

        InputStreamReader fr = new InputStreamReader(is);
        buf = new BufferedReader(fr);
        while ((line = buf.readLine()) != null) {
            contentBuf.append(line);
        }
        fr.close();
    } catch (FileNotFoundException e) {
        Log.e(THIS_FILE, "Error while restoring", e);
    } catch (IOException e) {
        Log.e(THIS_FILE, "Error while restoring", e);
    }

    JSONArray accounts = null;
    JSONObject settings = null;
    // Parse json if some string here
    if (contentBuf.length() > 0) {
        try {
            JSONObject mainJSONObject = new JSONObject(contentBuf.toString());
            // Retrieve accounts
            accounts = mainJSONObject.getJSONArray(KEY_ACCOUNTS);
            // Retrieve settings
            settings = mainJSONObject.getJSONObject(KEY_SETTINGS);

        } catch (JSONException e) {
            Log.e(THIS_FILE, "Error while parsing saved file", e);
        }
    } else {
        return false;
    }

    if (accounts != null && accounts.length() > 0) {
        restoreSipAccounts(ctxt, accounts);
    }

    if (settings != null) {
        restoreSipSettings(ctxt, settings);
        return true;
    }

    return false;
}

From source file:org.apache.ranger.plugin.store.TestTagStore.java

@BeforeClass
public static void setupTest() throws Exception {

    String textTemplate = "<configuration>\n" + "        <property>\n"
            + "                <name>ranger.tag.store.file.dir</name>\n" + "                <value>%s</value>\n"
            + "        </property>\n" + "        <property>\n"
            + "                <name>ranger.service.store.file.dir</name>\n"
            + "                <value>%s</value>\n" + "        </property>\n" + "</configuration>\n";

    File file = File.createTempFile("ranger-admin-test-site", ".xml");
    file.deleteOnExit();/*  ww  w .  j  a  v a2 s .c  o  m*/

    tagStoreDir = File.createTempFile("tagStore", "dir");

    if (tagStoreDir.exists()) {
        tagStoreDir.delete();
    }

    tagStoreDir.mkdirs();

    String tagStoreDirName = tagStoreDir.getAbsolutePath();

    String text = String.format(textTemplate, tagStoreDirName, tagStoreDirName);

    FileOutputStream outStream = new FileOutputStream(file);
    OutputStreamWriter writer = new OutputStreamWriter(outStream);
    writer.write(text);
    writer.close();

    RangerConfiguration config = RangerConfiguration.getInstance();
    config.addResource(new org.apache.hadoop.fs.Path(file.toURI()));

    ServiceStore svcStore = new ServiceFileStore();
    svcStore.init();

    tagStore = TagFileStore.getInstance();
    tagStore.init();
    tagStore.setServiceStore(svcStore);

    validator = new TagValidator();
    validator.setTagStore(tagStore);

    gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").setPrettyPrinting().create();

    InputStream inStream = TestTagStore.class.getResourceAsStream(serviceDefJsonFile);
    InputStreamReader reader = new InputStreamReader(inStream);

    serviceDef = gsonBuilder.fromJson(reader, RangerServiceDef.class);

    service = svcStore
            .createService(new RangerService(serviceDef.getName(), serviceName, serviceName, null, null));

    reader.close();
    inStream.close();

}

From source file:io.github.infolis.algorithm.Indexer.java

/**
 * Files a lucene document. Documents are created as follows:
 * <ol>/*from  w  ww.java  2  s  . co  m*/
 * <li>The path of the file is added as a field named "path". The field is
 * indexed (i.e. searchable), but not tokenized into words.</li>
 * <li>The last modified date of the file is added as a field named
 * "modified". The field is indexed (i.e. searchable), not tokenized into
 * words.</li>
 * <li>The contents of the file are added to a field named "contents". A
 * reader is specified so that the text of the file is tokenized and
 * indexed, but not stored. Note that FileReader expects the file to be in
 * the system's default encoding. If that's not the case searching for
 * special characters will fail.</li>
 * <li>Content (text files) is saved in the index along with position and
 * offset information.</li>
 * </ol>
 *
 * @param f   a txt-file to be included in the lucene index
 * @return a   lucene document
 * @throws IOException
 */
public static Document toLuceneDocument(FileResolver fileResolver, InfolisFile f) throws IOException {
    //use code below to process pdfs instead of text (requires pdfBox)
    /*FileInputStream fi = new FileInputStream(new File(f.getPath()));
        PDFParser parser = new PDFParser(fi);
        parser.parse();
        COSDocument cd = parser.getDocument();
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(new PDDocument(cd));  */
    InputStreamReader isr = new InputStreamReader(fileResolver.openInputStream(f), "UTF8");
    BufferedReader reader = new BufferedReader(isr);
    StringBuffer contents = new StringBuffer();
    String text = null;
    while ((text = reader.readLine()) != null) {
        contents.append(text).append(System.getProperty("line.separator"));
    }
    reader.close();
    isr.close();
    text = new String(contents);

    // make a new, empty document
    Document doc = new Document();

    // Add the path of the file as a field named "path".  Use a field that is
    // indexed (i.e. searchable), but don't tokenize the field into words.
    doc.add(new Field("path", f.getUri(), Field.Store.YES, Field.Index.NOT_ANALYZED));
    doc.add(new Field("fileName", f.getFileName(), Field.Store.YES, Field.Index.ANALYZED));

    // Add the last modified date of the file a field named "modified".  Use
    // a field that is indexed (i.e. searchable), but don't tokenize the field
    // into words.
    // TODO kba: Add modified to InfolisFile
    //      doc.add( new Field( "modified",
    //            DateTools.timeToString( f.lastModified(), DateTools.Resolution.MINUTE ),
    //            Field.Store.YES, Field.Index.NOT_ANALYZED ) );
    // save the content (text files) in the index
    // Add the contents of the file to a field named "contents".  Specify a Reader,
    // so that the text of the file is tokenized and indexed, but not stored.
    // Note that FileReader expects the file to be in the system's default encoding.
    // If that's not the case searching for special characters will fail.
    //Store both position and offset information
    // TextFilesContent = readTextFiles(f.getPath()) + " ";
    doc.add(new Field("contents", text, Field.Store.YES, Field.Index.ANALYZED,
            Field.TermVector.WITH_POSITIONS_OFFSETS));

    // return the document
    //cd.close();
    return doc;
}

From source file:org.jboss.additional.testsuite.jdkall.present.domain.management.cli.DomainDeploymentOverlayTestCase.java

public static String getContent(HttpResponse response) throws IOException {
    InputStreamReader reader = new InputStreamReader(response.getEntity().getContent());
    StringBuilder content = new StringBuilder();
    int c;//  w  w w .j  av  a  2  s. c o m
    while (-1 != (c = reader.read())) {
        content.append((char) c);
    }
    reader.close();
    return content.toString();
}

From source file:org.apache.zeppelin.notebook.NotebookAuthorization.java

private static void loadFromFile() throws IOException {
    File settingFile = new File(filePath);
    LOG.info(settingFile.getAbsolutePath());
    if (!settingFile.exists()) {
        // nothing to read
        return;/*from www  . j a  v a  2 s  .  c  om*/
    }
    FileInputStream fis = new FileInputStream(settingFile);
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader bufferedReader = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        sb.append(line);
    }
    isr.close();
    fis.close();

    String json = sb.toString();
    NotebookAuthorizationInfoSaving info = gson.fromJson(json, NotebookAuthorizationInfoSaving.class);
    authInfo = info.authInfo;
}

From source file:net.dries007.coremod.Coremod.java

private static void getJSON() {
    try {//from w w w .  j  av  a 2 s  .c  o  m
        InputStreamReader isr = new InputStreamReader(new URL(Data.get(Data.JSONNURL)).openStream());
        root = Coremod.JSON_PARSER.parse(isr).getNode(Data.get(Data.NAME));
        Coremod.online = true;
        isr.close();
    } catch (final IOException e) {
        msg("JSON offline? Check manually: " + Data.get(Data.JSONNURL),
                "###################################################",
                "##### WARNING: The update URL is unavailable. #####",
                "#####     Only classloading will be done!     #####",
                "###################################################");
    } catch (final InvalidSyntaxException e) {
        msg("Invalid JSON at target? Check manually: " + Data.get(Data.JSONNURL),
                "###############################################",
                "##### WARNING: The update URL is corrupt. #####",
                "#####   Only classloading will be done!   #####",
                "###############################################");
    }

    if (!online && Boolean.parseBoolean(Data.get(Data.FORCEONLINE))) {
        msg("################################################",
                "##### The update server must be available. #####",
                "################################################");
        System.exit(1);
    }
}

From source file:org.jetbrains.webdemo.ResponseUtils.java

public static String readData(InputStream is, boolean addNewLine) throws IOException {
    InputStreamReader reader = new InputStreamReader(is);
    StringBuilder response = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(reader);

    String tmp;/* ww w.j  av  a 2  s .c o m*/
    while ((tmp = bufferedReader.readLine()) != null) {
        response.append(tmp);
        if (addNewLine) {
            response.append("\n");
        }
    }
    reader.close();
    return response.toString();
}

From source file:org.apache.webdav.ant.taskdefs.Get.java

protected static void copyStream(InputStream in, OutputStream out, FilterSetCollection filterSets,
        String encoding) throws IOException {
    byte[] b = new byte[1024];
    if (filterSets.hasFilters()) {
        InputStreamReader reader = new InputStreamReader(in, encoding);
        OutputStreamWriter writer = new OutputStreamWriter(out, encoding);

        LineTokenizer tok = new LineTokenizer();
        tok.setIncludeDelims(true);//from   w w  w .  jav  a 2 s . c  om

        for (String l = tok.getToken(reader); l != null; l = tok.getToken(reader)) {
            writer.write(filterSets.replaceTokens(l));
        }
        writer.close();
        reader.close();
    } else {
        while (in.available() > 0) {
            int cnt = in.read(b, 0, b.length);
            if (cnt > -1) {
                out.write(b, 0, cnt);
            }
        }
    }
}