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:br.cefetrj.sagitarii.teapot.comm.WebClient.java

public String doGet(String action, String parameter) throws Exception {
    String resposta = "SEM_RESPOSTA";
    String mhpHost = gf.getHostURL();
    String url = mhpHost + "/" + action + "?" + parameter;

    DefaultHttpClient httpClient = new DefaultHttpClient();

    if (gf.useProxy()) {
        if (gf.getProxyInfo() != null) {
            HttpHost httpproxy = new HttpHost(gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort());
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort()),
                    new UsernamePasswordCredentials(gf.getProxyInfo().getUser(),
                            gf.getProxyInfo().getPassword()));
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpproxy);
        }/*from  w  w w .j a  v  a  2s .  c  o  m*/
    }

    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    HttpGet getRequest = new HttpGet(url);
    getRequest.addHeader("accept", "application/json");
    getRequest.addHeader("Content-Type", "plain/text; charset=utf-8");

    HttpResponse response = httpClient.execute(getRequest);
    response.setHeader("Content-Type", "plain/text; charset=UTF-8");

    int stCode = response.getStatusLine().getStatusCode();
    if (stCode != 200) {
        System.out.println("Sagitarii nao recebeu meu anuncio. Codigo de erro " + stCode);
        System.out.println(url);
    } else {
        HttpEntity entity = response.getEntity();
        InputStreamReader isr = new InputStreamReader(entity.getContent(), "UTF-8");
        resposta = convertStreamToString(isr);
        Charset.forName("UTF-8").encode(resposta);
        httpClient.getConnectionManager().shutdown();
        isr.close();
    }

    return resposta;
}

From source file:info.magnolia.module.model.reader.BetwixtModuleDefinitionReader.java

@Override
public ModuleDefinition readFromResource(String resourcePath) throws ModuleManagementException {
    final InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(resourcePath));
    try {//w w  w  .j  a va  2s.c om
        return read(reader);
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            log.error("Can't close input for " + resourcePath);
        }
    }
}

From source file:io.personium.common.utils.PersoniumCoreUtils.java

/**
 * InputStream?????String??./*www .j  av  a 2s.  com*/
 * @param is InputStream
 * @return 
 */
public static String readInputStreamAsString(InputStream is) {

    InputStreamReader isr = null;
    BufferedReader reader = null;
    String bodyString = null;
    try {

        isr = new InputStreamReader(is, "UTF-8");
        reader = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        int chr;
        while ((chr = is.read()) != -1) {
            sb.append((char) chr);
        }
        bodyString = sb.toString();
    } catch (IllegalStateException e) {
        log.info(e.getMessage());
    } catch (IOException e) {
        log.info(e.getMessage());
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            log.info(e.getMessage());
        }
    }

    return bodyString;
}

From source file:com.mpower.clientcollection.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString/*w ww . ja  v  a 2 s .  c  o m*/
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);
    //req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                ClientCollection.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                Header contentEncoding = entity.getContentEncoding();
                if (contentEncoding != null
                        && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING)) {
                    is = new GZIPInputStream(is);
                }
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:Engine.Lua.PlayerLua.java

