⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileexchangemodel.java

📁 JAVA Servlet2.3外文书籍源码
💻 JAVA
字号:
package firewall.client;

import firewall.common.*;

import java.io.*;

import java.net.*;
/**
 * Title:        FileExchangeModel
 * Description:  Contains the application processing logic
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author Andrew Harbourne-Thomas
 * @version 1.0
 */
public class FileExchangeModel {

  /** Reference to the view */
  FileExchangeView view;

  /**
   * Constructor
   *
   * @param view Reference to the view
   */
  public FileExchangeModel(FileExchangeView view) {
    this.view = view;
  }

  /**
   * Method to send a file from the application/client system
   * to the server system
   *
   * @param uploadFile File to send to server
   */
  public void uploadRequest(File uploadFile) {

    if (!FileValidator.isFileNameValid(uploadFile.getName())) {
        view.appendMessage("Upload:Error - File selected is invalid");
        return;
    }

    URL url = view.getHostServlet();
    HttpURLConnection httpURLConnection = null;
    int status = 0;
    String message = null;
    try {
      httpURLConnection = getHttpURLConnection(url);
      sendRequest(httpURLConnection,
                  new FileName(BaseRequest.UPLOAD, uploadFile.getName()),
                  false);

      //now send the file to the client
      FileReader fileReader = new FileReader(uploadFile);
      OutputStream os = httpURLConnection.getOutputStream();
      PrintWriter out = new PrintWriter(os);

      char c[] = new char[4096];
      int read = 0;
      // Read until end of file and send to client
      while ((read = fileReader.read(c)) != -1) {
        out.write(c, 0, read);
      }
      // Close
      fileReader.close();
      out.close();
      os.close();

      //read the server response
      status = httpURLConnection.getResponseCode();
      message = httpURLConnection.getResponseMessage();
    }
    catch (Exception e) {
      e.printStackTrace();
    }

    //inform the client
    if (status >= HttpURLConnection.HTTP_OK ||
        status < HttpURLConnection.HTTP_MULT_CHOICE) {
      view.appendMessage("Upload:Success (" + status + ") " + message);
    }
    else {
      view.appendMessage("Upload:Error (" + status + ") " + message);
    }

    //refresh the file list
    refreshRequest();
  }

  /**
   * Perform a download from the server of the selected file. This is saved
   * to the users home directory
   *
   * @param fileName File to download from the server
   */
  public void downloadRequest(String fileName) {

    //ensure valid file is selected
    if (!FileValidator.isFileNameValid(fileName)) {
      view.appendMessage("Download:File must be selected");
      return;
    }

    URL url = view.getHostServlet();
    HttpURLConnection httpURLConnection = null;
    //default location to save file to
    File saveFile = new File(System.getProperty("user.home"), fileName);
    try {
      httpURLConnection = getHttpURLConnection(url);
      sendRequest(httpURLConnection,
                  new FileName(BaseRequest.DOWNLOAD, fileName));

      int status = httpURLConnection.getResponseCode();
      String message = httpURLConnection.getResponseMessage();

      //inform the client
      if (status >= HttpURLConnection.HTTP_OK ||
          status < HttpURLConnection.HTTP_MULT_CHOICE) {
        view.appendMessage("Download:Success (" + status + ") " + message);
      }
      else {
        view.appendMessage("Download:Error (" + status + ") " + message);
        return;
      }

      //read the servers response
      InputStreamReader isr =
          new InputStreamReader(httpURLConnection.getInputStream());
      BufferedReader bfr = new BufferedReader(isr);
      FileWriter fileWriter = new FileWriter(saveFile);
      char c[] = new char[4096];
      int read = 0;

      while ((read = bfr.read(c)) != -1) {
        fileWriter.write(c, 0, read);
      }

      // Close
      fileWriter.close();
      isr.close();
      view.appendMessage("Download:File saved to:\n" + saveFile.getCanonicalPath());
    }
    catch (Exception e) {
      view.appendMessage("Download:Error downloading the file");
      e.printStackTrace();
    }
  }

