3
0

Deprecate installer & use KBootstrap for updating

This commit is contained in:
Prototik 2015-06-16 23:30:52 +07:00
parent 44020ecc25
commit 01acbd4779
10 changed files with 298 additions and 208 deletions

View File

@ -20,6 +20,11 @@ buildscript {
}
}
repositories {
maven { url 'https://prok.pw/repo' }
jcenter()
}
tasks.whenTaskAdded {
if (it.name.startsWith('publish')) it.dependsOn 'preparePublication'
}
@ -35,15 +40,6 @@ minecraft {
mainClass = 'cpw.mods.fml.relauncher.ServerLaunchWrapper'
tweakClass = 'cpw.mods.fml.common.launcher.FMLTweaker'
installerVersion = "1.4"
subprojects {
repositories {
mavenCentral()
maven {
name = "sonatype"
url = "https://oss.sonatype.org/content/repositories/snapshots/"
}
}
}
srgExtra "PK: org/bukkit/craftbukkit org/bukkit/craftbukkit/v1_7_R4"
}
@ -98,70 +94,148 @@ launch4j {
jreMinVersion = '1.6.0'
}
tasks.packageUniversal {
classifier = 'server'
manifest.attributes([
configurations {
compile.extendsFrom exported
libraries
bootstrap
}
dependencies {
bootstrap 'pw.prok:KBootstrap:0.0.9+'
libraries 'net.minecraft:launchwrapper:1.11'
libraries 'org.ow2.asm:asm-all:5.0.3'
libraries 'com.typesafe.akka:akka-actor_2.11:2.3.3'
libraries 'com.typesafe:config:1.2.1'
libraries 'org.scala-lang:scala-actors-migration_2.11:1.1.0'
libraries 'org.scala-lang:scala-compiler:2.11.1'
libraries 'org.scala-lang.plugins:scala-continuations-library_2.11:1.0.2'
libraries 'org.scala-lang.plugins:scala-continuations-plugin_2.11.1:1.0.2'
libraries 'org.scala-lang:scala-library:2.11.1'
libraries 'org.scala-lang:scala-parser-combinators_2.11:1.0.1'
libraries 'org.scala-lang:scala-reflect:2.11.1'
libraries 'org.scala-lang:scala-swing_2.11:1.0.1'
libraries 'org.scala-lang:scala-xml_2.11:1.0.2'
libraries 'net.sf.jopt-simple:jopt-simple:4.5'
libraries 'lzma:lzma:0.0.1'
libraries 'net.sf.jopt-simple:jopt-simple:4.5'
libraries 'org.yaml:snakeyaml:1.9'
libraries 'commons-lang:commons-lang:2.6'
libraries 'org.avaje:ebean:2.7.3'
libraries 'jline:jline:2.6'
libraries 'net.md-5:SpecialSource:1.7-SNAPSHOT'
libraries 'net.sourceforge.argo:argo:2.25'
libraries 'org.fusesource.jansi:jansi:1.8'
libraries 'com.googlecode.json-simple:json-simple:1.1'
libraries 'org.xerial:sqlite-jdbc:3.7.2'
libraries 'mysql:mysql-connector-java:5.1.14'
libraries 'javax.persistence:persistence-api:1.0.2'
libraries 'net.minecraft:server:1.7.10'
libraries 'pw.prok:KImagine:0.1.12@jar'
libraries 'org.apache.httpcomponents:httpclient:4.4.1'
}
packageUniversal {
from { configurations.exported.collect { it.isDirectory() ? it : zipTree(it) } }
}
def String repeat(String string, int times) {
StringBuilder builder = new StringBuilder(string.length() * times)
times.times { builder.append(string) }
builder as String
}
def generateClasspath(boolean legacy = false) {
def classpath = ''
configurations.libraries.resolvedConfiguration.resolvedArtifacts.collect { it.moduleVersion.id }.each {
def jar = "${it.group.replace('.', '/')}/${it.name}/${it.version}/${it.name}-${it.version}.jar"
classpath += " ${legacy ? 'libraries/' : repeat('../', (group as String).split('\\.').length + 2)}${jar}"
}
return classpath.trim()
}
def generateManifest(boolean legacy = false) {
[
'KCauldron-Git-Branch' : gitInfo('branch'),
'KCauldron-Git-Hash' : gitInfo('fullHash'),
'KCauldron-Version' : project.version,
'KCauldron-Channel' : project.name,
'KCauldron-Legacy' : legacy,
'Implementation-Vendor' : 'Prototik',
'Implementation-Title' : project.name,
'Implementation-Version': project.version,
'Forge-Version' : '10.13.3.1448',
'Specification-Vendor' : 'Bukkit Team',
'Specification-Title' : 'Bukkit',
'Specification-Version' : '1.7.10-R0.1-SNAPSHOT'
])
'Specification-Version' : '1.7.10-R0.1-SNAPSHOT',
'Forge-Version' : '10.13.3.1448',
'TweakClass' : 'cpw.mods.fml.common.launcher.FMLTweaker',
'Main-Class' : 'cpw.mods.fml.relauncher.ServerLaunchWrapper',
'Class-Path' : generateClasspath(legacy)
]
}
tasks.packageUniversal {
classifier = 'server'
setManifest {}
manifest.attributes(generateManifest(true))
}
task jar(type: Jar, dependsOn: packageUniversal) {
destinationDir file("${buildDir}/distributions")
from zipTree(tasks.packageUniversal.archivePath)
manifest.attributes(generateManifest())
}
tasks.createChangelog.onlyIf { false }
tasks.packageInstaller.onlyIf { false }
task packageChangelog(type: CreateChangelog) {
onlyIf { project.hasProperty('officialBuild') }
classifier = 'changelog'
extension = 'txt'
oldChangelogUrl = "https://prok.pw/repo/${project.group.replace('.','/')}/${project.name}/${buildInfo('version')}/${project.name}-${buildInfo('version')}-changelog.txt"
oldChangelogUrl = "https://prok.pw/repo/${project.group.replace('.', '/')}/${project.name}/${buildInfo('version')}/${project.name}-${buildInfo('version')}-changelog.txt"
hash = gitInfo('hash')
message = gitInfo('message')
version = project.version
}
task installBundle(type: InstallBundle, dependsOn: packageInstaller) {
installer packageInstaller.archivePath
task installBundle(type: InstallBundle, dependsOn: packageUniversal) {
serverJar tasks.jar.archivePath
bootstrapClasspath configurations.bootstrap
bootstrapMain 'pw.prok.bootstrap.Main'
}
task packageBundle(type: Zip, dependsOn: installBundle) {
onlyIf { project.hasProperty('officialBuild') }
classifier = 'bundle'
from packageInstaller
from packageUniversal
from fileTree(installBundle.installLocation, {
include 'libraries/**'
include 'minecraft_server.*.jar'
})
from fileTree(installBundle.installLocation)
}
task signJars(type: Sign, dependsOn: [packageUniversal, packageInstaller, packageChangelog, packageBundle]) {
sign packageInstaller
task signJars(type: Sign, dependsOn: [packageUniversal, packageChangelog, packageBundle, jar, 'generatePomFileForMavenPublication']) {
sign packageUniversal
sign packageChangelog
sign packageBundle
sign jar
}
task preparePublication(dependsOn: signJars) {}
task signPom(type: Sign, dependsOn: 'generatePomFileForMavenPublication') {
outputs.upToDateWhen { false }
sign file("${buildDir}/publications/maven/pom-default.xml")
}
task preparePublication(dependsOn: [signJars, signPom]) {}
def getSignatureFiles = {
def allFiles = project.tasks.signJars.signatureFiles.collect { it }
def signedServer = allFiles.find { it.name.contains('-server') }
def signedInstaller = allFiles.find { it.name.contains('-installer') }
def signedChangelog = allFiles.find { it.name.contains('-changelog') }
def signedBundle = allFiles.find { it.name.contains('-bundle') }
def signedJar = (allFiles - [signedServer, signedChangelog, signedBundle])[0]
return [
[archive: signedServer, classifier: 'server', extension: 'jar.asc'],
[archive: signedInstaller, classifier: 'installer', extension: 'jar.asc'],
[archive: signedChangelog, classifier: 'changelog', extension: 'txt.asc'],
[archive: signedBundle, classifier: 'bundle', extension: 'jar.asc']
[archive: signedBundle, classifier: 'bundle', extension: 'jar.asc'],
[archive: signedJar, classifier: null, extension: 'jar.asc']
]
}
@ -186,13 +260,17 @@ publishing {
}
}
artifact packageUniversal
artifact packageInstaller
artifact packageChangelog
artifact packageBundle
artifact jar
}
}
}
tasks.buildPackages {
dependsOn packageUniversal, packageChangelog, packageBundle, jar
}
tasks.generateProjectCauldron << {
def file = new File('eclipse/cauldron/build.gradle')
file.append('''
@ -202,27 +280,12 @@ repositories {
}
}
dependencies {
compile 'pw.prok:KImagine:0.1.12+@jar'
compile 'org.apache.httpcomponents:httpclient:4.4.1'
}
''')
}
configurations {
compile.extendsFrom exported
}
repositories {
maven {
url 'https://prok.pw/repo'
configurations.libraries.resolvedConfiguration.resolvedArtifacts.collect { it.moduleVersion.id }.each { module ->
if (['net.minecraft:server:', 'org.ow2.asm:asm-all'].findAll {(module as String).startsWith it}.size() > 0) {
return
}
}
dependencies {
exported 'pw.prok:KImagine:0.1.12+@jar'
exported 'org.apache.httpcomponents:httpclient:4.4.1'
}
packageUniversal {
from { configurations.exported.collect { it.isDirectory() ? it : zipTree(it) } }
file.append(" compile '${module}'\n")
}
file.append('}')
}

View File

@ -2,14 +2,26 @@ package kcauldron
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.incremental.IncrementalTaskInputs
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.tasks.*
class InstallBundle extends DefaultTask {
@InputFile
def File installer
def File serverJar
@InputFiles
def ConfigurableFileCollection bootstrapClasspath
@Input
def String bootstrapMain
InstallBundle() {
bootstrapClasspath = project.files()
}
def bootstrapClasspath(Object... args) {
bootstrapClasspath.from args
}
@OutputDirectory
def File getInstallLocation() {
@ -20,14 +32,40 @@ class InstallBundle extends DefaultTask {
def install() {
installLocation.deleteDir()
installLocation.mkdirs()
new File(installLocation, "README.txt").withWriter {
def String jarPath = 'bin/' << (project.group as String).replace('.', File.separator) << File.separator << project.name << File.separator << project.version << File.separator << project.name << '-' << project.version << '.jar'
it << '''KCauldron installation guide
# Understanding this bundle
You're reading this guide because you're using deprecated installation method
If you want use easier & safer method please read about KBootstrap at https://prok.pw/KBootstrap
# Installation and usage
1. Unpack this zip into server directory
2. Use following line to start the server:
java -jar '''
it << jarPath
it << '''
3. That's end, enjoy
# Why I should use KBootstrap?
1. Easiest server installation
2. Built-in libraries management
3. Update & run server in one line
4. Ability to not read this boring guide
5. What else?
If you are not yet convinced and want to use bundles instead KBootstrap... Meh, this is your choice.
'''
}
def cp = bootstrapClasspath
for (int i = 0; i < 3; i++) {
def result = project.javaexec {
def result = project.javaexec { it ->
workingDir installLocation
classpath installer
main 'net.minecraftforge.installer.SimpleInstaller'
args '--installServer'
standardOutput new NopOutputStream()
errorOutput new NopOutputStream()
classpath cp
main bootstrapMain
args '--serverDir', installLocation.canonicalPath,
'--installServer', serverJar.canonicalFile
}
if (result.exitValue == 0) return
}

View File

@ -1,6 +1,6 @@
#Fri May 08 13:12:57 KRAT 2015
#Tue Jun 16 17:21:00 KRAT 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip

View File

@ -34,13 +34,17 @@ public class KCauldron {
sCurrentVersion = version;
sBranch = manifest.getProperty("KCauldron-Branch");
sChannel = manifest.getProperty("KCauldron-Channel");
break;
}
manifest.clear();
}
} catch (Exception e) {
e.printStackTrace();
}
String home = System.getenv("KCAULDRON_HOME");
if (home != null) {
sServerLocation = new File(home);
}
}
private static String sCurrentVersion;

View File

@ -62,8 +62,8 @@ public class KCauldronCommand extends Command {
if (!testPermission(sender, CHECK))
return true;
sender.sendMessage(ChatColor.GREEN + "Initiated version check...");
new KVersionRetriever(new CommandSenderUpdateCallback(sender),
false);
KVersionRetriever.startServer(new CommandSenderUpdateCallback(
sender), false);
} else if ("update".equals(action)) {
KCauldronUpdater.initUpdate(sender, args.length > 1 ? args[1]
: null);

View File

@ -13,18 +13,14 @@ public class KCauldronConfig extends ConfigBase {
true, "Enable KCauldron command");
public BoolSetting updatecheckerEnable = new BoolSetting(this,
"updatechecker.enable", true, "Enable KCauldron update checker");
public BoolSetting updatecheckerDeleteOld = new BoolSetting(this,
"updatechecker.deleteOld", true, "Delete old version after update");
public StringSetting updatecheckerSymlinks = new StringSetting(this,
"updatechecker.symlinks", "", "(Re)create symlinks after update");
"updatechecker.symlinks", "KCauldron.jar", "(Re)create symlinks after update");
public BoolSetting updatecheckerAutoinstall = new BoolSetting(this,
"updatechecker.autoinstall", false, "Install updates without confirming");
public BoolSetting updatecheckerAutorestart = new BoolSetting(this,
"updatechecker.autorestart", false, "Restart server after updating without confirming (set restart script in spigot.yml)");
public BoolSetting updatecheckerQuite = new BoolSetting(this,
"updatechecker.quite", false, "Print less info during update");
public StringSetting updatecheckerInstallAs = new StringSetting(this,
"updatechecker.installAs", "", "Install new version with specified name");
public BoolSetting loggingMaterialInjection = new BoolSetting(this,
"logging.materialInjection", false, "Log material injection event");
@ -33,12 +29,10 @@ public class KCauldronConfig extends ConfigBase {
super("kcauldron.yml", "kc");
register(commandEnable);
register(updatecheckerEnable);
register(updatecheckerDeleteOld);
register(updatecheckerSymlinks);
register(updatecheckerAutoinstall);
register(updatecheckerAutorestart);
register(updatecheckerQuite);
register(updatecheckerInstallAs);
register(loggingMaterialInjection);
load();
}

View File

@ -3,6 +3,7 @@ package kcauldron.updater;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import kcauldron.KCauldron;
import kcauldron.updater.KVersionRetriever.IVersionCheckCallback;
import org.bukkit.ChatColor;
@ -20,32 +21,33 @@ public class CommandSenderUpdateCallback implements IVersionCheckCallback {
}
@Override
public void upToDate(String version) {
public void upToDate() {
CommandSender sender = mSender.get();
if (sender != null) {
sender.sendMessage(ChatColor.GREEN
+ "Running version of KCauldron is up-to-date: " + version);
+ "Running version of KCauldron is up-to-date: "
+ KCauldron.getCurrentVersion());
}
DefaultUpdateCallback.INSTANCE.upToDate(version);
DefaultUpdateCallback.INSTANCE.upToDate();
}
@Override
public void newVersion(String currentVersion, String newVersion) {
public void newVersion(String newVersion) {
CommandSender sender = mSender.get();
if (sender != null) {
newVersion(sender, currentVersion, newVersion);
newVersion(sender, KCauldron.getCurrentVersion(), newVersion);
}
DefaultUpdateCallback.INSTANCE.newVersion(currentVersion, newVersion);
DefaultUpdateCallback.INSTANCE.newVersion(newVersion);
}
public static void newVersion(CommandSender sender, String currentVersion, String newVersion) {
public static void newVersion(CommandSender sender, String currentVersion,
String newVersion) {
sender.sendMessage(new String[] {
ChatColor.YELLOW + "Found new version of KCauldron: "
+ newVersion,
ChatColor.YELLOW + "Current is " + currentVersion,
ChatColor.YELLOW + "Type '" + ChatColor.BLUE
+ "/kc update" + ChatColor.YELLOW
+ "' to update" });
ChatColor.YELLOW + "Type '" + ChatColor.BLUE + "/kc update"
+ ChatColor.YELLOW + "' to update" });
}
@Override

View File

@ -41,15 +41,15 @@ public class DefaultUpdateCallback implements IVersionCheckCallback {
}
@Override
public void upToDate(String version) {
public void upToDate() {
mHasUpdate = false;
mCurrentVersion = version;
mCurrentVersion = KCauldron.getCurrentVersion();
mNewVersion = null;
}
@Override
public void newVersion(String currentVersion, String newVersion) {
mCurrentVersion = currentVersion;
public void newVersion(String newVersion) {
mCurrentVersion = KCauldron.getCurrentVersion();
mNewVersion = newVersion;
if (!mHasUpdate) {
Bukkit.getConsoleSender().sendMessage(

View File

@ -1,10 +1,14 @@
package kcauldron.updater;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import kcauldron.KCauldron;
import kcauldron.updater.KVersionRetriever.IVersionCheckCallback;
import net.minecraft.server.MinecraftServer;
import org.apache.http.HttpResponse;
@ -15,9 +19,9 @@ import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.google.common.base.Splitter;
import com.google.common.base.Joiner;
public class KCauldronUpdater implements Runnable {
public class KCauldronUpdater implements Runnable, IVersionCheckCallback {
private static final class LatestVersionCallback extends
CommandSenderUpdateCallback {
public LatestVersionCallback(CommandSender sender) {
@ -25,17 +29,17 @@ public class KCauldronUpdater implements Runnable {
}
@Override
public void newVersion(String currentVersion, String newVersion) {
public void newVersion(String newVersion) {
startUpdate(getSender(), newVersion);
}
@Override
public void upToDate(String version) {
public void upToDate() {
KCauldron.sUpdateInProgress = false;
CommandSender sender = getSender();
if (sender != null) {
sender.sendMessage(ChatColor.DARK_PURPLE + "Current version ("
+ version + ") is up to date");
+ KCauldron.getCurrentVersion() + ") is up to date");
}
}
@ -56,7 +60,8 @@ public class KCauldronUpdater implements Runnable {
if (version == null) {
sender.sendMessage(ChatColor.DARK_PURPLE
+ "Fetching latest version...");
new KVersionRetriever(new LatestVersionCallback(sender), false);
KVersionRetriever.startServer(new LatestVersionCallback(sender),
false);
} else {
startUpdate(sender, version);
}
@ -85,78 +90,66 @@ public class KCauldronUpdater implements Runnable {
@Override
public void run() {
if (!MinecraftServer.kcauldronConfig.updatecheckerQuite.getValue()) {
mSender.sendMessage(ChatColor.DARK_PURPLE
+ "Retrieving latest KBootstrap version...");
}
new KVersionRetriever(this, false, false, "pw.prok", "KBootstrap");
}
@Override
public void upToDate() {
}
@Override
public void newVersion(String kbootstrapVersion) {
boolean quite = MinecraftServer.kcauldronConfig.updatecheckerQuite
.getValue();
try {
MinecraftServer server = MinecraftServer.getServer();
final String filename = KCauldron.getChannel() + "-" + mVersion
+ "-server.jar";
File path = KCauldron.getServerLocation();
File newPath = new File(path.getParentFile(),
getInstallAs(filename));
if (mSender != null) {
if (!quite) {
mSender.sendMessage(ChatColor.DARK_PURPLE
+ "Current version is located in " + ChatColor.GOLD
+ path.getAbsolutePath());
mSender.sendMessage(ChatColor.DARK_PURPLE
+ "Installing new version in " + ChatColor.GOLD
+ newPath.getAbsolutePath());
+ "Downloading KBootstrap " + kbootstrapVersion + "...");
}
if (newPath.exists()) {
File kbootstrap = File.createTempFile("kbootstrap",
String.valueOf(System.currentTimeMillis()));
download("https://prok.pw/repo/pw/prok/KBootstrap/"
+ kbootstrapVersion + "/KBootstrap-" + kbootstrapVersion
+ "-app.jar", kbootstrap);
if (!quite) {
mSender.sendMessage(ChatColor.DARK_PURPLE
+ "Installing KCauldron " + mVersion
+ " via KBootstrap " + kbootstrapVersion + "...");
}
String javahome = System.getProperty("java.home");
String javapath = javahome + "/bin/java";
List<String> command = new ArrayList<String>();
command.add(javapath);
command.add("-jar");
command.add(kbootstrap.getCanonicalPath());
command.add("--serverDir");
command.add(KCauldron.getServerLocation().getCanonicalPath());
command.add("--installKCauldron");
command.add(mVersion);
command.add("--serverSymlinks");
command.add(MinecraftServer.kcauldronConfig.updatecheckerSymlinks
.getValue());
Bukkit.getConsoleSender().sendMessage(
"ERROR: Install location already exists: "
+ newPath.getAbsolutePath());
"Starting command: " + Joiner.on(' ').join(command));
ProcessBuilder builder = new ProcessBuilder(command);
builder.environment().put("JAVA_HOME", javahome);
switch (builder.start().waitFor()) {
case 0:
mSender.sendMessage(ChatColor.GREEN + "KCauldron " + mVersion
+ " installed");
break;
default:
mSender.sendMessage(ChatColor.RED
+ "ERROR: Install location already exists");
return;
}
if (!quite) {
mSender.sendMessage(ChatColor.DARK_PURPLE
+ "Downloading new version...");
}
}
HttpUriRequest request = RequestBuilder
.get()
.setUri("https://prok.pw/repo/pw/prok/"
+ KCauldron.getChannel() + "/" + mVersion + "/"
+ filename)
.addParameter("hostname", server.getHostname())
.addParameter("port", "" + server.getPort()).build();
HttpResponse response = HttpClientBuilder.create()
.setUserAgent("KCauldron Updater").build().execute(request);
if (response.getStatusLine().getStatusCode() != 200) {
throw new IllegalStateException(
"Could not download new version");
}
InputStream is = response.getEntity().getContent();
Files.copy(is, newPath.toPath());
if (mSender != null && !quite) {
mSender.sendMessage(ChatColor.DARK_PURPLE
+ "Download completed");
}
makeSymlinks(newPath);
if (MinecraftServer.kcauldronConfig.updatecheckerDeleteOld
.getValue()) {
if (mSender != null && !quite) {
mSender.sendMessage(ChatColor.DARK_PURPLE
+ "Mark old version for deletion");
}
path.deleteOnExit();
if (KCauldron.sNewServerLocation != null) {
KCauldron.sNewServerLocation.deleteOnExit();
}
}
if (mSender != null) {
mSender.sendMessage(ChatColor.DARK_PURPLE + "Update completed");
}
KCauldron.sNewServerLocation = newPath;
KCauldron.sNewServerVersion = mVersion;
if (MinecraftServer.kcauldronConfig.updatecheckerAutorestart.getValue()) {
if (mSender != null) {
mSender.sendMessage(ChatColor.DARK_RED + "Initiate server restart");
}
KCauldron.restart();
+ "Failed to install KCauldron " + mVersion);
}
} catch (Exception e) {
if (!quite) {
@ -171,35 +164,29 @@ public class KCauldronUpdater implements Runnable {
}
}
private String getInstallAs(String filename) {
String path = MinecraftServer.kcauldronConfig.updatecheckerInstallAs
.getValue().trim();
if (path.length() > 0) {
return path.replace("%version%", mVersion);
}
return filename;
@Override
public void error(Throwable t) {
KCauldron.sUpdateInProgress = false;
t.printStackTrace();
}
private void makeSymlinks(File newPath) {
try {
for (String symlink : Splitter.on(File.pathSeparatorChar).split(
MinecraftServer.kcauldronConfig.updatecheckerSymlinks
.getValue())) {
symlink = symlink.trim();
if (symlink.length() == 0)
continue;
File symlinkPath = new File(symlink);
if (mSender != null
&& !MinecraftServer.kcauldronConfig.updatecheckerQuite
.getValue()) {
mSender.sendMessage(ChatColor.RED + "Create symlink "
+ ChatColor.GOLD + symlinkPath.getAbsolutePath());
}
Files.deleteIfExists(symlinkPath.toPath());
Files.createSymbolicLink(symlinkPath.toPath(), newPath.toPath());
}
} catch (Exception e) {
private static void download(String url, File destination)
throws IOException {
HttpUriRequest request = RequestBuilder
.get()
.setUri(url)
.addParameter("hostname",
MinecraftServer.getServer().getHostname())
.addParameter("port",
String.valueOf(MinecraftServer.getServer().getPort()))
.build();
HttpResponse response = HttpClientBuilder.create()
.setUserAgent("KCauldron Updater").build().execute(request);
if (response.getStatusLine().getStatusCode() != 200) {
throw new IllegalStateException("Could not download " + url);
}
InputStream is = response.getEntity().getContent();
Files.copy(is, destination.toPath());
is.close();
}
}

View File

@ -18,33 +18,42 @@ public class KVersionRetriever implements Runnable, UncaughtExceptionHandler {
private static final boolean DEBUG;
private static final KLog sLogger;
private static final JSONParser sParser;
private static final String sCurrentVersion;
private static MinecraftServer sServer;
static {
DEBUG = false;
sLogger = KLog.get(KVersionRetriever.class.getSimpleName());
sCurrentVersion = KCauldron.getCurrentVersion();
sParser = new JSONParser();
}
public static void init(MinecraftServer server) {
sServer = server;
if (MinecraftServer.kcauldronConfig.updatecheckerEnable.getValue()) {
new KVersionRetriever(DefaultUpdateCallback.INSTANCE, true);
startServer(DefaultUpdateCallback.INSTANCE, true);
}
}
public static void startServer(IVersionCheckCallback callback, boolean loop) {
new KVersionRetriever(callback, loop, true, "pw.prok",KCauldron.getChannel());
}
private final IVersionCheckCallback mCallback;
private final boolean mLoop;
private final Thread mThread;
private final String mGroup;
private final String mName;
private final boolean mUpToDateSupport;
public KVersionRetriever(IVersionCheckCallback callback, boolean loop) {
public KVersionRetriever(IVersionCheckCallback callback, boolean loop,
boolean upToDateSupport, String group, String name) {
if (DEBUG)
sLogger.info("Created new version retrivier");
mCallback = callback;
mLoop = loop;
mUpToDateSupport = upToDateSupport;
mGroup = group;
mName = name;
mThread = new Thread(this);
mThread.setName("KCauldron version retrievier");
mThread.setPriority(Thread.MIN_PRIORITY);
@ -68,13 +77,9 @@ public class KVersionRetriever implements Runnable, UncaughtExceptionHandler {
}
private void check() {
if (DEBUG)
sLogger.info("Requesting for new version...");
try {
HttpUriRequest request = RequestBuilder
.get()
.setUri("https://prok.pw/version/pw.prok/"
+ KCauldron.getChannel())
HttpUriRequest request = RequestBuilder.get()
.setUri("https://prok.pw/version/" + mGroup + "/" + mName)
.addParameter("hostname", sServer.getHostname())
.addParameter("port", "" + sServer.getPort()).build();
HttpResponse response = HttpClientBuilder.create()
@ -83,14 +88,11 @@ public class KVersionRetriever implements Runnable, UncaughtExceptionHandler {
JSONObject json = (JSONObject) sParser.parse(new InputStreamReader(
response.getEntity().getContent()));
String version = (String) json.get("version");
if (DEBUG) {
sLogger.info("Got the latest version: %s", version);
sLogger.info("Current version is %s", sCurrentVersion);
}
if (!sCurrentVersion.equals(version)) {
mCallback.newVersion(sCurrentVersion, version);
if (!mUpToDateSupport
|| !KCauldron.getCurrentVersion().equals(version)) {
mCallback.newVersion(version);
} else {
mCallback.upToDate(version);
mCallback.upToDate();
}
} catch (Exception e) {
uncaughtException(null, e);
@ -106,9 +108,9 @@ public class KVersionRetriever implements Runnable, UncaughtExceptionHandler {
}
public interface IVersionCheckCallback {
void upToDate(String version);
void upToDate();
void newVersion(String currentVersion, String newVersion);
void newVersion(String newVersion);
void error(Throwable t);
}