Exemple #1
0
 private void setFileText(File file, String text) throws Exception {
   BufferedWriter bw =
       new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
   bw.write(text, 0, text.length());
   bw.flush();
   bw.close();
 }
  /**
   * Checks whether a read/write handler exists.
   *
   * @param elementName The element name.
   * @param handlerName The handler name.
   * @param writeHandler True to check write handler, otherwise false.
   * @return True if handler exists, otherwise false.
   * @exception IOException If there was a stream or socket error.
   * @exception ClickException If there was some other error accessing the handler (e.g., the
   *     ControlSocket returned an unknown unknown error code, or the response could otherwise not
   *     be understood).
   * @see #read
   * @see #write
   * @see #getConfigElementNames
   * @see #getElementHandlers
   */
  public boolean checkHandler(String elementName, String handlerName, boolean writeHandler)
      throws ClickException, IOException {
    String handler = handlerName;
    if (elementName != null) handler = elementName + "." + handlerName;
    _out.write((writeHandler ? "CHECKWRITE " : "CHECKREAD ") + handler + "\n");
    _out.flush();

    // make sure we read all the response lines...
    String response = "";
    String lastLine = null;
    do {
      lastLine = _in.readLine();
      if (lastLine == null) throw new IOException("ControlSocket stream closed unexpectedly");
      if (lastLine.length() < 4) throw new ClickException("Bad response line from ControlSocket");
      response = response + lastLine.substring(4);
    } while (lastLine.charAt(3) == '-');

    int code = getResponseCode(lastLine);
    switch (getResponseCode(lastLine)) {
      case CODE_OK:
      case CODE_OK_WARN:
        return true;
      case CODE_NO_ELEMENT:
      case CODE_NO_HANDLER:
      case CODE_HANDLER_ERR:
      case CODE_PERMISSION:
        return false;
      case CODE_UNIMPLEMENTED:
        if (elementName == null) handleErrCode(code, elementName, handlerName, response);
        return checkHandlerWorkaround(elementName, handlerName, writeHandler);
      default:
        handleErrCode(code, elementName, handlerName, response);
        return false;
    }
  }
  private String ask(String cmd) {
    BufferedWriter out = null;
    BufferedReader in = null;
    Socket sock = null;
    String ret = "";
    try {
      System.out.println(server);
      sock = new Socket(server, ServerListener.PORT);
      out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      out.write(cmd, 0, cmd.length());
      out.flush();
      in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      int inr = in.read();
      while (inr != ';') {
        ret += Character.toString((char) inr);
        inr = in.read();
      }
    } catch (IOException io) {
      io.printStackTrace();
    } finally {
      try {
        out.close();
        in.close();
        sock.close();
      } catch (IOException io) {
        io.printStackTrace();
      }
    }

    return ret;
  }
 public static void makeTextFile(String fwrite) throws IOException {
   BufferedWriter writer = new BufferedWriter(new FileWriter(fwrite));
   int i, j;
   for (i = 65; i < 65 + FILESIZE; i++) {
     for (j = 0; j < PACKET_SIZE; j++) {
       writer.write((char) i);
     }
   }
   writer.close();
 }
