Exemple #1
0
  public boolean downloadRemoteToLocalTempfile(String s, File f) {
    try {
      URL url = new URI(s).toURL();
      URLConnection urlConnection = url.openConnection();
      try (BufferedInputStream in = new BufferedInputStream(urlConnection.getInputStream());
          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f))) {

        byte[] buffer = new byte[1024 * 1024];
        int len = in.read(buffer);
        while (len >= 0) {
          out.write(buffer, 0, len);
          len = in.read(buffer);
        }
        out.flush();
      }
      if (urlConnection.getContentLength() == f.length()) {
        return true;
      }
    } catch (MalformedURLException | URISyntaxException ex) {
      Logger.getLogger(TileServer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      // Logger.getLogger(TileServer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
  }
 public void write(File file, Drawing drawing) throws IOException {
     BufferedOutputStream out = new BufferedOutputStream(
             new FileOutputStream(file));
     try {
         write(out, drawing);
     } finally {
         if (out != null) {
             out.close();
         }
     }
 }
Exemple #3
0
  /**
   * Copies a file or directory
   *
   * @param src the file or directory to copy
   * @param dest where copy
   * @throws IOException
   */
  public static void copyFile(File src, File dest) throws IOException {
    if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'");
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));

    byte[] read = new byte[4096];
    int len;
    while ((len = in.read(read)) > 0) out.write(read, 0, len);

    out.flush();
    out.close();
    in.close();
  }
 /**
  * Sends an input stream to the server.
  *
  * @param input xml input
  * @throws IOException I/O exception
  */
 private void send(final InputStream input) throws IOException {
   final BufferedInputStream bis = new BufferedInputStream(input);
   final BufferedOutputStream bos = new BufferedOutputStream(out);
   for (int b; (b = bis.read()) != -1; ) {
     // 0x00 and 0xFF will be prefixed by 0xFF
     if (b == 0x00 || b == 0xFF) bos.write(0xFF);
     bos.write(b);
   }
   bos.write(0);
   bos.flush();
   info = receive();
   if (!ok()) throw new IOException(info);
 }
