Example usage for java.io InputStreamReader read

List of usage examples for java.io InputStreamReader read

Introduction

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

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:org.wso2.appserver.integration.tests.javaee.WebappDeploymentTestCase.java

private String getStringFromInputStream(InputStream in) throws Exception {
    InputStreamReader reader = new InputStreamReader(in);
    char[] buff = new char[1024];
    StringBuilder retValue = new StringBuilder();

    int i;//  w w w . j  a  v  a2 s  . c o  m
    try {
        while ((i = reader.read(buff)) > 0) {
            retValue.append(new String(buff, 0, i));
        }
    } catch (Exception var6) {
        log.error("Failed to get the response " + var6);
        throw new Exception("Failed to get the response :" + var6);
    }

    return retValue.toString();
}

From source file:org.spiffyui.maven.plugins.CssCompressMojo.java

/**
 * This method concatenates the set of CSS source files since YUI requires a 
 * single input file.//from w ww . j  a  v a  2s  .c o m
 * 
 * @param files  the files to concatenate
 * 
 * @return a temporary file containing the concatenated source files
 * @exception IOException
 */
private File concat(Collection<File> files) throws IOException {
    File outFile = File.createTempFile("spiffy_", ".css");
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outFile), encoding);
    try {
        for (File file : files) {
            InputStreamReader in = new InputStreamReader(new FileInputStream(file), encoding);
            int read;
            char[] buf = new char[1024];

            try {
                while ((read = in.read(buf)) > 0) {
                    out.write(buf, 0, read);
                }

                out.write('\n');
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }

    //outFile.deleteOnExit();
    return outFile;
}

From source file:com.example.firstapp.PlotMapJsonActivity.java

protected void retrieveAndAddMarkers(String createdURL) throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {//w  w w . j a v a 2 s. c  o  m
        // Connect to the web service
        URL url = new URL(createdURL);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the city data.
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                createMarkersFromJson(json.toString());
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
        }
    });
}

From source file:ch.ethz.tik.hrouting.providers.PlacesAutoCompleteAdapter.java

private StringBuilder getJsonResults(String requestType, List<String> parameters) {
    StringBuilder jsonResults = new StringBuilder();
    HttpURLConnection connection = null;
    String query = buildQuery(requestType, parameters);
    try {/*from w  w  w  .j  ava2 s .  c o m*/
        URL url = new URL(query);
        connection = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(connection.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to Places API", e);
        e.printStackTrace();

        // Autocomplete is running in a thread, create a handler to post
        // message to the main thread
        Handler mHandler = new Handler(getContext().getMainLooper());
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext().getApplicationContext(), "Not able to reach Google Place API",
                        Toast.LENGTH_LONG).show();
            }
        });

        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return jsonResults;
}

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 ww w .ja v a2s . c  o m*/
 * @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:com.tilusnet.wayta.MainActivity2.java

protected void queryClavin() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {/*from   ww  w  .  j  ava 2s .co  m*/
        // Connect to the web service
        String query = SERVICE_URL + URLEncoder.encode(editText.getEditableText().toString(), "utf-8");
        Log.i(LOG_TAG, "Querying " + query);
        URL url = new URL(query);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        errMsg = "Error connecting to service";
        Log.e(LOG_TAG, errMsg, e);
        throw new IOException(errMsg, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the query data; also highlight matches in text
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                createMarkersFromJson(json.toString());
                zoomToArea();
                highlightText(json.toString());
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
                //               Toast.makeText(MainActivity2.instance, errMsg, Toast.LENGTH_SHORT).show();
            }
        }
    });

    // 
}

From source file:com.jcertif.android.fragments.MapEventFragment.java

protected void retrieveAndAddPOI() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {// www.j  av a  2 s. com
        // Connect to the url
        /*URL url = new URL(geo_URL);
        conn = (HttpURLConnection) url.openConnection();*/
        /*InputStreamReader in = new InputStreamReader(conn.getInputStream());*/
        InputStreamReader in = new InputStreamReader(
                getSherlockActivity().getResources().openRawResource(R.raw.cgeventgeodata));
        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        createMarkersFromJson(json.toString());
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Error processing JSON", e);
    }
}

From source file:org.vivoweb.harvester.util.SOAPMessenger.java

/**
 * @param urlCon the url connection which the message it comming from.
 * @return the string version of the message
 * @throws IOException if there is a problem with the source.
 *//*from   w  ww .jav  a 2  s .  c o m*/
private String readMessage(URLConnection urlCon) throws IOException {
    InputStreamReader isReader = new InputStreamReader(this.urlCon.getInputStream());

    StringBuilder buf = new StringBuilder();
    char[] cbuf = new char[2048];
    int num;

    while (-1 != (num = isReader.read(cbuf))) {
        buf.append(cbuf, 0, num);
    }

    return buf.toString();
}

From source file:org.dbg4j.rest.DebugJerseyFilter.java

private String getResponseBody(ClientResponse response) {
    String result = "Error retrieving response body: ";

    try {//from   w  w w .  j  a v a2 s  .co  m
        StringBuilder b = new StringBuilder();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = response.getEntityInputStream();
        byte[] requestEntity;

        try {
            ReaderWriter.writeTo(in, out);
        } finally {
            in.close();
        }
        requestEntity = out.toByteArray();
        in = new ByteArrayInputStream(requestEntity);
        //re-set input stream
        response.setEntityInputStream(in);

        if (requestEntity.length > 0) {
            InputStreamReader reader = new InputStreamReader(
                    new ByteArrayInputStream(requestEntity, 0, requestEntity.length));
            char[] buffer = new char[requestEntity.length];
            int charsRead;
            while ((charsRead = reader.read(buffer)) > 0) {
                b.append(buffer, 0, charsRead);
            }
            b.append('\n');
        }

        result = b.toString();
    } catch (Exception e) {
        result += e.toString();
    }
    return result;
}

From source file:com.example.ramap.MainActivity.java

protected void retrieveAndAddBuildings() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {/*  www .j a v a2s  . c  o m*/
        // Connect to the web service
        URL url = new URL(SERVICE_URL);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the building data.
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                createMarkersFromJson(json.toString());
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
        }
    });
}