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:su.fmi.photoshareclient.remote.ImageHandler.java

public static ArrayList<ImageLabel> getImages() {
    ProjectProperties props = new ProjectProperties();
    String webPage = "http://" + props.get("socket") + props.get("restEndpoint") + "/image";
    URL url;/*from   w w  w.ja v  a2s  .  com*/
    try {
        url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + LoginHandler.getAuthStringEncripted());
        InputStream is = urlConnection.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();
        Gson gson = new Gson();

        RemoteImage[] remoteImages = gson.fromJson(result, RemoteImage[].class);

        ArrayList<ImageLabel> images = new ArrayList<ImageLabel>();
        Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        for (RemoteImage rimg : remoteImages) {
            ImageLabel img = getImage(rimg.id, rimg.fileName);
            int imageWidth = img.getImage().getWidth(null);
            int imageHeight = img.getImage().getHeight(null);
            // just a relative estimation
            int imagesPerColumn = (int) Math.floor(Math.sqrt(Pagination.getImagesPerPage()));
            double ratio = (screenSize.height / (double) imageHeight < screenSize.width / (double) imageWidth)
                    ? screenSize.height / (double) imageHeight
                    : screenSize.width / (double) imageWidth;
            ratio = ratio / imagesPerColumn; // reduce ratio because more than 1 image are located in the column
            int resizeWidth = (int) (imageWidth * ratio);
            int resizeHeight = (int) (imageHeight * ratio);
            Image resizedImage = createResizedCopy(img.getImage(), resizeWidth, resizeHeight, false);
            images.add(new ImageLabel(resizedImage, img.getImageId(), img.getFileName()));
        }
        return images;
    } catch (MalformedURLException ex) {
        System.out.println(ex);
    } catch (IOException ex) {
        System.out.println(ex);
    }

    return null;
}

From source file:com.jamesgiang.aussnowcam.Utils.java

public static String ReadSettings(Context context, String file) throws IOException {
    FileInputStream fIn = null;//w w w  .  j  a  v a 2s .c o  m
    InputStreamReader isr = null;
    String data = null;
    fIn = context.openFileInput(file);
    isr = new InputStreamReader(fIn);
    char[] inputBuffer = new char[fIn.available()];
    isr.read(inputBuffer);
    data = new String(inputBuffer);
    isr.close();
    fIn.close();
    return data;
}

From source file:it.feio.android.omninotes.utils.GeocodeHelper.java

