Skip to content

Commit

Permalink
comm/iridium/HubIridiumMessenger: Avoid potential null pointer and cl…
Browse files Browse the repository at this point in the history
…eanups.
  • Loading branch information
paulosousadias committed Jul 25, 2024
1 parent 13b41fd commit f32da94
Showing 1 changed file with 46 additions and 90 deletions.
136 changes: 46 additions & 90 deletions src/java/pt/lsts/neptus/comm/iridium/HubIridiumMessenger.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,11 @@ public class HubIridiumMessenger implements IridiumMessenger {
protected String messagesUrl = serverUrl+"iridium";
protected int timeoutMillis = 10000;
protected HashSet<IridiumMessageListener> listeners = new HashSet<>();
private static Pattern p = Pattern.compile("\\((.)\\) \\((.*)\\) (.*) / (.*), (.*) / .*");
private static TimeZone tz = TimeZone.getTimeZone("UTC");
private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private static final Pattern p = Pattern.compile("\\((.)\\) \\((.*)\\) (.*) / (.*), (.*) / .*");
private static final TimeZone tz = TimeZone.getTimeZone("UTC");
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
static { dateFormat.setTimeZone(tz); }

// protected Thread t = null;

// public HubIridiumMessenger() {
// startPolling();
// }

public DeviceUpdate pollActiveDevices() throws Exception {
Gson gson = new Gson();
URL url = new URL(activeSystemsUrl);
Expand All @@ -108,55 +102,22 @@ public DeviceUpdate pollActiveDevices() throws Exception {
for (HubSystemMsg s : sys) {
if (s.imcid > Integer.MAX_VALUE)
continue;

Date date = stringToDate(s.updated_at);
if (date == null)
date = new Date();
Position pos = new Position();
pos.id = (int) s.imcid;
pos.latRads = s.coordinates[0];
pos.lonRads = s.coordinates[1];
pos.timestamp = stringToDate(s.updated_at).getTime() / 1000.0;
pos.timestamp = date.getTime() / 1000.0;
pos.posType = PosType.Unknown;
up.getPositions().put(pos.id, pos);
}

return up;
}

// public void startPolling() {
// if (t != null)
// stopPolling();
// t = new Thread("Hub Iridium message updater") {
// @Override
// public void run() {
// Date lastTime = null;
// while (true) {
// try {
// Thread.sleep(60 * 1000);
//
// if (lastTime == null)
// lastTime = new Date(System.currentTimeMillis() - (3600 * 1000));
//
// Collection<IridiumMessage> newMessages = pollMessages(lastTime);
// lastTime = new Date();
//
// for (IridiumMessage m : newMessages)
// for (IridiumMessageListener listener : listeners)
// listener.messageReceived(m);
// }
// catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// };
// t.setDaemon(true);
// t.start();
// }

// public void stopPolling() {
// if (t != null)
// t.interrupt();
// t = null;
// }
//
@Override
public void addListener(IridiumMessageListener listener) {
listeners.add(listener);
Expand Down Expand Up @@ -184,20 +145,21 @@ public void sendMessage(IridiumMessage msg) throws Exception {
conn.setRequestProperty ("Authorization", authKey);
}

OutputStream os = conn.getOutputStream();
os.write(data);
os.close();
try (OutputStream os = conn.getOutputStream()) {
os.write(data);
}

NeptusLog.pub().info(messagesUrl+" : "+conn.getResponseCode()+" "+conn.getResponseMessage());
NeptusLog.pub().info("{} : {} {}", messagesUrl, conn.getResponseCode(), conn.getResponseMessage());

InputStream is = conn.getInputStream();
ByteArrayOutputStream incoming = new ByteArrayOutputStream();
IOUtils.copy(is, incoming);
is.close();

NeptusLog.pub().info("Sent "+msg.getClass().getSimpleName()+" through HTTP: "+conn.getResponseCode()+" "+conn.getResponseMessage());
try {
logHubInteraction(msg.getClass().getSimpleName()+" ("+msg.getMessageType()+")", messagesUrl, conn.getRequestMethod(), ""+conn.getResponseCode(), ByteUtil.encodeToHex(msg.serialize()), new String(incoming.toByteArray()));
try (InputStream is = conn.getInputStream(); ByteArrayOutputStream incoming = new ByteArrayOutputStream()) {
IOUtils.copy(is, incoming);

NeptusLog.pub().info("Sent {} through HTTP: {} {}", msg.getClass().getSimpleName(),
conn.getResponseCode(), conn.getResponseMessage());

logHubInteraction(msg.getClass().getSimpleName()+" ("+msg.getMessageType()+")", messagesUrl,
conn.getRequestMethod(), ""+conn.getResponseCode(), ByteUtil.encodeToHex(msg.serialize()),
incoming.toString());
}
catch (Exception e) {
NeptusLog.pub().error(e);
Expand All @@ -210,9 +172,9 @@ public void sendMessage(IridiumMessage msg) throws Exception {

public synchronized void logHubInteraction(String message, String url, String method, String statusCode, String requestData, String responseData) throws Exception {
if (! (new File("log/hub.log")).exists()) {
BufferedWriter tmp = new BufferedWriter(new FileWriter(new File("log/hub.log"), false));
tmp.write("Time of Day, Message Type, URL, Method, Status Code, Request Data (hex encoded), Response Data\n");
tmp.close();
try (BufferedWriter tmp = new BufferedWriter(new FileWriter(new File("log/hub.log"), false))) {
tmp.write("Time of Day, Message Type, URL, Method, Status Code, Request Data (hex encoded), Response Data\n");
}
}

BufferedWriter postWriter = new BufferedWriter(new FileWriter(new File("log/hub.log"), true));
Expand All @@ -231,15 +193,14 @@ public synchronized void logHubInteraction(String message, String url, String me

@Override
public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {
NeptusLog.pub().info("Polling messages since {}", dateToString(timeSince));

NeptusLog.pub().info("Polling messages since "+dateToString(timeSince));

String since = null;
if (timeSince != null)
since = dateToString(timeSince);
URL u = new URL(messagesUrl+"?since="+(timeSince.getTime()/1000));
if (since == null)
URL u;
if (timeSince != null) {
u = new URL(messagesUrl + "?since=" + (timeSince.getTime() / 1000));
} else {
u = new URL(messagesUrl);
}
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod( "GET" );
Expand All @@ -251,10 +212,12 @@ public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), baos);

logHubInteraction("Iridium Poll", u.toString(), conn.getRequestMethod(), ""+conn.getResponseCode(), "", new String(baos.toByteArray()));
logHubInteraction("Iridium Poll", u.toString(), conn.getRequestMethod(), ""
+ conn.getResponseCode(), "", baos.toString());

if (conn.getResponseCode() != 200)
throw new Exception("Hub iridium server returned "+conn.getResponseCode()+": "+conn.getResponseMessage());

HubMessage[] msgs = gson.fromJson(baos.toString(), HubMessage[].class);

Vector<IridiumMessage> ret = new Vector<>();
Expand All @@ -264,7 +227,6 @@ public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception
ret.add(m.message());
}
catch (Exception e) {

String report = new String(Hex.decodeHex(m.msg.toCharArray()));
Matcher matcher = p.matcher(report);
if (matcher.matches()) {
Expand All @@ -273,8 +235,8 @@ public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception
String latMins = matcher.group(4);
String lonMins = matcher.group(5);

String latParts[] = latMins.split(" ");
String lonParts[] = lonMins.split(" ");
String[] latParts = latMins.split(" ");
String[] lonParts = lonMins.split(" ");
double lat = getCoords(latParts);
double lon = getCoords(lonParts);
long timestamp = parseTimeString(timeOfDay).getTime();
Expand All @@ -284,8 +246,8 @@ public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception
if (system != null) {
system.setLocation(new LocationType(lat, lon), timestamp);
}
NeptusLog.pub().info("Text report: "+report);

NeptusLog.pub().info("Text report: {}", report);
}

IridiumCommand msg = new IridiumCommand();
Expand Down Expand Up @@ -364,7 +326,6 @@ public Date updatedAt() {
}

public static class HubSystemMsg {

public long imcid;
public String name;
public String updated_at;
Expand All @@ -386,27 +347,22 @@ public void cleanup() {
listeners.clear();
//stopPolling();
}


@Override
public String toString() {
return getName();
}

public static void main(String[] args) throws Exception {
GeneralPreferences.ripplesUrl = "https://ripples.lsts.pt";

HubIridiumMessenger messenger = new HubIridiumMessenger();
Date d = new Date(System.currentTimeMillis() - (1000 * 3600 * 5));

System.out.println(dateToString(d));
System.out.println(d.getTime());
Collection<IridiumMessage> msgs = messenger.pollMessages(d);
System.out.println(msgs.size());
msgs.stream().forEach(m -> {
System.out.println(m.asImc());
});



}

@Override
public String toString() {
return getName();
msgs.forEach(m -> System.out.println(m.asImc()));
}
}

0 comments on commit f32da94

Please sign in to comment.