whois in java for Android - java

I'm making a whois in java for android to train about streams and tcp connections.
But I have a problem. I have a php script, I wrote some time ago and I´m trying to make the same in java.
this is my java code :
public String consultawhois(String domain,String tld)
{
String domquest = domain + "." + tld;
String resultado = "";
Socket theSocket;
String hostname = "whois.internic.net";
int port = 43;
try {
theSocket = new Socket(hostname, port, true);
Writer out = new OutputStreamWriter(theSocket.getOutputStream());
out.write(domquest + "\r\n");
out.flush();
DataInputStream theWhoisStream;
theWhoisStream = new DataInputStream(theSocket.getInputStream());
String s;
while ((s = theWhoisStream.readLine()) != null) {
resultado = resultado + s + "\n";
}
}
catch (IOException e) {
}
return resultado;
}
The answer of the server is not correct and I think the problem is that I'm sending a bad query. The query I send is "dominio.com\r\n" and in my php whois code, it works perfectly.

It seems that the DNS query matches multiple records. At least, that is how I interpret the response. In the returned reponse you should see the following line:
To single out one record, look it up with "xxx", where xxx is one of the
of the records displayed above. If the records are the same, look them up
with "=xxx" to receive a full display for each record.
So if you prepend the query with "=" it returns the data of that record only. The following worked for me.
public String consultawhois(String domain,String tld)
{
String domquest = domain + "." + tld;
String resultado = "";
Socket theSocket;
String hostname = "whois.internic.net";
int port = 43;
try {
theSocket = new Socket(hostname, port, true);
Writer out = new OutputStreamWriter(theSocket.getOutputStream());
out.write("="+domquest + "\r\n");
out.flush();
DataInputStream theWhoisStream;
theWhoisStream = new DataInputStream(theSocket.getInputStream());
String s;
while ((s = theWhoisStream.readLine()) != null) {
resultado = resultado + s + "\n";
}
}
catch (IOException e) {
}
return resultado;
}
One thing to consider: Use English for method names, variables, etc. instead of Spanish. It will make your code easier to read internationally. The programming language itself also uses English words. Try to avoid a strange mix of English and your native language.

The lookup for dominio.com results in three matches:
DOMINIO.COM.BR
DOMINIO.COM.ASCPROBIENESTARIDSS.COM
DOMINIO.COM
You should specify wich one you are interested in with the query.
=dominio.com<newline>
This will allways work, even cases where there are no multiple matches.

Related

No process is on the other end of the pipe - Named Pipes in JAVA

