List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:org.georchestra.console.ReCaptchaV2.java
/** * * @param url/* w ww . jav a 2s. c o m*/ * @param privateKey * @param gRecaptchaResponse * * @return true if validaded on server side by google, false in case of error or if an exception occurs */ public boolean isValid(String url, String privateKey, String gRecaptchaResponse) { boolean isValid = false; try { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // add request header con.setRequestMethod("POST"); String postParams = "secret=" + privateKey + "&response=" + gRecaptchaResponse; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); if (LOG.isDebugEnabled()) { int responseCode = con.getResponseCode(); LOG.debug("\nSending 'POST' request to URL : " + url); LOG.debug("Post parameters : " + postParams); LOG.debug("Response Code : " + responseCode); } // getResponse BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result LOG.debug(response.toString()); JSONObject captchaResponse; try { captchaResponse = new JSONObject(response.toString()); if (captchaResponse.getBoolean("success")) { isValid = true; } else { // Error in response LOG.info("The user response to recaptcha is not valid. The error message is '" + captchaResponse.getString("error-codes") + "' - see Error Code Reference at https://developers.google.com/recaptcha/docs/verify."); } } catch (JSONException e) { // Error in response LOG.error("Error while parsing ReCaptcha JSON response", e); } } catch (IOException e) { LOG.error("An error occured when trying to contact google captchaV2", e); } return isValid; }
From source file:edu.isi.wings.util.oodt.CurationServiceAPI.java
private String query(String method, String op, Object... args) { String url = this.curatorurl + this.service + op; try {/* ww w . ja va 2s . c om*/ String params = "policy=" + URLEncoder.encode(this.policy, "UTF-8"); for (int i = 0; i < args.length; i += 2) { params += "&" + args[i] + "=" + URLEncoder.encode(args[i + 1].toString(), "UTF-8"); } URL urlobj = new URL(url); if ("GET".equals(method)) urlobj = new URL(url + "?" + params); HttpURLConnection con = (HttpURLConnection) urlobj.openConnection(); con.setRequestMethod(method); if (!"GET".equals(method)) { con.setDoOutput(true); DataOutputStream out = new DataOutputStream(con.getOutputStream()); out.writeBytes(params); out.flush(); out.close(); } String result = IOUtils.toString(con.getInputStream()); con.disconnect(); return result; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.wisdom.openid.connect.service.internal.DefaultIssuer.java
@Override public TokenResponse authorizationToken(final String redirectUrl, final String code) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("grant_type=authorization_code"); sb.append(format("&code=%s", code)); sb.append(format("&client_id=%s", clientId)); sb.append(format("&client_secret=%s", clientSecret)); sb.append(format("&redirect_uri=%s", redirectUrl)); String parameters = sb.toString(); URL tokenEndpoint = new URL(config.getTokenEndpoint()); HttpURLConnection connection = (HttpURLConnection) tokenEndpoint.openConnection(); connection.setRequestMethod("POST"); connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //connection.addRequestProperty("Authorization", format("Basic %s", credentials())); connection.setRequestProperty("Content-Length", valueOf(parameters.getBytes().length)); connection.setUseCaches(false);//from w w w.j a v a2s. c o m connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); //Get Response return buildTokenResponse(connection.getInputStream()); }
From source file:org.perfcake.reporting.destination.Client.java
public void addValue(TestExec te) throws Exception { HttpURLConnection conn = (HttpURLConnection) urlAdd.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Basic " + authorizationHeader); conn.setRequestProperty("Content-Type", "text/xml"); conn.setDoOutput(true);// w w w.j a va 2s .c o m DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(te.toXml()); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); if (responseCode == 201) { } else { //TODO ERROR } conn.disconnect(); }
From source file:com.googlecode.fascinator.portal.quartz.ExternalJob.java
/** * The real work happens here//from w w w . ja v a2s. c o m * */ private void runJob() { HttpURLConnection conn = null; log.debug("Job firing: '{}'", name); try { // Open tasks... much simpler if (token == null) { conn = (HttpURLConnection) url.openConnection(); // Secure tasks } else { String param = "token=" + URLEncoder.encode(token, "UTF-8"); // Prepare our request conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length)); conn.setUseCaches(false); conn.setDoOutput(true); // Send request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(param); wr.flush(); wr.close(); } // Get Response if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { log.error("Error hitting external script: {}", conn.getResponseMessage()); } } catch (IOException ex) { log.error("Error connecting to URL: ", ex); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:org.apache.hadoop.mapred.TestLocalModeWithNewApis.java
@Test public void testNewApis() throws Exception { Random r = new Random(System.currentTimeMillis()); Path tmpBaseDir = new Path("/tmp/wc-" + r.nextInt()); final Path inDir = new Path(tmpBaseDir, "input"); final Path outDir = new Path(tmpBaseDir, "output"); String input = "The quick brown fox\nhas many silly\nred fox sox\n"; FileSystem inFs = inDir.getFileSystem(conf); FileSystem outFs = outDir.getFileSystem(conf); outFs.delete(outDir, true);/*from ww w. j a v a2s .c om*/ if (!inFs.mkdirs(inDir)) { throw new IOException("Mkdirs failed to create " + inDir.toString()); } { DataOutputStream file = inFs.create(new Path(inDir, "part-0")); file.writeBytes(input); file.close(); } Job job = Job.getInstance(conf, "word count"); job.setJarByClass(TestLocalModeWithNewApis.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, inDir); FileOutputFormat.setOutputPath(job, outDir); assertEquals(job.waitForCompletion(true), true); String output = readOutput(outDir, conf); assertEquals("The\t1\nbrown\t1\nfox\t2\nhas\t1\nmany\t1\n" + "quick\t1\nred\t1\nsilly\t1\nsox\t1\n", output); outFs.delete(tmpBaseDir, true); }
From source file:ioc.wiki.processingmanager.http.HttpFileSender.java
/** * Prepara la comanda a enviar al servidor, l'envia i rep la resposta en un string. * Cont informaci sobre el xit de guardar el fitxer al servidor. * @return Retorna un string amb la resposta del servidor. *//*from w ww . j a v a 2 s .c om*/ @Override public String sendCommand() { super.prepareCommand(); try { ((HttpURLConnection) urlConnection).setRequestMethod(REQUEST_METHOD); urlConnection.setRequestProperty(PROPERTY_CONTENT_TYPE, content_type + boundary); DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream()); //Capalera fitxer request.writeBytes(twoHyphens + boundary + crlf); request.writeBytes(contentDispositionFile + quote + this.destFilename + quote + crlf); request.writeBytes(contentTypeFile + crlf); request.writeBytes(contentTransferEncodingFile + crlf); request.writeBytes(crlf); //IMAGE String base64Image = Base64.encodeBase64String(this.image); request.writeBytes(base64Image); //Tancament fitxer request.writeBytes(crlf); request.writeBytes(twoHyphens + boundary + twoHyphens + crlf); request.flush(); request.close(); } catch (IOException ex) { throw new ProcessingRtURLException(ex); } return super.receiveResponse(); }
From source file:net.mms_projects.copy_it.server.push.android.GCMRunnable.java
public void run() { try {//from w w w .j a va 2 s. com URL url = new URL(GCM_URL); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod(POST); conn.setRequestProperty(CONTENT_TYPE, Page.ContentTypes.JSON_TYPE); conn.setRequestProperty(AUTHORIZATION, KEY); final String output_json = full.toString(); System.err.println("Input json: " + output_json); conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(output_json.length())); conn.setDoOutput(true); conn.setDoInput(true); DataOutputStream outputstream = new DataOutputStream(conn.getOutputStream()); outputstream.writeBytes(output_json); outputstream.close(); DataInputStream input = new DataInputStream(conn.getInputStream()); StringBuilder builder = new StringBuilder(input.available()); for (int c = input.read(); c != -1; c = input.read()) builder.append((char) c); input.close(); output = new JSONObject(builder.toString()); System.err.println("Output json: " + output.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.hadoop.hdfs.TestFileCorruption.java
/** check if local FS can handle corrupted blocks properly */ @Test/*from www. j a v a2 s . c om*/ public void testLocalFileCorruption() throws Exception { Configuration conf = new HdfsConfiguration(); Path file = new Path(PathUtils.getTestDirName(getClass()), "corruptFile"); FileSystem fs = FileSystem.getLocal(conf); DataOutputStream dos = fs.create(file); dos.writeBytes("original bytes"); dos.close(); // Now deliberately corrupt the file dos = new DataOutputStream(new FileOutputStream(file.toString())); dos.writeBytes("corruption"); dos.close(); // Now attempt to read the file DataInputStream dis = fs.open(file, 512); try { System.out.println("A ChecksumException is expected to be logged."); dis.readByte(); } catch (ChecksumException ignore) { //expect this exception but let any NPE get thrown } fs.delete(file, true); }
From source file:net.namecoin.NameCoinI2PResolver.HttpSession.java
public String executePost(String postdata) throws HttpSessionException { URL url;// w w w . jav a 2 s . c om HttpURLConnection connection = null; try { //Create connection url = new URL(this.uri); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", POST_CONTENT_TYPE); connection.setRequestProperty("User-Agent", "java"); if (!this.user.isEmpty() && !this.password.isEmpty()) { String authString = this.user + ":" + this.password; String authStringEnc = Base64.encodeBytes(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + authStringEnc); } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(postdata); wr.flush(); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new HttpSessionException("Server returned: " + connection.getResponseMessage()); } return response.toString(); } catch (Exception e) { throw new HttpSessionException(e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } }