コード例 #1
0
ファイル: Chord.java プロジェクト: DevoutChaos/NetAssign3
 /**
  * @param guid
  * @param data
  * @throws IOException
  */
 public void write(int guid, byte[] data) throws IOException {
   File file = new File(Integer.toString(guid));
   FileOutputStream fos = null;
   fos = new FileOutputStream(file);
   // Writes bytes from the specified byte array to this file output stream
   fos.write(data);
 }
コード例 #2
0
  void ReceiveFile() throws Exception {
    String fileName;

    fileName = din.readUTF();

    if (fileName != null && !fileName.equals("NOFILE")) {
      System.out.println("Receiving File");
      File f =
          new File(
              System.getProperty("user.home")
                  + "/Desktop"
                  + "/"
                  + fileName.substring(fileName.lastIndexOf("/") + 1));
      System.out.println(f.toString());
      f.createNewFile();
      FileOutputStream fout = new FileOutputStream(f);
      int ch;
      String temp;
      do {
        temp = din.readUTF();
        ch = Integer.parseInt(temp);
        if (ch != -1) {
          fout.write(ch);
        }
      } while (ch != -1);
      System.out.println("Received File : " + fileName);
      fout.close();
    } else {
    }
  }
コード例 #3
0
  @Override
  public void run() {
    try {
      socket = server.accept();
      System.out.println("Download : " + socket.getRemoteSocketAddress());

      In = socket.getInputStream();
      Out = new FileOutputStream(saveTo);

      byte[] buffer = new byte[1024];
      int count;

      while ((count = In.read(buffer)) >= 0) {
        Out.write(buffer, 0, count);
      }

      Out.flush();

      if (Out != null) {
        Out.close();
      }
      if (In != null) {
        In.close();
      }
      if (socket != null) {
        socket.close();
      }
    } catch (Exception ex) {
      System.out.println("Exception [Download : run(...)]");
    }
  }
