diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..e0f15db --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "automatic" +} \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..417cdcf --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +# Použij JDK jako základ +FROM eclipse-temurin:11-jre + +# Nastav pracovní adresář +WORKDIR /app + +# Přidej fat JAR do kontejneru +COPY target/mining-info-server.jar app.jar + +# Exponuj port (nastav podle tvého serveru) +EXPOSE 8080 + +# Spusť aplikaci +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/pom.xml b/pom.xml index b1690f9..78b54cb 100644 --- a/pom.xml +++ b/pom.xml @@ -1,61 +1,70 @@ - - 4.0.0 - cz.kamma.mining - mining-info-web - war - 1.0-SNAPSHOT - mining-info-web - http://maven.apache.org - - - 1.8 - 1.8 - UTF-8 - - - - - javax.servlet - servlet-api - 2.5 - provided - - - javax.servlet.jsp - jsp-api - 2.1 - provided - - - - org.json - json - 20171018 - - - - - ROOT - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.8 - 1.8 - - - - - - - - prime-repo - Prime Repo - http://repository.primefaces.org - - - + + 4.0.0 + cz.kamma.mining + mining-info-web + jar + 1.0-SNAPSHOT + mining-info-web + http://maven.apache.org + + + 11 + 11 + UTF-8 + + + + + org.json + json + 20250517 + + + + + mining-info + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 11 + 11 + + + + org.codehaus.mojo + exec-maven-plugin + 3.0.0 + + cz.kamma.mining.MiningApplication + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + package + + shade + + + false + + + cz.kamma.mining.MiningApplication + + + mining-info-server + + + + + + + diff --git a/src/main/java/cz/kamma/mining/Constants.java b/src/main/java/cz/kamma/mining/Constants.java index 2f42898..cbbd997 100644 --- a/src/main/java/cz/kamma/mining/Constants.java +++ b/src/main/java/cz/kamma/mining/Constants.java @@ -1,10 +1,10 @@ -package cz.kamma.mining; - -public interface Constants { - - public static final String APP_VERSION = "v0.9.1"; - public static final String COPYRIGHT = "2024"; - public static final int DEFAULT_HTTP_CONNECTION_TIMEOUT = 6000; - public static final int DEFAULT_HTTP_READ_TIMEOUT = 18000; - public static final int RELOAD_TIME = 25000; -} +package cz.kamma.mining; + +public interface Constants { + + public static final String APP_VERSION = "v0.9.2"; + public static final String COPYRIGHT = "2025"; + public static final int DEFAULT_HTTP_CONNECTION_TIMEOUT = 6000; + public static final int DEFAULT_HTTP_READ_TIMEOUT = 18000; + public static final int RELOAD_TIME = 25000; +} diff --git a/src/main/java/cz/kamma/mining/MiningApplication.java b/src/main/java/cz/kamma/mining/MiningApplication.java new file mode 100644 index 0000000..ac0c88e --- /dev/null +++ b/src/main/java/cz/kamma/mining/MiningApplication.java @@ -0,0 +1,59 @@ +package cz.kamma.mining; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import com.sun.net.httpserver.HttpServer; + +import cz.kamma.mining.handler.MainPageHandler; +import cz.kamma.mining.handler.StaticFileHandler; +import cz.kamma.mining.handler.UpdateHandler; + +public class MiningApplication { + + private HttpServer server; + private static final int PORT = 8080; + private static final int THREAD_POOL_SIZE = 10; + + public MiningApplication() throws IOException { + this.server = HttpServer.create(new InetSocketAddress("0.0.0.0", PORT), 50); + ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE); + server.setExecutor(executorService); + + // Register handlers + server.createContext("/", new MainPageHandler()); + server.createContext("/ajaxview.html", new StaticFileHandler()); + server.createContext("/getupdate", new UpdateHandler()); + + System.out.println("Server initialized on port " + PORT); + } + + public void start() { + server.start(); + System.out.println("Mining Info Server started on http://0.0.0.0:" + PORT); + } + + public void stop() { + server.stop(0); + System.out.println("Mining Info Server stopped"); + } + + public static void main(String[] args) { + try { + MiningApplication app = new MiningApplication(); + app.start(); + + // Graceful shutdown on SIGTERM + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + System.out.println("Shutting down server..."); + app.stop(); + })); + + } catch (IOException e) { + System.err.println("Failed to start server: " + e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/src/main/java/cz/kamma/mining/bean/MiningBean.java b/src/main/java/cz/kamma/mining/bean/MiningBean.java index fe4efe7..1257bd1 100644 --- a/src/main/java/cz/kamma/mining/bean/MiningBean.java +++ b/src/main/java/cz/kamma/mining/bean/MiningBean.java @@ -1,692 +1,696 @@ -package cz.kamma.mining.bean; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONArray; -import org.json.JSONObject; - -import cz.kamma.mining.Constants; -import cz.kamma.mining.vo.KeyValue; - -public class MiningBean { - - String curSym = "$"; - String ltcapikey; - String dogapikey; - String ltcWallet; - String xrpWallet; - String ethWallet; - String currency; - String resultStr; - String restRequest; - int finished = 0b0; - - public String updateAll(HttpServletRequest request, HttpServletResponse response) throws Exception { - SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - java.lang.System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2"); - List prices = new ArrayList<>(); - List workers = new ArrayList<>(); - List pool = new ArrayList<>(); - List network = new ArrayList<>(); - - String[] cryptoCur = new String[] { "BTC", "LTC", "XRP", "ETH", "DOGE", "ADA", "SHIB" }; - int[] roundPrices = new int[] { 4, 4, 4, 4, 4, 4, 6 }; - double[] lastPrices = new double[cryptoCur.length]; - - ltcapikey = request.getParameter("ltcapikey"); - dogapikey = request.getParameter("dogapikey"); - ltcWallet = request.getParameter("ltc"); - xrpWallet = request.getParameter("xrp"); - ethWallet = request.getParameter("eth"); - currency = request.getParameter("cur"); - - if (currency == null || currency.equals("null") || currency.length() == 0) - currency = "usd"; - else - currency = currency.toLowerCase(); - - if (currency.equals("usd")) - curSym = "$"; - else if (currency.equals("eur")) - curSym = "\u20ac"; - - Map headers = new HashMap<>(); - headers.put("X-CMC_PRO_API_KEY", "d9fae81b-79a4-476e-8f5d-2b4f4033e9a1"); - restRequest = getStringResponse("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest", headers); - - if (restRequest != null && restRequest.length() > 0) { - JSONObject tmp = new JSONObject(restRequest); - JSONArray data = (JSONArray) tmp.get("data"); - - for (int i = 0; i < data.length(); i++) { - JSONObject o = data.getJSONObject(i); - String symbol = o.getString("symbol"); - int pos = searchArray(cryptoCur, symbol); - if (pos >= 0) { - JSONObject quote = (JSONObject) o.get("quote"); - JSONObject usd = (JSONObject) quote.get(currency.toUpperCase()); - double price = usd.getDouble("price"); - double change = usd.getDouble("percent_change_24h"); - - lastPrices[pos] = price; - if (price > 0d) - resultStr = curSym + String.format("%." + roundPrices[pos] + "f", (price)) + " (" - + String.format("%.2f", (change)) + "%)"; - else - resultStr = "Unknown"; - KeyValue wi = new KeyValue(); - wi.setKey(symbol.concat("/").concat(currency.toUpperCase())); - wi.setValue(resultStr); - if (change > 0) - wi.setColor("#00FF99"); - else - wi.setColor("#FF5050"); - prices.add(wi); - - } - } - - } - - new Thread(new Runnable() { - - @Override - public void run() { - try { - if (ltcWallet != null && !"null".equals(ltcWallet) && ltcWallet.length() > 0) { - restRequest = getStringResponse( - "https://api.blockcypher.com/v1/ltc/main/addrs/".concat(ltcWallet).concat("/balance")); - if (restRequest != null && restRequest.length() > 0) { - JSONObject full = new JSONObject(restRequest); - String balance = (String) full.get("final_balance").toString(); - - double res = Double.parseDouble(balance) / 100000000; - if (res > 0d) { -; resultStr = res + " LTC " + curSym + String.format("%.2f", (res * lastPrices[1])); - } else - resultStr = "Unknown"; - KeyValue wi = new KeyValue(); - wi.setKey("My Balance LTC"); - wi.setValue(resultStr); - prices.add(wi); - } - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - finished = finished | 0b1; - } - }).start(); - - new Thread(new Runnable() { - - @Override - public void run() { - try { - if (xrpWallet != null && !"null".equals(xrpWallet) && xrpWallet.length() > 0) { - String request = "{\r\n" + " \"method\": \"account_info\",\r\n" + " \"params\": [\r\n" - + " {\r\n" + " \"account\": \"" + xrpWallet + "\",\r\n" - + " \"ledger_index\": \"current\",\r\n" + " \"queue\": true\r\n" - + " }\r\n" + " ]\r\n" + "}"; - restRequest = makeRequest("http://s1.ripple.com:51234", "POST", 5000, 5000, null, - request.getBytes()); - if (restRequest != null && restRequest.length() > 0) { - JSONObject full = new JSONObject(restRequest); - String balance = (String) full.getJSONObject("result").getJSONObject("account_data") - .get("Balance"); - double res = Double.valueOf(balance.toString()); - if (res > 0d) { - res = res / 1000000; - resultStr = res + " XRP " + curSym + String.format("%.2f", (res * lastPrices[2])); - } else - resultStr = "Unknown"; - KeyValue wi = new KeyValue(); - wi.setKey("My Balance XRP"); - wi.setValue(resultStr); - prices.add(wi); - } - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - finished = finished | 0b10; - } - }).start(); - - new Thread(new Runnable() { - - @Override - public void run() { - try { - if (ethWallet != null && !"null".equals(ethWallet) && ethWallet.length() > 0) { - restRequest = getStringResponse( - "https://api.etherscan.io/api?module=account&action=balance&address=" + ethWallet - + "&tag=latest&apikey=N54NVXSVSISMQ4QIM2JVKJW56KHCKMU5T4"); - if (restRequest != null && restRequest.length() > 0) { - JSONObject full = new JSONObject(restRequest); - String confirmedBalance = (String) full.get("result"); - - double res = Double.parseDouble(confirmedBalance); - res = res * 0.000000000000000001; - if (res > 0d) { - resultStr = res + " ETH " + curSym + String.format("%.2f", (res * lastPrices[3])); - } else - resultStr = "Unknown"; - KeyValue wi = new KeyValue(); - wi.setKey("My Balance ETH"); - wi.setValue(resultStr); - prices.add(wi); - } - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - finished = finished | 0b100; - } - }).start(); - - new Thread(new Runnable() { - - @Override - public void run() { - try { - if (ltcapikey != null && !"null".equals(ltcapikey) && ltcapikey.length() > 0) { - String miningJson = getStringResponse( - "https://www.litecoinpool.org/api?api_key=".concat(ltcapikey)); - if (miningJson != null && miningJson.length() > 0) { - JSONObject full = new JSONObject(miningJson); - JSONObject user = (JSONObject) full.get("user"); - - KeyValue wi = new KeyValue(); - wi.setKey("HashRate"); - if (user.getInt("hash_rate") > 0) - wi.setValue((user.getInt("hash_rate") / 1000) + " MH/s"); - else - wi.setValue("Unknown"); - workers.add(wi); - - JSONObject workersJson = (JSONObject) full.get("workers"); - for (Iterator keys = workersJson.keys(); keys.hasNext();) { - String key = keys.next(); - JSONObject worker = (JSONObject) workersJson.get(key); - wi = new KeyValue(); - wi.setKey("HashRate " + key); - wi.setValue((worker.getInt("hash_rate") / 1000) + " MH/s"); - workers.add(wi); - } - - wi = new KeyValue(); - wi.setKey("Paid"); - if (user.getDouble("paid_rewards") > 0) - wi.setValue(user.getDouble("paid_rewards") + " LTC " + curSym - + String.format("%.2f", (user.getDouble("paid_rewards") * lastPrices[1]))); - else - wi.setValue("Unknown"); - workers.add(wi); - - wi = new KeyValue(); - wi.setKey("Unpaid"); - if (user.getDouble("unpaid_rewards") > 0) - wi.setValue(user.getDouble("unpaid_rewards") + " LTC " + curSym - + String.format("%.2f", (user.getDouble("unpaid_rewards") * lastPrices[1]))); - else - wi.setValue("Unknown"); - workers.add(wi); - - wi = new KeyValue(); - wi.setKey("Total"); - if (user.getDouble("total_rewards") > 0) - wi.setValue(user.getDouble("total_rewards") + " LTC " + curSym - + String.format("%.2f", (user.getDouble("total_rewards") * lastPrices[1]))); - else - wi.setValue("Unknown"); - workers.add(wi); - - wi = new KeyValue(); - wi.setKey("Expected 24h"); - if (user.getDouble("expected_24h_rewards") > 0) - wi.setValue(user.getDouble("expected_24h_rewards") + " LTC " + curSym + String - .format("%.2f", (user.getDouble("expected_24h_rewards") * lastPrices[1]))); - else - wi.setValue("Unknown"); - workers.add(wi); - - wi = new KeyValue(); - wi.setKey("Past 24h"); - if (user.getDouble("past_24h_rewards") > 0) - wi.setValue(user.getDouble("past_24h_rewards") + " LTC " + curSym - + String.format("%.2f", (user.getDouble("past_24h_rewards") * lastPrices[1]))); - else - wi.setValue("Unknown"); - workers.add(wi); - - JSONObject net = (JSONObject) full.get("network"); - wi = new KeyValue(); - wi.setKey("Network HashRate"); - if (net.getLong("hash_rate") > 0) - wi.setValue((net.getLong("hash_rate") / 1000000) + " GH/s"); - else - wi.setValue("Unknown"); - network.add(wi); - - wi = new KeyValue(); - wi.setKey("Difficulty"); - if (net.getDouble("difficulty") > 0) - wi.setValue("" + net.getDouble("difficulty")); - else - wi.setValue("Unknown"); - network.add(wi); - - wi = new KeyValue(); - wi.setKey("Next Difficulty"); - if (net.getDouble("next_difficulty") > 0) - wi.setValue("" + net.getDouble("next_difficulty")); - else - wi.setValue("Unknown"); - network.add(wi); - - wi = new KeyValue(); - wi.setKey("Retarget time"); - if (net.getDouble("retarget_time") > 0) - wi.setValue(splitToComponentTimes(net.getInt("retarget_time"))); - else - wi.setValue("Unknown"); - network.add(wi); - - JSONObject poolJson = (JSONObject) full.get("pool"); - wi = new KeyValue(); - wi.setKey("Pool HashRate"); - if (poolJson.getLong("hash_rate") > 0) - wi.setValue((poolJson.getLong("hash_rate") / 1000000) + " GH/s"); - else - wi.setValue("Unknown"); - pool.add(wi); - - wi = new KeyValue(); - wi.setKey("Active users"); - if (poolJson.getInt("active_users") > 0) - wi.setValue("" + poolJson.getInt("active_users")); - else - wi.setValue("Unknown"); - pool.add(wi); - - wi = new KeyValue(); - wi.setKey("PPS Ratio"); - if (poolJson.getDouble("pps_ratio") > 0) - wi.setValue("" + poolJson.getDouble("pps_ratio")); - else - wi.setValue("Unknown"); - pool.add(wi); - } - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - finished = finished | 0b1000; - } - }).start(); - - if (dogapikey != null && !"null".equals(dogapikey) && dogapikey.length() > 0) { - - new Thread(new Runnable() { - - @Override - public void run() { - try { - String miningJson = getStringResponse( - "https://aikapool.com/doge/index.php?page=api&action=getuserworkers&api_key=" - + dogapikey + "&id=282608&_=1621333944761"); - if (miningJson != null && miningJson.length() > 0) { - JSONObject full = new JSONObject(miningJson); - JSONObject user = (JSONObject) full.get("getuserworkers"); - JSONArray data = (JSONArray) user.get("data"); - KeyValue wi = new KeyValue(); - - for (Iterator it = data.iterator(); it.hasNext();) { - JSONObject workersJson = (JSONObject) it.next(); - wi = new KeyValue(); - wi.setKey("HashRate " + workersJson.getString("username")); - double hr = workersJson.getDouble("hashrate"); - wi.setValue(String.format("%.2f", (hr / 1000)) + " MH/s"); - workers.add(wi); - } - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - finished = finished | 0b10000; - } - }).start(); - - new Thread(new Runnable() { - - @Override - public void run() { - try { - String miningJson = getStringResponse( - "https://aikapool.com/doge/index.php?page=api&action=getdashboarddata&api_key=" - + dogapikey + "&id=282608&_=1621333944761"); - if (miningJson != null && miningJson.length() > 0) { - JSONObject full = new JSONObject(miningJson); - JSONObject user = (JSONObject) full.get("getdashboarddata"); - JSONObject data = (JSONObject) user.get("data"); - JSONObject net = (JSONObject) data.get("network"); - JSONObject pers = (JSONObject) data.get("personal"); - JSONObject poolj = (JSONObject) data.get("pool"); - JSONArray blocks = (JSONArray) poolj.get("blocks"); - JSONObject estimates = (JSONObject) pers.get("estimates"); - JSONObject raw = (JSONObject) data.get("raw"); - KeyValue wi = new KeyValue(); - - wi = new KeyValue(); - wi.setKey("Next Payout"); - if (estimates.getDouble("payout") > 0) - wi.setValue(estimates.getDouble("payout") + " DOG"); - else - wi.setValue("Unknown"); - workers.add(wi); - - wi = new KeyValue(); - wi.setKey("Last Block Time"); - if (blocks != null && blocks.get(0) != null) { - JSONObject block = (JSONObject) blocks.get(0); - long time = block.getLong("time"); - wi.setValue("" + sdf.format(new Date(time * 1000))); - } else - wi.setValue("Unknown"); - network.add(wi); - - wi = new KeyValue(); - wi.setKey("Last Block Finder"); - if (blocks != null && blocks.get(0) != null) { - JSONObject block = (JSONObject) blocks.get(0); - String finder = block.getString("finder"); - if (block.isNull("group_name")) - wi.setValue(finder); - else - wi.setValue(finder + " (SOLO)"); - } else - wi.setValue("Unknown"); - network.add(wi); - - wi = new KeyValue(); - wi.setKey("Difficulty"); - if (net.getDouble("difficulty") > 0) - wi.setValue("" + net.getDouble("difficulty")); - else - wi.setValue("Unknown"); - network.add(wi); - - wi = new KeyValue(); - wi.setKey("Next Difficulty"); - if (net.getDouble("nextdifficulty") > 0) - wi.setValue("" + net.getDouble("nextdifficulty")); - else - wi.setValue("Unknown"); - network.add(wi); - - wi = new KeyValue(); - wi.setKey("Pool Hashrate"); - if (raw.getJSONObject("pool").getDouble("hashrate") > 0) - wi.setValue((raw.getJSONObject("pool").getDouble("hashrate") / 1000000) + " GH/s"); - else - wi.setValue("Unknown"); - network.add(wi); - - wi = new KeyValue(); - wi.setKey("Network Hashrate"); - if (raw.getJSONObject("network").getDouble("hashrate") > 0) - wi.setValue((raw.getJSONObject("network").getDouble("hashrate") / 1000000) + " GH/s"); - else - wi.setValue("Unknown"); - network.add(wi); - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - finished = finished | 0b100000; - } - }).start(); - - new Thread(new Runnable() { - - @Override - public void run() { - try { - String miningJson = getStringResponse( - "https://aikapool.com/doge/index.php?page=api&action=getuserbalance&api_key=" - + dogapikey + "&id=282608&_=1621333944761"); - if (miningJson != null && miningJson.length() > 0) { - JSONObject full = new JSONObject(miningJson); - JSONObject user = (JSONObject) full.get("getuserbalance"); - JSONObject data = (JSONObject) user.get("data"); - KeyValue wi = new KeyValue(); - - wi = new KeyValue(); - wi.setKey("Paid"); - if (data.getDouble("paid") >= 0) - wi.setValue(data.getDouble("paid") + " DOG"); - else - wi.setValue("Unknown"); - workers.add(wi); - - wi = new KeyValue(); - wi.setKey("Confirmed"); - if (data.getDouble("confirmed") >= 0) - wi.setValue(data.getDouble("confirmed") + " DOG"); - else - wi.setValue("Unknown"); - workers.add(wi); - - wi = new KeyValue(); - wi.setKey("Unconfirmed"); - if (data.getDouble("unconfirmed") >= 0) - wi.setValue(data.getDouble("unconfirmed") + " DOG"); - else - wi.setValue("Unknown"); - workers.add(wi); - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - finished = finished | 0b1000000; - } - }).start(); - } else { - finished = finished | 0b10000; - finished = finished | 0b100000; - finished = finished | 0b1000000; - } - - while (finished != 0b1111111) { - // System.out.println(Integer.toBinaryString(finished)); - Thread.sleep(2000); - } - - // System.out.println("Done: " + Integer.toBinaryString(finished)); - finished = 0b0; - - KeyValue wi = new KeyValue(); - wi.setKey("Last Update"); - wi.setValue("" + sdf.format(new Date(System.currentTimeMillis()))); - workers.add(0, wi); - - String res = "#PRICES##WORKERS##POOL##NETWORK#"; - - String tmp = ""; - for (KeyValue kv : prices) { - if (kv.getColor() == null) - kv.setColor("#00CCFF"); - tmp = tmp.concat("").concat(kv.getKey().concat("").concat("").concat(kv.getValue()) - .concat("").concat("").concat(kv.getColor()).concat("")); - } - res = res.replace("#PRICES#", tmp); - - tmp = ""; - for (KeyValue kv : workers) { - tmp = tmp.concat("").concat( - kv.getKey().concat("").concat("").concat(kv.getValue()).concat("")); - } - res = res.replace("#WORKERS#", tmp); - - tmp = ""; - for (KeyValue kv : pool) { - tmp = tmp.concat("").concat( - kv.getKey().concat("").concat("").concat(kv.getValue()).concat("")); - } - res = res.replace("#POOL#", tmp); - - tmp = ""; - for (KeyValue kv : network) { - tmp = tmp.concat("").concat( - kv.getKey().concat("").concat("").concat(kv.getValue()).concat("")); - } - res = res.replace("#NETWORK#", tmp); - - return res; - } - - private int searchArray(String[] array, String key) { - int i = 0; - for (String str : array) { - if (str.equals(key)) - return i; - i++; - } - return -1; - } - - public String getVersion() { - return Constants.APP_VERSION; - } - - public static String splitToComponentTimes(int longVal) { - int days = longVal / (24 * 3600); - int remainder = longVal - (days * 24 * 3600); - int hours = remainder / 3600; - remainder = remainder - hours * 3600; - int mins = remainder / 60; - // remainder = remainder - mins * 60; - // int secs = remainder; - - return (days > 0 ? days + "d " : "") + (hours > 0 ? hours + "h " : "") + (mins > 0 ? mins + "m " : ""); - } - - public static String getStringResponse(String urlStr) { - return getStringResponse(urlStr, Constants.DEFAULT_HTTP_CONNECTION_TIMEOUT, Constants.DEFAULT_HTTP_READ_TIMEOUT, - null); - } - - public static String getStringResponse(String urlStr, Map headers) { - return getStringResponse(urlStr, Constants.DEFAULT_HTTP_CONNECTION_TIMEOUT, Constants.DEFAULT_HTTP_READ_TIMEOUT, - headers); - } - - public String makeRequest(String urlStr, String method, int timeout, int readTimeout, Map headers, - byte[] data) { - String output = ""; - - try { - URL url = new URL(urlStr); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setDoInput(true); - conn.setDoOutput(true); - conn.setConnectTimeout(timeout); - conn.setReadTimeout(readTimeout); - conn.setRequestProperty("User-Agent", - "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36"); - if (headers != null && !headers.isEmpty()) { - for (String key : headers.keySet()) { - conn.setRequestProperty(key, headers.get(key)); - } - } - conn.setRequestMethod(method); - conn.connect(); - OutputStream out = conn.getOutputStream(); - out.write(data); - out.flush(); - out.close(); - - BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String inputLine; - while ((inputLine = in.readLine()) != null) - output += inputLine; - in.close(); - conn.disconnect(); - } catch (Exception e) { - System.out.println("Error while getting HTTP response from " + urlStr + ". Ex:" + e); - } - return output; - } - - public static String getStringResponse(String urlStr, int timeout, int readTimeout, Map headers) { - String output = ""; - - try { - URL url = new URL(urlStr); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setDoInput(true); - conn.setDoOutput(false); - conn.setConnectTimeout(timeout); - conn.setReadTimeout(readTimeout); - conn.setRequestProperty("User-Agent", - "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36"); - if (headers != null && !headers.isEmpty()) { - for (String key : headers.keySet()) { - conn.setRequestProperty(key, headers.get(key)); - } - } - conn.connect(); - BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String inputLine; - while ((inputLine = in.readLine()) != null) - output += inputLine; - in.close(); - conn.disconnect(); - } catch (Exception e) { - System.out.println("Error while getting HTTP response from " + urlStr + ". Ex:" + e); - } - return output; - } - - public static void main(String[] args) { - String ltcWallet = "LZV1HpXEWoR1MWRiXeZSbkrgPfWE3oSwgh"; - String restRequest = ""; - try { - if (ltcWallet != null && !"null".equals(ltcWallet) && ltcWallet.length() > 0) { - restRequest = getStringResponse( - "https://api.blockcypher.com/v1/ltc/main/addrs/".concat(ltcWallet).concat("/balance")); - if (restRequest != null && restRequest.length() > 0) { - JSONObject full = new JSONObject(restRequest); - String balance = (String) full.get("final_balance").toString(); - - double res = Double.parseDouble(balance) / 100000000; - String curSym = "$"; - String resultStr = ""; - if (res > 0d) { - resultStr = res + " LTC " + curSym; - } else - resultStr = "Unknown"; - System.out.println(resultStr); - } - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - } - -} +package cz.kamma.mining.bean; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.json.JSONArray; +import org.json.JSONObject; + +import cz.kamma.mining.Constants; +import cz.kamma.mining.handler.RequestParams; +import cz.kamma.mining.vo.KeyValue; + +public class MiningBean { + + String curSym = "$"; + String ltcapikey; + String dogapikey; + String ltcWallet; + String xrpWallet; + String ethWallet; + String currency; + String resultStr; + String restRequest; + int finished = 0b0; + + public String updateAll(RequestParams request) throws Exception { + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + java.lang.System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2"); + List prices = new ArrayList<>(); + List workers = new ArrayList<>(); + List pool = new ArrayList<>(); + List network = new ArrayList<>(); + + String[] cryptoCur = new String[] { "BTC", "LTC", "XRP", "ETH", "DOGE", "ADA", "SHIB" }; + int[] roundPrices = new int[] { 4, 4, 4, 4, 4, 4, 6 }; + double[] lastPrices = new double[cryptoCur.length]; + + ltcapikey = request.getParameter("ltcapikey"); + dogapikey = request.getParameter("dogapikey"); + ltcWallet = request.getParameter("ltc"); + xrpWallet = request.getParameter("xrp"); + ethWallet = request.getParameter("eth"); + currency = request.getParameter("cur"); + + if (currency == null || currency.equals("null") || currency.length() == 0) + currency = "usd"; + else + currency = currency.toLowerCase(); + + if (currency.equals("usd")) + curSym = "$"; + else if (currency.equals("eur")) + curSym = "\u20ac"; + + Map headers = new HashMap<>(); + headers.put("X-CMC_PRO_API_KEY", "d9fae81b-79a4-476e-8f5d-2b4f4033e9a1"); + restRequest = getStringResponse("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest", headers); + + if (restRequest != null && restRequest.length() > 0) { + JSONObject tmp = new JSONObject(restRequest); + JSONArray data = (JSONArray) tmp.get("data"); + + for (int i = 0; i < data.length(); i++) { + JSONObject o = data.getJSONObject(i); + String symbol = o.getString("symbol"); + int pos = searchArray(cryptoCur, symbol); + if (pos >= 0) { + JSONObject quote = (JSONObject) o.get("quote"); + JSONObject usd = (JSONObject) quote.get(currency.toUpperCase()); + double price = usd.getDouble("price"); + double change = usd.getDouble("percent_change_24h"); + + lastPrices[pos] = price; + if (price > 0d) + resultStr = curSym + String.format("%." + roundPrices[pos] + "f", (price)) + " (" + + String.format("%.2f", (change)) + "%)"; + else + resultStr = "Unknown"; + KeyValue wi = new KeyValue(); + wi.setKey(symbol.concat("/").concat(currency.toUpperCase())); + wi.setValue(resultStr); + if (change > 0) + wi.setColor("#00FF99"); + else + wi.setColor("#FF5050"); + prices.add(wi); + + } + } + + } + + new Thread(new Runnable() { + + @Override + public void run() { + try { + if (ltcWallet != null && !"null".equals(ltcWallet) && ltcWallet.length() > 0) { + restRequest = getStringResponse( + "https://litecoinblockexplorer.net/api/v2/address/".concat(ltcWallet), 10000, 10000, null); + if (restRequest != null && restRequest.length() > 0) { + try { + JSONObject full = new JSONObject(restRequest); + String balance = full.getString("balance"); + + double res = Double.parseDouble(balance) / 100000000.0; + if (res > 0d) { + resultStr = res + " LTC " + curSym + String.format("%.2f", (res * lastPrices[1])); + } else + resultStr = "Unknown"; + KeyValue wi = new KeyValue(); + wi.setKey("My Balance LTC"); + wi.setValue(resultStr); + prices.add(wi); + } catch (Exception e) { + System.out.println("Error parsing LTC balance: " + e.getMessage()); + } + } + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finished = finished | 0b1; + } + }).start(); + + new Thread(new Runnable() { + + @Override + public void run() { + try { + if (xrpWallet != null && !"null".equals(xrpWallet) && xrpWallet.length() > 0) { + String request = "{\r\n" + " \"method\": \"account_info\",\r\n" + " \"params\": [\r\n" + + " {\r\n" + " \"account\": \"" + xrpWallet + "\",\r\n" + + " \"ledger_index\": \"current\",\r\n" + " \"queue\": true\r\n" + + " }\r\n" + " ]\r\n" + "}"; + restRequest = makeRequest("http://s1.ripple.com:51234", "POST", 5000, 5000, null, + request.getBytes()); + if (restRequest != null && restRequest.length() > 0) { + JSONObject full = new JSONObject(restRequest); + String balance = (String) full.getJSONObject("result").getJSONObject("account_data") + .get("Balance"); + double res = Double.valueOf(balance.toString()); + if (res > 0d) { + res = res / 1000000; + resultStr = res + " XRP " + curSym + String.format("%.2f", (res * lastPrices[2])); + } else + resultStr = "Unknown"; + KeyValue wi = new KeyValue(); + wi.setKey("My Balance XRP"); + wi.setValue(resultStr); + prices.add(wi); + } + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finished = finished | 0b10; + } + }).start(); + + new Thread(new Runnable() { + + @Override + public void run() { + try { + if (ethWallet != null && !"null".equals(ethWallet) && ethWallet.length() > 0) { + restRequest = getStringResponse( + "https://eth.blockscout.com/api/v2/addresses/" + ethWallet, 10000, 10000, null); + if (restRequest != null && restRequest.length() > 0) { + try { + JSONObject full = new JSONObject(restRequest); + String balanceStr = full.getString("coin_balance"); + + double res = Double.parseDouble(balanceStr); + res = res * 0.000000000000000001; + if (res > 0d) { + resultStr = res + " ETH " + curSym + String.format("%.2f", (res * lastPrices[3])); + } else + resultStr = "Unknown"; + KeyValue wi = new KeyValue(); + wi.setKey("My Balance ETH"); + wi.setValue(resultStr); + prices.add(wi); + } catch (Exception e) { + System.out.println("Error parsing ETH balance: " + e.getMessage()); + } + } + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finished = finished | 0b100; + } + }).start(); + + new Thread(new Runnable() { + + @Override + public void run() { + try { + if (ltcapikey != null && !"null".equals(ltcapikey) && ltcapikey.length() > 0) { + String miningJson = getStringResponse( + "https://www.litecoinpool.org/api?api_key=".concat(ltcapikey)); + if (miningJson != null && miningJson.length() > 0) { + JSONObject full = new JSONObject(miningJson); + JSONObject user = (JSONObject) full.get("user"); + + KeyValue wi = new KeyValue(); + wi.setKey("HashRate"); + if (user.getInt("hash_rate") > 0) + wi.setValue((user.getInt("hash_rate") / 1000) + " MH/s"); + else + wi.setValue("Unknown"); + workers.add(wi); + + JSONObject workersJson = (JSONObject) full.get("workers"); + for (Iterator keys = workersJson.keys(); keys.hasNext();) { + String key = keys.next(); + JSONObject worker = (JSONObject) workersJson.get(key); + wi = new KeyValue(); + wi.setKey("HashRate " + key); + wi.setValue((worker.getInt("hash_rate") / 1000) + " MH/s"); + workers.add(wi); + } + + wi = new KeyValue(); + wi.setKey("Paid"); + if (user.getDouble("paid_rewards") > 0) + wi.setValue(user.getDouble("paid_rewards") + " LTC " + curSym + + String.format("%.2f", (user.getDouble("paid_rewards") * lastPrices[1]))); + else + wi.setValue("Unknown"); + workers.add(wi); + + wi = new KeyValue(); + wi.setKey("Unpaid"); + if (user.getDouble("unpaid_rewards") > 0) + wi.setValue(user.getDouble("unpaid_rewards") + " LTC " + curSym + + String.format("%.2f", (user.getDouble("unpaid_rewards") * lastPrices[1]))); + else + wi.setValue("Unknown"); + workers.add(wi); + + wi = new KeyValue(); + wi.setKey("Total"); + if (user.getDouble("total_rewards") > 0) + wi.setValue(user.getDouble("total_rewards") + " LTC " + curSym + + String.format("%.2f", (user.getDouble("total_rewards") * lastPrices[1]))); + else + wi.setValue("Unknown"); + workers.add(wi); + + wi = new KeyValue(); + wi.setKey("Expected 24h"); + if (user.getDouble("expected_24h_rewards") > 0) + wi.setValue(user.getDouble("expected_24h_rewards") + " LTC " + curSym + String + .format("%.2f", (user.getDouble("expected_24h_rewards") * lastPrices[1]))); + else + wi.setValue("Unknown"); + workers.add(wi); + + wi = new KeyValue(); + wi.setKey("Past 24h"); + if (user.getDouble("past_24h_rewards") > 0) + wi.setValue(user.getDouble("past_24h_rewards") + " LTC " + curSym + + String.format("%.2f", (user.getDouble("past_24h_rewards") * lastPrices[1]))); + else + wi.setValue("Unknown"); + workers.add(wi); + + JSONObject net = (JSONObject) full.get("network"); + wi = new KeyValue(); + wi.setKey("Network HashRate"); + if (net.getLong("hash_rate") > 0) + wi.setValue((net.getLong("hash_rate") / 1000000) + " GH/s"); + else + wi.setValue("Unknown"); + network.add(wi); + + wi = new KeyValue(); + wi.setKey("Difficulty"); + if (net.getDouble("difficulty") > 0) + wi.setValue("" + net.getDouble("difficulty")); + else + wi.setValue("Unknown"); + network.add(wi); + + wi = new KeyValue(); + wi.setKey("Next Difficulty"); + if (net.getDouble("next_difficulty") > 0) + wi.setValue("" + net.getDouble("next_difficulty")); + else + wi.setValue("Unknown"); + network.add(wi); + + wi = new KeyValue(); + wi.setKey("Retarget time"); + if (net.getDouble("retarget_time") > 0) + wi.setValue(splitToComponentTimes(net.getInt("retarget_time"))); + else + wi.setValue("Unknown"); + network.add(wi); + + JSONObject poolJson = (JSONObject) full.get("pool"); + wi = new KeyValue(); + wi.setKey("Pool HashRate"); + if (poolJson.getLong("hash_rate") > 0) + wi.setValue((poolJson.getLong("hash_rate") / 1000000) + " GH/s"); + else + wi.setValue("Unknown"); + pool.add(wi); + + wi = new KeyValue(); + wi.setKey("Active users"); + if (poolJson.getInt("active_users") > 0) + wi.setValue("" + poolJson.getInt("active_users")); + else + wi.setValue("Unknown"); + pool.add(wi); + + wi = new KeyValue(); + wi.setKey("PPS Ratio"); + if (poolJson.getDouble("pps_ratio") > 0) + wi.setValue("" + poolJson.getDouble("pps_ratio")); + else + wi.setValue("Unknown"); + pool.add(wi); + } + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finished = finished | 0b1000; + } + }).start(); + + if (dogapikey != null && !"null".equals(dogapikey) && dogapikey.length() > 0) { + + new Thread(new Runnable() { + + @Override + public void run() { + try { + String miningJson = getStringResponse( + "https://aikapool.com/doge/index.php?page=api&action=getuserworkers&api_key=" + + dogapikey + "&id=282608&_=1621333944761"); + if (miningJson != null && miningJson.length() > 0) { + JSONObject full = new JSONObject(miningJson); + JSONObject user = (JSONObject) full.get("getuserworkers"); + JSONArray data = (JSONArray) user.get("data"); + KeyValue wi = new KeyValue(); + + for (Iterator it = data.iterator(); it.hasNext();) { + JSONObject workersJson = (JSONObject) it.next(); + wi = new KeyValue(); + wi.setKey("HashRate " + workersJson.getString("username")); + double hr = workersJson.getDouble("hashrate"); + wi.setValue(String.format("%.2f", (hr / 1000)) + " MH/s"); + workers.add(wi); + } + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finished = finished | 0b10000; + } + }).start(); + + new Thread(new Runnable() { + + @Override + public void run() { + try { + String miningJson = getStringResponse( + "https://aikapool.com/doge/index.php?page=api&action=getdashboarddata&api_key=" + + dogapikey + "&id=282608&_=1621333944761"); + if (miningJson != null && miningJson.length() > 0) { + JSONObject full = new JSONObject(miningJson); + JSONObject user = (JSONObject) full.get("getdashboarddata"); + JSONObject data = (JSONObject) user.get("data"); + JSONObject net = (JSONObject) data.get("network"); + JSONObject pers = (JSONObject) data.get("personal"); + JSONObject poolj = (JSONObject) data.get("pool"); + JSONArray blocks = (JSONArray) poolj.get("blocks"); + JSONObject estimates = (JSONObject) pers.get("estimates"); + JSONObject raw = (JSONObject) data.get("raw"); + KeyValue wi = new KeyValue(); + + wi = new KeyValue(); + wi.setKey("Next Payout"); + if (estimates.getDouble("payout") > 0) + wi.setValue(estimates.getDouble("payout") + " DOG"); + else + wi.setValue("Unknown"); + workers.add(wi); + + wi = new KeyValue(); + wi.setKey("Last Block Time"); + if (blocks != null && blocks.get(0) != null) { + JSONObject block = (JSONObject) blocks.get(0); + long time = block.getLong("time"); + wi.setValue("" + sdf.format(new Date(time * 1000))); + } else + wi.setValue("Unknown"); + network.add(wi); + + wi = new KeyValue(); + wi.setKey("Last Block Finder"); + if (blocks != null && blocks.get(0) != null) { + JSONObject block = (JSONObject) blocks.get(0); + String finder = block.getString("finder"); + if (block.isNull("group_name")) + wi.setValue(finder); + else + wi.setValue(finder + " (SOLO)"); + } else + wi.setValue("Unknown"); + network.add(wi); + + wi = new KeyValue(); + wi.setKey("Difficulty"); + if (net.getDouble("difficulty") > 0) + wi.setValue("" + net.getDouble("difficulty")); + else + wi.setValue("Unknown"); + network.add(wi); + + wi = new KeyValue(); + wi.setKey("Next Difficulty"); + if (net.getDouble("nextdifficulty") > 0) + wi.setValue("" + net.getDouble("nextdifficulty")); + else + wi.setValue("Unknown"); + network.add(wi); + + wi = new KeyValue(); + wi.setKey("Pool Hashrate"); + if (raw.getJSONObject("pool").getDouble("hashrate") > 0) + wi.setValue((raw.getJSONObject("pool").getDouble("hashrate") / 1000000) + " GH/s"); + else + wi.setValue("Unknown"); + network.add(wi); + + wi = new KeyValue(); + wi.setKey("Network Hashrate"); + if (raw.getJSONObject("network").getDouble("hashrate") > 0) + wi.setValue((raw.getJSONObject("network").getDouble("hashrate") / 1000000) + " GH/s"); + else + wi.setValue("Unknown"); + network.add(wi); + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finished = finished | 0b100000; + } + }).start(); + + new Thread(new Runnable() { + + @Override + public void run() { + try { + String miningJson = getStringResponse( + "https://aikapool.com/doge/index.php?page=api&action=getuserbalance&api_key=" + + dogapikey + "&id=282608&_=1621333944761"); + if (miningJson != null && miningJson.length() > 0) { + JSONObject full = new JSONObject(miningJson); + JSONObject user = (JSONObject) full.get("getuserbalance"); + JSONObject data = (JSONObject) user.get("data"); + KeyValue wi = new KeyValue(); + + wi = new KeyValue(); + wi.setKey("Paid"); + if (data.getDouble("paid") >= 0) + wi.setValue(data.getDouble("paid") + " DOG"); + else + wi.setValue("Unknown"); + workers.add(wi); + + wi = new KeyValue(); + wi.setKey("Confirmed"); + if (data.getDouble("confirmed") >= 0) + wi.setValue(data.getDouble("confirmed") + " DOG"); + else + wi.setValue("Unknown"); + workers.add(wi); + + wi = new KeyValue(); + wi.setKey("Unconfirmed"); + if (data.getDouble("unconfirmed") >= 0) + wi.setValue(data.getDouble("unconfirmed") + " DOG"); + else + wi.setValue("Unknown"); + workers.add(wi); + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finished = finished | 0b1000000; + } + }).start(); + } else { + finished = finished | 0b10000; + finished = finished | 0b100000; + finished = finished | 0b1000000; + } + + while (finished != 0b1111111) { + // System.out.println(Integer.toBinaryString(finished)); + Thread.sleep(2000); + } + + // System.out.println("Done: " + Integer.toBinaryString(finished)); + finished = 0b0; + + KeyValue wi = new KeyValue(); + wi.setKey("Last Update"); + wi.setValue("" + sdf.format(new Date(System.currentTimeMillis()))); + workers.add(0, wi); + + String res = "#PRICES##WORKERS##POOL##NETWORK#"; + + String tmp = ""; + for (KeyValue kv : prices) { + if (kv.getColor() == null) + kv.setColor("#00CCFF"); + tmp = tmp.concat("").concat(kv.getKey().concat("").concat("").concat(kv.getValue()) + .concat("").concat("").concat(kv.getColor()).concat("")); + } + res = res.replace("#PRICES#", tmp); + + tmp = ""; + for (KeyValue kv : workers) { + tmp = tmp.concat("").concat( + kv.getKey().concat("").concat("").concat(kv.getValue()).concat("")); + } + res = res.replace("#WORKERS#", tmp); + + tmp = ""; + for (KeyValue kv : pool) { + tmp = tmp.concat("").concat( + kv.getKey().concat("").concat("").concat(kv.getValue()).concat("")); + } + res = res.replace("#POOL#", tmp); + + tmp = ""; + for (KeyValue kv : network) { + tmp = tmp.concat("").concat( + kv.getKey().concat("").concat("").concat(kv.getValue()).concat("")); + } + res = res.replace("#NETWORK#", tmp); + + return res; + } + + private int searchArray(String[] array, String key) { + int i = 0; + for (String str : array) { + if (str.equals(key)) + return i; + i++; + } + return -1; + } + + public String getVersion() { + return Constants.APP_VERSION; + } + + public static String splitToComponentTimes(int longVal) { + int days = longVal / (24 * 3600); + int remainder = longVal - (days * 24 * 3600); + int hours = remainder / 3600; + remainder = remainder - hours * 3600; + int mins = remainder / 60; + // remainder = remainder - mins * 60; + // int secs = remainder; + + return (days > 0 ? days + "d " : "") + (hours > 0 ? hours + "h " : "") + (mins > 0 ? mins + "m " : ""); + } + + public static String getStringResponse(String urlStr) { + return getStringResponse(urlStr, Constants.DEFAULT_HTTP_CONNECTION_TIMEOUT, Constants.DEFAULT_HTTP_READ_TIMEOUT, + null); + } + + public static String getStringResponse(String urlStr, Map headers) { + return getStringResponse(urlStr, Constants.DEFAULT_HTTP_CONNECTION_TIMEOUT, Constants.DEFAULT_HTTP_READ_TIMEOUT, + headers); + } + + public String makeRequest(String urlStr, String method, int timeout, int readTimeout, Map headers, + byte[] data) { + String output = ""; + + try { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setConnectTimeout(timeout); + conn.setReadTimeout(readTimeout); + conn.setRequestProperty("User-Agent", + "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36"); + if (headers != null && !headers.isEmpty()) { + for (String key : headers.keySet()) { + conn.setRequestProperty(key, headers.get(key)); + } + } + conn.setRequestMethod(method); + conn.connect(); + OutputStream out = conn.getOutputStream(); + out.write(data); + out.flush(); + out.close(); + + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) + output += inputLine; + in.close(); + conn.disconnect(); + } catch (Exception e) { + System.out.println("Error while getting HTTP response from " + urlStr + ". Ex:" + e); + } + return output; + } + + public static String getStringResponse(String urlStr, int timeout, int readTimeout, Map headers) { + String output = ""; + + try { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setDoInput(true); + conn.setDoOutput(false); + conn.setConnectTimeout(timeout); + conn.setReadTimeout(readTimeout); + conn.setRequestProperty("User-Agent", + "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36"); + if (headers != null && !headers.isEmpty()) { + for (String key : headers.keySet()) { + conn.setRequestProperty(key, headers.get(key)); + } + } + conn.connect(); + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) + output += inputLine; + in.close(); + conn.disconnect(); + } catch (Exception e) { + System.out.println("Error while getting HTTP response from " + urlStr + ". Ex:" + e); + } + return output; + } + + public static void main(String[] args) { + String ltcWallet = "LZV1HpXEWoR1MWRiXeZSbkrgPfWE3oSwgh"; + String restRequest = ""; + try { + if (ltcWallet != null && !"null".equals(ltcWallet) && ltcWallet.length() > 0) { + restRequest = getStringResponse( + "https://litecoinblockexplorer.net/api/v2/address/".concat(ltcWallet), 10000, 10000, null); + if (restRequest != null && restRequest.length() > 0) { + JSONObject full = new JSONObject(restRequest); + String balance = full.getString("balance"); + double res = Double.parseDouble(balance) / 100000000.0; + String curSym = "$"; + String resultStr = ""; + if (res > 0d) { + resultStr = res + " LTC " + curSym; + } else + resultStr = "Unknown"; + System.out.println(resultStr); + } + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + +} diff --git a/src/main/java/cz/kamma/mining/handler/MainPageHandler.java b/src/main/java/cz/kamma/mining/handler/MainPageHandler.java new file mode 100644 index 0000000..b30f149 --- /dev/null +++ b/src/main/java/cz/kamma/mining/handler/MainPageHandler.java @@ -0,0 +1,38 @@ +package cz.kamma.mining.handler; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +public class MainPageHandler implements HttpHandler { + + @Override + public void handle(HttpExchange exchange) throws IOException { + if ("GET".equals(exchange.getRequestMethod())) { + try { + // Read index.html from src/main/webapp/ + Path filePath = Paths.get("src/main/webapp/index.html").normalize(); + if (Files.exists(filePath) && !Files.isDirectory(filePath)) { + byte[] fileContent = Files.readAllBytes(filePath); + exchange.getResponseHeaders().set("Content-Type", "text/html; charset=UTF-8"); + exchange.sendResponseHeaders(200, fileContent.length); + OutputStream os = exchange.getResponseBody(); + os.write(fileContent); + os.close(); + } else { + exchange.sendResponseHeaders(404, -1); + } + } catch (Exception e) { + exchange.sendResponseHeaders(500, -1); + } + } else { + exchange.sendResponseHeaders(405, -1); + } + } +} diff --git a/src/main/java/cz/kamma/mining/handler/RequestParams.java b/src/main/java/cz/kamma/mining/handler/RequestParams.java new file mode 100644 index 0000000..4ad9fd9 --- /dev/null +++ b/src/main/java/cz/kamma/mining/handler/RequestParams.java @@ -0,0 +1,23 @@ +package cz.kamma.mining.handler; + +import java.util.Map; + +/** + * Simple request parameters container without servlet API dependency + */ +public class RequestParams { + + private Map parameters; + + public RequestParams(Map parameters) { + this.parameters = parameters; + } + + public String getParameter(String name) { + return parameters.get(name); + } + + public Map getParameterMap() { + return parameters; + } +} diff --git a/src/main/java/cz/kamma/mining/handler/StaticFileHandler.java b/src/main/java/cz/kamma/mining/handler/StaticFileHandler.java new file mode 100644 index 0000000..3aeb851 --- /dev/null +++ b/src/main/java/cz/kamma/mining/handler/StaticFileHandler.java @@ -0,0 +1,77 @@ +package cz.kamma.mining.handler; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +public class StaticFileHandler implements HttpHandler { + + public StaticFileHandler() { + // staticDir is informational, actual path is resolved from classpath + } + + @Override + public void handle(HttpExchange exchange) throws IOException { + if ("GET".equals(exchange.getRequestMethod())) { + String path = exchange.getRequestURI().getPath(); + + // Remove leading slash + if (path.startsWith("/")) { + path = path.substring(1); + } + + try { + // Security: prevent directory traversal + if (path.contains("..")) { + exchange.sendResponseHeaders(403, -1); + return; + } + + InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(path); + + if (resourceStream != null) { + byte[] fileContent = resourceStream.readAllBytes(); + resourceStream.close(); + String contentType = getContentType(path); + + exchange.getResponseHeaders().set("Content-Type", contentType); + exchange.sendResponseHeaders(200, fileContent.length); + OutputStream os = exchange.getResponseBody(); + os.write(fileContent); + os.close(); + } else { + exchange.sendResponseHeaders(404, -1); + } + } catch (Exception e) { + exchange.sendResponseHeaders(500, -1); + } + } else { + exchange.sendResponseHeaders(405, -1); + } + } + + private String getContentType(String path) { + if (path.endsWith(".css")) { + return "text/css; charset=UTF-8"; + } else if (path.endsWith(".js")) { + return "application/javascript; charset=UTF-8"; + } else if (path.endsWith(".html")) { + return "text/html; charset=UTF-8"; + } else if (path.endsWith(".xml")) { + return "text/xml; charset=UTF-8"; + } else if (path.endsWith(".png")) { + return "image/png"; + } else if (path.endsWith(".jpg") || path.endsWith(".jpeg")) { + return "image/jpeg"; + } else if (path.endsWith(".gif")) { + return "image/gif"; + } else if (path.endsWith(".svg")) { + return "image/svg+xml"; + } + return "application/octet-stream"; + } +} + diff --git a/src/main/java/cz/kamma/mining/handler/UpdateHandler.java b/src/main/java/cz/kamma/mining/handler/UpdateHandler.java new file mode 100644 index 0000000..22d69fe --- /dev/null +++ b/src/main/java/cz/kamma/mining/handler/UpdateHandler.java @@ -0,0 +1,80 @@ +package cz.kamma.mining.handler; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +import cz.kamma.mining.bean.MiningBean; + +public class UpdateHandler implements HttpHandler { + + @Override + public void handle(HttpExchange exchange) throws IOException { + if ("POST".equals(exchange.getRequestMethod())) { + // Parse POST parameters + byte[] buffer = new byte[exchange.getRequestBody().available()]; + exchange.getRequestBody().read(buffer); + String postData = new String(buffer, StandardCharsets.UTF_8); + + Map params = parsePostData(postData); + + // Create RequestParams object + try { + MiningBean bean = new MiningBean(); + RequestParams request = new RequestParams(params); + String result = bean.updateAll(request); + + exchange.getResponseHeaders().set("Content-Type", "text/xml; charset=UTF-8"); + exchange.sendResponseHeaders(200, result.getBytes(StandardCharsets.UTF_8).length); + OutputStream os = exchange.getResponseBody(); + os.write(result.getBytes(StandardCharsets.UTF_8)); + os.close(); + } catch (Exception e) { + String errorResponse = "" + escapeXml(e.getMessage()) + ""; + exchange.getResponseHeaders().set("Content-Type", "text/xml; charset=UTF-8"); + exchange.sendResponseHeaders(500, errorResponse.getBytes(StandardCharsets.UTF_8).length); + OutputStream os = exchange.getResponseBody(); + os.write(errorResponse.getBytes(StandardCharsets.UTF_8)); + os.close(); + } + } else { + exchange.sendResponseHeaders(405, -1); + } + } + + private Map parsePostData(String postData) { + Map params = new HashMap<>(); + if (postData == null || postData.isEmpty()) { + return params; + } + + String[] pairs = postData.split("&"); + for (String pair : pairs) { + int idx = pair.indexOf('='); + if (idx > 0) { + String key = pair.substring(0, idx); + String value = idx + 1 < pair.length() ? pair.substring(idx + 1) : ""; + try { + params.put(java.net.URLDecoder.decode(key, "UTF-8"), + java.net.URLDecoder.decode(value, "UTF-8")); + } catch (Exception e) { + params.put(key, value); + } + } + } + return params; + } + + private String escapeXml(String str) { + if (str == null) { + return ""; + } + return str.replace("&", "&").replace("<", "<").replace(">", ">") + .replace("\"", """).replace("'", "'"); + } +} diff --git a/src/main/java/cz/kamma/mining/vo/KeyValue.java b/src/main/java/cz/kamma/mining/vo/KeyValue.java index c54671c..c009d65 100644 --- a/src/main/java/cz/kamma/mining/vo/KeyValue.java +++ b/src/main/java/cz/kamma/mining/vo/KeyValue.java @@ -1,39 +1,39 @@ -package cz.kamma.mining.vo; - -import java.io.Serializable; - -public class KeyValue implements Serializable { - private static final long serialVersionUID = 1L; - - String key; - String value; - String color; - - public KeyValue() { - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - -} +package cz.kamma.mining.vo; + +import java.io.Serializable; + +public class KeyValue implements Serializable { + private static final long serialVersionUID = 1L; + + String key; + String value; + String color; + + public KeyValue() { + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/src/main/resources/ajaxview.html b/src/main/resources/ajaxview.html new file mode 100644 index 0000000..52579a8 --- /dev/null +++ b/src/main/resources/ajaxview.html @@ -0,0 +1,305 @@ + + + + + + +Mining Info + + + +

