/**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy with Basic
   * authentication. It issues a CONNECT request and authenticates with the HTTP proxy with Basic
   * protocol.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket authenticateBasic(InetSocketAddress address, ConnectivitySettings cs)
      throws IOException {
    Socket proxy = new Socket(cs.getProxyHost(), cs.getProxyPort());
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    String username = cs.getProxyUsername() == null ? "" : cs.getProxyUsername();
    String password = cs.getProxyPassword() == null ? "" : String.valueOf(cs.getProxyPassword());
    String credentials = username + ":" + password;
    String basicCookie = Base64Encoder.encode(credentials.getBytes("US-ASCII"));

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n");
    dos.writeBytes("Proxy-Authorization: Basic " + basicCookie + "\r\n");
    dos.writeBytes("\r\n");
    dos.flush();

    String line = r.readLine();
    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    }
    throw new IOException("Basic authentication failed: " + line);
  }
  private HtmlRequest readRequest(Socket socket) throws IOException {

    BufferedReader requestBufferedReader =
        new BufferedReader(new InputStreamReader(socket.getInputStream()));
    StringBuilder requestStringBuilder = new StringBuilder();
    try {
      String line = requestBufferedReader.readLine();

      while (!line.isEmpty()) {
        requestStringBuilder.append(line + NEWLINE);
        line = requestBufferedReader.readLine();
      }

    } catch (IOException e) {
      System.out.println("An error occured while reading from the socket: " + e.toString());
    }
    if (requestStringBuilder.toString().isEmpty()) {
      return null;
    }
    HtmlRequest htmlRequest = new HtmlRequest(requestStringBuilder.toString());
    if (htmlRequest.type.equals("POST") || htmlRequest.type.equals("TRACE")) {
      htmlRequest.getParametersFromBody(requestBufferedReader);
    }
    return htmlRequest;
  }
Example #3
0
  private static void serverWaiting() throws Exception {
    System.out.println("Waiting Mode");
    ServerSocket waitingSocket = new ServerSocket(serverInfo.getPort());
    String line;

    while (true) {
      Socket connectionSocket = waitingSocket.accept();
      BufferedReader in =
          new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
      DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream());
      // System.out.println("Waiting for migration");
      line = in.readLine();
      // System.out.println("Received: " + line);
      String info = line;
      out.writeBytes("Info OK\n");
      line = in.readLine();
      // System.out.println("Received: " + line);
      serverInit();
      game.setMoving(true);
      reconstruction(info);
      out.writeBytes("Bind OK\n");
      waitingSocket.close();
      break;
    }
    while (!allConnected) {
      System.out.print("");
    }
    game.setMoving(false);
    // System.out.println("Fin server waiting");
    serverRunning();
  }
Example #4
0
  private static void recuperacionFallas() {
    File file = new File(serverName + ".swp");
    if (file.exists()) {
      try {
        System.out.println("Un fichero de salvaguarda es presente:");
        System.out.println("Quiere recuperar el antiguo juego(y/n)?");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
          String s = in.readLine();
          if (s.equals("y")) {
            recuperationServer();
            InputStream ips = new FileInputStream(serverName + ".swp");
            InputStreamReader ipsr = new InputStreamReader(ips);
            BufferedReader br = new BufferedReader(ipsr);
            String info = br.readLine();
            reconstruction(info);
            game.setRecoveringServer(false);
            break;
          } else if (s.equals("n")) {
            serverInit();
            break;
          }
        }

      } catch (FileNotFoundException e) {
        System.out.println("Failed to wait");
      } catch (IOException e) {
        System.out.println("Failed to wait");
      }

    } else serverInit();
    saveStateServer();
  }
Example #5
0
 public static void main(String[] args) {
   try {
     ServerSocket server = null;
     try {
       server = new ServerSocket(4700);
     } catch (Exception e) {
       System.out.println("Can Not Listem To:" + e);
     }
     Socket socket = null;
     try {
       socket = server.accept();
     } catch (Exception e) {
       System.out.println("Error: " + e);
     }
     String line;
     BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     PrintWriter os = new PrintWriter(socket.getOutputStream());
     BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
     System.out.println("Client:" + is.readLine());
     line = sin.readLine();
     while (!line.equals("bye")) {
       os.println(line);
       os.flush();
       System.out.println("Server:" + line);
       System.out.println("Client:" + is.readLine());
       line = sin.readLine();
     }
     os.close();
     is.close();
     socket.close();
     server.close();
   } catch (Exception e) {
     System.out.println("Error:" + e);
   }
 }
  /**
   * Load string map from a URL.
   *
   * @param mapURL URL for map file.
   * @param separator Field separator.
   * @param qualifier Quote character.
   * @param encoding Character encoding for the file.
   * @throws FileNotFoundException If input file does not exist.
   * @throws IOException If input file cannot be opened.
   * @return Map with values read from file.
   */
  public static Map<String, String> loadMap(
      URL mapURL, String separator, String qualifier, String encoding)
      throws IOException, FileNotFoundException {
    Map<String, String> map = MapFactory.createNewMap();

    if (mapURL != null) {
      BufferedReader bufferedReader =
          new BufferedReader(new UnicodeReader(mapURL.openStream(), encoding));

      String inputLine = bufferedReader.readLine();
      String[] tokens;

      while (inputLine != null) {
        tokens = inputLine.split(separator);

        if (tokens.length > 1) {
          map.put(tokens[0], tokens[1]);
        }

        inputLine = bufferedReader.readLine();
      }

      bufferedReader.close();
    }

    return map;
  }
