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:magoffin.matt.sobriquet.sendmail.test.SendmailAliasLDIFGeneratorTests.java

@Test
public void generateSamples() throws IOException {
    ClassPathResource r = new ClassPathResource("aliases.txt", getClass());
    InputStreamReader in = null;
    ByteArrayOutputStream byos = new ByteArrayOutputStream();
    try {/*  w  w w .j a va 2  s. c om*/
        in = new InputStreamReader(r.getInputStream());
        SendmailAliasFileParser parser = new SendmailAliasFileParser(in);
        SendmailAliasLDIFGenerator gen = new SendmailAliasLDIFGenerator("ou=Test", "aliases", "example.com");
        gen.generate(parser, byos);
        String generated = new String(byos.toByteArray(), "US-ASCII");
        log.debug("Generated LDIF:\n{}", generated);
        String expected = FileCopyUtils
                .copyToString(new FileReader(new ClassPathResource("aliases.ldif", getClass()).getFile()));
        Assert.assertEquals("Generated LDIF", expected, generated);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.bankinterface.config.JsonBankConfig.java

/**
 * ??/*from  ww w  .j av  a 2 s.  c  om*/
 * 
 * @param configName
 * @return
 * @throws IOException
 */
private String getContent(String configName) throws IOException {
    InputStreamReader in = null;
    String content = null;
    try {
        in = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(configName), "UTF-8");
        StringWriter out = new StringWriter();
        int n = 0;
        char[] buffer = new char[4096];
        while (-1 != (n = in.read(buffer))) {
            out.write(buffer, 0, n);
        }
        content = out.toString();
    } finally {
        if (in != null) {
            in.close();
        }
    }
    return content;
}

From source file:org.apache.zeppelin.interpreter.InterpreterFactory.java

private void loadFromFile() throws IOException {
    GsonBuilder builder = new GsonBuilder();
    builder.setPrettyPrinting();//from  ww  w  . j  a  v  a  2 s .  c om
    builder.registerTypeAdapter(Interpreter.class, new InterpreterSerializer());
    Gson gson = builder.create();

    File settingFile = new File(conf.getInterpreterSettingPath());
    if (!settingFile.exists()) {
        // nothing to read
        return;
    }
    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();
    InterpreterInfoSaving info = gson.fromJson(json, InterpreterInfoSaving.class);

    for (String k : info.interpreterSettings.keySet()) {
        InterpreterSetting setting = info.interpreterSettings.get(k);

        // Always use separate interpreter process
        // While we decided to turn this feature on always (without providing
        // enable/disable option on GUI).
        // previously created setting should turn this feature on here.
        setting.getOption().setRemote(true);

        InterpreterSetting intpSetting = new InterpreterSetting(setting.id(), setting.getName(),
                setting.getGroup(), setting.getOption());

        InterpreterGroup interpreterGroup = createInterpreterGroup(setting.id(), setting.getGroup(),
                setting.getOption(), setting.getProperties());
        intpSetting.setInterpreterGroup(interpreterGroup);

        interpreterSettings.put(k, intpSetting);
    }

    this.interpreterBindings = info.interpreterBindings;
}

From source file:de.teamgrit.grit.checking.compile.GccCompileChecker.java

@Override
public CompilerOutput checkProgram(Path pathToProgramFile, Path outputFolder, String compilerName,
        List<String> compilerFlags)
        throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException {

    // First we build the command to invoke the compiler. This consists of
    // the compiler executable, the path of the
    // file to compile and compiler flags. So for example we call:
    List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName, compilerFlags);
    // Now we build a launchable process from the given parameters and set
    // the working directory.
    Process compilerProcess = null;

    try {/*from www  .j av  a2  s. c o  m*/
        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);
        // make sure the compiler stays in its directory.
        if (Files.isDirectory(pathToProgramFile)) {
            compilerProcessBuilder.directory(pathToProgramFile.toFile());
        } else {
            compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile());
        }
        compilerProcess = compilerProcessBuilder.start();
    } catch (IOException e) {
        // If we cannot call the compiler we return a CompilerOutput
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        LOGGER.severe("Couldn't launch GCC. Check whether it's in the system's PATH");
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok gcc reports
    // nothing at all.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();
    } catch (IOException e) {
        // Reading might go wrong here if gcc should unexpectedly terminate
        LOGGER.severe("Error while reading from compiler stream.");
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    if (compilerOutputLines.size() == 0) {
        compilerOutput.setClean(true);
    }

    compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput);

    // delete all .o and .exe files
    // these are output files generated by gcc which we won't need
    // anymore
    File[] candidateToplevelFiles = pathToProgramFile.toFile().listFiles();
    for (File candidateFile : candidateToplevelFiles) {
        if (!candidateFile.isDirectory()) {
            String extension = FilenameUtils.getExtension(candidateFile.toString());
            if (extension.matches("([Oo]|([Ee][Xx][Ee]))")) {
                // We only pass the filename, since gcc will be
                // confined to the dir the file is located in.
                candidateFile.delete();
            }
        }

    }

    return compilerOutput;
}