  /**
   * Request to the server to refresh the list of files
   */
  public void refreshRequest() {
    URL url = view.getHostServlet();
    HttpURLConnection httpURLConnection = null;
    FileList files = null;
    try {
      httpURLConnection = getHttpURLConnection(url);
      sendRequest(httpURLConnection,
                  new BaseRequest(BaseRequest.REFRESH));

      //read the response from the server

      int status = httpURLConnection.getResponseCode();
      String message = httpURLConnection.getResponseMessage();

      //inform the client
      if (status < HttpURLConnection.HTTP_OK ||
          status >= HttpURLConnection.HTTP_MULT_CHOICE) {
           view.appendMessage("Refresh:Error (" + status + ") " + message);
        return;
      }

      files = (FileList) readResponse(httpURLConnection);

      if (files == null)
      {
        view.appendMessage("Refresh:Error - directory is null");
      }
      else
      {
        //refresh the filelist on the screen
        FileValidator.cleanFileList(files.getFileList());
        view.refreshFileList(files.getFileList());
      }
    }
    catch (Exception e) {
      e.printStackTrace();
      view.appendMessage("Refresh:Error refreshing the filelist");
      view.appendMessage("Using URL:" + url);
      view.appendMessage("Check the URL to the servlet including port");
    }
  }

  /**
   * Method to delete a selected file from the server
   *
   * @param fileName File to be deleted from the server
   */
  public void deleteRequest(String fileName) {
    //check the file is correct and selected
    if (!FileValidator.isFileNameValid(fileName)) {
      view.appendMessage("Delete:File not selected. Please select file");
    }
    else {
      URL url = view.getHostServlet();
      HttpURLConnection httpURLConnection = null;
      String message = null;
      int status = 0;
      try {
        httpURLConnection = getHttpURLConnection(url);
        sendRequest(httpURLConnection,
                    new FileName(FileName.DELETE, fileName));

        //read server response
        status = httpURLConnection.getResponseCode();
        message = httpURLConnection.getResponseMessage();
      }
      catch (Exception e) {
        e.printStackTrace();
      }

      //inform the application view
      if (status >= HttpURLConnection.HTTP_OK ||
          status < HttpURLConnection.HTTP_MULT_CHOICE) {
        view.appendMessage("Delete:Success (" + status + ") " + message);
      }
      else {
        view.appendMessage("Delete:Error (" + status + ") " + message);
        return;
      }
    }
    //refresh the file list
    refreshRequest();
  }

  /**
   * Set up the connection to the server
   *
   * @param url - to connect to
   * @param request - object to send
   */
  private HttpURLConnection getHttpURLConnection(URL url)
    throws IOException {
    //setup connection
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    httpURLConnection.setDoOutput(true);
    httpURLConnection.setUseCaches(false);
    httpURLConnection.setRequestProperty("Content-Type",
                                         "application/x-java-serialized-object");
    return httpURLConnection;
  }

  /**
   * send the request query object to the server. Default action is to close
   * the output stream
   *
   * @param url - to connect to
   * @param request - object to send
   */
  private void sendRequest(HttpURLConnection httpURLConnection,
    BaseRequest request) throws IOException {

    sendRequest(httpURLConnection, request, true);
    }

  /**
   * send the request query object to the server.
   *
   * @param url - to connect to
   * @param request - object to send
   * @param closeStream - boolean specifying if the output stream should be
   *        closed.
   */
  private void sendRequest(HttpURLConnection httpURLConnection,
      BaseRequest request, boolean closeStream) throws IOException {

      //send the request query object to the server
      OutputStream os = httpURLConnection.getOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(os);
      oos.writeObject(request);
      oos.flush();
      if (closeStream) {
        os.close();
      }
  }

  /**
   * read a server response object from the input stream.
   *
   * @param httpURLConnection - connection to read from
   */
  private Object readResponse(HttpURLConnection httpURLConnection)
    throws IOException, ClassNotFoundException {
      return readResponse(httpURLConnection, true);
    }

  /**
   * read a server response object from the input stream.
   *
   * @param httpURLConnection - connection to read from
   */
  private Object readResponse(HttpURLConnection httpURLConnection,
    boolean closeOutput) throws IOException, ClassNotFoundException {

    InputStream ins = httpURLConnection.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(ins);
    Object response = ois.readObject();
    if (closeOutput) {
      ois.close();
    }
    return response;
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -