// ------------------------------------
 // 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);
   }
 }
示例#2
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);
    }
  }
示例#4
0
  /**
   * 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;
  }
示例#6
0
文件: Installer.java 项目: suever/CTP
 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();
 }
示例#7
0
  /**
   * 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();
    }
  }
示例#8
0
 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();
 }
示例#9
0
 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();
 }
示例#10
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();
 }
示例#11
0
 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;
   }
 }
示例#12
0
 /**
  * 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;
  }
示例#14
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();
    }
  }
示例#15
0
  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);
      }
    }
  }
示例#16
0
文件: GSUtils.java 项目: CJ-Chen/igv
  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) {
      }
    }
  }
示例#17
0
文件: Signup.java 项目: ukkukkukk/app
  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;
  }
示例#18
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";
    }
  }
示例#19
0
 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();
   }
 }
示例#20
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) {}
        });
  }
示例#21
0
  // 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();
      }
    }
  }
示例#22
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;
  }
示例#23
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.");
    }
  }
  public static int commitGUIConfigurationTransaction(
      XMLTreeForConfiguration xtfcXMLTreeForConfiguration, Vector vFunctionalities) {

    TreeVisit tvConfigurationTreeVisit;
    TreeVisitToGetConfigurationFile tvgcTreeVisitToGetConfigurationFile;
    String sConfigurationFile;
    URL uXML;
    String sConfigurationLockFile;
    BufferedWriter bwBufferedWriter;
    File fFile;

    tvgcTreeVisitToGetConfigurationFile = new TreeVisitToGetConfigurationFile(vFunctionalities);
    tvConfigurationTreeVisit = new TreeVisit(tvgcTreeVisitToGetConfigurationFile);

    if (tvConfigurationTreeVisit.inOrderVisit(xtfcXMLTreeForConfiguration.getXMLTopTreeComponent())
        != 0) {
      JOptionPane.showMessageDialog(
          null, "inOrderVisit failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

    sConfigurationFile = tvgcTreeVisitToGetConfigurationFile.getConfigurationFile();

    System.out.println("commitGUIConfigurationTransaction: " + sConfigurationFile);

    uXML = xtfcXMLTreeForConfiguration.getXML();

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

      System.out.println(
          "commitGUIConfigurationTransaction: file written ("
              + URLDecoder.decode(uXML.getFile(), "UTF-8")
              + ")");
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null,
          "Operation on BufferedWriter failed (3)",
          "ConfigurationTransaction",
          JOptionPane.ERROR_MESSAGE);

      return 2;
    }

    sConfigurationLockFile = new String(uXML.getFile() + ".lck");

    try {
      fFile = new File(URLDecoder.decode(sConfigurationLockFile, "UTF-8"));

      System.out.println("File. delete: " + URLDecoder.decode(sConfigurationLockFile, "UTF-8"));
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null, "URLDecoder.decode failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

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

      return 3;
    }

    return 0;
  }
示例#25
0
  public static void main(String args[]) {

    String host = "localhost";
    int port = 1099;

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

    // Initialise auctions from permanent storage
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
      AuctionServer rmiServer = new AuctionServer();
      Registry reg = LocateRegistry.getRegistry(host, port);
      reg.rebind("auctionServer", rmiServer);
      System.out.println("AuctionServer is ready");
      System.out.println(
          "Select one of the two options :\n1: To save live auctions\n2: To load test auctions that expire in a minute (note you need to start 5 clients first)  ");
      Scanner sc = new Scanner(System.in);
      bw = new BufferedWriter(new FileWriter("auctionsSaved.dat"));
      switch (sc.nextInt()) {
        case 1:
          for (AuctionItem item : rmiServer.liveAuctionItems.values()) {
            bw.write(item.toString() + "\n");
          }
          System.out.println("Saved auctions state.");
          break;
        case 2:
          GenerateAuctions generator = new GenerateAuctions();
          generator.generateList();
          br = new BufferedReader(new FileReader("auctionsBackup.dat"));
          String currentLine;
          while ((currentLine = br.readLine()) != null) {
            String[] array = currentLine.split(",");
            String name = array[0];
            double min_item_value = Double.parseDouble(array[1]);
            Date closing_date = new SimpleDateFormat("d/M/y H:mm:s").parse(array[2]);
            int client = Integer.parseInt(array[3]);
            rmiServer.registerAuctionItem(name, min_item_value, closing_date, client);
          }
          System.out.println("Initialised auctions...");
          break;
      }

    } catch (RemoteException e) {
      System.out.println("Exception in AuctionServer.main " + e);
    } catch (MalformedURLException ue) {
      System.out.println("MalformedURLException in RMIServerImp.main " + ue);
    } catch (IOException e) {
      System.out.println("Could not open file ");
      e.printStackTrace();
    } catch (ParseException e) {
      System.out.println("Unable to parse date");
      e.printStackTrace();
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          System.out.println("Unable to close file.");
        }
      }
      if (bw != null) {
        try {
          bw.close();
        } catch (IOException e) {
          System.out.println("Unable to close file.");
        }
      }
    }
  }
  // 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.");
    }
  }
  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 void bad() throws Throwable {
    if (IO.static_returns_t_or_f()) {
      java.util.logging.Logger log_bs = java.util.logging.Logger.getLogger("local-logger");
      Socket sock = null;
      PrintWriter out = null;
      try {
        sock = new Socket("remote_host", 1337);
        out = new PrintWriter(sock.getOutputStream(), true);
        /* FLAW: sending over an unencrypted (non-SSL) channel */
        out.println("plaintext send");
      } catch (Exception ex) {
        IO.writeLine("Error writing to the socket");
      } finally {
        try {
          if (out != null) {
            out.close();
          }
        } catch (Exception e) {
          log_bs.warning("Error closing out");
        }

        try {
          if (sock != null) {
            sock.close();
          }
        } catch (Exception e) {
          log_bs.warning("Error closing sock");
        }
      }
    } else {

      java.util.logging.Logger log_gs = java.util.logging.Logger.getLogger("local-logger");

      OutputStream outStream = null;
      BufferedWriter bWriter = null;
      OutputStreamWriter outStreamWriter = null;
      SSLSocketFactory sslssocketfactory = null;
      SSLSocket sslsocket = null;
      try {
        sslssocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        sslsocket = (SSLSocket) sslssocketfactory.createSocket("remote_host", 1337);

        outStream = sslsocket.getOutputStream();
        outStreamWriter = new OutputStreamWriter(outStream);
        bWriter = new BufferedWriter(outStreamWriter);

        /* FIX: sending over an SSL encrypted channel */
        bWriter.write("encrypted send");
        bWriter.flush();
      } catch (Exception ex) {
        IO.writeLine("Error writing to the socket");
      } finally {
        try {
          if (bWriter != null) {
            bWriter.close();
          }
        } catch (IOException e) {
          log_gs.warning("Error closing bWriter");
        } finally {
          try {
            if (outStreamWriter != null) {
              outStreamWriter.close();
            }
          } catch (IOException e) {
            log_gs.warning("Error closing outStreamWriter");
          }
        }
        try {
          if (sslsocket != null) {
            sslsocket.close();
          }
        } catch (Exception e) {
          log_gs.warning("Error closing sslsocket");
        }
      }
    }
  }
示例#29
0
 /* クライアントにデータを送信するメソッド */
 void send(String message) throws IOException {
   out.write(message); // messageの中身をバッファに書き込む
   out.write("\r\n"); // (ネットワークの改行)
   out.flush(); // バッファの文字をクライアント側に画面出力
 }
示例#30
0
 // ついでにWHOAMIコマンドを実装しておく
 public void whoami() throws IOException {
   out.write(usrName);
   out.flush();
 }