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:hudson.tools.JDKInstaller.java

public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log)
        throws IOException, InterruptedException {
    FilePath expectedLocation = preferredLocation(tool, node);
    PrintStream out = log.getLogger();
    try {/*from ww  w  . j  a  v  a 2  s .c  o  m*/
        if (!acceptLicense) {
            out.println("Unable to perform installation until the license is accepted.");
            return expectedLocation;
        }
        // already installed?
        FilePath marker = expectedLocation.child(".installedByHudson");
        if (marker.exists())
            return expectedLocation;
        expectedLocation.mkdirs();

        Platform p = Platform.of(node);
        URL url = locate(log, p, CPU.of(node));

        out.println("Downloading " + url);
        FilePath file = expectedLocation.child(fileName(p));
        file.copyFrom(url);

        out.println("Installing " + file);
        switch (p) {
        case LINUX:
        case SOLARIS:
            file.chmod(0755);
            if (node.createLauncher(log).launch().cmds(file.getRemote(), "-noregister")
                    .stdin(new ByteArrayInputStream("yes".getBytes())).stdout(out).pwd(expectedLocation)
                    .join() != 0)
                throw new AbortException("Failed to install JDK");

            // JDK creates its own sub-directory, so pull them up
            List<FilePath> paths = expectedLocation.list(new JdkFinder());
            if (paths.size() != 1)
                throw new AbortException("Failed to find the extracted JDKs: " + paths);

            // remove the intermediate directory 
            paths.get(0).moveAllChildrenTo(expectedLocation);
            break;
        case WINDOWS:
            /*
            Windows silent installation is full of bad know-how.
                    
            On Windows, command line argument to a process at the OS level is a single string,
            not a string array like POSIX. When we pass arguments as string array, JRE eventually
            turn it into a single string with adding quotes to "the right place". Unfortunately,
            with the strange argument layout of InstallShield (like /v/qn" INSTALLDIR=foobar"),
            it appears that the escaping done by JRE gets in the way, and prevents the installation.
            Presumably because of this, my attempt to use /q/vn" INSTALLDIR=foo" didn't work with JDK5.
                    
            I tried to locate exactly how InstallShield parses the arguments (and why it uses
            awkward option like /qn, but couldn't find any. Instead, experiments revealed that
            "/q/vn ARG ARG ARG" works just as well. This is presumably due to the Visual C++ runtime library
            (which does single string -> string array conversion to invoke the main method in most Win32 process),
            and this consistently worked on JDK5 and JDK4.
                    
            Some of the official documentations are available at
            - http://java.sun.com/j2se/1.5.0/sdksilent.html
            - http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/silent.html
             */
            // see
            //

            FilePath logFile = node.getRootPath().createTempFile("jdk-install", ".log");
            // JDK6u13 doesn't like path representation like "/tmp/foo", so make it a strict Windows format
            String normalizedPath = expectedLocation.absolutize().getRemote();

            ArgumentListBuilder args = new ArgumentListBuilder();
            args.add(file.getRemote());
            args.add("/s");
            // according to http://community.acresso.com/showthread.php?t=83301, \" is the trick to quote values with whitespaces.
            // Oh Windows, oh windows, why do you have to be so difficult?
            args.add("/v/qn REBOOT=Suppress INSTALLDIR=\\\"" + normalizedPath + "\\\" /L \\\""
                    + logFile.getRemote() + "\\\"");

            if (node.createLauncher(log).launch().cmds(args).stdout(out).pwd(expectedLocation).join() != 0) {
                out.println("Failed to install JDK");
                // log file is in UTF-16
                InputStreamReader in = new InputStreamReader(logFile.read(), "UTF-16");
                try {
                    IOUtils.copy(in, new OutputStreamWriter(out));
                } finally {
                    in.close();
                }
                throw new AbortException();
            }

            logFile.delete();

            break;
        }

        // successfully installed
        file.delete();
        marker.touch(System.currentTimeMillis());

    } catch (DetectionFailedException e) {
        out.println("JDK installation skipped: " + e.getMessage());
    }

    return expectedLocation;
}

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

