I want to compare the response from the server with a string, but I get a false result when testing the two strings. Why?
I found this but didn't help: How do I compare strings in Java?
I tried two ways:
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
String code;
if(Objects.equals((code = in.readLine()), "S")) { //Input string: "S"
//code
}
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
String code;
if((code = in.readLine()).equals("S")) { //Input string: "S"
//code
}
The code does not run in either case because the value of the test is false.
Full code
Server side - C# (Windows)
class ManagePhoneClients
{
public void managePhoneClients(object obj)
{
Boolean socketalive = true;
TcpClient tcpClient = (TcpClient)obj;
StreamReader sr = new StreamReader(tcpClient.GetStream(), Encoding.UTF8);
StreamWriter sw = new StreamWriter(tcpClient.GetStream(), Encoding.UTF8);
Boolean isPhoneClientConnected = false;
String user;
String answer;
String tl;
List<string> LC = new List<string>();
Boolean qss = false;
Program program = new Program();
Int32 points = 0;
ConsoleMethods.writeLine("Thread started for the phone client.", "Info", ConsoleColor.Cyan);
sw.WriteLine("S");
sw.Flush();
while (socketalive == true)
{
try
{
if (Program.isMainClientConnected != true || Program.isPowerPointConnected != true)
{
ConsoleMethods.writeLine("Connection refused because the necessary clients are not connected!", "Error", ConsoleColor.Red);
sw.WriteLine("NS");
sw.Flush();
tcpClient.Close();
socketalive = false;
}
else
{
sw.WriteLine("LC");
sw.Flush();
}
if (isPhoneClientConnected != true & sr.Peek() != -1)
{
String rLC = sr.ReadLine();
LC.AddRange(rLC.Split('|'));
if (LC[1].ToString() == Program.passPhoneClient)
{
user = LC[0];
Program.userNames.Add(user);
ConsoleMethods.writeLine("Phone connected from: " + tcpClient.Client.RemoteEndPoint, "Info", ConsoleColor.Cyan);
sw.WriteLine("S");
sw.Flush();
Program.utnr = rLC;
isPhoneClientConnected = true;
}
else
{
sw.WriteLine("NS");
sw.Flush();
socketalive = false;
ConsoleMethods.writeLine("Phone client disconnected because the password was invalid!", "Error", ConsoleColor.Red);
}
}
switch (sr.ReadLine())
{
case "CLIENT-EXCEPTION":
ConsoleMethods.writeLine("Exception in phone client from: " + tcpClient.Client.RemoteEndPoint + "\n" + sr.ReadLine(), "Client-Error", ConsoleColor.DarkRed);
break;
case "RECEIVED_POINTS":
int point = int.Parse(sr.ReadLine());
points += point;
ConsoleMethods.writeLine("Phone client succesfully completed a task from: " + tcpClient.Client.RemoteEndPoint + " Point: " + point, "Client-Received Points", ConsoleColor.DarkRed);
ConsoleMethods.writeLine("Phone client collected points from: " + tcpClient.Client.RemoteEndPoint + " Points: " + points, "Client-Collected Points", ConsoleColor.DarkRed);
break;
}
}
catch (Exception e)
{
tcpClient.Close();
socketalive = false;
ConsoleMethods.writeLine(e.Message + e.StackTrace + e.StackTrace, "Error", ConsoleColor.Red);
}
}
}
}
(This is not yet complete!)
Client side - Java (Android)
public void login(View v) {
final Context context = this;
new Thread(new Runnable() {
public void run() {
try {
final Socket socket = new Socket("192.168.0.104", 90);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print("P" + "\r\n");
out.flush();
String code;
code = in.readLine();
if(code.equals("S")) {
if (Objects.equals((code = in.readLine()), "LC")) {
out.print(((EditText)findViewById(R.id.username)).getText().toString() + "|" + ((EditText)findViewById(R.id.password)).getText().toString() + "\r\n");
out.flush();
if(Objects.equals((code = in.readLine()), "S")) {
new ServerContact(context).Listener(socket);
startActivity(new Intent(Login.this, Waiting.class));
} else {
throw new Exception("Login failed because the server refused the login request. Server responded with status code: '" + code + "'.");
}
} else {
throw new Exception("Login failed because the server refused the login request. Server responded with status code: '" + code + "'.");
}
} else {
throw new Exception("Login failed because the server refused the login request. Server responded with status code: '" + code + "'.");
}
} catch (Exception e) {
new ExceptionWriter(e);
}
}
}).start();
}
(This is not yet complete!)
I managed to solve it. On the server side I have to disable the BOM.
No BOM:
StreamWriter sw = new StreamWriter(tcpClient.GetStream(), new UTF8Encoding(false));
With BOM:
StreamWriter sw = new StreamWriter(tcpClient.GetStream(), Encoding.UTF8);
It works for me (using your first case). I think we've all concluded that code is not in fact equal to "S", sorry about that.
public class EqualsTest {
public static void main( String[] args ) throws IOException {
MyStream socket = new MyStream( new ByteArrayInputStream( "S\n".getBytes() ));
BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream(), "UTF8" ) );
String code;
if( Objects.equals( (code = in.readLine()), "S" ) ) {
System.out.println( "true" );
} else {
System.out.println( "false" );
}
}
static class MyStream {
private final InputStream ins;
public MyStream( InputStream ins ) {
this.ins = ins;
}
public InputStream getInputStream() {
return ins;
}
}
}
Output:
run:
true
BUILD SUCCESSFUL (total time: 0 seconds)
I'll add some ideas for testing code for debugging:
// how to debug
System.err.println( "code="+code+" length="+code.length() );
System.err.println( "code bytes="+Arrays.toString( code.getBytes() ) );
Related
The need:
I want to write data into compressed and normal format as well. When I'll have to write data into compressed format "useCompression" will be sent as "true" and "useCompression" will be false when data needs to be stored in normal(as it is given to the Writer class) format.
The problem here is, how will I identify whether the data is compressed or not later when Reader class is trying to read the data?
So, to solve the problem, I am writing "1" into file if is "useCompression" is true and "0" if "useCompression" is false.
writing is fine, but when we try to skip the first element using "fIn.skip(1)" cause it is the identifier and not actual data, it is leaving behind some garbage value.
For, example, I am trying to write "2019-07-31" into a file and "useCompression" is false, so my file will hold "02019-07-31" and post "fIn.skip(1)" call it should hold "2019-07-31" but it is holding "^#2019-07-31".
Please help me figure out what I am doing wrong here
I've tried to update Reader class's constructor as:
public Reader(String key)
{
mKey = key;
try {
FileInputStream fIn = new FileInputStream(streamFileForKey(key));
byte[] firstByte = new byte[1];
int read = fIn.read(firstByte);
boolean shouldUseDecompression = (1 == firstByte[0]);
if (shouldUseDecompression) {
mFin = new GZIPInputStream(fIn);
}
else {
mFin = fIn;
}
}
catch (Exception e) {
System.out.println("Failed to open (r) key " + key + " exception : " + e);
}
}
But it does not solve the problem.
The actual code is:
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.GZIPInputStream;
public class forStackOverflow {
public static void main(String []args) {
// Write to normal file
mReader1 = new Reader(mInputFileName);
mWriter1 = new Writer(mOutputFilename1, false);
int availableBytes = mReader1.availableBytes();
int readBytes = 1000;
while (availableBytes > 0)
{
if (availableBytes >= 1000) {
availableBytes = availableBytes - readBytes;
}
else {
readBytes = availableBytes;
availableBytes = availableBytes - readBytes;
}
mWriter1.write(mReader1.read(readBytes), 0, readBytes);
}
mReader1.close();
mWriter1.close();
}
private static File streamFileForKey(String key)
{
return new File(key);
}
static String mInputFileName = "~/Downloads/inputStream.txt";
static String mOutputFilename1 = "~/Downloads/outputStream.txt";
static Reader mReader1;
static Writer mWriter1;
private static class Writer
{
public Writer(String key, boolean useCompression) {
mKey = key;
try {
FileOutputStream fileOutput = new FileOutputStream(streamFileForKey(key));
if (useCompression) {
fileOutput.write(1);
gOutputStream = new GZIPOutputStream(fileOutput);
}
else {
fileOutput.write(0);
gOutputStream = new DataOutputStream(fileOutput);
}
}
catch (Exception e) {
System.out.println("Got error while opening stream for " + mKey + ". Ex: " + e);
}
}
public boolean write(byte[] bytes, int pos, int len)
{
boolean retVal = true;
if (gOutputStream == null) {
return false;
}
try {
gOutputStream.write(bytes, pos, len);
retVal = true;
}
catch (Exception e) {
System.out.println("Failed to write " + len + " bytes to key " +
mKey + e);
retVal = false;
}
return retVal;
}
public void close()
{
if (gOutputStream != null) {
try {
gOutputStream.close();
}
catch (Exception e) {
System.out.println("Failed to close key " + mKey + e);
}
gOutputStream = null;
}
}
private String mKey;
private OutputStream gOutputStream;
}
private static class Reader
{
public Reader(String key)
{
mKey = key;
try {
FileInputStream fIn = new FileInputStream(streamFileForKey(key));
if (shouldUseDecompression()) {
long skipped = fIn.skip(1);
mFin = new GZIPInputStream(fIn);
}
else {
long skipped = fIn.skip(1);
mFin = fIn;
}
}
catch (Exception e) {
System.out.println("Failed to open (r) key " + key + " exception : " + e);
}
}
public byte[] read(int len)
{
if (mFin == null) {
return null;
}
byte[] b = null;
try {
b = new byte[len];
int read;
read = mFin.read(b, 0, len);
if (read <= 0) {
return null;
}
}
catch (Exception e) {
System.out.println("Failed to read " + len + " bytes from key " +
mKey + " exception : " + e);
}
return b;
}
public void close()
{
if (mFin != null) {
try {
mFin.close();
}
catch (Exception e) {
System.out.println("Failed to close key " + mKey + " exception : " + e);
}
mFin = null;
}
}
private boolean shouldUseDecompression()
{
boolean retVal = false;
try {
FileInputStream fIn = new FileInputStream(streamFileForKey(mKey));
byte[] firstByte = new byte[1];
int read = fIn.read(firstByte);
// If first byte is `1` the we need to use decompression on it.
retVal = (1 == firstByte[0]);
fIn.close();
}
catch(Exception e) {
System.out.println("Exception in shouldUseDecompression() : " + e);
retVal = false;
}
return retVal;
}
public int availableBytes()
{
int available = 0;
try {
if (mFin != null) {
available = mFin.available();
}
}
catch (IOException e) {
System.out.println("Failed to read available bytes for " + mKey + ". Exception : " + e);
}
return available;
}
private String mKey;
private InputStream mFin;
}
}
The expected result should be, post "fIn.skip(1)" call file should hold "2019-07-31" and not "^#2019-07-31".
After a lot of struggle, I found out that it was the expected result.
^# was nothing but the binary 0 I was writing from Writer class's constructor incase useCompression was false.
From line fileOutput.write(0);.
I need to implement a program to transfer files. I decided to make it using a chat template I've made about 1 month ago so I would have a chat with file transfer option.
The transfer should follow the following points:
1- Server only keeps a list of all files provided by connected clients (No file are actually located in the server, only their names)
2- Client "1" requests file "A" then:
if file "A" is located ONLY in client "2", then client "2" should send 100% of the file to client "1"
if file "A" is located in client "2" and client "3" also has file "A", then client "2" should send 50% of the file to client "1" and client "3" should send the other 50%.
(if the file is located in 4 clients it should be 25% each....and so it goes...)
I've already managed to make the server find out which client is requesting the file and which clients have it. But now I'm stuck, I don't know how to make the transfer.
Could someone give me an example of how to do it? or point me through the right direction?
[I'm aware my code has some flaws and I will fix it later, right now I need to make the transfer happen before working on fixes, so please, unless it's related, try to focus on that]
Server:
package tor;
import java.util.*;
import java.io.*;
import java.net.*;
public class Server extends Thread {
private String cname;
private Socket client;
public static Vector<PrintStream> clients;
public static Vector<String> clientnames;
public static Vector<String> archives;
public Server(Socket client) {
this.client = client;
}
public static void main(String[] args) {
clients = new Vector<PrintStream>();
clientnames = new Vector<String>();
archives = new Vector<String>();
try {
ServerSocket server = new ServerSocket(2391);
System.out.println("Server Started!!\n");
while (true) {
Socket client = server.accept();
Server s = new Server(client);
s.start();
}
} catch (IOException e) {
System.out.println("Server could not start ");
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream out = new PrintStream(client.getOutputStream());
cname = in.readLine();
System.out.println(cname + " Connected --- SERVER!");
if (cname == null) {
System.out.println("Unknown Name");
return;
}
clientnames.add(cname);
clients.add(out);
connected(" ********** [", cname, "] Connected! **********");
String arq;
int size = in.read();
System.out.println(size);
for (int i = 0; i < size; i++) {
arq = in.readLine();
archives.add(arq);
}
String msg = in.readLine();
String selected;
while (true) {
while (!(msg).equals("/exit") && !(msg).equals("/Exit") && !(msg).equals("/EXIT")) {
if ((msg).equals("/list") || (msg).equals("/List") || (msg).equals("/list")) {
out.println("-------- Archives List --------");
for (int i = 0; i < archives.size(); i++) {
out.println(i+"- "+archives.get(i));
}
out.println("-------- ******************* --------");
msg = in.readLine();
} else if (msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))){
msg = in.readLine();
int gnum = Integer.parseInt(msg);
selected=archives.get(gnum);
returnAll("[", out, "]: ", "idreq");
out.println("1");
reqAll(selected);
// I BELIVE HERE IS THE RIGHT PLACE TO MAKE DE TRANSFER CODE
msg = in.readLine();
} else {
returnAll("[", out, "]: ", msg);
msg = in.readLine();
}
}
msg = in.readLine();
size = Integer.parseInt(msg);
for (int i = 0; i <= size; i++) {
arq = in.readLine();
for(int j=0;j<archives.size();j++) {
if (archives.get(j).equals(arq)) {
archives.remove(j);
}
}
}
returnAll(" ********** [", out, "] disconnected ", " ********** ");
clients.remove(out);
clientnames.remove(cname);
client.close();
break;
}
} catch (IOException e) {
System.out.println("A Client disconnected ");
}
}
// METHOD TO SEND CONNECTION MESSAGE
public void connected(String msg1, String cname, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + msg2);
}
}
// METHOD TO RETURN MESSAGE TO ALL CLIENTS
public void returnAll(String msg1, PrintStream saida, String ac, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + ac + msg2);
}
}
public void reqAll(String req) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(req);
}
}
}
Client:
package tor;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Client extends Thread {
private Socket con;
private static boolean done = false;
static ArrayList<String> localArq = new ArrayList<String>();
static int c=0;
public Client(Socket s) {
con = s;
}
public static void main(String[] args) {
try {
String ip;
Scanner s = new Scanner(System.in);
System.out.print("Enter Server's IP: ");
ip =s.next();
Socket con = new Socket(ip, 2391);
PrintStream out = new PrintStream(con.getOutputStream());
System.out.println("Connected to Server!");
System.out.print("Enter your Nickname: ");
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
String cname = scan.readLine();
out.println(cname);
String dir="C:\\javator\\"+cname;
Thread t = new Client(con);
t.start();
File folder = new File(dir);
folder.mkdir();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
localArq.add(listOfFiles[i].getName());
}
}
int size=localArq.size();
out.write(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
String msg;
while (true) {
System.out.print("");
msg = scan.readLine();
if(msg.equals("/ll")) {
System.out.println("-------- LOCAL LIST --------");
for (int i = 0; i < localArq.size(); i++) {
System.out.println(localArq.get(i));
}
System.out.println("-------- ******************* --------");
msg = scan.readLine();
}else if(msg.equals("/exit") || (msg.equals("/Exit")) || (msg.equals("/EXIT"))) {
out.println(msg);
size=localArq.size();
out.println(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
}
else if(msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))) {
System.out.println("Chose file's number to /get: ");
c++;
}
if (done == true) {
break;
}
out.println(msg);
}
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String rmsg;
String req;
while (true) {
rmsg = in.readLine();
if (rmsg == null) {
System.out.println("Connection Terminated");
break;
}else if(rmsg.substring(rmsg.length() - 5).equals("idreq")) {
req = in.readLine();
for(int i=0;i<localArq.size();i++) { //IDENTIFIES WHO OWNS THE REQUESTED FILE
if(localArq.get(i).equals(req)) {
System.out.println("Owns requested file");
Socket requester = new Socket("192.168.3.114", 2007);
ObjectOutputStream outputr = new ObjectOutputStream(requester.getOutputStream());
ObjectInputStream inputr = new ObjectInputStream(requester.getInputStream());
Object mens= inputr.readObject();
System.out.println(mens);
outputr.writeObject("OWNER FOUND");
}
}
if(c==1) { //IDENTIFIES WHO WANTS THE FILE
rmsg = in.readLine();
c= Integer.parseInt(rmsg);
System.out.println("file: "+req);
ServerSocket peer = new ServerSocket(2007);
System.out.println("OPEN FOR CONNECTIONS\n");
Socket client = peer.accept();
System.out.println("Client connected: " + client.getInetAddress().getHostAddress());
ObjectOutputStream outputo = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream inputo = new ObjectInputStream(client.getInputStream());
outputo.flush();
outputo.writeObject("Connected to requester");
Object mens= inputo.readObject();
System.out.println(mens);
}
}
else {
System.out.println(rmsg);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
done = true;
}
}
I was able to make a transfer between two clients easily with the information provided and a little research on stackOverflow to understand more about out/inputStreams!
This post also helped me a lot: Sending a file with Java Sockets, losing data
next step is the shared transfer
This question already has answers here:
How do I fix a compilation error for unhandled exception on call to Thread.sleep()?
(2 answers)
Closed 5 years ago.
I'm having difficulty using InetAddress in Java for my Android project. I included the InetAddress library, however it never works.
The code is the follow:
InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
However all time show me:
Description Resource Path Location Type
Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor LauncherActivity.java /src/my/app/client line 25 Java Problem
I included the library:
import java.net.InetAddress;
What must I do to use InetAddress in my Android Project?
The class of my project is:
public class LauncherActivity extends Activity
{
/** Called when the activity is first created. */
Intent Client, ClientAlt;
// Button btnStart, btnStop;
// EditText ipfield, portfield;
//InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
//private InetAddress giriAddress;
private InetAddress giriAddress;
public LauncherActivity()
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
private String myIp = "MYIP"; // Put your IP in these quotes.
private int myPort = PORT; // Put your port there, notice that there are no quotes here.
#Override
public void onStart()
{
super.onStart();
onResume();
}
#Override
public void onResume()
{
super.onResume();
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
moveTaskToBack(true);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
//moveTaskToBack(true);
}
/**
* get Config
*/
private void getConfig()
{
Properties pro = new Properties();
InputStream is = getResources().openRawResource(R.raw.config);
try
{
pro.load(is);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myIp = pro.getProperty("host");
myPort = Integer.valueOf(pro.getProperty("prot"));
System.out.println(myIp);
System.out.println(myPort);
}
}
The error's i get.
Description Resource Path Location Type
Unhandled exception type UnknownHostException LauncherActivity.java /Androrat/src/my/app/client line 31 Java Problem
Picture:
MY VERSION OF JAVA IS JAVA SE 1.6
I propose two alternatives:
If the IP of the given host is mandatory for your application to work properly, you could get it into the constructor and re-throw the exception as a configuration error:
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
{
try {
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
catch (UnknownHostException e)
{
throw new ServiceConfigurationError(e.toString(),e);
}
}
}
But if it is not that mandatory, and this error might be recovered somehow, simply declare UnknownHostException in the constructor's throws clause (which will force you to capture/rethrow that exception in all the call hierarchy of your class' constructor):
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
throws UnknownHostException
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
}
This is my simple method using my android application.
private static int timeout = 500;
private static int isIpAddressString(String tstr, byte[] ipbytes)
{
final String str = tstr;
boolean isIpAddress = true;
StringTokenizer st = new StringTokenizer(str, ".");
int idx = 0;
if(st.countTokens() == 4)
{
String tmpStr = null;
byte[] ipBytes = new byte[4];
while(st.hasMoreTokens())
{
tmpStr = st.nextToken();
for (char c: tmpStr.toCharArray()) {
if(Character.isDigit(c)) continue;
else
{
//if(c != '.')
{
isIpAddress = false;
break;
}
}
}
if(!isIpAddress) break;
ipBytes[idx] = (byte)(Integer.valueOf(tmpStr.trim()).intValue());
idx++;
}
System.arraycopy(ipBytes, 0, ipbytes, 0, ipbytes.length);
}
return idx;
}
public static boolean canResolveThisUrlString(final String TAG, String urlStr)
{
String resolveUrl = urlStr;
boolean isResolved = false;
java.net.InetAddress inetaddr = null;
try
{
//java.net.InetAddress addr = java.net.InetAddress.getByName(resolveUrl);
byte[] ipbytes = new byte[4];
if(isIpAddressString(urlStr, ipbytes) == 4)
{
inetaddr = java.net.InetAddress.getByAddress(ipbytes);
}
else
{
String host = null;
if(resolveUrl.startsWith("http") ||resolveUrl.startsWith("https") )
{
URL url = new URL(resolveUrl);
host = url.getHost();
}
else
host = resolveUrl;
inetaddr = java.net.InetAddress.getByName(host);
}
//isResolved = addr.isReachable(SettingVariables.DEFAULT_CONNECTION_TIMEOUT);
isResolved = inetaddr.isReachable(timeout);
//isResolved = true;
}
catch(java.net.UnknownHostException ue)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, ue);
ue.printStackTrace();
isResolved = false;
}
catch(Exception e)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, e);
e.printStackTrace();
isResolved = false;
}
//System.out.println(isResolved + "::::::::" + inetaddr.toString());
return isResolved;
}
You can test it with
public static void main(String[] args)
{
String urlString = "https://www.google.com";
String urlString1 = "www.google.com";
String urlString2 = "https://www.google.co.kr/search?q=InetAddress+create&rlz=1C1NHXL_koKR690KR690&oq=InetAddress+create&aqs=chrome..69i57j0l5.5732j0j8&sourceid=chrome&ie=UTF-8";
String urlString3 = "127.0.0.1";
//URL url = null;
try {
boolean canResolved = canResolveThisUrlString(null, urlString);
System.out.println("resolved " + canResolved + " : url [" + urlString + "]");
canResolved = canResolveThisUrlString(null, urlString1);
System.out.println("resolved " + canResolved + " : url [" + urlString1 + "]");
canResolved = canResolveThisUrlString(null, urlString2);
System.out.println("resolved " + canResolved + " : url [" + urlString2 + "]");
canResolved = canResolveThisUrlString(null, urlString3);
System.out.println("resolved " + canResolved + " : url [" + urlString3 + "]");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you've got a UnknownHostException from your app when the url you've requested can't be resolved by whatever dns servers.
This case, you can not get any host name with ip address like 'www.girionjava.com' host in the internet world.
I have return one script which on execution modifies a line in one file.
Flow for working script is from run method after printing checkpoint 111 it is going to executeCmd method after printing checkpoint aaaa, execution again goes to run method prints checkpoint 222 and comeback to executeCmd method and exit the execution after printing bbb.
But in my case after checkpoint aaa it is printing checkpoint bbb and this loop is never ending so execution is not going back to run method and hence script is stuck and hangs the session.
public String executeCmd(String classOpts, String cmdLine, String[] opts)
{
while (myCmd.isAlive() == true)
{
try
{
log.debug("checkpoint aaaa");
Thread.sleep(100);
log.debug("checkpoint bbbb");
}
}
exitVal = myCmd.getCmdExitValue();
log.debug("The script exit code: = " + exitVal);
}
public void run()
{
Runtime rt = Runtime.getRuntime();
try
{
String sCommand = cmdUtils.sScriptLauncher + " " + this.cmdline;
proc = rt.exec(cmdUtils.sScriptLauncher + " " + this.cmdline;
proc = rt.exec(cmdUtils.ParseCommandLine(sCommand));
try
{
log.debug("Checkpoint 111");
cmdExitVal = proc.waitFor();`enter code here`
log.debug("Checkpoint 222");
}
//remaining code
I use following class RunProcessCMD that uses ProcessBuilder, stdout and stderr:
class RunProcessCMD {
static BufferedReader stdout, stderr;
private Boolean isWaitFor = true;// wait for reply from CMD
private static RunProcessCMD startRunProcessCMD = null;
private String[] input = null;
private static boolean isRealTime = false;
private static StringBuilder buff = null;
public static RunProcessCMD getInstance(){
if(startRunProcessCMD == null){
startRunProcessCMD = new RunProcessCMD();
}
return startRunProcessCMD;
}
private RunProcessCMD(){}// destroy public constructor
public void start(String[] command) throws IOException {
buff = new StringBuilder();
System.out.println(Arrays.asList( command ) );
ProcessBuilder launcher = new ProcessBuilder();
launcher.redirectErrorStream(true);
launcher.command(command);
launcher.start(); // And launch a new process
buff.append("Done").append("\n");System.out.println("Done.");
}
public void start () throws IOException, InterruptedException{
buff = new StringBuilder();
if(input == null){
buff.append("Command == null");
return;
}
//String[] input = new String[] {"tasklist"};
Runtime r = Runtime.getRuntime();
//System.out.println("Execute ...");
//Process p = r.exec("cmd /c", input, null);
System.out.println(Arrays.asList( input ) );
Process p = r.exec(input);
//System.out.println("Finish to execute, start read output");
InputStream is = p.getInputStream();
stdout = new BufferedReader(new InputStreamReader(is));
is = p.getErrorStream();
stderr = new BufferedReader(new InputStreamReader(is));
//outputLines = new Vector();
if( isWaitFor == true ){
StdoutThread cltOut = RunProcessCMD.getInstance().new StdoutThread();
Thread tOut = new Thread(cltOut);
tOut.start();
StderrThread cltErr = RunProcessCMD.getInstance().new StderrThread();
Thread tErr = new Thread(cltErr);
tErr.start();
p.waitFor();
}
buff.append("Done").append("\n");System.out.println("Done.");
if( isWaitFor == false ){
buff.append("WaitFor defined to be false, respectivally no output from CMD").append("\n");
System.out.println("WaitFor defined to be false, respectively no output from CMD");
}
}
private class StdoutThread implements Runnable {
#Override
public void run() {
try {
int l;
String line;
for(l = 0; (line = stdout.readLine()) != null; ) {
if (line.length() > 0)
l++;
//outputLines.addElement(line);
buff.append(line).append("\n");
if(!line.trim().equals("")){
System.out.println(line);
}
}
stdout.close();
}
catch(IOException ie) {
buff.append("IO exception on stdout: " + ie).append("\n");
}
}
}
private class StderrThread implements Runnable {
public StderrThread() {}
#Override
public void run() {
try {
int l;
String line;
for(l = 0; (line = stderr.readLine()) != null; ) {
if (line.length() > 0) l++;
buff.append(line).append("\n");
System.out.print(line);
}
stderr.close();
}
catch(IOException ie) {
buff.append("IO exception on stdout: " + ie).append("\n");//System.out.println("IO exception on stdout: " + ie);
}
}
}
public static void ClearBuff (){
buff.setLength(0);
isRealTime = false;
}
public void setInput(String[] input) {
// reset flag
isWaitFor = true;
if(input[input.length-1].contains("waitFor") && input[input.length-1].split("=").length == 2 ){
String bull = input[input.length-1].split("=")[1];
isWaitFor = new Boolean( bull );
System.out.println("isWaitFor = " + isWaitFor);
// remove last value from String array
String[] input_new = new String[input.length -1];
for(int k=0; k < input_new.length; k++){
input_new[k] = input[k];
}
input = input_new;
}
// add proper value for input
String[] str = new String[input.length + 2];
str[0] = "cmd.exe";
str[1] = "/c";
for(int i=2; i<str.length; i++){
str[i] = input[i-2];
}
this.input = str;
}
public static StringBuilder getBuff() {
if( buff == null ){
return new StringBuilder( "" );
}
return buff;
}
public void setRealTime(boolean b) {
isRealTime = b;
}
}
Usage:
private void runSomeCommandOverCmd(){
String runP = "adb devices";
String[] strArr = new String[2];
strArr[0] = runP;
strArr[1] = "waitFor=true";
RunProcessCMD.getInstance().setInput( strArr );
try {
RunProcessCMD.getInstance().start();
String str = ( RunProcessCMD.getBuff() ).toString();
System.out.println(str);
RunProcessCMD.ClearBuff();
} catch (Exception e) {
try {
throw new Exception( "Failed to Start process CMD" );
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
I am new to cryptography. I have to develop project based on cryptography..In part of my project I have to insert a key to the registry and afterwards I have to retrieve the same key for decryption.. I done until getting the path of the registry ..
Here I am showing my code:
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public final class Project {
public static final String readRegistry(String location, String key) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg query " +
'"' + location + "\" /v " + key);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
if (!output.contains("\t")) {
return null;
}
// Parse out the value
String[] parsed = output.split("\t");
return parsed[parsed.length - 1];
} catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw = new StringWriter();
public StreamReader(InputStream is) {
this.is = is;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1) {
System.out.println("Reading" + c);
sw.write(c);
}
} catch (IOException e) {
System.out.println("Exception in run() " + e);
}
}
public String getResult() {
System.out.println("Content " + sw.toString());
return sw.toString();
}
}
public static boolean addValue(String key, String valName, String val) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg add \"" + key + "\" /v \"" + valName + "\" /d \"\\\"" + val + "\\\"\" /f");
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
System.out.println("Processing........ggggggggggggggggggggg." + output);
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
return output.contains("The operation completed successfully");
} catch (Exception e) {
System.out.println("Exception in addValue() " + e);
}
return false;
}
public static void main(String[] args) {
// Sample usage
JAXRDeleteConcept hc = new JAXRDeleteConcept();
System.out.println("Before Insertion");
if (JAXRDeleteConcept.addValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU", "REG_SZ", "Muthus")) {
System.out.println("Inserted Successfully");
}
String value = JAXRDeleteConcept.readRegistry("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU" , "Project_Key");
System.out.println(value);
}
}
But i dont know how to insert a key in a registry and read the particular key which i inserted..Please help me..
Thanks in advance..
It would be a lot easier to use the JRegistry library to edit the registry, rather than execute commands.