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:com.amazonaws.codedeploy.AWSCodeDeployPublisher.java

private RevisionLocation zipAndUpload(AWSClients aws, String projectName, FilePath sourceDirectory)
        throws IOException, InterruptedException, IllegalArgumentException {

    File zipFile = null;//from   w ww  .  j  a va 2s  .c o m
    File versionFile;
    versionFile = new File(sourceDirectory + "/" + versionFileName);

    InputStreamReader reader = null;
    String version = null;
    try {
        reader = new InputStreamReader(new FileInputStream(versionFile), "UTF-8");
        char[] chars = new char[(int) versionFile.length() - 1];
        reader.read(chars);
        version = new String(chars);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }

    if (version != null) {
        zipFile = new File("/tmp/" + projectName + "-" + version + ".zip");
        final boolean fileCreated = zipFile.createNewFile();
        if (!fileCreated) {
            logger.println("File already exists, overwriting: " + zipFile.getPath());
        }
    } else {
        zipFile = File.createTempFile(projectName + "-", ".zip");
    }

    String key;
    File appspec;
    File dest;
    String deploymentGroupName = getDeploymentGroupNameFromEnv();
    String prefix = getS3PrefixFromEnv();
    String bucket = getS3BucketFromEnv();

    if (bucket.indexOf("/") > 0) {
        throw new IllegalArgumentException(
                "S3 Bucket field cannot contain any subdirectories.  Bucket name only!");
    }

    try {
        if (this.deploymentGroupAppspec) {
            appspec = new File(sourceDirectory + "/appspec." + deploymentGroupName + ".yml");
            if (appspec.exists()) {
                dest = new File(sourceDirectory + "/appspec.yml");
                FileUtils.copyFile(appspec, dest);
                logger.println("Use appspec." + deploymentGroupName + ".yml");
            }
            if (!appspec.exists()) {
                throw new IllegalArgumentException(
                        "/appspec." + deploymentGroupName + ".yml file does not exist");
            }

        }

        logger.println("Zipping files into " + zipFile.getAbsolutePath());

        FileOutputStream outputStream = new FileOutputStream(zipFile);
        try {
            sourceDirectory.zip(outputStream, new DirScanner.Glob(this.includes, this.excludes));
        } finally {
            outputStream.close();
        }

        if (prefix.isEmpty()) {
            key = zipFile.getName();
        } else {
            key = Util.replaceMacro(prefix, envVars);
            if (prefix.endsWith("/")) {
                key += zipFile.getName();
            } else {
                key += "/" + zipFile.getName();
            }
        }
        logger.println("Uploading zip to s3://" + bucket + "/" + key);
        PutObjectResult s3result = aws.s3.putObject(bucket, key, zipFile);

        S3Location s3Location = new S3Location();
        s3Location.setBucket(bucket);
        s3Location.setKey(key);
        s3Location.setBundleType(BundleType.Zip);
        s3Location.setETag(s3result.getETag());

        RevisionLocation revisionLocation = new RevisionLocation();
        revisionLocation.setRevisionType(RevisionLocationType.S3);
        revisionLocation.setS3Location(s3Location);

        return revisionLocation;
    } finally {
        final boolean deleted = zipFile.delete();
        if (!deleted) {
            logger.println("Failed to clean up file " + zipFile.getPath());
        }
    }
}

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  . java  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:com.nearnotes.NoteEdit.java

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

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {//from  ww  w. j a  v a  2s  .  com
        StringBuilder sb = new StringBuilder("http://www.nearnotes.com/places.php");
        sb.append("?longitude=" + String.valueOf(mLongitude));
        sb.append("&latitude=" + String.valueOf(mLatitude));
        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) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        Toast.makeText(getActivity(), "You are offline", Toast.LENGTH_SHORT).show();
        Log.e(LOG_TAG, "Error connecting to Places API", e);
        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");
        if (predsJsonArray.length() == 0) {
            Toast.makeText(getActivity(), "No locations found", Toast.LENGTH_SHORT).show();
        }

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

From source file:at.gv.egiz.bku.binding.DataUrlConnectionImpl.java

