Example #1
0
 private void passTcpFileDescriptor(
     LocalSocket fdSocket,
     OutputStream outputStream,
     String socketId,
     String dstIp,
     int dstPort,
     int connectTimeout)
     throws Exception {
   Socket sock = new Socket();
   sock.setTcpNoDelay(true); // force file descriptor being created
   if (protect(sock)) {
     try {
       sock.connect(new InetSocketAddress(dstIp, dstPort), connectTimeout);
       ParcelFileDescriptor fd = ParcelFileDescriptor.fromSocket(sock);
       tcpSockets.put(socketId, sock);
       fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()});
       outputStream.write('*');
       outputStream.flush();
       fd.detachFd();
     } catch (ConnectException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } catch (SocketTimeoutException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } finally {
       outputStream.flush();
     }
   } else {
     LogUtils.e("protect tcp socket failed");
   }
 }
Example #2
0
  public void secondRun() throws Exception {
    // Read the JSESSIONID from the previous run
    FileInputStream fis = new FileInputStream(JSESSIONID);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String jsessionId = br.readLine();
    new File(JSESSIONID).delete();

    Socket sock = new Socket(host, new Integer(port).intValue());
    OutputStream os = sock.getOutputStream();
    String get = "GET " + contextRoot + "/ResumeSession" + " HTTP/1.0\n";
    System.out.println(get);
    os.write(get.getBytes());
    String cookie = "Cookie: " + jsessionId + "\n";
    os.write(cookie.getBytes());
    os.write("\n".getBytes());

    InputStream is = sock.getInputStream();
    br = new BufferedReader(new InputStreamReader(is));

    String line = null;
    boolean found = false;
    while ((line = br.readLine()) != null) {
      System.out.println(line);
      if (line.contains(EXPECTED_RESPONSE)) {
        found = true;
        break;
      }
    }

    if (found) {
      stat.addStatus(TEST_NAME, stat.PASS);
    } else {
      throw new Exception("Wrong response. Expected response: " + EXPECTED_RESPONSE + " not found");
    }
  }
Example #3
0
 /**
  * Checks if a given file exists and, if not, create it by copying a default template from
  * resources; used to create default conf files.
  *
  * @param file The path of the file that needs to exist
  * @param template The path of the template for the file
  */
 public static void ensureFileExists(final String file, final String template) {
   if (LAUNCHED_FROM_JAR && !Files.exists(Paths.get(file))) {
     if (Debug.on) printDebug("[Meta] " + file + " does not exist: creating a default one.");
     InputStream stream = Meta.class.getResourceAsStream(template);
     if (stream == null) {
       printDebug(
           "[ WARNING ] template for "
               + template
               + " not found. Won't create a default "
               + file
               + ".");
     } else {
       int readBytes;
       byte[] buffer = new byte[4096];
       try (OutputStream outStream = new FileOutputStream(new File(file))) {
         while ((readBytes = stream.read(buffer)) > 0) {
           outStream.write(buffer, 0, readBytes);
         }
         if (Debug.on)
           printDebug("[Meta] created default file " + file + " from " + template + ".");
       } catch (IOException e) {
         e.printStackTrace();
       } finally {
         try {
           stream.close();
         } catch (IOException ignore) {
         }
       }
     }
   } else {
     if (Meta.LAUNCHED_FROM_JAR && Debug.on) printDebug("[Meta] file exists: " + file + ".");
   }
 }
Example #4
0
  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);
  }
Example #5
0
  private void invokeJsp() throws Exception {

    Socket sock = new Socket(host, new Integer(port).intValue());
    OutputStream os = sock.getOutputStream();
    String get = "GET " + contextRoot + "/jsp/test1.jsp" + " HTTP/1.0\n";
    System.out.println(get);
    os.write(get.getBytes());
    os.write("\n".getBytes());

    InputStream is = sock.getInputStream();
    BufferedReader bis = new BufferedReader(new InputStreamReader(is));

    String line = null;
    while ((line = bis.readLine()) != null) {
      if (line.startsWith("Location:")) {
        break;
      }
    }

    if (line != null) {
      System.out.println(line);

      // Check the path
      if (line.startsWith("Location: " + PATH)) {
        fail = false;
      } else {
        System.err.println("Wrong path: " + line + ", expected: " + PATH);
        stat.addStatus(TEST_NAME, stat.FAIL);
        fail = true;
      }
    } else {
      System.err.println("Missing Location response header");
      stat.addStatus(TEST_NAME, stat.FAIL);
    }
  }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    sslSocket.close();
  }
Example #7
0
 private boolean userPassAuth() throws IOException {
   int ver = in.read();
   int ulen = in.read();
   if (ulen <= 0) throw new SocketException("SOCKS protocol error");
   byte[] buf = new byte[ulen];
   readBuf(in, buf);
   String uname = new String(buf);
   String password = null;
   ulen = in.read();
   if (ulen < 0) throw new SocketException("SOCKS protocol error");
   if (ulen > 0) {
     buf = new byte[ulen];
     readBuf(in, buf);
     password = new String(buf);
   }
   // Check username/password validity here
   System.err.println("User: '******'" + password);
   if (users.containsKey(uname)) {
     String p1 = users.get(uname);
     System.err.println("p1 = " + p1);
     if (p1.equals(password)) {
       out.write(PROTO_VERS);
       out.write(REQUEST_OK);
       out.flush();
       return true;
     }
   }
   out.write(PROTO_VERS);
   out.write(NOT_ALLOWED);
   out.flush();
   return false;
 }
Example #8
0
  public static void main(String args[]) throws Exception {
    int count = 0;
    ServerSocket serv = null;
    InputStream in = null;
    OutputStream out = null;
    Socket sock = null;
    int clientId = 0;
    Map<Integer, Integer> totals = new HashMap<Integer, Integer>();

    try {
      serv = new ServerSocket(8888);
    } catch (Exception e) {
      e.printStackTrace();
    }
    while (serv.isBound() && !serv.isClosed()) {
      System.out.println("Ready...");
      try {
        sock = serv.accept();
        in = sock.getInputStream();
        out = sock.getOutputStream();

        char c = (char) in.read();

        System.out.print("Server received " + c);
        switch (c) {
          case 'r':
            clientId = in.read();
            totals.put(clientId, 0);
            out.write(0);
            break;
          case 't':
            clientId = in.read();
            int x = in.read();
            System.out.print(" for client " + clientId + " " + x);
            Integer total = totals.get(clientId);
            if (total == null) {
              total = 0;
            }
            totals.put(clientId, total + x);
            out.write(totals.get(clientId));
            break;
          default:
            int x2 = in.read();
            int y = in.read();
            System.out.print(" " + x2 + " " + y);
            out.write(x2 + y);
        }
        System.out.println("");
        out.flush();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (out != null) out.close();
        if (in != null) in.close();
        if (sock != null) sock.close();
      }
    }
  }
Example #9
0
 /**
  * Writes an address to the SOCKS connection in domain-name format (including sending the type
  * field).
  *
  * @param host Host name
  * @param port Port
  * @throws IOException
  */
 protected void writeAddress(String host, int port) throws IOException {
   output.write(3); // Domain name
   // Actual name
   output.write(host.length());
   output.write(host.getBytes("ISO-8859-1"));
   // Port in network byte order
   int port1 = port >> 8, port2 = port & 0xff;
   output.write(port1);
   output.write(port2);
 }
Example #10
0
  private void invokeJsp() throws Exception {

    Socket sock = null;
    OutputStream os = null;
    InputStream is = null;
    BufferedReader bis = null;
    try {
      sock = new Socket(host, new Integer(port).intValue());
      os = sock.getOutputStream();
      String get = "GET " + contextRoot + "/jsp/test.jsp HTTP/1.0\n";
      System.out.println(get);
      os.write(get.getBytes());
      os.write("\n".getBytes());

      is = sock.getInputStream();
      bis = new BufferedReader(new InputStreamReader(is));

      boolean found = false;
      String line = null;
      while ((line = bis.readLine()) != null) {
        if (line.endsWith(EXPECTED_ERROR) || line.endsWith(EXPECTED_ERROR_JDK6)) {
          found = true;
          break;
        }
      }

      if (!found) {
        throw new Exception(
            "Wrong response, expected: \n"
                + "For JDK 5: "
                + EXPECTED_ERROR
                + '\n'
                + "For JDK 6: "
                + EXPECTED_ERROR_JDK6);
      }
    } finally {
      try {
        if (os != null) os.close();
      } catch (IOException ex) {
      }
      try {
        if (is != null) is.close();
      } catch (IOException ex) {
      }
      try {
        if (sock != null) sock.close();
      } catch (IOException ex) {
      }
      try {
        if (bis != null) bis.close();
      } catch (IOException ex) {
      }
    }
  }
Example #11
0
    private void doConnect(InetSocketAddress addr) throws IOException {
      dest = new Socket();
      try {
        dest.connect(addr, 10000);
      } catch (SocketTimeoutException ex) {
        sendError(HOST_UNREACHABLE);
        return;
      } catch (ConnectException cex) {
        sendError(CONN_REFUSED);
        return;
      }
      // Success
      InetAddress iadd = addr.getAddress();
      if (iadd instanceof Inet4Address) {
        out.write(PROTO_VERS);
        out.write(REQUEST_OK);
        out.write(0);
        out.write(IPV4);
        out.write(iadd.getAddress());
      } else if (iadd instanceof Inet6Address) {
        out.write(PROTO_VERS);
        out.write(REQUEST_OK);
        out.write(0);
        out.write(IPV6);
        out.write(iadd.getAddress());
      } else {
        sendError(GENERAL_FAILURE);
        return;
      }
      out.write((addr.getPort() >> 8) & 0xff);
      out.write((addr.getPort() >> 0) & 0xff);
      out.flush();

      InputStream in2 = dest.getInputStream();
      OutputStream out2 = dest.getOutputStream();

      Tunnel tunnel = new Tunnel(in2, out);
      tunnel.start();

      int b = 0;
      do {
        // Note that the socket might be closed from another thread (the tunnel)
        try {
          b = in.read();
          if (b == -1) {
            in.close();
            out2.close();
            return;
          }
          out2.write(b);
        } catch (IOException ioe) {
        }
      } while (!client.isClosed());
    }
Example #12
0
 // Send error message then close the streams
 private void sendError(int code) {
   try {
     out.write(PROTO_VERS);
     out.write(code);
     out.write(0);
     out.write(IPV4);
     for (int i = 0; i < 6; i++) out.write(0);
     out.flush();
     out.close();
   } catch (IOException ex) {
   }
 }
Example #13
0
  private void goGet(String host, int port, String contextPath) throws Exception {

    sock = new Socket(host, port);
    OutputStream os = sock.getOutputStream();

    System.out.println(("GET " + contextPath + " HTTP/1.0\n"));
    os.write(("GET " + contextPath + " HTTP/1.0\n").getBytes());
    os.write("\n".getBytes());

    InputStream is = null;
    BufferedReader bis = null;
    String line = null;
    boolean pass = false;
    try {
      is = sock.getInputStream();
      bis = new BufferedReader(new InputStreamReader(is));
      while ((line = bis.readLine()) != null) {
        System.out.println(line);
        // Check if the filter was invoked
        if (EXPECTED_RESPONSE.equals("LLiFFiSSi")) {
          pass = true;
          break;
        }
      }
    } finally {
      try {
        if (is != null) {
          is.close();
        }
      } catch (IOException ioe) {
        // ignore
      }
      try {
        if (bis != null) {
          bis.close();
        }
      } catch (IOException ioe) {
        // ignore
      }
    }

    if (pass) {
      System.out.println("security constraint processed");
      stat.addStatus(TEST_NAME + " PASSED", stat.PASS);
    } else {
      System.out.println("security constraint NOT processed");
      stat.addStatus(TEST_NAME + " FAILED", stat.FAIL);
    }
  }
Example #14
0
 // Negociate the authentication scheme with the client
 private void negociate() throws IOException {
   int ver = in.read();
   int n = in.read();
   byte[] buf = null;
   if (n > 0) {
     buf = new byte[n];
     readBuf(in, buf);
   }
   int scheme = NO_AUTH;
   for (int i = 0; i < n; i++) if (buf[i] == USER_PASSW) scheme = USER_PASSW;
   out.write(PROTO_VERS);
   out.write(scheme);
   out.flush();
   if (scheme == USER_PASSW) userPassAuth();
 }
Example #15
0
  // Send File
  public void sendFile(String chunkName) throws IOException {
    OutputStream os = null;
    String currentDir = System.getProperty("user.dir");
    chunkName = currentDir + "/src/srcFile/" + chunkName;
    File myFile = new File(chunkName);

    byte[] arrby = new byte[(int) myFile.length()];

    try {
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(arrby, 0, arrby.length);

      os = csocket.getOutputStream();
      System.out.println("Sending File.");
      os.write(arrby, 0, arrby.length);
      os.flush();
      System.out.println("File Sent.");
      //			os.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //			os.close();
    }
  }
Example #16
0
 private void downloadInternal(URI address, File destination) throws Exception {
   OutputStream out = null;
   URLConnection conn;
   InputStream in = null;
   try {
     URL url = address.toURL();
     out = new BufferedOutputStream(new FileOutputStream(destination));
     conn = url.openConnection();
     final String userAgentValue = calculateUserAgent();
     conn.setRequestProperty("User-Agent", userAgentValue);
     in = conn.getInputStream();
     byte[] buffer = new byte[BUFFER_SIZE];
     int numRead;
     long progressCounter = 0;
     while ((numRead = in.read(buffer)) != -1) {
       progressCounter += numRead;
       if (progressCounter / PROGRESS_CHUNK > 0) {
         System.out.print(".");
         progressCounter = progressCounter - PROGRESS_CHUNK;
       }
       out.write(buffer, 0, numRead);
     }
   } finally {
     System.out.println("");
     if (in != null) {
       in.close();
     }
     if (out != null) {
       out.close();
     }
   }
 }