From source file:azkaban.jobtype.HadoopSparkJob.java

/**
 * Add additional namenodes specified in the Spark Configuration
 * ({@link #SPARK_CONF_ADDITIONAL_NAMENODES}) to the Props provided.
 * @param props Props to add additional namenodes to.
 * @see HadoopJobUtils#addAdditionalNamenodesToProps(Props, String)
 *///from w w w  .jav a2 s .c o m
void addAdditionalNamenodesFromConf(final Props props) {
    final String sparkConfDir = getSparkLibConf()[1];
    final File sparkConfFile = new File(sparkConfDir, "spark-defaults.conf");
    try {
        final InputStreamReader inReader = new InputStreamReader(new FileInputStream(sparkConfFile),
                StandardCharsets.UTF_8);
        // Use Properties to avoid needing Spark on our classpath
        final Properties sparkProps = new Properties();
        sparkProps.load(inReader);
        inReader.close();
        final String additionalNamenodes = sparkProps.getProperty(SPARK_CONF_ADDITIONAL_NAMENODES);
        if (additionalNamenodes != null && additionalNamenodes.length() > 0) {
            getLog().info("Found property " + SPARK_CONF_ADDITIONAL_NAMENODES + " = " + additionalNamenodes
                    + "; setting additional namenodes");
            HadoopJobUtils.addAdditionalNamenodesToProps(props, additionalNamenodes);
        }
    } catch (final IOException e) {
        getLog().warn("Unable to load Spark configuration; not adding any additional "
                + "namenode delegation tokens.", e);
    }
}

From source file:cn.edu.henu.rjxy.lms.controller.Tea_Controller.java

