Ejemplo n.º 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();
 }
Ejemplo 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;
  }
Ejemplo n.º 3
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;
    }
  }
Ejemplo n.º 4
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();
 }
Ejemplo n.º 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();
 }
Ejemplo n.º 6
0
 // ------------------------------------
 // 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);
   }
 }
Ejemplo n.º 7
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);
  }
Ejemplo n.º 8
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);
    }
  }
Ejemplo n.º 9
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;
  }
Ejemplo n.º 11
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();
    }
  }
Ejemplo n.º 12
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();
    }
  }
Ejemplo n.º 13
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;
  }
Ejemplo n.º 14
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";
    }
  }
Ejemplo n.º 15
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();
   }
 }
Ejemplo n.º 16
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) {}
        });
  }
Ejemplo n.º 17
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();
      }
    }
  }
Ejemplo n.º 18
0
  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;
  }
Ejemplo n.º 19
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;
  }
Ejemplo n.º 20
0
  @SuppressWarnings("resource")
  public static void main(String[] e) throws Exception {

    ServerSocket serverSocket = new ServerSocket(8888);
    System.out.println("Estableciendo conexion TCP . . .");

    File file;
    FileWriter writingFile;
    BufferedWriter writingBuffered;

    while (true) {
      System.out.println("Conexion establecida. Esperando solicitud del sistema . . .");
      Socket clientSocket = serverSocket.accept();
      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      InetAddress ip = clientSocket.getInetAddress();
      String command = in.readLine();
      System.out.println("Client: " + ip + "Command: " + command);
      out.println(command);
      char[] arrayCommand = command.toCharArray();
      String pinBeagle = "";
      String run = "";
      String duty = "";
      String direction = "";
      System.out.println(command.getBytes());
      System.out.println(command.length());
      System.out.println(command.getBytes().toString());
      int i = 0;

      while (i < arrayCommand.length) {
        while (arrayCommand[i] != '*' && arrayCommand[i] != '-' && arrayCommand[i] != '+') {
          pinBeagle = pinBeagle + arrayCommand[i];
          i++;
        }

        if (arrayCommand[i] == '*') {
          i = i + 1;
          while (i < arrayCommand.length) {
            duty = duty + arrayCommand[i];
            i++;
          }
        } else if (arrayCommand[i] == '-') {
          run = arrayCommand[i + 1] + "";
          break;
        } else if (arrayCommand[i] == '+') {
          i = i + 1;
          System.out.println(pinBeagle);
          while (i < arrayCommand.length) {
            direction = direction + arrayCommand[i];
            System.out.println(i + " -> " + arrayCommand.length);
            i++;
          }
        }
      }
      if (!run.equals("")) {
        file = new File("/sys/devices/ocp.3/" + pinBeagle + "/run");
        writingFile = new FileWriter(file);
        writingBuffered = new BufferedWriter(writingFile);
        writingBuffered.write(run);
        writingBuffered.flush();
      } else if (!duty.equals("")) {
        file = new File("/sys/devices/ocp.3/" + pinBeagle + "/duty");
        writingFile = new FileWriter(file);
        writingBuffered = new BufferedWriter(writingFile);
        writingBuffered.write(duty);
        writingBuffered.flush();
      } else {
        file = new File("/sys/class/gpio/" + pinBeagle + "/direction");
        writingFile = new FileWriter(file);
        writingBuffered = new BufferedWriter(writingFile);
        writingBuffered.write(direction);
        writingBuffered.flush();
      }
    }
  }
Ejemplo n.º 21
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());
    }
  }
Ejemplo n.º 22
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;
  }
Ejemplo n.º 23
0
 /* クライアントにデータを送信するメソッド */
 void send(String message) throws IOException {
   out.write(message); // messageの中身をバッファに書き込む
   out.write("\r\n"); // (ネットワークの改行)
   out.flush(); // バッファの文字をクライアント側に画面出力
 }
Ejemplo n.º 24
0
 // ついでにWHOAMIコマンドを実装しておく
 public void whoami() throws IOException {
   out.write(usrName);
   out.flush();
 }
  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");
        }
      }
    }
  }