Mining Info

+
+
+
+
LOADING
+
+
+ + + + + diff --git a/src/main/resources/index.html b/src/main/resources/index.html new file mode 100644 index 0000000..450f88a --- /dev/null +++ b/src/main/resources/index.html @@ -0,0 +1,149 @@ + + + + + + +Mining Info + + + +

Mining Info

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
litecoinpool.org LTC API key (optional)
aikapool.org DOGE API key (optional)
Litecoin wallet address (optional)
Ethereum wallet address (optional)
Ripple wallet address (optional)
Fiat currency
+ +
mining-info.eu v0.9.1 ©2024
LTC: LgQU1Pf96Bip67bpUrTw6K1goayWjPwfay
+
+ + diff --git a/src/main/webapp/META-INF/MANIFEST.MF b/src/main/webapp/META-INF/MANIFEST.MF deleted file mode 100644 index 254272e..0000000 --- a/src/main/webapp/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Class-Path: - diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 141d980..0000000 --- a/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - Mining Console - - index.jsp - - diff --git a/src/main/webapp/ajaxview.jsp b/src/main/webapp/ajaxview.jsp deleted file mode 100644 index 605b335..0000000 --- a/src/main/webapp/ajaxview.jsp +++ /dev/null @@ -1,34 +0,0 @@ - -<%@page contentType="text/html; charset=UTF-8" %> -<%@page import="cz.kamma.mining.Constants"%> - - - - - - -Mining Info - - - - -
-

