コード例 #1
0
ファイル: IRCSandbox.java プロジェクト: frankhale/random
  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);
    }
  }
コード例 #2
0
  /**
   * 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());
  }
コード例 #3
0
  /**
   * {@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);
    }
  }
コード例 #4
0
ファイル: IRCSandbox.java プロジェクト: frankhale/random
 private void sendMSG(String msg) throws IOException {
   try {
     out.write(msg);
     out.flush();
   } catch (IOException ioe) {
     throw (ioe);
   }
 }
コード例 #5
0
    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();
    }
コード例 #6
0
ファイル: Client.java プロジェクト: foxor/fun-finder
  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();
  }
コード例 #7
0
ファイル: DFSMonitor.java プロジェクト: selamat/dfs
  /**
   * 通过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;
  }
コード例 #8
0
ファイル: Client.java プロジェクト: JamJan4444/SEM5
  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();
    }
  }
コード例 #9
0
ファイル: SrlClient2.java プロジェクト: viericwf/SRL
  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.");
    }
  }
コード例 #10
0
  /*
   * 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;
  }
コード例 #11
0
 /**
  * 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;
 }