public PlayerLua(String luaFile) {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine scriptEngine = sem.getEngineByName("luaj");
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("Scripts/" + luaFile);
    InputStreamReader isr = new InputStreamReader(is);
    CompiledScript script;//from w  w w.  j av a  2s.co m
    try {
        script = ((Compilable) scriptEngine).compile(isr);
        isr.close();
        is.close();
        sb = new SimpleBindings();
        script.eval(sb); // Put the Lua functions into the sb environment
    } catch (ScriptException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.michelin.cio.hudson.plugins.qc.client.QualityCenterClientInstaller.java

public void install(Launcher launcher, TaskListener log, String expectedLocation, FilePath qcBundle)
        throws IOException, InterruptedException {
    PrintStream out = log.getLogger();
    String qcBundleName = qcBundle.getName();
    String qcBundlePath = qcBundle.absolutize().getRemote();

    out.println(Messages.QualityCenterClientInstaller_Installing(qcBundleName));
    String logFile = qcBundlePath + ".install.log";

    StringBuilder cmd = new StringBuilder();
    cmd.append('"').append(qcBundlePath).append('"');
    cmd.append(" /qn /norestart TARGETDIR=");
    cmd.append('"').append(expectedLocation).append('"');
    cmd.append(" /l ");
    cmd.append('"').append(logFile).append('"');

    // Run the install on the node
    // The result must be 0
    ArgumentListBuilder args = new ArgumentListBuilder().add("cmd.exe", "/C").addQuoted(cmd.toString());
    if (launcher.launch().cmds(args).stdout(out).pwd(expectedLocation).join() != 0) {
        log.fatalError(Messages.QualityCenterClientInstaller_AbortedInstall());
        // log file is in UTF-16
        InputStream is = new FileInputStream(logFile);
        InputStreamReader in = new InputStreamReader(is, "UTF-16");
        try {//from   w ww.  jav  a  2 s.co m
            IOUtils.copy(in, new OutputStreamWriter(out));
        } finally {
            in.close();
            is.close();
        }
        throw new AbortException();
    }

    out.println(Messages.QualityCenterClientInstaller_InstallationSuccessfull());
}

From source file:Engine.Lua.PlayerLua.java

public void tester(String luaFile) {
    Dog dog = new Dog("Rex");
    Cat cat = new Cat("Felix");
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine scriptEngine = sem.getEngineByName("luaj");
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("Scripts/" + luaFile);
    InputStreamReader isr = new InputStreamReader(is);
    CompiledScript script;//from   w  ww  .  j  a  va2s. c o m
    try {
        script = ((Compilable) scriptEngine).compile(isr);
        isr.close();
        is.close();
        Bindings sb = new SimpleBindings();
        script.eval(sb); // Put the Lua functions into the sb environment
        LuaValue luaDog = CoerceJavaToLua.coerce(dog); // Java to Lua
        //CoerceLuaToJava()
        LuaFunction onTalk = (LuaFunction) sb.get("onTalk"); // Get Lua function
        LuaValue b = onTalk.call(luaDog); // Call the function
        System.out.println("onTalk answered: " + b);
        LuaFunction onWalk = (LuaFunction) sb.get("onWalk");
        LuaValue[] dogs = { luaDog };
        Varargs dist = onWalk.invoke(LuaValue.varargsOf(dogs)); // Alternative

        System.out.println("onWalk returned: " + dist);

        Dog retunredDog = (Dog) CoerceLuaToJava.coerce(luaDog, Dog.class);
        System.out.println("AAAAAAAAAa:" + retunredDog.name);
    } catch (ScriptException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.alfresco.module.vti.web.actions.VtiWelcomeInfoAction.java

/**
 * <p>Return the information to determine the entry point for 
 * the Microsoft FrontPage Server Extensions.</p> 
 *
 * @param request HTTP request//from   w ww.  ja  v  a2  s.c  o m
 * @param response HTTP response
 */
public void execute(HttpServletRequest request, HttpServletResponse response) {
    // Build the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("alfrescoUrl", UrlUtil.getAlfrescoUrl(sysAdminParams));
    model.put("shareUrl", UrlUtil.getShareUrl(sysAdminParams));
    model.put("vtiUrl", getVtiUrl(request));

    // Get the welcome template
    InputStream templateStream = getClass().getResourceAsStream(template);
    if (templateStream == null) {
        logger.warn("Welcome template missing: " + template);
        return;
    }
    StringBuilder template = new StringBuilder();
    try {
        InputStreamReader r = new InputStreamReader(templateStream, Charset.forName("UTF-8"));
        int read;
        char[] c = new char[4096];
        while ((read = r.read(c)) != -1) {
            template.append(c, 0, read);
        }
        r.close();
    } catch (IOException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Action IO exception", e);
        }
    } finally {
        try {
            templateStream.close();
        } catch (Exception e) {
        }
    }

    try {
        String res = templateService.processTemplateString("freemarker", template.toString(), model);
        PrintWriter r = response.getWriter();
        r.append(res);
        r.close();
    } catch (IOException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Action IO exception", e);
        }
    }
}

From source file:com.jaeksoft.searchlib.analysis.synonym.SynonymMap.java

private void loadFromFile(File file) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line;/*from w  w w.  ja  v a 2s.  c  o m*/
    while ((line = br.readLine()) != null) {
        String[] terms = splitTerms(line);
        for (String key : terms)
            expressionMap.add(key, terms);
        size++;
    }
    br.close();
    isr.close();
    fis.close();
}

From source file:org.opendatakit.utils.WebUtils.java

private static String readResponseHelper(InputStream content) {
    StringBuffer response = new StringBuffer();

    if (content != null) {
        // TODO: this section of code is possibly causing 'WARNING: Going to
        // buffer
        // response body of large or unknown size. Using getResponseBodyAsStream
        // instead is recommended.'
        // The WARNING is most likely only happening when running appengine
        // locally,
        // but we should investigate to make sure
        BufferedReader reader = null;
        InputStreamReader isr = null;
        try {/* w  w w  . java2  s  . co m*/
            reader = new BufferedReader(isr = new InputStreamReader(content, BasicConsts.UTF8_ENCODE));
            String responseLine;
            while ((responseLine = reader.readLine()) != null) {
                response.append(responseLine);
            }
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        } catch (IllegalStateException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                // no-op
            }
            try {
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException ex) {
                // no-op
            }
        }
    }
    return response.toString();
}