@RequestMapping("scTree")
public @ResponseBody String scTree(HttpServletRequest request) throws FileNotFoundException, IOException {
    String sn = getCurrentUsername();
    Teacher tec = TeacherDao.getTeacherBySn(sn);
    String tec_sn = tec.getTeacherSn();
    String tec_name = tec.getTeacherName();
    String collage = tec.getTeacherCollege();
    String term = request.getParameter("term");
    String courseName = request.getParameter("courseName");
    String ff = getFileFolder(request) + term + "/" + collage + "/" + tec_sn + "/" + tec_name + "/" + courseName
            + "/" + "" + "/" + "test.json";
    String fileContent = "";
    try {//from w  w w  .ja va2s . c  o m
        File f = new File(ff);
        if (f.isFile() && f.exists()) {
            InputStreamReader read = new InputStreamReader(new FileInputStream(f), "gbk");
            BufferedReader reader = new BufferedReader(read);
            String line;
            while ((line = reader.readLine()) != null) {
                fileContent += line;
            }
            read.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(fileContent);
    return fileContent;
}

From source file:com.sds.acube.ndisc.mts.xserver.util.XNDiscUtils.java

/**
 * XNDisc ? ?/*from   w w w . j av  a2s.c  o m*/
 */
private static void readVersionFromFile() {
    XNDisc_PublishingVersion = "<unknown>";
    XNDisc_PublishingDate = "<unknown>";
    InputStreamReader isr = null;
    LineNumberReader lnr = null;
    try {
        isr = new InputStreamReader(
                XNDiscUtils.class.getResourceAsStream("/com/sds/acube/ndisc/mts/xserver/version.txt"));
        if (isr != null) {
            lnr = new LineNumberReader(isr);
            String line = null;
            do {
                line = lnr.readLine();
                if (line != null) {
                    if (line.startsWith("Publishing-Version=")) {
                        XNDisc_PublishingVersion = line.substring("Publishing-Version=".length(), line.length())
                                .trim();
                    } else if (line.startsWith("Publishing-Date=")) {
                        XNDisc_PublishingDate = line.substring("Publishing-Date=".length(), line.length())
                                .trim();
                    }
                }
            } while (line != null);
            lnr.close();
        }
    } catch (IOException ioe) {
        XNDisc_PublishingVersion = "<unknown>";
        XNDisc_PublishingDate = "<unknown>";
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
            if (isr != null) {
                isr.close();
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:com.fujitsu.dc.test.jersey.DcResponse.java

/**
 * ???.//from  w w w  .j a  va2  s  .c o  m
 * @param enc 
 * @return 
 * @throws DaoException DAO
 */
public final String bodyAsString(final String enc) throws DaoException {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader reader = null;
    try {
        is = this.getResponseBodyInputStream(response);
        isr = new InputStreamReader(is, enc);
        reader = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        int chr;
        while ((chr = reader.read()) != -1) {
            sb.append((char) chr);
        }
        return sb.toString();
    } catch (IOException e) {
        throw DaoException.create("io exception", 0);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            throw DaoException.create("io exception", 0);
        } finally {
            try {
                if (isr != null) {
                    isr.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e2) {
                throw DaoException.create("io exception", 0);
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (Exception e3) {
                    throw DaoException.create("io exception", 0);
                }
            }
        }
    }
}

From source file:cn.dreampie.CoffeeCompiler.java

private String readSourceFrom(InputStream inputStream) {
    final InputStreamReader streamReader = new InputStreamReader(inputStream);
    try {/* w w  w.ja v a 2 s.  c  om*/
        try {
            StringBuilder builder = new StringBuilder(BUFFER_SIZE);
            char[] buffer = new char[BUFFER_SIZE];
            int numCharsRead = streamReader.read(buffer, BUFFER_OFFSET, BUFFER_SIZE);
            while (numCharsRead >= 0) {
                builder.append(buffer, BUFFER_OFFSET, numCharsRead);
                numCharsRead = streamReader.read(buffer, BUFFER_OFFSET, BUFFER_SIZE);
            }
            return builder.toString();
        } finally {
            streamReader.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.esri.gpt.server.csw.client.CswClient.java

/**
 * Fully reads the characters from an input stream.
 * @param stream the input stream/*ww w.java  2s  . com*/
 * @param charset the encoding of the input stream
 * @return the characters read
 * @throws IOException if an exception occurs
 */
private String readCharacters(InputStream stream, String charset) throws IOException {
    StringBuffer sb = new StringBuffer();
    BufferedReader br = null;
    InputStreamReader ir = null;
    try {
        if ((charset == null) || (charset.trim().length() == 0))
            charset = "UTF-8";
        char cbuf[] = new char[4096];
        int n = 0;
        int nLen = cbuf.length;
        ir = new InputStreamReader(stream, charset);
        br = new BufferedReader(ir);
        while ((n = br.read(cbuf, 0, nLen)) >= 0)
            sb.append(cbuf, 0, n);
    } finally {
        try {
            if (br != null)
                br.close();
        } catch (Exception ef) {
        }
        try {
            if (ir != null)
                ir.close();
        } catch (Exception ef) {
        }
    }
    return sb.toString();
}