Example #7
0
  protected static synchronized String getVRMLreply(int queryno) {

    String req = "0";
    String rep = "";

    // This waits for the correct event toe be returned. Note that
    // sendevents dont wait, so there is the possibility that
    // we will have to while away a bit of time waiting...

    while (queryno != Integer.parseInt(req)) {
      try {
        req = BrowserfromEAI.readLine();
      } catch (IOException ie) {
        System.out.println("EAI: caught " + ie);
        return rep;
      }

      if (queryno != Integer.parseInt(req)) {
        System.out.println(
            "EAI: getVRMLreply - REPLIES MIXED UP!!! Expecting " + queryno + " got " + req);
      }

      try {
        rep = BrowserfromEAI.readLine();
      } catch (IOException ie) {
        System.out.println("EAI: getVRMLreply failed");
        return null;
      }
    }

    return rep;
  }
Example #8
0
  private String getTitle(File f) {
    String result = "";
    if (!f.getName().endsWith(".html")) return "not HTML";
    else {
      try {
        BufferedReader reader = new BufferedReader(new FileReader(f));
        String ligne = reader.readLine();
        while (ligne != null && !ligne.contains("<TITLE>") && !ligne.contains("<title>")) {
          ligne = reader.readLine();
        }
        reader.close();
        if (ligne == null) return "No TITLE in page " + f.getName();
        else {
          String fin = "";
          String debut = "";
          if (ligne.contains("</TITLE>")) {
            debut = "<TITLE>";
            fin = "</TITLE>";
          } else if (ligne.contains("</title>")) {
            debut = "<title>";
            fin = "</title>";
          } else return "No title in page " + f.getName();

          int fin_index = ligne.lastIndexOf(fin);
          result = ligne.substring(ligne.indexOf(debut) + 7, fin_index);
          return result;
        }
      } catch (Exception e) {
        LOG.error("Error while reading file " + e);
        return "Error for file " + f.getName();
      }
    }
  }
  private ServerSocketDemo() {
    try {
      ss = new ServerSocket(2002);
      s = ss.accept();

      System.out.println("Server started");
      local = new BufferedReader(new InputStreamReader(System.in));
      remote = new BufferedReader(new InputStreamReader(s.getInputStream()));
      ps = new PrintStream(s.getOutputStream());

      while (true) {
        System.out.println("Type a message to send to the client");
        String localdata = local.readLine();
        ps.println(localdata); // sends the data to output stream
        String remotedata = remote.readLine();
        System.out.println("Client:= " + remotedata);
        if (remotedata.equals("bye")) {
          System.out.println("Client Disconnected");
          break;
        }
      }
    } catch (Exception e) {
      System.out.println("Error in Server" + e);
    }
  }
