Java serialization with empty and substrings - java

Had a look at the implementation and haven't been able to think of an explanation to this but maybe someone here will know.
public static void main(String[] args) throws Exception {
List<String> emptyStrings = new ArrayList<String>();
List<String> emptySubStrings = new ArrayList<String>();
for (int i = 0; i < 20000; i++) {
String actuallyEmpty = "";
String subStringedEmpty = " ";
subStringedEmpty = subStringedEmpty.substring(0, 0);
emptyStrings.add(actuallyEmpty);
emptySubStrings.add(subStringedEmpty);
}
System.out.println("Substring test");
// Write to files
long time = System.currentTimeMillis();
writeObjectToFile(emptyStrings, "empty.list");
System.out.println("Time taken to write empty list " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
writeObjectToFile(emptySubStrings, "substring.list");
System.out.println("Time taken to write substring list " + (System.currentTimeMillis() - time));
//Read from files
time = System.currentTimeMillis();
List<String> readEmptyString = readObjectFromFile("empty.list");
System.out.println("Time taken to read empty list " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
List<String> readEmptySubStrings = readObjectFromFile("substring.list");
System.out.println("Time taken to read substring list " + (System.currentTimeMillis() - time));
}
private static void writeObjectToFile(Object o, String file) throws Exception {
FileOutputStream out = new FileOutputStream(file);
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(o);
oout.flush();
oout.close();
}
private static <T> T readObjectFromFile(String file) throws Exception {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(file));
return (T) ois.readObject();
} finally {
ois.close();
}
}
Ultimately these 2 lists contain 20,000 empty strings (one list contains "" empty strings and the other contains empty strings generated by substring(0,0)). But if you check the sizes of the serialized files generated (empty.list and substring.list) you will notice that the empty.list contains substantially more data.
I have noticed that the callers of remote EJB's which un-serialize these substring objects seem to have severe performance issues also.

The sizes of the lists are different because java uses a mechanism to store multiples references to the same object, like described:
References to other objects (except in transient or static fields)
cause those objects to be written also. Multiple references to a
single object are encoded using a reference sharing mechanism so that
graphs of objects can be restored to the same shape as when the
original was written.
see ObjectOutputStream
If you look the generated serialized file, you will see:
With 1 String empty inside:
empty.list:
ac ed 00 05 73 72 00 13 6a 61 76 61 2e 75 74 69
6c 2e 41 72 72 61 79 4c 69 73 74 78 81 d2 1d 99
c7 61 9d 03 00 01 49 00 04 73 69 7a 65 78 70 00
00 00 01 77 04 00 00 00 01 74 00 00 78
The string "" corresponds to the last three bytes (00 00 78)
substring.list
ac ed 00 05 73 72 00 13 6a 61 76 61 2e 75 74 69
6c 2e 41 72 72 61 79 4c 69 73 74 78 81 d2 1d 99
c7 61 9d 03 00 01 49 00 04 73 69 7a 65 78 70 00
00 00 01 77 04 00 00 00 01 74 00 00 78
Note that with one element the resulted file is the same.
But if we want to add more times the same object, we will be faced with other behavior.
Look the respective files with 2 times that string.
empty.list:
ac ed 00 05 73 72 00 13 6a 61 76 61 2e 75 74 69
6c 2e 41 72 72 61 79 4c 69 73 74 78 81 d2 1d 99
c7 61 9d 03 00 01 49 00 04 73 69 7a 65 78 70 00
00 00 02 77 04 00 00 00 02 74 00 00 71 00 7e 00
02 78
substring.list
ac ed 00 05 73 72 00 13 6a 61 76 61 2e 75 74 69
6c 2e 41 72 72 61 79 4c 69 73 74 78 81 d2 1d 99
c7 61 9d 03 00 01 49 00 04 73 69 7a 65 78 70 00
00 00 02 77 04 00 00 00 02 74 00 00 74 00 00 78
Note that substring continues "normal", two non related strings with different references. But empty has some extra bytes to handle the issue of same reference.
Six bytes from substring (00 00 74 00 00 78) versus eight bytes from emptylist (00 00 71 00 7e 00 02 78)
This goes wrong because every repeated string that you add, more extra bytes are added. So when you full your arrayList there will be a lot of extra bytes to make it possible to reconstruct as it's original way.
If you want to know why there is that sharing mechanism, I suggest you to take a look at this question:
What is the meaning of reference sharing in Serialization? How Enums are Serialized?

