Example #1
1
  /**
   * Loads the drawing. By convention this method is invoked on a worker thread.
   *
   * @param progress A ProgressIndicator to inform the user about the progress of the operation.
   * @return The Drawing that was loaded.
   */
  protected Drawing loadDrawing(ProgressIndicator progress) throws IOException {
    Drawing drawing = createDrawing();
    if (getParameter("datafile") != null) {
      URL url = new URL(getDocumentBase(), getParameter("datafile"));
      URLConnection uc = url.openConnection();

      // Disable caching. This ensures that we always request the
      // newest version of the drawing from the server.
      // (Note: The server still needs to set the proper HTTP caching
      // properties to prevent proxies from caching the drawing).
      if (uc instanceof HttpURLConnection) {
        ((HttpURLConnection) uc).setUseCaches(false);
      }

      // Read the data into a buffer
      int contentLength = uc.getContentLength();
      InputStream in = uc.getInputStream();
      try {
        if (contentLength != -1) {
          in = new BoundedRangeInputStream(in);
          ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
          progress.setProgressModel((BoundedRangeModel) in);
          progress.setIndeterminate(false);
        }
        BufferedInputStream bin = new BufferedInputStream(in);
        bin.mark(512);

        // Read the data using all supported input formats
        // until we succeed
        IOException formatException = null;
        for (InputFormat format : drawing.getInputFormats()) {
          try {
            bin.reset();
          } catch (IOException e) {
            uc = url.openConnection();
            in = uc.getInputStream();
            in = new BoundedRangeInputStream(in);
            ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
            progress.setProgressModel((BoundedRangeModel) in);
            bin = new BufferedInputStream(in);
            bin.mark(512);
          }
          try {
            bin.reset();
            format.read(bin, drawing, true);
            formatException = null;
            break;
          } catch (IOException e) {
            formatException = e;
          }
        }
        if (formatException != null) {
          throw formatException;
        }
      } finally {
        in.close();
      }
    }
    return drawing;
  }
Example #2
1
 /**
  * Starts a native process on the server
  *
  * @param command the command to start the process
  * @param dir the dir in which the process starts
  */
 static String startProcess(String command, String dir) throws IOException {
   StringBuffer ret = new StringBuffer();
   String[] comm = new String[3];
   comm[0] = COMMAND_INTERPRETER[0];
   comm[1] = COMMAND_INTERPRETER[1];
   comm[2] = command;
   long start = System.currentTimeMillis();
   try {
     // Start process
     Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir));
     // Get input and error streams
     BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream());
     BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream());
     boolean end = false;
     while (!end) {
       int c = 0;
       while ((ls_err.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_err.read()));
       }
       c = 0;
       while ((ls_in.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_in.read()));
       }
       try {
         ls_proc.exitValue();
         // if the process has not finished, an exception is thrown
         // else
         while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read()));
         while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read()));
         end = true;
       } catch (IllegalThreadStateException ex) {
         // Process is running
       }
       // The process is not allowed to run longer than given time.
       if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) {
         ls_proc.destroy();
         end = true;
         ret.append("!!!! Process has timed out, destroyed !!!!!");
       }
       try {
         Thread.sleep(50);
       } catch (InterruptedException ie) {
       }
     }
   } catch (IOException e) {
     ret.append("Error: " + e);
   }
   return ret.toString();
 }
Example #3
0
 public Properties loadUpdateProperties() {
   File propertiesDirectory;
   Properties updateProperties = new Properties();
   // First we look at local configuration directory
   propertiesDirectory = new File(System.getProperty("user.home"), PROPERTIES_DIRECTORY_NAME);
   if (!propertiesDirectory.exists()) {
     // Second we look at tangara binary path
     propertiesDirectory = getTangaraPath().getParentFile();
   }
   BufferedInputStream input = null;
   try {
     input =
         new BufferedInputStream(
             new FileInputStream(
                 new File(propertiesDirectory, getProperty("checkUpdate.fileName"))));
     updateProperties.load(input);
     input.close();
     return updateProperties;
   } catch (IOException e) {
     LOG.warn("Error trying to load update properties");
   } finally {
     IOUtils.closeQuietly(input);
   }
   return null;
 }
Example #4
0
  // Send File
  public void sendFile(String chunkName) throws IOException {
    OutputStream os = null;
    String currentDir = System.getProperty("user.dir");
    chunkName = currentDir + "/src/srcFile/" + chunkName;
    File myFile = new File(chunkName);

    byte[] arrby = new byte[(int) myFile.length()];

    try {
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(arrby, 0, arrby.length);

      os = csocket.getOutputStream();
      System.out.println("Sending File.");
      os.write(arrby, 0, arrby.length);
      os.flush();
      System.out.println("File Sent.");
      //			os.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //			os.close();
    }
  }
