List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:fr.mby.saml2.sp.opensaml.query.engine.SloRequestQueryProcessor.java
/** * Send the SLO Response via the URL Api. * //from w w w . j a va2s. com * @param binding * the binding to use * @param sloResponseRequest * the SLO Response request */ protected void sendSloResponse(final SamlBindingEnum binding, final IOutgoingSaml sloResponseRequest) { URL sloUrl = null; HttpURLConnection sloConnexion = null; try { switch (binding) { case SAML_20_HTTP_REDIRECT: final String redirectUrl = sloResponseRequest.getHttpRedirectBindingUrl(); sloUrl = new URL(redirectUrl); sloConnexion = (HttpURLConnection) sloUrl.openConnection(); sloConnexion.setReadTimeout(10000); sloConnexion.connect(); break; case SAML_20_HTTP_POST: final String sloEndpointUrl = sloResponseRequest.getEndpointUrl(); final Collection<Entry<String, String>> sloPostParams = sloResponseRequest .getHttpPostBindingParams(); final StringBuffer samlDatas = new StringBuffer(1024); final Iterator<Entry<String, String>> itParams = sloPostParams.iterator(); final Entry<String, String> firstParam = itParams.next(); samlDatas.append(firstParam.getKey()); samlDatas.append("="); samlDatas.append(firstParam.getValue()); while (itParams.hasNext()) { final Entry<String, String> param = itParams.next(); samlDatas.append("&"); samlDatas.append(param.getKey()); samlDatas.append("="); samlDatas.append(param.getValue()); } sloUrl = new URL(sloEndpointUrl); sloConnexion = (HttpURLConnection) sloUrl.openConnection(); sloConnexion.setDoInput(true); final OutputStreamWriter writer = new OutputStreamWriter(sloConnexion.getOutputStream()); writer.write(samlDatas.toString()); writer.flush(); writer.close(); sloConnexion.setReadTimeout(10000); sloConnexion.connect(); break; default: break; } if (sloConnexion != null) { final InputStream responseStream = sloConnexion.getInputStream(); final StringWriter writer = new StringWriter(); IOUtils.copy(responseStream, writer, "UTF-8"); final String response = writer.toString(); this.logger.debug(String.format("HTTP response to SLO Request sent: [%s] ", response)); final int responseCode = sloConnexion.getResponseCode(); final String samlMessage = sloResponseRequest.getSamlMessage(); final String endpointUrl = sloResponseRequest.getEndpointUrl(); if (responseCode < 0) { this.logger.error("Unable to send SAML 2.0 Single Logout Response [{}] to endpoint URL [{}] !", samlMessage, endpointUrl); } else if (responseCode == 200) { this.logger.info("SAML 2.0 Single Logout Request correctly sent to [{}] !", endpointUrl); } else { this.logger.error( "HTTP response code: [{}] ! Error while sending SAML 2.0 Single Logout Request [{}] to endpoint URL [{}] !", new Object[] { responseCode, samlMessage, endpointUrl }); } } } catch (final MalformedURLException e) { this.logger.error(String.format("Malformed SAML SLO request URL: [%s] !", sloUrl.toExternalForm()), e); } catch (final IOException e) { this.logger.error(String.format("Unable to send SAML SLO request URL: [%s] !", sloUrl.toExternalForm()), e); } finally { sloConnexion.disconnect(); } }
From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java
private String getResultFromHttp(final String location, final JSONObject object) throws ExternalDbUnavailableException { HttpURLConnection conn = null; try {/*from w w w . j a va 2 s. c o m*/ URL url = new URL(location); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON); OutputStreamWriter stream = new OutputStreamWriter(conn.getOutputStream(), Charset.defaultCharset()); stream.write(object.toString()); stream.flush(); int status = conn.getResponseCode(); while (true) { String header = conn.getHeaderField(HTTP_HEADER_RETRY_AFTER); long wait = 0; if (header != null) { wait = Integer.valueOf(header); } if (wait == 0) { break; } LOGGER.info(String.format(WAITING_FORMAT, wait)); conn.disconnect(); Thread.sleep(wait * MILLIS_IN_SECOND); conn = (HttpURLConnection) new URL(location).openConnection(); conn.setDoInput(true); conn.connect(); status = conn.getResponseCode(); } return getHttpResult(status, location, conn); } catch (IOException | InterruptedException | ExternalDbUnavailableException e) { throw new ExternalDbUnavailableException(String.format(EXCEPTION_MESSAGE, location), e); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:br.ufjf.taverna.core.TavernaClientBase.java
protected HttpURLConnection request(String endpoint, TavernaServerMethods method, int expectedResponseCode, String acceptData, String contentType, String filePath, String putData) throws TavernaException { HttpURLConnection connection = null; try {//from ww w . j a v a 2 s. c o m String uri = this.getBaseUri() + endpoint; URL url = new URL(uri); connection = (HttpURLConnection) url.openConnection(); connection.setUseCaches(false); connection.setDoOutput(true); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Cache-Control", "no-cache"); String authorization = this.username + ":" + this.password; String encodedAuthorization = "Basic " + new String(Base64.encodeBase64(authorization.getBytes())); connection.setRequestProperty("Authorization", encodedAuthorization); connection.setRequestMethod(method.getMethod()); if (acceptData != null) { connection.setRequestProperty("Accept", acceptData); } if (contentType != null) { connection.setRequestProperty("Content-Type", contentType); } if (TavernaServerMethods.GET.equals(method)) { } else if (TavernaServerMethods.POST.equals(method)) { FileReader fr = new FileReader(filePath); char[] buffer = new char[1024 * 10]; int read; OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); while ((read = fr.read(buffer)) != -1) { writer.write(buffer, 0, read); } writer.flush(); writer.close(); fr.close(); } else if (TavernaServerMethods.PUT.equals(method)) { OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(putData); writer.flush(); writer.close(); } else if (TavernaServerMethods.DELETE.equals(method)) { } int responseCode = connection.getResponseCode(); if (responseCode != expectedResponseCode) { throw new TavernaException( String.format("Invalid HTTP Response Code. Expected %d, actual %d, URL %s", expectedResponseCode, responseCode, url)); } } catch (IOException ioe) { ioe.printStackTrace(); } return connection; }
From source file:nl.welteninstituut.tel.la.importers.fitbit.FitbitTask.java
public String postUrl(String url, String data, String authorization) { StringBuilder result = new StringBuilder(); try {// w w w.j a v a 2 s. co m URLConnection conn = new URL(url).openConnection(); // conn.setConnectTimeout(30); conn.setDoOutput(true); if (authorization != null) conn.setRequestProperty("Authorization", "Basic " + new String(new Base64().encode(authorization.getBytes()))); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } wr.close(); rd.close(); } catch (Exception e) { } return result.toString(); }
From source file:org.asimba.auth.smsotp.distributor.mollie.MollieOTPDistributor.java
/** * Distribute the OTP to the user<br/> * Requires a configured attribute to be present in the User's Attributes()-collection to * establish the phonenr to send the OneTimePassword to!<br/> * Updates Otp-instance to reflect the result of distributing the password (timessent, timesent) * /*from w w w . ja v a 2s . c o m*/ * Sources inspired by A-Select SMS AuthSP */ public int distribute(OTP oOtp, IUser oUser) throws OAException, OTPDistributorException { // Are we operational? if (!_bStarted) { throw new OAException(SystemErrors.ERROR_NOT_INITIALIZED); } String sMsg; String sRecipient; IAttributes oUserAttributes; int returncode = 15; // Establish the phonenr to send message to oUserAttributes = oUser.getAttributes(); if (!oUserAttributes.contains(_sPhonenrAttribute)) { _oLogger.error("Unknown phonenr for user " + oUser.getID() + "; missing attribute '" + _sPhonenrAttribute + "'"); throw new OTPDistributorException(returncode); } sRecipient = (String) oUserAttributes.get(_sPhonenrAttribute); // Establish message sMsg = getMessageForPwd(oOtp.getValue()); // Establish URL StringBuffer sbData = new StringBuffer(); try { ArrayList<String> params = new ArrayList<String>(); // Depend on Apache Commons Lang for join params.add(StringUtils.join(new String[] { "gebruikersnaam", URLEncoder.encode(_sUsername, "UTF-8") }, "=")); params.add( StringUtils.join(new String[] { "wachtwoord", URLEncoder.encode(_sPassword, "UTF-8") }, "=")); params.add( StringUtils.join(new String[] { "afzender", URLEncoder.encode(_sSenderName, "UTF-8") }, "=")); params.add(StringUtils.join(new String[] { "bericht", URLEncoder.encode(sMsg, "UTF-8") }, "=")); params.add( StringUtils.join(new String[] { "ontvangers", URLEncoder.encode(sRecipient, "UTF-8") }, "=")); String sCGIString = StringUtils.join(params, "&"); returncode++; // 16 URLConnection oURLConnection = _oURL.openConnection(); returncode++; // 17 oURLConnection.setDoOutput(true); OutputStreamWriter oWriter = new OutputStreamWriter(oURLConnection.getOutputStream()); oWriter.write(sCGIString); oWriter.flush(); returncode++; // 18 // Get the response BufferedReader oReader = new BufferedReader(new InputStreamReader(oURLConnection.getInputStream())); String sLine; if ((sLine = oReader.readLine()) != null) { returncode = Integer.parseInt(sLine); } if (returncode != 0) { _oLogger.error("Mollie could not send sms, returncode from Mollie: " + returncode + "."); throw new OTPDistributorException(returncode); } returncode++; // 19 oWriter.close(); oReader.close(); } catch (NumberFormatException e) { _oLogger.error("Sending SMS, using \'" + _oURL.toString() + ", data=" + sbData.toString() + "\' failed due to number format exception!" + e.getMessage()); throw new OTPDistributorException(returncode); } catch (Exception e) { _oLogger.error("Sending SMS, using \'" + _oURL.toString() + ", data=" + sbData.toString() + "\' failed (return code=" + returncode + ")! " + e.getMessage()); throw new OTPDistributorException(returncode); } _oLogger.info("Sending to user " + oUser.getID() + " password with value " + oOtp.getValue()); oOtp.registerSent(Long.valueOf(System.currentTimeMillis())); return returncode; }
From source file:com.rapleaf.api.personalization.RapleafApi.java
protected String bulkJsonResponse(String urlStr, String list) throws Exception { URL url = new URL(urlStr); HttpURLConnection handle = (HttpURLConnection) url.openConnection(); handle.setRequestProperty("User-Agent", getUserAgent()); handle.setRequestProperty("Content-Type", "application/json"); handle.setConnectTimeout(timeout);/*from w w w . j a v a 2 s. c o m*/ handle.setReadTimeout(bulkTimeout); handle.setDoOutput(true); handle.setRequestMethod("POST"); OutputStreamWriter wr = new OutputStreamWriter(handle.getOutputStream()); wr.write(list); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(handle.getInputStream())); String line = rd.readLine(); StringBuilder sb = new StringBuilder(); while (line != null) { sb.append(line); line = rd.readLine(); } wr.close(); rd.close(); int responseCode = handle.getResponseCode(); if (responseCode < 200 || responseCode > 299) { throw new Exception("Error Code " + responseCode + ": " + sb.toString()); } return sb.toString(); }
From source file:BRHInit.java
public JSONObject json_rpc(String method, JSONArray params) throws Exception { URLConnection conn = rpc_url.openConnection(); if (cookie != null) conn.addRequestProperty("cookie", cookie); JSONObject request = new JSONObject(); request.put("id", false); request.put("method", method); request.put("params", params); conn.setDoOutput(true);/*from ww w . ja v a 2 s . c o m*/ OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); try { wr.write(request.toString()); wr.flush(); } finally { wr.close(); } // Get the response InputStreamReader rd = new InputStreamReader(conn.getInputStream()); try { JSONTokener tokener = new JSONTokener(rd); return (JSONObject) tokener.nextValue(); } finally { rd.close(); } }
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 av a 2s . c o m 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.amalto.workbench.editors.XSDDriver.java
public String outputXSD_UTF_8(String src, String fileName) { // File file = new File(fileName); try {/*from ww w . j a v a 2 s .c om*/ OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName), DEFAULT_OUTPUT_ENCODING); out.write(src); // System.out.println("OutputStreamWriter: "+out.getEncoding()); out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block log.error(e.getMessage(), e); return null; } return Messages.XSDDriver_SUCCESS; }
From source file:org.geoserver.wms.describelayer.GeoJSONDescribeLayerResponse.java
private void writeJSONP(OutputStream out, DescribeLayerModel layers) throws IOException { OutputStreamWriter outWriter = null; try {/*from w w w . j a v a 2 s.co m*/ outWriter = new OutputStreamWriter(out, wms.getGeoServer().getSettings().getCharset()); outWriter.write(getCallbackFunction() + "("); writeJSON(outWriter, layers); } finally { if (outWriter != null) { outWriter.write(")"); outWriter.flush(); IOUtils.closeQuietly(outWriter); } } }