empty.list contains one String object and lots of references to it.
substring.list contains 2000 string objects, all of them are equal in content.
You could "fix" this by intern()ing the strings.
private void verify(String name, Supplier<String> stringSupplier) throws IOException, ClassNotFoundException {
List<String> inputStrings = new ArrayList<String>();
inputStrings.add(stringSupplier.get());
inputStrings.add(stringSupplier.get());
ByteArrayOutputStream boas = new ByteArrayOutputStream();
ObjectOutputStream emptyOut = new ObjectOutputStream(boas);
emptyOut.writeObject(inputStrings);
emptyOut.flush();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(boas.toByteArray()));
List<String> returnedStrings = (List<String>)ois.readObject();
if(returnedStrings.get(0) == returnedStrings.get(1)) {
System.out.println(name + " contains the same object");
} else {
System.out.println(name + " contains DIFFERENT objects");
}
}
#Test
public void test() throws IOException, ClassNotFoundException {
verify("empty string", new Supplier<String>() {
#Override
public String get() {
return "";
}
});
verify("sub string", new Supplier<String>() {
#Override
public String get() {
String data = " ";
return data.substring(0, 0);
}
});
verify("intern()ed substring", new Supplier<String>() {
#Override
public String get() {
String data = " ";
return data.substring(0, 0).intern();
}
});
}

Related

Java SSL/TLS Handshake

im writing a small HTTP/S Server for an Embeded Device Framework.
Because i use plain Java Sockets i need to implement the TLS/SSL myself.
For the Client Handshake i wrote following Function:
if (secureIO) {
// Print Message if Client Handshake was correct.
((SSLSocket) clientIO)
.addHandshakeCompletedListener(new HandshakeCompletedListener() {
#Override
public void handshakeCompleted(HandshakeCompletedEvent eventIO) {
logIO.debug(GuardianLog.Type.SUCCESS,
"Handshake with Client "
+ clientIO.getInetAddress().getHostAddress() + " via Method "
+ eventIO + " was correct.");
// Unlock Stream Lock.
lockIO[0] = false;
}
});
// ((SSLSocket) clientIO).setNeedClientAuth(true);
// Session Creation Blocks everything...
((SSLSocket) clientIO).setEnableSessionCreation(true);
// Set Cipher and Protocols for Client.
((SSLSocket) clientIO)
.setEnabledProtocols(((SSLServerSocket) tcpIO).getEnabledProtocols());
((SSLSocket) clientIO)
.setEnabledCipherSuites(
((SSLServerSocket) tcpIO).getEnabledCipherSuites());
// Start Handshake to Client.
((SSLSocket) clientIO).startHandshake();
}
The Problem is, when i opening the Socket Port in the Browser, the Page loads forever.
So i tried to debug the SSLSocket with OPENSSL it seems that the Handshake gets not fully finished.
I thought some Stream gets confused by an Listener on my Server, but i disabled the Input/Output Stream entirely with the lock bool, until the Handshake Complete Listener gets executed.
Some outstanding Debug Traces from the Server have given me this theory.
javax.net.ssl|ALL|1C|Server-Socket|2022-07-08 21:51:57.696 CEST|SSLSessionImpl.java:250|Session initialized: Session(1657309917387|TLS_AES_256_GCM_SHA384)
javax.net.ssl|FINE|1C|Server-Socket|2022-07-08 21:51:57.696 CEST|SSLSocketOutputRecord.java:241|WRITE: TLS13 handshake, length = 50
javax.net.ssl|FINE|1C|Server-Socket|2022-07-08 21:51:57.697 CEST|SSLCipher.java:2013|Plaintext before ENCRYPTION (
0000: 04 00 00 2E 00 01 51 80 F9 1F 1E 31 01 01 00 20 ......Q....1...
0010: E5 5B CF E4 29 3B 0E 9F E4 12 D7 CD 8B 34 2C 22 .[..);.......4,"
0020: 0B 14 45 B3 E9 94 CC 62 64 C3 06 E4 4F 72 82 D3 ..E....bd...Or..
0030: 00 00 16 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0040: 00 00 00 ...
)
javax.net.ssl|FINE|1C|Server-Socket|2022-07-08 21:51:57.697 CEST|SSLSocketOutputRecord.java:255|Raw write (
0000: 17 03 03 00 53 6B D3 EE EF C5 DD D2 E3 3F DF 15 ....Sk.......?..
0010: 13 87 A5 9E BB AC 0A 1F 1F 6A 77 50 B1 4D 51 39 .........jwP.MQ9
0020: 4D 0C 00 78 D1 4A D8 78 79 9A 79 7E AD EB 20 80 M..x.J.xy.y... .
0030: 91 C3 A5 14 33 FF 13 01 9B D6 37 7E 3A 7B 9F 7D ....3.....7.:...
0040: 03 E6 59 90 FF 9B E3 63 87 18 FD 84 37 C7 21 CA ..Y....c....7.!.
0050: A7 AC ED 25 C3 05 73 A8 ...%..s.
)
Heres an example of my Read Function, the InputStream is setet after the Socket.accpet() Method:
private void read(InputStream streamIO, java.net.Socket clientIO) {
// todo: Test Performance between execute and submit.
poolIO.execute(new Runnable() {
#Override
public void run() {
try {
// clientIO.isConnected() && !tcpIO.isClosed() &&
while (!shutdownIO && clientIO.isConnected() && !tcpIO.isClosed()) {
// Byte Buffer ho contains read Data.
// #todo: add buffer max size, read until -1 (EOF).
byte[] bufferIO = new byte[streamIO.available()];
// Read Data into Buffer and store (EOF).
int codeIO = streamIO.read(bufferIO);
if (codeIO != 0 || bufferIO.length != 0) {
System.out.println(codeIO);
System.out.println(bufferIO.length);
}
// Check if bytes in the Buffer.
if (bufferIO.length != 0 && streamIO.available() == 0) {
if (binaryIO)
binary(new Socket(clientIO), bufferIO);
if (stringIO)
string(new Socket(clientIO), new String(bufferIO, charsetIO));
}
if (eofIO && (codeIO == -1)) {
break;
}
// Sleep for 100 Milliseconds (CPU Usage)
Thread.sleep(100);
}
streamIO.reset();
streamIO.close();
clientIO.close();
disconnect(new Socket(clientIO));
// Clear Buffer Stream.
// bufferIO = new byte[0];
} catch (IOException | InterruptedException errorIO) {
if (errorIO.getMessage().equalsIgnoreCase("Stream closed.")
|| errorIO.getMessage().equalsIgnoreCase("Connection reset")) {
logIO.debug(GuardianLog.Type.INFO,
"Client with IP " + clientIO.getInetAddress().getHostAddress()
+ " disconnected from Server with Port " + networkIO.getPort()
+ ".");
disconnect(new Socket(clientIO));
} else if (errorIO.getMessage().equalsIgnoreCase("sleep interrupted")) {
logIO.debug(
GuardianLog.Type.WARNING, "Socket Thread interrupted.", errorIO);
} else
logIO.append(
GuardianLog.Type.ERROR, "Socket throw an Error ", errorIO);
}
}
});
}