Mining Info

-
-
    -
  • LOADING...
  • -
- - - - - \ No newline at end of file diff --git a/src/main/webapp/client.js b/src/main/webapp/client.js deleted file mode 100644 index 0449dde..0000000 --- a/src/main/webapp/client.js +++ /dev/null @@ -1,145 +0,0 @@ -var URLsuffix = '/getupdate.jsp'; -//var URLsuffix = '/mining-console/getupdate.jsp'; - -var ajaxHttp = getAjaxLibrary(); - -function getAjaxLibrary() { - var activexmodes = [ "Msxml2.XMLHTTP", "Microsoft.XMLHTTP" ] // activeX - // versions - // to check - // for in IE - if (window.ActiveXObject) { // Test for support for ActiveXObject in IE - // first (as XMLHttpRequest in IE7 is broken) - for (var i = 0; i < activexmodes.length; i++) { - try { - return new ActiveXObject(activexmodes[i]) - } catch (e) { - // suppress error - } - } - } else if (window.XMLHttpRequest) // if Mozilla, Safari etc - return new XMLHttpRequest() - else - return false -} - -/******************************************************************************* - * F U N C T I O N S - ******************************************************************************/ - -function getHost() { - var url = "" + window.location; - var prot = url.split('//')[0]; - var urlparts = url.split('//')[1].split('/'); - return urlparts[0]; -} - -function getProt() { - var url = "" + window.location; - return url.split('//')[0]; -} - -function ajaxSendRequest(data, onReadyStateChange) { - var URL = getProt() + '//' + getHost() + URLsuffix; - // if (ajaxHttp.overrideMimeType) - // ajaxHttp.overrideMimeType('text/xml') - ajaxHttp.open("POST", URL, true); - ajaxHttp.onreadystatechange = onReadyStateChange; - ajaxHttp.setRequestHeader('Content-Type', - 'application/x-www-form-urlencoded'); - ajaxHttp.send(data); -} -function ajaxResponseReady() { - if (ajaxHttp.readyState == 4) { - /* received */ - if (ajaxHttp.status == 200 - || window.location.href.indexOf("http") == -1) { - /* response is ok */ - return true; - } else { - return false; - } - } - return false; -} - -function ajaxGetXmlResponse() { - if (ajaxHttp.responseXML && ajaxHttp.responseXML.parseError - && (ajaxHttp.responseXML.parseError.errorCode != 0)) { - ajaxGetXmlError(true); - return null; - } else { - return ajaxHttp.responseXML; - } -} - -function AX_asynchUpdate(ltcapikey, dogapikey, ltc, eth, xrp, cur) { - var data = 'ajaxMethod=asynchUpdate<capikey=' + ltcapikey + '&dogapikey=' + dogapikey + '<c=' + ltc + 'ð=' + eth - + '&xrp=' + xrp+ '&cur=' + cur; - ajaxSendRequest(data, AX_asynchUpdateResponse); -} - -function AX_asynchUpdateResponse() { - if (ajaxResponseReady()) { - if (ajaxHttp.responseText.indexOf('invalid') == -1) { - var xmlDocument = ajaxGetXmlResponse(); - - var prices = xmlDocument.getElementsByTagName("prices")[0] - .getElementsByTagName("pair"); - var workers = xmlDocument.getElementsByTagName("workers")[0] - .getElementsByTagName("pair"); - var pool = xmlDocument.getElementsByTagName("pool")[0] - .getElementsByTagName("pair"); - var network = xmlDocument.getElementsByTagName("network")[0] - .getElementsByTagName("pair"); - - var resStr = "
  • Prices
  • "; - for (var i = 0; i <= (prices.length - 1); i++) { - var color = prices[i].getElementsByTagName("color")[0].firstChild.data; - if (color==null) - color = "GREEN"; - resStr = resStr - + "
  • " - + prices[i].getElementsByTagName("key")[0].firstChild.data - + " " - + prices[i].getElementsByTagName("value")[0].firstChild.data - + "
  • "; - } - - if (workers.length > 0) { - resStr = resStr + "
  • Workers
  • "; - for (var i = 0; i <= (workers.length - 1); i++) { - resStr = resStr - + "
  • " - + workers[i].getElementsByTagName("key")[0].firstChild.data - + " " - + workers[i].getElementsByTagName("value")[0].firstChild.data - + "
  • "; - } - } - if (pool.length > 0) { - resStr = resStr + "
  • Pool
  • "; - for (var i = 0; i <= (pool.length - 1); i++) { - resStr = resStr - + "
  • " - + pool[i].getElementsByTagName("key")[0].firstChild.data - + " " - + pool[i].getElementsByTagName("value")[0].firstChild.data - + "
  • "; - } - } - if (network.length > 0) { - resStr = resStr + "
  • Network
  • "; - for (var i = 0; i <= (network.length - 1); i++) { - resStr = resStr - + "
  • " - + network[i].getElementsByTagName("key")[0].firstChild.data - + " " - + network[i].getElementsByTagName("value")[0].firstChild.data - + "
  • "; - } - } - document.getElementById('overview').innerHTML = resStr; - } - } -} \ No newline at end of file diff --git a/src/main/webapp/css/default-theme.css b/src/main/webapp/css/default-theme.css deleted file mode 100644 index f7ba187..0000000 --- a/src/main/webapp/css/default-theme.css +++ /dev/null @@ -1,83 +0,0 @@ -body { - margin: 0; - font-family: Helvetica; - background: #424242; - color: rgb(202, 202, 0); - overflow-x: hidden; -} - -body>*:not(.toolbar) { - position: absolute; - margin: 0; - padding: 0; - left: 0; - top: 45px; - width: 100%; - height: auto; - min-height: 415px; -} - -/************************************************************************************************/ -body>.toolbar { - box-sizing: border-box; - border-bottom: 1px solid #2d3642; - border-top: 1px solid #6d84a2; - padding: 0 10px 10px 10px; - height: 45px; - background: #6d84a2 repeat-x; -} - -.toolbar>h1 { - position: absolute; - overflow: hidden; - left: 0%; - margin: 1px 0 0 -1px; - padding-top: 10px; - height: 45px; - font-size: 20px; - width: 100%; - font-weight: bold; - text-shadow: rgba(0, 0, 0, 0.4) 0px -1px 0; - text-align: center; - text-overflow: ellipsis; - white-space: nowrap; - color: #FFFFFF; -} - -/************************************************************************************************/ -body>ul>li { - position: relative; - margin: 0; - border-bottom: 1px solid #E0E0E0; - padding: 8px 0 8px 10px; - font-size: 17px; - font-weight: bold; - list-style: none; -} - -a { - color: rgb(3, 203, 33); - font-weight: bold; - font-style: normal; - text-decoration: none; -} - -.group { - position: relative; - top: -1px; - margin-bottom: -2px; - border-top: 1px solid #7d7d7d; - border-bottom: 1px solid #999999; - padding: 1px 10px; - font-weight: bold; - text-shadow: rgba(0, 0, 0, 0.4) 0 1px 0; - color: #FFFFFF; - opacity: 0.7; - background: #c8c8c8 repeat-x; -} - -.value { - color: #55AA55; - float: right; - padding: 0 8px; -} \ No newline at end of file diff --git a/src/main/webapp/getupdate.jsp b/src/main/webapp/getupdate.jsp deleted file mode 100644 index b9861ae..0000000 --- a/src/main/webapp/getupdate.jsp +++ /dev/null @@ -1,13 +0,0 @@ -<%@page import="cz.kamma.mining.bean.MiningBean"%> -<%@page import="java.util.Date"%> -<%@ page language="java" contentType="text/html; charset=UTF-8" - pageEncoding="UTF-8"%> -<% - MiningBean mb = new MiningBean(); - String res = mb.updateAll(request, response); - - response.setContentType("text/xml; charset=UTF-8"); - response.setHeader("Cache-Control", "no-cache"); - response.getWriter().write(res); - response.getWriter().flush(); -%> \ No newline at end of file diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp deleted file mode 100644 index 5b057c9..0000000 --- a/src/main/webapp/index.jsp +++ /dev/null @@ -1,70 +0,0 @@ - -<%@page contentType="text/html; charset=UTF-8" %> -<%@page import="cz.kamma.mining.Constants"%> - - - - -Mining Info - - - -
    -

    Mining Info

    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    litecoinpool.org LTC API key (optional)
    aikapool.org DOGE API key (optional)
    Litecoin wallet address (optional)
    Ethereum wallet address (optional)
    Ripple wallet address (optional)
    Fiat currency
    - -
    mining-info.eu <%=Constants.APP_VERSION%> ©<%=Constants.COPYRIGHT%>
    LTC: LgQU1Pf96Bip67bpUrTw6K1goayWjPwfay
    -
    - - \ No newline at end of file