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:com.controller.CuotasController.java

@RequestMapping("cuotasAdmin.htm")
public ModelAndView getCuotasAdmin(HttpServletRequest request) {
    sesion = request.getSession();/*from  w w w  .j a va 2s . c  om*/
    ModelAndView mav = new ModelAndView();
    String mensaje = null;
    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");

    String country = detalle.getCiudad();
    String amount = "5";
    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;
}

From source file:com.controller.CuotasController.java

@RequestMapping(value = "postCuotas.htm", method = RequestMethod.POST)
public ModelAndView postCuotas(HttpServletRequest request) {

    sesion = request.getSession();//from  w  ww  .java2  s.c o  m
    String country = request.getParameter("country");
    String amount = request.getParameter("amount");

    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
    System.out.print(detalle.getCiudad());

    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    ModelAndView mav = new ModelAndView();
    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;

}

From source file:org.apache.jasper.compiler.JspReader.java

/**
 * Push a file (and its associated Stream) on the file stack.  THe
 * current position in the current file is remembered.
 *///from  w ww  . j a va 2s.com
private void pushFile(String file, String encoding, InputStreamReader reader)
        throws JasperException, FileNotFoundException {

    // Register the file
    String longName = file;

    int fileid = registerSourceFile(longName);

    if (fileid == -1) {
        err.jspError("jsp.error.file.already.registered", file);
    }

    currFileId = fileid;

    try {
        CharArrayWriter caw = new CharArrayWriter();
        char buf[] = new char[1024];
        for (int i = 0; (i = reader.read(buf)) != -1;)
            caw.write(buf, 0, i);
        caw.close();
        if (current == null) {
            current = new Mark(this, caw.toCharArray(), fileid, getFile(fileid), master, encoding);
        } else {
            current.pushStream(caw.toCharArray(), fileid, getFile(fileid), longName, encoding);
        }
    } catch (Throwable ex) {
        log.error("Exception parsing file ", ex);
        // Pop state being constructed:
        popFile();
        err.jspError("jsp.error.file.cannot.read", file);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception any) {
            }
        }
    }
}

From source file:eu.musesproject.server.policyrulesselector.PolicySelector.java

private String getFullJSONDevicePolicy() {//TODO This is a sample policy selection, hence the selection of concrete policies based on decisions is yet to be done
    String jsonDevicePolicy = null;
    BufferedReader br = null;//  w  w  w.  j  av a 2 s.  c  o m
    InputStream in = null;
    InputStreamReader is = null;
    try {
        in = FileManager.get().open("devpolicies/muses-device-policy-prototype.xml");
        is = new InputStreamReader(in);
        StringBuilder sb = new StringBuilder();
        br = new BufferedReader(is);
        String read = br.readLine();

        while (read != null) {
            sb.append(read);
            read = br.readLine();
        }
        String fileContent = sb.toString();
        JSONObject xmlJSONObj = XML.toJSONObject(fileContent);
        jsonDevicePolicy = xmlJSONObj.toString();
    } catch (JSONException je) {
        logger.error("JSONException:" + je.getCause());
    } catch (IOException e) {
        logger.error("IOException:" + e.getCause());
    } finally {

        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
    }

    return jsonDevicePolicy;
}

From source file:org.activiti.dmn.xml.converter.DmnXMLConverter.java

public DmnDefinition convertToDmnModel(InputStreamProvider inputStreamProvider, boolean validateSchema,
        boolean enableSafeBpmnXml, String encoding) {
    XMLInputFactory xif = XMLInputFactory.newInstance();

    if (xif.isPropertySupported(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)) {
        xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    }//w  ww  .j  av a2s .co  m

    if (xif.isPropertySupported(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) {
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    }

    if (xif.isPropertySupported(XMLInputFactory.SUPPORT_DTD)) {
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    }

    InputStreamReader in = null;
    try {
        in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding);
        XMLStreamReader xtr = xif.createXMLStreamReader(in);

        try {
            if (validateSchema) {

                if (!enableSafeBpmnXml) {
                    validateModel(inputStreamProvider);
                } else {
                    validateModel(xtr);
                }

                // The input stream is closed after schema validation
                in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding);
                xtr = xif.createXMLStreamReader(in);
            }

        } catch (Exception e) {
            throw new DmnXMLException(e.getMessage(), e);
        }

        // XML conversion
        return convertToDmnModel(xtr);

    } catch (UnsupportedEncodingException e) {
        throw new DmnXMLException("The dmn xml is not UTF8 encoded", e);
    } catch (XMLStreamException e) {
        throw new DmnXMLException("Error while reading the BPMN 2.0 XML", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOGGER.debug("Problem closing DMN input stream", e);
            }
        }
    }
}

From source file:org.apache.hadoop.util.SysInfoLinux.java

/**
 * Read /proc/stat file, parse and calculate cumulative CPU.
 *//*ww  w .ja  v a  2s. c o m*/
private void readProcStatFile() {
    // Read "/proc/stat" file
    BufferedReader in;
    InputStreamReader fReader;
    try {
        fReader = new InputStreamReader(new FileInputStream(procfsStatFile), Charset.forName("UTF-8"));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // shouldn't happen....
        return;
    }

    Matcher mat;
    try {
        String str = in.readLine();
        while (str != null) {
            mat = CPU_TIME_FORMAT.matcher(str);
            if (mat.find()) {
                long uTime = Long.parseLong(mat.group(1));
                long nTime = Long.parseLong(mat.group(2));
                long sTime = Long.parseLong(mat.group(3));
                cpuTimeTracker.updateElapsedJiffies(BigInteger.valueOf(uTime + nTime + sTime),
                        getCurrentTime());
                break;
            }
            str = in.readLine();
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }
}

From source file:org.apache.hadoop.util.SysInfoLinux.java

/**
 * Read /proc/net/dev file, parse and calculate amount
 * of bytes read and written through the network.
 *///from  w  ww. j  a  va2s  .c  om
private void readProcNetInfoFile() {

    numNetBytesRead = 0L;
    numNetBytesWritten = 0L;

    // Read "/proc/net/dev" file
    BufferedReader in;
    InputStreamReader fReader;
    try {
        fReader = new InputStreamReader(new FileInputStream(procfsNetFile), Charset.forName("UTF-8"));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        return;
    }

    Matcher mat;
    try {
        String str = in.readLine();
        while (str != null) {
            mat = PROCFS_NETFILE_FORMAT.matcher(str);
            if (mat.find()) {
                assert mat.groupCount() >= 16;

                // ignore loopback interfaces
                if (mat.group(1).equals("lo")) {
                    str = in.readLine();
                    continue;
                }
                numNetBytesRead += Long.parseLong(mat.group(2));
                numNetBytesWritten += Long.parseLong(mat.group(10));
            }
            str = in.readLine();
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }
}

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

public String read(String ff) {
    String fileContent = "";
    try {//from   ww  w  .j  av a 2s  .co  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();
    }
    return fileContent;
}

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

@RequestMapping("teacher/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.  j a  v  a2 s  .  co  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;
}