Example #1
0
 @Override
 public boolean call(Object sender, Integer t) {
   if (t == 0) {
     sendStatus("*** 服务端已停止 ***");
     System.out.println("Server stopped successfully");
   } else {
     sendStatus("*** 服务端崩溃了!(错误码:" + t + ") ***");
     System.err.println("Server crashed(exit code: " + t + ")");
   }
   isRunning = false;
   for (Schedule schedule : schedules)
     if (schedule.timeType == Schedule.TIME_TYPE_SERVER_STOPPED)
       ScheduleTranslator.translate(this, schedule).run();
   if (timer != null) timer.cancel();
   if (pastTimer != null) pastTimer.stop();
   restoreMods();
   if (isRestart) {
     try {
       run();
     } catch (IOException ex) {
       MessageBox.Show("重启失败!");
       HMCLog.warn("Failed to launch!", ex);
     }
     isRestart = false;
   }
   return true;
 }
Example #2
0
 @Override
 public void onStatus(String status) {
   System.out.println(status);
   if (isGettingPlayerNumber == 1) {
     Pattern p = Pattern.compile("There are [0-9]*/[0-9]* players online");
     Matcher m = p.matcher(status);
     if (!m.find()) return;
     String s = m.group(0);
     s = s.substring(10, s.length() - 15);
     playerNumber = s;
     isGettingPlayerNumber = 2;
     return;
   } else if (isGettingPlayerNumber == 2) {
     try {
       status = status.substring(status.lastIndexOf("]") + 1);
       status = status.substring(status.indexOf(":") + 1);
     } catch (Exception e) {
       HMCLog.warn("Failed to substring status.", e);
     }
     String[] s;
     if (StrUtils.isNotBlank(status)) s = status.trim().split(", ");
     else s = new String[0];
     Pair<String, String[]> p = new Pair<>(playerNumber, s);
     isGettingPlayerNumber = 0;
     gettingPlayerNumber.accept(p);
     return;
   }
   if (isDone == false) {
     Pattern p =
         Pattern.compile(
             "\\[INFO\\] Done \\([0-9]*\\.[0-9]*s\\)! For help, type \"help\" or \"\\?\"");
     Matcher m = p.matcher(status);
     if (m.find()) {
       stoppedEvent.execute(null);
       timer = new Timer();
       timerTasks.clear();
       for (int i = 0; i < schedules.size(); i++) {
         if (schedules.get(i).timeType == Schedule.TIME_TYPE_SERVER_STARTED) {
           ScheduleTranslator.translate(this, schedules.get(i)).run();
           continue;
         }
         if (schedules.get(i).timeType != Schedule.TIME_TYPE_PER) continue;
         long mill = (long) Math.floor(schedules.get(i).per * 60 * 1000);
         timerTasks.add(ScheduleTranslator.translate(this, schedules.get(i)));
         timer.schedule(timerTasks.get(i), mill, mill);
       }
       pastTimer = new javax.swing.Timer(1000, this);
       pastTimer.start();
       System.out.println("Server started!");
       sendStatus("*** 服务端已启动完成 ***");
       isDone = true;
     }
   }
   if (status.length() > 20)
     if (status.substring(20).contains("[SEVERE] This crash report has been saved to: "))
       for (Schedule schedule : schedules)
         if (schedule.timeType == Schedule.TIME_TYPE_SERVER_CRASHED)
           ScheduleTranslator.translate(this, schedule).run();
 }
Example #3
0
 public static ImageIcon getIcon(String path) {
   try {
     return new ImageIcon(
         Main.class.getResource("/org/jackhuang/hellominecraft/launcher/" + path));
   } catch (Exception e) {
     HMCLog.err("Failed to load icon", e);
     return null;
   }
 }
Example #4
0
  private void closeFiles() {
    // Close file.
    if (file != null)
      try {
        file.close();
        file = null;
      } catch (IOException e) {
        HMCLog.warn("Failed to close file", e);
      }

    // Close connection to server.
    if (stream != null)
      try {
        stream.close();
        stream = null;
      } catch (IOException e) {
        HMCLog.warn("Failed to close stream", e);
      }
  }
Example #5
0
  private Localization(Locale locale) {
    InputStream is =
        Localization.class.getResourceAsStream(
            String.format(ROOT_LOCATION, "_" + locale.getLanguage() + "_" + locale.getCountry()));
    if (is == null)
      is =
          Localization.class.getResourceAsStream(
              String.format(ROOT_LOCATION, "_" + locale.getLanguage()));
    if (is == null) is = Localization.class.getResourceAsStream(String.format(ROOT_LOCATION, ""));
    if (is == null) throw new RuntimeException("LANG FILE MISSING");

    this.lang = new HashMap<>();
    try {
      String[] strings = IOUtils.readFully(is).toString().split("\n");
      for (String s : strings)
        if (!s.isEmpty() && s.charAt(0) != 35) {
          int i = s.indexOf("=");
          if (i == -1) continue;
          lang.put(s.substring(0, i), s.substring(i + 1));
        }
    } catch (IOException ex) {
      HMCLog.err("LANG FILE MISSING", ex);
    }
  }
Example #6
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 #7
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);
      }
    }
  }