3

我编写了一个测试用户链接速度的 java 小程序。我收集了一些系统信息 prom 用户的计算机:CPU 负载、在 eth0 接口上下载的数据量以及使用 SIGAR API 的 NIC 卡最大速度。我将它部署在 Web 服务器上,但是当我尝试运行它时,我在 java 控制台中收到以下错误信息:

java.lang.reflect.InvocationTargetException
    at java.awt.EventQueue.invokeAndWait(Unknown Source)
    at speedtester_pkg.AppletMain.init(AppletMain.java:80)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ExceptionInInitializerError
    at speedtester_pkg.Test.<init>(Test.java:54)
    at speedtester_pkg.AppletMain.createGUI(AppletMain.java:282)
    at speedtester_pkg.AppletMain$1.run(AppletMain.java:82)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission sigar.nativeLogging read)
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
    at java.lang.System.getProperty(Unknown Source)
    at org.hyperic.sigar.Sigar.<clinit>(Sigar.java:78)
    ... 17 more

我不确定这是否由于小程序安全限制而被阻止,但是从 SIGAR 用户论坛(http://forums.hyperic.com/jiveforums/forum.jspa?forumID=2)我有印象,它是可以将它与 Web 应用程序一起使用。

这是我使用 Sigar API 的课程:

    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package speedtester_pkg;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

/**
 *  The logic of the speed test. Starts downloading threads and performs measurements.
 *
 * @author Karol Abramczyk
 */
public class Test implements Runnable{

    private ArrayList <String> urlsValues;
    private URL[] urls;
    private File[] files;
    private int stabilizationTimeSeconds, threadNo, allThreadsNo;
    private boolean continueDownload;
    public AppletMain applet;
    private Sigar sigar;
    private NetInterfaceStat nis;
    private long downloadedDataOld, downloadedDataNew, uploadedDataOld, uploadedDataNew, dataDownloaded,
            downloadingTime;
    private long startTime, stopTime;
    private double speed;
//    private String dir = "D:\\StraTJ_THD\\Abramczyk\\TestySpeedtestera\\";


    /**
     * Creates new instance of the Test object
     * @param gui the calling AppletGUI object
     * @param urlsVal the list of urls to files to download
     * @param time the time of the delay for line stabilization
     */
    public Test(AppletMain applet, ArrayList<String> urlsVal, int time){
        try {
            this.applet = applet;
            this.urlsValues = urlsVal;
            stabilizationTimeSeconds = time;
            allThreadsNo = urlsVal.size();
            AccessController.doPrivileged(new PrivilegedAction()
            { public Object run()
              {
                try {
                    sigar = new Sigar();
                    nis = sigar.getNetInterfaceStat("eth0");
                } catch (SigarException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
                return null;
              }
            });


            urls = new URL[allThreadsNo];
            for (int j = 0; j < allThreadsNo; j++) {
                    urls[j] = new URL(urlsValues.get(j));
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * returns number of bytes downloaded so far
     * @return number of bytes downloaded
     */
    private long getDownloadedDataSize()
    {
        return nis.getRxBytes()*8;
    }

    /**
     * returns number of bytes uploaded so far
     * @return number of bytes uploaded
     */
    private long getUploadedDataSize()
    {
        return nis.getTxBytes()*8;
    }

    /**
     * saves data on the test start: time, downloaded and uploaded number of bytes
     */
    private void getStartData()
    {
        downloadedDataOld = getDownloadedDataSize();
        uploadedDataOld = getUploadedDataSize();
        startTime = System.currentTimeMillis();
        System.out.println(nis.getRxBytes());
        System.out.println(downloadedDataOld);
    }

    /**
     * saves dataon the test stop: time, downloaded and uploaded number of bytes
     */
    private void getStopData()
    {
        stopTime = System.currentTimeMillis();
        downloadedDataNew = getDownloadedDataSize();
        uploadedDataNew = getUploadedDataSize();
    }

    /**
     * starts downloading all the files specified in input file
     * @throws java.io.IOException
     * @throws java.lang.InterruptedException
     */
    public void startDownload() throws IOException, InterruptedException{
        continueDownload = true;

        files = new File[allThreadsNo];
        for (int g = 0; g < allThreadsNo; g++) {
            String name = "speedTest" + g + "_";
            files[g] = File.createTempFile(name, null);
        }

        Thread[] threads = new Thread[allThreadsNo];
        for(int i=0; i<allThreadsNo;i++)
        {
            threadNo = i;
            threads[threadNo] = new Thread(new Download(this, threadNo));
            threads[threadNo].start();
        }

    }

    /**
     * preforms mesurements of speed ralated values as speed, cpu load, nic card speed
     * @throws org.hyperic.sigar.SigarException
     * @throws java.lang.InterruptedException
     */
    private void measure() throws SigarException, InterruptedException {

        measureCPUload();

        measureLinkSpeed();

        System.out.println(dataDownloaded);
        System.out.println(downloadingTime);
        System.out.println(speed);

        measureNICspeed();

    }

    /**
     * measures system CPU load and displays it in applet GUI
     * @throws org.hyperic.sigar.SigarException
     */
    private void measureCPUload() throws SigarException
    {
        CpuPerc cpuPerc = sigar.getCpuPerc();
        applet.setLabelProcessorLoad(CpuPerc.format(cpuPerc.getCombined()));
        applet.setCpuLoad(CpuPerc.format(cpuPerc.getCombined()));
    }

    /**
     * measures link speed as:
     * (number_of_bytes_downloaded_at_the_end - number_of_bytes_downloaded_at_the_beginning)/test_time
     * @throws org.hyperic.sigar.SigarException
     */
    private void measureLinkSpeed() throws SigarException
    {
        nis = sigar.getNetInterfaceStat("eth0");
        getStopData();
        dataDownloaded = downloadedDataNew-downloadedDataOld;
        downloadingTime = (stopTime - startTime)/1000;
        speed = dataDownloaded/downloadingTime;
        applet.setLabelLinkSpeed(formatSpeed(speed));
        applet.setSpeed(formatSpeed(speed));
    }

    /**
     * measures Network Card Interface speed
     * @throws org.hyperic.sigar.SigarException
     */
    private void measureNICspeed() throws SigarException
    {
        nis = sigar.getNetInterfaceStat("eth0");
        long nicSpeed = nis.getSpeed();
        applet.setLabelNIC(formatSpeed(nicSpeed));
        applet.setNICspeed(formatSpeed(nicSpeed));
    }

    /**
     * stops file download
     */
    private void stopDownload()
    {
        continueDownload = false;
    }

    /**
     * formats link speed to more readable format with units. For example "3.54324E7"
     * would be formatted to "35.0 Mb/s"
     * @param speed the link speed
     * @return the more readable link speed with units
     */
    public String formatSpeed(double speed)
    {
        double speedD;
        int speedI;

        if(speed>=1000000)
        {
            speedI = (int)speed/10000;
            speedD = speedI/100;
            return new String(speedD + " Mb/s");
        }
        else if(speed<1000000 && speed>=1000)
        {
            speedI = (int)speed/10;
            speedD = speedI/100;
            return new String(speedD + " Kb/s");
        }
        else
        {
            speedI = (int)speed*100;
            speedD = speedI/100;
            return new String(speedD + " b/s");
        }

    }

    /**
     * starts the test thread
     */
    public void run() {
        try {
            startDownload();
            getStartData();
            System.out.println("Sleep for " + stabilizationTimeSeconds + " seconds");
            Thread.sleep(stabilizationTimeSeconds * 1000);
            System.out.println("Sleep finished");
            measure();
            stopDownload();
            Thread.sleep(1000 * files.length / 2);
            //            removeDownloadedFiles();
        } catch (SigarException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public URL[] getUrls() {
        return urls;
    }

    public boolean isContinueDownload() {
        return continueDownload;
    }

    public File[] getFiles() {
        return files;
    }

    public int getStabilizationTimeSeconds() {
        return stabilizationTimeSeconds;
    }

}

这是我的第一个小程序,我对网络解决方案不是很熟悉,所以如果有人可以帮助我,我将不胜感激。我有许多类似主题的搜索者,但没有找到解决方案。我尝试使用 AccessCONtroller.do Priviliged() 方法,但效果不佳。我用小程序类签署了我的 jar 文件。我不确定是否应该签署这些 jar 库,应该吗?我的html文件如下:

<HTML>
<HEAD>
    <TITLE>Speed Test</TITLE>
</HEAD>
<BODY>


<P>
<APPLET 
    code="speedtester_pkg.AppletMain" 
    archive="SpeedTester.jar,activation.jar,mail.jar,mailapi.jar,sigar.jar,smtp.jar" 
    width=440     
    height=600>
</APPLET>
</P>

</BODY>
</HTML>
4

1 回答 1

3

需要信任小程序才能执行某些操作。要被信任,一个小程序(和其他依赖的罐子)必须是:

  1. 由开发人员进行数字签名(使用有效的代码签名证书)。
  2. 提示时由最终用户确定。通常,在向用户提出提示之前,预先警告用户对他们的要求(“出现提示时单击确定”)以及原因(“这样小程序可以运行”)是值得的。
于 2011-09-15T13:53:40.300 回答