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.bna.ezrxlookup.service.OpenFdaService.java

/**
 * Close input stream resource// www  .j a va  2s. co  m
 * @param isReader
 */
private void closeInputStream(InputStreamReader isReader) throws Exception {
    if (isReader != null) {
        try {
            isReader.close();
        } catch (IOException e) {
            LOG.error(e);
            throw e;
        }
        isReader = null;
    }
}

From source file:fr.ybonnel.simpleweb4j.MultipartIntegrationTest.java

@Before
public void startServer() {
    resetDefaultValues();/*from   w  w  w  . j av a2s.  c o m*/
    port = Integer.getInteger("test.http.port", random.nextInt(10000) + 10000);
    setPort(port);

    resource(new RestResource<TestUploadImage>("multipart", TestUploadImage.class) {
        @Override
        public TestUploadImage getById(String id) throws HttpErrorException {
            return null;
        }

        @Override
        public List<TestUploadImage> getAll() throws HttpErrorException {
            return Collections.emptyList();
        }

        @Override
        public void update(String id, TestUploadImage resource) throws HttpErrorException {
            resource.id = id;
            lastCall = resource;
        }

        @Override
        public TestUploadImage create(TestUploadImage resource) throws HttpErrorException {
            lastCall = resource;
            return resource;
        }

        @Override
        public Route<TestUploadImage, TestUploadImage> routeCreate() {
            return new Route<TestUploadImage, TestUploadImage>("multipart", TestUploadImage.class) {
                @Override
                public Response<TestUploadImage> handle(TestUploadImage param, RouteParameters routeParams)
                        throws HttpErrorException {
                    return new Response<>(create(param), HttpServletResponse.SC_CREATED);
                }

                @Override
                protected TestUploadImage getRouteParam(HttpServletRequest request) throws IOException {
                    try {
                        Part dataPart = request.getPart("data");
                        TestUploadImage data = ContentType.GSON
                                .fromJson(new InputStreamReader(dataPart.getInputStream()), getParamType());

                        Part imagePart = request.getPart("image");
                        if (null != imagePart) {
                            data.imageName = ((MultiPartInputStreamParser.MultiPart) imagePart)
                                    .getContentDispositionFilename();
                            data.image = IOUtils.toByteArray(imagePart.getInputStream());
                        }
                        return data;
                    } catch (ServletException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            };
        }

        @Override
        public Route<TestUploadImage, Void> routeUpdate() {
            return new Route<TestUploadImage, Void>("multipart/:id", TestUploadImage.class) {
                @Override
                public Response<Void> handle(TestUploadImage param, RouteParameters routeParams)
                        throws HttpErrorException {
                    update(routeParams.getParam("id"), param);
                    return new Response<>(null);
                }

                @Override
                protected TestUploadImage getRouteParam(HttpServletRequest request) throws IOException {
                    try {
                        Part dataPart = request.getPart("data");
                        InputStreamReader dataReader = new InputStreamReader(dataPart.getInputStream());
                        TestUploadImage data = ContentType.GSON.fromJson(dataReader, getParamType());
                        dataReader.close();

                        Part imagePart = request.getPart("image");
                        if (null != imagePart) {
                            data.imageName = ((MultiPartInputStreamParser.MultiPart) imagePart)
                                    .getContentDispositionFilename();
                            data.image = IOUtils.toByteArray(imagePart.getInputStream());
                        }
                        return data;
                    } catch (ServletException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            };
        }

        @Override
        public void delete(String id) throws HttpErrorException {
        }
    });

    start(false);
}

From source file:org.blazr.extrastorage.ExtraStorage.java

private static String getText(String myURL, boolean main_thread) {
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {/*from   ww w.  j  a  v a2  s .  co  m*/
        URL url = new URL(StringEscapeUtils.escapeHtml(myURL));
        urlConn = url.openConnection();
        if (urlConn != null)
            if (main_thread)
                urlConn.setReadTimeout(5 * 1000);
            else
                urlConn.setReadTimeout(30 * 1000);
        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 (IOException e) {
        if (e.getMessage().contains("429"))
            return "wait";
        return null;
    } catch (Exception e) {
        return null;
    }
    return sb.toString();
}

From source file:nz.co.fortytwo.freeboard.installer.ChartProcessor.java

/**
 * Reads the .kap file, and the generated tilesresource.xml to get
 * chart desc, bounding box, and zoom levels
 * @param chartFile//from w w  w  .  j  av  a 2 s. c  om
 * @param false 
 * @throws Exception
 */
public void processKapChart(File chartFile, boolean reTile, String charset) throws Exception {
    //String chartPath = chartFile.getParentFile().getAbsolutePath();
    String chartName = chartFile.getName();
    chartName = chartName.substring(0, chartName.lastIndexOf("."));
    File dir = new File(chartFile.getParentFile(), chartName);
    //      if(manager){
    //         logger.info("Chart tag:"+chartName+"\n");
    //         logger.info("Chart dir:"+dir.getPath()+"\n");
    //      }
    //      logger.info("Processing Chart tag:"+chartName);
    logger.info("Chart dir:" + dir.getPath());

    if (reTile) {
        KapProcessor processor = new KapProcessor();
        processor.setObserver(new KapObserver() {
            public void appendMsg(final String message) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        textArea.append(message);
                    }
                });
            }
        });
        processor.createTilePyramid(chartFile, mapCacheDir, false);
    }
    //process the layer data
    File xmlFile = new File(dir, "tilemapresource.xml");

    //read data from dirName/tilelayers.xml
    SAXReader reader = new SAXReader();

    Document document = reader.read(new InputStreamReader(new FileInputStream(xmlFile), charset));

    logger.info("KAP file using " + charset);
    //now get the Chart Name from the kap file
    InputStreamReader fileReader = new InputStreamReader(new FileInputStream(chartFile), charset);
    char[] chars = new char[4096];
    fileReader.read(chars);
    fileReader.close();
    String header = new String(new String(chars).getBytes(), "UTF-8");
    int pos = header.indexOf("BSB/NA=") + 7;
    String desc = header.substring(pos, header.indexOf("\n", pos)).trim();
    //if(desc.endsWith("\n"))desc=desc.substring(0,desc.length()-1);
    logger.debug("Name:" + desc);
    //we cant have + or , or = in name, as its used in storing ChartplotterViewModel
    //US50_2 BERING SEA CONTINUATION,NU=2401,RA=2746,3798,DU=254
    desc = desc.replaceAll("\\+", " ");
    desc = desc.replaceAll(",", " ");
    desc = desc.replaceAll("=", "/");
    //limit length too
    if (desc.length() > 40) {
        desc = desc.substring(0, 40);
    }

    //we need BoundingBox
    Element box = (Element) document.selectSingleNode("//BoundingBox");
    String minx = box.attribute("minx").getValue();
    String miny = box.attribute("miny").getValue();
    String maxx = box.attribute("maxx").getValue();
    String maxy = box.attribute("maxy").getValue();
    //        if(manager){
    //         logger.info("Box:"+minx+","+miny+","+maxx+","+maxy+"\n");
    //      }
    logger.debug("Box:" + minx + ", " + miny + ", " + maxx + ", " + maxy);

    //we need TileSets, each tileset has an href, we need first and last for zooms
    @SuppressWarnings("unchecked")
    List<Attribute> list = document.selectNodes("//TileSets/TileSet/@href");
    int minZoom = 18;
    int maxZoom = 0;
    for (Attribute attribute : list) {
        int zoom = Integer.valueOf(attribute.getValue());
        if (zoom < minZoom)
            minZoom = zoom;
        if (zoom > maxZoom)
            maxZoom = zoom;
    }
    //        if(manager){
    //         System.out.print("Zoom:"+minZoom+"-"+maxZoom+"\n");
    //      }
    logger.debug("Zoom:" + minZoom + "-" + maxZoom);

    //cant have - in js var name
    String chartNameJs = chartName.replaceAll("^[^a-zA-Z_$]|[^\\w$]", "_");
    String snippet = "\n\tvar " + chartNameJs + " = L.tileLayer(\"http://{s}.{server}:8080/mapcache/"
            + chartName + "/{z}/{x}/{y}.png\", {\n" + "\t\tserver: host,\n" + "\t\tsubdomains: 'abcd',\n"
            + "\t\tattribution: '" + chartName + " " + desc + "',\n" + "\t\tminZoom: " + minZoom + ",\n"
            + "\t\tmaxNativeZoom: " + maxZoom + ",\n" + "\t\tmaxZoom: " + (maxZoom + 3) + ",\n"
            + "\t\ttms: true\n" + "\t\t}).addTo(map);\n";

    //        if(manager){
    //         System.out.print(snippet+"\n");
    //      }
    logger.debug(snippet);
    //add it to local freeboard.txt
    File layers = new File(dir, "freeboard.txt");
    FileUtils.writeStringToFile(layers, snippet, StandardCharsets.UTF_8.name());
    //now zip the result
    logger.info("Zipping directory...");
    ZipUtils.zip(dir, new File(dir.getParentFile(), chartName + ".zip"));
    logger.info("Zipping directory complete, in "
            + new File(dir.getParentFile(), chartName + ".zip").getAbsolutePath());
}

From source file:magoffin.matt.sobriquet.sendmail.test.SendmailAliasFileParserTests.java

@Test
public void testParseEmptyReader() {
    ByteArrayInputStream byos = new ByteArrayInputStream(new byte[0]);
    InputStreamReader in = null;
    try {/* ww  w .  ja v  a2 s . c  om*/
        in = new InputStreamReader(byos);
        SendmailAliasFileParser parser = new SendmailAliasFileParser(in);
        for (@SuppressWarnings("unused")
        Alias a : parser) {
            Assert.fail("Should not parse anything");
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.apache.solr.common.util.ContentStreamTest.java

public void testFileStream() throws IOException {
    InputStream is = new SolrResourceLoader().openResource("solrj/README");
    assertNotNull(is);/*from  w  w w. j  ava2s. c om*/
    File file = new File(createTempDir().toFile(), "README");
    FileOutputStream os = new FileOutputStream(file);
    IOUtils.copy(is, os);
    os.close();
    is.close();

    ContentStreamBase stream = new ContentStreamBase.FileStream(file);
    InputStream s = stream.getStream();
    FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
    Reader r = stream.getReader();
    try {
        assertEquals(file.length(), stream.getSize().intValue());
        assertTrue(IOUtils.contentEquals(fis, s));
        assertTrue(IOUtils.contentEquals(isr, r));
    } finally {
        s.close();
        r.close();
        isr.close();
        fis.close();
    }
}

From source file:org.mulgara.store.jxunit.SparqlQueryJX.java

/**
 * Execute a query against a SPARQL endpoint.
 * @param endpoint The URL of the endpoint.
 * @param query The query to execute./*from ww  w .j  a  va  2s  .  co  m*/
 * @param defGraph The default graph to execute the query against,
 *        or <code>null</code> if not set.
 * @return A string representation of the result from the server.
 * @throws IOException If there was an error communicating with the server.
 * @throws UnsupportedEncodingException The SPARQL endpoint used an encoding not understood by this system.
 * @throws HttpClientException An unexpected response was returned from the SPARQL endpoint.
 */
String executeQuery(String endpoint, String query, URI defGraph)
        throws IOException, UnsupportedEncodingException, HttpClientException {
    String request = endpoint + "?";
    if (defGraph != null && (0 != defGraph.toString().length()))
        request += "default-graph-uri=" + defGraph.toString() + "&";
    request += "query=" + URLEncoder.encode(query, UTF8);
    requestUrl = request;

    HttpClient client = new DefaultHttpClient();
    client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    HttpGet get = new HttpGet(request);
    get.setHeader("Accept", "application/rdf+xml");

    StringBuilder result = new StringBuilder();
    try {
        HttpResponse response = client.execute(get);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HttpStatus.SC_OK) {
            String msg = "Bad result from SPARQL endpoint: " + status;
            System.err.println(msg);
            throw new HttpClientException(msg);
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStreamReader resultStream = new InputStreamReader(entity.getContent());
            char[] buffer = new char[BUFFER_SIZE];
            int len;
            while ((len = resultStream.read(buffer)) >= 0)
                result.append(buffer, 0, len);
            resultStream.close();
        } else {
            String msg = "No data in response from SPARQL endpoint";
            System.out.println(msg);
            throw new HttpClientException(msg);
        }
    } catch (UnsupportedEncodingException e) {
        System.err.println("Unsupported encoding returned from SPARQL endpoint: " + e.getMessage());
        throw e;
    } catch (IOException ioe) {
        System.err.println("Error communicating with SPARQL endpoint: " + ioe.getMessage());
        throw ioe;
    }
    return result.toString();
}

From source file:com.esprit.android.inart.FillableLoaderPage.java

public String readSavedData() {
    StringBuffer datax = new StringBuffer("");
    try {// w w  w. ja v a  2  s .com
        FileInputStream fIn = this.getActivity().openFileInput("loulou.txt");
        InputStreamReader isr = new InputStreamReader(fIn);
        BufferedReader buffreader = new BufferedReader(isr);

        String readString = buffreader.readLine();
        while (readString != null) {
            datax.append(readString);
            readString = buffreader.readLine();
        }

        isr.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return datax.toString();
}

From source file:com.instantme.api.SimpleAPIResponse.java

public boolean Response20X(HttpConnection connection, Hashtable cookies) {

    boolean result = false;
    StringBuffer strf = null;//www  .jav  a2s  .com
    response = null;

    try {
        InputStream is = connection.openInputStream();
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");

        int ch;
        strf = new StringBuffer();
        while ((ch = isr.read()) != -1) {
            strf.append((char) ch);
        }

        response = strf.toString();
        strf = null;
        int code = new JSONObject(response).getJSONObject("meta").getInt("code");
        result = code == 200;
        response = null;
        isr.close();
        is.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (JSONException ex) {
        ex.printStackTrace();
    }

    return result;
}

From source file:edu.illinois.cs.cogcomp.pipeline.server.ServerClientAnnotator.java

/**
 * The method is synchronized since the caching seems to have issues upon mult-threaded caching
 * @param overwrite if true, it would overwrite the values on cache
 *//*from  ww  w  .j  a  va  2  s.c  o  m*/
public synchronized TextAnnotation annotate(String str, boolean overwrite) throws Exception {
    String viewsConnected = Arrays.toString(viewsToAdd);
    String views = viewsConnected.substring(1, viewsConnected.length() - 1).replace(" ", "");
    ConcurrentMap<String, byte[]> concurrentMap = (db != null)
            ? db.hashMap(viewName, Serializer.STRING, Serializer.BYTE_ARRAY).createOrOpen()
            : null;
    String key = DigestUtils.sha1Hex(str + views);
    if (!overwrite && concurrentMap != null && concurrentMap.containsKey(key)) {
        byte[] taByte = concurrentMap.get(key);
        return SerializationHelper.deserializeTextAnnotationFromBytes(taByte);
    } else {
        URL obj = new URL(url + ":" + port + "/annotate");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("charset", "utf-8");
        con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");

        con.setDoOutput(true);
        con.setUseCaches(false);

        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write("text=" + URLEncoder.encode(str, "UTF-8") + "&views=" + views);
        wr.flush();

        InputStreamReader reader = new InputStreamReader(con.getInputStream());
        BufferedReader in = new BufferedReader(reader);
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        reader.close();
        wr.close();
        con.disconnect();
        TextAnnotation ta = SerializationHelper.deserializeFromJson(response.toString());
        if (concurrentMap != null) {
            concurrentMap.put(key, SerializationHelper.serializeTextAnnotationToBytes(ta));
            this.db.commit();
        }
        return ta;
    }
}