List of usage examples for java.io OutputStreamWriter write
public void write(int c) throws IOException
From source file:com.domsplace.DomsCommandsXenforoAddon.Threads.XenforoUpdateThread.java
@Override public void run() { debug("THREAD STARTED"); long start = getNow(); while (start + TIMEOUT <= getNow() && player == null) { }//ww w .j ava 2s. c o m this.stopThread(); this.deregister(); if (player == null) return; boolean alreadyActivated = false; boolean isActivated = false; try { String x = player.getSavedVariable("xenforo"); alreadyActivated = x.equalsIgnoreCase("yes"); } catch (Exception e) { } try { String url = XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", "") + APPEND; if (url.equals(APPEND)) return; String encodedData = "name=" + encode("username") + "&value=" + encode(this.player.getPlayer()) + "&_xfResponseType=json"; //String rawData = "name=username"; String type = "application/x-www-form-urlencoded; charset=UTF-8"; //String encodedData = URLEncoder.encode(rawData, "ISO-8859-1"); URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", type); conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length())); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Referer", XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", "")); conn.setUseCaches(false); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(encodedData); wr.flush(); InputStream in = conn.getInputStream(); BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); String out = responseStrBuilder.toString(); JSONObject o = (JSONObject) JSONValue.parse(out); try { isActivated = o.get("_redirectMessage").toString().equalsIgnoreCase("ok"); } catch (NullPointerException e) { isActivated = true; } debug("GOT: " + isActivated); } catch (Exception e) { if (DebugMode) e.printStackTrace(); return; } player.setSavedVariable("xenforo", (isActivated ? "yes" : "no")); player.save(); if (isActivated && !alreadyActivated) { runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onRegistered")); } if (!isActivated && alreadyActivated) { runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onDeRegistered")); } }
From source file:pl.maciejwalkowiak.plist.spring.PlistHttpMessageConverter.java
@Override protected void writeInternal(Object o, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException { Charset charset = getCharset(httpOutputMessage.getHeaders()); OutputStreamWriter writer = new OutputStreamWriter(httpOutputMessage.getBody(), charset); String result = addHeader ? plistSerializer.toXmlPlist(o) : plistSerializer.serialize(o); writer.write(result); writer.close();//from w ww .j a va2 s.c om }
From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java
@SuppressWarnings("unchecked") public T fetchObject() { T object = null;/*from w w w . j a va 2 s. co m*/ try { final StringBuilder sb = new StringBuilder(); sb.append(urlStr); sb.append("/"); sb.append(action); final Gson gson = new Gson(); final String bodyParamsString = gson.toJson(bodyParams); final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); conn.addRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(bodyParamsString); wr.flush(); final StringWriter writer = new StringWriter(); final InputStream in = conn.getInputStream(); IOUtils.copy(in, writer); in.close(); wr.close(); final String jsonString = writer.toString(); JSONObject jsonObject; jsonObject = new JSONObject(jsonString); JSONObject jsonRootArray; jsonRootArray = jsonObject.getJSONObject("d"); object = (T) gson.fromJson(jsonRootArray.toString(), typeOfClass); android.util.Log.d("JSON", jsonRootArray.toString()); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch (final JSONException e) { e.printStackTrace(); } return object; }
From source file:de.uni_koeln.spinfo.maalr.webapp.controller.EditorController.java
@RequestMapping("/editor/download/{fileName}.html") public void export(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException { File dir = new File("exports"); File file = new File(dir, fileName); ServletOutputStream out = response.getOutputStream(); if (!file.exists()) { OutputStreamWriter writer = new OutputStreamWriter(out); writer.write("This link has expired. Please re-export the data and try again."); writer.flush();/*from ww w .j a va 2 s . co m*/ return; } response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(in, out); in.close(); out.close(); file.delete(); }
From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java
private String httpPost(Map<String, String> requestParams) throws Exception { final URL url = new URL(authUrl); final StringBuilder data = new StringBuilder(); for (String key : requestParams.keySet()) data.append(String.format("%s=%s&", key, requestParams.get(key))); final String dataString = data.toString(); final String formData = dataString.substring(0, dataString.length() - 1); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); connection.setDoOutput(true);/* w ww. java2 s .c o m*/ final OutputStream outputStream = connection.getOutputStream(); final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(formData); outputStreamWriter.flush(); InputStream is = connection.getResponseCode() != 400 ? connection.getInputStream() : connection.getErrorStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader(is)); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) stringBuffer.append(line); outputStreamWriter.close(); rd.close(); if (connection.getResponseCode() == 400) throw new Exception("error: " + stringBuffer.toString()); return stringBuffer.toString(); }
From source file:ch.sdi.SocialDataImporterRunner.java
/** * Runs the SocialDataImporter application. * <p>/* www. j a va 2 s. c o m*/ * @param args * @throws SdiException */ public void run(String[] args) throws SdiException { initialize(args); try { PersonKey.initCustomKeys(myEnv); mySdiReporter.reset(); Collection<? extends Person<?>> inputPersons = myCollectorExecutor.execute(); if (myLog.isDebugEnabled()) { myLog.debug("collected persons: " + inputPersons); } // if myLog.isDebugEnabled() myTargetExecutor.execute(inputPersons); } finally { String report = mySdiReporter.getReport(); myLog.debug("Generated report:\n" + report); File outputDir = myEnv.getProperty(ConfigUtils.KEY_PROP_OUTPUT_DIR, File.class); if (outputDir != null) { File reportFile = new File(outputDir, "SdiReport.txt"); try { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(reportFile), "UTF-8"); osw.write(report); osw.close(); } catch (IOException t) { myLog.warn("Unable to write report file: " + reportFile.getPath(), t); } } // if outputDir != null } }
From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java
@SuppressWarnings("unchecked") public T fetchArray() { ArrayList<E> array = new ArrayList<E>(); try {//from w w w .j a va 2 s. c o m final StringBuilder sb = new StringBuilder(); sb.append(urlStr); sb.append("/"); sb.append(action); final Gson gson = new Gson(); final String bodyParamsString = gson.toJson(bodyParams); final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); conn.addRequestProperty("Content-Type", "application/json"); conn.addRequestProperty("charset", "utf-8"); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(bodyParamsString); wr.flush(); final StringWriter writer = new StringWriter(); final InputStream in = conn.getInputStream(); IOUtils.copy(in, writer); in.close(); wr.close(); final String jsonString = writer.toString(); final ArrayList<E> objectList = new ArrayList<E>(); JSONObject jsonObject; jsonObject = new JSONObject(jsonString); JSONArray jsonRootArray; jsonRootArray = jsonObject.getJSONObject("d").getJSONArray(liste); android.util.Log.d("JSON", jsonRootArray.toString()); for (int i = 0; i < jsonRootArray.length(); i++) { objectList.add(gson.fromJson(jsonRootArray.getJSONObject(i).toString(), typeOfClass)); } array = objectList; } catch (final IOException e) { e.printStackTrace(); } catch (final JSONException e) { e.printStackTrace(); } return (T) array; }
From source file:NetUtils.java
/** * Encode a path as required by the URL specificatin (<a href="http://www.ietf.org/rfc/rfc1738.txt"> * RFC 1738</a>). This differs from <code>java.net.URLEncoder.encode()</code> which encodes according * to the <code>x-www-form-urlencoded</code> MIME format. * * @param path the path to encode/* w ww .jav a2 s. com*/ * @return the encoded path */ public static String encodePath(String path) { // stolen from org.apache.catalina.servlets.DefaultServlet ;) /** * Note: This code portion is very similar to URLEncoder.encode. * Unfortunately, there is no way to specify to the URLEncoder which * characters should be encoded. Here, ' ' should be encoded as "%20" * and '/' shouldn't be encoded. */ int maxBytesPerChar = 10; StringBuffer rewrittenPath = new StringBuffer(path.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar); OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(buf, "UTF8"); } catch (Exception e) { e.printStackTrace(); writer = new OutputStreamWriter(buf); } for (int i = 0; i < path.length(); i++) { int c = (int) path.charAt(i); if (safeCharacters.get(c)) { rewrittenPath.append((char) c); } else { // convert to external encoding before hex conversion try { writer.write(c); writer.flush(); } catch (IOException e) { buf.reset(); continue; } byte[] ba = buf.toByteArray(); for (int j = 0; j < ba.length; j++) { // Converting each byte in the buffer byte toEncode = ba[j]; rewrittenPath.append('%'); int low = (int) (toEncode & 0x0f); int high = (int) ((toEncode & 0xf0) >> 4); rewrittenPath.append(hexadecimal[high]); rewrittenPath.append(hexadecimal[low]); } buf.reset(); } } return rewrittenPath.toString(); }
From source file:com.oxiane.maven.xqueryMerger.Merger.java
@Override public void execute() throws MojoExecutionException { Path sourceRootPath = inputSources.toPath(); Path destinationRootPath = outputDirectory.toPath(); IOFileFilter filter = buildFilter(); Iterator<File> it = FileUtils.iterateFiles(inputSources, filter, FileFilterUtils.directoryFileFilter()); if (!it.hasNext()) { getLog().warn("No file found matching " + filter.toString() + " in " + inputSources.getAbsolutePath()); }/*from w w w. j av a 2 s.c om*/ while (it.hasNext()) { File sourceFile = it.next(); Path fileSourcePath = sourceFile.toPath(); Path relativePath = sourceRootPath.relativize(fileSourcePath); getLog().debug("[Merger] found source: " + fileSourcePath.toString()); getLog().debug("[Merger] relative path is " + relativePath.toString()); StreamSource source = new StreamSource(sourceFile); XQueryMerger merger = new XQueryMerger(source); merger.setMainQuery(); File destinationFile = destinationRootPath.resolve(relativePath).toFile(); getLog().debug("[Merger] destination will be " + destinationFile.getAbsolutePath()); try { String result = merger.merge(); destinationFile.getParentFile().mkdirs(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destinationFile), merger.getEncoding()); osw.write(result); osw.flush(); osw.close(); getLog().debug("[Merger] " + relativePath.toString() + " merged into " + destinationFile.getAbsolutePath()); } catch (ParsingException ex) { getLog().error(ex.getMessage()); throw new MojoExecutionException("Merge of " + sourceFile.getAbsolutePath() + " fails", ex); } catch (FileNotFoundException ex) { getLog().error(ex.getMessage()); throw new MojoExecutionException( "Unable to create destination " + destinationFile.getAbsolutePath(), ex); } catch (IOException ex) { getLog().error(ex.getMessage()); throw new MojoExecutionException("While writing " + destinationFile.getAbsolutePath(), ex); } } }
From source file:com.twilio.sdk.TwilioRestClient.java
@Override public TwilioRestResponse request(String path, String method, Map<String, String> vars) throws TwilioRestException { String encoded = ""; if (vars != null && !vars.isEmpty()) { for (String key : vars.keySet()) { try { encoded += "&" + key + "=" + URLEncoder.encode(vars.get(key), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new TwilioRestException(e); }/*from w w w . j a va2 s. c o m*/ } encoded = encoded.substring(1); } // construct full url String url = this.endpoint + path; // if GET and vars, append them if (method.toUpperCase().equals("GET")) url += ((path.indexOf('?') == -1) ? "?" : "&") + encoded; try { HttpURLConnection con = openConnection(url); String userpass = this.accountSid + ":" + this.authToken; String encodeuserpass = new String(Base64.encodeBase64(userpass.getBytes())); con.setRequestProperty("Authorization", "Basic " + encodeuserpass); con.setDoOutput(true); // initialize a new curl object if (method.toUpperCase().equals("GET")) { con.setRequestMethod("GET"); } else if (method.toUpperCase().equals("POST")) { con.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("PUT")) { con.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("DELETE")) { con.setRequestMethod("DELETE"); } else { throw new TwilioRestException("Unknown method " + method); } BufferedReader in = null; try { if (con.getInputStream() != null) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); } } catch (IOException e) { if (con.getErrorStream() != null) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } } if (in == null) { throw new TwilioRestException("Unable to read response from server"); } StringBuilder decodedString = new StringBuilder(); String line; while ((line = in.readLine()) != null) { decodedString.append(line); } in.close(); // get result code int responseCode = con.getResponseCode(); return new TwilioRestResponse(url, decodedString.toString(), responseCode); } catch (MalformedURLException e) { throw new TwilioRestException(e); } catch (IOException e) { throw new TwilioRestException(e); } }