Example #5
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;
  }
  /** @throws IOException If failed. */
  private void initFavicon() throws IOException {
    assert favicon == null;

    InputStream in = getClass().getResourceAsStream("favicon.ico");

    if (in != null) {
      BufferedInputStream bis = new BufferedInputStream(in);

      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      try {
        byte[] buf = new byte[2048];

        while (true) {
          int n = bis.read(buf);

          if (n == -1) break;

          bos.write(buf, 0, n);
        }

        favicon = bos.toByteArray();
      } finally {
        U.closeQuiet(bis);
      }
    }
  }
  private Icon makeIcon(final String gifFile) throws IOException {
    /* Copy resource into a byte array.  This is
     * necessary because several browsers consider
     * Class.getResource a security risk because it
     * can be used to load additional classes.
     * Class.getResourceAsStream just returns raw
     * bytes, which we can convert to an image.
     */
    InputStream resource = MyImageView.class.getResourceAsStream(gifFile);

    if (resource == null) {
      System.err.println(MyImageView.class.getName() + "/" + gifFile + " not found!!.");
      return null;
    }
    BufferedInputStream in = new BufferedInputStream(resource);
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    byte[] buffer = new byte[1024];
    int n;
    while ((n = in.read(buffer)) > 0) {
      out.write(buffer, 0, n);
    }
    in.close();
    out.flush();

    buffer = out.toByteArray();
    if (buffer.length == 0) {
      System.err.println("warning: " + gifFile + " is zero-length");
      return null;
    }
    return new ImageIcon(buffer);
  }
 /**
  * Load UTF8withBOM or any ansi text file.
  *
  * @param filename
  * @return
  * @throws java.io.IOException
  */
 public static String loadFileAsString(String filename) throws java.io.IOException {
   final int BUFLEN = 1024;
   BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
     byte[] bytes = new byte[BUFLEN];
     boolean isUTF8 = false;
     int read, count = 0;
     while ((read = is.read(bytes)) != -1) {
       if (count == 0
           && bytes[0] == (byte) 0xEF
           && bytes[1] == (byte) 0xBB
           && bytes[2] == (byte) 0xBF) {
         isUTF8 = true;
         baos.write(bytes, 3, read - 3); // drop UTF8 bom marker
       } else {
         baos.write(bytes, 0, read);
       }
       count += read;
     }
     return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
   } finally {
     try {
       is.close();
     } catch (Exception ex) {
     }
   }
 }
Example #9
0
  /**
   * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件
   *
   * @param task
   * @return "ok" if download success (else return errmessage);
   */
  static String download(DownloadTask task) {
    if (!openedStatus && show) openStatus();

    URL url;
    HttpURLConnection conn;
    try {
      url = new URL(task.getOrigin());
      conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/"
              + Math.random());
      if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求
        conn.setRequestProperty(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
        // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229;
        // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800");
        conn.setRequestProperty(
            "Cookie",
            "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800");
        conn.setRequestProperty("Host", "www.imgjav.com");
      }
      Path directory = Paths.get(task.getDest()).getParent();
      if (!Files.exists(directory)) Files.createDirectories(directory);
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    try (InputStream is = conn.getInputStream();
        BufferedInputStream in = new BufferedInputStream(is);
        FileOutputStream fos = new FileOutputStream(task.getDest());
        OutputStream out = new BufferedOutputStream(fos); ) {
      int length = conn.getContentLength();
      if (length < 1) throw new IOException("length<1");
      byte[] binary = new byte[length];
      byte[] buff = new byte[65536];
      int len;
      int index = 0;
      while ((len = in.read(buff)) != -1) {
        System.arraycopy(buff, 0, binary, index, len);
        index += len;
        allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了
        task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%");
      }
      out.write(binary);
    } catch (IOException e) {
      e.printStackTrace();
      return e.getMessage();
    }
    return "ok";
  }
Example #10
0
  public void run() {
    URL url;
    Base64Encoder base64 = new Base64Encoder();

    try {
      url = new URL(urlString);
    } catch (MalformedURLException e) {
      System.err.println("Invalid URL");
      return;
    }

    try {
      conn = (HttpURLConnection) url.openConnection();
      conn.setRequestProperty("Authorization", "Basic " + base64.encode(user + ":" + pass));
      httpIn = new BufferedInputStream(conn.getInputStream(), 8192);
    } catch (IOException e) {
      System.err.println("Unable to connect: " + e.getMessage());
      return;
    }

    int prev = 0;
    int cur = 0;

    try {
      while (keepAlive && (cur = httpIn.read()) >= 0) {
        if (prev == 0xFF && cur == 0xD8) {
          jpgOut = new ByteArrayOutputStream(8192);
          jpgOut.write((byte) prev);
        }
        if (jpgOut != null) {
          jpgOut.write((byte) cur);
        }
        if (prev == 0xFF && cur == 0xD9) {
          synchronized (curFrame) {
            curFrame = jpgOut.toByteArray();
          }
          frameAvailable = true;
          jpgOut.close();
        }
        prev = cur;
      }
    } catch (IOException e) {
      System.err.println("I/O Error: " + e.getMessage());
    }
    try {
      jpgOut.close();
      httpIn.close();
    } catch (IOException e) {
      System.err.println("Error closing streams: " + e.getMessage());
    }
    conn.disconnect();
  }