@Override
public void transmit(SLResult slResult) throws IOException {
    log.trace("Sending data.");
    if (urlEncoded) {
        ///*from   w w w.  j  a v  a2 s  .c  o  m*/
        // application/x-www-form-urlencoded (legacy, SL < 1.2)
        //

        OutputStream os = connection.getOutputStream();
        OutputStreamWriter streamWriter = new OutputStreamWriter(os, HttpUtil.DEFAULT_CHARSET);

        // ResponseType
        streamWriter.write(FORMPARAM_RESPONSETYPE);
        streamWriter.write("=");
        streamWriter.write(URLEncoder.encode(DEFAULT_RESPONSETYPE, "UTF-8"));
        streamWriter.write("&");

        // XMLResponse / Binary Response
        if (slResult.getResultType() == SLResultType.XML) {
            streamWriter.write(DataUrlConnection.FORMPARAM_XMLRESPONSE);
        } else {
            streamWriter.write(DataUrlConnection.FORMPARAM_BINARYRESPONSE);
        }
        streamWriter.write("=");
        streamWriter.flush();
        URLEncodingWriter urlEnc = new URLEncodingWriter(streamWriter);
        slResult.writeTo(new StreamResult(urlEnc), false);
        urlEnc.flush();

        // transfer parameters
        char[] cbuf = new char[512];
        int len;
        for (HTTPFormParameter formParameter : httpFormParameter) {
            streamWriter.write("&");
            streamWriter.write(URLEncoder.encode(formParameter.getName(), "UTF-8"));
            streamWriter.write("=");
            InputStreamReader reader = new InputStreamReader(formParameter.getData(),
                    (formParameter.getCharSet() != null) ? formParameter.getCharSet() : "UTF-8"); // assume request was
                                                                                                                                                                            // application/x-www-form-urlencoded,
                                                                                                                                                                            // formParam therefore UTF-8
            while ((len = reader.read(cbuf)) != -1) {
                urlEnc.write(cbuf, 0, len);
            }
            urlEnc.flush();
        }
        streamWriter.close();

    } else {
        //
        // multipart/form-data (conforming to SL 1.2)
        //

        ArrayList<Part> parts = new ArrayList<Part>();

        // ResponseType
        StringPart responseType = new StringPart(FORMPARAM_RESPONSETYPE, DEFAULT_RESPONSETYPE, "UTF-8");
        responseType.setTransferEncoding(null);
        parts.add(responseType);

        // XMLResponse / Binary Response
        SLResultPart slResultPart = new SLResultPart(slResult, XML_RESPONSE_ENCODING);
        if (slResult.getResultType() == SLResultType.XML) {
            slResultPart.setTransferEncoding(null);
            slResultPart.setContentType(slResult.getMimeType());
            slResultPart.setCharSet(XML_RESPONSE_ENCODING);
        } else {
            slResultPart.setTransferEncoding(null);
            slResultPart.setContentType(slResult.getMimeType());
        }
        parts.add(slResultPart);

        // transfer parameters
        for (HTTPFormParameter formParameter : httpFormParameter) {
            InputStreamPartSource source = new InputStreamPartSource(null, formParameter.getData());
            FilePart part = new FilePart(formParameter.getName(), source, formParameter.getContentType(),
                    formParameter.getCharSet());
            part.setTransferEncoding(formParameter.getTransferEncoding());
            parts.add(part);
        }

        OutputStream os = connection.getOutputStream();
        Part.sendParts(os, parts.toArray(new Part[parts.size()]), boundary.getBytes());
        os.close();

    }

    // MultipartRequestEntity PostMethod
    InputStream is = null;
    try {
        is = connection.getInputStream();
    } catch (IOException iox) {
        log.info("Failed to get InputStream of HTTPUrlConnection.", iox);
    }
    log.trace("Reading response.");
    response = new DataUrlResponse(url.toString(), connection.getResponseCode(), is);
    Map<String, String> responseHttpHeaders = new HashMap<String, String>();
    Map<String, List<String>> httpHeaders = connection.getHeaderFields();
    for (Iterator<String> keyIt = httpHeaders.keySet().iterator(); keyIt.hasNext();) {
        String key = keyIt.next();
        StringBuffer value = new StringBuffer();
        for (String val : httpHeaders.get(key)) {
            value.append(val);
            value.append(HttpUtil.SEPARATOR[0]);
        }
        String valString = value.substring(0, value.length() - 1);
        if ((key != null) && (value.length() > 0)) {
            responseHttpHeaders.put(key, valString);
        }
    }
    response.setResponseHttpHeaders(responseHttpHeaders);
}

