List of usage examples for java.io Writer flush
public abstract void flush() throws IOException;
From source file:com.netxforge.oss2.config.AmiPeerFactory.java
/** * Saves the current settings to disk// w ww. ja v a2 s .c o m * * @throws java.lang.Exception if saving settings to disk fails. */ public void saveCurrent() throws Exception { getWriteLock().lock(); try { optimize(); // Marshal to a string first, then write the string to the file. This // way the original config // isn't lost if the XML from the marshal is hosed. final StringWriter stringWriter = new StringWriter(); Marshaller.marshal(m_config, stringWriter); if (stringWriter.toString() != null) { final Writer fileWriter = new OutputStreamWriter( new FileOutputStream(ConfigFileConstants.getFile(ConfigFileConstants.AMI_CONFIG_FILE_NAME)), "UTF-8"); fileWriter.write(stringWriter.toString()); fileWriter.flush(); fileWriter.close(); } reload(); } finally { getWriteLock().unlock(); } }
From source file:com.comcast.cmb.test.tools.CNSTestingUtils.java
/** * Generate the Json string for sending different messages to different endpoitns * @param emailMessage The message to send to the email endpoints * @param emailJson The message to send to the email-json endpoints * @param defaultMessage The default message to send to the endpoints if there is no other specified * @param httpMessage The message to send to the http endpoints * @param httpsMessage The message to send to the https endpoints * @param cqsMessage The message to send to the cqs endpoints * @return the JSON string to send to the publish method *///ww w .ja va 2s.com public static String generateMultiendpointMessageJson(String emailMessage, String emailJson, String defaultMessage, String httpMessage, String httpsMessage, String cqsMessage) { ByteArrayOutputStream out = new ByteArrayOutputStream(); Writer writer = new PrintWriter(out); JSONWriter jw = new JSONWriter(writer); try { jw = jw.object(); if (defaultMessage != null) { jw.key("default").value(defaultMessage); } if (emailMessage != null) { jw.key("email").value(emailMessage); } if (emailJson != null) { jw.key("email-json").value(emailJson); } if (httpMessage != null) { jw.key("http").value(httpMessage); } if (httpsMessage != null) { jw.key("https").value(httpsMessage); } if (cqsMessage != null) { jw.key("cqs").value(cqsMessage); } jw.endObject(); writer.flush(); } catch (Exception e) { return ""; } return out.toString(); }
From source file:com.sun.faban.harness.webclient.CLIServlet.java
private void sendPending(HttpServletResponse response) throws IOException { String[] pending = RunQ.listPending(); if (pending == null) { response.sendError(HttpServletResponse.SC_NO_CONTENT, "No pending runs"); } else {//ww w . ja va 2 s . c o m Writer w = response.getWriter(); for (int i = 0; i < pending.length; i++) w.write(pending[i] + '\n'); w.flush(); w.close(); } }
From source file:org.archive.crawler.restlet.BeanBrowseResource.java
protected void writeHtml(Writer writer) { String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if (!baseRef.endsWith("/")) { baseRef += "/"; }/*from w w w. j ava 2s .c o m*/ Configuration tmpltCfg = getTemplateConfiguration(); ViewModel viewModel = new ViewModel(); viewModel.setFlashes(Flash.getFlashes(getRequest())); viewModel.put("baseRef", baseRef); viewModel.put("model", makeDataModel()); try { Template template = tmpltCfg.getTemplate("Beans.ftl"); template.process(viewModel, writer); writer.flush(); } catch (IOException e) { throw new RuntimeException(e); } catch (TemplateException e) { throw new RuntimeException(e); } }
From source file:com.ikon.util.impexp.RepositoryExporter.java
/** * Performs a recursive repository content export with metadata *//*from ww w . j a v a2 s. com*/ private static ImpExpStats exportDocumentsHelper(String token, String fldPath, File fs, String metadata, boolean history, Writer out, InfoDecorator deco) throws FileNotFoundException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException, ParseException, NoSuchGroupException, MessagingException { log.debug("exportDocumentsHelper({}, {}, {}, {}, {}, {}, {})", new Object[] { token, fldPath, fs, metadata, history, out, deco }); ImpExpStats stats = new ImpExpStats(); DocumentModule dm = ModuleManager.getDocumentModule(); FolderModule fm = ModuleManager.getFolderModule(); MailModule mm = ModuleManager.getMailModule(); MetadataAdapter ma = MetadataAdapter.getInstance(token); Gson gson = new Gson(); String path = null; File fsPath = null; if (firstTime) { path = fs.getPath(); fsPath = new File(path); firstTime = false; } else { // Repository path needs to be "corrected" under Windoze path = fs.getPath() + File.separator + PathUtils.getName(fldPath).replace(':', '_'); fsPath = new File(path); fsPath.mkdirs(); FileLogger.info(BASE_NAME, "Created folder ''{0}''", fsPath.getPath()); if (out != null) { out.write(deco.print(fldPath, 0, null)); out.flush(); } } for (Iterator<Mail> it = mm.getChildren(token, fldPath).iterator(); it.hasNext();) { Mail mailChild = it.next(); path = fsPath.getPath() + File.separator + PathUtils.getName(mailChild.getPath()).replace(':', '_'); ImpExpStats mailStats = exportMail(token, mailChild.getPath(), path + ".eml", metadata, out, deco); // Stats stats.setSize(stats.getSize() + mailStats.getSize()); stats.setMails(stats.getMails() + mailStats.getMails()); } for (Iterator<Document> it = dm.getChildren(token, fldPath).iterator(); it.hasNext();) { Document docChild = it.next(); path = fsPath.getPath() + File.separator + PathUtils.getName(docChild.getPath()).replace(':', '_'); ImpExpStats docStats = exportDocument(token, docChild.getPath(), path, metadata, history, out, deco); // Stats stats.setSize(stats.getSize() + docStats.getSize()); stats.setDocuments(stats.getDocuments() + docStats.getDocuments()); } for (Iterator<Folder> it = fm.getChildren(token, fldPath).iterator(); it.hasNext();) { Folder fldChild = it.next(); ImpExpStats tmp = exportDocumentsHelper(token, fldChild.getPath(), fsPath, metadata, history, out, deco); path = fsPath.getPath() + File.separator + PathUtils.getName(fldChild.getPath()).replace(':', '_'); // Metadata if (metadata.equals("JSON")) { FolderMetadata fmd = ma.getMetadata(fldChild); String json = gson.toJson(fmd); FileOutputStream fos = new FileOutputStream(path + Config.EXPORT_METADATA_EXT); IOUtils.write(json, fos); fos.close(); } else if (metadata.equals("XML")) { FileOutputStream fos = new FileOutputStream(path + ".xml"); FolderMetadata fmd = ma.getMetadata(fldChild); JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(FolderMetadata.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(fmd, fos); } catch (JAXBException e) { log.error(e.getMessage(), e); FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage()); } } // Stats stats.setSize(stats.getSize() + tmp.getSize()); stats.setDocuments(stats.getDocuments() + tmp.getDocuments()); stats.setFolders(stats.getFolders() + tmp.getFolders() + 1); stats.setOk(stats.isOk() && tmp.isOk()); } log.debug("exportDocumentsHelper: {}", stats); return stats; }
From source file:seava.j4e.web.controller.data.AbstractDsReadController.java
@RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_PRINT) @ResponseBody//from w ww .j av a 2s . com public String print(@PathVariable String resourceName, @PathVariable String dataFormat, @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String filterString, @RequestParam(value = Constants.REQUEST_PARAM_ADVANCED_FILTER, required = false, defaultValue = "") String filterRulesString, @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString, @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = DEFAULT_RESULT_START) int resultStart, @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = DEFAULT_RESULT_SIZE) int resultSize, @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol, @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense, @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy, @RequestParam(value = Constants.REQUEST_PARAM_EXPORT_DOWNLOAD, required = false, defaultValue = "true") Boolean exportDownload, @RequestParam(value = Constants.REQUEST_PARAM_EXPORT_INFO, required = true, defaultValue = "") String exportInfoString, HttpServletRequest request, HttpServletResponse response) throws Exception { // return null; try { if (logger.isInfoEnabled()) { logger.info("Processing request: {}.{} -> action = {} ", new Object[] { resourceName, dataFormat, Constants.DS_ACTION_PRINT }); } if (logger.isDebugEnabled()) { logger.debug(" --> request-filter: {} ", new Object[] { filterString }); logger.debug(" --> request-params: {} ", new Object[] { paramString }); logger.debug(" --> request-result-range: {} ", new Object[] { resultStart + "", (resultStart + resultSize) + "" }); } this.prepareRequest(request, response); this.authorizeDsAction(resourceName, Constants.DS_ACTION_EXPORT, null); IDsService<M, F, P> service = this.findDsService(resourceName); IDsMarshaller<M, F, P> marshaller = service.createMarshaller("json"); F filter = marshaller.readFilterFromString(filterString); P params = marshaller.readParamsFromString(paramString); ExportInfo exportInfo = marshaller.readDataFromString(exportInfoString, ExportInfo.class); exportInfo.prepare(service.getModelClass()); IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize) .addFilter(filter).addParams(params); if (orderBy != null && !orderBy.equals("")) { List<ISortToken> sortTokens = marshaller.readSortTokens(orderBy); builder.addSortInfo(sortTokens); } else { builder.addSortInfo(orderByCol, orderBySense); } if (filterRulesString != null && !filterRulesString.equals("")) { List<IFilterRule> filterRules = marshaller.readFilterRules(filterRulesString); builder.addFilterRules(filterRules); } List<M> data = service.find(builder); File _tplDir = null; String _tplName = null; String _tpl = this.getSettings().getParam(SysParam.CORE_PRINT_HTML_TPL.name()); if (_tpl == null || "".equals(_tpl)) { _tpl = "print-template/print.ftl"; } _tpl = Session.user.get().getWorkspace().getWorkspacePath() + "/" + _tpl; File _tplFile = new File(_tpl); _tplDir = _tplFile.getParentFile(); _tplName = _tplFile.getName(); if (!_tplFile.exists()) { // _tplDir = _tplFile.getParentFile(); if (!_tplDir.exists()) { _tplDir.mkdirs(); } Resource resource = new ClassPathResource("seava/j4e/web/ftl/data/print.ftl"); FileUtils.copyInputStreamToFile(resource.getInputStream(), _tplFile); } Configuration cfg = new Configuration(); cfg.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER); cfg.setDirectoryForTemplateLoading(_tplDir); Map<String, Object> root = new HashMap<String, Object>(); root.put("printer", new ModelPrinter()); root.put("data", data); root.put("filter", filter); root.put("params", params); root.put("client", Session.user.get().getClient()); Map<String, Object> reportConfig = new HashMap<String, Object>(); reportConfig.put("logo", this.getSettings().getParam(SysParam.CORE_LOGO_URL_REPORT.name())); reportConfig.put("runBy", Session.user.get().getName()); reportConfig.put("runAt", new Date()); reportConfig.put("title", exportInfo.getTitle()); reportConfig.put("orientation", exportInfo.getLayout()); reportConfig.put("columns", exportInfo.getColumns()); reportConfig.put("filter", exportInfo.getFilter()); root.put("cfg", reportConfig); if (dataFormat.equals(Constants.DATA_FORMAT_HTML)) { response.setContentType("text/html; charset=UTF-8"); } Template temp = cfg.getTemplate(_tplName); if (exportDownload) { Writer out = new OutputStreamWriter(response.getOutputStream(), response.getCharacterEncoding()); temp.process(root, out); out.flush(); return null; } else { String path = Session.user.get().getWorkspace().getTempPath(); String fileName = UUID.randomUUID().toString(); File outFile = new File(path + "/" + fileName + "." + dataFormat); Writer out = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"); temp.process(root, out); out.flush(); out.close(); // just send the file name return "{success:true, file:\"" + outFile.getName() + "\"}"; } } catch (Exception e) { e.printStackTrace(); this.handleException(e, response); return null; } finally { this.finishRequest(); } }
From source file:com.athenahealth.api.APIConnection.java
/** * Make the API call./*from w ww .ja va 2 s.c om*/ * * This method abstracts away the connection, streams, and readers necessary to make an HTTP * request. It also adds in the Authorization header and token. * * @param verb HTTP method to use * @param path URI to find * @param parameters key-value pairs of request parameters * @param headers key-value pairs of request headers * @param secondcall true if this is the retried request * @return the JSON-decoded response * * @throws AthenahealthException If there is an error making the call. * API-level errors are reported in the return-value. */ private Object call(String verb, String path, Map<String, String> parameters, Map<String, String> headers, boolean secondcall) throws AthenahealthException { try { // Join up a url and open a connection URL url = new URL(path_join(getBaseURL(), version, practiceid, path)); HttpURLConnection conn = openConnection(url); conn.setRequestMethod(verb); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // Set the Authorization header using the token, then do the rest of the headers conn.setRequestProperty("Authorization", "Bearer " + token); if (headers != null) { for (Map.Entry<String, String> pair : headers.entrySet()) { conn.setRequestProperty(pair.getKey(), pair.getValue()); } } // Set the request parameters, if there are any if (parameters != null) { conn.setDoOutput(true); Writer wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); wr.write(urlencode(parameters)); wr.flush(); wr.close(); } // If we get a 401, retry once if (conn.getResponseCode() == 401 && !secondcall) { authenticate(); return call(verb, path, parameters, headers, true); } // The API response is in the input stream on success and the error stream on failure. BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (IOException e) { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); String rawResponse = sb.toString(); if (503 == conn.getResponseCode()) throw new AthenahealthException("Service Temporarily Unavailable: " + rawResponse); if (!"application/json".equals(conn.getContentType())) throw new AthenahealthException("Expected application/json response, got " + conn.getContentType() + " instead." + " Content=" + rawResponse); // If it won't parse as an object, it'll parse as an array. Object response; try { response = new JSONObject(rawResponse); } catch (JSONException e) { try { response = new JSONArray(rawResponse); } catch (JSONException e2) { if (Boolean.getBoolean("com.athenahealth.api.dump-response-on-JSON-error")) { System.err.println("Server response code: " + conn.getResponseCode()); Map<String, List<String>> responseHeaders = conn.getHeaderFields(); for (Map.Entry<String, List<String>> header : responseHeaders.entrySet()) for (String value : header.getValue()) { if (null == header.getKey() || "".equals(header.getKey())) System.err.println("Status: " + value); else System.err.println(header.getKey() + "=" + value); } } throw new AthenahealthException( "Cannot parse response from server as JSONObject or JSONArray: " + rawResponse, e2); } } return response; } catch (MalformedURLException mue) { throw new AthenahealthException("Invalid URL", mue); } catch (IOException ioe) { throw new AthenahealthException("I/O error during call", ioe); } }
From source file:org.wso2.carbon.ml.rest.api.ModelApiV11.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 * @param percentile a threshold value used to identified cluster boundaries * @param skipDecoding whether the decoding should not be done (true or false) * @return A file as a {@link StreamingOutput} *///from w ww . j a v a 2s. c om @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, @QueryParam("percentile") double percentile, @QueryParam("skipDecoding") boolean skipDecoding) { 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( "No file found to predict with 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)) .type(MediaType.APPLICATION_JSON).build(); } final String predictions = mlModelHandler.streamingPredict(tenantId, userName, modelId, dataFormat, columnHeader, inputStream, percentile, skipDecoding); 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())) .type(MediaType.APPLICATION_JSON).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())) .type(MediaType.APPLICATION_JSON).build(); } }
From source file:org.artifactory.webapp.servlet.TraceLoggingResponse.java
/** * Writes the request info and messages to the response * * @param requestId Request trace context ID * @param methodName HTTP method name//from w w w.j av a 2 s . c om * @param username Authenticated user name * @param requestPath Request repo path id * @throws IOException */ public void sendResponse(String requestId, String methodName, String username, String requestPath) throws IOException { Writer writer = null; try { artifactoryResponse.setContentType(MediaType.TEXT_PLAIN.toString()); writer = artifactoryResponse.getWriter(); writer.append("Request ID: ").append(requestId).append("\n"); writer.append("Repo Path ID: ").append(requestPath).append("\n"); writer.append("Method Name: ").append(methodName).append("\n"); writer.append("User: ").append(username).append("\n"); writer.append("Time: ").append(time).append("\n"); writer.append("Thread: ").append(threadName).append("\n"); writer.flush(); writer.append("Steps: ").append("\n"); IOUtils.writeLines(logAggregator, null, writer); writer.flush(); artifactoryResponse.sendSuccess(); } finally { if (writer != null) { writer.close(); } } }
From source file:com.joliciel.csvLearner.features.BestFeatureFinder.java
public void writeFeatureList(Writer writer, Map<String, Collection<NameValuePair>> bestFeatureMap, int featureListSize) { try {// w w w . ja v a2s . com Set<String> features = new TreeSet<String>(); for (Collection<NameValuePair> bestFeatures : bestFeatureMap.values()) { int i = 0; for (NameValuePair pair : bestFeatures) { features.add(pair.getName()); i++; if (i == featureListSize) break; } } for (String feature : features) { writer.append(feature); writer.append("\n"); } writer.flush(); } catch (IOException ioe) { throw new RuntimeException(ioe); } }