@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(...)]");
    }
  }
  // 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;
    }
  }
Exemplo n.º 3
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;
    }
  }
Exemplo n.º 4
0
  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;
  }
Exemplo n.º 5
0
 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);
   }
 }
Exemplo n.º 6
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();
    }
  }
  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());
    }
  }