Exemple #5
0
 /**
  * print the informations for one specified port
  *
  * @param i theport
  * @param output where to write/print
  * @throws IOException
  */
 private void printInfoPort(int i, BufferedWriter output) throws IOException {
   StringBuffer sb = new StringBuffer();
   InetSocketAddress os = getPort(i).getIsa();
   sb.append("Port <" + new Integer(i).toString() + ">\n State : ");
   if (os == null) sb.append("down");
   else {
     sb.append("up\n");
     sb.append(" Colision domain : " + os);
   }
   output.write(sb.toString() + "\n");
   output.flush();
 }
  public void registrarUsuario() {
    String dato = "";
    JSONParser parser = new JSONParser();
    try {
      while (true) {
        dato = dis.readUTF();
        String usuario = "";
        String contraseña = "";
        String contra = "";
        if (dato.equals("Usuario")) {
          while (true) {
            usuario = dis.readUTF();
            if (usuario != null) {
              JSONObject user = new JSONObject();
              user.put(usuario, null);
              FileWriter escribir = new FileWriter("texto.txt");
              BufferedWriter bw = new BufferedWriter(escribir);
              PrintWriter pw = new PrintWriter(bw);
              pw.write(user.toJSONString());
              pw.close();
              bw.close();
              while (true) {
                contra = dis.readUTF();
                if (contra.equals("Contraseña")) {
                  while (true) {
                    contraseña = dis.readUTF();
                    if (contraseña != null) {
                      Object obj = parser.parse(new FileReader("texto.txt"));
                      JSONObject asignaPass = (JSONObject) obj;
                      asignaPass.put(usuario, contra);
                      FileWriter escribir2 = new FileWriter("texto.txt");
                      BufferedWriter bw2 = new BufferedWriter(escribir2);
                      PrintWriter pw2 = new PrintWriter(bw2);
                      pw2.write(asignaPass.toJSONString());
                      bw2.newLine();
                      pw2.close();
                      bw2.close();
                      break;
                    }
                  }
                  break;
                }
              }
              break;
            }
          }
          break;
        }
      }
    } catch (Exception e) {

    }
  }
 // ------------------------------------
 // Send RTSP Response
 // ------------------------------------
 private void send_RTSP_response() {
   try {
     RTSPBufferedWriter.write("RTSP/1.0 200 OK" + CRLF);
     RTSPBufferedWriter.write("CSeq: " + RTSPSeqNb + CRLF);
     RTSPBufferedWriter.write("Session: " + RTSP_ID + CRLF);
     RTSPBufferedWriter.flush();
     // System.out.println("RTSP Server - Sent response to Client.");
   } catch (Exception ex) {
     System.out.println("Exception caught: " + ex);
     System.exit(0);
   }
 }
  public void write(String elementName, String handlerName, String data)
      throws ClickException, IOException {

    String handler = handlerName;
    if (elementName != null) handler = elementName + "." + handlerName;

    _out.write("WRITEDATA " + handler + " " + data.length() + "\n");
    _out.write(data);
    _out.flush();

    handleWriteResponse(elementName, handlerName);
  }
  public static void main(String args[]) {

    int port = 6502;
    SSLServerSocket server;

    try {
      // get the keystore into memory
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(keyStore), keyStorePass);

      // initialize the key manager factory with the keystore data
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, keyStorePass);

      // initialize the SSLContext engine
      // may throw NoSuchProvider or NoSuchAlgorithm exception
      // TLS - Transport Layer Security most generic

      SSLContext sslContext = SSLContext.getInstance("TLS");

      // Inititialize context with given KeyManagers, TrustManagers,
      // SecureRandom defaults taken if null

      sslContext.init(kmf.getKeyManagers(), null, null);

      // Get ServerSocketFactory from the context object
      ServerSocketFactory ssf = sslContext.getServerSocketFactory();
      //  Now like programming with normal server sockets
      ServerSocket serverSocket = ssf.createServerSocket(port);

      System.out.println("Accepting secure connections");

      Socket client = serverSocket.accept();
      System.out.println("Got connection");

      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      String username = in.readLine();
      String password = in.readLine();

      if (username.equals("Josh") && password.equals("GoBucs")) {
        out.write("Greeting Client");
      } else {
        out.write("Sorry, you are not authorized");
      }
      out.flush();
      in.close();
      out.close();
    } catch (Exception e) {
      System.out.println("Exception thrown " + e);
    }
  }
 private boolean saveToFile(String data, String locId) {
   try {
     BufferedWriter out =
         new BufferedWriter(new FileWriter(filePath + "\\log\\" + locId + ".dat", true));
     out.write(data);
     out.newLine();
     out.close();
     return true;
   } catch (Exception e) {
     windowServer.txtErrors.append(e.getMessage() + "\n");
     return false;
   }
 }
 /**
  * A static method to write a line to a BufferedOutputStream and then pass the line to the log
  * method of the supplied PircBot instance.
  *
  * @param bot The underlying PircBot instance.
  * @param out The BufferedOutputStream to write to.
  * @param line The line to be written. "\r\n" is appended to the end.
  * @param encoding The charset to use when encoing this string into a byte array.
  */
 static void sendRawLine(PircBot bot, BufferedWriter bwriter, String line) {
   if (line.length() > bot.getMaxLineLength() - 2) {
     line = line.substring(0, bot.getMaxLineLength() - 2);
   }
   synchronized (bwriter) {
     try {
       bwriter.write(line + "\r\n");
       bwriter.flush();
       bot.log(">>>" + line);
     } catch (Exception e) {
       // Silent response - just lose the line.
     }
   }
 }
  @Override
  protected TicketItemResponse doInBackground(String... urls) {

    TicketItemResponse result = null;

    String uri = GV.URL + "/AddMenuItemToTicketServlet";

    try {

      URL url = new URL(uri);
      CookieManager cookieManager = new CookieManager();
      CookieHandler.setDefault(cookieManager);

      HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("ticketId", String.valueOf(ticketId)));
      params.add(new BasicNameValuePair("menuItemId", String.valueOf(menuItemId)));
      params.add(new BasicNameValuePair("userId", String.valueOf(userId)));
      connection.setRequestMethod("POST");
      connection.setDoInput(true);
      connection.setDoOutput(true);

      OutputStream os = connection.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(getQuery(params));
      writer.flush();
      writer.close();
      os.close();

      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      StringBuilder temp = new StringBuilder();
      String inputLine;

      while ((inputLine = in.readLine()) != null) {
        temp.append((inputLine));
      }

      in.close();

      result = new Gson().fromJson(temp.toString(), TicketItemResponse.class);

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

    return result;
  }
