I have written an app that should ping (use isReachable) for all the clients on the subnet the host sits on but I'm getting strange results when it is run on an XP machine (SP2) it fails to get all the hosts. It appears to be linked to threading as if I put in a join and effectively force the app to use one thread it works. It works fine in windows 7 and in ubuntu linux without the join so I'm a bit stumped as to why it falls over on XP. It's made up of two classes ill post them now. Also fairly new to java so hopefully it's nothing obvious. Thanks in advance.
Main.java
package subnetping;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
//Set this to your ip and netmask
Network myNetwork = new Network("192.168.1.33", 24);
Thread t = null;
for(String aHost : myNetwork.getClients()){
t = new Thread(new pinger(aHost));
t.start();
// Following makes it work on XP by forcing wait on thread
// try {
// t.join();
// } catch (InterruptedException ex) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
public static class pinger implements Runnable{
private String host;
private InetAddress address;
public pinger(String host){
this.host = host;
try {
address = InetAddress.getByName(host);
} catch (UnknownHostException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void run(){
try {
if (address.isReachable(3000)) {
System.out.println(host + " reachable");
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Network.java
package subnetping;
import java.util.ArrayList;
import java.util.List;
public class Network {
private String subnet = "";
private int subnetMask;
private List<String> myClients = new ArrayList<String>();
public Network(String hostIP, int subnetMask){
this.subnetMask = subnetMask;
this.subnet = getSubNet(hostIP, this.subnetMask);
createClients();
}
private String ipToBinary(String ipNumber){
String[] temp;
String binOctet1;
String binOctet2;
String binOctet3;
String binOctet4;
String ipAsBinary;
temp = ipNumber.split("\\.");
binOctet1 = padLeftToEight(Integer.toBinaryString(Integer.parseInt(temp[0])));
binOctet2 = padLeftToEight(Integer.toBinaryString(Integer.parseInt(temp[1])));
binOctet3 = padLeftToEight(Integer.toBinaryString(Integer.parseInt(temp[2])));
binOctet4 = padLeftToEight(Integer.toBinaryString(Integer.parseInt(temp[3])));
ipAsBinary = binOctet1 + binOctet2 + binOctet3 + binOctet4;
return ipAsBinary;
}
private String binaryToIP(String binaryIP){
return longToIP(Long.parseLong(binaryIP, 2));
}
private Long ipToLong (String ipNumber){
String[] temp;
String binOctet1;
String binOctet2;
String binOctet3;
String binOctet4;
Long ipAsLong;
temp = ipNumber.split("\\.");
binOctet1 = padLeftToEight(Integer.toBinaryString(Integer.parseInt(temp[0])));
binOctet2 = padLeftToEight(Integer.toBinaryString(Integer.parseInt(temp[1])));
binOctet3 = padLeftToEight(Integer.toBinaryString(Integer.parseInt(temp[2])));
binOctet4 = padLeftToEight(Integer.toBinaryString(Integer.parseInt(temp[3])));
ipAsLong = Long.parseLong((binOctet1 + binOctet2 + binOctet3 + binOctet4),2);
return ipAsLong;
}
private String longToIP (Long LongIP){
String binOctet1;
String binOctet2;
String binOctet3;
String binOctet4;
int intOctet1;
int intOctet2;
int intOctet3;
int intOctet4;
String fullBin;
String ipAsString;
fullBin = padLeftToThirtyTwo(Long.toBinaryString(LongIP));
binOctet1 = fullBin.substring(0, 8);
binOctet2 = fullBin.substring(8, 16);
binOctet3 = fullBin.substring(16, 24);
binOctet4 = fullBin.substring(24);
intOctet1 = Integer.parseInt(binOctet1, 2);
intOctet2 = Integer.parseInt(binOctet2, 2);
intOctet3 = Integer.parseInt(binOctet3, 2);
intOctet4 = Integer.parseInt(binOctet4, 2);
ipAsString = intOctet1 + "." + intOctet2 + "." + intOctet3 + "." + intOctet4;
return ipAsString;
}
private String padLeftToEight(String octet){
String paddedOctet = octet;
if(octet.length() == 8){
return octet;
}else{
for( int i = 1; i <= (8 - octet.length()); i++){
paddedOctet = "0" + paddedOctet;
}
return paddedOctet;
}
}
private String padLeftToThirtyTwo(String ipNumber){
String paddedIPNumber = ipNumber;
if(ipNumber.length() == 32){
return ipNumber;
}else{
for( int i = 1; i <= (32 - ipNumber.length()); i++){
paddedIPNumber = "0" + paddedIPNumber;
}
return paddedIPNumber;
}
}
private String padRightToThirtyTwo(String ipNumber){
String paddedIPNumber = ipNumber;
if(ipNumber.length() == 32){
return ipNumber;
}else{
for( int i = 1; i <= (32 - ipNumber.length()); i++){
paddedIPNumber = paddedIPNumber + "0";
}
return paddedIPNumber;
}
}
private String getSubNet(String ipNumber, int subnetMask){
for(int i = 0; i < subnetMask; i++){
subnet = subnet + ipToBinary(ipNumber).charAt(i);
}
return binaryToIP(padRightToThirtyTwo(subnet));
}
private void createClients(){
long subnetLong;
long clientRange;
clientRange = ((long) Math.pow(2L, (32L - subnetMask)) - 2);
subnetLong = ipToLong(this.subnet);
for(int i = 1; i <= clientRange; i ++){
myClients.add(longToIP(subnetLong + i));
}
}
public List<String> getClients(){
return myClients;
}
}
Have shelled out to ping to cure the problem it not only didn't work properly on XP the isReachable() failed on a few hosts that ping found. Wasn't an ideal solution as now it's platform dependant but will be running WMI queries so tied to windows anyway.
Thanks for looking.
Related
I have a file that contains more than one value in one column. I was trying to read this file using java with this code:
ArrayList<String> linesList1 = new ArrayList<>();
ArrayList<String> roadlinkid = new ArrayList<>();
ArrayList<String> road_name_orignal = new ArrayList<>();
ArrayList<String> road_name_copy = new ArrayList<>();
ArrayList<String[]> networkmember_href = new ArrayList<>();
ArrayList<String> road_fid = new ArrayList<>();
// Input of file which needs to be parsed
String csvFile1 = "RoadData.csv";
BufferedReader csvReader1;
// Data split by ',' in CSV file
String csvSplitBy = ",";
try {
String line;
csvReader1 = new BufferedReader(new FileReader(csvFile1));
while ((line = csvReader1.readLine()) !=null) {
linesList1.add(line);
}
csvReader1.close();
}
catch (IOException e) { e.printStackTrace(); }
for (int i = 0; i < linesList1.size(); i++) {
String[] data = linesList1.get(i).split(csvSplitBy);
road_fid.add( data[1]);
road_name_orignal.add( data[9]);
if (data[9].contains("{")) {
String[] xy = data[9].replaceAll("\\{|\\}", "").split(",");
int leng = xy.length;
String[] networkmember = new String [leng];
for ( int n = 0 ; n < leng ; n++) {
networkmember[n] = xy [n];
}
networkmember_href.add(networkmember);
}
}
This code works well, but the problem is that the code deals with each value in the column as a separate column. Therefore, it returns wrong data.
Files:
http://s000.tinyupload.com/?file_id=47090134488569683648
The idea is Finding the road name from RoadData.csv and write it in RoadLink.csv by comparing road_fid in RoadData.csv and roadlink_fid in RoadLink.csv. Unfortunately, I could find a way to deal with a column with multi-values. Any advice, please.
Thanks in advance.
Below is some code to parse the file, you can add additional processing to parse the fields that have lists in them or to combine the lists like changedate and reasonforchange into a list of Objects containing both pieces of data. For example a List<ChangeInfo> where ChangeInfo holds both the changedate and reasonforchange.
I still would recommend using a csv parser but this code should work well enough for this specific use case. Test thoroughly..
Main:
public static void main(String[] args){
List<RoadLinkRecord> records = parse("path\\to\\RoadLink.csv");
// display all the records
for (RoadLinkRecord record : records) {
System.out.println(record);
}
}
CSV Parsing:
private static final Pattern csvFieldPattern =
Pattern.compile("(?<=[$,])(\"(\"\"|[^\"])*\"|[^,]*)");
/** This parse method requires the CSV file to have a header row */
public static List<RoadLinkRecord> parse(String csvFilePath) {
// TODO accept Reader or maybe InputStream rather than file path
File f = new File(csvFilePath);
List<RoadLinkRecord> records = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(f));) {
// get the header fields
String line = br.readLine();
List<String> headers = new ArrayList<>();
{
Matcher matcher = csvFieldPattern.matcher(line);
while (matcher.find())
headers.add(matcher.group());
}
// iterate through record fields
int recordNum = 0;
while ((line = br.readLine()) != null) {
recordNum++;
// allocate array to hold the fields
String[] fields = new String[headers.size()];
// use matcher to get each of the fields
Matcher matcher = csvFieldPattern.matcher(line);
for (int i = 0; i < headers.size(); i++) {
if (!matcher.find()) {
throw new IllegalArgumentException(
"Couldn't find field '" + headers.get(i) + "' for record " + recordNum);
}
fields[i] = matcher.group();
}
if (matcher.find()) {
throw new IllegalArgumentException("Found excess fields in record " + recordNum);
}
// add the record from this line
records.add(new RoadLinkRecord(recordNum, fields));
}
} catch (IOException e) {
// TODO trouble reading the file
} catch (IllegalArgumentException e) {
// TODO error while parsing the file
}
return records;
}
Data Container:
public class RoadLinkRecord {
private final int recordNumber;
private final String roadlink_fid;
private final String version;
private final String versiondate;
private final String changedate;
private final String reasonforchange;
private final String descriptivegroup;
private final String descriptiveterm;
private final String natureofroad;
private final String length;
private final String directednode_href;
private final String directednode_orientation;
private final String directednode_gradeseparation;
private final String referencetotopographicarea_href;
private final String theme;
private final String filename;
private final String wkb_geometry;
private final String roadnumber;
private final String dftname;
private final String fid;
private final String roadname;
public RoadLinkRecord(final int recordNumber, final String[] csvFields) {
if (csvFields.length != 20) {
throw new IllegalArgumentException(
"Wrong number of fields for a RoadLinkRecord! Expected 20, found "
+ csvFields.length);
}
this.recordNumber = recordNumber;
this.roadlink_fid = processStringField(csvFields[0]);
this.version = processStringField(csvFields[1]);
this.versiondate = processStringField(csvFields[2]);
this.changedate = processStringField(csvFields[3]);
this.reasonforchange = processStringField(csvFields[4]);
this.descriptivegroup = processStringField(csvFields[5]);
this.descriptiveterm = processStringField(csvFields[6]);
this.natureofroad = processStringField(csvFields[7]);
this.length = processStringField(csvFields[8]);
this.directednode_href = processStringField(csvFields[9]);
this.directednode_orientation = processStringField(csvFields[10]);
this.directednode_gradeseparation = processStringField(csvFields[11]);
this.referencetotopographicarea_href = processStringField(csvFields[12]);
this.theme = processStringField(csvFields[13]);
this.filename = processStringField(csvFields[14]);
this.wkb_geometry = processStringField(csvFields[15]);
this.roadnumber = processStringField(csvFields[16]);
this.dftname = processStringField(csvFields[17]);
this.fid = processStringField(csvFields[18]);
this.roadname = processStringField(csvFields[19]);
}
private static String processStringField(String field) {
// consider empty fields as null
if (field.isEmpty()) {
return null;
}
// strip double quotes and replace any escaped quotes
final int endIndex = field.length() - 1;
if (field.charAt(0) == '"' && field.charAt(endIndex) == '"') {
return field.substring(1, endIndex).replace("\"\"", "\"");
}
return field;
}
public int getRecordNumber() { return recordNumber; }
public String getRoadlink_fid() { return roadlink_fid; }
public String getVersion() { return version; }
public String getVersiondate() { return versiondate; }
public String getChangedate() { return changedate; }
public String getReasonforchange() { return reasonforchange; }
public String getDescriptivegroup() { return descriptivegroup; }
public String getDescriptiveterm() { return descriptiveterm; }
public String getNatureofroad() { return natureofroad; }
public String getLength() { return length; }
public String getDirectednode_href() { return directednode_href; }
public String getDirectednode_orientation() { return directednode_orientation; }
public String getDirectednode_gradeseparation() { return directednode_gradeseparation; }
public String getReferencetotopographicarea_href() { return referencetotopographicarea_href; }
public String getTheme() { return theme; }
public String getFilename() { return filename; }
public String getWkb_geometry() { return wkb_geometry; }
public String getRoadnumber() { return roadnumber; }
public String getDftname() { return dftname; }
public String getFid() { return fid; }
public String getRoadname() { return roadname; }
#Override
public String toString() {
return "roadlink_fid= " + roadlink_fid + "; version= " + version + "; versiondate= "
+ versiondate + "; changedate= " + changedate + "; reasonforchange= "
+ reasonforchange + "; descriptivegroup= " + descriptivegroup + "; descriptiveterm= "
+ descriptiveterm + "; natureofroad= " + natureofroad + "; length= " + length
+ "; directednode_href= " + directednode_href + "; directednode_orientation= "
+ directednode_orientation + "; directednode_gradeseparation= "
+ directednode_gradeseparation + "; referencetotopographicarea_href= "
+ referencetotopographicarea_href + "; theme= " + theme + "; filename= " + filename
+ "; wkb_geometry= " + wkb_geometry + "; roadnumber= " + roadnumber + "; dftname= "
+ dftname + "; fid= " + fid + "; roadname= " + roadname + ";";
}
}
I am using java for sending streams at given rate(say 100 events/sec) via UDP to another receiver program. The receiver program has 2 threads. Thread 1 appends the values to List and another thread is checking is the list has some element and perform some action on it.
Earlier, I have been using a queue instead of a list. I was having issues with Iterator thread while checking if the queue has some element or not. It's a wired problem, I may be making some silly mistake. For this reason, I decided to use List, but I am having same issues now.
Can someone please tell me what am I doing wrong?
Code of Sender Program is
public class simpleGen {
public static void main(String[] args) throws IOException, InterruptedException {
Integer arrival_rate = 1;
Integer sleep_time = 1000/arrival_rate;
Long currentTime;
Integer value = null;
Integer Sensor_id;
Integer Patient_id;
Integer uid = 0;
Long count = 0L;
Integer time_in_sec = 60*2 ;
Integer lower_bound = 10;
Integer upper_bound = 20;
Long start_time = System.currentTimeMillis();
Long end_time = start_time + (1000 * time_in_sec);
int server_port = 8000;
DatagramSocket s = new DatagramSocket();
s.setSendBufferSize(2147483647);
InetAddress local = InetAddress.getByName("172.17.195.107");
while (System.currentTimeMillis() < end_time) {
uid = 1;
count += 1;
Random random = new Random(System.currentTimeMillis());
Patient_id = 1;
Sensor_id = 1;
currentTime = System.nanoTime();
value = lower_bound + random.nextInt((upper_bound - lower_bound) + 1);
Event event = new Event(Patient_id, Sensor_id, uid, currentTime, value);
String messageStr = event.toString();
// System.out.println(messageStr);
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
s.send(p);
System.out.print(" \r Sensor 1 count = " + count );
System.out.flush();
Thread.sleep(sleep_time );
}
Float inpt_rate = Float.valueOf(count)/time_in_sec;
System.out.println(" \n Average output rate = " + inpt_rate + " events/second" );
}
}
Code of Receiver Program is
public class Simplereceiver {
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static void main(String args[]) throws Exception
{
Queue<String> queue = new LinkedList<String>();
List<String> list = new ArrayList<String>();
Thread iterating_thread = new Thread(){
#Override
public void run() {
System.out.println( ANSI_BLUE + " iterating_thread started");
Boolean running = true ;
while(running){
if(list.size() > 0){
System.out.println("has element ----");
System.out.println(list.size());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}};
Thread receiving_thread = new Thread(){
#Override
public void run() {
Integer total_re_ECG = 0;
String[] sensor_value = new String[10];
String[] parsed_tuple = new String[10];
boolean run = true;
DatagramSocket udpSocket = null;
DatagramPacket packet = null;
try {
udpSocket = new DatagramSocket(8000);
udpSocket.setReceiveBufferSize(2147483647);
} catch (SocketException e) {
e.printStackTrace();
}
byte[] message = new byte[8000];
packet = new DatagramPacket(message, message.length);
System.out.println( ANSI_RED + " receiving_thread started");
while (run) {
try {
// Block until the host receives a UDP packet.
udpSocket.receive(packet);
String text = new String(message, 0, packet.getLength());
String[] tupleData = text.split(",");
int i = 0;
for (String tuple : tupleData) {
String[] tupleValue = tuple.split("=");
sensor_value[i] = tupleValue[1];
i += 1;
}// key pair of tuple ends
total_re_ECG += 1;
Integer patient_id = Integer.valueOf(sensor_value[0]);
Integer sensor_id = Integer.valueOf(sensor_value[1]);
Integer tuple_id = Integer.valueOf(sensor_value[2]);
Long generation_time = Long.valueOf(sensor_value[3]);
Float sensor1_data = Float.valueOf(sensor_value[4]);
Long event_arrival_time = System.nanoTime();
// System.out.println(event_arrival_time);
parsed_tuple[0] = total_re_ECG + "," + event_arrival_time ;
// queue.add(String.valueOf(sensor1_data));
list.add(String.valueOf(sensor1_data));
System.out.println("packet added is = " + parsed_tuple[0]);
} catch (IOException e) {
run = false;
}//catch
}//while
}
};
receiving_thread.start();
iterating_thread.start();
}//main
}//class
Using LinkedBlockingQueue solved my issue
Updated code for Iterator Thread is
Thread iterating_thread = new Thread(){
#Override
public void run() {
System.out.println( ANSI_BLUE + " iterating_thread started");
Boolean running = true ;
while(running){
if(!linkedBlockingQueue.isEmpty()){
System.out.println(linkedBlockingQueue.element());
linkedBlockingQueue.remove();
}
}
}};
I have a Java project that I am working for the school, and I am a beginner. For school, I have to create an authentication program, and for the most part, I figured it out on my own. However, I am having an issue implementing a three failed attempts, and you're locked out kind of thing. All while loops and if statements just mess up the program. I also need help re-initializing the program once it brings up the prompt of a correct user input. The main method is in another class but essentially all it does is it only asks the user for the username, and then it sends it to this class while this class does all the work. It needs to be polished as well, so there is a lot of unnecessary code that I will remove once I get the program running how I like.
package authenticationsystem;
import java.security.MessageDigest;
import java.io.*;
import java.util.*;
public class UserInfo {
private Scanner x;
private Scanner z;
private String user;
private String pass;
private String role;
private String hash;
private boolean trip = false;
public void userName(String name) throws Exception {
Scanner scnr = new Scanner(System.in);
String userLine, hashCode, password="", userPass, roleFile;
int quotes, quotes2, lineLength, usernameLength, hashLength;
int lineNumber = 0, i = 0;
user = name;
try{
x = new Scanner(new File("src\\authenticationsystem\\credentials.txt"));
}
catch(Exception e) {
System.out.println("could not find file");
}
while(x.hasNextLine()) {
userLine = x.nextLine();
if (userLine.contains(user)) {
usernameLength = user.length();
lineLength = userLine.length();
quotes = userLine.indexOf('\"');
quotes2 = userLine.lastIndexOf('\"');
//password = userLine.substring((quotes + 1), quotes2);
//System.out.println(password);
System.out.println(usernameLength + " " + lineLength);
System.out.println("Please enter your password");
userPass = scnr.nextLine();
//userPass = password;
hashCode = userLine.substring((usernameLength + 1), (usernameLength + 32));
roleFile = userLine.substring((quotes2 + 1), lineLength);
setPassword(userPass);
setHashCode(hashCode, roleFile);
user = userLine.substring(0, usernameLength);
}
else if (user.equals("Exit") || user.equals("exit")) {
System.exit(i);
}
lineNumber++;
}
}
String getName() {
return user;
}
public void setPassword(String passW) throws Exception {
pass = passW;
String original = passW; //Replace "password" with the actual password inputted by the user
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
hash = sb.toString();
}
public String getPassword() {
return pass;
}
public void setHashCode(String hashC, String roleF) {
AuthenticationSystem mane = new AuthenticationSystem();
Scanner scnr = new Scanner(System.in);
if (hash.contains(hashC)) {
if (roleF.contains("admin") || roleF.contains("Admin")) {
try{
z = new Scanner(new File("src\\authenticationsystem\\admin.txt"));
}
catch(Exception e) {
System.out.println("could not find file");
}
while(z.hasNext()) {
String a = z.nextLine();
String b = z.nextLine();
String c = z.nextLine();
System.out.printf("\n%s\n%s\n%s\n", a, b, c);
}
role = roleF;
}
else if (roleF.contains("veterinarian") || roleF.contains("Veterinarian")) {
try{
z = new Scanner(new File("src\\authenticationsystem\\veterinarian.txt"));
}
catch(Exception e) {
System.out.println("could not find file");
}
while(z.hasNext()) {
String a = z.nextLine();
String b = z.nextLine();
String c = z.nextLine();
System.out.printf("\n%s\n%s\n%s\n", a, b, c);
}
role = roleF;
}
else if (roleF.contains("zookeeper") || roleF.contains("Zookeeper")) {
try{
z = new Scanner(new File("src\\authenticationsystem\\zookeeper.txt"));
}
catch(Exception e) {
System.out.println("could not find file");
}
while(z.hasNext()) {
String a = z.nextLine();
String b = z.nextLine();
String c = z.nextLine();
System.out.printf("\n%s\n%s\n%s\n", a, b, c);
}
role = roleF;
}
}
else {
System.out.println("Invalid hash codes.");
}
}
public String getHashCode() {
return hash;
}
public void closeFile () {
x.close();
}
}
first of all, when you do a throw exception you don't need to try catch it. practically the throws exception works as a "i'll let another method to handle my exception".
Regarding on how you want to loop to prompt for the password you might want to use a switch case and use a counter variable to do the tries for it, so lets say it would be something like this:
int counter = 0;
do{
switch(counter){
case 1:
askForPass();
counter++;
break;
.
.
.
case 3:
askForPass();
counter++;
myBool = true;
}while(myBool == false);
Let me know if it worked!
I am developing a speed test app like OKLA app (http://www.speedtest.net/).
I've been trying to get bandwidth rate with the most common approach:
Get the time before downloading.
Download some file for some time X.
Get the time after downloading and the total size downloaded.
Calculate speed from TIME and BYTES RECEIVED.
Also, I execute this in two different threads at the same time because is required to saturate de connection to achieve good results.
This approach works very well on PC environment with this JAVA code:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class TestVelocidad {
static long totalBytesReceived = 0; //
static long startSample;
static long endSample ;
private static final long TIME_FOR_DOWNLOAD_MILISECONDS = (long) 10000.0;
private static final long MILI_TO_NANO = 1000000;
public static void main(String[] args) throws InterruptedException, ExecutionException {
try{
final ExecutorService service;
String downloadFileUrl100MB = "http://cachefly.cachefly.net/100mb.test";
startSample = System.nanoTime();
service = Executors.newFixedThreadPool(6);
FutureTask futureTask_1 = new FutureTask(new SpeedTestThread(downloadFileUrl100MB));
service.execute(futureTask_1);
FutureTask futureTask_2 = new FutureTask(new SpeedTestThread(downloadFileUrl100MB));
service.execute(futureTask_2);
service.shutdownNow();
long result1 = (Long) futureTask_1.get();
long result2 = (Long) futureTask_2.get();
endSample = System.nanoTime();
long timeSpent = (long) endSample-startSample;
long totalBytesReceived = result1 + result2;
System.out.println("Time of threads: " + timeSpent/1000000000.0 + " seconds " + "\nbytes received: " + (totalBytesReceived) );
double calculatedSpeed;
// long finalTimeSpent ;
// finalTimeSpent = (long) ((TIME_FOR_DOWNLOAD_MILISECONDS * MILI_TO_NANO - diff));
calculatedSpeed = SpeedInfo.calculate(timeSpent, totalBytesReceived).megabits;
System.out.println("Velocidad calculada: " + calculatedSpeed + " mbps" );
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class SpeedTestThread implements Callable<Long> {
private String url = new String("");
private static final long TIME_FOR_DOWNLOAD_NANOSECONDS = (long) 10000000000.0;
private static final long MILI_TO_NANO = 1000000;
private long bytesThread;
public SpeedTestThread(String urlToDownload){
url = urlToDownload;
}
public void run() {
}
#Override
public Long call() throws Exception {
System.out.println("FileDownload " + " File to download: " + url );
InputStream stream = null;
long startCon = System.nanoTime();
URL urlToDownload = null;
try {
urlToDownload = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection con = null;
try {
con = urlToDownload.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
con.setUseCaches(false);
//Tiempo de acceso al archivo.
long connectionLatency = (System.nanoTime() - startCon)/MILI_TO_NANO;
System.out.println("Connection latency = " + connectionLatency + "");
con.setConnectTimeout(5000);
try {
stream = con.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
long startNano = System.nanoTime();
int currentByte = 0;
try {
while ((currentByte = stream.read()) != -1 ) {
bytesThread++;
if ((System.nanoTime() - startNano) > TIME_FOR_DOWNLOAD_NANOSECONDS){
System.out.println("Time");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Thread bytes received: " + bytesThread);
return bytesThread;
}
}
class SpeedInfo {
public double kilobits = 0;
public double megabits = 0;
public double downspeed = 0;
private static final double BYTE_TO_KILOBIT = 0.008;
private static final double KILOBIT_TO_MEGABIT = 0.001;
/**
* 1 byte = 0.0078125 kilobits
* 1 kilobits = 0.0009765625 megabit
*
* #param downloadTime in miliseconds
* #param bytesIn number of bytes downloaded
* #return SpeedInfo containing current testVelocidadThread
*/
public static SpeedInfo calculate(final long downloadTime, final long bytesIn) {
SpeedInfo info = new SpeedInfo();
//from mil to sec
System.out.println("Bytes transferidos: " + bytesIn + "Tiempo de descarga: " + downloadTime/1000000000);
double time = downloadTime;
double byteIn1 = bytesIn;
double division = (double)(byteIn1 / time);
double bytespersecond = ((division) * 1000000000);
double kilobits = bytespersecond * BYTE_TO_KILOBIT;
double megabits = kilobits * KILOBIT_TO_MEGABIT;
info.downspeed = bytespersecond;
info.kilobits = kilobits;
info.megabits = megabits;
return info;
}
}
The problem is when I run this on a Android application, I had good results on phones with more processing and memory capacity, but poor results on phones with lower capacity.
Any good ideas to achieve good results on most android's phones?.
try to download the file with java nio rather than java io
java io transfer the file first to memory which make the performance poor on low end devices
while java nio using channels you can transfer the file to storage which will make the performance same on all devices approximately
use this code :
len = out.getChannel().transferFrom(readableByteChannel , seekPos , Long.MAX_VALUE);
I'm getting a NullPointerException error in Eclipse. Code as it stands right now:
Java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System. * ;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib() {}
public MadLib(String fileName) {
//load stuff
try {
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e) {
out.println("Houston we have a problem!");
}
}
public void loadNouns() {
nouns = new ArrayList < String > ();
try {
Scanner chopper = new Scanner("nouns.dat");
while (chopper.hasNext()) {
nouns.add(chopper.next());
}
chopper.close();
out.println(nouns);
}
catch(Exception e) {
out.println("Will");
}
}
public void loadVerbs() {
verbs = new ArrayList < String > ();
try {
Scanner chopper = new Scanner("verbs.dat");
while (chopper.hasNext()) {
verbs.add(chopper.next());
}
chopper.close();
}
catch(Exception e) {
out.println("run");
}
}
public void loadAdjectives() {
adjectives = new ArrayList < String > ();
try {
Scanner chopper = new Scanner("adjectives.dat");
while (chopper.hasNext()) {
adjectives.add(chopper.next());
}
chopper.close();
}
catch(Exception e) {}
}
public String getRandomVerb() {
String verb = "";
int num = 0;
num = (int)(Math.random() * verbs.size());
verb = verbs.get(num);
return verb;
}
public String getRandomNoun() {
String noun = "";
int num = 0;
num = (int)(Math.random() * nouns.size());
noun = nouns.get(num);
return noun;
}
public String getRandomAdjective() {
String adj = "";
int num = 0;
num = (int)(Math.random() * adjectives.size());
adj = adjectives.get(num);
return adj;
}
public String toString() {
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
Eclipse is pointing to the issue occurring at the linenum = (int)(Math.random()*nouns.size()); but this seems to not make much sense to me.
I have the private ArrayList<String> initialized at the method loadNouns. I origianlly had ArrayList<String> nouns initialized at getRandomNoun(), but that threw a different error, so I was advised to move the initialization statement to the loadNouns method.
Runner Class:
import static java.lang.System.*;
public class Lab16d
public static void main( String args[] ) {
//make a new MadLib
MadLib fun = new MadLib();
out.println(fun);
}
Update:
The real issue appears to be that ArrayList<String> nouns never is "loaded up" with the separate strings which are supposed to be scanned in from the nouns.dat file
Update 2:
Java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System. * ;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib() {
loadNouns();
loadVerbs();
loadAdjectives();
out.println(nouns);
}
public MadLib(String fileName) {
//load stuff
loadNouns();
loadVerbs();
loadAdjectives();
try {
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e) {
out.println("Houston we have a problem!");
}
}
public void loadNouns() {
nouns = new ArrayList < String > ();
try {
//nouns = new ArrayList<String>();
String nou = "";
Scanner chopper = new Scanner(new File("nouns.dat"));
//chopper.nextLine();
while (chopper.hasNext()) {
nou = chopper.next();
out.println(nou);
nouns.add(nou);
//chopper.nextLine();
}
//chopper.close();
out.println(nouns.size());
}
catch(Exception e) {
out.println("Will");
}
}
public void loadVerbs() {
verbs = new ArrayList < String > ();
try {
Scanner chopper = new Scanner(new File("verbs.dat"));
while (chopper.hasNext()) {
verbs.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e) {
out.println("run");
}
}
public void loadAdjectives() {
adjectives = new ArrayList < String > ();
try {
Scanner chopper = new Scanner(new File("adjectives.dat"));
while (chopper.hasNext()) {
adjectives.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e) {}
}
public String getRandomVerb() {
String verb = "";
int num = 0;
num = (int)(Math.random() * (verbs.size() - 1));
verb = verbs.get(num);
return verb;
}
public String getRandomNoun() {
String noun = "";
int num = 0;
if (nouns == null) {
loadNouns();
}
double rand = (Math.random());
num = (int)(rand * (nouns.size() - 1));
out.println(num);
noun = nouns.get((int) num);
out.print(noun);
return noun;
}
public String getRandomAdjective() {
String adj = "";
int num = 0;
num = (int)(Math.random() * (adjectives.size() - 1));
adj = adjectives.get(num);
return adj;
}
public String toString() {
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
You are creating an instance of MadLib, then printing the object in a println in your Runner class...
//make a new MadLib
MadLib fun = new MadLib();
out.println(fun);
The out.println calls the toString() method you overrode in MadLib...
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
Your MadLib object has 3 ArrayLists you never initialized, so they are null...
private ArrayList<String> verbs;
private ArrayList<String> nouns;
private ArrayList<String> adjectives
The easiest way to fix the NullPointerException is to initialize the variables....
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
However, what I really think you want to do is load all the nouns, verbs and adjectives when your object is constructed so your toString actually prints something useful. I'd add this to your constructor as well...
public MadLib() {
loadNouns();
loadVerbs();
loadAdjectives();
}
Edit: Your getRandom methods need to check if the list is empty to avoid the IndexOutOfBounds exception as well...
public String getRandomVerb() {
String verb = "";
if (!verbs.isEmpty()) {
int num = (int) (Math.random() * verbs.size() - 1);
verb = verbs.get(num);
}
return verb;
}
public String getRandomNoun() {
String noun = "";
if (!nouns.isEmpty()) {
int num = (int) (Math.random() * nouns.size() - 1);
noun = nouns.get(num);
}
return noun;
}
public String getRandomAdjective() {
String adj = "";
if (!adjectives.isEmpty()) {
int num = (int) (Math.random() * adjectives.size());
adj = adjectives.get(num);
}
return adj;
}
Hope that helps