commit c531b6e90955eca096211d3044e11efdd6a11723 Author: BuildTools Date: Fri Dec 20 13:12:42 2024 -0500 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..2a65317 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,17 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..73e812d --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..c3454c9 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + id("java") +} + +group = "org.example" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +dependencies { + testImplementation(platform("org.junit:junit-bom:5.9.1")) + testImplementation("org.junit.jupiter:junit-jupiter") + implementation("org.jfree:jfreechart:1.5.3") + implementation("org.jfree:jcommon:1.0.24") + // Add other dependencies if needed +} + +tasks.test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..f6f0974 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Jun 08 10:23:03 EDT 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..205f8a9 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "speedtest" + diff --git a/src/main/java/org/example/InternetSpeedTest.java b/src/main/java/org/example/InternetSpeedTest.java new file mode 100644 index 0000000..698be11 --- /dev/null +++ b/src/main/java/org/example/InternetSpeedTest.java @@ -0,0 +1,448 @@ +package org.example; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.jfree.chart.axis.NumberAxis; +import org.jfree.chart.entity.ChartEntity; +import org.jfree.chart.entity.XYItemEntity; +import org.jfree.chart.labels.XYToolTipGenerator; +import org.jfree.chart.plot.PlotOrientation; +import org.jfree.chart.plot.XYPlot; +import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; +import org.jfree.data.xy.XYSeries; +import org.jfree.data.xy.XYSeriesCollection; +import org.jfree.data.xy.XYDataset; +import org.jfree.chart.ChartFactory; +import org.jfree.chart.ChartMouseEvent; +import org.jfree.chart.ChartMouseListener; +import org.jfree.chart.ChartPanel; +import org.jfree.chart.JFreeChart; + +public class InternetSpeedTest extends JFrame { + private XYSeries uploadSeries; + private XYSeries downloadSeries; + private JLabel status; + private JButton startButton; + private JLabel testNum; + private XYSeriesCollection dataset; + private JFreeChart chart; + private JSlider tests; + private int numberOfTests; + private int testsLeft; + public String timings; + private JLabel timeLeft; + private JLabel tlabel; + private JProgressBar bar; + private int onTest; + private JLabel uploadSpeedLabel; + private JLabel downloadSpeedLabel; + private long startTime; + private double etime; + private List elapsedTimes; + private JWindow tooltipWindow; + private JLabel tooltipLabel; + + private Point cursorPosition; + + public InternetSpeedTest() { + setTitle("Connectivity Speed Test"); + setSize(1800, 600); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setLayout(new BorderLayout()); + // Initialize variables + elapsedTimes = new ArrayList<>(); + // Setup graph + uploadSeries = new XYSeries("Upload Speed"); + downloadSeries = new XYSeries("Download Speed"); + + + dataset = new XYSeriesCollection(); + dataset.addSeries(uploadSeries); + dataset.addSeries(downloadSeries); + chart = ChartFactory.createXYLineChart( + "Speed Test", + "Time", + "Speed (Mbps)", + dataset, + PlotOrientation.VERTICAL, + true, + true, + false + ); + + ChartPanel chartPanel = new ChartPanel(chart) { + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + if (cursorPosition != null) { + XYPlot plot = chart.getXYPlot(); + Rectangle2D plotArea = getScreenDataArea(); + Point2D p = translateScreenToJava2D(cursorPosition); + + if (plotArea.contains(p)) { + Graphics2D g2 = (Graphics2D) g; + g2.setColor(new Color(42, 50, 58)); + g2.setStroke(new BasicStroke(1)); + + // Get data area coordinates from screen coordinates + Rectangle2D dataArea = getScreenDataArea(); + int x = cursorPosition.x; + int y = cursorPosition.y; + + // Draw vertical line within plot area + g2.drawLine(x, (int) dataArea.getMinY(), x, (int) dataArea.getMaxY()); + // Draw horizontal line within plot area + g2.drawLine((int) dataArea.getMinX(), y, (int) dataArea.getMaxX(), y); + } + } + } + }; + // Add a mouse motion listener for drawing dynamic axis lines + chartPanel.addMouseMotionListener(new MouseMotionListener() { + @Override + public void mouseDragged(MouseEvent e) { + // Not used + } + + @Override + public void mouseMoved(MouseEvent e) { + cursorPosition = e.getPoint(); + chartPanel.repaint(); // Trigger a repaint to draw lines + } + }); + + // Add a mouse listener to clear cursor position when mouse exits the chart + chartPanel.addMouseListener(new MouseAdapter() { + @Override + public void mouseExited(MouseEvent e) { + cursorPosition = null; + chartPanel.repaint(); // Clear the lines when the mouse exits + } + }); + chartPanel.setDomainZoomable(true); + chartPanel.setRangeZoomable(true); + add(chartPanel, BorderLayout.CENTER); + + // Customize point shapes and sizes + XYPlot plot = chart.getXYPlot(); + // Set the x-axis to show time in seconds + NumberAxis domainAxis = new NumberAxis("Time (s)"); + domainAxis.setTickUnit(new org.jfree.chart.axis.NumberTickUnit(1)); + plot.setDomainAxis(domainAxis); + // Set geom shape for up and down points + XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); + renderer.setSeriesShapesVisible(0, true); + renderer.setSeriesShapesVisible(1, true); + renderer.setSeriesShape(0, createTriangleUpShape(6)); // Triangle facing up + renderer.setSeriesShape(1, createTriangleDownShape(6)); // Triangle facing down + plot.setRenderer(renderer); + // Add tooltips + // Create a custom tooltip window + tooltipWindow = new JWindow(); + tooltipWindow.setAlwaysOnTop(true); + tooltipWindow.setFocusableWindowState(false); + // Configure the tooltip label + tooltipLabel = new JLabel(); + tooltipLabel.setOpaque(true); + tooltipLabel.setBackground(new Color(58, 64, 71)); // Light grey background + tooltipLabel.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createLineBorder(new Color(0, 120, 215)), // Blue border + BorderFactory.createEmptyBorder(5, 10, 5, 10) // Padding inside the label + )); + tooltipLabel.setFont(new Font("SansSerif", Font.PLAIN, 12)); // Set font + tooltipLabel.setForeground(new Color(255, 255, 255)); // Black text color + tooltipLabel.setVerticalAlignment(SwingConstants.CENTER); + tooltipLabel.setHorizontalAlignment(SwingConstants.LEFT); // Align text to the left + tooltipWindow.getContentPane().add(tooltipLabel); + tooltipWindow.pack(); + + // Add a mouse motion listener to show custom tooltips + chartPanel.addChartMouseListener(new ChartMouseListener() { + @Override + public void chartMouseClicked(ChartMouseEvent event) { + // Not used + } + + @Override + public void chartMouseMoved(ChartMouseEvent event) { + + ChartEntity entity = event.getEntity(); + if (entity instanceof XYItemEntity) { + XYItemEntity itemEntity = (XYItemEntity) entity; + XYDataset dataset = itemEntity.getDataset(); + int series = itemEntity.getSeriesIndex(); + int item = itemEntity.getItem(); + double x = dataset.getXValue(series, item); + double y = dataset.getYValue(series, item); + String seriesName = dataset.getSeriesKey(series).toString(); + + // Get the specific time taken for this point + double test = elapsedTimes.get(item)/1e9; + double elapsedTime = test; + + String tooltipText = String.format( + "%s
Elapsed: %.2f s
Speed: %.2f Mbps
Time: %.2f s", + seriesName, x, y, elapsedTime + ); + + Point p = event.getTrigger().getPoint(); + SwingUtilities.convertPointToScreen(p, chartPanel); + tooltipLabel.setText(tooltipText); + tooltipWindow.pack(); + tooltipWindow.setLocation(p.x - 130, p.y + 15); + tooltipWindow.setVisible(true); + } else { + tooltipWindow.setVisible(false); + } + } + }); + + + // Setup controls + JPanel controlPanel = new JPanel(); + startButton = new JButton("Start Test"); + tests = new JSlider(); + tlabel = new JLabel("Tests: 2"); + controlPanel.add(tlabel); + tests.setMaximum(12); + tests.setMinimum(2); + tests.setValue(2); + tests.revalidate(); + controlPanel.add(tests); + startButton.addActionListener(new StartButtonListener()); + tests.addChangeListener(e -> setTestsNum()); + tests.addChangeListener((e -> startButton.setText("Queue Tests"))); + tests.addChangeListener((e -> testNum.setText(" | Test#: " + onTest + "/" + numberOfTests))); + controlPanel.add(startButton); + uploadSpeedLabel = new JLabel("Up: N/A"); + controlPanel.add(uploadSpeedLabel); + downloadSpeedLabel = new JLabel(" | Down: N/A"); + controlPanel.add(downloadSpeedLabel); + status = new JLabel(" | Status: Not Running"); + controlPanel.add(status); + testNum = new JLabel(" | Test#: N/A | "); + controlPanel.add(testNum); + bar = new JProgressBar(0, tests.getValue()); + controlPanel.add(bar); + timeLeft = new JLabel(" | est time"); + controlPanel.add(timeLeft); + add(controlPanel, BorderLayout.SOUTH); + //customize chart data + + } + + public void disableActions() { + startButton.setEnabled(false); + tests.setEnabled(false); + } + + public void enableActions() { + startButton.setEnabled(true); + tests.setEnabled(true); + } + + public void setTestsNum() { + numberOfTests = tests.getValue(); + tlabel.setText("Tests: " + tests.getValue()); + bar.setMaximum(numberOfTests); + } + + private class StartButtonListener implements ActionListener { + @Override + public void actionPerformed(ActionEvent e) { + setTestsNum(); + new Thread(new SpeedTestTask()).start(); + new Thread(new ElapsedTimeTask()).start(); + //new Thread(new calculateTime()).start(); + elapsedTimes.clear(); + downloadSeries.clear(); + uploadSeries.clear(); + System.out.println("tests queued: "+tests.getValue()); + } + } + + private Shape createTriangleUpShape(int size) { + Path2D.Double path = new Path2D.Double(); + path.moveTo(-size / 2.0, size / 2.0); + path.lineTo(size / 2.0, size / 2.0); + path.lineTo(0, -size / 2.0); + path.closePath(); + return path; + } + + private Shape createTriangleDownShape(int size) { + Path2D.Double path = new Path2D.Double(); + path.moveTo(-size / 2.0, -size / 2.0); + path.lineTo(size / 2.0, -size / 2.0); + path.lineTo(0, size / 2.0); + path.closePath(); + return path; + } + + private class SpeedTestTask implements Runnable { + @Override + public void run() { + try { + disableActions(); + long previousTime = System.nanoTime(); + for (int i = 1; i <= numberOfTests; i++) { + int tn = i; + onTest = tn; + testNum.setText(" | Test#: " + tn + "/" + numberOfTests); + bar.setValue(i); + double downloadSpeed = performDownloadTest(); + double uploadSpeed = performUploadTest(); + + long currentTime = System.nanoTime(); + double elapsedTime = (currentTime - startTime) / 1e9; // convert to seconds + long timeDiff = currentTime - previousTime; + previousTime = currentTime; + + downloadSeries.add(elapsedTime, downloadSpeed,true); + uploadSeries.add(elapsedTime, uploadSpeed,true); + + //lastTime = (int) elapsedTime; + + testsLeft = numberOfTests - tn; + + + downloadSpeedLabel.setText(String.format(" | Down: %.2f Mbps", downloadSpeed)); + uploadSpeedLabel.setText(String.format("Up: %.2f Mbps", uploadSpeed)); + + if (elapsedTimes.size() > 0) { + elapsedTimes.add(timeDiff); + } else { + elapsedTimes.add(currentTime - startTime); + } + + System.out.println("last time: " + elapsedTime); + System.out.println("tests left to complete: " + testsLeft); + System.out.println("math: " + doMath()); + System.out.println("took: "+timeDiff); + System.out.println(elapsedTimes); + timeLeft.setText(doMath()); + + Thread.sleep(100); + } + startButton.setText("Complete"); + enableActions(); + } catch (InterruptedException ex) { + ex.printStackTrace(); + status.setText(" | Status: Failed"); + } catch (Exception ex) { + ex.printStackTrace(); + status.setText(" | Status: Failed"); + } + } + private String doMath() { + if (elapsedTimes.size() < 1) { + return "Calculating..."; + } + + // Calculate the average elapsed time between points + long totalElapsedTime = 0; + for (long elapsedTime : elapsedTimes) { + totalElapsedTime += elapsedTime; + } + double averageTimePerTest = totalElapsedTime / (double) elapsedTimes.size() / 1e9; // convert to seconds + + // Estimate the remaining time + double estimatedRemainingTime = averageTimePerTest * testsLeft; + return String.format(" | ~Time Remaining: %.2f s", estimatedRemainingTime); + } + + private double performDownloadTest() throws Exception { + startButton.setText("Running"); + URL url = new URL("http://speedtest.tele2.net/20MB.zip"); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + int fileSize = connection.getContentLength(); + BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream()); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + + byte[] buffer = new byte[1024]; + long startTime = System.nanoTime(); + int bytesRead; + while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) { + byteArrayOutputStream.write(buffer, 0, bytesRead); + } + long endTime = System.nanoTime(); + double timeTaken = (endTime - startTime) / 1e9; // convert to seconds + + double downloadSpeed = (fileSize * 8) / (timeTaken * 1e6); // in Mbps + inputStream.close(); + return downloadSpeed; + } + + private double performUploadTest() throws Exception { + startButton.setText("Running"); + // Perform a real upload test + byte[] uploadData = new byte[3 * 1024 * 1024]; // 10 MB of data + URL url = new URL("https://httpbin.org/post"); // Replace with a valid endpoint + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + + long startTime = System.nanoTime(); + OutputStream outputStream = connection.getOutputStream(); + outputStream.write(uploadData); + outputStream.flush(); + outputStream.close(); + + int responseCode = connection.getResponseCode(); + long endTime = System.nanoTime(); + double timeTaken = (endTime - startTime) / 1e9; // convert to seconds + + if (responseCode == HttpURLConnection.HTTP_OK) { + double uploadSpeed = (uploadData.length * 8) / (timeTaken * 1e6); // in Mbps + return uploadSpeed; + } else { + throw new Exception("Failed to upload data: " + responseCode); + } + } + + } + + private class ElapsedTimeTask implements Runnable { + @Override + public void run() { + startTime = System.nanoTime(); + while (true) { + long elapsedTime = (System.nanoTime() - startTime) / 1_000_000_000; + status.setText(String.format(" | Elapsed Time: %d s", elapsedTime)); + etime = elapsedTime; + try { + Thread.sleep(1000); + //etime = (int) elapsedTime; + if (startButton.getText().equals("Complete")) { + break; + } + } catch (InterruptedException e) { + e.printStackTrace(); + break; + } + } + } + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(() -> { + InternetSpeedTest frame = new InternetSpeedTest(); + frame.setVisible(true); + }); + } +}