Exemple #5
0
 // Take a tree of files starting in a directory in a zip file
 // and copy them to a disk directory, recreating the tree.
 private int unpackZipFile(
     File inZipFile, String directory, String parent, boolean suppressFirstPathElement) {
   int count = 0;
   if (!inZipFile.exists()) return count;
   parent = parent.trim();
   if (!parent.endsWith(File.separator)) parent += File.separator;
   if (!directory.endsWith(File.separator)) directory += File.separator;
   File outFile = null;
   try {
     ZipFile zipFile = new ZipFile(inZipFile);
     Enumeration zipEntries = zipFile.entries();
     while (zipEntries.hasMoreElements()) {
       ZipEntry entry = (ZipEntry) zipEntries.nextElement();
       String name = entry.getName().replace('/', File.separatorChar);
       if (name.startsWith(directory)) {
         if (suppressFirstPathElement) name = name.substring(directory.length());
         outFile = new File(parent + name);
         // Create the directory, just in case
         if (name.indexOf(File.separatorChar) >= 0) {
           String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1);
           File dirFile = new File(parent + p);
           dirFile.mkdirs();
         }
         if (!entry.isDirectory()) {
           System.out.println("Installing " + outFile);
           // Copy the file
           BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
           BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
           int size = 1024;
           int n = 0;
           byte[] b = new byte[size];
           while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n);
           in.close();
           out.flush();
           out.close();
           // Count the file
           count++;
         }
       }
     }
     zipFile.close();
   } catch (Exception e) {
     System.err.println("...an error occured while installing " + outFile);
     e.printStackTrace();
     System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage());
     return -count;
   }
   System.out.println(count + " files were installed.");
   return count;
 }
  public void run() {

    byte[] tmp = new byte[10000];
    int read;
    try {
      FileInputStream fis = new FileInputStream(fileToSend.getFile());

      read = fis.read(tmp);
      while (read != -1) {
        baos.write(tmp, 0, read);
        read = fis.read(tmp);
        System.out.println(read);
      }
      fis.close();
      baos.writeTo(sWriter);
      sWriter.flush();
      baos.flush();
      baos.close();
      System.out.println("fileSent");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {

      this.closeSocket();
    }
  }
  public static void main(String args[]) {

    while (true) {
      ServerSocket welcomeSocket = null;
      Socket connectionSocket = null;
      BufferedOutputStream outToClient = null;

      try {
        welcomeSocket = new ServerSocket(3248);
        connectionSocket = welcomeSocket.accept();
        outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
      } catch (IOException e) {
        e.printStackTrace();
      }

      if (outToClient != null) {
        File myFile = new File(fileToSend);
        byte[] mybytearray = new byte[(int) myFile.length()];

        FileInputStream fis = null;

        try {
          fis = new FileInputStream(myFile);
        } catch (FileNotFoundException ex) {
          ex.printStackTrace();
        }
        BufferedInputStream bis = new BufferedInputStream(fis);

        try {
          bis.read(mybytearray, 0, mybytearray.length);
          outToClient.write(mybytearray, 0, mybytearray.length);
          outToClient.flush();
          // the next two lines are not necessary (Autocloseable))
          outToClient.close();
          connectionSocket.close();

          // File sent, exit the main method
          return;
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Exemple #8
0
  public void run() {

    do {
      try {
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        File file = new File("time.txt");
        FileWriter fw = new FileWriter(file);
        Long start = 0l;
        Long end = 0l;
        BufferedWriter bw = new BufferedWriter(fw);
        System.out.println("Enter the preferred choice");
        System.out.println("1. REGISTER");
        System.out.println("2. LEAVE");
        System.out.println("3. SEARCH FOR RFC");
        System.out.println("4. KEEPALIVE");
        System.out.println("5. Do you want to EXIT");
        System.out.println("*********************************************");

        choice = Integer.parseInt(inFromUser.readLine());
        // System.out.println(" Client requesting for connection");
        clientSocket = new Socket("192.168.15.103", 6500);
        BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter outToServer =
            new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);

        // outToServer.println("Peer Requesting Connection");

        switch (choice) {
          case 4:
            outToServer.println(
                "KEEP ALIVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;
          case 1:
            try {
              // System.out.println("Case 1 entered"); // testing
              // statement
              System.out.println("Please enter your IP addres");
              ip = inFromUser.readLine();
              outToServer.println(
                  "REG P2P-DI/1.1 -1 Portno 6789 Hostname "
                      + ip
                      + " OS: "
                      + System.getProperty("os.name")
                      + " "
                      + "v"
                      + System.getProperty("os.version")
                      + " USER: "******"user.name"));
              cookie = Integer.parseInt(inFromServer.readLine());
              TTL = 7200;

              System.out.println(inFromServer.readLine());
              System.out.print("You are registered at time : ");
              ct.currenttime();
              System.out.println("Peer " + cookie); // peer cookie value
              System.out.println("TTL Value :" + TTL);
              System.out.println("*********************************************");

              break;
            } catch (Exception e) {
            }
          case 2:

            // System.out.println("Case 2 entered"); testing statement
            outToServer.println(
                "LEAVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            // System.out.println("I am in peer"); testing statement
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;

          case 3:
            outToServer.println(
                "PQUERY P2P-DI Cookieno "
                    + cookie
                    + " Portno 6789"
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println("Which RFC number do you wish to have ?");
            reqrfc = Integer.parseInt(inFromUser.readLine());

            // System.out.println("Entered peer again");
            // outToServer.println("KEEP ALIVE cookieno "+cookie);

            String details = inFromServer.readLine();

            String[] parray = details.split(" ");
            int inactive = Integer.parseInt(parray[(parray.length - 1)]);
            // System.out.println(darray.length);
            if ((parray.length == 3) && (ip.equals(parray[1]))) {
              System.out.println("P2P-DI No Active Peers available");
              System.out.println("*********************************************");
            } else {
              System.out.println("****<POPULATING THE ACTIVE PEER LIST>****");
              System.out.println();
              System.out.println("The active peer list is as follows:");
              System.out.println();

              String[] darray = details.split(" ");

              // System.out.println("Array length"+darray.length);
              for (int i = 0; i < (darray.length - 2); i = i + 2) {

                acthostname[j] = darray[i + 1];
                System.out.println("Hostname :" + acthostname[j]);

                actportno[j] = Integer.parseInt(darray[i + 2]);
                System.out.println("Portno :" + actportno[j]);

                System.out.println("*****************************");
                j = j + 1;
              }

              System.out.println("Connecting to the active peers for its RFC Index");
              for (int x = 0; x < j; x++) {
                // System.out.println(ip);
                if (!(acthostname[x].equals(ip))) {
                  System.out.println("Connecting to " + acthostname[x]);

                  Socket peersocket = new Socket(acthostname[x], 6791); // implement
                  // a for
                  // loop

                  BufferedReader inFromPeer =
                      new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
                  PrintWriter outToPeer =
                      new PrintWriter(new OutputStreamWriter(peersocket.getOutputStream()), true);

                  outToPeer.println("RFCIndex");
                  // System.out.println(inFromServer.readLine());
                  // int searchrfc=Integer.parseInt(inFromUser.readLine());
                  // outToServer.println(searchrfc);

                  String rfcindex = inFromPeer.readLine(); // tell server to
                  // send rfc in
                  // string
                  String rfcarray[] = rfcindex.split(" ");
                  //  System.out.println(rfcindex);
                  for (int i = 1; i < rfcarray.length; i = i + 4) {
                    trfcno[z] = Integer.parseInt(rfcarray[i]);
                    //	System.out.println("RFC number " + trfcno[z]);
                    trfctitle[z] = rfcarray[i + 1];
                    //	System.out.println("RFC Title " + trfctitle[z]);
                    tpeername[z] = rfcarray[i + 2];
                    //	System.out.println("Peer Ip Address " + tpeername[z]);
                    tpTTL[z] = Integer.parseInt(rfcarray[i + 3]);
                    //	System.out.println("TTL value :" + tpTTL[z]);

                    counter1 = counter1 + 1;

                    z = z + 1;
                  }
                  z = 0;
                  //         if(arraybound==0)
                  //         {
                  System.arraycopy(trfcno, 0, rfcno, counter2, trfcno.length);
                  System.arraycopy(trfctitle, 0, rfctitle, counter2, trfctitle.length);
                  System.arraycopy(tpeername, 0, peername, counter2, tpeername.length);
                  System.arraycopy(tpTTL, 0, pTTL, counter2, tpTTL.length);
                  z = 0;
                  counter2 = counter1;
                  counter1 = 0;
                  //         arraybound=arraybound+1;
                  //        }

                  System.out.println();
                  System.out.println();
                  System.out.println("*************************************************");
                  System.out.println("RFC Index received from the Peer");
                  //		System.out.println();
                  System.out.println("\n-----------------------------------------");
                  System.out.println("RFC Index System - Display RFC Idex");
                  System.out.println("-------------------------------------------");
                  System.out.format(
                      "%10s%15s%15s%10s", "RFC No", "RFC Title", "Peer Name", "TTL Value");
                  System.out.println();
                  // StudentNode current = top;
                  // while (current != null){
                  // Student read = current.getStudentNode();
                  for (int i = 0; i < 60; i++) {
                    System.out.format(
                        "%10s%15s%15s%10s",
                        " " + rfcno[i], rfctitle[i], peername[i], " " + pTTL[i]);
                    System.out.println();
                  }
                  // This will output with a set number of character spaces
                  // per field, giving the list a table-like quality
                  // }

                  peersocket.close();
                } // end of if

                for (int i = 0; i < rfcno.length; i++) {

                  if (rfcno[i] == reqrfc) {
                    String taddress = InetAddress.getByName(peername[i]).toString();
                    String[] taddr = taddress.split("/");
                    InetAddress tproperaddress = InetAddress.getByName(taddr[1]);
                    //	System.out.println("Inetaddress" + tproperaddress);

                    Socket peersocket1 = new Socket(tproperaddress, 6791); // implement
                    // a
                    // for
                    // loop
                    System.out.println("The connection to the Active Peer is establshed");
                    BufferedReader inFromP2P =
                        new BufferedReader(new InputStreamReader(peersocket1.getInputStream()));
                    PrintWriter outToP2P =
                        new PrintWriter(
                            new OutputStreamWriter(peersocket1.getOutputStream()), true);

                    System.out.println("Requested the RFC to the Active Peer Server");

                    start = System.currentTimeMillis();

                    outToP2P.println("GETRFC " + reqrfc);

                    // Socket socket = ;

                    try {

                      // Socket socket = null;
                      InputStream is = null;
                      FileOutputStream fos = null;
                      BufferedOutputStream bos = null;
                      int bufferSize = 0;

                      try {
                        is = peersocket1.getInputStream();

                        bufferSize = 64;
                        // System.out.println("Buffer size: " + bufferSize);
                      } catch (IOException ex) {
                        System.out.println("Can't get socket input stream. ");
                      }

                      try {
                        fos = new FileOutputStream("E:\\rfc" + reqrfc + "copy.txt");
                        bos = new BufferedOutputStream(fos);

                      } catch (FileNotFoundException ex) {
                        System.out.println("File not found. ");
                      }

                      byte[] bytes = new byte[bufferSize];

                      int count;

                      while ((count = is.read(bytes)) > 0) {
                        //	System.out.println(count);
                        bos.write(bytes, 0, count);
                      }
                      System.out.println("P2P-DI 200 OK The RFC is copied");
                      end = System.currentTimeMillis();
                      System.out.println(
                          "Total Time to download file   " + (end - start) + " milliseconds");

                      bos.flush();

                      bos.close();
                      is.close();
                      peersocket1.close();
                      break;

                    } catch (SocketException e) {
                      System.out.println("Socket exception");
                    }

                  } // end of if
                  else {
                    //  	System.out.println("No Peer with the required RFC could be found");

                  }
                  clientSocket.close();
                  //	System.out.println("Connection closed");
                  bw.close();
                  fw.close();
                } // end of inner for
              } // end of outer for
              System.out.println("Connection closed");
            } // end of switch
        } // end of else which checks the inactive conditions
      } // end of try
      catch (IOException ioe) {
        System.out.println("IOException on socket listen: " + ioe);
        ioe.printStackTrace();
      }

    } // end of do
    while (choice != 5);
  } // end of run
  public static void main(String args[]) {

    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    int bytesRead;
    int current = 0;
    int varInc = 0; // A decrementer pour simuler la perte de la meme trame pour son deuxiem envoi

    int port = 1500;
    ServerSocket socket_serveur;
    BufferedReader input;
    PrintWriter out; // Ajouté

    System.out.println("\n\n*********************************");
    System.out.println("***********Serveur***************");
    System.out.println("*********************************\n\n");
    // si le port est donne en argument!!
    if (args.length == 1) {
      try {
        port = Integer.parseInt(args[0]);
      } catch (Exception e) {
        System.out.println("port d'ecoute= 1500 (par defaut)");
        port = 1500;
      }
    }

    // Ouverture du socket en attente de connexions
    try {
      socket_serveur = new ServerSocket(port);
      System.out.println(
          "Serveur en attente de clients sur le port " + socket_serveur.getLocalPort());

      // boucle infinie: traitement d'une connexion client
      while (true) {
        Socket socket = socket_serveur.accept();
        System.out.println(
            "nouvelle connexion acceptee " + socket.getInetAddress() + ":" + socket.getPort());
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        /*
         *
         * Reception des Trames envoyées par le client 1 Rassembler le
         * tout dans un tableau
         */

        ArrayList<Tram> listTrames = new ArrayList<Tram>();
        try {
          ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
          ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
          Tram trame;
          Tram ack;

          while ((trame = (Tram) ois.readObject()) != null) {
            System.out.print(
                "trame n° "
                    + trame.id
                    + " du fichier : "
                    + FILE_TO_RECEIVED
                    + " telechargée  ("
                    + trame.tabOct.length
                    + "bytes read)");

            if (!listTrames.isEmpty()) { // si ce n'est pas la premiere trame
              if (listTrames.get(listTrames.size() - 1).id
                  == trame.id - 1) { // si c'est la trame qui suit celle recue prealabment
                System.out.println(" <= Données acceptées ");
                listTrames.add(trame);

              } else {
                System.out.println(" <= Données refusées ");
              }

            } else {
              if (trame.id == 0) {
                System.out.println(" <= Données acceptées ");
                listTrames.add(trame);
              } else {
                System.out.println(" <= Données refusées ");
              }
            }

            // Données acceptées ou refusées il faut envoyer un ACK !!!

            // envoie ACK //
            ack = new Tram(null, trame.id); // Envoi une trame vide
            // de 0 octets mais avec
            // l'id de la trame
            // d'avant
            Timer timer = new Timer();
            if (ack.id == 2 && varInc == 0) {
              varInc++;

            } else {
              oos.writeObject(ack);
              System.out.println("Envoi de l'ack pour la trame " + trame.id);
            }

            if (trame.id == 8) break; // le break est a refaire dynamiquement

            oos.flush();
          }

        } catch (ClassNotFoundException e1) {
          // TODO Auto-generated catch block
          e1.printStackTrace();
        }

        /*
         * ETAPE 2 : parcourir le tableau contenant les trames pour les
         * rasesmbler
         */

        System.out.println("Etap 2 ");

        fos = new FileOutputStream(FILE_TO_RECEIVED);
        bos = new BufferedOutputStream(fos);

        for (Tram trame : listTrames) {

          bos.write(trame.tabOct, 0, trame.tabOct.length); // ecrire
          // les 5
          // bytes
          // de la
          // trame
          // i (
          // ou
          // moins
          // pour
          // la
          // derniere)
          // dans
          // bos
          bos.flush();
        }

        // connexion fermee par client
        try {
          socket.close();
          System.out.println("connexion fermee par le client");
        } catch (IOException e) {
          System.out.println(e);
        }
      }

    } catch (IOException e) {
      System.out.println(e);
    }
  }
Exemple #10
0
 @Override
 public void run() {
   String output = "";
   // Get launcher jar
   File Launcher = new File(mcopy.getMinecraftPath() + "minecrafterr.jar");
   jTextArea1.setText(
       "Checking for Minecraft launcher (minecrafterr.jar) in "
           + Launcher.getAbsolutePath()
           + "\n");
   if (!Launcher.exists()) {
     jTextArea1.setText(jTextArea1.getText() + "Error: Could not find launcher!\n");
     jTextArea1.setText(jTextArea1.getText() + "Downloading from Minecraft.net...\n");
     try {
       BufferedInputStream in =
           new BufferedInputStream(
               new URL("https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar")
                   .openStream());
       FileOutputStream fos = new FileOutputStream(mcopy.getMinecraftPath() + "minecrafterr.jar");
       BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
       byte data[] = new byte[1024];
       int x = 0;
       while ((x = in.read(data, 0, 1024)) >= 0) {
         bout.write(data, 0, x);
       }
       bout.close();
       in.close();
     } catch (IOException e) {
       jTextArea1.setText(jTextArea1.getText() + "Download failed..." + "\n");
     }
     jTextArea1.setText(jTextArea1.getText() + "Download successful!" + "\n");
   }
   // Got launcher.
   jTextArea1.setText(jTextArea1.getText() + "Minecraft launcher found!" + "\n");
   jTextArea1.setText(jTextArea1.getText() + "Starting launcher..." + "\n");
   try {
     System.out.println(System.getProperty("os.name"));
     // Run launcher in new process
     Process pr =
         Runtime.getRuntime()
             .exec(
                 System.getProperty("java.home")
                     + "/bin/java -Ddebug=full -cp "
                     + mcopy.getMinecraftPath()
                     + "minecrafterr.jar net.minecraft.LauncherFrame");
     // Grab output
     BufferedReader out = new BufferedReader(new InputStreamReader(pr.getInputStream()));
     BufferedReader outERR = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
     String line = "";
     while ((line = out.readLine()) != null || (line = outERR.readLine()) != null) {
       if (!line.startsWith(
           "Setting user: "******"\n";
         jTextArea1.setText(jTextArea1.getText() + line + "\n");
         jTextArea1.setCaretPosition(jTextArea1.getText().length() - 1);
       }
     }
   } catch (IOException e) {
     jTextArea1.setText(jTextArea1.getText() + e.getMessage() + "\n");
     jTextArea1.setCaretPosition(jTextArea1.getText().length() - 1);
   }
   // set output
   Main.Output = output;
   Main.SPAMDETECT = false;
   jTextArea1.setText(jTextArea1.getText() + "Error report complete.");
   jTextArea1.setCaretPosition(jTextArea1.getText().length() - 1);
   mcopy.analyze(); // Auto-analyze
 }
  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());
    }
  }
Exemple #12
0
    public void run() {
      try {
        boolean keepalive = false;

        do {
          // reset user authentication
          user = password = null;
          String line = readLine();
          // Netscape sends an extra \n\r after bodypart, swallow it
          if ("".equals(line)) line = readLine();
          if (XmlRpc.debug) System.err.println(line);
          // get time of last request
          lastRequest = System.currentTimeMillis();
          int contentLength = -1;

          // tokenize first line of HTTP request
          StringTokenizer tokens = new StringTokenizer(line);
          String method = tokens.nextToken();
          String uri = tokens.nextToken();
          String httpversion = tokens.nextToken();
          keepalive = XmlRpc.getKeepAlive() && "HTTP/1.1".equals(httpversion);
          do {
            line = readLine();
            if (line != null) {
              if (XmlRpc.debug) System.err.println(line);
              String lineLower = line.toLowerCase();
              if (lineLower.startsWith("content-length:"))
                contentLength = Integer.parseInt(line.substring(15).trim());
              if (lineLower.startsWith("connection:"))
                keepalive = XmlRpc.getKeepAlive() && lineLower.indexOf("keep-alive") > -1;
              if (lineLower.startsWith("authorization: basic ")) parseAuth(line);
            }
          } while (line != null && !line.equals(""));

          if ("POST".equalsIgnoreCase(method)) {
            ServerInputStream sin = new ServerInputStream(input, contentLength);
            byte result[] = xmlrpc.execute(sin, user, password);
            output.write(httpversion.getBytes());
            output.write(ok);
            output.write(server);
            if (keepalive) output.write(conkeep);
            else output.write(conclose);
            output.write(ctype);
            output.write(clength);
            output.write(Integer.toString(result.length).getBytes());
            output.write(doubleNewline);
            output.write(result);
            output.flush();
          } else {
            output.write(httpversion.getBytes());
            output.write(" 400 Bad Request\r\n".getBytes());
            output.write("Server: helma.XML-RPC\r\n\r\n".getBytes());
            output.write(("Method " + method + " not implemented (try POST)").getBytes());
            output.flush();
            keepalive = false;
          }
        } while (keepalive);
      } catch (Exception exception) {
        if (XmlRpc.debug) {
          System.err.println(exception);
          exception.printStackTrace();
        }
      } finally {
        try {
          socket.close();
        } catch (IOException ignore) {
        }
      }
    }
  private void readData() {
    if (couldNotFetch) return;

    String test = VoxelUpdate.url;
    test = test.toLowerCase();

    if (!test.endsWith(".xml")) {
      return;
    }

    try {
      File xml = new File("plugins/VoxelUpdate/temp.xml");

      if (!xml.exists()) {
        xml.createNewFile();
      }

      BufferedInputStream bi = new BufferedInputStream(new URL(VoxelUpdate.url).openStream());
      FileOutputStream fo = new FileOutputStream(xml);
      BufferedOutputStream bo = new BufferedOutputStream(fo, 1024);
      byte[] b = new byte[1024];
      int i = 0;

      while ((i = bi.read(b, 0, 1024)) >= 0) {
        bo.write(b, 0, i);
      }

      bo.close();
      bi.close();

      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(xml);
      doc.getDocumentElement().normalize();

      Element base = doc.getDocumentElement();
      NodeList pluginList = doc.getElementsByTagName("plugin");
      xml.delete();

      for (i = 0; i < pluginList.getLength(); i++) {
        Node n = pluginList.item(i);
        String name = null;
        HashMap<String, String> _map = new HashMap<String, String>();

        if (n.getNodeType() == Node.ELEMENT_NODE) {
          Element e = (Element) n;
          String version = "";
          String url = "";
          String authors = "";
          String description = "";

          try {

            if (getTagValue("name", e) != null) {
              name = getTagValue("name", e);
            } else {
              return;
            }
            if (getTagValue("version", e) != null) {
              version = getTagValue("version", e);
            }
            if (getTagValue("url", e) != null) {
              url = getTagValue("url", e);
            }
            if (getTagValue("authors", e) != null) {
              authors = getTagValue("authors", e);
            }
            if (getTagValue("description", e) != null) {
              description = getTagValue("description", e);
            }

          } catch (NullPointerException ex) {
            continue;
          }

          if (!"".equals(version)) {
            _map.put("version", version);
          }
          if (!"".equals(url)) {
            _map.put("url", url);
          }
          if (!"".equals(authors)) {
            _map.put("authors", authors);
          }
          if (!"".equals(description)) {
            _map.put("description", description);
          }

          map.put(name, _map);
        }
      }

      lastDataFetch = System.currentTimeMillis();

    } catch (MalformedURLException e) {
      VoxelUpdate.log.severe("[VoxelUpdate] Incorrectly formatted URL to data file in preferences");
    } catch (IOException e) {
      VoxelUpdate.log.severe("[VoxelUpdate] Could not assign data to BIS");
      VoxelUpdate.log.warning(
          "[VoxelUpdate] Probably because the link is broken or the server host is down");
      VoxelUpdate.log.warning(
          "[VoxelUpdate] Also, check the properties file... It might be empty. If so, grab the default configuration (from TVB's wiki) after you stop your server, paste it into the .properties, and restart");
      VoxelUpdate.log.warning("[VoxelUpdate] ... Turning off data search until a reload...");
      couldNotFetch = true;
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    }
  }
  public boolean doDownload(String plugin) {
    boolean downloaded = false;

    try {
      File dl = new File("plugins/VoxelUpdate/Downloads/" + plugin + ".jar");

      if (!dl.getParentFile().isDirectory()) {
        dl.getParentFile().mkdirs();
      }

      if (!dl.exists()) {
        dl.createNewFile();
      }

      if (get(plugin, "url") == null) {
        return false;
      }

      BufferedInputStream bi = new BufferedInputStream(new URL(get(plugin, "url")).openStream());
      FileOutputStream fo = new FileOutputStream(dl);
      BufferedOutputStream bo = new BufferedOutputStream(fo, 1024);

      byte[] b = new byte[1024];
      int i = 0;

      while ((i = bi.read(b, 0, 1024)) >= 0) {
        bo.write(b, 0, i);
      }

      bo.close();
      bi.close();

      if (VoxelUpdate.autoUpdate) {
        File dupe = new File("plugins/" + dl.getName());

        FileChannel ic = new FileInputStream(dl).getChannel();
        FileChannel oc = new FileOutputStream(dupe).getChannel();
        ic.transferTo(0, ic.size(), oc);
        ic.close();
        oc.close();

        VoxelUpdate.s
            .getPluginManager()
            .disablePlugin(VoxelUpdate.s.getPluginManager().getPlugin(plugin));

        try {
          VoxelUpdate.s
              .getPluginManager()
              .enablePlugin(VoxelUpdate.s.getPluginManager().loadPlugin(dl));
        } catch (Exception e) {
          VoxelUpdate.log.severe("[VoxelUpdate] Could not reload plugin \"" + plugin + "\"");
        }
      }

      downloaded = true;
    } catch (MalformedURLException e) {
      VoxelUpdate.log.severe(
          "[VoxelUpdate] Incorrectly formatted URL for download of \"" + plugin + "\"");
      return downloaded;
    } catch (FileNotFoundException e) {
      VoxelUpdate.log.severe("[VoxelUpdate] Could not save data to VoxelUpdate/Downloads");
      e.printStackTrace();
      return downloaded;
    } catch (IOException e) {
      VoxelUpdate.log.severe("[VoxelUpdate] Could not assign data to BIS");
      e.printStackTrace();
      return downloaded;
    }

    return downloaded;
  }