コード例 #4
0
  void writeImageToDisk(Document document, String imgURLString, String fileName) {
    // We could just reference the image on the netscape site,
    // but the point of this example is to show how to write
    // a file to the disk.

    // In order to do this, we need to have the ability access files.
    netscape.security.PrivilegeManager.enablePrivilege("UniversalFileAccess");
    // And the ability to connect to an arbitrary URL.
    netscape.security.PrivilegeManager.enablePrivilege("UniversalConnect");

    // Copy the image to the work directory.
    File outFile = new File(document.getWorkDirectory(), fileName);
    if (!outFile.exists()) {
      try {
        InputStream in = new URL(imgURLString).openStream();
        FileOutputStream outStream = new FileOutputStream(outFile);
        int chunkSize = 1024;
        byte[] bytes = new byte[chunkSize];
        int readSize;
        while ((readSize = in.read(bytes)) >= 0) {
          outStream.write(bytes, 0, readSize);
        }
        outStream.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
コード例 #5
0
  // Merge the availableChunks to build the original file
  void MergeChunks(File[] chunks) throws IOException {

    // Safety check
    if (chunks == null) {
      System.err.println("ERROR: No chunks to merge!");
      return;
    }

    FileOutputStream fos = new FileOutputStream("complete/" + filename);

    try {
      FileInputStream fis;
      byte[] fileBytes;
      int bytesRead;
      for (File f : chunks) {
        fis = new FileInputStream(f);
        fileBytes = new byte[(int) f.length()];
        bytesRead = fis.read(fileBytes, 0, (int) f.length());
        assert (bytesRead == fileBytes.length);
        assert (bytesRead == (int) f.length());
        fos.write(fileBytes);
        fos.flush();
        fileBytes = null;
        fis.close();
        fis = null;
      }
    } catch (Exception exception) {
      exception.printStackTrace();
    } finally {
      fos.close();
      fos = null;
    }
  }
コード例 #6
0
 /** Разархивация файла с БД */
 private void dearchiveDB() {
   String zipFile = RES_ABS_PATH + File.separator + DB_ARCHIVE_NAME;
   String outputFolder = RES_ABS_PATH;
   try {
     ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
     ZipEntry ze = zis.getNextEntry();
     while (ze != null) {
       String fileName = ze.getName();
       File newFile = new File(outputFolder + File.separator + fileName);
       System.out.println("File unzip : " + newFile.getAbsoluteFile());
       new File(newFile.getParent()).mkdirs();
       FileOutputStream fos = new FileOutputStream(newFile);
       int len;
       byte[] buffer = new byte[1024];
       while ((len = zis.read(buffer)) > 0) {
         fos.write(buffer, 0, len);
       }
       fos.close();
       ze = zis.getNextEntry();
     }
     zis.closeEntry();
     zis.close();
     System.out.println("File unziped");
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
コード例 #7
0
ファイル: SaveURL.java プロジェクト: tchipwanya/cs458-f12
 public static void writeURLtoFile(URL url, String filename) throws IOException {
   // FileWriter writer = new FileWriter(filename);
   // saveURL(url, writer);
   // writer.close();
   FileOutputStream os = new FileOutputStream(filename);
   saveURL(url, os);
   os.close();
 }
コード例 #8
0
 void saveJar(File f, byte[] data) {
   try {
     FileOutputStream out = new FileOutputStream(f);
     out.write(data, 0, data.length);
     out.close();
   } catch (IOException e) {
   }
 }
コード例 #9
0
 protected void saveGlyphFile(File a_file) throws FileNotFoundException {
   FileOutputStream output = new FileOutputStream(a_file);
   saveGlyphFile(output);
   try {
     output.close(); // JPEXS
   } catch (IOException ex) {
     Logger.getLogger(GlyphFile.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
コード例 #10
0
 boolean savePlugin(File f, byte[] data) {
   try {
     FileOutputStream out = new FileOutputStream(f);
     out.write(data, 0, data.length);
     out.close();
   } catch (IOException e) {
     IJ.error("Plugin Installer", "" + e);
     return false;
   }
   return true;
 }
コード例 #11
0
 public static void downloadFileFromURL(String urlString, File destination) {
   try {
     URL website = new URL(urlString);
     ReadableByteChannel rbc;
     rbc = Channels.newChannel(website.openStream());
     FileOutputStream fos = new FileOutputStream(destination);
     fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
     fos.close();
     rbc.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
コード例 #12
0
 /** A put is used to send a chunk of a file. */
 void doPut(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   int transferred = getTransferred();
   int length = getLength();
   int headerLength = Integer.valueOf(req.getHeader(ProtocolConstants.HEADER_CONTENT_LENGTH));
   String rangeString = req.getHeader(ProtocolConstants.HEADER_CONTENT_RANGE);
   if (rangeString == null) rangeString = "bytes 0-" + (length - 1) + '/' + length; // $NON-NLS-1$
   ContentRange range = ContentRange.parse(rangeString);
   if (length != range.getLength()) {
     fail(req, resp, "Chunk specifies an incorrect document length");
     return;
   }
   if (range.getStartByte() > transferred) {
     fail(req, resp, "Chunk missing; Expected start byte: " + transferred);
     return;
   }
   if (range.getEndByte() < range.getStartByte()) {
     fail(req, resp, "Invalid range: " + rangeString);
     return;
   }
   int chunkSize = 1 + range.getEndByte() - range.getStartByte();
   if (chunkSize != headerLength) {
     fail(req, resp, "Content-Range doesn't agree with Content-Length");
     return;
   }
   byte[] chunk = readChunk(req, chunkSize);
   FileOutputStream fout = null;
   try {
     fout = new FileOutputStream(new File(getStorageDirectory(), FILE_DATA), true);
     FileChannel channel = fout.getChannel();
     channel.position(range.getStartByte());
     channel.write(ByteBuffer.wrap(chunk));
     channel.close();
   } finally {
     try {
       if (fout != null) fout.close();
     } catch (IOException e) {
       // ignore secondary failure
     }
   }
   transferred = range.getEndByte() + 1;
   setTransferred(transferred);
   save();
   if (transferred >= length) {
     completeTransfer(req, resp);
     return;
   }
   resp.setStatus(308); // Resume Incomplete
   resp.setHeader("Range", "bytes 0-" + range.getEndByte()); // $NON-NLS-2$
   setResponseLocationHeader(req, resp);
 }
コード例 #13
0
  public File download(String songId) {
    try {
      String maxRate = getMaxRate(songId);
      JSONObject songInfo = getSongInfo(songId);
      // 以歌手名字+歌曲名称组成文件名,格式:歌手 - 歌曲名称
      String filename = songInfo.getString("artistName") + " - " + songInfo.getString("songName");

      String link =
          "http://yinyueyun.baidu.com/data/cloud/downloadsongfile?songIds="
              + songId
              + "&rate="
              + maxRate;

      URL urlObject = new URL(link);
      HttpURLConnection httpUrlConnection = (HttpURLConnection) urlObject.openConnection();
      httpUrlConnection.setRequestMethod("GET");
      httpUrlConnection.setDoOutput(true);
      httpUrlConnection.setRequestProperty("Cookie", cookieValue);
      String disposition = httpUrlConnection.getHeaderField("Content-Disposition");
      disposition = disposition.replaceAll("\"", "");
      // 此转码经测试发现有些是UTF-8编码,有些是GBK编码,所以文件名采用另外方式获得
      // disposition = new String(disposition.getBytes("iso-8859-1"),"UTF-8");

      // 根据disposition中信息确定歌曲格式
      String suffix = disposition.substring(disposition.lastIndexOf("."));
      // System.out.println(disposition);

      InputStream inputStream = httpUrlConnection.getInputStream();

      File file = new File(downloadDirectory + "/" + filename + suffix);
      FileOutputStream fos = new FileOutputStream(file);

      byte[] buf = new byte[4096];
      int read = 0;
      while ((read = inputStream.read(buf)) > 0) {
        fos.write(buf, 0, read);
      }
      fos.flush();
      fos.close();
      inputStream.close();
      // System.out.println("完成<"+file.getName()+">歌曲下载!");
      return file;

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
コード例 #14
0
ファイル: RunRetriever.java プロジェクト: ronaldploeger/faban
  private static File download(Config.HostInfo host, NameValuePair<Long> run) throws IOException {

    File jarFile = null;
    FileOutputStream jarOut = null;
    URL target = new URL(host.url, SERVLET_PATH);

    HttpURLConnection c = null;
    try {
      c = (HttpURLConnection) target.openConnection();
      c.setRequestMethod("POST");
      c.setConnectTimeout(2000);
      c.setDoOutput(true);
      c.setDoInput(true);
      PrintWriter out = new PrintWriter(c.getOutputStream());
      out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&runid=" + run.name);
      out.flush();
      out.close();
    } catch (SocketTimeoutException e) {
      logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e);
      throw new IOException("Socket connect timeout");
    }

    int responseCode = c.getResponseCode();
    if (responseCode == HttpServletResponse.SC_OK) {
      InputStream is = c.getInputStream();
      // We allocate in every method instead of a central buffer
      // to allow concurrent downloads. This can be expanded to use
      // buffer pools to avoid GC, if necessary.
      byte[] buffer = new byte[8192];
      int size;
      while ((size = is.read(buffer)) != -1) {
        if (size > 0 && jarFile == null) {
          jarFile = new File(Config.TMP_DIR, host.name + '.' + run.name + ".jar");
          jarOut = new FileOutputStream(jarFile);
        }
        jarOut.write(buffer, 0, size);
      }
      is.close();
      jarOut.flush();
      jarOut.close();
    } else {
      logger.warning(
          "Downloading run " + run.name + " from " + target + " got response code " + responseCode);
    }
    return jarFile;
  }
コード例 #15
0
ファイル: FileServer.java プロジェクト: scyptnex/computing
 public static byte[] recvFile(Socket sock, File out)
     throws IOException, NoSuchAlgorithmException {
   FileOutputStream mainOut = new FileOutputStream(out);
   byte[] ret = null;
   boolean reading = true;
   MessageDigest major = MessageDigest.getInstance(SecureUtils.STD_HASH);
   int block = 0;
   while (reading) { // while there is data to be read
     long readln = readInteger(sock.getInputStream()); // read the length of the next block
     if (readln == TRANS_FINISH) { // if there are no more block
       mainOut.close();
       ret = major.digest();
       sock.getOutputStream().write(ret); // send my major hash
       long finishReply = readInteger(sock.getInputStream()); // read the reply
       if (finishReply == TRANS_FINISH) { // if the major hash was correct
         reading = false; // complete the transaction
       } else { // else the major has was incorrect
         out.delete(); // delete the file
         mainOut = new FileOutputStream(out); // reset the output streams
         // start again
         block = 0;
         major = MessageDigest.getInstance(SecureUtils.STD_HASH);
         ret = null;
       }
     } else { // else there are more blocks
       File tempOut = new File(out.getParentFile(), out.getName() + ".part" + block);
       FileOutputStream partStream = new FileOutputStream(tempOut); // spawn a temporary file
       byte[] hash =
           hashpipe(sock.getInputStream(), partStream, readln); // read the block to temp file
       partStream.close();
       sock.getOutputStream().write(hash); // send my minor hash
       long minorReply = readInteger(sock.getInputStream()); // read the reply
       if (minorReply == TRANS_SUCCESS) { // if the transfer was correct
         FileInputStream partIn = new FileInputStream(tempOut);
         hashpipe(partIn, mainOut, readln, major); // send the temp file to the main file
         block++;
       } else { // if the transfer was wrong
         // do nothing
       }
       tempOut.delete(); // delete the temp file
     }
   }
   return ret;
 }
コード例 #16
0
ファイル: youtubedl.java プロジェクト: akashthakrar/youtubedl
  public static void download(String index, String fname) throws Exception {
    int avd = Integer.parseInt(index.split("-")[0]);
    String type;
    URL ylink_download;
    int dindex = Integer.parseInt(index.split("-")[1]);
    if (avd == 3) {
      ylink_download = new URL((av_set.get(dindex - 1)).split("\n")[0]);
      type = (av_set.get(dindex - 1)).split("\n")[1];
    } else if (avd == 2) {
      ylink_download = new URL((video_set.get(dindex - 1)).split("\n")[0]);
      type = (video_set.get(dindex - 1)).split("\n")[1];
    } else if (avd == 1) {
      ylink_download = new URL((audio_set.get(dindex - 1)).split("\n")[0]);
      type = (audio_set.get(dindex - 1)).split("\n")[1];
    } else {
      System.out.println("Enter valid input");
      return;
    }
    InputStream is = ylink_download.openStream();
    URLConnection con = (URLConnection) ylink_download.openConnection();
    double dsize = con.getContentLength() / 1048576;
    System.out.println("\nDownloading : " + dsize + " MB");
    if (con != null) {
      String wd = System.getProperty("user.dir");
      String fo = fname + "." + type.split("%2F")[1];
      File f = new File(wd, fo);

      FileOutputStream fos = new FileOutputStream(f);
      byte[] buffer = new byte[1024];
      progressbar t1 = new progressbar(dsize * 1048576, fo);
      t1.start();
      int len1 = 0;
      if (is != null) {
        while ((len1 = is.read(buffer)) > 0) {
          fos.write(buffer, 0, len1);
        }
      }
      if (fos != null) {
        fos.close();
      }
    }
    System.out.println("Download Complete");
  }
コード例 #17
0
ファイル: FileGetter.java プロジェクト: dpaola2/Spider
 public FileGetter(String name) {
   try {
     file = new File(name);
     os = new FileOutputStream(file);
     sock = serv.accept();
     is = new DataInputStream(sock.getInputStream());
   } catch (Exception e) {
     System.out.println("Error in constructor: " + e);
   }
   try {
     boolean go = true;
     while (go) {
       int c = is.readInt();
       if (c != -1) {
         os.write(c);
         os.flush();
       } else go = false;
     }
   } catch (Exception e) {
     System.out.println("Error getting file: " + e);
   }
 }
コード例 #18
0
  public static void saveBinaryFile(URL u) throws IOException {
    URLConnection uc = u.openConnection();
    String contentType = uc.getContentType();
    int contentLength = uc.getContentLength();
    if (contentType.startsWith("text/") || contentLength == -1) {
      throw new IOException("This is not a binary file.");
    }
    InputStream raw = uc.getInputStream();
    try {
      InputStream in = new BufferedInputStream(raw);
      byte[] data = new byte[contentLength];
      int offset = 0;
      while (offset < contentLength) {
        int bytesRead = in.read(data, offset, data.length - offset);
        if (bytesRead == -1) break;
        offset += bytesRead;
      }

      if (offset != contentLength) {
        throw new IOException(
            "Only read " + offset + " bytes; Expected " + contentLength + " bytes");
      }
      String filename = u.getFile();
      filename = filename.substring(filename.lastIndexOf('/') + 1);
      FileOutputStream fout = new FileOutputStream(filename);
      try {
        fout.write(data);
        fout.flush();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        fout.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #19
0
  void ReceiveFile() throws Exception {
    String fileName;
    System.out.print("Enter File Name :");
    fileName = br.readLine();
    dout.writeUTF(fileName);
    String msgFromServer = din.readUTF();

    if (msgFromServer.compareTo("File Not Found") == 0) {
      System.out.println("File not found on Server ...");
      return;
    } else if (msgFromServer.compareTo("READY") == 0) {
      System.out.println("Receiving File ...");
      File f = new File(fileName);
      if (f.exists()) {
        String Option;
        System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
        Option = br.readLine();
        if (Option == "N") {
          dout.flush();
          return;
        }
      }
      FileOutputStream fout = new FileOutputStream(f);
      int ch;
      String temp;
      do {
        temp = din.readUTF();
        ch = Integer.parseInt(temp);
        if (ch != -1) {
          fout.write(ch);
        }
      } while (ch != -1);
      fout.close();
      System.out.println(din.readUTF());
    }
  }
コード例 #20
0
 @Override
 public void close() throws IOException {
   if (connHandler == null) {
     return;
   }
   super.close();
   InputStream in = new FileInputStream(tmpFile);
   try {
     copyFileToRemote(fileName, in, this.tmpFile.length(), connHandler, fileManager);
   } finally {
     connHandler.releaseLock();
     connHandler = null;
     in.close();
     tmpFile.delete();
   }
 }
コード例 #21
0
  public final void run() {
    if (socketthread) {
      socketrun();
      return;
    }
    socketthread = true;
    try {
      boolean flag = false;
      try {
        String s = getParameter("member");
        int i = Integer.parseInt(s);
        if (i == 1) flag = true;
      } catch (Exception _ex) {
      }
      loading = getImage(new URL(getCodeBase(), "loading.jpg"));
      mt = new MediaTracker(this);
      mt.addImage(loading, 0);
      m = MessageDigest.getInstance("SHA");
      System.out.println(link.class);
      String s1 = ".file_store_32/";
      if (s1 == null) return;
      link.uid = getuid(s1);
      link.mainapp = this;
      link.numfile = 0;
      for (int j = 0; j < 14; j++)
        if (flag || !internetname[j].endsWith(".mem")) {
          for (int k = 0; k < 4; k++) {
            if (k == 3) return;
            byte abyte0[] = loadfile(s1 + localname[j], sha[j]);
            if (abyte0 != null) {
              if (j > 0) link.putjag(internetname[j], abyte0);
              break;
            }
            try {
              URL url = new URL(getCodeBase(), internetname[j]);
              DataInputStream datainputstream = new DataInputStream(url.openStream());
              int l = size[j];
              byte abyte1[] = new byte[l];
              for (int i1 = 0; i1 < l; i1 += 1000) {
                int j1 = l - i1;
                if (j1 > 1000) j1 = 1000;
                datainputstream.readFully(abyte1, i1, j1);
                showpercent(nicename[j], (i1 * 100) / l, barpos[j]);
              }

              datainputstream.close();
              FileOutputStream fileoutputstream = new FileOutputStream(s1 + localname[j]);
              fileoutputstream.write(abyte1);
              fileoutputstream.close();
            } catch (Exception _ex) {
            }
          }
        }
      System.out.println(cloader.class);
      cloader cloader1 = new cloader();
      cloader1.zip = new ZipFile(s1 + localname[0]);
      cloader1.link = Class.forName("link");
      inner = new mudclient_Debug();
      loadMacros();
      // inner = (Applet)cloader1.loadClass("mudclient").newInstance();
      inner.init();
      inner.start();
      return;
    } catch (Exception exception) {
      System.out.println(exception + " " + exception.getMessage());
      exception.printStackTrace();
      return;
    }
  }
コード例 #22
0
  public void run() {
    active = true;
    String s = findcachedir();
    uid = getuid(s);
    try {
      File file = new File(s + "main_file_cache.dat");
      if (file.exists() && file.length() > 0x3200000L) file.delete();
      cache_dat = new RandomAccessFile(s + "main_file_cache.dat", "rw");
      for (int j = 0; j < 5; j++)
        cache_idx[j] = new RandomAccessFile(s + "main_file_cache.idx" + j, "rw");

    } catch (Exception exception) {
      exception.printStackTrace();
    }
    for (int i = threadliveid; threadliveid == i; ) {
      if (socketreq != 0) {
        try {
          socket = new Socket(socketip, socketreq);
        } catch (Exception _ex) {
          socket = null;
        }
        socketreq = 0;
      } else if (threadreq != null) {
        Thread thread = new Thread(threadreq);
        thread.setDaemon(true);
        thread.start();
        thread.setPriority(threadreqpri);
        threadreq = null;
      } else if (dnsreq != null) {
        try {
          dns = InetAddress.getByName(dnsreq).getHostName();
        } catch (Exception _ex) {
          dns = "unknown";
        }
        dnsreq = null;
      } else if (savereq != null) {
        if (savebuf != null)
          try {
            FileOutputStream fileoutputstream = new FileOutputStream(s + savereq);
            fileoutputstream.write(savebuf, 0, savelen);
            fileoutputstream.close();
          } catch (Exception _ex) {
          }
        if (waveplay) {
          String wave = s + savereq;
          waveplay = false;
        }
        if (midiplay) {
          midi = s + savereq;
          midiplay = false;
        }
        savereq = null;
      } else if (urlreq != null) {
        try {
          System.out.println("urlstream");
          urlstream = new DataInputStream((new URL(mainapp.getCodeBase(), urlreq)).openStream());
        } catch (Exception _ex) {
          urlstream = null;
        }
        urlreq = null;
      }
      try {
        Thread.sleep(50L);
      } catch (Exception _ex) {
      }
    }
  }
コード例 #23
0
  public static void main(String[] args) throws IOException {

    int servPort = Integer.parseInt(args[0]);

    String ksName = "keystore.jks";
    char ksPass[] = "password".toCharArray();
    char ctPass[] = "password".toCharArray();
    try {
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(ksName), ksPass);
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, ctPass);
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(kmf.getKeyManagers(), null, null);
      SSLServerSocketFactory ssf = sc.getServerSocketFactory();
      SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(servPort);

      while (true) {
        // Listen for a TCP connection request.
        SSLSocket c = (SSLSocket) s.accept();

        BufferedOutputStream out = new BufferedOutputStream(c.getOutputStream(), 1024);
        BufferedInputStream in = new BufferedInputStream(c.getInputStream(), 1024);

        byte[] byteBuffer = new byte[1024];
        int count = 0;
        while ((byteBuffer[count] = (byte) in.read()) != -2) {
          count++;
        }
        String newFile = new String(byteBuffer, 0, count, "US-ASCII");
        FileOutputStream writer = new FileOutputStream(newFile.trim());
        int buffSize = 0;
        while ((buffSize = in.read(byteBuffer, 0, 1024)) != -1) {
          int index = 0;
          if ((index =
                  (new String(byteBuffer, 0, buffSize, "US-ASCII"))
                      .indexOf("------MagicStringCSE283Miami"))
              == -1) {
            writer.write(byteBuffer, 0, buffSize);
          } else {
            writer.write(byteBuffer, 0, index);
            break;
          }
        }
        writer.flush();
        writer.close();

        ZipOutputStream outZip = new ZipOutputStream(new BufferedOutputStream(out));
        FileInputStream fin = new FileInputStream(newFile.trim());
        BufferedInputStream origin = new BufferedInputStream(fin, 1024);
        ZipEntry entry = new ZipEntry(newFile.trim());
        outZip.putNextEntry(entry);

        byteBuffer = new byte[1024];
        int bytes = 0;
        while ((bytes = origin.read(byteBuffer, 0, 1024)) != -1) {
          outZip.write(byteBuffer, 0, bytes);
        }
        origin.close();
        outZip.flush();
        outZip.close();
        out.flush();
        out.close();
      }
    } catch (Exception e) {
      System.err.println(e.toString());
    }
  }
コード例 #24
0
  /** The run method. */
  public void run() {
    instances.add(this);
    try {
      listener.startUnpack();
      String currentOs = System.getProperty("os.name").toLowerCase();
      //
      // Initialisations
      FileOutputStream out = null;
      ArrayList parsables = new ArrayList();
      ArrayList executables = new ArrayList();
      List packs = idata.selectedPacks;
      int npacks = packs.size();
      udata = UninstallData.getInstance();

      // Specific to the web installers
      if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) {
        InputStream kin = getClass().getResourceAsStream("/res/WebInstallers.url");
        BufferedReader kreader = new BufferedReader(new InputStreamReader(kin));
        jarLocation = kreader.readLine();
      }

      // We unpack the selected packs
      for (int i = 0; i < npacks; i++) {
        // We get the pack stream
        int n = idata.allPacks.indexOf(packs.get(i));
        ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n));

        // We unpack the files
        int nfiles = objIn.readInt();
        listener.changeUnpack(0, nfiles, ((Pack) packs.get(i)).name);
        for (int j = 0; j < nfiles; j++) {
          // We read the header
          PackFile pf = (PackFile) objIn.readObject();
          if (null == pf.os || matchOS(currentOs, pf.os.toLowerCase())) {
            // We translate & build the path
            String path = translatePath(pf.targetPath);
            File pathFile = new File(path);
            String fname = pathFile.getName();
            int z = fname.length();
            File dest = pathFile.getParentFile();
            if (!dest.exists()) dest.mkdirs();

            // We add the path to the log,
            udata.addFile(path);

            listener.progressUnpack(j, path);

            // if this file exists and shouldnot override skip this file
            if (((pf.override == false) && (pathFile.exists()))) {
              objIn.skip(pf.length);
              continue;
            }

            // We copy the file
            out = new FileOutputStream(path);
            byte[] buffer = new byte[5120];
            long bytesCopied = 0;
            while (bytesCopied < pf.length) {
              int maxBytes =
                  (pf.length - bytesCopied < buffer.length
                      ? (int) (pf.length - bytesCopied)
                      : buffer.length);
              int bytesInBuffer = objIn.read(buffer, 0, maxBytes);
              if (bytesInBuffer == -1) throw new IOException("Unexpected end of stream");

              out.write(buffer, 0, bytesInBuffer);

              bytesCopied += bytesInBuffer;
            }
            // Cleanings
            out.close();

            // Empty dirs restoring
            String _n = pathFile.getName();
            if (_n.startsWith("izpack-keepme") && _n.endsWith(".tmp")) pathFile.delete();

          } else objIn.skip(pf.length);
        }

        // Load information about parsable files
        int numParsables = objIn.readInt();
        int k;
        for (k = 0; k < numParsables; k++) {
          ParsableFile pf = (ParsableFile) objIn.readObject();
          pf.path = translatePath(pf.path);
          parsables.add(pf);
        }

        // Load information about executable files
        int numExecutables = objIn.readInt();
        for (k = 0; k < numExecutables; k++) {
          ExecutableFile ef = (ExecutableFile) objIn.readObject();
          ef.path = translatePath(ef.path);
          if (null != ef.argList && !ef.argList.isEmpty()) {
            String arg = null;
            for (int j = 0; j < ef.argList.size(); j++) {
              arg = (String) ef.argList.get(j);
              arg = translatePath(arg);
              ef.argList.set(j, arg);
            }
          }
          executables.add(ef);
          if (ef.executionStage == ExecutableFile.UNINSTALL) {
            udata.addExecutable(ef);
          }
        }
        objIn.close();
      }

      // We use the scripts parser
      ScriptParser parser = new ScriptParser(parsables, vs);
      parser.parseFiles();

      // We use the file executor
      FileExecutor executor = new FileExecutor(executables);
      if (executor.executeFiles(ExecutableFile.POSTINSTALL) != 0)
        javax.swing.JOptionPane.showMessageDialog(
            null,
            "The installation was not completed.",
            "Installation warning",
            javax.swing.JOptionPane.WARNING_MESSAGE);

      // We put the uninstaller
      putUninstaller();

      // The end :-)
      listener.stopUnpack();
    } catch (Exception err) {
      listener.stopUnpack();
      listener.errorUnpack(err.toString());
    }
    instances.remove(instances.indexOf(this));
  }
コード例 #25
0
ファイル: Client.java プロジェクト: kallivis/DataComProject
  public static void main(String[] args) {
    // Checks if no command line args were given by usej
    if (args.length <= 0) {
      System.out.println("No user specified!");
      return;
    }
    // Sets the filename equal to the command line argument
    String filename = "";
    String message = args[0];

    try {
      // Creates an InetAddress using localhost
      InetAddress address = InetAddress.getByName("localhost");

      // The byte buffer used for data the client is sending
      byte[] sdata = new byte[PACKET_SIZE];
      // The byte buffer used for data the client is receiving
      byte[] rData = new byte[PACKET_SIZE];

      // Puts "Sync" into the send Data
      sdata = ("SYNC" + message).getBytes();

      DatagramSocket socket = new DatagramSocket();
      // Socket timesout after 5 seconds to prevent infinite wait
      socket.setSoTimeout(5000);

      // Creates the packet and puts in the message
      DatagramPacket packet = new DatagramPacket(sdata, sdata.length, address, 3031);

      // Sends packet with the message to the server
      socket.send(packet);

      // Creates the recieve packet
      DatagramPacket rpacket = new DatagramPacket(rData, rData.length);

      socket.receive(rpacket);
      // Pulls the string out of the recieved packet
      String cmd1 = new String(rpacket.getData(), 0, rpacket.getLength());

      // Checks if the server sent SYNACK
      if (cmd1.substring(0, 6).equals("SYNACK")) {
        String dirList = cmd1.substring(6);
        System.out.println(dirList);
        System.out.flush();
        System.out.println(
            "Please type the file you wish to receive, or type " + "EXIT to close the server");
        Scanner scan = new Scanner(System.in);
        filename = scan.next();
        // Puts the file named into the Send Data
        sdata = filename.getBytes();
        // Creates a Packet with the Filename
        packet = new DatagramPacket(sdata, sdata.length, address, 3031);
        socket.send(packet);
      } else return;
      // Checks if the filename is Exit. If so the client exits as well
      if (filename.equals("EXIT")) {
        System.out.println("Exit request sent.");
        return;
      }
      // Creates a local file to put the data recieved from the server in.
      socket.receive(rpacket);
      // Pulls the filename out of the recieved packet
      filename = new String(rpacket.getData(), 0, rpacket.getLength());

      // Check if the first 7 characters are 'FILEACK', if so set file name
      // to the rest of the message
      if (filename.substring(0, 7).equals("FILEACK")) {
        filename = filename.substring(9 + message.length(), filename.length());
        System.out.println("File name requested: " + filename);
      } else {
        // If no FILEACK, then the file specified was not valid
        System.out.println("Not a valid file!");
        return;
      }
      File file = new File("local_" + filename);
      // Opens a FileOutputStream to use to write the data in the above file.
      FileOutputStream fos = new FileOutputStream(file);
      // Creates the receiving packet for data comming form the server

      System.out.println("Transfer started.");
      // The loop to received the packets of requested data.

      windowPackets = new DatagramPacket[MAX_SEQ];
      CRC32 crc = new CRC32();
      while (!done) {
        // Receives a packet sent from server
        socket.receive(rpacket);

        // Initialize arrays
        byte[] info = new byte[INT_SIZE];
        byte[] code = new byte[CHECKSUM_SIZE];
        byte[] data = new byte[rpacket.getLength() - SAC_SIZE];
        byte[] data2 = new byte[rpacket.getLength() - CHECKSUM_SIZE];

        // Split packet data into appropriate arrays
        System.arraycopy(rpacket.getData(), 0, info, 0, INT_SIZE);
        System.arraycopy(rpacket.getData(), INT_SIZE, data, 0, rpacket.getLength() - SAC_SIZE);
        System.arraycopy(rpacket.getData(), 0, data2, 0, rpacket.getLength() - CHECKSUM_SIZE);
        System.arraycopy(
            rpacket.getData(), rpacket.getLength() - CHECKSUM_SIZE, code, 0, CHECKSUM_SIZE);

        // Convert seq num and other numbers from bytes to ints
        int packNum2 = ByteConverter.toInt(info, 0);
        int sCode = ByteConverter.toInt(code, 0);
        int packNum = ByteConverter.toInt(info, 0);

        // Reset and update crc for next packet
        crc.reset();
        crc.update(data2, 0, data2.length);
        int cCode = (int) crc.getValue();

        byte[] ackNum = ByteConverter.toBytes(packNum);
        ArrayList<Integer> expecting = new ArrayList<Integer>();

        // Check for errors
        if (cCode == sCode) {
          // Create expected sequence numbers
          for (int i = 0; i < WINDOW_SIZE; i++) {
            if (base + i >= MAX_SEQ) expecting.add((base + i) - MAX_SEQ);
            else expecting.add(base + i);
          }

          // If packet number is base packet number
          if (packNum == base) {
            ackNum = ByteConverter.toBytes(packNum);
            packet = new DatagramPacket(ackNum, ackNum.length, address, 3031);
            socket.send(packet);

            // If last packet
            if (rpacket.getLength() == 0) {
              done = true;
              break;
            }
            // Write and move base forward
            fos.write(data, 0, data.length);
            base++;

            if (base == MAX_SEQ) base = 0;

            // update expected packets
            for (int i = 0; i < WINDOW_SIZE; i++) {
              if (base + i >= MAX_SEQ) expecting.add((base + i) - MAX_SEQ);
              else expecting.add(base + i);
            }

            // If the packet has data it writes it into the local file.
            // If this packet is smaller than the agree upon size then it knows
            // that the transfer is complete and client ends.
            if (rpacket.getLength() < PACKET_SIZE) {
              System.out.println("File transferred");
              done = true;
              break;
            }

            // While there are packets in buffer, move packet to file
            while (windowPackets[base] != null) {
              DatagramPacket nextPacket = windowPackets[base];
              windowPackets[base] = null;

              data = new byte[nextPacket.getLength() - SAC_SIZE];
              System.arraycopy(
                  nextPacket.getData(), INT_SIZE, data, 0, nextPacket.getLength() - SAC_SIZE);
              System.arraycopy(nextPacket.getData(), 0, info, 0, INT_SIZE);

              packNum = ByteConverter.toInt(info, 0);

              // If packet size is 0, then it is the last packet
              if (nextPacket.getLength() == 0) {
                System.out.println("File transferred");
                done = true;
                break;
              }

              // Write and move base forward
              fos.write(data, 0, data.length);
              base++;

              if (base == MAX_SEQ) base = 0;
              expecting.clear();

              // Update expected
              for (int i = 0; i < WINDOW_SIZE; i++) {
                if (base + i >= MAX_SEQ) expecting.add((base + i) - MAX_SEQ);
                else expecting.add(base + i);
              }

              // If the packet has data it writes it into the local file.
              // If this packet is smaller than the agree upon size then it knows
              // that the transfer is complete and client ends.
              if (nextPacket.getLength() < PACKET_SIZE) {
                System.out.println("File transferred");
                done = true;
                break;
              }
            }
          } else if (expecting.contains(packNum)) {
            // If its expected, put it into buffer
            windowPackets[packNum] = rpacket;
            System.arraycopy(rpacket.getData(), 0, info, 0, INT_SIZE);
            packNum = ByteConverter.toInt(info, 0);
            ackNum = ByteConverter.toBytes(packNum);
            packet = new DatagramPacket(ackNum, ackNum.length, address, 3031);
            socket.send(packet);
          } else {
            // If not expected, just ACK packet
            System.arraycopy(rpacket.getData(), 0, info, 0, INT_SIZE);
            packNum = ByteConverter.toInt(info, 0);
            ackNum = ByteConverter.toBytes(packNum);
            packet = new DatagramPacket(ackNum, ackNum.length, address, 3031);
            socket.send(packet);
          }

        } else {
          // CRC found error with packet
          System.out.println("ERROR");
        }
      }

      // transfer is done
      System.out.println("File length - " + file.length());
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #26
0
  // 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.");
    }
  }