I am using this codes in communicating with Evolis KC200 printer:
#Test
public void studyPipe() {
try {
String echoText = " {\"id\":\"1\",\"jsonrpc\":\"2.0\",\"method\":\"CMD.GetStatus\",\"params\":{\"device\":\"Evolis KC200\"}}";
System.out.println("CMD.GetStatus Request: " + echoText);
String pipeName = "\\\\.\\pipe\\EspfServer00";
RandomAccessFile pipe = new RandomAccessFile(pipeName, "rw");
System.out.println("Writing in pipe: " + echoText + " in pipe "
+ pipeName);
pipe.write(echoText.getBytes("UTF-8"));
// Thread.sleep(1000);
String echoResponse = pipe.readLine();
System.out.println("Response: " + echoResponse);
pipe.close();
} catch (Exception e) {
e.printStackTrace();
}
}
But all I'm getting is this:
java.io.IOException: No process is on the other end of the pipe
at java.io.RandomAccessFile.read0(Native Method)
at java.io.RandomAccessFile.read(RandomAccessFile.java:330)
at java.io.RandomAccessFile.readLine(RandomAccessFile.java:939)
at
They have a test tool built on another language (C#) and their Named Pipe client looks like this:
What is missing in my JAVA codes?
public static string SendRequestPipe(string ip, string port, string request)
{
NamedPipeClientStream objPipeClient;
string answer = string.Empty;
objPipeClient = new NamedPipeClientStream(ip, port, PipeDirection.InOut);
try
{
// Connexion au named pipe ou attente de la disponibilité du named pipe
objPipeClient.Connect(1000);
// Paramétrage de la connexion
objPipeClient.ReadMode = PipeTransmissionMode.Message;
if (objPipeClient.IsConnected == true)
{
// Send request
byte[] datain = Encoding.UTF8.GetBytes(request);
objPipeClient.Write(datain, 0, datain.Length);
// Get answer
int recv = 0;
byte[] data = new byte[1024];
do
{
recv = objPipeClient.Read(data, 0, data.Length);
answer += Encoding.UTF8.GetString(data, 0, recv);
} while (!objPipeClient.IsMessageComplete);
}
}
catch (Exception ex)
{
}
finally
{
objPipeClient.Close();
objPipeClient.Dispose();
}
return answer;
}
I also tried similar approaches in Java but I'm getting the same error.
UPDATE:
I think I know the issue already but I still do not have the resolution.
It seems that the JAVA code is creating another instance of the PIPE that is why it is not receiving any process on that new instance.
I tested with the C# code and it was not creating a new instance.
I checked the instances using this tool:
https://learn.microsoft.com/en-us/sysinternals/downloads/pipelist

SHA1 digest from two PDFs is different but when converted to PDF/A is equal

I generate two PDFs from a jasper passing the same parameters to both of them, when I hash these two PDFs their hash is different which I think is the correct result, because eventough they have the same content they were created at different times.
But when I convert these two PDFs to PDF/A their sha1 hash is equal.
Can someone help me with this issue? How is this possible?
EDIT:
private static final String OUTPUT_FORMAT = "fi_pdfa";
public void convert(String exeFullPath, String inputFile,
String outputFile, String fontDirectory) {
String[] execParams = new String[4];
execParams[0] = exeFullPath;
execParams[1] = "\"inputpath_u=" + base64Encode(inputFile) + "\"";
execParams[2] = "\"outputpath_u=" + base64Encode(outputFile) + "\"";
execParams[3] = "\"outputid=" + OUTPUT_FORMAT + "\"";
// execParams[1] = "inputpath_u=\"" + base64Encode(inputFile) + "\"";
// execParams[2] = "outputpath_u=\"" + base64Encode(outputFile) + "\"";
// execParams[3] = "outputid=" + OUTPUT_FORMAT;
// execParams[4] = "fontdirectory=\"" + fontDirectory + "\"";
Runtime runtime = Runtime.getRuntime();
Process process = null;
ExportStatusCode statusCode = null;
ExportShutdownHook shutdownHook = null;
try {
process = runtime.exec(execParams);
// Install a shutdown hook to perform cleanup if we're interrupted.
shutdownHook = new ExportShutdownHook(process);
runtime.addShutdownHook(shutdownHook);
process.waitFor();
InputStream is = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null)
System.out.println(line);
reader.close();
runtime.removeShutdownHook(shutdownHook);
shutdownHook.finished();
statusCode = new ExportStatusCode(process.exitValue());
} catch (IOException ex) {
log.error(ex);
if (shutdownHook != null) {
runtime.removeShutdownHook(shutdownHook);
shutdownHook.finished();
}
statusCode = ExportStatusCode.SCCERR_JAVA_IO_ERROR;
} catch (InterruptedException ex) {
log.error(ex);
runtime.removeShutdownHook(shutdownHook);
shutdownHook.finished();
process.destroy();
statusCode = ExportStatusCode.SCCERR_JAVA_INTERRUPTED;
}
}
Based on the description, I don't believe it is an issue with your code so much as with the PDF/A converter being used.
There are some PDF features that require or suggest a timestamp be used (e.g. digital signatures, annotations, PieceInfo dictionaries), and there are some features that require or suggest a unique identifier be used.
The PDF Reference strongly recommends that PDF Producers generate File Identifiers (stored in an array in the trailer dictionary), so even if the rest of the files were created identically, the ID entries in the trailer dictionary should be unique and cause the hash value for the files to be different...which strongly indicates that the ID array is either not being populated by the PDF Converter or that the generation of the identifiers is flawed; This can be verified by opening the two PDFs in a Hex Viewer and scrolling to the bottom of the files.
Disclaimer: Once upon a time, I provided technical support for the OutsideIn products.

Start user's standard mail client with attachment pre-attached