@Test
public void testParseSampleFile() throws IOException {
    ClassPathResource r = new ClassPathResource("aliases.txt", getClass());
    InputStreamReader in = null;
    try {/*from   w ww  .j  a v a 2 s .c  o m*/
        in = new InputStreamReader(r.getInputStream());
        SendmailAliasFileParser parser = new SendmailAliasFileParser(in);
        int count = 0;
        for (Alias a : parser) {
            Assert.assertEquals("Alias " + count, SAMPLE_ALIASES[count][0], a.getAlias());
            Assert.assertEquals("Actual " + count, SAMPLE_ALIASES[count][1], a.getActual());
            Assert.assertEquals("Acutal count " + count, 1, a.getActuals().size());
            count++;
        }
        Assert.assertEquals("Parsed count", SAMPLE_ALIASES.length, count);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:com.netsteadfast.greenstep.util.SystemExpressionJobUtils.java

public static SysExprJobLogVO executeJobForManualFromRestServiceUrl(SysExprJobVO sysExprJob, String accountId,
        HttpServletRequest request) throws ServiceException, Exception {
    SysExprJobLogVO result = new SysExprJobLogVO();
    // ? executeJob/ ? ManualJobServiceImpl.java @Path("/executeJob/") ?, ,  url ?
    String url = ApplicationSiteUtils.getBasePath(sysExprJob.getSystem(), request);
    if (!url.endsWith("/")) {
        url += "/";
    }/*from ww w .ja  v  a2  s  .  c o  m*/
    //url += "services/jaxrs/executeJob/";
    url += Constants.getCxfWebServiceMainPathName() + Constants.getJAXRSServerFactoryBeanAddress()
            + "executeJob/";
    String encUploadOidStr = SystemExpressionJobUtils.getEncUploadOid(accountId, sysExprJob.getOid());
    url += encUploadOidStr;
    InputStreamReader isr = null;
    BufferedReader reader = null;
    try {
        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod(url);
        /*
          NameValuePair[] data = {
         new NameValuePair("uploadOid", encUploadOidStr)
          };
          post.setRequestBody(data);
          */
        post.setParameter("uploadOid", encUploadOidStr);
        int statusCode = httpClient.executeMethod(post);
        if (statusCode != 200 && statusCode != 202) {
            throw new Exception("error, http status code: " + statusCode);
        }
        isr = new InputStreamReader(post.getResponseBodyAsStream());
        reader = new BufferedReader(isr);
        String line = "";
        StringBuilder str = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            str.append(line);
        }
        ObjectMapper mapper = new ObjectMapper();
        result = mapper.readValue(str.toString(), SysExprJobLogVO.class);
    } catch (IOException e) {
        e.printStackTrace();
        result.setFaultMsg(e.getMessage().toString());
    } catch (Exception e) {
        e.printStackTrace();
        result.setFaultMsg(e.getMessage().toString());
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (isr != null) {
            isr.close();
        }
        reader = null;
        isr = null;
    }
    return result;
}

From source file:cn.util.RSAUtils.java

/**
 * ?/?/*  w  ww .  ja  v  a 2  s  .c  o m*/
 * @return void
 * @author 
 * @time 2015-6-6?12:54:36
 */
@SuppressWarnings("static-access")
private static void loadProperties(String publicFileName, String privateFileName) {
    InputStream publicIn = null;
    InputStream privateIn = null;
    InputStreamReader inReader = null;
    BufferedReader brKeyword = null;
    try {
        publicIn = RSAUtils.class.getResourceAsStream("/key/" + publicFileName);
        privateIn = RSAUtils.class.getResourceAsStream("/key/" + privateFileName);

        inReader = new InputStreamReader(publicIn);
        brKeyword = new BufferedReader(inReader);
        StringBuffer sb = new StringBuffer();
        String keyword = null;

        while ((keyword = brKeyword.readLine()) != null) {
            sb.append(keyword);
        }
        keyword = sb.toString().replaceAll("-----\\w+ PUBLIC KEY-----", "").replace("\n", "");
        publickKeyData = (new Base64()).decodeBase64(keyword.getBytes());

        inReader = new InputStreamReader(privateIn);
        brKeyword = new BufferedReader(inReader);
        sb = new StringBuffer();
        while ((keyword = brKeyword.readLine()) != null) {
            sb.append(keyword);
        }
        keyword = sb.toString().replaceAll("-----\\w+ PRIVATE KEY-----", "").replace("\n", "");
        privateKeyData = (new Base64()).decodeBase64(keyword.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != brKeyword)
                brKeyword.close();
            if (null != inReader)
                inReader.close();
            if (null != inReader)
                publicIn.close();
            privateIn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:damian.hashmap.MyActivity.java

public String loadJSONFromAsset() {
    String json = "{}";
    InputStreamReader is = null;
    try {//from   w  w w.ja  v  a2  s  . c  o  m
        is = new InputStreamReader(getAssets().open("person.json"), "UTF-8");

        char[] buffer = new char[BUFFER_SIZE];

        StringBuilder stringBuilder = new StringBuilder();

        int r = is.read(buffer);
        while (r != -1) {

            stringBuilder.append(buffer, 0, r);
            r = is.read(buffer);
        }

        json = new String(stringBuilder.toString());

    } catch (IOException ex) {
        Log.e(TAG, "Error reading questions file", ex);
        return "{}";
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                Log.e(TAG, "Error closing questions file", e);
            }
        }
    }
    return json;

}

From source file:com.pactodigital.apiconnect.api.APIResponse.java

public boolean Response20X(HttpConnection connection) {

    boolean result = false;
    StringBuffer strf = null;//from www. j a v  a 2s .  c om
    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;

        try {
            JSONArray objArray = new JSONArray(response);

            for (int i = 0; i < objArray.length(); i++) {
                JSONObject jobj = objArray.getJSONObject(i);
                data.fromJSONObject(jobj);
            }
            result = true;
        } catch (JSONException ex) {
            ex.printStackTrace();
            result = false;
        }

        response = null;
        isr.close();
        is.close();

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

    return result;
}

From source file:org.apache.chemistry.opencmis.server.impl.browser.POSTHttpServletRequestWrapper.java

public POSTHttpServletRequestWrapper(HttpServletRequest request, File tempDir, int memoryThreshold)
        throws Exception {
    super(request);

    parameters = new HashMap<String, String[]>();

    // parse query string
    parseFormData(request.getQueryString());

    // check multipart
    isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream itemStream = new BufferedInputStream(item.openStream());

            if (item.isFormField()) {
                InputStreamReader reader = new InputStreamReader(itemStream, "UTF-8");

                try {
                    StringBuilder sb = new StringBuilder();

                    char[] buffer = new char[64 * 1024];
                    int b = 0;

                    while ((b = reader.read(buffer)) > -1) {
                        sb.append(buffer, 0, b);
                    }/*  ww w  . j av a2 s.com*/

                    addParameter(name, sb.toString());
                } finally {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            } else {
                filename = item.getName();
                contentType = ((item.getContentType() == null) ? Constants.MEDIATYPE_OCTETSTREAM
                        : item.getContentType());

                ThresholdOutputStream os = new ThresholdOutputStream(tempDir, memoryThreshold);

                try {
                    byte[] buffer = new byte[64 * 1024];
                    int b = 0;

                    while ((b = itemStream.read(buffer)) > -1) {
                        os.write(buffer, 0, b);
                    }

                    os.close();

                    size = BigInteger.valueOf(os.getSize());
                    stream = os.getInputStream();
                } catch (Exception e) {
                    // if something went wrong, make sure the temp file will
                    // be deleted
                    os.destroy();
                    throw e;
                } finally {
                    try {
                        itemStream.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
        }

        String filenameControl = HttpUtils.getStringParameter(this, Constants.CONTROL_FILENAME);

        if (((filenameControl) != null) && (filenameControl.trim().length() > 0)) {
            filename = filenameControl;
        }

        String contentTypeControl = HttpUtils.getStringParameter(this, Constants.CONTROL_CONTENT_TYPE);

        if ((contentTypeControl != null) && (contentTypeControl.trim().length() > 0)) {
            contentType = contentTypeControl;
        }
    } else {
        // form data processing
        StringBuilder sb = new StringBuilder();

        InputStreamReader sr = new InputStreamReader(request.getInputStream(), "UTF-8");
        char[] buffer = new char[4096];
        int c = 0;

        while ((c = sr.read(buffer)) > -1) {
            sb.append(buffer, 0, c);
        }

        parseFormData(sb.toString());
    }
}

From source file:net.mybox.mybox.Common.java

/**
 * Run a system command on the local machine
 * @param command/*from w w  w  .j a va2s.c  o  m*/
 * @return
 */
public static SysResult syscommand(String[] command) {
    Runtime r = Runtime.getRuntime();

    SysResult result = new SysResult();

    System.out.println("syscommand array: " + StringUtils.join(command, " "));

    try {

        Process p = r.exec(command);
        // should use a thread so it can be killed if it has not finished and another one needs to be started
        InputStream in = p.getInputStream();

        InputStream stderr = p.getErrorStream();
        InputStreamReader inreadErr = new InputStreamReader(stderr);
        BufferedReader brErr = new BufferedReader(inreadErr);

        BufferedInputStream buf = new BufferedInputStream(in);
        InputStreamReader inread = new InputStreamReader(buf);
        BufferedReader bufferedreader = new BufferedReader(inread);

        // Read the ls output
        String line;
        while ((line = bufferedreader.readLine()) != null) {
            result.output += line + "\n";
            System.err.print("  output> " + result.output);
            // should check for last line "Contacting server..." after 3 seconds, to restart unison command X times
        }

        result.worked = true;

        // Check for failure
        try {
            if (p.waitFor() != 0) {
                System.err.println("exit value = " + p.exitValue());
                System.err.println("command> " + command);
                System.err.println("output> " + result.output);
                System.err.print("error> ");

                while ((line = brErr.readLine()) != null)
                    System.err.println(line);

                result.worked = false;
            }
            result.returnCode = p.waitFor();
        } catch (InterruptedException e) {
            System.err.println(e);
            result.worked = false;
        } finally {
            // Close the InputStream
            bufferedreader.close();
            inread.close();
            buf.close();
            in.close();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        result.worked = false;
    }

    result.output = result.output.trim();

    return result;
}

From source file:com.garethahealy.quotalimitsgenerator.cli.parsers.DefaultCLIParser.java

private Map<String, Pair<Integer, Integer>> parseLines(String instanceTypeCsv)
        throws IOException, URISyntaxException, ParseException {
    InputStreamReader inputStreamReader;
    if (instanceTypeCsv.equalsIgnoreCase("classpath")) {
        inputStreamReader = new InputStreamReader(
                getClass().getClassLoader().getResourceAsStream("instancetypes.csv"), Charset.forName("UTF-8"));
    } else {/*from w w  w.  j  a  va  2s . co m*/
        URI uri = new URI(instanceTypeCsv);
        inputStreamReader = new InputStreamReader(new FileInputStream(new File(uri)), Charset.forName("UTF-8"));
    }

    CSVParser parser = null;
    List<CSVRecord> lines = null;
    try {
        parser = CSVFormat.DEFAULT.parse(new BufferedReader(inputStreamReader));
        lines = parser.getRecords();
    } finally {
        inputStreamReader.close();

        if (parser != null) {
            parser.close();
        }
    }

    if (lines == null || lines.size() <= 0) {
        throw new ParseException("instance-type-csv data is empty");
    }

    Map<String, Pair<Integer, Integer>> linesMap = new HashMap<String, Pair<Integer, Integer>>();
    for (CSVRecord current : lines) {
        linesMap.put(current.get(1), new ImmutablePair<Integer, Integer>(Integer.parseInt(current.get(2)),
                Integer.parseInt(current.get(3))));
    }

    return linesMap;
}

From source file:org.abstracthorizon.proximity.maven.MavenProximityLogic.java

/**
 * This postprocessing simply merges the fetched list of metadatas.
 * //from w w  w  .ja va2 s.c om
 * @param request the request
 * @param groupRequest the group request
 * @param listOfProxiedItems the list of proxied items
 * 
 * @return the merged metadata.
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public Item postprocessItemList(ProximityRequest request, ProximityRequest groupRequest,
        List listOfProxiedItems) throws IOException {

    if (listOfProxiedItems.size() == 0) {

        throw new IllegalArgumentException("The listOfProxiedItems list cannot be 0 length!");
    }

    Item item = (Item) listOfProxiedItems.get(0);
    ItemProperties itemProps = item.getProperties();

    if (listOfProxiedItems.size() > 1) {

        if (MavenArtifactRecognizer.isChecksum(request.getPath())) {

            File tmpFile = new File(System.getProperty("java.io.tmpdir"),
                    request.getPath().replace(ItemProperties.PATH_SEPARATOR.charAt(0), '_'));
            if (tmpFile.exists()) {
                logger.info("Item for path " + request.getPath() + " SPOOFED with merged metadata checksum.");
                item.setStream(new DeleteOnCloseFileInputStream(tmpFile));
                itemProps.setSize(tmpFile.length());
            } else {
                logger.debug("Item for path " + request.getPath() + " SPOOFED with first got from repo group.");
            }

        } else {
            logger.debug("Item for path " + request.getPath() + " found in total of "
                    + listOfProxiedItems.size() + " repositories, will merge them.");

            MetadataXpp3Reader metadataReader = new MetadataXpp3Reader();
            MetadataXpp3Writer metadataWriter = new MetadataXpp3Writer();
            InputStreamReader isr;

            Metadata mergedMetadata = null;

            for (int i = 0; i < listOfProxiedItems.size(); i++) {

                Item currentItem = (Item) listOfProxiedItems.get(i);
                try {
                    isr = new InputStreamReader(currentItem.getStream());
                    Metadata imd = metadataReader.read(isr);
                    if (mergedMetadata == null) {
                        mergedMetadata = imd;
                    } else {
                        mergedMetadata.merge(imd);
                    }
                    isr.close();
                } catch (XmlPullParserException ex) {
                    logger.warn("Could not merge M2 metadata: " + currentItem.getProperties().getDirectoryPath()
                            + " from repository " + currentItem.getProperties().getRepositoryId(), ex);
                } catch (IOException ex) {
                    logger.warn("Got IOException during merge of M2 metadata: "
                            + currentItem.getProperties().getDirectoryPath() + " from repository "
                            + currentItem.getProperties().getRepositoryId(), ex);
                }

            }

            try {
                // we know that maven-metadata.xml is relatively small
                // (few
                // KB)
                MessageDigest md5alg = MessageDigest.getInstance("md5");
                MessageDigest sha1alg = MessageDigest.getInstance("sha1");
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                DigestOutputStream md5os = new DigestOutputStream(bos, md5alg);
                DigestOutputStream sha1os = new DigestOutputStream(md5os, sha1alg);
                OutputStreamWriter osw = new OutputStreamWriter(sha1os);
                metadataWriter.write(osw, mergedMetadata);
                osw.flush();
                osw.close();

                storeDigest(request, md5alg);
                storeDigest(request, sha1alg);

                ByteArrayInputStream is = new ByteArrayInputStream(bos.toByteArray());
                item.setStream(is);
                itemProps.setSize(bos.size());
            } catch (NoSuchAlgorithmException ex) {
                throw new IllegalArgumentException("No MD5 or SHA1 algorithm?");
            }
        }

    }

    return item;
}