List of usage examples for com.google.common.io Closeables closeQuietly
public static void closeQuietly(@Nullable Reader reader)
From source file:interactivespaces.service.template.internal.freemarker.FreemarkerTemplater.java
@Override public void writeTemplate(String templateName, Map<String, Object> data, File outputFile) { Writer out = null;// www . j av a 2 s. c o m try { Template template = freemarkerConfig.getTemplate(templateName); out = new FileWriter(outputFile); template.process(data, out); out.close(); } catch (Exception e) { throw new InteractiveSpacesException(String.format("Could not instantiate template %s", templateName), e); } finally { Closeables.closeQuietly(out); } }
From source file:de.blizzy.documentr.web.project.ProjectController.java
@RequestMapping(value = "/save", method = RequestMethod.POST) @PreAuthorize("projectExists(#form.name) ? " + "hasProjectPermission(#form.name, EDIT_PROJECT) : " + "hasApplicationPermission(EDIT_PROJECT)") public String saveProject(@ModelAttribute @Valid ProjectForm form, BindingResult bindingResult, Authentication authentication) throws IOException, GitAPIException { if (bindingResult.hasErrors()) { return "/project/edit"; //$NON-NLS-1$ }//w w w . j a v a2 s .c o m ILockedRepository repo = null; try { User user = userStore.getUser(authentication.getName()); repo = globalRepositoryManager.createProjectCentralRepository(form.getName(), user); } finally { Closeables.closeQuietly(repo); } return "redirect:/project/" + form.getName(); //$NON-NLS-1$ }
From source file:org.eclipse.wb.internal.core.DesignerPlugin.java
/** * Reads the contents of an {@link InputStreamReader} using the default * platform encoding and return it as a String. This method will close the * input stream./*from w w w. j a v a 2 s . c o m*/ * * @param inputStream the input stream to be read from * @param charset the charset to use * @return the String read from the stream, or null if there was an error */ public static String readFile(InputStream inputStream, Charset charset) { if (inputStream == null) { return null; } Closeable closeMe = inputStream; try { final InputStreamReader isr = new InputStreamReader(inputStream, charset); closeMe = isr; try { return CharStreams.toString(isr); } catch (Exception ioe) { // pass -- ignore files we can't read return null; } } finally { Closeables.closeQuietly(closeMe); } }
From source file:net.awired.visuwall.plugin.hudson.HudsonPlugin.java
private String getContent(URL url) { InputStream stream = null;//from w w w . ja v a 2 s. co m try { url = new URL(url.toString() + "/api/"); stream = url.openStream(); byte[] content = ByteStreams.toByteArray(stream); String xml = new String(content); return xml; } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Can't get content of " + url, e); } return ""; } finally { Closeables.closeQuietly(stream); } }
From source file:com.atoito.please.core.actions.ExecAction.java
protected void internalExecute() { M.info("running %s from wd %s", Arrays.asList(commandLine), workingDirectory); // Just call the getExecuteStreamHandler() and let it handle // the semantics of instantiation or retrieval. Execute executor = new Execute(getExecuteStreamHandler(), null); executor.setWorkingDirectory(workingDirectory); executor.setCommandline(commandLine); try {/*from www. j a v a2 s.c o m*/ executor.execute(); } catch (IOException e) { throw new PleaseException("error executing " + Arrays.asList(commandLine) + " ."); } int exit = executor.getExitValue(); M.info("executed %s , exit value = %d%n", Arrays.asList(commandLine), exit); if (showOutput) /* && (output == null)) */ { M.info("%n---%n%s%n---%n", outputStream); } Closeables.closeQuietly(outputStream); Closeables.closeQuietly(errorStream); }
From source file:de.blizzy.documentr.web.filter.TrimWriter.java
void write(String text, OutputStream out, Charset charset) throws IOException { BufferedReader in = null;/*from w w w . jav a 2 s . c o m*/ try { in = new BufferedReader(new StringReader(text)); String line; boolean textareaTag = false; boolean preTag = false; boolean notrimTag = false; boolean trim = true; while ((line = in.readLine()) != null) { String origLine = line; line = StringUtils.replace(line, "__NOTRIM__", StringUtils.EMPTY); //$NON-NLS-1$ line = StringUtils.replace(line, "__/NOTRIM__", StringUtils.EMPTY); //$NON-NLS-1$ line = REMOVE_COMMENT.replaceAll(line); if (trim) { line = TRIM_LEFT.replaceAll(line); } if (origLine.contains("<textarea")) { //$NON-NLS-1$ textareaTag = true; } if (origLine.contains("<pre")) { //$NON-NLS-1$ preTag = true; } if (origLine.contains("__NOTRIM__")) { //$NON-NLS-1$ notrimTag = true; } if (textareaTag || preTag || notrimTag) { trim = false; } if (origLine.contains("</textarea")) { //$NON-NLS-1$ textareaTag = false; } if (origLine.contains("</pre")) { //$NON-NLS-1$ preTag = false; } if (origLine.contains("__/NOTRIM__")) { //$NON-NLS-1$ notrimTag = false; } if (!textareaTag && !preTag && !notrimTag) { trim = true; } if (trim) { line = TRIM_RIGHT.replaceAll(line); } boolean doWrite = !trim || StringUtils.isNotBlank(line); if (doWrite) { writeln(line, out, charset); } } } finally { Closeables.closeQuietly(in); } }
From source file:com.elex.dmp.vectorizer.TFPartialVectorReducer.java
@Override protected void reduce(Text key, Iterable<StringTuple> values, Context context) throws IOException, InterruptedException { Iterator<StringTuple> it = values.iterator(); if (!it.hasNext()) { return;/*from w w w .j av a 2 s.c o m*/ } StringTuple value = it.next(); Vector vector = new RandomAccessSparseVector(dimension, value.length()); // guess at initial size if (maxNGramSize >= 2) { ShingleFilter sf = new ShingleFilter(new IteratorTokenStream(value.getEntries().iterator()), maxNGramSize); try { do { String term = sf.getAttribute(CharTermAttribute.class).toString(); if (!term.isEmpty() && dictionary.containsKey(term)) { // ngram int termId = dictionary.get(term); vector.setQuick(termId, vector.getQuick(termId) + 1); } } while (sf.incrementToken()); sf.end(); } finally { Closeables.closeQuietly(sf); } } else { for (String term : value.getEntries()) { if (!term.isEmpty() && dictionary.containsKey(term)) { // unigram int termId = dictionary.get(term); vector.setQuick(termId, vector.getQuick(termId) + 1); } } } if (sequentialAccess) { vector = new SequentialAccessSparseVector(vector); } if (namedVector) { vector = new NamedVector(vector, key.toString()); } // if the vector has no nonZero entries (nothing in the dictionary), let's not waste space sending it to disk. if (vector.getNumNondefaultElements() > 0) { VectorWritable vectorWritable = new VectorWritable(vector); context.write(key, vectorWritable); } else { context.getCounter("TFParticalVectorReducer", "emptyVectorCount").increment(1); } }
From source file:com.fluxcapacitor.core.server.BaseServer.java
@Override public void close() { Closeables.closeQuietly(karyonServer); Hystrix.reset(); Closeables.closeQuietly(metrics); LoggingConfiguration.getInstance().stop(); }
From source file:org.jclouds.cloudstack.handlers.CloudStackErrorHandler.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 {/*from www . j a v a2 s . c om*/ message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: exception = new IllegalArgumentException(message, exception); break; case 531: case 401: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 405: exception = new IllegalArgumentException(message, exception); break; case 409: case 431: if (message.contains("does not exist")) { exception = new ResourceNotFoundException(message, exception); } else { exception = new IllegalStateException(message, exception); } break; case 534: if (message.contains("Maximum number of resources of type")) { exception = new InsufficientResourcesException(message, exception); } break; case 537: exception = new IllegalStateException(message, exception); break; } } finally { Closeables.closeQuietly(response.getPayload()); command.setException(exception); } }
From source file:edu.isi.karma.cleaning.features.LogisticModelParameters.java
/** * Reads a model from a file.//w ww . ja v a 2 s. c om * @throws IOException If there is an error opening or closing the file. */ public static LogisticModelParameters loadFrom(File in) throws IOException { InputStream input = new FileInputStream(in); try { return loadFrom(input); } finally { Closeables.closeQuietly(input); } }