Example #11
0
 /**
  * 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);
 }
Example #12
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();
  }
Example #13
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;
 }
Example #14
0
  private String readLine4Big() throws Exception {
    byte[] b = new byte[1024 * 256];

    int i = 0;
    int readLen = 0;
    while ((readLen = bis.read(b, 0, 1024 * 256)) != -1) {

      if (readLen == 1) {
        if (b[0] == 10) {
          break;
        } else if (b[0] != 13) {
          this.bos.write(b, 0, readLen);
        }
      } else if (b[readLen - 2] != 13 && b[readLen - 1] != 10) {
        this.bos.write(b, 0, readLen);
      } else if (b[readLen - 1] == 10) {
        if (b[readLen - 2] == 13) {
          this.bos.write(b, 0, (readLen - 2));
        } else {
          this.bos.write(b, 0, (readLen - 1));
        }
        break;
      }
    }

    String ret = this.bos.toString();
    this.bos.reset();
    return ret;
  }
Example #15
0
  /**
   * Reads color table as 256 RGB integer values
   *
   * @param ncolors int number of colors to read
   * @return int array containing 256 colors (packed ARGB with full alpha)
   */
  protected int[] readColorTable(int ncolors) {
    int nbytes = 3 * ncolors;
    int[] tab = null;
    byte[] c = new byte[nbytes];
    int n = 0;
    try {
      n = in.read(c);
    } catch (IOException e) {
    }
    if (n < nbytes) {
      status = STATUS_FORMAT_ERROR;
    } else {
      tab = new int[256]; // max size to avoid bounds checks

      int i = 0;
      int j = 0;
      while (i < ncolors) {
        int r = ((int) c[j++]) & 0xff;
        int g = ((int) c[j++]) & 0xff;
        int b = ((int) c[j++]) & 0xff;
        tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
      }
    }
    return tab;
  }
Example #16
0
  public int read(byte[] buf) throws Exception {

    for (int i = 0; i < buf.length; i++) {
      bis.read(buf, i, 1);
    }

    return buf.length;
  }
Example #17
0
 /** Reads a single byte from the input stream. */
 protected int read() {
   int curByte = 0;
   try {
     curByte = in.read();
   } catch (IOException e) {
     status = STATUS_FORMAT_ERROR;
   }
   return curByte;
 }
Example #18
0
  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();
        }
      }
    }
  }
  private byte[] readFileForResponse(HtmlRequest htmlRequest) throws IOException {

    if (htmlRequest.requestedFile.equals("/")
        || htmlRequest.requestedFile.equals("/" + defaultPage.getName())) {
      fullPathForFile = rootDirectory.getCanonicalPath() + "\\" + defaultPage.getName();
      return prepareDefaultPage(null);
    } else {
      fullPathForFile = rootDirectory.getCanonicalPath() + htmlRequest.requestedFile;
    }

    File file = new File(fullPathForFile);
    byte[] buffer = new byte[(int) file.length()];
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    bis.read(buffer, 0, buffer.length);
    bis.close();

    return buffer;
  }
Example #20
0
  public Image getImage(String sImage) {
    Image imReturn = null;
    try {
      if (jar == null) {
        imReturn = this.toolkit.createImage(this.getClass().getClassLoader().getResource(sImage));
      } else {
        //
        BufferedInputStream bis = new BufferedInputStream(jar.getInputStream(jar.getEntry(sImage)));
        ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096);
        int b;
        while ((b = bis.read()) != -1) {
          buffer.write(b);
        }
        byte[] imageBuffer = buffer.toByteArray();
        imReturn = this.toolkit.createImage(imageBuffer);
        bis.close();
        buffer.close();
      }
    } catch (IOException ex) {

    }
    return imReturn;
  }
Example #21
0
 private String readLine() throws IOException {
   if (buffer == null) {
     buffer = new byte[512];
   }
   int next;
   int count = 0;
   for (; ; ) {
     next = input.read();
     if (next < 0 || next == '\n') break;
     if (next != '\r') {
       buffer[count++] = (byte) next;
     }
     if (count >= 512) throw new IOException("HTTP Header too long");
   }
   return new String(buffer, 0, count);
 }