From source file:com.mocap.MocapFragment.java

public void Read_File(Context context) {
    FileInputStream fIn = null;//  w  ww  . j  a v  a 2  s  .c om
    InputStreamReader isr = null;

    char[] inputBuffer = new char[255];
    String data = null;

    JSONObject json = null;

    try {
        fIn = context.openFileInput("objet_1.obj");
        isr = new InputStreamReader(fIn);
        isr.read(inputBuffer);
        data = new String(inputBuffer);
        //affiche le contenu de mon fichier dans un popup surgissant
        //Log.i(TAG, "Data: " + data);
        //Toast.makeText(context, "data: " + data, Toast.LENGTH_SHORT).show();
        //json=new JSONObject(data);

    } catch (Exception e) {
        Toast.makeText(context, "Objet not read", Toast.LENGTH_SHORT).show();
    }
    /*finally {
       try {
              isr.close();
              fIn.close();
              } catch (IOException e) {
                Toast.makeText(context, "Settings not read",Toast.LENGTH_SHORT).show();
              }
    } */
    //return json;
}

From source file:org.apache.james.mailbox.maildir.MaildirFolder.java

/**
 * Read the uidValidity of the given mailbox from the file system.
 * If the respective file is not yet there, it gets created and
 * filled with a brand new uidValidity.//from  ww w  .ja v  a  2s  .c o  m
 * @return The uidValidity
 * @throws IOException if there are problems with the validity file
 */
private long readUidValidity() throws IOException {
    File validityFile = new File(rootFolder, VALIDITY_FILE);
    if (!validityFile.exists()) {
        return resetUidValidity();
    }
    FileInputStream fis = null;
    InputStreamReader isr = null;
    try {
        fis = new FileInputStream(validityFile);
        isr = new InputStreamReader(fis);
        char[] uidValidity = new char[20];
        int len = isr.read(uidValidity);
        return Long.parseLong(String.valueOf(uidValidity, 0, len).trim());
    } finally {
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(fis);
    }
}

From source file:net.wm161.microblog.lib.backends.statusnet.HTTPAPIRequest.java

protected String getData(URI location) throws APIException {
    Log.d("HTTPAPIRequest", "Downloading " + location);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(location);
    client.addRequestInterceptor(preemptiveAuth, 0);

    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    if (!m_params.isEmpty()) {
        MultipartEntity params = new MultipartEntity();
        for (Entry<String, Object> item : m_params.entrySet()) {
            Object value = item.getValue();
            ContentBody data;//w  w  w  . jav  a 2s . c  o  m
            if (value instanceof Attachment) {
                Attachment attachment = (Attachment) value;
                try {
                    data = new InputStreamBody(attachment.getStream(), attachment.contentType(),
                            attachment.name());
                    Log.d("HTTPAPIRequest",
                            "Found a " + attachment.contentType() + " attachment named " + attachment.name());
                } catch (FileNotFoundException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                } catch (IOException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                }
            } else {
                try {
                    data = new StringBody(value.toString());
                } catch (UnsupportedEncodingException e) {
                    getRequest().setError(ErrorType.ERROR_INTERNAL);
                    throw new APIException();
                }
            }
            params.addPart(item.getKey(), data);
        }
        post.setEntity(params);
    }

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(m_api.getAccount().getUser(),
            m_api.getAccount().getPassword());
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

    HttpResponse req;
    try {
        req = client.execute(post);
    } catch (ClientProtocolException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    } catch (IOException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_FAILED);
        throw new APIException();
    }

    InputStream result;
    try {
        result = req.getEntity().getContent();
    } catch (IllegalStateException e1) {
        getRequest().setError(ErrorType.ERROR_INTERNAL);
        throw new APIException();
    } catch (IOException e1) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }

    InputStreamReader in = null;
    int status;
    in = new InputStreamReader(result);
    status = req.getStatusLine().getStatusCode();
    Log.d("HTTPAPIRequest", "Got status code of " + status);
    setStatusCode(status);
    if (status >= 300 || status < 200) {
        getRequest().setError(ErrorType.ERROR_SERVER);
        Log.w("HTTPAPIRequest", "Server code wasn't 2xx, got " + m_status);
        throw new APIException();
    }

    int totalSize = -1;
    if (req.containsHeader("Content-length"))
        totalSize = Integer.parseInt(req.getFirstHeader("Content-length").getValue());

    char[] buffer = new char[1024];
    //2^17 = 131072.
    StringBuilder contents = new StringBuilder(131072);
    try {
        int size = 0;
        while ((totalSize > 0 && size < totalSize) || totalSize == -1) {
            int readSize = in.read(buffer);
            size += readSize;
            if (readSize == -1)
                break;
            if (totalSize >= 0)
                getRequest().publishProgress(new APIProgress((size / totalSize) * 5000));
            contents.append(buffer, 0, readSize);
        }
    } catch (IOException e) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }
    return contents.toString();
}

