public void firstRun() throws Exception { Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/test.jsp" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); // Get the JSESSIONID from the response String line = null; while ((line = br.readLine()) != null) { System.out.println(line); if (line.startsWith("Set-Cookie:") || line.startsWith("Set-cookie:")) { break; } } if (line == null) { throw new Exception("Missing Set-Cookie response header"); } String jsessionId = getSessionIdFromCookie(line, JSESSIONID); // Store the JSESSIONID in a file FileOutputStream fos = new FileOutputStream(JSESSIONID); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(jsessionId); osw.close(); stat.addStatus(TEST_NAME, stat.PASS); }
/** * Method to return a set of hazard data within CACHE_DISTANCE of given location * * @param location An instance of Location that stores latitude and longitude data * @return JSONObject an instance of JSONObject with json encoded hazard data * @throws IOException * @throws JSONException */ public static JSONObject getHazards(LatLng location) throws IOException, JSONException { // request hazards from long / lat data and retrieve json hazards // tested and working! String longitude = String.valueOf(location.longitude); String latitude = String.valueOf(location.latitude); String query = String.format("longitude=%s&latitude=%s", longitude, latitude); // encode the post query // Set a POST connection URL url = new URL(site + "/request.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); System.out.println(query); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // Send post request OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(query); writer.flush(); writer.close(); BufferedReader response = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer hazards = new StringBuffer(); String inputLine; while ((inputLine = response.readLine()) != null) { hazards.append(inputLine); } response.close(); return new JSONObject(hazards.toString()); }
/** * {@inheritDoc} * * @see edu.mcmaster.maplelab.common.datamodel.TrialLogger#saveSessionConfig() */ public void saveSessionConfig() throws IOException { // Save session configuration data. URLConnection conn = makeSaveConfigConnection(); if (conn == null) return; conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); Map<String, String> fields = new HashMap<String, String>(); fields.put("config", getSession().toPropertiesString()); String row = encode(fields); LogContext.getLogger().finer("-> config log: " + row); if (getSession().getExperimentDBKey() >= 0) { OutputStreamWriter out = null; try { out = new OutputStreamWriter(conn.getOutputStream()); out.write(row); out.flush(); } finally { if (out != null) out.close(); } conn.connect(); readResponse(conn); } }
private int send(final String yaml, final HttpURLConnection connection) throws IOException { int statusCode; final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(yaml); writer.close(); statusCode = connection.getResponseCode(); return statusCode; }
private void sendMSG(String msg) throws IOException { try { out.write(msg); out.flush(); } catch (IOException ioe) { throw (ioe); } }
public static boolean putStringToXml(String fileName, String content) { File file = new File(fileName); try { OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); out.write(content); out.close(); return true; } catch (IOException e) { return false; } }
public void Connect() throws IOException { try { InetAddress addr = InetAddress.getByName(server); Socket socket = new Socket(addr, port); in = new InputStreamReader(socket.getInputStream()); out = new OutputStreamWriter(socket.getOutputStream()); char c[] = new char[LINE_LENGTH]; boolean authed = false; while (true) { if (in.read(c) > 0) { String msg = new String(c).trim(); if (!authed) { if (msg.endsWith("No Ident response")) { System.out.println("...sending identity..."); out.write(String.format("NICK %s\r\n", nickname)); out.write(String.format("USER %s %s %s :s\r\n", nickname, host, server, realname)); out.flush(); authed = true; for (IRCAuthListener a : authListeners) { a.afterAuthentication(this); } } } if (msg.startsWith("PING")) { System.out.println("Sending pong..."); out.write("PONG\r\n"); out.flush(); } for (IRCRawDataListener d : rawDataListeners) { d.processRawData(this, msg); } c = new char[LINE_LENGTH]; } else { System.out.println("Oops, if you see this we just got kicked or connection timed out..."); break; } } } catch (IOException ioe) { throw (ioe); } }
public static void main(String[] args) { URL url; URLConnection connection = null; String inputLine = ""; try { url = new URL( "https://ecom.payfirma.com/authorize/?merchant_id=YOURMERCHANTID&key=YOURAPIKEY&amount=0.02"); connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write("card_number=4111111111111111&card_expiry_month=12&card_expiry_year=13&cvv2=121"); out.close(); BufferedReader inStream = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((inputLine = inStream.readLine()) != null) { System.out.println(inputLine); } inStream.close(); } catch (MalformedURLException me) { System.err.println("MalformedURLException: " + me); } catch (IOException ioe) { System.err.println("IOException: " + ioe); InputStream error = ((HttpURLConnection) connection).getErrorStream(); try { int data = error.read(); while (data != -1) { inputLine = inputLine + (char) data; data = error.read(); } error.close(); } catch (Exception ex) { try { if (error != null) { error.close(); } } catch (Exception e) { System.out.println("Unhandled error"); } } System.out.println(inputLine); } }
private String transportHttpMessage(String message) { URL serverurl; HttpURLConnection connection; try { serverurl = new URL(this.ServerUrl); connection = (HttpURLConnection) serverurl.openConnection(); connection.setDefaultUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("content-type", "application/x-www-form-urlencoded"); } catch (Exception e) { e.printStackTrace(); return null; } OutputStreamWriter outstream; try { outstream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); outstream.write(message); outstream.flush(); /* PrintWriter writer = new PrintWriter(outstream); writer.write(message); writer.flush(); */ outstream.close(); } catch (Exception e) { e.printStackTrace(); return null; } StringBuilder strbuilder = new StringBuilder(); try { InputStreamReader instream = new InputStreamReader(connection.getInputStream(), "UTF-8"); BufferedReader reader = new BufferedReader(instream); String str; while ((str = reader.readLine()) != null) strbuilder.append(str + "\r\n"); instream.close(); } catch (Exception e) { e.printStackTrace(); return null; } connection.disconnect(); return strbuilder.toString(); }
public void end() throws Exception { FunMessage.Builder fm = FunMessage.newBuilder().setGameId(gameId).setFunScore(rate()); URL url = new URL("http://localhost:5000/gameFinish"); URLConnection urlCon = url.openConnection(); urlCon.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(urlCon.getOutputStream()); wr.write("rating="); wr.flush(); fm.build().writeTo(urlCon.getOutputStream()); urlCon.getOutputStream().close(); // No network I/O happens until you ask for feedback apparently urlCon.getInputStream(); }
/** * Writes the XML Declaration and the opening RDF tag to the print Writer. Encoding attribute is * specified as the encoding argument. * * @param out PrintWriter * @throws IOException */ protected void writeHeader(OutputStreamWriter out) throws IOException { // validate if (out != null) { // wrapper for output stream writer (enable autoflushing) PrintWriter writer = new PrintWriter(out, true); // get encoding from the Encoding map String encoding = EncodingMap.getJava2IANAMapping(out.getEncoding()); // only insert encoding if there is a value if (encoding != null) { // print opening tags <?xml version="1.0" encoding=*encoding*?> writer.println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>"); } else { // print opening tags <?xml version="1.0"?> writer.println("<?xml version=\"1.0\"?>"); } // print the Entities this.writeXMLEntities(writer); // print the opening RDF tag (including namespaces) this.writeRDFHeader(writer); } else { throw new IllegalArgumentException("Cannot write to null Writer."); } }
/** * 通过post方式访问短信接口 * * @param param sms message, like key1=value1&key2=value2 * @param isproxy 是否启用代理模式 * @return */ public String sendPost(String param, boolean isproxy) { OutputStreamWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(this.url); HttpURLConnection conn = null; conn = (HttpURLConnection) realUrl.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); // POST方法 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty( "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.connect(); out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); out.write(param); out.flush(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("[ERROR]发送 POST 请求出现异常!" + e); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
/** * create a Bufferedreader that read from the open url The parameter of the search term research * can be setup using the various command */ private String post(String post) { buffer = new StringBuilder(); // --4. Do the work try { url = new URL(composite_url); // Config.log("ESearch for: "+search_term); } catch (MalformedURLException e) { Config.log("Error: URL is not good.\n" + composite_url); } try { URLConnection connection = url.openConnection(); // --Output the post connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(post); out.close(); // --Read the answer in_connection = new BufferedReader(new InputStreamReader(connection.getInputStream())); if (in_connection != null) in_connection_open = true; String inputLine = ""; if (isOutputToDisk()) output = new PrintWriter(new FileWriter(new File(filename))); while ((inputLine = in_connection.readLine()) != null) { if (!this.isOutputToDisk()) { buffer.append(inputLine + "\n"); } else { output.println(inputLine); } } if (isOutputToDisk()) { output.flush(); output.close(); } } catch (IOException e) { Config.log("Unable to download from..." + composite_url); } return buffer.toString(); }
public void sendMsg() { try { Socket talkSocket = new Socket("localhost", 4711); BufferedReader fromServer = new BufferedReader(new InputStreamReader(talkSocket.getInputStream(), "Cp1252")); OutputStreamWriter toServer = new OutputStreamWriter(talkSocket.getOutputStream(), "Cp1252"); System.out.println(s1); toServer.write(s1); toServer.flush(); // force message to be sent String result = fromServer.readLine(); // blocking read System.out.println("Receive: " + result); toServer.close(); // close writer fromServer.close(); // close reader talkSocket.close(); // close socket (necessary??) } catch (Exception e) { e.printStackTrace(); } }
/** * This calls the external Moodle web service. * * <p>params String containing the parameters of the call.<br> * elements NodeList containing name/value pairs of returned XML data. * * @param params String * @return elements NodeList * @throws MoodleRestException */ public static NodeList call(String params) throws MoodleRestException { NodeList elements = null; try { URL getUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "application/xml"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(params); writer.flush(); writer.close(); // Used for testing StringBuilder buffer = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = reader.readLine(); buffer.append(line).append('\n'); // FindPath fp=new FindPath(); InputStream resource = ClassLoader.getSystemClassLoader() .getResourceAsStream("net/beaconhillcott/moodlerest/EntityInjection.xml"); BufferedReader entities = new BufferedReader(new InputStreamReader(/*fp.*/ resource)); String entitiesLine = null; while ((entitiesLine = entities.readLine()) != null) { // System.out.println(entitiesLine); buffer.append(entitiesLine).append('\n'); } entities.close(); boolean error = false; while ((line = reader.readLine()) != null) { // System.out.println(line); if (error) throw new MoodleRestException( line.substring(line.indexOf('>') + 1, line.indexOf('<', line.indexOf('>') + 1))); if (line.contains("<EXCEPTION")) error = true; buffer.append(line).append('\n'); } reader.close(); if (debug) { System.out.println(buffer.toString()); } XPath xpath = XPathFactory.newInstance().newXPath(); // InputSource source=new InputSource(connection.getInputStream()); InputSource source = new InputSource(new ByteArrayInputStream(buffer.toString().getBytes())); elements = (NodeList) xpath.evaluate("//VALUE", source, XPathConstants.NODESET); // Used for testing if (debug) { for (int i = 0; i < elements.getLength(); i++) { String parent = elements .item(i) .getParentNode() .getParentNode() .getParentNode() .getParentNode() .getNodeName(); if (parent.equals("KEY")) parent = elements .item(i) .getParentNode() .getParentNode() .getParentNode() .getParentNode() .getAttributes() .getNamedItem("name") .getNodeValue(); String content = elements.item(i).getTextContent(); String nodeName = elements.item(i).getParentNode().getAttributes().getNamedItem("name").getNodeValue(); System.out.println("parent=" + parent + " nodeName=" + nodeName + " content=" + content); } } connection.disconnect(); } catch (XPathExpressionException ex) { Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex); } return elements; }
public static void main(String[] args) { /** Define a host server */ String host = "localhost"; /** Define a port */ int port = 19999; int port2 = 19990; // int port3 = 19980; StringBuffer instr = new StringBuffer(); String TimeStamp; Parser parser = new Parser(); System.out.println("SocketClient initialized"); try { // parsing // DataStream ds = // new PlainTextByLineDataStream( // new FileReader(new File("input.txt"))); BufferedReader inputReader = new BufferedReader(new FileReader("input.txt")); String sent; while ((sent = inputReader.readLine()) != null) { // String sentence = (String)ds.nextToken() + (char) 13; String sentence = sent + (char) 13; // System.out.println(str); System.out.println("Parsing...."); Tree tree = parser.parse(sentence); System.out.println(tree); System.out.println("Extracting features..."); String srlIdentifier = "python srl-identifier.py " + '"' + tree + '"'; // System.out.println(srlIdentifier); Runtime rr = Runtime.getRuntime(); Process pp = rr.exec(srlIdentifier); BufferedReader brr = new BufferedReader(new InputStreamReader(pp.getInputStream())); pp.waitFor(); BufferedReader reader = new BufferedReader(new FileReader("identifier.test")); BufferedReader classifier = new BufferedReader(new FileReader("classifier.test")); String line; PrintWriter identifierOutput = new PrintWriter("identifier-output.txt"); PrintWriter classifierOutput = new PrintWriter("classifier-output.txt"); BufferedReader preds = new BufferedReader(new FileReader("pred.test")); while ((line = reader.readLine()) != null) { String pred = preds.readLine(); String features = line + (char) 13; String classifierFeature = classifier.readLine() + (char) 13; InetAddress address = InetAddress.getByName(host); // Establish a socket connetion Socket connection = new Socket(address, port); Socket connection2 = new Socket(address, port2); // Instantiate a BufferedOutputStream object BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream()); // Instantiate an OutputStreamWriter object with the optional character // encoding. // OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII"); BufferedReader fromServer = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Write across the socket connection and flush the buffer osw.write(features); osw.flush(); String identifierResponse = fromServer.readLine(); identifierOutput.println(identifierResponse); BufferedOutputStream bos2 = new BufferedOutputStream(connection2.getOutputStream()); // Instantiate an OutputStreamWriter object with the optional character // encoding. // OutputStreamWriter osw2 = new OutputStreamWriter(bos2, "US-ASCII"); BufferedReader fromServer2 = new BufferedReader(new InputStreamReader(connection2.getInputStream())); osw2.write(classifierFeature); osw2.flush(); String ClassifierResponse = fromServer2.readLine(); classifierOutput.println(pred + ' ' + ClassifierResponse); } identifierOutput.close(); classifierOutput.close(); Runtime rlabeler = Runtime.getRuntime(); String srlClassifier = "python concept-formulator.py"; Process p = rlabeler.exec(srlClassifier); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); p.waitFor(); // System.out.println("here i am"); String line2; while ((line2 = br.readLine()) != null) { System.out.println(line2); // while (br.ready()) // System.out.println(br.readLine()); } } } catch (Exception e) { String cause = e.getMessage(); if (cause.equals("python: not found")) System.out.println("No python interpreter found."); } }
public void bad() throws Throwable { if (IO.static_returns_t_or_f()) { java.util.logging.Logger log_bs = java.util.logging.Logger.getLogger("local-logger"); Socket sock = null; PrintWriter out = null; try { sock = new Socket("remote_host", 1337); out = new PrintWriter(sock.getOutputStream(), true); /* FLAW: sending over an unencrypted (non-SSL) channel */ out.println("plaintext send"); } catch (Exception ex) { IO.writeLine("Error writing to the socket"); } finally { try { if (out != null) { out.close(); } } catch (Exception e) { log_bs.warning("Error closing out"); } try { if (sock != null) { sock.close(); } } catch (Exception e) { log_bs.warning("Error closing sock"); } } } else { java.util.logging.Logger log_gs = java.util.logging.Logger.getLogger("local-logger"); OutputStream outStream = null; BufferedWriter bWriter = null; OutputStreamWriter outStreamWriter = null; SSLSocketFactory sslssocketfactory = null; SSLSocket sslsocket = null; try { sslssocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); sslsocket = (SSLSocket) sslssocketfactory.createSocket("remote_host", 1337); outStream = sslsocket.getOutputStream(); outStreamWriter = new OutputStreamWriter(outStream); bWriter = new BufferedWriter(outStreamWriter); /* FIX: sending over an SSL encrypted channel */ bWriter.write("encrypted send"); bWriter.flush(); } catch (Exception ex) { IO.writeLine("Error writing to the socket"); } finally { try { if (bWriter != null) { bWriter.close(); } } catch (IOException e) { log_gs.warning("Error closing bWriter"); } finally { try { if (outStreamWriter != null) { outStreamWriter.close(); } } catch (IOException e) { log_gs.warning("Error closing outStreamWriter"); } } try { if (sslsocket != null) { sslsocket.close(); } } catch (Exception e) { log_gs.warning("Error closing sslsocket"); } } } }
/* * This method is use to receive client information according to his code. * The request is a post request */ public String getClientInformations(String url, List<String> parameters, List<String> value) { // If the both list hasn't the same size, then the request will not // be possible. In that case, we return null for the response if (parameters.size() != value.size()) { return null; } String response = null; int i = 0; int size = value.size(); String reqParameters = ""; OutputStreamWriter outWriter = null; URL myUrl; try { // We set the parameters of the request. We scan both of the list // and we set the parameters of request according to the index of // both lists. while (i < size) { if (i == 0) { reqParameters = URLEncoder.encode(parameters.get(i), "UTF-8") + "=" + URLEncoder.encode(value.get(i), "UTF-8"); } else { reqParameters += "&" + URLEncoder.encode(parameters.get(i), "UTF-8") + "=" + URLEncoder.encode(value.get(i), "UTF-8"); } i += 1; } // We create the connection to instagram myUrl = new URL(url); // We open the connection URLConnection connect = myUrl.openConnection(); // We use connect for output connect.setDoOutput(true); // We send the request; outWriter = new OutputStreamWriter(connect.getOutputStream()); // We add parameters to the request outWriter.write(reqParameters); // We flush the stream outWriter.flush(); // We get response for instagram response = getResponseOfInstagram(connect); // We close the stream outWriter.close(); } catch (Exception exc) { System.out.println(exc.getStackTrace()); } return response; }