Extract .gz files in java

I'm trying to unzip some .gz files in java. After some researches i wrote this method:
public static void gunzipIt(String name){
byte[] buffer = new byte[1024];
try{
GZIPInputStream gzis = new GZIPInputStream(new FileInputStream("/var/www/html/grepobot/API/"+ name + ".txt.gz"));
FileOutputStream out = new FileOutputStream("/var/www/html/grepobot/API/"+ name + ".txt");
int len;
while ((len = gzis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
gzis.close();
out.close();
System.out.println("Extracted " + name);
} catch(IOException ex){
ex.printStackTrace();
}
}
when i try to execute it i get this error:
java.util.zip.ZipException: Not in GZIP format
how can i solve it? Thanks in advance for your help
Test a sample, correct, gzipped file to see whether the problem lies in your code or not.
There are many possible ways to build a (g)zip file. Your file may have been built differently from what Java's built-in support expects, and the fact that one uncompressor understands a compression variant is no guarantee that Java will also recognize that variant. Please verify exact file type with file and/or other uncompression utilities that can tell you which options were used when compressing it. You may also have a look at the file itself with a tool such as hexdump. This is the output of the following command:
$ hexdump -C lgpl-2.1.txt.gz | head
00000000 1f 8b 08 08 ed 4f a9 4b 00 03 6c 67 70 6c 2d 32 |.....O.K..lgpl-2|
00000010 2e 31 2e 74 78 74 00 a5 5d 6d 73 1b 37 92 fe 8e |.1.txt..]ms.7...|
00000020 ba 1f 81 d3 97 48 55 34 13 7b 77 73 97 78 2b 55 |.....HU4.{ws.x+U|
00000030 b4 44 d9 bc 95 25 2d 29 c5 eb ba ba aa 1b 92 20 |.D...%-)....... |
00000040 39 f1 70 86 99 17 29 bc 5f 7f fd 74 37 30 98 21 |9.p...)._..t70.!|
00000050 29 7b ef 52 9b da 58 c2 00 8d 46 bf 3c fd 02 d8 |){.R..X...F.<...|
00000060 da fe 3f ef 6f 1f ed cd 78 36 1b 4f ed fb f1 ed |..?.o...x6.O....|
00000070 78 3a ba b1 f7 8f ef 6e 26 97 96 fe 1d df ce c6 |x:.....n&.......|
00000080 e6 e0 13 f9 e7 57 57 56 69 91 db 37 c3 d7 03 7b |.....WWVi..7...{|
00000090 ed e6 65 93 94 7b fb fa a7 9f 7e 32 c6 5e 16 bb |..e..{....~2.^..|
In this case, I used standard gzip on this license text. The 1st few bytes are unique to GZipped files (although they do not specify variants) - if your file does not start with 1f 8b, Java will complain, regardless of remaining contents.
If the problem is due to the file, it is possible that other uncompression libraries available in Java may deal with the format correctly - for example, see Commons Compress
import com.horsefly.utils.GZIP;
import org.apache.commons.io.FileUtils;
....
String content = new String(new GZIP().decompresGzipToBytes(FileUtils.readFileToByteArray(fileName)), "UTF-8");
in case someone needs it.

Fatal Error :1:40: Content is not allowed in prolog

I have a super simple XML document encoded in UTF-16 LE.
<?xml version="1.0" encoding="utf-16"?><X id="1" />
I'm loading it in as such (using jcabi-xml):
BOMInputStream bomIn = new BOMInputStream(Main.class.getResourceAsStream("resources/test.xml"), ByteOrderMark.UTF_16LE);
String firstNonBomCharacter = Character.toString((char)bomIn.read());
Reader reader = new InputStreamReader(bomIn, "UTF-16");
String xmlString = IOUtils.toString(reader);
xmlString = xmlString.trim();
xmlString = firstNonBomCharacter + xmlString;
bomIn.close();
reader.close();
final XML xml = new XMLDocument(xmlString);
I have checked that there are no extra BOM/junk symbols (leading or anywhere) by saving out the file and inspecting it with a hex editor. The XML is properly formatted.
However, I still get the following error:
[Fatal Error] :1:40: Content is not allowed in prolog.
Exception in thread "main" java.lang.IllegalArgumentException: Invalid XML: "<?xml version="1.0" encoding="utf-16"?><X id="1" />"
at com.jcabi.xml.DomParser.document(DomParser.java:115)
at com.jcabi.xml.XMLDocument.<init>(XMLDocument.java:155)
at Main.getTransformedString(Main.java:47)
at Main.main(Main.java:26)
Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 40; Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at com.jcabi.xml.DomParser.document(DomParser.java:105)
... 3 more
I have googled up and down for this error but they all say that it's the BOM's fault, which I have confirmed (to the best of my knowledge) to not be the case. What else could be wrong?
The following works for me:
try (InputStream stream = Test.class.getResourceAsStream("/Test.xml")) {
StreamSource source = new StreamSource(stream);
final XML xml = new XMLDocument(source);
}
With the input file's hex dump:
FF FE 3C 00 3F 00 78 00 6D 00 6C 00 20 00 76 00 65 00 72 00 73 00 69 00
6F 00 6E 00 3D 00 27 00 31 00 2E 00 30 00 27 00 20 00 65 00 6E 00 63 00
6F 00 64 00 69 00 6E 00 67 00 3D 00 27 00 55 00 54 00 46 00 2D 00 31 00
36 00 27 00 3F 00 3E 00 3C 00 58 00 20 00 69 00 64 00 3D 00 22 00 31 00
22 00 2F 00 3E 00
As far as I can tell, in your example you are converting the contents of the file to a string. But this is problematic because you actually throw away the encoding when you convert bytes to string. When the SAX parser converts the string to a byte array, it decides it will be UTF-8, but the prolog states that it is UTF-16 and so you have a problem.
Instead, when I use the StreamSource, it just automatically detects the fact that the file is encoded in UTF-16 LE from the BOM.
If you are not using java-7 or up and cannot use try-with-resources, then use the stream.close() as before.

H.323, How to make a simple ring without media. This script was following Q.931 setup but still not working

Can anyone please help me to solve this? When i send this request i have seen in wireshark that packets are going to SJPhone in 1720 tcp port. But still SJPhone does not ring. I want to make it ring (no matter for media).
I would really appreciate your support. I must be missing the message protocol details to implement this. Please show me some positive pointers.
FYI: i have used this trace: http://www.vconsole.com/usermanuals/sample_isdn_trace.pdf
import java.io.*;
import java.net.*;
public class test
{
public static void main(String[] args) throws UnknownHostException, IOException
{
/* Step 1: simulate the Q.931 packets exchange */
byte st[]=new byte[256];
st[0]=0x08; // protocol discriminator
st[1]=0x02; // length (bytes) of call reference
st[2]=0x02; // call reference (1-15 bytes)
// message type
st[3]=0x05;
// information Elements
st[4]=0x6C; // calling party number
st[5]=0; // unknown
st[6]=0; // unknown
st[7]=1; // "1"
// information elements
st[8]=0x70; // called party number
st[9]=0; // unknown
st[10]=0; // unknown
st[11]=5; // "5"
System.out.println(st);
/* Step 2: by-pass it for testing with tcpdump */
Socket clientSocket = new Socket("localhost", 1720);
DataInputStream input = new DataInputStream(clientSocket.getInputStream());
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.write(st);
String get;
get = inFromServer.readLine();
System.out.println("FROM SERVER: " + get);
clientSocket.close();
}
}
--More info:
-When SJPhone to SJPhone communicate i see this logs:
0000 00 00 03 04 00 06 00 00 00 00 00 00 00 00 08 00 ................
0010 45 00 00 3c 88 6c 40 00 40 06 b4 4d 7f 00 00 01 E..<.l#.#..M....
0020 7f 00 00 01 b4 a8 06 b8 56 f6 c4 b3 00 00 00 00 ........V.......
0030 a0 02 80 18 fe 30 00 00 02 04 40 0c 04 02 08 0a .....0....#.....
0040 02 a1 4c df 00 00 00 00 01 03 03 06 ..L.........
-When this test.java communicate to SJPhone i see this logs:
0000 00 00 03 04 00 06 00 00 00 00 00 00 00 00 08 00 ........ ........
0010 45 00 00 3c 1f ba 40 00 40 06 1d 00 7f 00 00 01 E..<..#. #.......
0020 7f 00 00 01 d6 ca 06 b8 8c e7 41 15 00 00 00 00 ........ ..A.....
0030 a0 02 80 18 fe 30 00 00 02 04 40 0c 04 02 08 0a .....0.. ..#.....
0040 02 a6 5e af 00 00 00 00 01 03 03 06 ..^..... ....
Note:
Friendly dump can be done using this command, to see realtime + save what you have seen: tcpdump -XX -s 0 -i lo | tee /tmp/log.log
So, the question was only to send a ring, without an actual call.
Here is some code that does the job. It was a lot of fun to see when it started working:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
/**
*
* #author martijncourteaux
*/
public class SJPhoneRinger
{
private static String setupOpenLogicChannel = "03|00|02|32|08|02|10|00|05|04|03|88|c0|a5|28|07|75|6e|6b|6e|6f|77|6e|6c|05|81|32|30|30|35|7e|02|11|05|20|88|06|00|08|91|4a|00|04|22|c0|00|00|00|00|0f|53|4a|20|4c|61|62|73|ae|20|53|4a|70|68|6f|6e|65|08|31|2e|36|30|2e|32|39|39|61|00|7f|00|00|01|06|b8|00|c4|a1|56|3c|d2|1d|b2|11|a8|ed|b7|8a|c2|c1|98|8f|00|c1|1d|80|04|11|00|f6|a1|56|3c|d2|1d|b2|11|a8|ed|b7|8a|c2|c1|98|8f|81|3a|0a|21|40|00|00|06|04|01|00|4e|0c|03|00|20|00|80|12|1e|00|01|00|7f|00|00|01|c0|04|00|7f|00|00|01|c0|05|00|2b|40|00|00|06|04|01|00|4c|10|00|00|00|00|09|69|4c|42|43|2d|31|33|6b|33|80|12|1e|40|01|00|7f|00|00|01|c0|04|00|7f|00|00|01|c0|05|04|2b|40|00|00|06|04|01|00|4c|10|00|00|00|00|09|69|4c|42|43|2d|31|35|6b|32|80|12|1e|40|01|00|7f|00|00|01|c0|04|00|7f|00|00|01|c0|05|08|1e|40|00|00|06|04|01|00|4c|20|13|80|12|1e|00|01|00|7f|00|00|01|c0|04|00|7f|00|00|01|c0|05|00|1e|40|00|00|06|04|01|00|4c|60|13|80|12|1e|00|01|00|7f|00|00|01|c0|04|00|7f|00|00|01|c0|05|00|16|00|00|0d|0e|0c|03|00|20|00|80|0b|06|00|01|00|7f|00|00|01|c0|05|00|20|00|00|0e|0c|10|00|00|00|00|09|69|4c|42|43|2d|31|33|6b|33|80|0b|06|40|01|00|7f|00|00|01|c0|05|04|20|00|00|0f|0c|10|00|00|00|00|09|69|4c|42|43|2d|31|35|6b|32|80|0b|06|40|01|00|7f|00|00|01|c0|05|08|13|00|00|10|0c|20|13|80|0b|06|00|01|00|7f|00|00|01|c0|05|00|13|00|00|11|0c|60|13|80|0b|06|00|01|00|7f|00|00|01|c0|05|00|01|00|01|00|01|00|01|00|6e|02|64|02|70|01|06|00|08|81|75|00|08|80|0d|00|00|3c|00|01|00|00|01|00|00|01|00|00|04|80|00|00|24|18|03|00|20|00|80|00|01|20|20|00|00|00|00|09|69|4c|42|43|2d|31|33|6b|33|80|00|02|20|20|00|00|00|00|09|69|4c|42|43|2d|31|35|6b|32|80|00|03|20|40|13|80|00|04|20|c0|13|00|80|06|00|04|00|00|00|01|00|02|00|03|00|04|07|01|00|32|80|d8|50|5f|02|80|01|80";
private static String alertingTSCA = "03|00|00|d8|08|02|90|00|01|28|07|75|6e|6b|6e|6f|77|6e|7e|00|c3|05|23|c0|06|00|08|91|4a|00|04|22|c0|00|00|00|00|0f|53|4a|20|4c|61|62|73|ae|20|53|4a|70|68|6f|6e|65|08|31|2e|36|30|2e|32|38|39|61|00|5e|e0|cc|44|98|ff|0d|0c|11|00|f6|a1|56|3c|d2|1d|b2|11|a8|ed|b7|8a|c2|c1|98|8f|01|00|01|00|04|c0|01|80|74|04|03|21|80|01|64|02|70|01|06|00|08|81|75|00|08|80|0d|00|00|3c|00|01|00|00|01|00|00|01|00|00|04|80|00|00|24|18|03|00|20|00|80|00|01|20|20|00|00|00|00|09|69|4c|42|43|2d|31|33|6b|33|80|00|02|20|20|00|00|00|00|09|69|4c|42|43|2d|31|35|6b|32|80|00|03|20|40|13|80|00|04|20|c0|13|00|80|06|00|04|00|00|00|01|00|02|00|03|00|04|06|01|00|32|40|1b|33|02|20|80";
private static String facilityTSCA = "03|00|00|62|08|02|10|00|62|1c|00|28|07|75|6e|6b|6e|6f|77|6e|7e|00|4b|05|26|90|06|00|08|91|4a|00|04|c4|a1|56|3c|d2|1d|b2|11|a8|ed|b7|8a|c2|c1|98|8f|86|01|00|13|05|80|11|00|f6|a1|56|3c|d2|1d|b2|11|a8|ed|b7|8a|c2|c1|98|8f|07|00|5e|e0|cc|44|ab|62|01|00|01|00|04|c0|01|80|08|02|03|21|80|01|02|20|a0";
private static String connectOpenLogicChannel = "03|00|00|b6|08|02|90|00|07|28|07|75|6e|6b|6e|6f|77|6e|7e|00|a1|05|22|c0|06|00|08|91|4a|00|04|00|5e|e0|cc|44|98|ff|22|c0|00|00|00|00|0f|53|4a|20|4c|61|62|73|ae|20|53|4a|70|68|6f|6e|65|08|31|2e|36|30|2e|32|38|39|61|00|c4|a1|56|3c|d2|1d|b2|11|a8|ed|b7|8a|c2|c1|98|8f|0d|1c|11|00|f6|a1|56|3c|d2|1d|b2|11|a8|ed|b7|8a|c2|c1|98|8f|41|02|21|40|00|03|06|04|01|00|4e|0c|03|00|20|00|80|12|1e|00|01|00|7f|00|00|01|c0|04|00|5e|e0|cc|44|c0|07|00|1d|00|00|0d|0e|0c|03|00|20|00|80|12|1e|00|01|00|5e|e0|cc|44|c0|06|00|5e|e0|cc|44|c0|07|00|01|00|01|00|02|80|01|80";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
Socket socket = new Socket("localhost", 1720);
System.out.println("Connected to SJPhone!");
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
sendBytes(dos, setupOpenLogicChannel);
/* Following three packages were not needed. It worked without them.
* Of course, because it is only a sample ring request, SJPhone will tell you
* That the call is corrupted */
// sendBytes(dos, alertingTSCA);
// sendBytes(dos, facilityTSCA);
// sendBytes(dos, connectOpenLogicChannel);
try
{
Thread.sleep(10000); // Let it ring for ten seconds.
} catch (Exception e)
{
}
}
public static void sendBytes(OutputStream os, String bytes) throws IOException
{
String byteArrayStr[] = bytes.split("\\|");
byte bytesArray[] = new byte[byteArrayStr.length];
for (int i = 0; i < byteArrayStr.length; ++i)
{
bytesArray[i] = (byte) (Integer.parseInt(byteArrayStr[i],16));
}
os.write(bytesArray);
os.flush();
}
}

Read Java in as Hex

I have tried to solve this but I keep coming up with stuff that is no help I'm sure this is easy (when you know how of course ;) )
What I would like to do is read in a file using a byte stream like below:
while((read = in.read()) != -1){
//code removed to save space
Integer.toHexString(read);
System.out.println(read);
}
When it prints out the Hex to the screen it will print out numbers fine e.g
31
13
12
0
but when it comes to a hex code that should be 01 31 it will print 0 131. I want to read it in to a variable like you would see in a hex editor i.e 00 11 21 31 no single numbers as i need to scan the whole file and look for patterns which I know how to do I'm just stuck on this :/
so in short i need a variabe to contain the two hex characters i.e int temp = 01 not int temp = 0 , I hope this all makes sense, I'm a little confused as it's 3am!
If anyone knows how to do this I would be most greatful, p.s thanks for the help in advance this site has saved me loads of research and have learnt a lot!
Many thanks.
This method :
public static void printHexStream(final InputStream inputStream, final int numberOfColumns) throws IOException{
long streamPtr=0;
while (inputStream.available() > 0) {
final long col = streamPtr++ % numberOfColumns;
System.out.printf("%02x ",inputStream.read());
if (col == (numberOfColumns-1)) {
System.out.printf("\n");
}
}
}
will output something like this :
40 32 38 00 5f 57 69 64 65 43
68 61 72 54 6f 4d 75 6c 74 69
42 79 74 65 40 33 32 00 5f 5f
69 6d 70 5f 5f 44 65 6c 65 74
65 46 69 6c 65 41 40 34 00 5f
53 65 74 46 69 6c 65 50 6f 69
6e 74 65 72 40 31 36 00 5f 5f
69 6d 70 5f 5f 47 65 74 54 65
6d 70 50 61 74 68 41 40 38 00
Is it what you are looking for?
I think what you're looking for is a formatter. Try:
Formatter formatter = new Formatter();
formatter.format("%02x", your_int);
System.out.println(formatter.toString());
Does that do what you're looking for? Your question wasn't all that clear (and I think maybe you deleted too much code from your snippet).
import org.apache.commons.io.IOUtils;
import org.apache.commons.codec.binary.Hex;
InputStream is = new FileInputStream(new File("c:/file.txt"));
String hexString = Hex.encodeHexString(IOUtils.toByteArray(is));
In java 7 you can read byte array directly from file as below :
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("path/to/file");
byte[] data = Files.readAllBytes(path)
Hi everyone one posted, thanks for the reply but the way I eneded up doing it was:
hexIn = in.read();
s = Integer.toHexString(hexIn);
if(s.length() < 2){
s = "0" + Integer.toHexString(hexIn);
}
Just thought I would post they way I did it for anyone else in future, thank you soo much for your help though!

Categories