Example #17
0
  /**
   * Method to update database on the server with new and changed hazards given as a JSONObject
   * instance
   *
   * @param uploadHazards A JSONObject instance with encoded new and update hazards
   * @throws IOException
   */
  public static void uploadHazards(JSONObject uploadHazards) throws IOException {
    // upload hazards in json to php (to use json_decode)
    // Hazard parameter should be encoded as json already

    // Set Post connection
    URL url = new URL(site + "/update.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setRequestMethod("POST");

    OutputStream writer = conn.getOutputStream();
    writer.write(
        uploadHazards.toString().getBytes("UTF-8")); // toString produces compact JSONString
    // no white space
    writer.close();
    // read response (success / error)

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer response = new StringBuffer();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();
  }
Example #18
0
 private static void writePostReply(HttpExchange msg, byte[] buf) throws Exception {
   msg.getResponseHeaders().add("Content-Type", "text/xml");
   msg.sendResponseHeaders(200, buf.length);
   OutputStream out = msg.getResponseBody();
   out.write(buf);
   out.close();
 }
Example #19
0
 public void run() {
   try {
     Thread.sleep(10);
     byte[] buf = getBuf();
     URL url = new URL("http://127.0.0.1:" + port + "/test");
     HttpURLConnection con = (HttpURLConnection) url.openConnection();
     con.setDoOutput(true);
     con.setDoInput(true);
     con.setRequestMethod("POST");
     con.setRequestProperty(
         "Content-Type",
         "Multipart/Related; type=\"application/xop+xml\"; boundary=\"----=_Part_0_6251267.1128549570165\"; start-info=\"text/xml\"");
     OutputStream out = con.getOutputStream();
     out.write(buf);
     out.close();
     InputStream in = con.getInputStream();
     byte[] newBuf = readFully(in);
     in.close();
     if (buf.length != newBuf.length) {
       System.out.println("Doesn't match");
       error = true;
     }
     synchronized (lock) {
       ++received;
       if ((received % 1000) == 0) {
         System.out.println("Received=" + received);
       }
     }
   } catch (Exception e) {
     // e.printStackTrace();
     System.out.print(".");
     error = true;
   }
 }
  public static void main(String args[]) {
    int size = 1024;
    File site = new File("site.html");

    OutputStream outStream = null;
    InputStream is;

    try {
      URL url;
      byte[] buf;
      int ByteRead;
      url =
          new URL(
              "http://zakupki.gov.ru/epz/order/notice/ea44/view/common-info.html?regNumber=0148300015814000370");
      System.out.println(url.getFile());
      outStream = new BufferedOutputStream(new FileOutputStream(site));
      URLConnection uCon = url.openConnection();
      is = uCon.getInputStream();
      buf = new byte[size];
      while ((ByteRead = is.read(buf)) != -1) {
        outStream.write(buf, 0, ByteRead);
      }
      System.out.println("Downloaded Successfully.");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #21
0
 public void sendMessage(String message) {
   checkConnected();
   HttpURLConnection outcomeConnection = null;
   try {
     CLIENT_LOGGER.info("start sending message \"" + message + "\"");
     outcomeConnection = prepareOutputConnection();
     byte[] buffer = MessageHelper.buildSendMessageRequestBody(message).getBytes();
     OutputStream outputStream = outcomeConnection.getOutputStream();
     outputStream.write(buffer, 0, buffer.length);
     outputStream.close();
     outcomeConnection.getInputStream(); // to send data to server
     CLIENT_LOGGER.info("message sent");
   } catch (ConnectException e) {
     logger.error("Connection error. Disconnecting...", e);
     CLIENT_LOGGER.error("connection error", e);
     disconnect();
   } catch (IOException e) {
     CLIENT_LOGGER.error("IOException", e);
     logger.error("IOException occurred while sending message", e);
   } finally {
     if (outcomeConnection != null) {
       outcomeConnection.disconnect();
     }
     CLIENT_LOGGER.info("stop sending message \"" + message + "\"");
   }
 }
Example #22
0
  public static void ensureExists(File thing, String resource) {
    System.err.println("configfile = " + thing);
    if (!thing.exists()) {
      try {
        System.err.println("Creating: " + thing + " from " + resource);
        if (resource.indexOf("/") != 0) {
          resource = "/" + resource;
        }

        InputStream is = Config.class.getResourceAsStream(resource);
        if (is == null) {
          throw new NullPointerException("Can't find resource: " + resource);
        }
        getParentFile(thing).mkdirs();
        OutputStream os = new FileOutputStream(thing);

        for (int next = is.read(); next != -1; next = is.read()) {
          os.write(next);
        }

        os.flush();
        os.close();
      } catch (FileNotFoundException fnfe) {
        throw new Error("Can't create resource: " + fnfe.getMessage());
      } catch (IOException ioe) {
        throw new Error("Can't create resource: " + ioe.getMessage());
      }
    }
  }
Example #23
0
  public void copyFile(String file1, String file2) {
    InputStream inStream = null;
    OutputStream outStream = null;

    try {

      File afile = new File(file1);
      File bfile = new File(file2);

      inStream = new FileInputStream(afile);
      outStream = new FileOutputStream(bfile);

      byte[] buffer = new byte[1024];

      int length;
      // copy the file content in bytes
      while ((length = inStream.read(buffer)) > 0) {

        outStream.write(buffer, 0, length);
      }

      inStream.close();
      outStream.close();

      System.out.println("File is copied successful!");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #24
0
  public static void main(String[] args) throws IOException {
    int servPort = Integer.parseInt(args[0]);
    ServerSocket servSock = new ServerSocket(8080); // cria o socket servidor

    int recvMsgSize; // tamanho da msg
    byte[] byteBuffer = new byte[BufSize]; // buffer de recebimento

    for (; ; ) {
      // espera as solicitações dos clientes
      Socket clntSock = servSock.accept(); // server aceita a conexão
      // imprimi o ip e a porta do servidor
      System.out.println(
          "Controlando o cliente"
              + clntSock.getInetAddress().getHostAddress()
              + "na porta"
              + clntSock.getPort());

      InputStream in = clntSock.getInputStream();
      OutputStream out = clntSock.getOutputStream();

      while ((recvMsgSize = in.read(byteBuffer))
          != -1) // lê a msg a ser transmitida até estourar o tamanho
      out.write(byteBuffer, 0, recvMsgSize);
      clntSock.close(); // fecha o socket do cliente
    }
  }
  void serviceClientApp(final Socket socket) throws Throwable {

    socket.setTcpNoDelay(true);

    final InputStream clientInput = socket.getInputStream();
    clientOutput = socket.getOutputStream();
    patchNumber = 1;

    mainFilePath = readPath(clientInput, false);

    byte ok[] = new byte[] {1, 0, 0, 0};
    clientOutput.write(ok);

    executablePath = readPath(clientInput, true);

    new Thread(
            new Runnable() {
              public void run() {
                try {
                  while (true) {
                    int bundleLoaded = readInt(clientInput);
                  }
                } catch (IOException e) {
                } finally {
                  try {
                    socket.close();
                  } catch (IOException e) {
                  }
                  clientOutput = null;
                }
              }
            })
        .start();
  }
Example #26
0
  // postToRestfulApi -
  // Note: params in the addr field need to be URLEncoded
  private String postToRestfulApi(
      String addr, String data, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);
    String result = "";
    try {
      URLConnection connection = new URL(API_ROOT + addr).openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        connection.setDoInput(true);
      }
      connection.setDoOutput(true);
      connection.setRequestProperty("Accept-Charset", "UTF-8");

      // Post JSON string to URL
      OutputStream os = connection.getOutputStream();
      byte[] b = data.getBytes("UTF-8");
      os.write(b);

      // Receive results back from API
      InputStream is = connection.getInputStream();
      result = IOUtils.toString(is, "UTF-8");

      String newCookie = getConnectionInfiniteCookie(connection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
    } catch (Exception e) {
      // System.out.println("Exception: " + e.getMessage());
    }
    return result;
  } // TESTED
Example #27
0
 void handleRequest(InputStream in, OutputStream out) throws IOException {
   boolean newline = false;
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       throw new EOFException();
     }
     sb.append((char) ch);
     if (ch == '\r') {
       // empty
     } else if (ch == '\n') {
       if (newline) {
         // 2nd newline in a row, end of request
         break;
       }
       newline = true;
     } else {
       newline = false;
     }
   }
   String request = sb.toString();
   if (request.startsWith("GET / HTTP/1.") == false) {
     throw new IOException("Invalid request: " + request);
   }
   out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes());
 }
  public AuthenticatedSocket(InetAddress ia, int port, MessageDigest md, byte[] secret)
      throws IOException, AuthenticationException {
    super(ia, port);

    try {
      OutputStream output = this.getOutputStream();
      InputStream input = this.getInputStream();

      // Get challenge length
      byte[] challengeSize = new byte[4];
      input.read(challengeSize);

      // Receive random challenge string
      byte[] challenge = new byte[Bytes.toInt(challengeSize)];
      input.read(challenge);

      // Generate MD5 hash
      byte[] append = Bytes.append(challenge, secret);
      byte[] hash = md.digest(append);

      // Send time and hash strings
      output.write(hash);
    } catch (Exception e) {
      throw new AuthenticationException("Authentication failed: " + e.getMessage());
    }
  }
Example #29
0
 /**
  * ** Writes the specified byte array to the specified socket's output stream ** @param socket The
  * socket which's output stream to write to ** @param b The byte array to write to the socket
  * output stream ** @throws IOException if an error occurs
  */
 protected static void socketWriteBytes(Socket socket, byte b[]) throws IOException {
   if ((socket != null) && (b != null)) {
     OutputStream output = socket.getOutputStream();
     output.write(b);
     output.flush();
   }
 }
Example #30
0
 /**
  * Unwatches an event.
  *
  * @param name event name
  * @throws IOException I/O exception
  */
 public void unwatch(final String name) throws IOException {
   out.write(11);
   send(name);
   info = receive();
   if (!ok()) throw new IOException(info);
   notifiers.remove(name);
 }