Example #1
0
  // Download file.
  @Override
  public void executeTask() throws Throwable {
    for (PreviousResult<String> p : al) this.url = IOUtils.parseURL(p.getResult());

    for (int repeat = 0; repeat < 6; repeat++) {
      if (repeat > 0)
        if (failedCallbackReturnsNewURL != null) {
          URL tmp = IOUtils.parseURL(failedCallbackReturnsNewURL.apply(repeat));
          if (tmp != null) {
            url = tmp;
            HMCLog.warn("Switch to: " + url);
          }
        }
      HMCLog.log("Downloading: " + url + ", to: " + filePath);
      if (!shouldContinue) break;
      try {
        if (ppl != null) ppl.setProgress(this, -1, 1);

        // Open connection to URL.
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setConnectTimeout(5000);
        connection.setRequestProperty("User-Agent", "Hello Minecraft!");

        // Connect to server.
        connection.connect();

        // Make sure response code is in the 200 range.
        if (connection.getResponseCode() / 100 != 2)
          throw new NetException(C.i18n("download.not_200") + " " + connection.getResponseCode());

        // Check for valid content length.
        int contentLength = connection.getContentLength();
        if (contentLength < 1) throw new NetException("The content length is invalid.");

        filePath.getParentFile().mkdirs();

        File tempFile = new File(filePath.getAbsolutePath() + ".hmd");
        if (!tempFile.exists()) tempFile.createNewFile();
        else if (!tempFile.renameTo(tempFile)) // check file lock
        throw new RuntimeException(
              "The temp file is locked, maybe there is an application using the file?");

        // Open file and seek to the end of it.
        file = new RandomAccessFile(tempFile, "rw");

        MessageDigest digest = DigestUtils.getSha1Digest();

        stream = connection.getInputStream();
        int lastDownloaded = 0;
        downloaded = 0;
        long lastTime = System.currentTimeMillis();
        while (true) {
          // Size buffer according to how much of the file is left to download.
          if (!shouldContinue) {
            closeFiles();
            filePath.delete();
            break;
          }

          byte buffer[] = new byte[MAX_BUFFER_SIZE];

          // Read from server into buffer.
          int read = stream.read(buffer);
          if (read == -1) break;

          digest.update(buffer, 0, read);

          // Write buffer to file.
          file.write(buffer, 0, read);
          downloaded += read;

          long now = System.currentTimeMillis();
          if (ppl != null && (now - lastTime) >= 1000) {
            ppl.setProgress(this, downloaded, contentLength);
            ppl.setStatus(this, (downloaded - lastDownloaded) / 1024 + "KB/s");
            lastDownloaded = downloaded;
            lastTime = now;
          }
        }
        closeFiles();
        if (aborted) tempFile.delete();
        else {
          if (filePath.exists()) filePath.delete();
          tempFile.renameTo(filePath);
        }
        if (!shouldContinue) break;
        if (downloaded != contentLength)
          throw new IllegalStateException(
              "Unexptected file size: " + downloaded + ", expected: " + contentLength);
        String hashCode =
            String.format("%1$040x", new Object[] {new BigInteger(1, digest.digest())});
        if (expectedHash != null && !expectedHash.equals(hashCode))
          throw new IllegalStateException(
              "Unexpected hash code: " + hashCode + ", expected: " + expectedHash);

        if (ppl != null) ppl.onProgressProviderDone(this);
        return;
      } catch (Exception e) {
        setFailReason(new NetException(C.i18n("download.failed") + " " + url, e));
      } finally {
        closeFiles();
      }
    }
    if (failReason != null) throw failReason;
  }
Example #2
0
  @SuppressWarnings({"CallToPrintStackTrace", "UseSpecificCatch"})
  public static void main(String[] args) throws IOException {
    {
      PluginManager.getPlugin(DefaultPlugin.class);
      if (IUpgrader.NOW_UPGRADER.parseArguments(getVersionNumber(), args)) return;

      System.setProperty("awt.useSystemAAFontSettings", "on");
      System.setProperty("swing.aatext", "true");
      System.setProperty("sun.java2d.noddraw", "true");
      System.setProperty("sun.java2d.dpiaware", "false");
      Thread.setDefaultUncaughtExceptionHandler(new CrashReporter(true));

      try {
        File file = new File("hmcl.log");
        if (!file.exists() && !file.createNewFile())
          HMCLog.warn("Failed to create log file " + file);
        Configuration.DEFAULT.appenders.add(
            new ConsoleAppender(
                "File", new DefaultLayout(), true, new FileOutputStream(file), true));
      } catch (IOException ex) {
        LOGGER.log(
            Level.SEVERE,
            "Failed to add log appender File because an error occurred while creating or opening hmcl.log",
            ex);
      }

      HMCLog.log("*** " + Main.makeTitle() + " ***");

      String s = Settings.getInstance().getLocalization();
      for (SupportedLocales sl : SupportedLocales.values())
        if (sl.name().equals(s)) {
          SupportedLocales.NOW_LOCALE = sl;
          Locale.setDefault(sl.self);
        }

      LogWindow.INSTANCE.clean();
      LogWindow.INSTANCE.setTerminateGame(GameLauncher.PROCESS_MANAGER::stopAllProcesses);

      try {
        LOOK_AND_FEEL = new HelloMinecraftLookAndFeel(Settings.getInstance().getTheme().settings);
        UIManager.setLookAndFeel(LOOK_AND_FEEL);
      } catch (ParseException | UnsupportedLookAndFeelException ex) {
        HMCLog.warn("Failed to set look and feel...", ex);
      }

      Settings.UPDATE_CHECKER.outdated.register(IUpgrader.NOW_UPGRADER);
      Settings.UPDATE_CHECKER.process(false).reg(t -> Main.invokeUpdate()).execute();

      if (StrUtils.isNotBlank(Settings.getInstance().getProxyHost())
          && StrUtils.isNotBlank(Settings.getInstance().getProxyPort())
          && MathUtils.canParseInt(Settings.getInstance().getProxyPort())) {
        HMCLog.log("Initializing customized proxy");
        System.setProperty("http.proxyHost", Settings.getInstance().getProxyHost());
        System.setProperty("http.proxyPort", Settings.getInstance().getProxyPort());
        if (StrUtils.isNotBlank(Settings.getInstance().getProxyUserName())
            && StrUtils.isNotBlank(Settings.getInstance().getProxyPassword()))
          Authenticator.setDefault(
              new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(
                      Settings.getInstance().getProxyUserName(),
                      Settings.getInstance().getProxyPassword().toCharArray());
                }
              });
      }

      try {
        PluginManager.plugin().showUI();
      } catch (Throwable t) {
        new CrashReporter(false).uncaughtException(Thread.currentThread(), t);
        System.exit(1);
      }
    }
  }