From source file:org.pentaho.di.trans.steps.webservices.WebService.java

private String readStringFromInputStream(InputStream is, String encoding) throws KettleStepException {

    try {/*from w  w  w.ja  va  2s. c o  m*/

        StringBuilder sb = new StringBuilder(Math.max(16, is.available()));
        char[] tmp = new char[4096];

        try {
            InputStreamReader reader = new InputStreamReader(is, encoding != null ? encoding : "UTF-8");
            for (int cnt; (cnt = reader.read(tmp)) > 0;) {
                sb.append(tmp, 0, cnt);
            }
        } finally {
            is.close();
        }
        return sb.toString();

    } catch (Exception e) {
        throw new KettleStepException("Unable to read web service response data from input stream", e);
    }

}

From source file:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java

public Process startPythonThread(String batfilePath) throws Exception {

    File file = new File("state.file");
    file.createNewFile();//from ww  w . j ava  2s  .c o m
    try {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader) cl).getURLs();
        for (URL url : urls) {
            System.out.println(url.getFile());
        }

        Runtime runTime = Runtime.getRuntime();
        pythonProcess = runTime.exec("cmd.exe /k " + batfilePath);
        InputStream inputStream = pythonProcess.getInputStream();
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(isr);
        InputStream errorStream = pythonProcess.getErrorStream();
        InputStreamReader esr = new InputStreamReader(errorStream);

        String n1 = "";
        StringBuffer standardOutput = new StringBuffer();
        while ((n1 = reader.readLine()) != null) {
            System.out.println(n1);
        }
        //          System.out.println("Standard Output: " + standardOutput.toString());
        int n2;
        char[] c2 = new char[1024];
        StringBuffer standardError = new StringBuffer();
        while ((n2 = esr.read(c2)) > 0) {
            standardError.append(c2, 0, n2);
        }
        System.out.println("Standard Error: " + standardError.toString());
        return pythonProcess;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.nextep.datadesigner.vcs.services.VCSFiles.java

private String getFileAsString(Connection conn, IRepositoryFile file) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;/* w  ww  .java 2s  .  c  o  m*/
    InputStream blobStream = null;
    InputStreamReader reader = null;
    StringWriter os = null;
    try {
        // Querying blob
        stmt = conn.prepareStatement("SELECT rf.file_content " //$NON-NLS-1$
                + "FROM rep_files rf " //$NON-NLS-1$
                + "WHERE rf.file_id = ? "); //$NON-NLS-1$
        stmt.setLong(1, file.getUID().rawId());
        rs = stmt.executeQuery();
        if (rs.next()) {
            // Retrieving blob input stream
            blobStream = rs.getBinaryStream(1);
            if (blobStream == null) {
                return ""; //$NON-NLS-1$
            }
            reader = new InputStreamReader(blobStream);

            // Opening output file
            os = new StringWriter(10240);

            // Large 10K buffer for efficient read
            char[] buffer = new char[10240];
            int bytesRead = 0;
            while ((bytesRead = reader.read(buffer)) >= 0) {
                os.write(buffer, 0, bytesRead);
            }
            return os.toString();
        } else {
            throw new ErrorException(VCSMessages.getString("files.notFound")); //$NON-NLS-1$
        }
    } catch (IOException e) {
        throw new ErrorException(VCSMessages.getString("files.readRepositoryProblem"), //$NON-NLS-1$
                e);
    } finally {
        safeClose(os);
        safeClose(blobStream);
        safeClose(reader);
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}