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) {

    }
  }
Exemplo n.º 2
0
  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;
  }
Exemplo n.º 3
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) {
      }
    }
  }
Exemplo n.º 4
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();
 }
Exemplo n.º 5
0
 private void closeOutputFile() {
   try {
     if (m_outWriter != null) {
       m_outWriter.close();
     }
   } catch (IOException ex) {
     System.err.println("Error closing output file.");
   }
 }
Exemplo n.º 6
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();
 }
Exemplo n.º 7
0
  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);
    }
  }
Exemplo n.º 8
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;
   }
 }
  @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;
  }
Exemplo n.º 10
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();
    }
  }
Exemplo n.º 11
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;
  }
Exemplo n.º 12
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();
      }
    }
  }
Exemplo n.º 13
0
  /* クライアントとの接続を閉じるメソッド */
  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メソッドが例外を投げるかもしれないので例外処理

  }
Exemplo n.º 14
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.");
        }
      }
    }
  }
Exemplo n.º 15
0
  public static void main(String[] args) {
    BufferedReader sysIn =
        new BufferedReader(new InputStreamReader(System.in)); // Read from console
    PrintStream sysOut = System.out; // Print to console
    SSLSocketFactory mainFactory =
        (SSLSocketFactory) SSLSocketFactory.getDefault(); // Get default SSL socket factory
    try {
      SSLSocket clientSocket =
          (SSLSocket)
              mainFactory.createSocket(
                  "pop.mail.yahoo.com", 995); // create, connect, start handshake
      printSocketInfo(clientSocket); // Print connection info
      BufferedWriter serverWriter =
          new BufferedWriter(
              new OutputStreamWriter(clientSocket.getOutputStream())); // Write to server
      BufferedReader serverReader =
          new BufferedReader(
              new InputStreamReader(clientSocket.getInputStream())); // Read from server

      String serverInput = null; // Stores latest line from server
      String userInput = ""; // Stores lastest input line from user
      boolean tryRead =
          true; // Whether to read next line from serverReader (prevents blocking on multiline SMTP
                // responses)

      // The below booleans, used to successully close the connection, might be unnecessary
      boolean quitUser = false; // Whether the user has entered quit, might be unnecessary
      boolean openRead = true; // Whether serverReader is still open (serverInput != null)
      boolean openSocket = true; // Whether clientSocket is still open (clientSocket != null)

      // SMTP input variables
      boolean sendingData = false;
      boolean multi = false;

      // Main connection loop
      while (openSocket && openRead && !quitUser) {
        if (clientSocket == null) { // Break if socket is closed
          openSocket = false;
          break;
        }
        // Display server response/message
        if (multi) {
          while (tryRead) {
            serverInput = serverReader.readLine();
            if (serverInput == null) { // If serverReader gets closed/connection broken
              openRead = false;
              tryRead = false;
              break;
            }
            sysOut.println(serverInput);
            // Check for multiline response or error
            if (serverInput.equals(".")
                || (serverInput.length() >= 4 && serverInput.startsWith("-ERR"))) {
              tryRead = false;
            } else {
              tryRead = true;
            }
          }
        } else {
          serverInput = serverReader.readLine();
          if (serverInput == null) { // If serverReader gets closed/connection broken
            openRead = false;
            tryRead = false;
            break;
          }
          sysOut.println(serverInput);
        }
        multi = false;
        // Exit client if connection lost/closed prematurely
        if (openSocket == false || openRead == false) {
          break;
        }
        // If user previously entered quit
        if (userInput.length() >= 4 && userInput.substring(0, 4).equalsIgnoreCase("quit")) {
          quitUser = true;
          break;
        }
        // Get user input
        userInput = ""; // Reset userInput to show prompt
        // Read user input, display prompt if blank enter, otherwise send to server
        while (userInput.equals("")) {
          sysOut.print("C: ");
          userInput = sysIn.readLine();
        }
        serverWriter.write(userInput, 0, userInput.length()); // Writing to server
        serverWriter.newLine();
        serverWriter.flush();
        tryRead = true;
        // Prepare for multi-line response if list, uidl, retr, or top
        if (userInput.equalsIgnoreCase("list")
            || userInput.equalsIgnoreCase("uidl")
            || userInput.equalsIgnoreCase("auth")
            || (userInput.length() >= 4 && userInput.substring(0, 4).equalsIgnoreCase("capa"))
            || (userInput.length() >= 4 && userInput.substring(0, 4).equalsIgnoreCase("retr"))
            || (userInput.length() >= 4 && userInput.substring(0, 3).equalsIgnoreCase("top"))) {
          multi = true;
        }
      }
      // Clean up all connection objects
      serverWriter.close();
      serverReader.close();
      clientSocket.close();
      sysIn.close();
      sysOut.close();
    } catch (IOException e) {
      System.err.println(e.toString());
    }
  }
Exemplo n.º 16
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
Exemplo n.º 17
0
  public boolean test() {
    ExtendedService es = null;
    boolean ok = true;

    String tmpfilename = getParameter("tmpfile");

    try {
      // Lookup the javax.jnlp.ExtendedService object
      es = (ExtendedService) ServiceManager.lookup("javax.jnlp.ExtendedService");
    } catch (UnavailableServiceException ue) {
      System.out.println(ue);
      ue.printStackTrace();
      // Service is not supported
      ok = false;
    }
    if (!ok) return false;

    // Open a specific file in the local machine

    File tmpfile = new File(tmpfilename);

    // Java Web Start will pop up a dialog asking the user to grant permission
    // to read/write the file 'tempfile'

    try {
      FileContents fc_tmpfile = es.openFile(tmpfile);

      if (!tmpfilename.equals(fc_tmpfile.getName())) {
        System.out.println(
            "\t tmpfile(out): "
                + tmpfilename
                + ", unequal to fc-filename: "
                + fc_tmpfile.getName()
                + " - info");
        // ok=false;
        // return ok;
      }

      if (!fc_tmpfile.canWrite()) {
        System.out.println(
            "\t outfile: " + tmpfilename + ", no write access (may not exist yet) - info");
      }

      // You can now use the FileContents object to read/write the file

      java.io.OutputStream sout = fc_tmpfile.getOutputStream(true);

      BufferedWriter bwsout = new BufferedWriter(new OutputStreamWriter(sout));

      bwsout.write(datum, 0, datum.length());
      bwsout.flush();
      bwsout.close();
    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
      System.out.println("\t Error while IO write - failed");
      ok = false;
      return ok;
    }

    // read back ..
    try {
      FileContents fc_tmpfile = es.openFile(tmpfile);

      if (!tmpfilename.equals(fc_tmpfile.getName())) {
        System.out.println(
            "\t tmpfile(in): "
                + tmpfilename
                + ", unequal to fc-filename: "
                + fc_tmpfile.getName()
                + " - info");
        // ok=false;
        // return ok;
      }

      if (!fc_tmpfile.canRead()) {
        System.out.println("\t outfile: " + tmpfilename + ", read access failed");
        ok = false;
      }

      // You can now use the FileContents object to read/write the file

      java.io.InputStream sin = fc_tmpfile.getInputStream();
      BufferedReader brsin = new BufferedReader(new InputStreamReader(sin));
      String in = brsin.readLine();

      if (!in.equals(datum)) {
        System.out.println("\t file content <" + in + "> does not match <" + datum + "> - failed");
        ok = false;
      }
      brsin.close();
    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
      System.out.println("\t Error while IO read - failed");
      ok = false;
      return ok;
    }

    return ok;
  }
Exemplo n.º 18
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 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");
        }
      }
    }
  }
  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 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;
  }