Exemple #13
0
  public static void saveStateServer() {
    String nomFic = serverName + ".swp";

    try {
      FileWriter fw = new FileWriter(nomFic, false);
      BufferedWriter output = new BufferedWriter(fw);

      output.write(infoComplete());
      output.flush();
      output.close();
    } catch (IOException ioe) {
      System.out.print("Erreur : ");
      ioe.printStackTrace();
    }
  }
Exemple #14
0
  private static void writeToFile(String line, File aFile) {
    BufferedWriter bw = null;
    try {
      bw = new BufferedWriter(new FileWriter(aFile));
      bw.write(line);

      bw.close();
    } catch (Exception e) {
      log.error("Failed to save the token for later Single Sign on", e);
    } finally {
      try {
        if (bw != null) bw.close();
      } catch (Exception e) {
      }
    }
  }
  private void outputMessage(String msg, int msgType) {
    if (isInterrupted()) {
      return;
    }

    if (m_msgHandler != null) {
      m_msgHandler.outputMessage(msg + "\n", msgType);
    } else {
      try {
        m_outWriter.write(msg);
        m_outWriter.newLine();
      } catch (Exception ex) {
        System.err.println(msg);
      }
    }
  }
  /**
   * Send a message to remote.
   *
   * <pre>
   *   <length (8 Bytes)><answer>
   * </pre>
   */
  private void sendMessage(BufferedWriter out, String message) {

    System.out.println("To remote: " + message);

    String to = albumName + ";" + message;

    int lg = to.length();
    String l = PM_Utils.stringToString("000000000000" + Integer.toString(lg), 8);

    try {
      out.write(l);
      out.write(to);
      out.flush();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 private void closeOutputFile() {
   try {
     if (m_outWriter != null) {
       m_outWriter.close();
     }
   } catch (IOException ex) {
     System.err.println("Error closing output file.");
   }
 }
Exemple #18
0
  public String performPostCall(String requestURL, String param) {

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy);

    URL url;
    String response = "";
    try {
      url = new URL(requestURL);

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(15000);
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoInput(true);
      conn.setDoOutput(true);

      OutputStream os = conn.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(param);

      writer.flush();
      writer.close();
      os.close();
      // int responseCode=conn.getResponseCode();

      // if (responseCode == HttpURLConnection.HTTP_OK) {
      String line;
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      while ((line = br.readLine()) != null) {
        response += line;
      }
      //  }
      //  else {
      //  response= null;

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

    return response;
  }
Exemple #19
0
  ///
  /// Envoie une requete au server et retourne sa reponse.
  /// Noter que la methode bloque si le serveur ne repond pas.
  ///
  public String send(String request) {
    // Envoyer la requete au serveur
    try {
      request += "\n"; // ajouter le separateur de lignes
      output.write(request, 0, request.length());
      output.flush();
    } catch (java.io.IOException e) {
      System.err.println("Client: Couldn't send message: " + e);
      return "The message could't be sent to the server";
    }

    // Recuperer le resultat envoye par le serveur
    try {
      return input.readLine();
    } catch (java.io.IOException e) {
      System.err.println("Client: Couldn't receive message: " + e);
      return "Couldn't receive message about the server";
    }
  }
 public static void main(String[] args) {
   try {
     ServerSocket server = new ServerSocket(4444);
     System.out.println("Server ready. Listening in port 4444");
     Socket clientSocket = server.accept();
     System.out.println("Connection from client is excepted");
     BufferedWriter out =
         new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
     BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
     String inputLine = null;
     while ((inputLine = in.readLine()) != null) {
       System.out.println("Recieved " + inputLine + " from client");
       out.write("Pong\n");
       System.out.println("Send Pong to client");
       out.flush();
     }
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
Exemple #21
0
  public static void main(String[] args) {

    fileName = dateFormat.format(date);
    try {
      String curDir = System.getProperty("user.dir");
      boolean dirMake = (new File(curDir + "\\Logs\\")).mkdir();
      if (dirMake) {}
      fileWrite = new BufferedWriter(new FileWriter(curDir + "\\Logs\\" + fileName + "log.txt"));
      fileWrite.write("Chat log:" + fileName + "\n");
      fileWrite.flush();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    ChatServer frame = new ChatServer();
    frame.setVisible(true);
    frame.setResizable(false);
    frame.addWindowListener(
        new WindowListener() {
          public void windowClosed(WindowEvent arg0) {
            ClientListener.writeLog();
            System.exit(-1);
          }

          public void windowActivated(WindowEvent arg0) {}

          public void windowClosing(WindowEvent arg0) {
            ClientListener.writeLog();
            System.exit(-1);
          }

          public void windowDeactivated(WindowEvent arg0) {}

          public void windowDeiconified(WindowEvent arg0) {}

          public void windowIconified(WindowEvent arg0) {}

          public void windowOpened(WindowEvent arg0) {}
        });
  }
  // network-y stuff
  private void command(String cmd) {
    BufferedWriter out = null;
    try {
      Socket sock = new Socket(server, ServerListener.PORT);
      out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));

      char[] oar = cmd.toCharArray();
      for (char c : oar) {
        out.write(c);
      }
      out.flush();
    } catch (IOException io) {
      io.printStackTrace();
    } finally {
      try {
        out.close();
      } catch (IOException io) {
        io.printStackTrace();
      }
    }
  }
Exemple #23
0
  /**
   * Returns the result of reading an element's handler.
   *
   * @param elementName The element name.
   * @param handlerName The handler name.
   * @return Char array containing the data.
   * @exception NoSuchHandlerException If there is no such read handler.
   * @exception NoSuchElementException If there is no such element in the current configuration.
   * @exception HandlerErrorException If the handler returned an error.
   * @exception PermissionDeniedException If the router would not let us access the handler.
   * @exception IOException If there was a stream or socket error.
   * @exception ClickException If there was some other error accessing the handler (e.g., the
   *     ControlSocket returned an unknown unknown error code, or the response could otherwise not
   *     be understood).
   * @see #checkHandler
   * @see #write
   * @see #getConfigElementNames
   * @see #getElementHandlers
   */
  public char[] read(String elementName, String handlerName) throws ClickException, IOException {
    String handler = handlerName;
    if (elementName != null) handler = elementName + "." + handlerName;
    _out.write("READ " + handler + "\n");
    _out.flush();

    // make sure we read all the response lines...
    String response = "";
    String lastLine = null;
    do {
      lastLine = _in.readLine();
      if (lastLine == null) throw new IOException("ControlSocket stream closed unexpectedly");
      if (lastLine.length() < 4) throw new ClickException("Bad response line from ControlSocket");
      response = response + lastLine.substring(4);
    } while (lastLine.charAt(3) == '-');

    int code = getResponseCode(lastLine);
    if (code != CODE_OK && code != CODE_OK_WARN)
      handleErrCode(code, elementName, handlerName, response);

    response = _in.readLine();
    if (response == null) throw new IOException("ControlSocket stream closed unexpectedly");
    int num_bytes = getDataLength(response);
    if (num_bytes < 0) throw new ClickException("Bad length returned from ControlSocket");

    if (num_bytes == 0) return new char[0];

    // sometimes, read will return without completely filling the
    // buffer (e.g. on win32 JDK)
    char data[] = new char[num_bytes];
    int bytes_left = num_bytes;
    while (bytes_left > 0) {
      int bytes_read = _in.read(data, num_bytes - bytes_left, bytes_left);
      bytes_left -= bytes_read;
    }
    return data;
  }
  private Set outputUrlResults(String url, Set m_inclset, Set m_exclset) {
    Set new_incls = new TreeSet(CollectionUtils.subtract(m_inclset, m_reported));
    Set new_excls = new TreeSet(CollectionUtils.subtract(m_exclset, m_reported));
    if (!m_inclset.isEmpty()) {
      outputMessage(
          "\nIncluded Urls: ("
              + new_incls.size()
              + " new, "
              + (m_inclset.size() - new_incls.size())
              + " old)",
          URL_SUMMARY_MESSAGE);
      depth_incl[m_curDepth - 1] += new_incls.size();
    }
    for (Iterator it = new_incls.iterator(); it.hasNext(); ) {
      outputMessage(it.next().toString(), PLAIN_MESSAGE);
    }

    if (!m_exclset.isEmpty()) {
      outputMessage(
          "\nExcluded Urls: ("
              + new_excls.size()
              + " new, "
              + (m_exclset.size() - new_excls.size())
              + " old)",
          URL_SUMMARY_MESSAGE);
    }
    for (Iterator it = new_excls.iterator(); it.hasNext(); ) {
      outputMessage(it.next().toString(), PLAIN_MESSAGE);
    }
    m_reported.addAll(new_incls);
    m_reported.addAll(new_excls);

    if (m_outWriter != null) {
      try {
        m_outWriter.flush();
      } catch (IOException ex) {
      }
    }
    return new_incls;
  }
  /* クライアントとの接続を閉じるメソッド */
  void close() {
    if (in != null) {
      try {
        in.close();
      } catch (IOException e) {
      }
    }
    if (out != null) {
      try {
        out.close();
      } catch (IOException e) {
      }
    }
    if (socket != null) {
      try {
        socket.close();
      } catch (IOException e) {
      }
    }
    // closeメソッドが例外を投げるかもしれないので例外処理

  }
 public void exce(String name, CommandUsers comUsers, Vector clients) throws IOException {
   comUsers.makeNameList(clients); // 名前のリストを作成するメソッド
   // そのリストを用いて重複する名前を検出する処理を行う
   for (int i = 0; i < comUsers.getNameList().size(); i++) {
     String s = (String) comUsers.getNameList().get(i);
     if (name.equals(s)) {
       System.out.println(name + ": already used");
       out.write(name + ": already used");
       out.write("\r\n");
       out.flush();
       return;
     }
   }
   // 重複が無ければそのまま代入
   usrName = name;
   System.out.println("change name to " + usrName); // サーバ側ログ
   out.write("change name to " + usrName); // クライアント側ログ
   out.write("\r\n");
   out.flush();
 }
  public static int beginGUIConfigurationTransaction(String sConfigurationFileName, String sUser) {

    String sConfigurationLockFile;
    BufferedWriter bwBufferedWriter;
    File fFile;

    sConfigurationLockFile = new String(sConfigurationFileName + ".lck");

    System.out.println("beginGUIConfigurationTransaction: " + sConfigurationFileName);

    try {
      fFile = new File(URLDecoder.decode(sConfigurationLockFile, "UTF-8"));
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null, "URLDecoder.decode failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

    if (fFile.exists()) {
      BufferedReader brBufferedReader;
      char cLastConfigurationUser[];

      cLastConfigurationUser = new char[((int) fFile.length())];

      try {
        brBufferedReader =
            new BufferedReader(new FileReader(URLDecoder.decode(sConfigurationLockFile, "UTF-8")));
        brBufferedReader.read(cLastConfigurationUser, 0, (int) (fFile.length()));
        brBufferedReader.close();

        System.out.println(
            "Last configuration user: "******"Operation on BufferedWriter failed (1)",
            "ConfigurationTransaction",
            JOptionPane.ERROR_MESSAGE);

        return 1;
      }

      if (String.copyValueOf(cLastConfigurationUser).compareTo(sUser) == 0) {
        System.out.println("File. delete: " + sConfigurationFileName);

        if (fFile.delete() == false) {
          JOptionPane.showMessageDialog(
              null, "fFile.delete failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

          return 2;
        }
      } else {
        JOptionPane.showMessageDialog(
            null,
            "The configuration is locked by "
                + String.copyValueOf(cLastConfigurationUser)
                + ".\nYou cannot change the configuration.",
            "ConfigurationTransaction",
            JOptionPane.PLAIN_MESSAGE);

        return 3;
      }
    }

    try {
      bwBufferedWriter =
          new BufferedWriter(new FileWriter(URLDecoder.decode(sConfigurationLockFile, "UTF-8")));
      bwBufferedWriter.write(sUser, 0, sUser.length());
      bwBufferedWriter.close();

      System.out.println("Configuration user written: " + sUser);
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null,
          "Operation on BufferedWriter failed (" + e + ")",
          "ConfigurationTransaction",
          JOptionPane.ERROR_MESSAGE);

      return 4;
    }

    return 0;
  }
  public static void main(String[] args) {

    System.out.println("I am waiting for a request, send one.");

    ServerSocket socket;
    Socket client;

    PrintStream output;
    BufferedReader input;

    try {
      // Create socket
      socket = new ServerSocket(Integer.parseInt(args[0]));

      // Create a socket listener
      client = socket.accept();

      // open input and output streams
      input = new BufferedReader(new InputStreamReader(client.getInputStream()));
      output = new PrintStream(client.getOutputStream());

      // Wait for requests
      while (true) {
        String response;
        response = input.readLine();
        // GET request
        if (response.indexOf("GET") != -1) {
          output.println("200 OK close");
          System.out.println("Communications Closed - GET");
          break;
        } else if (response.indexOf("PUT") != -1) {
          // PUT request
          // Save text to file
          BufferedWriter out = new BufferedWriter(new FileWriter("NEWFILE.txt"));

          // Remove put from Response
          String writeToFile = response.substring(3);
          out.write(writeToFile);
          out.close();

          output.println(response);
          output.println("200 OK File Created close");
          System.out.println("Communications Closed - PUT");
          break;
        } else {
          // Unrecognized request
          output.println("400 BAD REQUEST");
          System.out.println("Communication Closed - Bad Request");
          break;
        }
      }
      // Close everything
      output.close();
      input.close();
      client.close();
      socket.close();

    } catch (IOException e) {
      System.out.println("I could not create a socket, sorry.");
    }
  }
Exemple #29
0
  public void run() {

    do {
      try {
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        File file = new File("time.txt");
        FileWriter fw = new FileWriter(file);
        Long start = 0l;
        Long end = 0l;
        BufferedWriter bw = new BufferedWriter(fw);
        System.out.println("Enter the preferred choice");
        System.out.println("1. REGISTER");
        System.out.println("2. LEAVE");
        System.out.println("3. SEARCH FOR RFC");
        System.out.println("4. KEEPALIVE");
        System.out.println("5. Do you want to EXIT");
        System.out.println("*********************************************");

        choice = Integer.parseInt(inFromUser.readLine());
        // System.out.println(" Client requesting for connection");
        clientSocket = new Socket("192.168.15.103", 6500);
        BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter outToServer =
            new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);

        // outToServer.println("Peer Requesting Connection");

        switch (choice) {
          case 4:
            outToServer.println(
                "KEEP ALIVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;
          case 1:
            try {
              // System.out.println("Case 1 entered"); // testing
              // statement
              System.out.println("Please enter your IP addres");
              ip = inFromUser.readLine();
              outToServer.println(
                  "REG P2P-DI/1.1 -1 Portno 6789 Hostname "
                      + ip
                      + " OS: "
                      + System.getProperty("os.name")
                      + " "
                      + "v"
                      + System.getProperty("os.version")
                      + " USER: "******"user.name"));
              cookie = Integer.parseInt(inFromServer.readLine());
              TTL = 7200;

              System.out.println(inFromServer.readLine());
              System.out.print("You are registered at time : ");
              ct.currenttime();
              System.out.println("Peer " + cookie); // peer cookie value
              System.out.println("TTL Value :" + TTL);
              System.out.println("*********************************************");

              break;
            } catch (Exception e) {
            }
          case 2:

            // System.out.println("Case 2 entered"); testing statement
            outToServer.println(
                "LEAVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            // System.out.println("I am in peer"); testing statement
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;

          case 3:
            outToServer.println(
                "PQUERY P2P-DI Cookieno "
                    + cookie
                    + " Portno 6789"
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println("Which RFC number do you wish to have ?");
            reqrfc = Integer.parseInt(inFromUser.readLine());

            // System.out.println("Entered peer again");
            // outToServer.println("KEEP ALIVE cookieno "+cookie);

            String details = inFromServer.readLine();

            String[] parray = details.split(" ");
            int inactive = Integer.parseInt(parray[(parray.length - 1)]);
            // System.out.println(darray.length);
            if ((parray.length == 3) && (ip.equals(parray[1]))) {
              System.out.println("P2P-DI No Active Peers available");
              System.out.println("*********************************************");
            } else {
              System.out.println("****<POPULATING THE ACTIVE PEER LIST>****");
              System.out.println();
              System.out.println("The active peer list is as follows:");
              System.out.println();

              String[] darray = details.split(" ");

              // System.out.println("Array length"+darray.length);
              for (int i = 0; i < (darray.length - 2); i = i + 2) {

                acthostname[j] = darray[i + 1];
                System.out.println("Hostname :" + acthostname[j]);

                actportno[j] = Integer.parseInt(darray[i + 2]);
                System.out.println("Portno :" + actportno[j]);

                System.out.println("*****************************");
                j = j + 1;
              }

              System.out.println("Connecting to the active peers for its RFC Index");
              for (int x = 0; x < j; x++) {
                // System.out.println(ip);
                if (!(acthostname[x].equals(ip))) {
                  System.out.println("Connecting to " + acthostname[x]);

                  Socket peersocket = new Socket(acthostname[x], 6791); // implement
                  // a for
                  // loop

                  BufferedReader inFromPeer =
                      new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
                  PrintWriter outToPeer =
                      new PrintWriter(new OutputStreamWriter(peersocket.getOutputStream()), true);

                  outToPeer.println("RFCIndex");
                  // System.out.println(inFromServer.readLine());
                  // int searchrfc=Integer.parseInt(inFromUser.readLine());
                  // outToServer.println(searchrfc);

                  String rfcindex = inFromPeer.readLine(); // tell server to
                  // send rfc in
                  // string
                  String rfcarray[] = rfcindex.split(" ");
                  //  System.out.println(rfcindex);
                  for (int i = 1; i < rfcarray.length; i = i + 4) {
                    trfcno[z] = Integer.parseInt(rfcarray[i]);
                    //	System.out.println("RFC number " + trfcno[z]);
                    trfctitle[z] = rfcarray[i + 1];
                    //	System.out.println("RFC Title " + trfctitle[z]);
                    tpeername[z] = rfcarray[i + 2];
                    //	System.out.println("Peer Ip Address " + tpeername[z]);
                    tpTTL[z] = Integer.parseInt(rfcarray[i + 3]);
                    //	System.out.println("TTL value :" + tpTTL[z]);

                    counter1 = counter1 + 1;

                    z = z + 1;
                  }
                  z = 0;
                  //         if(arraybound==0)
                  //         {
                  System.arraycopy(trfcno, 0, rfcno, counter2, trfcno.length);
                  System.arraycopy(trfctitle, 0, rfctitle, counter2, trfctitle.length);
                  System.arraycopy(tpeername, 0, peername, counter2, tpeername.length);
                  System.arraycopy(tpTTL, 0, pTTL, counter2, tpTTL.length);
                  z = 0;
                  counter2 = counter1;
                  counter1 = 0;
                  //         arraybound=arraybound+1;
                  //        }

                  System.out.println();
                  System.out.println();
                  System.out.println("*************************************************");
                  System.out.println("RFC Index received from the Peer");
                  //		System.out.println();
                  System.out.println("\n-----------------------------------------");
                  System.out.println("RFC Index System - Display RFC Idex");
                  System.out.println("-------------------------------------------");
                  System.out.format(
                      "%10s%15s%15s%10s", "RFC No", "RFC Title", "Peer Name", "TTL Value");
                  System.out.println();
                  // StudentNode current = top;
                  // while (current != null){
                  // Student read = current.getStudentNode();
                  for (int i = 0; i < 60; i++) {
                    System.out.format(
                        "%10s%15s%15s%10s",
                        " " + rfcno[i], rfctitle[i], peername[i], " " + pTTL[i]);
                    System.out.println();
                  }
                  // This will output with a set number of character spaces
                  // per field, giving the list a table-like quality
                  // }

                  peersocket.close();
                } // end of if

                for (int i = 0; i < rfcno.length; i++) {

                  if (rfcno[i] == reqrfc) {
                    String taddress = InetAddress.getByName(peername[i]).toString();
                    String[] taddr = taddress.split("/");
                    InetAddress tproperaddress = InetAddress.getByName(taddr[1]);
                    //	System.out.println("Inetaddress" + tproperaddress);

                    Socket peersocket1 = new Socket(tproperaddress, 6791); // implement
                    // a
                    // for
                    // loop
                    System.out.println("The connection to the Active Peer is establshed");
                    BufferedReader inFromP2P =
                        new BufferedReader(new InputStreamReader(peersocket1.getInputStream()));
                    PrintWriter outToP2P =
                        new PrintWriter(
                            new OutputStreamWriter(peersocket1.getOutputStream()), true);

                    System.out.println("Requested the RFC to the Active Peer Server");

                    start = System.currentTimeMillis();

                    outToP2P.println("GETRFC " + reqrfc);

                    // Socket socket = ;

                    try {

                      // Socket socket = null;
                      InputStream is = null;
                      FileOutputStream fos = null;
                      BufferedOutputStream bos = null;
                      int bufferSize = 0;

                      try {
                        is = peersocket1.getInputStream();

                        bufferSize = 64;
                        // System.out.println("Buffer size: " + bufferSize);
                      } catch (IOException ex) {
                        System.out.println("Can't get socket input stream. ");
                      }

                      try {
                        fos = new FileOutputStream("E:\\rfc" + reqrfc + "copy.txt");
                        bos = new BufferedOutputStream(fos);

                      } catch (FileNotFoundException ex) {
                        System.out.println("File not found. ");
                      }

                      byte[] bytes = new byte[bufferSize];

                      int count;

                      while ((count = is.read(bytes)) > 0) {
                        //	System.out.println(count);
                        bos.write(bytes, 0, count);
                      }
                      System.out.println("P2P-DI 200 OK The RFC is copied");
                      end = System.currentTimeMillis();
                      System.out.println(
                          "Total Time to download file   " + (end - start) + " milliseconds");

                      bos.flush();

                      bos.close();
                      is.close();
                      peersocket1.close();
                      break;

                    } catch (SocketException e) {
                      System.out.println("Socket exception");
                    }

                  } // end of if
                  else {
                    //  	System.out.println("No Peer with the required RFC could be found");

                  }
                  clientSocket.close();
                  //	System.out.println("Connection closed");
                  bw.close();
                  fw.close();
                } // end of inner for
              } // end of outer for
              System.out.println("Connection closed");
            } // end of switch
        } // end of else which checks the inactive conditions
      } // end of try
      catch (IOException ioe) {
        System.out.println("IOException on socket listen: " + ioe);
        ioe.printStackTrace();
      }

    } // end of do
    while (choice != 5);
  } // end of run
  // public static void main() throws Exception {
  public void statisticsReceiver(BufferedReader inFromClient) {
    String cpu = "";
    String hdd = "";
    String ram = "";
    String clientIP = "";
    int i;
    // int count = 0;

    // ServerSocket welcomeSocket = new ServerSocket(6789);
    //		while(true) {
    //
    //			Socket connSocket = welcomeSocket.accept();
    //			BufferedReader inFromClient = new BufferedReader(new
    // InputStreamReader(connSocket.getInputStream()));
    //			DataOutputStream outToClient = new DataOutputStream(connSocket.getOutputStream());
    try {
      clientIP = inFromClient.readLine();
      clientIP = clientIP.substring(0); // To remove the preceding slash

      cpu = inFromClient.readLine();
      hdd = inFromClient.readLine();
      ram = inFromClient.readLine();
      System.out.println(
          "Stats from " + clientIP + "\n CPU-" + cpu + "\n HDD- " + hdd + "\n RAM-" + ram);
    }
    // Writer writer = null;
    catch (Exception e) {
      // e.printStackTrace();
      System.out.println("Exception in TCPServer.java while receiving statistics.");
    }
    System.out.println("OperatingSystem.pm.length = " + OperatingSystem.pm.length);
    System.out.println("clientIP = " + clientIP);
    for (i = 0; i < OperatingSystem.pm.length; i++) {

      String temp[] = OperatingSystem.pm[i].getIp().split("@");

      if (clientIP.equalsIgnoreCase(temp[1])) {
        System.out.println("Stat values from " + clientIP + "added to queues");
        OperatingSystem.pm[i].cpuQueue.insert(Double.parseDouble(cpu));
        OperatingSystem.pm[i].hddQueue.insert(Double.parseDouble(hdd));
        OperatingSystem.pm[i].ramQueue.insert(Double.parseDouble(ram));
      }
    }

    try {
      File file = new File(clientIP);
      boolean exist = file.createNewFile();
      BufferedWriter writer;

      if (exist) {
        writer = new BufferedWriter(new FileWriter(file));
        // writer.write(cpu+"\n");
        // writer.write(hdd+"\n");
        // writer.write(ram+"\n");
        writer.write("cpu: " + cpu + " hdd: " + hdd + " ram: " + ram);
        writer.write("\n");
      } else {
        FileOutputStream fos = new FileOutputStream(clientIP, true);
        // String strContent = "Append output to a file example";
        String newline = "\n";
        String CPU = "cpu: ";
        String HDD = " hdd: ";
        String RAM = " ram: ";
        fos.write(newline.getBytes());
        // fos.write(newline.getBytes());
        // fos.write(clientIP.getBytes());
        // fos.write(newline.getBytes());
        fos.write(CPU.getBytes());
        fos.write(cpu.getBytes());
        // fos.write(newline.getBytes());
        fos.write(HDD.getBytes());
        fos.write(hdd.getBytes());
        // fos.write(newline.getBytes());
        fos.write(RAM.getBytes());
        fos.write(ram.getBytes());
        fos.write(newline.getBytes());
      }
    } catch (Exception ex) {
      // ex.printStackTrace();
      System.out.println("Exception in TCPServer.java while writing statistics.");
    }
  }