How to convert ARP code of JAVA to Kotlin in Android - java

I am trying to get all the mac and IP from my android using the following code. But the following code only works in java. I want to use it in kotlin so I tried java to kotlin converter. But it didn't work. could anyone tell me how the following part of the code will be used in kotlin:
listNote.clear();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ip = splitted[0];
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
Node thisNode = new Node(ip, mac);
listNote.add(thisNode);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Auto conversion does not handle your while loop since "Assignments are not expression".
You can work around it by using built-in Readers extension function forEachLine, in which case each line is passed as the only argument to the lambda expression as it:
var bufferedReader: BufferedReader? = null
try {
bufferedReader = BufferedReader(FileReader("/proc/net/arp"))
bufferedReader.forEachLine {
val splitted = it.split(" +".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (splitted.size >= 4) {
val ip = splitted[0]
val mac = splitted[3]
if (mac.matches("..:..:..:..:..:..".toRegex())) {
listNote.add(Node(ip, mac))
}
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
bufferedReader?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
You can also remove FileNotFoundException since it's a subclass of IOException, and catch block is the same.

Related

Why I can't test for FileNotFoundException in java JUnit 4.13

I am facing some difficulties with testing constructor of my class using JUnit 4.13. What I am trying to do is to test that constructor is throwing FileNotFoundExeption when I pass wrong file name.
This is my constructor (parameter 'file' is name of file where I store languages):
public LanguageManager(String file) {
this.languages = new ArrayList<Language>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
String line;
while((line = in.readLine()) != null) {
line = line.trim();
if (line.equals("") || line.startsWith("#"))
continue;
Language j = new Language(line);
this.languages.add(j);
}
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my function for testing this constructor:
#Test(expected=FileNotFoundException.class)
public void testLanguageManager() {
LanguageManager ajm = new LanguageManager("non_existing_file.txt");
}
I suspect that there is problem with try catch block in constructor but can't figure out what I am doing wrong. Any help is appreciated.

How to eliminate having an ArrayIndexOutOfBoundExceptions in Java?

I have a Java program that reads from a cvs file that looks like this:
2000;Mall1;8
2002;Mall3;23
2003;Mall4;31
...
I want the program to read from the cvs file into an array and sort the array based on the third column/field.
However, whenever I print the elements of array[2] I get an ArrayIndexOutOfBoundException. I can't see why is this happening since the array's[2] size should be already fixed.
Here is the code:
import java.util.*;
import java.io.*;
public class Prog3
{
public static void main(String[] args)
{
String csvFile = "test.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] array = line.split(cvsSplitBy);
System.out.println(array[2]);
Arrays.sort(array[2]);
System.out.println("Sorted\n" + Arrays.toString(array[2]));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
finally {
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Any help is appreciated :)

Automated Telnet client using commons-net

My requirement is to connect to some server through telnet using a java program and run few commands and read the responses. Based on these responses I need to perform some operation
I strated with https://stackoverflow.com/a/1213188/1025328
I'm using commons-net and my program is something like this:
public class TelnetSample {
private TelnetClient telnet;
private InputStream in;
private PrintStream out;
public TelnetSample(String server, int port) {
try {
// Connect to the specified server
telnet = new TelnetClient();
telnet.connect(server, port);
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
public String readResponse() {
System.out.println("TelnetSample.readResponse()");
StringBuilder out = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(out.toString());
System.out.println("==========================================================");
return out.toString();
}
public String read2() {
System.out.println("TelnetSample.read()");
StringBuffer sb = new StringBuffer();
try {
int available = in.available();
for (int index = 0; index < available; index++) {
char ch = (char) in.read();
System.out.print(ch);
sb.append(ch);
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public String sendCommand(String command) {
try {
InputStream is = new ByteArrayInputStream(command.getBytes());
int ch;
while ((ch = is.read()) != -1) {
out.write(ch);
out.flush();
}
System.out.println(command);
String output = read2();
if (output.trim().isEmpty()) {
System.out.println("output empty");
} else {
System.out.println(output);
}
System.out.println("==========================================================");
return output;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
TelnetSample telnet = new TelnetSample("aspmx2.xxxxxx.com", 25);
telnet.readResponse();
telnet.sendCommand("Helo hi");
telnet.sendCommand("mail from:xyz#testmail.com");
telnet.sendCommand("rcpt to:pk#testmail.com");
telnet.sendCommand("quit");
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here apart form the telnet connection response, for every other sendCommand I'm getting an empty response. Can some one point me what could be the issue.
My output is something like this
TelnetSample.readResponse()
220 mx.xxxxxx.com ESMTP o86si4086625pfi.217 - gsmtp
==========================================================
Helo hi
TelnetSample.read()
output empty
==========================================================
mail from:xyz#testmail.com
TelnetSample.read()
output empty
==========================================================
rcpt to:pk#testmail.com
TelnetSample.read()
output empty
==========================================================
quit
TelnetSample.read()
output empty
==========================================================
This code has several issue:
the first issue is in readResponse method. When you use
readLine() you can easy block your code and will wait forever. Please have a look at discussion How to determine the exact state of a BufferedReader?
the second you don't send any CR/LF chars. Server got your requests like a single line. Ex:
mail from:xyz#testmail.comrcpt to:pk#testmail.comquit
To fix first issue you can choose several ways:
use multi-threading model
use NIO API. I would recommend Netty for that. Especially for your case as i can see you didn't use Telnet protocol at all, you connected to SMTP server.
Quick fix but the worst, wait first line from server and go on:
public String readResponse() {
System.out.println("TelnetSmtpSample.readResponse()");
StringBuilder out = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
out.append(reader.readLine());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(out.toString());
System.out.println("=====================");
return out.toString();
}
To fix second one:
telnet.sendCommand("Helo hi\r\n");
telnet.sendCommand("mail from:xyz#testmail.com\r\n");
telnet.sendCommand("rcpt to:pk#testmail.com\r\n");
telnet.sendCommand("quit\r\n");
It's possible read2 is getting a null value back from the input stream before data is actually returned. Try something like this:
private String read2() {
StringBuffer sb = new StringBuffer();
try {
do {
if (in.available() > 0) {
char ch = (char) in.read();
sb.append(ch);
} else {
Thread.sleep(1000);
}
} while (in.available()>0);
String output = new String(sb);
return output;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Avoid same try catch blocks in Java

I am developing a project which involves JSON manipulation in Java using JSON API. There are many places where I need to read values from JSON file. The API provides checked exceptions for the same. Everytime I use the API to read JSON values, I am forced to write try catch block. As a result, there is a large number of try catch blocks. It makes the code look messy.
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
}
catch(Exception e) {
System.out.println("File Not found");
}
try {
while((line = read.readLine() ) != null) {
Content = Content+line;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
ResponseArr = new JSONArray( Content );
} catch (JSONException e) {
e.printStackTrace();
}
try {
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
}
try {
StoreResponse = ResponseArr.getJSONObject(0).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
}
Is there any way to avoid this ?A single try catch block would not suffice and the statements are not dependent. Each read statement requires a separate try catch block as I have to log the details of places while catching the exception. Can I invoke a common method whenever I have a code to read JSON data, like sending the code as a paramater to a method which would take care of the exception handling or some other way round ?
Since (all?) the subsequent statements are dependent on the previous it makes no sense having that many try/catch blocks. I would rather put the code inside one try/catch and handle the exceptions by type
Pseudo-code:
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
} catch(FileNotFoundException)
System.out.println("File Not found");
}
// and so on
As some are suggesting, you might want to let all these exceptions bubble up (not catching them) since you're not doing anything meaningful when catching them. However, I think that depends on the calling context.
If you are handling all exceptions in the same way, why not combine them in one try/ catch clause
for example like this :
try {
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (Exception e) {
e.printStackTrace();
}
Try like this
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
catch(Exception e) {
System.out.println("File Not found");
}

execute shell command from android

I'm trying to execute this command from the application emulator terminal (you can find it in google play) in this app i write su and press enter, so write:
screenrecord --time-limit 10 /sdcard/MyVideo.mp4
and press again enter and start the recording of the screen using the new function of android kitkat.
so, i try to execute the same code from java using this:
Process su = Runtime.getRuntime().exec("su");
Process execute = Runtime.getRuntime().exec("screenrecord --time-limit 10 /sdcard/MyVideo.mp4");
But don't work because the file is not created. obviously i'm running on a rooted device with android kitkat installed. where is the problem? how can i solve? because from terminal emulator works and in Java not?
You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.
Try something like this:
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
}catch(IOException e){
throw new Exception(e);
}catch(InterruptedException e){
throw new Exception(e);
}
A modification of the code by #CarloCannas:
public static void sudo(String...strings) {
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
outputStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
(You are welcome to find a better place for outputStream.close())
Usage example:
private static void suMkdirs(String path) {
if (!new File(path).isDirectory()) {
sudo("mkdir -p "+path);
}
}
Update:
To get the result (the output to stdout), use:
public static String sudoForResult(String...strings) {
String res = "";
DataOutputStream outputStream = null;
InputStream response = null;
try{
Process su = Runtime.getRuntime().exec("su");
outputStream = new DataOutputStream(su.getOutputStream());
response = su.getInputStream();
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
res = readFully(response);
} catch (IOException e){
e.printStackTrace();
} finally {
Closer.closeSilently(outputStream, response);
}
return res;
}
public static String readFully(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString("UTF-8");
}
The utility to silently close a number of Closeables (Soсket may be no Closeable) is:
public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
// Note: on Android API levels prior to 19 Socket does not implement Closeable
for (Object x : xs) {
if (x != null) {
try {
Log.d("closing: "+x);
if (x instanceof Closeable) {
((Closeable)x).close();
} else if (x instanceof Socket) {
((Socket)x).close();
} else if (x instanceof DatagramSocket) {
((DatagramSocket)x).close();
} else {
Log.d("cannot close: "+x);
throw new RuntimeException("cannot close "+x);
}
} catch (Throwable e) {
Log.x(e);
}
}
}
}
}
Process p;
StringBuffer output = new StringBuffer();
try {
p = Runtime.getRuntime().exec(params[0]);
BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
p.waitFor();
}
}
catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
String response = output.toString();
return response;
Late reply, but it will benefit someone. You can use the sh command in the exec() method.
Here is my example:
try {
File workingDirectory = new File(getApplicationContext().getFilesDir().getPath());
Process shProcess = Runtime.getRuntime().exec("sh", null, workingDirectory);
try{
PrintWriter outputExec = new PrintWriter(new OutputStreamWriter(shProcess.getOutputStream()));
outputExec.println("PATH=$PATH:/data/data/com.bokili.server.nginx/files;export LD_LIBRARY_PATH=/data/data/com.bokili.server.nginx/files;nginx;exit;");
outputExec.flush();
} catch(Exception ignored){ }
shProcess.waitFor();
} catch (IOException ignored) {
} catch (InterruptedException e) {
try{ Thread.currentThread().interrupt(); }catch(Exception ignored){}
} catch (Exception ignored) { }
What have I done with this?
First I call the shell, then I change (set) the necessary environments in it, and finally I start my nginx with it.
This works on unrooted devices too.
Greetings.

Categories