List of usage examples for java.io OutputStreamWriter close
public void close() throws IOException
From source file:at.gv.egiz.bku.binding.DataUrlConnectionImpl.java
@Override public void transmit(SLResult slResult) throws IOException { log.trace("Sending data."); if (urlEncoded) { ///* w ww . j a v a 2s . c om*/ // application/x-www-form-urlencoded (legacy, SL < 1.2) // OutputStream os = connection.getOutputStream(); OutputStreamWriter streamWriter = new OutputStreamWriter(os, HttpUtil.DEFAULT_CHARSET); // ResponseType streamWriter.write(FORMPARAM_RESPONSETYPE); streamWriter.write("="); streamWriter.write(URLEncoder.encode(DEFAULT_RESPONSETYPE, "UTF-8")); streamWriter.write("&"); // XMLResponse / Binary Response if (slResult.getResultType() == SLResultType.XML) { streamWriter.write(DataUrlConnection.FORMPARAM_XMLRESPONSE); } else { streamWriter.write(DataUrlConnection.FORMPARAM_BINARYRESPONSE); } streamWriter.write("="); streamWriter.flush(); URLEncodingWriter urlEnc = new URLEncodingWriter(streamWriter); slResult.writeTo(new StreamResult(urlEnc), false); urlEnc.flush(); // transfer parameters char[] cbuf = new char[512]; int len; for (HTTPFormParameter formParameter : httpFormParameter) { streamWriter.write("&"); streamWriter.write(URLEncoder.encode(formParameter.getName(), "UTF-8")); streamWriter.write("="); InputStreamReader reader = new InputStreamReader(formParameter.getData(), (formParameter.getCharSet() != null) ? formParameter.getCharSet() : "UTF-8"); // assume request was // application/x-www-form-urlencoded, // formParam therefore UTF-8 while ((len = reader.read(cbuf)) != -1) { urlEnc.write(cbuf, 0, len); } urlEnc.flush(); } streamWriter.close(); } else { // // multipart/form-data (conforming to SL 1.2) // ArrayList<Part> parts = new ArrayList<Part>(); // ResponseType StringPart responseType = new StringPart(FORMPARAM_RESPONSETYPE, DEFAULT_RESPONSETYPE, "UTF-8"); responseType.setTransferEncoding(null); parts.add(responseType); // XMLResponse / Binary Response SLResultPart slResultPart = new SLResultPart(slResult, XML_RESPONSE_ENCODING); if (slResult.getResultType() == SLResultType.XML) { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); slResultPart.setCharSet(XML_RESPONSE_ENCODING); } else { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); } parts.add(slResultPart); // transfer parameters for (HTTPFormParameter formParameter : httpFormParameter) { InputStreamPartSource source = new InputStreamPartSource(null, formParameter.getData()); FilePart part = new FilePart(formParameter.getName(), source, formParameter.getContentType(), formParameter.getCharSet()); part.setTransferEncoding(formParameter.getTransferEncoding()); parts.add(part); } OutputStream os = connection.getOutputStream(); Part.sendParts(os, parts.toArray(new Part[parts.size()]), boundary.getBytes()); os.close(); } // MultipartRequestEntity PostMethod InputStream is = null; try { is = connection.getInputStream(); } catch (IOException iox) { log.info("Failed to get InputStream of HTTPUrlConnection.", iox); } log.trace("Reading response."); response = new DataUrlResponse(url.toString(), connection.getResponseCode(), is); Map<String, String> responseHttpHeaders = new HashMap<String, String>(); Map<String, List<String>> httpHeaders = connection.getHeaderFields(); for (Iterator<String> keyIt = httpHeaders.keySet().iterator(); keyIt.hasNext();) { String key = keyIt.next(); StringBuffer value = new StringBuffer(); for (String val : httpHeaders.get(key)) { value.append(val); value.append(HttpUtil.SEPARATOR[0]); } String valString = value.substring(0, value.length() - 1); if ((key != null) && (value.length() > 0)) { responseHttpHeaders.put(key, valString); } } response.setResponseHttpHeaders(responseHttpHeaders); }
From source file:openscience.crowdsource.experiments.MainActivity.java
/*************************************************************************/ /* read one string file */ private boolean save_one_string_file(String fname, String text) { FileOutputStream o = null;//from w ww. j a v a 2s . com try { o = new FileOutputStream(fname, false); } catch (FileNotFoundException e) { return false; } OutputStreamWriter oo = new OutputStreamWriter(o); try { oo.append(text); oo.flush(); oo.close(); } catch (IOException e) { return false; } return true; }
From source file:com.ibm.domino.das.resources.DocumentResource.java
@GET @Produces(MediaType.APPLICATION_JSON)/*from w ww . j a va2 s. c om*/ public Response getDocumentByUnid(@Context final UriInfo uriInfo, @PathParam(PARAM_UNID) final String unid, @HeaderParam(HEADER_IF_MODIFIED_SINCE) final String ifModifiedSince, @QueryParam(PARAM_COMPACT) final boolean compact, @QueryParam(PARAM_DOC_STRONGTYPE) final boolean strongType, @QueryParam(PARAM_DOC_HIDDEN) final boolean hidden, @QueryParam(PARAM_DOC_MARKREAD) final String markRead, @QueryParam(PARAM_DOC_MULTIPART) final String multipart, @QueryParam(PARAM_DOC_LOWERCASEFIELDS) final boolean lowercaseItems, @QueryParam(PARAM_DOC_FIELDS) final String items) { DAS_LOGGER.traceEntry(this, "getDocumentByUnid"); // $NON-NLS-1$ final ResponseBuilder builder = Response.ok(); abstract class StreamingOutputImpl implements StreamingOutput { Response response = null; public void setResponse(Response response) { this.response = response; } } StreamingOutputImpl streamJsonEntity = new StreamingOutputImpl() { // @Override public void write(OutputStream outputStream) throws IOException { Document document = null; try { Database database = getDatabase(DB_ACCESS_VIEWS_DOCS); try { document = database.getDocumentByUNID(unid); } catch (NotesException e) { throw new WebApplicationException( ErrorHelper.createErrorResponse(e, Response.Status.NOT_FOUND)); } URI baseUri = UriHelper.copy(uriInfo.getAbsolutePath(), DataService.isUseRelativeUrls()); //Unid don't contain special characters, so don't need encode baseUri = UriHelper.trimAtLast(baseUri, PARAM_SEPERATOR + unid); OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream); String lastModifiedHeader = ifModifiedSince(document, ifModifiedSince); if (lastModifiedHeader != null) { response.getMetadata().add(HEADER_LAST_MODIFIED, lastModifiedHeader); } JsonWriter jsonWriter = new JsonWriter(streamWriter, compact); JsonDocumentContent content = new JsonDocumentContent(document); int sysItems = DocumentParameters.SYS_ITEM_ALL; String rtType = TYPE_MULTIPART; // Handle parameters if (!hidden) { sysItems &= ~DocumentParameters.SYS_ITEM_HIDDEN; } if (multipart != null && multipart.compareToIgnoreCase(PARAM_VALUE_FALSE) == 0) { rtType = TYPE_RICHTEXT; // Deprecated } List<String> defItemFilter = null; if (StringUtil.isNotEmpty(items)) { defItemFilter = DataService.getParameterStringList(PARAM_DOC_FIELDS, items); } try { content.writeDocumentAsJson(jsonWriter, sysItems, true, defItemFilter, lowercaseItems, null, strongType, rtType, baseUri.toString()); } finally { jsonWriter.flush(); } // Handle parameters. if (markRead == null || markRead.compareToIgnoreCase(PARAM_VALUE_TRUE) == 0) { document.markRead(); } else if (markRead.compareToIgnoreCase(PARAM_VALUE_FALSE) != 0) { throw new WebApplicationException( ErrorHelper.createErrorResponse("Invalid parameter.", Response.Status.BAD_REQUEST)); // $NLX-DocumentResource.Invalidparameter-1$ } streamWriter.close(); } catch (NotesException e) { throw new WebApplicationException( ErrorHelper.createErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (ServiceException e) { throw new WebApplicationException( ErrorHelper.createErrorResponse(e, Response.Status.BAD_REQUEST)); } finally { if (document != null) { try { document.recycle(); } catch (NotesException e) { // Ignore } } } } }; builder.type(MediaType.APPLICATION_JSON_TYPE).entity(streamJsonEntity); Response response = builder.build(); streamJsonEntity.setResponse(response); DAS_LOGGER.traceExit(this, "getDocumentByUnid", response); // $NON-NLS-1$ return response; }
From source file:com.knowgate.dfs.FileSystem.java
/** * Write a String to a text file using given encoding * @param sFilePath Full file path. For example "file:///tmp/myfile.txt" or "ftp://localhost:21/tmp/myfile.txt" * @param sText String to be written//from ww w. j a va 2 s .com * @param sEncoding Encoding to be used * see <a href="http://java.sun.com/j2se/1.4.2/docs/guide/intl/encoding.doc.html">Java Supported Encodings</a> * @throws IOException * @throws OutOfMemoryError */ public void writefilestr(String sFilePath, String sText, String sEncoding) throws IOException, OutOfMemoryError { if (DebugFile.trace) { DebugFile.writeln("Begin FileSystem.writefilestr(" + sFilePath + ", ..., " + sEncoding + ")"); DebugFile.incIdent(); } String sLower = sFilePath.toLowerCase(); if (sLower.startsWith("file://")) sFilePath = sFilePath.substring(7); if (sLower.startsWith("ftp://")) { FTPClient oFTPC = null; boolean bFTPSession = false; splitURI(sFilePath); try { if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")"); oFTPC = new FTPClient(sHost); if (DebugFile.trace) DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")"); oFTPC.login(sUsr, sPwd); bFTPSession = true; if (DebugFile.trace) DebugFile.writeln("FTPClient.chdir(" + sPath + ")"); oFTPC.chdir(sPath); oFTPC.setType(FTPTransferType.BINARY); if (DebugFile.trace) DebugFile.writeln("FTPClient.put(byte[], " + sFile + ")"); oFTPC.put(sText.getBytes(sEncoding), sFile); } catch (FTPException ftpe) { throw new IOException(ftpe.getMessage()); } finally { if (DebugFile.trace) DebugFile.writeln("FTPClient.quit()"); try { if (bFTPSession) oFTPC.quit(); } catch (Exception ignore) { } } } else { FileOutputStream oOutStrm = new FileOutputStream(sFilePath); if (sText.length() > 0) { BufferedOutputStream oBFStrm = new BufferedOutputStream(oOutStrm, sText.length()); OutputStreamWriter oWriter = new OutputStreamWriter(oBFStrm, sEncoding); oWriter.write(sText); oWriter.close(); oBFStrm.close(); } // fi (sText!="") oOutStrm.close(); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End FileSystem.writefilestr()"); } }
From source file:eionet.cr.web.util.TriplesToOutputStream.java
/** * * @param out/* w w w .jav a 2 s.c o m*/ * @param subjectUri * @param triples */ public static void triplesToHtml(OutputStream out, String subjectUri, List<SubjectDTO> triples) { OutputStreamWriter writer = new OutputStreamWriter(out); try { writer.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en-gb\">"); writer.append("<head>"); writer.append("<title>").append(subjectUri).append("</title>"); writer.append("<link rel=\"alternate\" type=\"application/rdf+xml\" href=\"").append(subjectUri) .append("\" />"); writer.append("<style type=\"text/css\">" + "/*<![CDATA[*/ " + "table { border: 1px solid black; border-collapse:collapse; } " + "td, th { border: 1px solid black; padding: 0.3em; } " + "/*]]>*/" + "</style>"); writer.append("</head>"); writer.append("<body>"); writer.append("<h1>").append(subjectUri).append("</h1>"); writer.append("<table>"); writer.append("<tr><th>Subject</th><th>Predicate</th><th>Value</th></tr>"); if (triples != null) { for (SubjectDTO subject : triples) { Map<String, Collection<ObjectDTO>> predicates = subject.getPredicates(); if (predicates != null) { for (String predicateUri : predicates.keySet()) { Collection<ObjectDTO> objects = predicates.get(predicateUri); if (objects != null) { for (ObjectDTO object : objects) { writer.append("<tr>"); writer.append("<td>"); writer.append("<a href=\"").append(subject.getUri()).append("\">"); writer.append(subject.getUri()); writer.append("</a>"); writer.append("</td>"); writer.append("<td>").append(predicateUri).append("</td>"); writer.append("<td>"); if (object.isLiteral()) { writer.append(object.getValue()); } else { writer.append("<a href=\"").append(object.getValue()).append("\">") .append(object.getValue()).append("</a>"); } writer.append("</td>"); writer.append("</tr>"); } } } } } /* * for (TripleDTO triple : triples) { writer.append("<tr>"); * writer.append("<td>").append(triple.getSubjectUri()).append("</td>"); * writer.append("<td>").append(triple.getPredicateUri()).append("</td>"); * writer.append("<td>").append(triple.getObject()).append("</td>"); writer.append("</tr>"); } */ } writer.append("</table>"); writer.append("</body>"); writer.append("</html>"); writer.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { writer.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.cloud.bridge.service.EC2RestServlet.java
/** * Send out an error response according to Amazon convention. *///from w w w. ja va 2 s . c om private void faultResponse(HttpServletResponse response, String errorCode, String errorMessage) { try { OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream()); response.setContentType("text/xml; charset=UTF-8"); out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.write("<Response><Errors><Error><Code>"); out.write(errorCode); out.write("</Code><Message>"); out.write(errorMessage); out.write("</Message></Error></Errors><RequestID>"); out.write(UUID.randomUUID().toString()); out.write("</RequestID></Response>"); out.flush(); out.close(); } catch (IOException e) { logger.error("Unexpected exception " + e.getMessage(), e); } }
From source file:org.smilec.smile.student.CourseList.java
private void logError(String url, String err) { boolean reachable = false; String internetTest = ""; String str = ""; Date now = new Date(); internetTest = now.toString() + ", loading page " + url + " error: " + err + "\n"; ;/* w w w . ja va 2s. c om*/ System.out.println(internetTest); try { //test router //InetAddress address = InetAddress.getByName("192.168.2.1"); byte[] b = new byte[] { (byte) 192, (byte) 168, (byte) 2, (byte) 1 }; InetAddress address = InetAddress.getByAddress(b); // Try to reach the specified address within the timeout // periode. If during this periode the address cannot be // reach then the method returns false. reachable = address.isReachable(5000); // 5 seconds } catch (Exception e) { reachable = false; e.printStackTrace(); } str = "Is router (192.168.2.1) reachable? " + reachable + "\n"; System.out.println(str); internetTest += str; try { //test server InetAddress address = InetAddress.getByName(cururi); reachable = address.isReachable(5000); } catch (Exception e) { reachable = false; e.printStackTrace(); } str = "Is host reachable? " + reachable + "\n"; System.out.println(str); internetTest += str; String received = ""; int statusCode = 0; try { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); // until first connection HttpConnectionParams.setSoTimeout(params, 5000); // 10000 ms socket timeout --? no time out for socket HttpClient httpclient = new DefaultHttpClient(params); HttpGet httpget; httpget = new HttpGet("http://" + cururi); HttpResponse response = httpclient.execute(httpget); statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 404) { // server not ready // do nothing throw new Exception("" + response.getStatusLine()); } else if ((statusCode / 100) != 2) { throw new Exception("" + response.getStatusLine()); } else { BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line; StringBuffer sb = new StringBuffer(""); while ((line = in.readLine()) != null) { sb.append(line); } received = sb.toString(); if (received != null && received.length() > 0) reachable = true; received = "http status code: " + statusCode; } } catch (Exception e) { //e.printStackTrace(); received = "loading error, http status code: " + statusCode; reachable = false; } str = "Is Apache reachable? " + reachable + ", " + received + "\n"; System.out.println(str); internetTest += str; try { // open myfilename.txt for writing Log.d("Write log Err", "Start writing error log"); OutputStreamWriter out = new OutputStreamWriter(openFileOutput("smileErrorLog.txt", 0)); out.write(internetTest); out.close(); Log.d("Write log Err", "Writing error log finished."); } catch (java.io.IOException e) { //do something if an IOException occurs. Log.d("Write log Error", "ERROR"); e.printStackTrace(); } }
From source file:org.kew.rmf.reconciliation.ws.MatchController.java
/** * Matches the records in the uploaded file. * * Results are put into a temporary file (available for download) and also shown in the web page. *//*from w ww.ja v a2 s.c o m*/ @RequestMapping(value = "/filematch/{configName}", method = RequestMethod.POST) public String doFileMatch(@PathVariable String configName, @RequestParam("file") MultipartFile file, HttpServletResponse response, Model model) { logger.info("{}: File match query {}", configName, file); // Map of matches // Key is the ID of supplied records // Entries are a List of Map<String,String> Map<String, List<Map<String, String>>> matches = new HashMap<String, List<Map<String, String>>>(); // Map of supplied data (useful for display) List<Map<String, String>> suppliedData = new ArrayList<Map<String, String>>(); // Temporary file for results File resultsFile; List<String> properties = new ArrayList<String>(); if (!file.isEmpty()) { try { logger.debug("Looking for : " + configName); LuceneMatcher matcher = reconciliationService.getMatcher(configName); if (matcher != null) { resultsFile = File.createTempFile("match-results-", ".csv"); OutputStreamWriter resultsFileWriter = new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8"); resultsFileWriter.write("queryId,matchId\n"); // TODO: attempt to use same line ending as input file // Save the property names: for (Property p : matcher.getConfig().getProperties()) { properties.add(p.getQueryColumnName()); } CsvPreference customCsvPref = new CsvPreference.Builder('"', ',', "\n").build(); CsvMapReader mr = new CsvMapReader(new InputStreamReader(file.getInputStream(), "UTF-8"), customCsvPref); final String[] header = mr.getHeader(true); Map<String, String> record = null; while ((record = mr.read(header)) != null) { logger.debug("Next record is {}", record); suppliedData.add(record); try { List<Map<String, String>> theseMatches = matcher.getMatches(record); // Just write out some matches to std out: if (theseMatches != null) { logger.debug("Record ID {}, matched: {}", record.get("id"), theseMatches.size()); } else { logger.debug("Record ID {}, matched: null", record.get("id")); } matches.put(record.get("id"), theseMatches); // Append matche results to file StringBuilder sb = new StringBuilder(); for (Map<String, String> result : theseMatches) { if (sb.length() > 0) sb.append('|'); sb.append(result.get("id")); } sb.insert(0, ',').insert(0, record.get("id")).append("\n"); resultsFileWriter.write(sb.toString()); } catch (TooManyMatchesException | MatchExecutionException e) { logger.error("Problem handling match", e); } } mr.close(); resultsFileWriter.close(); logger.debug("got file's bytes"); model.addAttribute("resultsFile", resultsFile.getName()); response.setHeader("X-File-Download", resultsFile.getName()); // Putting this in a header saves the unit tests from needing to parse the HTML. } model.addAttribute("suppliedData", suppliedData); model.addAttribute("matches", matches); model.addAttribute("properties", properties); } catch (Exception e) { logger.error("Problem reading file", e); } } return "file-matcher-results"; }
From source file:fr.paris.lutece.portal.web.user.AdminUserJspBeanTest.java
public void testDoImportUsersFromFileNoToken() throws AccessDeniedException, UserNotSignedException, IOException { AdminUserJspBean bean = new AdminUserJspBean(); MockHttpServletRequest request = new MockHttpServletRequest(); AdminUser user = getUserToModify();/* ww w . jav a2 s . c o m*/ AdminAuthenticationService.getInstance().registerUser(request, user); bean.init(request, "CORE_USERS_MANAGEMENT"); Map<String, List<FileItem>> multipartFiles = new HashMap<>(); List<FileItem> fileItems = new ArrayList<>(); FileItem file = new DiskFileItem("import_file", "application/csv", true, "junit.csv", 1024, new File(System.getProperty("java.io.tmpdir"))); OutputStreamWriter writer = new OutputStreamWriter(file.getOutputStream(), Charset.forName("UTF-8")); writer.write( "test;test;test;test@test.fr;" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;"); writer.close(); fileItems.add(file); multipartFiles.put("import_file", fileItems); Map<String, String[]> parameters = request.getParameterMap(); MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, multipartFiles, parameters); bean.getImportUsersFromFile(request); // initialize _importAdminUserService AdminUser importedUser = null; try { bean.doImportUsersFromFile(multipartRequest); fail("Should have thrown"); } catch (AccessDeniedException e) { importedUser = AdminUserHome.findUserByLogin("test"); assertNull(importedUser); } finally { if (importedUser != null) { disposeOfUser(importedUser); } disposeOfUser(user); } }
From source file:fr.paris.lutece.portal.web.user.AdminUserJspBeanTest.java
public void testDoImportUsersFromFileInvalidToken() throws AccessDeniedException, UserNotSignedException, IOException { AdminUserJspBean bean = new AdminUserJspBean(); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance().getToken(request, "jsp/admin/user/ImportUser.jsp") + "b"); AdminUser user = getUserToModify();//from w ww .ja v a 2 s .c om AdminAuthenticationService.getInstance().registerUser(request, user); bean.init(request, "CORE_USERS_MANAGEMENT"); Map<String, List<FileItem>> multipartFiles = new HashMap<>(); List<FileItem> fileItems = new ArrayList<>(); FileItem file = new DiskFileItem("import_file", "application/csv", true, "junit.csv", 1024, new File(System.getProperty("java.io.tmpdir"))); OutputStreamWriter writer = new OutputStreamWriter(file.getOutputStream(), Charset.forName("UTF-8")); writer.write( "test;test;test;test@test.fr;" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;"); writer.close(); fileItems.add(file); multipartFiles.put("import_file", fileItems); Map<String, String[]> parameters = request.getParameterMap(); MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, multipartFiles, parameters); bean.getImportUsersFromFile(request); // initialize _importAdminUserService AdminUser importedUser = null; try { bean.doImportUsersFromFile(multipartRequest); fail("Should have thrown"); } catch (AccessDeniedException e) { importedUser = AdminUserHome.findUserByLogin("test"); assertNull(importedUser); } finally { if (importedUser != null) { disposeOfUser(importedUser); } disposeOfUser(user); } }