Example #10
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 #11
0
  public String readFileFromJAR(String filepath) {

    String out = "";

    try {

      // setup input buffer
      ClassLoader cl = this.getClass().getClassLoader();
      InputStream instream = cl.getResourceAsStream(filepath);
      BufferedReader filereader = new BufferedReader(new InputStreamReader(instream));

      // read lines
      String line = filereader.readLine();
      while (line != null) {
        out += "\n" + line;
        line = filereader.readLine();
      }

      filereader.close();

    } catch (Exception e) {
      // e.printStackTrace();
    }

    return out;
  }
  /** The logic that runs in separate thread. Dispatching responses. */
  public void run() {
    if (connection == null) {
      logger.error("No connection.");
      return;
    }

    try {
      connectionReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      if (!connectionReader.readLine().contains("XiVO")) {
        logger.error("Error xivo with server!");
        destroy();
        return;
      }

      String line;
      while ((line = connectionReader.readLine()) != null || !stopped) {
        try {
          if (logger.isTraceEnabled()) logger.trace("Read from server:" + line);

          handle((JSONObject) JSONValue.parseWithException(line));
        } catch (Throwable ex) {
          logger.error("Error parsing object:" + line, ex);
        }
      }
    } catch (IOException ex) {
      destroy();
    }
  }
  void writeoneline(String filename1, String filename2) throws IOException {
    // open the file for reading
    BufferedReader file = new BufferedReader(new FileReader(filename1));

    String line = null;
    // send message
    System.out.println("Sending message to the server...");

    while ((line = file.readLine()) != null) {
      String onebyone = line;
      output.println(onebyone);
    }
    file.close();

    // open the file for reading
    PrintWriter file2 = new PrintWriter(new BufferedWriter(new FileWriter(filename2)));
    String line2 = input.readLine();
    // receive a message
    // String response = input.readLine();
    if (line2.isEmpty()) System.out.println("(server did not reply with a message)");
    else {
      System.out.println("Writing to file...:");
      // String line= null;

      file2.println(line2);
      file2.close();
    }
    System.out.println("Done!");
  }
  private String printPOPOptions() throws IOException {
    System.out.println("****************INBOX OPTIONS*****************");
    System.out.println(
        "Press (1) to read a message\n"
            + "Press (2) to delete a message\n"
            + "Press (3) to return to menu\n"
            + "**********************************************");

    int option = 3;
    try {
      option = Integer.parseInt(writer.readLine());
    } catch (IOException e) {
      System.out.println(e);
    }
    switch (option) {
      case 1:
        System.out.print("Please type the ID of the message you would like to read: ");
        return ("retr " + Integer.parseInt(writer.readLine()));

      case 2:
        System.out.print("Please type the ID of the message you would like to delete: ");
        return ("dele " + Integer.parseInt(writer.readLine()));

      case 3:
        return "quit POP3";
    }
    return "quit POP3";
  }
  public void connect(GUIClient GUI) throws IOException {

    try {
      connectSocket = new Socket(ServerIp, ServerPort);
      out = new PrintWriter(connectSocket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(connectSocket.getInputStream()));
    } catch (UnknownHostException e) {
      System.err.println("Cannot Connect to server");
      // System.exit(1);
    } catch (IOException e) {
      System.err.println("Couldn't get I/O for " + "the connection to: " + ServerIp.toString());
      // System.exit(1);
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

    String clientInput = GUI.getJTareaOut().getText();

    while ((clientInput = stdIn.readLine()) != null) {
      out.println(clientInput);
      System.out.println("Writing: " + in.readLine());
    }

    out.close();
    in.close();
    stdIn.close();
    connectSocket.close();
  }
Example #16
0
  // **********************************************************************************
  //
  // Theoretically, you shouldn't have to alter anything below this point in this file
  //      unless you want to change the color of your agent
  //
  // **********************************************************************************
  public void getConnected(String args[]) {
    try {
      // initial connection
      int port = 3000 + Integer.parseInt(args[1]);
      s = new Socket(args[0], port);
      sout = new PrintWriter(s.getOutputStream(), true);
      sin = new BufferedReader(new InputStreamReader(s.getInputStream()));

      // read in the map of the world
      numNodes = Integer.parseInt(sin.readLine());
      int i, j;
      for (i = 0; i < numNodes; i++) {
        world[i] = new node();
        String[] buf = sin.readLine().split(" ");
        world[i].posx = Double.valueOf(buf[0]);
        world[i].posy = Double.valueOf(buf[1]);
        world[i].numLinks = Integer.parseInt(buf[2]);
        // System.out.println(world[i].posx + ", " + world[i].posy);
        for (j = 0; j < 4; j++) {
          if (j < world[i].numLinks) {
            world[i].links[j] = Integer.parseInt(buf[3 + j]);
            // System.out.println("Linked to: " + world[i].links[j]);
          } else world[i].links[j] = -1;
        }
      }
      currentNode = Integer.parseInt(sin.readLine());

      String myinfo =
          args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink
      // send the agents name and color
      sout.println(myinfo);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
    private String getAddressXY(String x, String y) {
      try {
        StringBuilder text = new StringBuilder();

        String url = properties.getProperty("geocoderUrl");
        String param1 = properties.getProperty("geocoderUrlParam1");
        String param2 = properties.getProperty("geocoderUrlParam2");
        url = url + "?" + param1 + "=" + x + "&" + param2 + "=" + y;

        URL page = new URL(url);
        HttpURLConnection urlConn = (HttpURLConnection) page.openConnection();
        urlConn.connect();
        InputStreamReader in = new InputStreamReader((InputStream) urlConn.getContent());
        BufferedReader buff = new BufferedReader(in);
        String line = buff.readLine();

        while (line != null) {
          text.append(line);
          line = buff.readLine();
        }

        String result = text.toString();
        buff.close();
        in.close();

        return result;

      } catch (MalformedURLException e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");
        return "";
      } catch (Exception e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");
        return "";
      }
    }
 private void sourcesMenu() throws IOException {
   System.out.println("List of all known sources");
   for (int i = 0; i < repo.getSources().size(); i++) {
     System.out.println(repo.getSources().get(i));
   }
   System.out.println("Enter 1 or 'add' to add a source.");
   System.out.println("Enter 0 or 'back' to return to the main menu.");
   input = in.readLine();
   if (input.equals("0") || input.equals("back")) {
     name = MenuName.MAIN;
   } else if (input.equals("1") || input.equals("add")) {
     System.out.println("Please enter the URL or filepath to the source.");
     System.out.println("Enter 0 or 'back' to return to the source menu.");
     input = in.readLine();
     if (input.equals("0") || input.equals("back")) {
       return;
     }
     try {
       repo.getSources().add((new URL(input)));
       System.out.println("Source has been added to the repository.");
     } catch (MalformedURLException me) {
       System.out.println("Invalid URL or file path.");
     }
   }
 }
Example #19
0
 private Vector readServerResponse_(InputStream is) throws IOException {
   InputStreamReader isr = new InputStreamReader(is);
   BufferedReader br = new BufferedReader(isr);
   Vector ret = new Vector();
   String line = br.readLine();
   while (line != null) {
     ret.addElement(line);
     line = br.readLine();
   }
   return ret;
 }
Example #20
0
  public static void main(String args[]) {
    int port;
    String host;

    if (args.length == 1) {
      try {
        port = Integer.parseInt(args[0]);

        doEcho(port);

      } catch (IOException io_ex) {
        io_ex.printStackTrace();
        System.exit(1);

      } catch (NumberFormatException num_ex) {
        num_ex.printStackTrace();
        System.exit(1);
      }
    } else if (args.length == 2) {
      try {
        host = args[0];
        port = Integer.parseInt(args[1]);

        UDPEcho ut = new UDPEcho(host, port);
        Thread thread = new Thread(ut);
        thread.start();

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String s;
        System.out.print("Enter datagram:");
        s = in.readLine();
        while (s != null) {
          ut.send(s);
          try {
            Thread.currentThread().sleep(100);
          } catch (InterruptedException i_ex) {
          }
          System.out.print("Enter datagram:");
          s = in.readLine();
        }
        System.exit(1);

      } catch (IOException io_ex) {
        io_ex.printStackTrace();
        System.exit(1);
      } catch (NumberFormatException num_ex) {
        num_ex.printStackTrace();
        System.exit(1);
      }

    } else {
      usage();
    }
  }
 public static void main(String[] args) throws Exception {
   String host = (args.length > 0) ? args[0] : "localhost";
   BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Request : ");
   String symbol = console.readLine();
   URL url = new URL("http://" + host + ":8055/" + symbol);
   InputStream in = url.openStream();
   BufferedReader reader = new BufferedReader(new InputStreamReader(in));
   System.out.println("Response : " + reader.readLine());
   reader.close();
 }
Example #22
0
  public static void main(String[] arg) throws IOException {
    ServerSocket connection = new ServerSocket(8080);
    Socket socket = connection.accept();

    InputStream is = socket.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(is));
    String line = in.readLine();
    while (line != null) {
      System.out.println("Robin dit : " + line);
      line = in.readLine();
    }
  }
  public static void main(String[] args) {
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    BufferedReader userInputStream = null;
    String IP = "127.0.0.1";
    final int PORT_NUM = 4444;
    try {
      socket = new Socket(IP, PORT_NUM);
      out = new PrintWriter(socket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
      System.out.println("Unknown host:" + IP + " at port: " + PORT_NUM);
      e.printStackTrace();
      System.exit(0);
    } catch (IOException e) {
      System.out.println("Cannot connect to server...");
      e.printStackTrace();
      System.exit(0);
    }
    String userInput, fromServer;
    try {
      userInputStream = new BufferedReader(new InputStreamReader(System.in));
      while ((fromServer = in.readLine()) != null) {
        System.out.println("Server: " + fromServer);
        if (fromServer.equals(":q")) break;

        userInput = userInputStream.readLine();
        Calendar cal = Calendar.getInstance();
        cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        if (userInput != null) {
          out.println(userInput + " (sent at " + (sdf.format(cal.getTime())) + ")");
        }
      }
    } catch (IOException e) {
      System.out.println("Could not access data from client printstream...");
      e.printStackTrace();
      System.exit(0);
    }
    try {
      out.close();
      in.close();
      userInputStream.close();
      socket.close();
      System.out.println("I love you, bye.");
      System.out.println("Terminating client...");
    } catch (IOException e) {
      System.out.println("Socket and stream closing error...");
      e.printStackTrace();
      System.exit(0);
    }
  }
Example #24
0
  public static void main(String[] args) throws Exception {

    // URL oracle = new URL("http://www.oracle.com/");
    URL oracle = new URL("http://shrib.com/SSnwjY6Q");
    String startTag = "<textarea ";
    String endTag = "</textarea>";
    BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
    StringBuilder result = new StringBuilder();
    String inputLine;
    int textAreaOpened = 0;
    int indexStart = -1;
    int indexEnd = -1;
    int line = 0;
    int lineStart = 0;
    int lineEnd = 0;
    while ((inputLine = in.readLine()) != null) {
      if (indexStart == -1) {
        indexStart = inputLine.indexOf(startTag);
        lineStart = line;
      }
      if (inputLine.indexOf(endTag) != -1) {
        indexEnd = inputLine.indexOf(endTag);
        lineEnd = line;
      }
      line++;
    }

    line = 0;
    in = new BufferedReader(new InputStreamReader(oracle.openStream()));
    int desde = 0;
    int hasta = 0;
    while ((inputLine = in.readLine()) != null) {
      if (line >= lineStart && line <= lineEnd) {
        desde = 0;
        hasta = inputLine.length();
        if (line == lineStart) {
          desde = inputLine.indexOf(">") + 1;
        }
        if (line == lineEnd) {
          hasta = inputLine.lastIndexOf("</textarea>");
        }

        result.append(inputLine.substring(desde, hasta));
      }
      line++;
    }
    System.out.println(result);
    System.out.println(indexStart + "-" + lineStart);
    System.out.println(indexEnd + "-" + lineEnd);

    in.close();
  }
Example #25
0
  public static void main(String args[]) throws Exception {
    int choice;

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Vishwa Based Campus Compute Cloud");

    while (true) {
      System.out.println("");

      if (username != null) {
        System.out.println("1. Logout");
      } else {
        System.out.println("1. Login");
      }

      System.out.println("2. Join the Grid");
      System.out.println("3. Avail the compute facility");

      System.out.println("4. Quit");
      System.out.printf("Enter your choice: ");

      try {
        choice = Integer.parseInt(in.readLine());
      } catch (NumberFormatException ex) {
        System.out.println("WARNING: Enter a number only!");
        continue;
      }

      if (choice == 1) {
        if (username != null) {
          username = null;
        } else {
          System.out.printf("Enter your username: "******"Enter your password: "******"Successfully logged in!");
          } else {
            System.out.println("Unable to login. Please check your credentials.");
            username = null;
          }
        }
      } else if (choice == 2) {
        share();
      } else if (choice == 3) {
        compute();
      } else {
        System.exit(0);
      }
    }
  }
Example #26
0
 static void define(String word, Writer writer, BufferedReader reader)
     throws IOException, UnsupportedEncodingException {
   writer.write("DEFINE fd-eng-lat " + word + "\r\n");
   writer.flush();
   for (String line = reader.readLine(); line != null; line = reader.readLine()) {
     if (line.startsWith("250 ")) return;
     else if (line.startsWith("552")) {
       System.out.println("no definition found for " + word);
       return;
     } else if (line.matches("\\d\\d\\d .*")) continue;
     else if (line.trim().equals(".")) continue;
     else System.out.println(line);
   }
 }
  /**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy. It issues a
   * CONNECT request and eventually authenticates with the HTTP proxy. Supported authentication
   * methods include: Basic.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws UnknownHostException if the proxy host name cannot be resolved
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket getHttpsTunnelSocket(
      InetSocketAddress address, ConnectivitySettings cs, int timeout) throws IOException {
    Socket proxy = new Socket();
    proxy.connect(new InetSocketAddress(cs.getProxyHost(), cs.getProxyPort()), timeout);
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n\r\n");
    dos.flush();

    String line;
    line = r.readLine();

    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    } else if (sProxyAuthRequiredPattern.matcher(line).find()) {
      boolean authMethodSelected = false;
      String authMethod = AUTH_NONE;
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
        if (line.startsWith("Proxy-Authenticate:") && !authMethodSelected) {
          authMethod = line.substring(19).trim();
          if (authMethod.equals(AUTH_BASIC)) {
            authMethodSelected = true;
          }
        }
      }
      // TODO: need to read full response before closing connection?
      proxy.close();

      if (authMethod.startsWith(AUTH_BASIC)) {
        return authenticateBasic(address, cs);
      } else {
        throw new IOException("Unsupported authentication method: " + authMethod);
      }
    } else {
      proxy.close();
      throw new IOException("HTTP proxy does not support CONNECT command. Received reply: " + line);
    }
  }
Example #28
0
  public boolean doUsername(String x) {
    try {

      if (x == null) {
        return false;
      }
      if (x.equals("")) {
        return false;
      }
      String old = username;
      username = x;

      toUser.println("USERNAME_RQUEST");
      toUser.println(username);
      toUser.flush();
      // System.out.println("sent username");
      // keep doing until has a username that is unused
      String reply = fromUser.readLine();
      // System.out.println("this is the reply:" + reply);
      while (reply.equals("USERNAME_USED")) {
        String temp =
            JOptionPane.showInputDialog(
                null,
                "Please enter a new username, \""
                    + username
                    + "\" has been taken on this server or is invalid.");
        if (temp == null) {
          return false;
        }
        username = temp;
        toUser.println(username);
        toUser.flush();
        reply = fromUser.readLine();
        // System.out.println("This is reply" + reply);
      }
      String t = username;
      username = old;
      sendMessage("set my new username to: " + t);
      username = t;
      JOptionPane.showMessageDialog(
          null, "Username \"" + username + "\" has been accepted by the server.");

      return true;

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return false;
    }
  }
Example #29
0
  public static void main(String[] args) {
    String ipv4;
    try {
      System.out.println("Stablishing the server socket...");
      ServerSocket srvSock = new ServerSocket(4201);
      System.out.println(
          "Server socket stablished to "
              + srvSock.getInetAddress().getHostName()
              + " at port number "
              + srvSock.getLocalPort()
              + ".\n");

      try {
        Socket comSock = srvSock.accept();
        System.out.println(
            "New connection stablished with "
                + comSock.getInetAddress().getHostName()
                + " (port "
                + comSock.getPort()
                + "), trying to communicate...");
        // DO STUFF
        try {
          BufferedReader br = new BufferedReader(new InputStreamReader(comSock.getInputStream()));
          ipv4 = br.readLine();
          br.close();
          comSock.close();
          srvSock.close();
          Socket sock = new Socket(ipv4, 4202);
          BufferedReader br2 = new BufferedReader(new InputStreamReader(sock.getInputStream()));
          System.out.println(br2.readLine());
          br2.close();
          sock.close();
          // System.out.println(ipv4);
        } catch (Exception e) {
          e.printStackTrace();
          System.out.println("Connection failed. Try again later.");
        }

      } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Problem with client.\n");
      }

    } catch (Exception e) {
      System.out.println("Failed to create server socket:");
      e.printStackTrace();
    }
  }
  public void run() {
    System.out.println("New Communication Thread Started");

    try {
      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      String inputLine;
      String[] inputTemp = new String[3];

      while ((inputLine = in.readLine()) != null) {
        System.out.println("Server: " + inputLine);

        out.println(inputLine);

        if (inputLine.equals("Bye.")) break;
      }

      out.close();
      in.close();
      clientSocket.close();
    } catch (IOException e) {
      System.err.println("Problem with Communication Server");
      System.exit(1);
    }
  }