I'm looking for a way that my application can call the user's standard mail application (e.g. Outlook, Thunderbird, etc.). And give it an recipient address, the email text and an attachment.
So, basically the standard email application should pop up have the email ready for me (with recipient, text and attachment) and all that is left to do for me is pressing "send" in my outlook, thunderbird etc.
I've been googling for a while now, but I couldn't find a real solution.
I've been looking into mapi a bit but it seems like 1. it's deprecated and 2. it's mainly built for outlook.
Any help/suggestions/solutions greatly appreciated!
Edit: I have seen the question Start Mail-Client with Attachment but no working answer was provided there and also the question is more than 3 years old.
Edit: Other languages would be ok, too. Has to work on Windows XP, Vista, 7, 8 (both 32 and 64 bit)
UPDATE: It seems to be more difficult than I have thought it to be.
I've been looking into JMAPI, which apparently only works for 32bit Systems.
I've also seen the solutions on codeproject.org (here and here), but I somehow couldn't get them to work.
Now I'm trying to do it with command line:
1. Read user's default mail client
2. Call a batch file according to the email client. (Yes you have to write a batch file for every common mail client.
Example for outlook:
"outlook.exe" /a "F:\test.png" /m "test.test#test.test&cc=test#test.test&subject=subject123&body=Hello, how are you%%3F%%0D%%0Anew line"
--> see my provided answer for futher info on that method
So...
After days of research I gave up to get a general solution.
I came up with a solution working at least for the two most common clients (Thunderbird & Outlook)
My solution is basically calling the application from command line.
For those interested, here is my solution: (I haven't tested it cross platform - works on my old XP laptop though)
import java.io.IOException;
/*
:: Punctuation Hexadecimal equivalent
:: ----------------------------------------------
:: Space ( ) %20
:: Comma (,) %2C
:: Question mark (?) %3F
:: Period (.) %2E
:: Exclamation point (!) %21
:: Colon (:) %3A
:: Semicolon (;) %3B
:: Line feed %0A --> New line %0D%0A
:: Line break (ENTER key) %0D --> New line %0D%0A
*/
public class Main {
static String test = "hi";
private static String attachment;
private static String to;
private static String cc;
private static String subject;
private static String body;
public static void main (String[] args){
attachment = "F:\\pietquest.png";
to = "test#test.de";
cc = "a.b#c.de";
subject = "TestSubject 123";
body = "Hi, what\'s going on%0D%0Anew line";
body = replace(body);
subject = replace(subject);
String[] value = WindowsRegistry.readRegistry("HKEY_LOCAL_MACHINE\\SOFTWARE\\Clients\\Mail", "");
if (value[10].contains("Thunderbird")){
System.out.println("Thunderbird");
String[] pfad = WindowsRegistry.readRegistry("HKEY_LOCAL_MACHINE\\SOFTWARE\\Clients\\Mail\\Mozilla Thunderbird\\shell\\open\\command", "");
String Pfad = pfad[10] + " " + pfad[11];
String argument = Pfad + " /compose \"to=" + to + ",cc=" + cc + ",subject=" + subject + ",body=" + body + ",attachment=" + attachment + "\"";
// System.out.println(argument);
try {
Runtime.getRuntime().exec(argument);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (value[10].contains("Outlook")){
System.out.println("Outlook");
String[] pfad = WindowsRegistry.readRegistry(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Clients\\Mail\\Microsoft Outlook\\shell\\open\\command", "");
String Pfad = pfad[10];
String argument = Pfad + " /a " + attachment + " /m \"" + to
+ "&cc=" + cc + "&subject=" + subject + "&body=" + body + "\"";
// System.out.println(argument);
try {
Runtime.getRuntime().exec(argument);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String replace(String toReplace){
toReplace = toReplace.replace(" ", "%20");
toReplace = toReplace.replace(",", "%2C");
toReplace = toReplace.replace("?", "%3F");
toReplace = toReplace.replace(".", "%2E");
toReplace = toReplace.replace("!", "%21");
toReplace = toReplace.replace(":", "%3A");
toReplace = toReplace.replace(";", "%3B");
return toReplace;
}
}
and this is the Windows Registry Class: (got that from here)
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public class WindowsRegistry {
/**
*
* #param location path in the registry
* #param key registry key
* #return registry value or null if not found
*/
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);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
// Parse out the value
String[] parsed = reader.getResult().split("\\s+");
if (parsed.length > 1) {
return parsed;
}
} 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)
sw.write(c);
} catch (IOException e) {
}
}
public String getResult() {
return sw.toString();
}
}
you can use C#: Example C# or java: Example Java
EDIT
You can use Boost for ssl and send email via smtp

Parsing java streams

I am trying to access data from a raw data stream. Before accessing the raw data stream, I must parse/remove any traces of xml. I do this by converting the raw stream to a string array and by iterating through each line to remove the xml.
I can parse/remove the xml from the string okay and I can recreate the data stream. The problem I have is reading through each line and storing each value (year, month, day, power)
The while loop fails with an out of bound exception on the line:
int year = bb.get(0);
My guess is that this is happening because the newResult string that's created isn't being read correctly through the readLine method. Instead of having a list of raw data, there's only one line of raw data. According to the specifications, there should be 60 (and the length of decResult-1 is 60.
Here is the code below. Can anyone help me to figure out why the while loop isn't iterating through each line? Thanks.
try {
HttpRequestBase request = null;
request = new HttpGet(urlString);
consumer.sign(request);
Log.v(TAG, "consumer.sign");
HttpResponse response = client.execute(request);
InputStream stream = (InputStream)response.getEntity().getContent();
String result = convertStreamToString(stream);
String[] decResult = result.split("<day raw=\"");
String newResult = "";
if(decResult.length > 1) {
for(int i=1; i<decResult.length; i++) {
decResult[i] = decResult[i].replaceAll("\"\\/>", "");
Log.v(TAG, "DecResult = "+ (decResult[i]).toString());
decResult[i] = decResult[i].replaceAll("</ted5000_mtu_days>","");
Log.v("DayData", decResult[i].toString());
newResult = newResult.concat((decResult[i].toString() + "\n"));
}
}
Log.v("DayData", "newResult = "+ newResult);
Log.v("DayData", "End NewResult");
BufferedReader reader = new BufferedReader(new StringReader(newResult));
String line = null;
while((line = reader.readLine()) != null) {
Log.v("DayData", "****Entering while loop***");
Log.v("DayData", "Line = " + line);
String bytes = Base64.decode(line);
Log.v("DayData", "Received bytes");
ByteBuffer bb = ByteBuffer.wrap(bytes.getBytes());
Log.v("DayData", "ByteBuffer.wrap");
bb.order(ByteOrder.LITTLE_ENDIAN);
int year = bb.get(0);
int month = bb.get(1);
int day = bb.get(2);
int power = bb.getInt(3);
Log.i("DayData", "Date: " + month + "/" + day + "/" + year + " Power: " + power);
}
Log.v("DayData", "Exiting while loop");
} catch (Exception e) {
e.printStackTrace();
Log.e("DayData", "Exception: " + e.toString());
return false;
}
}
You should use an XML parser that suits your needs. From the wikipedia page:
Existing APIs for XML processing tend to fall into these categories:
Stream-oriented APIs accessible from a programming language, for example SAX and StAX.
Tree-traversal APIs accessible from a programming language, for example DOM.
XML data binding, which provides an automated translation between an XML document and
programming-language objects.
Declarative transformation languages such as XSLT and XQuery.
It sounds like you're bombing out on an empty line. Since you already have lots of debug logging you could verify that by changing this line Log.v("DayData", "Received bytes"); to something like this Log.v("DayData", "Received bytes: \""+bytes+"\"");
You probably should still check for this condition, even if you find some other error is causing the problem. If you expect a certain length, you can check that the .limit() on the buffer meets your expectations.

java TCP socket message breaks

i have a java client-server app in java, both using the same connection class that contains both send/receive messages.
for some reason, some of the messages i send are received in a malformed order:
here's the code
//set up
_in = new BufferedReader(new InputStreamReader(this._socket.getInputStream()));
_out = new BufferedWriter(new OutputStreamWriter(this._socket.getOutputStream()));
this._socket.setSoTimeout(S_TIMEOUT);
public synchronized boolean send(String message){
try {
_out.write(message);
_out.write(Connection.DELIMITER);
_out.flush();
return true;
} catch (IOException e) {
}
return false;
}
public String receive(){
int c;
try {
String message = "";
System.out.println("Getting message:");
c = _in.read();
while(c != -1 && c != Connection.DELIMITER) {
message += (char) c;
c = _in.read();
}
if (c == -1) {
return null;
}
return message;
} catch (IOException e) { }
return null;
}
some messages, for example "new_order" will might return with "ew_ord".
some characters are lost, others are sent separately. this seems odd as its TCP
could this be an encoding related issue?
Delimiter is (char) 0
socket timeout is 20000 (ie 20 senconds). every 10 seconds i send an empty message to make sure socket does not close
EDIT:
although it was solved using the Scanner, i must say that the original code worked fine for many messages/various machines for a very long time (a few weeks), and then suddenly failed to work with one specific message on one specific machine (other messages went through just fine). i've done socket data transfer in java MANY times and i've written many read/write methods to handle the sockets. it's the first time i ran into this.
although in the original code i set the encoding (in the posted code i didn't), i believe that the problem was encoding related. at one point, the message that was received had every second character missing. afterwards i changed it a bit, and the first/second character of the message were received in a separate message. from my understanding, it's either an encoding issue or some firewall/other security program that was running on the message sender machine, that decided to filter outgoing packets.
Try replacing your receive with a Scanner and let it do the work for you.
// in your setup
Scanner sc = new Scanner(_in).useDelimiter(Connection.DELIMETER);
public String receive() {
try {
return sc.next();
} catch(IOException e) {
return "";
}
}
For starters, I would make sure you're printing exceptions in those catch blocks.
Then, you're using the platform default encoding for converting characters to bytes. If these two processes are running on different machines, it's possible they're using different encodings. I would make sure you're specifying an encoding when you set up the Reader and Writer.
You can use UTF encoding for getting Full String of Message.
U can try this code and I am Sure About this code because i used it in My Chat Application.
String data=" ";
socket = new Socket("localhost",999);
while(true)
{
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
data = dis.readUTF();
jta.append(data +"\n");
}
Where jta is JTextArea.
It's for Client Side
Now For Server Side:
try
{
server = new ServerSocket(999);
Socket soc = server.accept();
while(true)
{
String data="";
try
{
dis = new DataInputStream(soc.getInputStream());
dos = new DataOutputStream(soc.getOutputStream());
data = dis.readUTF();
}
catch(Exception e)
{ }
jta.append(data + "\n");
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, e);
System.exit(-1);
}

Categories

Resources