Example #22
0
  private String readLine4Small() throws Exception {
    this.b[0] = (byte) 0;

    int i = 0;
    while (bis.read(this.b, 0, 1) != -1) {

      if (this.b[0] != 13 && this.b[0] != 10) {
        this.bos.write(this.b, 0, 1);
      } else if (this.b[0] == 10) {
        break;
      }
    }

    String ret = this.bos.toString();
    this.bos.reset();
    return ret;
  }
Example #23
0
  /**
   * Reads next variable length block from input.
   *
   * @return number of bytes stored in "buffer"
   */
  protected int readBlock() {
    blockSize = read();
    int n = 0;
    if (blockSize > 0) {
      try {
        int count = 0;
        while (n < blockSize) {
          count = in.read(block, n, blockSize - n);
          if (count == -1) break;
          n += count;
        }
      } catch (IOException e) {
      }

      if (n < blockSize) {
        status = STATUS_FORMAT_ERROR;
      }
    }
    return n;
  }
Example #24
0
 /**
  * Reads GIF image from stream
  *
  * @param BufferedInputStream containing GIF file.
  * @return read status code (0 = no errors)
  */
 public int read(BufferedInputStream is) {
   init();
   if (is != null) {
     in = is;
     readHeader();
     if (!err()) {
       readContents();
       if (frameCount < 0) {
         status = STATUS_FORMAT_ERROR;
       }
     }
   } else {
     status = STATUS_OPEN_ERROR;
   }
   try {
     is.close();
   } catch (IOException e) {
   }
   return status;
 }
Example #25
0
  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;
  }
Example #26
0
  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 void run() {
    try {
      Random rd = new Random();
      int clientChallenge = rd.nextInt();
      if (m_remoteSocket != null) {

        String msg = "initusername:"******"\n challenge:" + clientChallenge;
        System.out.println(
            "Client init the connection to server ...\n"
                + "	send challenge to server, challenge = "
                + clientChallenge);
        this.sendMessage(msg);
      }

      // match challenge
      byte[] buffer = new byte[40960];

      Pattern userPwdPattern =
          // Pattern.compile("password:(\\S+)\\s+command:(\\S+)\\sCN:(\\S*)\\s");
          Pattern.compile("challenge:(\\S+)verification:(\\S+)\\s");

      BufferedInputStream in =
          new BufferedInputStream(m_remoteSocket.getInputStream(), buffer.length);

      // Read a buffer full.
      int bytesRead = in.read(buffer);

      String line = bytesRead > 0 ? new String(buffer, 0, bytesRead) : "";

      Matcher userPwdMatcher = userPwdPattern.matcher(line);

      // parse username and pwd
      if (userPwdMatcher.find()) {

        String serverchallenge = userPwdMatcher.group(1);
        Integer verification = Integer.parseInt(userPwdMatcher.group(2));

        System.out.println(
            "Client got challenge and verification from server: "
                + clientChallenge
                + ", verificaiton: "
                + verification
                + "\n");

        Integer clientVerification =
            sharedSecret(clientChallenge, Integer.parseInt(serverchallenge));
        if (!clientVerification.equals(verification)) {
          System.out.println("Server fail to be authenticated by client");
          return;
        } else {
          System.out.println("	Client authenticates server!");
        }
        if (m_remoteSocket != null) {
          // System.out.println("client sends pwd+challenge etc to server");

          String msg =
              "username:"******"\n"
                  + "password:"******"\n"
                  + "command:"
                  + command
                  + "\n"
                  + "CN:"
                  + commonName
                  + "\n"
                  + "verification:"
                  + verification;
          this.sendMessage(msg);
          if (command.equals("shutdown")) System.exit(1);
        }
      }

      // now read back any response
      // Read a buffer full.
      bytesRead = in.read(buffer);

      line = bytesRead > 0 ? new String(buffer, 0, bytesRead) : "";

      System.out.println("");
      System.out.println("Receiving input from MITM proxy:");
      System.out.println("");

      BufferedReader r = new BufferedReader(new InputStreamReader(m_remoteSocket.getInputStream()));
      // String line = null;
      while ((line = r.readLine()) != null) {
        // while (line != null) {
        System.out.println(line);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.err.println("Admin Client exited");
    System.exit(0);
  }
Example #28
0
 public static void saveURL(URL url, Writer writer) throws IOException {
   BufferedInputStream in = new BufferedInputStream(url.openStream());
   for (int c = in.read(); c != -1; c = in.read()) {
     writer.write(c);
   }
 }
Example #29
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());
    }
  }