List of usage examples for com.google.common.io Closeables closeQuietly
public static void closeQuietly(@Nullable Reader reader)
From source file:io.smartspaces.util.io.BasicCsvReader.java
/** * Process the CSV source./*from w ww . j a v a 2 s. c o m*/ * * @param source * the source content * @param handler * the handler for each line * @param skipFirstLine * {@code true} if should skip the first line * * @throws Exception * something bad happened */ private void processSource(Reader source, ColumnSourceHandler handler, boolean skipFirstLine) throws Exception { CsvColumnSource columnSource = new CsvColumnSource(); BufferedReader reader = null; try { reader = new BufferedReader(source); if (skipFirstLine) { reader.readLine(); } String line = null; while ((line = reader.readLine()) != null) { columnSource.setLine(line); handler.processColumns(columnSource); } } finally { Closeables.closeQuietly(reader); } }
From source file:eu.operando.pq.PrivacyQuestionsService.java
/** * Load the questions from the given resource file in JAR/WAR and * turn then into JSON string.//from w ww.j a va 2 s . c o m * @return The list of questions held in the file. */ private List<Questionobject> getQuestionsFromFile(String filename) { InputStream fis = null; try { fis = this.getClass().getClassLoader().getResourceAsStream(filename); String content = CharStreams.toString(new InputStreamReader(fis, Charsets.UTF_8)); Closeables.closeQuietly(fis); ObjectMapper mapper = new ObjectMapper(); //JSON from String to Object return mapper.readValue(content, new TypeReference<List<Questionobject>>() { }); } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:com.mockey.ui.JsonSchemaLoadSamplesServlet.java
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final int index = RND.nextInt(SAMPLE_DATA_SIZE); final JsonNode ret = SAMPLE_DATA.get(index); final OutputStream out = resp.getOutputStream(); try {//from w w w. j av a 2 s . c o m out.write(ret.toString().getBytes(Charset.forName("UTF-8"))); out.flush(); } finally { Closeables.closeQuietly(out); } }
From source file:com.metamx.druid.collect.OrderedMergeSequence.java
@Override public <OutType> OutType accumulate(OutType initValue, Accumulator<OutType, T> accumulator) { Yielder<OutType> yielder = null; try {/*ww w . j av a 2s . c o m*/ yielder = toYielder(initValue, YieldingAccumulators.fromAccumulator(accumulator)); return yielder.get(); } finally { Closeables.closeQuietly(yielder); } }
From source file:org.jclouds.glesys.handlers.GleSYSErrorHandler.java
public void handleError(HttpCommand command, HttpResponse response) { // it is important to always read fully and close streams String message = parseMessage(response); Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); try {// ww w .ja v a 2 s . c o m message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: case 403: exception = new AuthorizationException(message, exception); break; case 400: if (message.indexOf("not find") != -1) { exception = new ResourceNotFoundException(message, exception); } break; case 404: if (message.indexOf("Not supported") != -1) { exception = new UnsupportedOperationException(message, exception); } else { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (message.indexOf("Locked") != -1) { exception = new IllegalStateException(message, exception); } break; } } finally { Closeables.closeQuietly(response.getPayload()); command.setException(exception); } }
From source file:org.apache.drill.exec.rpc.bit.BitComImpl.java
public void close() { Closeables.closeQuietly(server); for (BitConnectionManager bt : connectionRegistry) { bt.close(); } }
From source file:org.restexpress.pipeline.writer.FileWritingChannelFutureListener.java
@Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { LOGGER.warn("File transfer did not complete: () ", future.getCause().toString()); future.getChannel().close();/*www .jav a2 s . c om*/ Closeables.closeQuietly(inputStream); return; } buffer.clear(); buffer.writeBytes(inputStream, (int) Math.min(contentLength - offset, buffer.writableBytes())); offset += buffer.writerIndex(); HttpChunk chunk = new DefaultHttpChunk(buffer); ChannelFuture chunkWriteFuture = future.getChannel().write(chunk); // LOGGER.debug("Written {} of {}", offset, contentLength); if (offset < contentLength) { chunkWriteFuture.addListener(this); } else { ChannelFuture finalFuture = chunkWriteFuture.getChannel().write(HttpChunk.LAST_CHUNK); finalFuture.addListener(channelFutureListener); Closeables.closeQuietly(inputStream); } }
From source file:com.griddynamics.jagger.util.SerializationUtils.java
public static String toString(Serializable o) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try {//from w w w.j a va 2 s.co m if (useJBoss) { oos = new JBossObjectOutputStream(baos); } else { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); } oos.writeObject(o); } catch (IOException e) { log.error("Serialization exception ", e); throw new TechnicalException(e); } finally { String s = new String(Base64Coder.encode(baos.toByteArray())); if (s.isEmpty()) { log.info("toString({}, '{}', '{}')", new Object[] { toStringCount.getAndIncrement(), s, o }); } Closeables.closeQuietly(oos); return s; } }
From source file:gg.pistol.sweeper.i18n.XMLResourceBundleControl.java
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { Preconditions.checkNotNull(baseName); Preconditions.checkNotNull(locale);//from www . j a va 2 s . co m Preconditions.checkNotNull(format); Preconditions.checkNotNull(loader); if (!format.equals("xml")) { return null; } String bundleName = toBundleName(baseName, locale); if (bundleName == null) { return null; } String resourceName = toResourceName(bundleName, format); InputStream stream = null; if (reload) { URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); } } } else { stream = loader.getResourceAsStream(resourceName); } if (stream == null) { return null; } stream = new BufferedInputStream(stream); try { return new XMLResourceBundle(stream); } finally { Closeables.closeQuietly(stream); } }
From source file:com.xebialabs.overthere.cifs.winrm.connector.JdkHttpConnector.java
@Override public Document sendMessage(Document requestDocument, SoapAction soapAction) { try {/*from ww w. j a v a 2 s . com*/ final URLConnection urlConnection = targetURL.openConnection(); HttpURLConnection con = (HttpURLConnection) urlConnection; con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); final String authToken = tokenGenerator.generateToken(); if (authToken != null) con.addRequestProperty("Authorization", authToken); if (soapAction != null) { con.setRequestProperty("SOAPAction", soapAction.getValue()); } final String requestDocAsString = toString(requestDocument); logger.trace("Sending request to {}", targetURL); logger.trace("Request body: {} {}", targetURL, requestDocAsString); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream())); try { bw.write(requestDocAsString, 0, requestDocAsString.length()); } finally { Closeables.closeQuietly(bw); } InputStream is = null; if (con.getResponseCode() >= 400) { is = con.getErrorStream(); } if (is == null) { is = con.getInputStream(); } Writer writer = new StringWriter(); Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); try { int n; char[] buffer = new char[1024]; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { Closeables.closeQuietly(reader); Closeables.closeQuietly(is); } if (logger.isDebugEnabled()) { for (int i = 0; i < con.getHeaderFields().size(); i++) { logger.trace("Header {}: {}", con.getHeaderFieldKey(i), con.getHeaderField(i)); } } final String text = writer.toString(); logger.trace("Response body: {}", text); return DocumentHelper.parseText(text); } catch (BlankValueRuntimeException bvrte) { throw bvrte; } catch (InvalidFilePathRuntimeException ifprte) { throw ifprte; } catch (Exception e) { throw new WinRMRuntimeIOException("Send message on " + targetURL + " error ", requestDocument, null, e); } }