public static ArrayList<String> autocomplete(String input) {
    ArrayList<String> resultList = null;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {/*from ww w . ja va 2 s  .c o  m*/
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.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) {
        Ln.e(e, "Error processing Places API URL");
        return resultList;
    } catch (IOException e) {
        Ln.e(e, "Error connecting to Places API");
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList<String>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        Ln.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}

From source file:org.flowerplatform.tests.TestUtil.java

/**
 * Copied from http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file
 *///w ww .  ja  va  2  s.  c  o m
public static String readFile(String path) {
    StringBuffer loadedContent = new StringBuffer();
    try {
        InputStreamReader fileEditorInputReader = new InputStreamReader(new FileInputStream(path));
        char[] buffer = new char[1024];
        int bytesRead;
        do {
            bytesRead = fileEditorInputReader.read(buffer);
            if (bytesRead > 0)
                loadedContent.append(buffer, 0, bytesRead);
        } while (bytesRead > 0);
        fileEditorInputReader.close();
    } catch (Exception e) {
        throw new RuntimeException("Error while loading file content " + path, e);
    }
    return loadedContent.toString();
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpClientUtil.java

private static String getStringFromInputStream(InputStream in) throws Exception {
    InputStreamReader reader = new InputStreamReader(in, Charset.defaultCharset());
    char[] buff = new char[1024];
    int i;/* w  w w  . ja v  a2 s  .co m*/
    StringBuffer retValue = new StringBuffer();
    try {
        while ((i = reader.read(buff)) > 0) {
            retValue.append(new String(buff, 0, i));
        }
    } catch (Exception e) {
        log.error("Failed to get the response " + e);
        throw new Exception("Failed to get the response :" + e);
    }
    return retValue.toString();
}

From source file:com.github.thorqin.toolkit.mail.MailService.java

public static Mail createMailByTemplateStream(InputStream in, Map<String, String> replaced) throws IOException {
    Mail mail = new Mail();
    InputStreamReader reader = new InputStreamReader(in, "utf-8");
    char[] buffer = new char[1024];
    StringBuilder builder = new StringBuilder();
    while (reader.read(buffer) != -1)
        builder.append(buffer);//from   w ww.ja  v  a 2s.c  o m
    String mailBody = builder.toString();
    builder.setLength(0);
    Pattern pattern = Pattern.compile("<%\\s*(.+?)\\s*%>", Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(mailBody);
    int scanPos = 0;
    while (matcher.find()) {
        builder.append(mailBody.substring(scanPos, matcher.start()));
        scanPos = matcher.end();
        String key = matcher.group(1);
        if (replaced != null) {
            String value = replaced.get(key);
            if (value != null) {
                builder.append(value);
            }
        }
    }
    builder.append(mailBody.substring(scanPos, mailBody.length()));
    mail.htmlBody = builder.toString();
    pattern = Pattern.compile("<title>(.*)</title>",
            Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(mail.htmlBody);
    if (matcher.find()) {
        mail.subject = matcher.group(1);
    }
    return mail;
}

From source file:com.github.thorqin.webapi.mail.MailService.java

public static Mail createHtmlMailFromTemplate(String templatePath, Map<String, String> replaced) {
    Mail mail = new Mail();
    try (InputStream in = MailService.class.getClassLoader().getResourceAsStream(templatePath)) {
        InputStreamReader reader = new InputStreamReader(in, "utf-8");
        char[] buffer = new char[1024];
        StringBuilder builder = new StringBuilder();
        while (reader.read(buffer) != -1)
            builder.append(buffer);/*from   w w  w . ja  va  2  s . c  om*/
        String mailBody = builder.toString();
        builder.setLength(0);
        Pattern pattern = Pattern.compile("<%\\s*(.+?)\\s*%>", Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(mailBody);
        int scanPos = 0;
        while (matcher.find()) {
            builder.append(mailBody.substring(scanPos, matcher.start()));
            scanPos = matcher.end();
            String key = matcher.group(1);
            if (replaced != null) {
                String value = replaced.get(key);
                if (value != null) {
                    builder.append(value);
                }
            }
        }
        builder.append(mailBody.substring(scanPos, mailBody.length()));
        mail.htmlBody = builder.toString();
        pattern = Pattern.compile("<title>(.*)</title>",
                Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
        matcher = pattern.matcher(mail.htmlBody);
        if (matcher.find()) {
            mail.subject = matcher.group(1);
        }
    } catch (IOException ex) {
        logger.log(Level.SEVERE, "Create mail from template error: {0}, {1}",
                new Object[] { templatePath, ex });
    }
    return mail;
}

From source file:com.dmsl.anyplace.utils.NetworkUtils.java

private static String readInputStream(InputStream stream) throws IOException {
    int n = 0;/*  w  w  w.j  a v  a  2 s  . c  o m*/
    char[] buffer = new char[1024 * 4];
    InputStreamReader reader = new InputStreamReader(stream, "UTF8");
    StringWriter writer = new StringWriter();
    while (-1 != (n = reader.read(buffer)))
        writer.write(buffer, 0, n);
    return writer.toString();
}

From source file:de.Keyle.MyPet.api.Util.java

public static String toString(InputStream is, Charset charset) {
    String content = "";

    try {//from w  w w.  j  ava  2  s .  co m
        InputStreamReader in = new InputStreamReader(is, charset);
        int numBytes;
        final char[] buf = new char[512];
        while ((numBytes = in.read(buf)) != -1) {
            content += String.copyValueOf(buf, 0, numBytes);
        }
    } catch (Exception ignored) {
    }

    return content;
}

From source file:net.fenyo.mail4hotspot.service.Browser.java

public static String getHtml(final String target_url, final Cookie[] cookies) throws IOException {
    // log.debug("RETRIEVING_URL=" + target_url);
    final URL url = new URL(target_url);

    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.69.60.6", 3128)); 
    // final HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);

    //      HttpURLConnection.setFollowRedirects(true);
    // conn.setRequestProperty("User-agent", "my agent name");

    conn.setRequestProperty("Accept-Language", "en-US");

    //      conn.setRequestProperty(key, value);

    // allow both GZip and Deflate (ZLib) encodings
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    final String encoding = conn.getContentEncoding();
    InputStream is = null;// w w  w .  j  av  a 2s . c om
    // create the appropriate stream wrapper based on the encoding type
    if (encoding != null && encoding.equalsIgnoreCase("gzip"))
        is = new GZIPInputStream(conn.getInputStream());
    else if (encoding != null && encoding.equalsIgnoreCase("deflate"))
        is = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
    else
        is = conn.getInputStream();

    final InputStreamReader reader = new InputStreamReader(new BufferedInputStream(is));

    final CharBuffer cb = CharBuffer.allocate(1024 * 1024);
    int ret;
    do {
        ret = reader.read(cb);
    } while (ret > 0);
    cb.flip();
    return cb.toString();
}