List of usage examples for java.io Writer flush
public abstract void flush() throws IOException;
From source file:com.day.cq.wcm.foundation.forms.FormsHelper.java
/** * Writes the given form load resource as JSON into the given writer. Can be * used in JSPs to inline JSON for javascript code, for example: * * <pre>/* w w w . java 2 s . c o m*/ * var data = <% FormsHelper.inlineValuesAsJson(slingRequest, out, "."); %>; * </pre> * * which might result in: * * <pre> * var data = { "jcr:primaryType": "nt:unstructured", "property" : "value" }; * </pre> * * <p> * If the path cannot be found, an empty object "<code>{}</code>" will be * written. Any exception will be passed to the caller. * * <p> * The underlying form load resource must be based on a JCR Node. The path * is relative and allows to specify subnodes. It cannot point to JCR * properties, please use * {@link #getValue(SlingHttpServletRequest, String, String)} or * {@link #getValues(SlingHttpServletRequest, String, String[])} for them. * * @param request * the current request * @param out * a writer, such as a {@link JspWriter}, to write the JSON into. * Will automatically be flushed before and after. * @param path * an absolute node path or a node path relativ to the current * form load resource. Use "." for the resource node itself. * @param nodeDepth * until which depth the tree should be written; 0 means the * current node and its properties only; -1 means the whole tree. * @throws RepositoryException * if some jcr error happened * @throws JSONException * if writing the json failed * @throws IOException * if there was a problem with the writer */ public static void inlineValuesAsJson(final SlingHttpServletRequest request, Writer out, String path, int nodeDepth) throws IOException, RepositoryException, JSONException { out.flush(); Node node; Session session = request.getResourceResolver().adaptTo(Session.class); if (path.startsWith("/")) { if (session.nodeExists(path)) { node = session.getNode(path); } else { // write empty object to not break javascript syntax out.append("{}"); return; } } else { Resource loadResource = FormsHelper.getFormLoadResource(request); if (loadResource == null) { out.append("{}"); return; } node = loadResource.adaptTo(Node.class); if (node == null) { out.append("{}"); return; } if (!node.hasNode(path)) { out.append("{}"); return; } node = node.getNode(path); } JsonItemWriter jsonWriter = new JsonItemWriter(null); jsonWriter.dump(node, new PrintWriter(out), nodeDepth); out.flush(); }
From source file:org.wso2.carbon.ml.rest.api.ModelApiV10.java
/** * Predict using a file and return predictions as a CSV. * @param modelId Unique id of the model * @param dataFormat Data format of the file (CSV or TSV) * @param columnHeader Whether the file contains the column header as the first row (YES or NO) * @param inputStream Input stream generated from the file used for predictions * @return A file as a {@link javax.ws.rs.core.StreamingOutput} *//*from ww w . j a v a2 s. co m*/ @POST @Path("/predictionStreams") @Produces(MediaType.APPLICATION_OCTET_STREAM) @Consumes(MediaType.MULTIPART_FORM_DATA) public Response streamingPredict(@Multipart("modelId") long modelId, @Multipart("dataFormat") String dataFormat, @Multipart("columnHeader") String columnHeader, @Multipart("file") InputStream inputStream) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); int tenantId = carbonContext.getTenantId(); String userName = carbonContext.getUsername(); try { // validate input parameters // if it is a file upload, check whether the file is sent if (inputStream == null || inputStream.available() == 0) { String msg = String.format( "Error occurred while reading the file for model [id] %s of tenant [id] %s and [user] %s .", modelId, tenantId, userName); logger.error(msg); return Response.status(Response.Status.BAD_REQUEST).entity(new MLErrorBean(msg)).build(); } final String predictions = mlModelHandler.streamingPredict(tenantId, userName, modelId, dataFormat, columnHeader, inputStream); StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream outputStream) throws IOException { Writer writer = new BufferedWriter( new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)); writer.write(predictions); writer.flush(); writer.close(); } }; return Response.ok(stream).header("Content-disposition", "attachment; filename=Predictions_" + modelId + "_" + MLUtils.getDate() + MLConstants.CSV) .build(); } catch (IOException e) { String msg = MLUtils.getErrorMsg(String.format( "Error occurred while reading the file for model [id] %s of tenant [id] %s and [user] %s.", modelId, tenantId, userName), e); logger.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(new MLErrorBean(e.getMessage())).build(); } catch (MLModelHandlerException e) { String msg = MLUtils.getErrorMsg(String.format( "Error occurred while predicting from model [id] %s of tenant [id] %s and [user] %s.", modelId, tenantId, userName), e); logger.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new MLErrorBean(e.getMessage())) .build(); } }
From source file:dk.defxws.fgssolrremote.OperationsImpl.java
private StringBuffer sendToSolr(String solrCommand, String postParameters) throws Exception { if (logger.isDebugEnabled()) logger.debug("sendToSolr solrCommand=" + solrCommand + "\nPost parameters=\n" + postParameters); String base = config.getIndexBase(indexName); URI uri = new URI(base + solrCommand); URL url = uri.toURL();/*from w w w. ja va2 s .co m*/ HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (postParameters != null) { con.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); con.setRequestMethod("POST"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); Writer writer = new OutputStreamWriter(out, "UTF-8"); Reader reader = new StringReader(postParameters); char[] buf = new char[1024]; int read = 0; while ((read = reader.read(buf)) >= 0) { writer.write(buf, 0, read); } writer.flush(); writer.close(); out.close(); } int responseCode = con.getResponseCode(); if (logger.isDebugEnabled()) logger.debug("sendToSolr solrCommand=" + solrCommand + " response Code=" + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if (logger.isDebugEnabled()) logger.debug("sendToSolr solrCommand=" + solrCommand + "\n response=" + response); return response; }
From source file:edu.duke.cabig.c3pr.web.security.SecureWebServiceHandler.java
/** * Store the certificate in a temporary file for further investigation. * //w w w . ja v a 2 s . c o m * @param cert */ private void store(X509Certificate cert, boolean binary) { try { byte[] buf = cert.getEncoded(); final File file = new File(SystemUtils.JAVA_IO_TMPDIR, "Certificate_" + System.currentTimeMillis() + ".crt"); log.error("Storing X.509 certificate in the file: " + file.getCanonicalPath()); OutputStream os = new FileOutputStream(file); if (binary) { os.write(buf); os.flush(); } else { Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8")); wr.write("-----BEGIN CERTIFICATE-----\n"); wr.write(new sun.misc.BASE64Encoder().encode(buf)); wr.write("\n-----END CERTIFICATE-----\n"); wr.flush(); } os.close(); } catch (Exception e) { log.info(e.toString(), e); } }
From source file:com.centeractive.ws.client.core.SoapClient.java
private String performTransmission(String data) throws IOException { Writer outputWriter = null; try {/* w w w .jav a2 s .com*/ outputStream = connection.getOutputStream(); outputWriter = new OutputStreamWriter(outputStream, Charset.forName("UTF-8")); outputWriter.write(data); outputWriter.flush(); inputStream = connection.getInputStream(); StringBuilder response = new StringBuilder(); int inputChar; while ((inputChar = inputStream.read()) != -1) { response.append((char) inputChar); } return response.toString(); } finally { if (outputWriter != null) { IOUtils.closeQuietly(outputWriter); } } }
From source file:com.otisbean.keyring.Ring.java
private void closeWriter(Writer writer, String outFile) throws IOException { if (outFile.equals("-")) { writer.write("\n"); writer.flush(); } else {//from w ww . j a v a 2 s.c o m writer.close(); } }
From source file:dk.deck.remoteconsole.SshRemoteConsole.java
private void output(String data, Writer liveOutput, StringBuilder output) throws IOException { if (liveOutput != null) { liveOutput.append(data);//from w w w . j a v a2s . com liveOutput.flush(); } if (output.toString().length() < MAX_CONTENT_LENGTH) { output.append(data); } }
From source file:org.kurento.test.grid.GridHandler.java
private void createRemoteScript(GridNode node, String remotePort, String remoteScript, String remoteFolder, String remoteChromeDriver, String classpath, BrowserType browser, int maxInstances) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put("remotePort", String.valueOf(remotePort)); data.put("maxInstances", String.valueOf(maxInstances)); data.put("hubIp", hubAddress); data.put("hubPort", String.valueOf(hubPort)); data.put("tmpFolder", node.getTmpFolder()); data.put("remoteChromeDriver", remoteChromeDriver); data.put("classpath", classpath); data.put("pidFile", REMOTE_PID_FILE); data.put("browser", browser); // Create script for Node Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); cfg.setClassForTemplateLoading(PerformanceTest.class, "/templates/"); String tmpScript = node.getTmpFolder() + LAUNCH_SH; try {//from w w w. j a va 2 s .com Template template = cfg.getTemplate(LAUNCH_SH + ".ftl"); Writer writer = new FileWriter(new File(tmpScript)); template.process(data, writer); writer.flush(); writer.close(); } catch (Exception e) { throw new RuntimeException("Exception while creating file from template", e); } // Copy script to remote node node.getSshConnection().scp(tmpScript, remoteScript); node.getSshConnection().execAndWaitCommand("chmod", "+x", remoteScript); Shell.runAndWait("rm", tmpScript); }
From source file:com.eyeq.pivot4j.ui.aggregator.AbstractAggregatorTestCase.java
/** * @see com.eyeq.pivot4j.AbstractIntegrationTestCase#setUp() *//* ww w. j ava 2 s .co m*/ @Override public void setUp() throws Exception { super.setUp(); PivotModel model = getPivotModel(); model.setMdx(readTestResource(getQueryName() + ".txt")); model.initialize(); Writer writer = null; File file = File.createTempFile("pivot4j-", ".html"); if (deleteTestFile) { file.deleteOnExit(); } try { writer = new FileWriter(file); HtmlRenderer renderer = new HtmlRenderer(writer); renderer.initialize(); renderer.setTableId("pivot"); renderer.setBorder(1); configureRenderer(renderer); configureAggregators(renderer); renderer.render(model); } finally { writer.flush(); IOUtils.closeQuietly(writer); } WebClient webClient = new WebClient(); HtmlPage page = webClient.getPage(file.toURI().toURL()); this.table = page.getHtmlElementById("pivot"); assertThat("Table element is not found.", table, is(notNullValue())); }