List of usage examples for java.io OutputStreamWriter write
public void write(int c) throws IOException
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. *//*www .java 2 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:gate.util.Files.java
/** * Writes aString into a temporary file located inside * the default temporary directory defined by JVM, using the specific * anEncoding./*from w w w . j ava 2 s . c o m*/ * An unique ID is generated and associated automaticaly with the file name. * @param aString the String to be written. If is null then the file will be * empty. * @param anEncoding the encoding to be used. If is null then the default * encoding will be used. * @return the tmp file containing the string. */ public static File writeTempFile(String aString, String anEncoding) throws UnsupportedEncodingException, IOException { File resourceFile = null; OutputStreamWriter writer = null; // Create a temporary file name resourceFile = File.createTempFile("gateResource", ".tmp"); resourceFile.deleteOnExit(); if (aString == null) return resourceFile; // Prepare the writer if (anEncoding == null) { // Use default encoding writer = new OutputStreamWriter(new FileOutputStream(resourceFile)); } else { // Use the specified encoding writer = new OutputStreamWriter(new FileOutputStream(resourceFile), anEncoding); } // End if // This Action is added only when a gate.Document is created. // So, is for sure that the resource is a gate.Document writer.write(aString); writer.flush(); writer.close(); return resourceFile; }
From source file:com.upnext.blekit.util.http.HttpClient.java
public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod, String payload, String payloadContentType) { try {// w w w. j a v a 2s . c om String fullUrl = urlWithParams(path != null ? url + path : url, params); L.d("[" + httpMethod + "] " + fullUrl); final URLConnection connection = new URL(fullUrl).openConnection(); if (connection instanceof HttpURLConnection) { final HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setDoInput(true); if (httpMethod != null) { httpConnection.setRequestMethod(httpMethod); if (httpMethod.equals("POST")) { connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", payloadContentType); } } else { httpConnection.setRequestMethod(params != null ? "POST" : "GET"); } httpConnection.addRequestProperty("Accept", "application/json"); httpConnection.connect(); if (payload != null) { OutputStream outputStream = httpConnection.getOutputStream(); try { if (LOG_RESPONSE) { L.d("[payload] " + payload); } OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); writer.write(payload); writer.close(); } finally { outputStream.close(); } } InputStream input = null; try { input = connection.getInputStream(); } catch (IOException e) { // workaround for Android HttpURLConnection ( IOException is thrown for 40x error codes ). final int statusCode = httpConnection.getResponseCode(); if (statusCode == -1) throw e; return new Response<T>(Error.httpError(httpConnection.getResponseCode())); } final int statusCode = httpConnection.getResponseCode(); L.d("statusCode " + statusCode); if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) { try { T value = null; if (clazz != Void.class) { if (LOG_RESPONSE || clazz == String.class) { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(input)); String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } String response = sb.toString(); if (LOG_RESPONSE) { L.d("response " + response); } if (clazz == String.class) { value = (T) response; } else { value = (T) objectMapper.readValue(response, clazz); } } else { value = (T) objectMapper.readValue(input, clazz); } } return new Response<T>(value); } catch (JsonMappingException e) { return new Response<T>(Error.serlizerError(e)); } catch (JsonParseException e) { return new Response<T>(Error.serlizerError(e)); } } else if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) { try { T def = clazz.newInstance(); if (LOG_RESPONSE) { L.d("statusCode == HttpURLConnection.HTTP_NO_CONTENT"); } return new Response<T>(def); } catch (InstantiationException e) { return new Response<T>(Error.ioError(e)); } catch (IllegalAccessException e) { return new Response<T>(Error.ioError(e)); } } else { if (LOG_RESPONSE) { L.d("error, statusCode " + statusCode); } return new Response<T>(Error.httpError(statusCode)); } } return new Response<T>(Error.ioError(new Exception("Url is not a http link"))); } catch (IOException e) { if (LOG_RESPONSE) { L.d("error, ioError " + e); } return new Response<T>(Error.ioError(e)); } }
From source file:com.contrastsecurity.ide.eclipse.core.extended.ExtendedContrastSDK.java
private HttpURLConnection makeConnection(String url, String method, Object body) throws IOException { HttpURLConnection connection = makeConnection(url, method); connection.setDoOutput(true);/*from w w w . j a v a 2s . c o m*/ connection.setRequestProperty("Content-Type", "application/json"); OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8"); osw.write(gson.toJson(body)); osw.flush(); osw.close(); os.close(); return connection; }
From source file:com.amastigote.xdu.query.module.WaterAndElectricity.java
@Override public boolean login(@NotNull String username, @NotNull String password) throws IOException { preLogin();/* w w w .j a v a 2s .c om*/ URL url = new URL(HOST + LOGIN_SUFFIX); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setInstanceFollowRedirects(false); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + ASP_dot_NET_SessionId); httpURLConnection.setRequestProperty("AjaxPro-Method", "getLoginInput"); JSONObject jsonObject = new JSONObject(); jsonObject.put("webName", username); jsonObject.put("webPass", password); httpURLConnection.connect(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream()); outputStreamWriter.write(jsonObject.toString()); outputStreamWriter.flush(); outputStreamWriter.close(); httpURLConnection.getResponseCode(); httpURLConnection.disconnect(); return checkIsLogin(username); }
From source file:com.cladonia.xngreditor.URLUtilities.java
public static void save(URL url, InputStream input, String encoding) throws IOException { // System.out.println( "URLUtilities.save( "+url+", "+encoding+")"); String password = URLUtilities.getPassword(url); String username = URLUtilities.getUsername(url); String protocol = url.getProtocol(); if (protocol.equals("ftp")) { FTPClient client = null;//from w ww. jav a2 s. c om String host = url.getHost(); client = new FTPClient(); // System.out.println( "Connecting ..."); client.connect(host); // System.out.println( "Connected."); // After connection attempt, you should check the reply code to verify // success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // System.out.println( "Disconnecting..."); client.disconnect(); throw new IOException("FTP Server \"" + host + "\" refused connection."); } // System.out.println( "Logging in ..."); if (!client.login(username, password)) { // System.out.println( "Could not log in."); // TODO bring up login dialog? client.disconnect(); throw new IOException("Could not login to FTP Server \"" + host + "\"."); } // System.out.println( "Logged in."); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); // System.out.println( "Writing output ..."); OutputStream output = client.storeFileStream(url.getFile()); // if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) { // output.close(); // client.disconnect(); // throw new IOException( "Could not transfer file \""+url.getFile()+"\"."); // } InputStreamReader reader = new InputStreamReader(input, encoding); OutputStreamWriter writer = new OutputStreamWriter(output, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); output.close(); // Must call completePendingCommand() to finish command. if (!client.completePendingCommand()) { client.disconnect(); throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } else { client.disconnect(); } } else if (protocol.equals("http") || protocol.equals("https")) { WebdavResource webdav = createWebdavResource(toString(url), username, password); if (webdav != null) { webdav.putMethod(url.getPath(), input); webdav.close(); } else { throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } } else if (protocol.equals("file")) { FileOutputStream stream = new FileOutputStream(toFile(url)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding)); InputStreamReader reader = new InputStreamReader(input, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); } else { throw new IOException("The \"" + protocol + "\" protocol is not supported."); } }
From source file:cli.Manager.java
public void save() { String out = new JSONObject().put("username", username).put("password", password) .put("signalingKey", signalingKey).put("preKeyIdOffset", preKeyIdOffset) .put("nextSignedPreKeyId", nextSignedPreKeyId).put("axolotlStore", axolotlStore.getJson()) .put("registered", registered).toString(); try {/*from ww w. j a va2s . co m*/ OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(getFileName())); writer.write(out); writer.flush(); writer.close(); } catch (Exception e) { System.err.println("Saving file error: " + e.getMessage()); } }
From source file:com.jaspersoft.jrx.query.JRXPathQueryExecuter.java
private Document getDocumentFromUrl(Map<String, ? extends JRValueParameter> parametersMap) throws Exception { // Get the url... String urlString = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_URL); // add GET parameters to the urlString... Iterator<String> i = parametersMap.keySet().iterator(); String div = "?"; URL url = new URL(urlString); if (url.getQuery() != null) div = "&"; while (i.hasNext()) { String keyName = "" + i.next(); if (keyName.startsWith("XML_GET_PARAM_")) { String paramName = keyName.substring("XML_GET_PARAM_".length()); String value = (String) getParameterValue(keyName); urlString += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); div = "&"; }/* w ww. j a v a2s . c o m*/ } url = new URL(urlString); if (url.getProtocol().toLowerCase().equals("file")) { // do nothing return JRXmlUtils.parse(url.openStream()); } else if (url.getProtocol().toLowerCase().equals("http") || url.getProtocol().toLowerCase().equals("https")) { String username = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_USERNAME); String password = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_PASSWORD); if (url.getProtocol().toLowerCase().equals("https")) { JRPropertiesUtil dPROP = PropertiesHelper.DPROP; String socketFactory = dPROP .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultSSLSocketFactory"); if (socketFactory == null) { socketFactory = dPROP.getProperty( "net.sf.jasperreports.query.executer.factory.XPath.DefaultSSLSocketFactory"); } if (socketFactory != null) { // setSSLSocketFactory HttpsURLConnection.setDefaultSSLSocketFactory( (SSLSocketFactory) Class.forName(socketFactory).newInstance()); } else { log.debug("No SSLSocketFactory defined, using default"); } String hostnameVerifyer = dPROP .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultHostnameVerifier"); if (hostnameVerifyer == null) { hostnameVerifyer = dPROP.getProperty( "net.sf.jasperreports.query.executer.factory.XPath.DefaultHostnameVerifier"); } if (hostnameVerifyer != null) { // setSSLSocketFactory HttpsURLConnection.setDefaultHostnameVerifier( (HostnameVerifier) Class.forName(hostnameVerifyer).newInstance()); } else { log.debug("No HostnameVerifier defined, using default"); } } URLConnection conn = url.openConnection(); if (username != null && username.length() > 0 && password != null) { ByteArrayInputStream bytesIn = new ByteArrayInputStream((username + ":" + password).getBytes()); ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); Base64Encoder enc = new Base64Encoder(bytesIn, dataOut); enc.process(); String encoding = dataOut.toString(); conn.setRequestProperty("Authorization", "Basic " + encoding); } // add POST parameters to the urlString... i = parametersMap.keySet().iterator(); String data = ""; div = ""; while (i.hasNext()) { String keyName = "" + i.next(); if (keyName.startsWith("XML_POST_PARAM_")) { String paramName = keyName.substring("XML_POST_PARAM_".length()); String value = (String) getParameterValue(keyName); data += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); div = "&"; } } conn.setDoOutput(true); if (data.length() > 0) { conn.setDoInput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); } try { return XMLUtils.parseNoValidation(conn.getInputStream()); } catch (SAXException e) { throw new JRException("Failed to parse the xml document", e); } catch (IOException e) { throw new JRException("Failed to parse the xml document", e); } catch (ParserConfigurationException e) { throw new JRException("Failed to create a document builder factory", e); } // return JRXmlUtils.parse(conn.getInputStream()); } else { throw new JRException("URL protocol not supported"); } }
From source file:davmail.exchange.dav.ExchangePropPatchMethod.java
protected byte[] generateRequestContent() { try {// w w w .j av a 2 s .c om // build namespace map int currentChar = 'e'; final Map<String, Integer> nameSpaceMap = new HashMap<String, Integer>(); final Set<PropertyValue> setPropertyValues = new HashSet<PropertyValue>(); final Set<PropertyValue> deletePropertyValues = new HashSet<PropertyValue>(); for (PropertyValue propertyValue : propertyValues) { // data type namespace if (!nameSpaceMap.containsKey(TYPE_NAMESPACE) && propertyValue.getTypeString() != null) { nameSpaceMap.put(TYPE_NAMESPACE, currentChar++); } // property namespace String namespaceUri = propertyValue.getNamespaceUri(); if (!nameSpaceMap.containsKey(namespaceUri)) { nameSpaceMap.put(namespaceUri, currentChar++); } if (propertyValue.getXmlEncodedValue() == null) { deletePropertyValues.add(propertyValue); } else { setPropertyValues.add(propertyValue); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8"); writer.write("<D:propertyupdate xmlns:D=\"DAV:\""); for (Map.Entry<String, Integer> mapEntry : nameSpaceMap.entrySet()) { writer.write(" xmlns:"); writer.write((char) mapEntry.getValue().intValue()); writer.write("=\""); writer.write(mapEntry.getKey()); writer.write("\""); } writer.write(">"); if (!setPropertyValues.isEmpty()) { writer.write("<D:set><D:prop>"); for (PropertyValue propertyValue : setPropertyValues) { String typeString = propertyValue.getTypeString(); char nameSpaceChar = (char) nameSpaceMap.get(propertyValue.getNamespaceUri()).intValue(); writer.write('<'); writer.write(nameSpaceChar); writer.write(':'); writer.write(propertyValue.getName()); if (typeString != null) { writer.write(' '); writer.write(nameSpaceMap.get(TYPE_NAMESPACE)); writer.write(":dt=\""); writer.write(typeString); writer.write("\""); } writer.write('>'); writer.write(propertyValue.getXmlEncodedValue()); writer.write("</"); writer.write(nameSpaceChar); writer.write(':'); writer.write(propertyValue.getName()); writer.write('>'); } writer.write("</D:prop></D:set>"); } if (!deletePropertyValues.isEmpty()) { writer.write("<D:remove><D:prop>"); for (PropertyValue propertyValue : deletePropertyValues) { char nameSpaceChar = (char) nameSpaceMap.get(propertyValue.getNamespaceUri()).intValue(); writer.write('<'); writer.write(nameSpaceChar); writer.write(':'); writer.write(propertyValue.getName()); writer.write("/>"); } writer.write("</D:prop></D:remove>"); } writer.write("</D:propertyupdate>"); writer.close(); return baos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.cprassoc.solr.auth.SolrHttpHandler.java
private String cURLRequest(String url, String data, Method method) { String result = ""; if (method == null) { method = Method.GET;//from ww w . j av a 2 s . com } try { URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); // conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); conn.setRequestMethod(method.name()); String userpass = "solr" + ":" + "SolrRocks"; String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8")); conn.setRequestProperty("Authorization", basicAuth); //String data = "{\"format\":\"json\",\"pattern\":\"#\"}"; OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); if (data != null && !data.equals("")) { out.write(data); } out.close(); // new InputStreamReader(conn.getInputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } return result; }