SSHD Java example - java

Can anyone point me to some example code for using SSHD to access a server and execute some commands from a JAVA application. I have looked through the Apache SSHD website and downloads and have not found anything useful yet as far as documentation and example code. I also googled SSHD example code and was unsuccessful.

This one can run,I have checked it.I just delete the import.
version apache sshd-core-0.7.0.jar
public class SshClient extends AbstractFactoryManager implements ClientFactoryManager {
protected IoConnector connector;
protected SessionFactory sessionFactory;
private ServerKeyVerifier serverKeyVerifier;
public SshClient() {
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public ServerKeyVerifier getServerKeyVerifier() {
return serverKeyVerifier;
}
public void setServerKeyVerifier(ServerKeyVerifier serverKeyVerifier) {
this.serverKeyVerifier = serverKeyVerifier;
}
public void start() {
// Register the additional agent forwarding channel if needed
if (getAgentFactory() != null) {
List<NamedFactory<Channel>> factories = getChannelFactories();
if (factories == null) {
factories = new ArrayList<NamedFactory<Channel>>();
} else {
factories = new ArrayList<NamedFactory<Channel>>(factories);
}
factories.add(getAgentFactory().getChannelForwardingFactory());
setChannelFactories(factories);
}
connector = createAcceptor();
if (sessionFactory == null) {
sessionFactory = new SessionFactory();
}
sessionFactory.setClient(this);
connector.setHandler(sessionFactory);
}
protected NioSocketConnector createAcceptor() {
return new NioSocketConnector(getNioWorkers());
}
public void stop() {
connector.dispose();
connector = null;
}
public ConnectFuture connect(String host, int port) throws Exception {
assert host != null;
assert port >= 0;
if (connector == null) {
throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server");
}
SocketAddress address = new InetSocketAddress(host, port);
return connect(address);
}
public ConnectFuture connect(SocketAddress address) throws Exception {
assert address != null;
if (connector == null) {
throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server");
}
final ConnectFuture connectFuture = new DefaultConnectFuture(null);
connector.connect(address).addListener(new IoFutureListener<org.apache.mina.core.future.ConnectFuture>() {
public void operationComplete(org.apache.mina.core.future.ConnectFuture future) {
if (future.isCanceled()) {
connectFuture.cancel();
} else if (future.getException() != null) {
connectFuture.setException(future.getException());
} else {
ClientSessionImpl session = (ClientSessionImpl) AbstractSession.getSession(future.getSession());
connectFuture.setSession(session);
}
}
});
return connectFuture;
}
/**
* Setup a default client. The client does not require any additional setup.
*
* #return a newly create SSH client
*/
public static SshClient setUpDefaultClient() {
SshClient client = new SshClient();
// DHG14 uses 2048 bits key which are not supported by the default JCE provider
if (SecurityUtils.isBouncyCastleRegistered()) {
client.setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>>asList(
new DHG14.Factory(),
new DHG1.Factory()));
client.setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
} else {
client.setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>>asList(
new DHG1.Factory()));
client.setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
}
setUpDefaultCiphers(client);
// Compression is not enabled by default
// client.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList(
// new CompressionNone.Factory(),
// new CompressionZlib.Factory(),
// new CompressionDelayedZlib.Factory()));
client.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList(
new CompressionNone.Factory()));
client.setMacFactories(Arrays.<NamedFactory<Mac>>asList(
new HMACMD5.Factory(),
new HMACSHA1.Factory(),
new HMACMD596.Factory(),
new HMACSHA196.Factory()));
client.setSignatureFactories(Arrays.<NamedFactory<Signature>>asList(
new SignatureDSA.Factory(),
new SignatureRSA.Factory()));
return client;
}
private static void setUpDefaultCiphers(SshClient client) {
List<NamedFactory<Cipher>> avail = new LinkedList<NamedFactory<Cipher>>();
avail.add(new AES128CBC.Factory());
avail.add(new TripleDESCBC.Factory());
avail.add(new BlowfishCBC.Factory());
avail.add(new AES192CBC.Factory());
avail.add(new AES256CBC.Factory());
for (Iterator<NamedFactory<Cipher>> i = avail.iterator(); i.hasNext();) {
final NamedFactory<Cipher> f = i.next();
try {
final Cipher c = f.create();
final byte[] key = new byte[c.getBlockSize()];
final byte[] iv = new byte[c.getIVSize()];
c.init(Cipher.Mode.Encrypt, key, iv);
} catch (InvalidKeyException e) {
i.remove();
} catch (Exception e) {
i.remove();
}
}
client.setCipherFactories(avail);
}
/*=================================
Main class implementation
*=================================*/
public static void main(String[] args) throws Exception {
int port = 22;
String host = null;
String login = System.getProperty("user.name");
boolean agentForward = false;
List<String> command = null;
int logLevel = 0;
boolean error = false;
for (int i = 0; i < args.length; i++) {
if (command == null && "-p".equals(args[i])) {
if (i + 1 >= args.length) {
System.err.println("option requires an argument: " + args[i]);
error = true;
break;
}
port = Integer.parseInt(args[++i]);
} else if (command == null && "-l".equals(args[i])) {
if (i + 1 >= args.length) {
System.err.println("option requires an argument: " + args[i]);
error = true;
break;
}
login = args[++i];
} else if (command == null && "-v".equals(args[i])) {
logLevel = 1;
} else if (command == null && "-vv".equals(args[i])) {
logLevel = 2;
} else if (command == null && "-vvv".equals(args[i])) {
logLevel = 3;
} else if ("-A".equals(args[i])) {
agentForward = true;
} else if ("-a".equals(args[i])) {
agentForward = false;
} else if (command == null && args[i].startsWith("-")) {
System.err.println("illegal option: " + args[i]);
error = true;
break;
} else {
if (host == null) {
host = args[i];
} else {
if (command == null) {
command = new ArrayList<String>();
}
command.add(args[i]);
}
}
}
if (host == null) {
System.err.println("hostname required");
error = true;
}
if (error) {
System.err.println("usage: ssh [-A|-a] [-v[v][v]] [-l login] [-p port] hostname [command]");
System.exit(-1);
}
// TODO: handle log level
SshClient client = SshClient.setUpDefaultClient();
client.start();
try {
boolean hasKeys = false;
/*
String authSock = System.getenv(SshAgent.SSH_AUTHSOCKET_ENV_NAME);
if (authSock == null) {
KeyPair[] keys = null;
AgentServer server = new AgentServer();
authSock = server.start();
List<String> files = new ArrayList<String>();
File f = new File(System.getProperty("user.home"), ".ssh/id_dsa");
if (f.exists() && f.isFile() && f.canRead()) {
files.add(f.getAbsolutePath());
}
f = new File(System.getProperty("user.home"), ".ssh/id_rsa");
if (f.exists() && f.isFile() && f.canRead()) {
files.add(f.getAbsolutePath());
}
try {
if (files.size() > 0) {
keys = new FileKeyPairProvider(files.toArray(new String[0]), new PasswordFinder() {
public char[] getPassword() {
try {
System.out.println("Enter password for private key: ");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String password = r.readLine();
return password.toCharArray();
} catch (IOException e) {
return null;
}
}
}).loadKeys();
}
} catch (Exception e) {
}
SshAgent agent = new AgentClient(authSock);
for (KeyPair key : keys) {
agent.addIdentity(key, "");
}
agent.close();
}
if (authSock != null) {
SshAgent agent = new AgentClient(authSock);
hasKeys = agent.getIdentities().size() > 0;
}
client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME, authSock);
*/
ClientSession session = client.connect(host, port).await().getSession();
int ret = ClientSession.WAIT_AUTH;
while ((ret & ClientSession.WAIT_AUTH) != 0) {
if (hasKeys) {
session.authAgent(login);
ret = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
} else {
System.out.print("Password:");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String password = r.readLine();
session.authPassword(login, password);
ret = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
}
}
if ((ret & ClientSession.CLOSED) != 0) {
System.err.println("error");
System.exit(-1);
}
ClientChannel channel;
if (command == null) {
channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
((ChannelShell) channel).setAgentForwarding(agentForward);
channel.setIn(new NoCloseInputStream(System.in));
} else {
channel = session.createChannel(ClientChannel.CHANNEL_EXEC);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(baos);
for (String cmd : command) {
w.append(cmd).append(" ");
}
w.append("\n");
w.close();
channel.setIn(new ByteArrayInputStream(baos.toByteArray()));
}
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open().await();
channel.waitFor(ClientChannel.CLOSED, 0);
session.close(false);
} finally {
client.stop();
}
}
}

public static void main(String[] args) throws IOException, InterruptedException
{
SshClient client = SshClient.setUpDefaultClient();
client.start();
final ClientSession session = client.connect("bob", "bob.mynetwork.com", 22).await().getSession();
int authState = ClientSession.WAIT_AUTH;
while ((authState & ClientSession.WAIT_AUTH) != 0) {
session.addPasswordIdentity("bobspassword");
System.out.println("authenticating...");
final AuthFuture authFuture = session.auth();
authFuture.addListener(new SshFutureListener<AuthFuture>()
{
#Override
public void operationComplete(AuthFuture arg0)
{
System.out.println("Authentication completed with " + ( arg0.isSuccess() ? "success" : "failure"));
}
});
authState = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
}
if ((authState & ClientSession.CLOSED) != 0) {
System.err.println("error");
System.exit(-1);
}
final ClientChannel channel = session.createShellChannel();
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open();
executeCommand(channel, "pwd\n");
executeCommand(channel, "ll\n");
channel.waitFor(ClientChannel.CLOSED, 0);
session.close(false);
client.stop();
}
private static void executeCommand(final ClientChannel channel, final String command) throws IOException
{
final InputStream commandInput = new ByteArrayInputStream(command.getBytes());
channel.setIn(new NoCloseInputStream(commandInput));
}

Having tracked development regarding Java support for SSH for many years now, I strongly recommend against using any Java SSH implementation. Noone cares to develop them any further. None of them has proper SSH-Agent support. And SSH without SSH-Agent, especially when running code on top of it, makes those implementations rather useless - unless you are willing to put unencrypted keys or passwords everywhere.
The best solution IMHO is to write a wrapper around the rock-solid OpenSSH implementations.

Related

Execute command line equivalent to Runtime.getRuntime().exec(cmd); in JNI C

I was developing an app which had requirement to implement root detection logic, so by researching I found some detection logic in JAVA and had implemented following class.
class RootDetection {
public boolean isDeviceRooted() {
return checkForBinary("su") || checkForBinary("busybox") || checkForMaliciousPaths() || checkSUonPath()
|| detectRootManagementApps() || detectPotentiallyDangerousApps() || detectRootCloakingApps()
|| checkForDangerousProps() || checkForRWPaths()
|| detectTestKeys() || checkSuExists();
}
private boolean detectTestKeys() {
String buildTags = android.os.Build.TAGS;
String buildFinger = Build.FINGERPRINT;
String product = Build.PRODUCT;
String hardware = Build.HARDWARE;
String display = Build.DISPLAY;
System.out.println("Java: build: " + buildTags + "\nFingerprint: " + buildFinger + "\n Product: " + product + "\n Hardware: " + hardware + "\nDisplay: " + display);
return (buildTags != null) && (buildTags.contains("test-keys") || buildFinger.contains("genric.*test-keys") || product.contains("generic") || product.contains("sdk") || hardware.contains("goldfish") || display.contains(".*test-keys"));
}
private boolean detectRootManagementApps() {
return detectRootManagementApps(null);
}
private boolean detectRootManagementApps(String[] additionalRootManagementApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownRootAppsPackages));
if (additionalRootManagementApps != null && additionalRootManagementApps.length > 0) {
packages.addAll(Arrays.asList(additionalRootManagementApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean detectPotentiallyDangerousApps() {
return detectPotentiallyDangerousApps(null);
}
private boolean detectPotentiallyDangerousApps(String[] additionalDangerousApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownDangerousAppsPackages));
if (additionalDangerousApps != null && additionalDangerousApps.length > 0) {
packages.addAll(Arrays.asList(additionalDangerousApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean detectRootCloakingApps() {
return detectRootCloakingApps(null);
}
private boolean detectRootCloakingApps(String[] additionalRootCloakingApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownRootCloakingPackages));
if (additionalRootCloakingApps != null && additionalRootCloakingApps.length > 0) {
packages.addAll(Arrays.asList(additionalRootCloakingApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean checkForBinary(String filename) {
for (String path : suPaths) {
String completePath = path + filename;
File f = new File(completePath);
boolean fileExists = f.exists();
if (fileExists) {
return true;
}
}
return false;
}
private boolean checkForMaliciousPaths() {
for (String path : maliciousPaths) {
File f = new File(path);
boolean fileExists = f.exists();
if (fileExists) {
return true;
}
}
return false;
}
private static boolean checkSUonPath() {
for (String pathDir : System.getenv("PATH").split(":")) {
if (new File(pathDir, "su").exists()) {
return true;
}
}
return false;
}
private String[] propsReader() {
InputStream inputstream = null;
try {
inputstream = Runtime.getRuntime().exec("getprop").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String propval = "";
try {
propval = new Scanner(inputstream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
}
return propval.split("\n");
}
private String[] mountReader() {
InputStream inputstream = null;
try {
inputstream = Runtime.getRuntime().exec("mount").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
if (inputstream == null) return null;
String propval = "";
try {
propval = new Scanner(inputstream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
e.printStackTrace();
}
return propval.split("\n");
}
private boolean isAnyPackageFromListInstalled(List<String> packages) {
PackageManager pm = activity.getPackageManager();
for (String packageName : packages) {
try {
pm.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
}
return false;
}
private boolean checkForDangerousProps() {
final Map<String, String> dangerousProps = new HashMap<>();
dangerousProps.put("ro.debuggable", "1");
dangerousProps.put("ro.secure", "0");
String[] lines = propsReader();
for (String line : lines) {
for (String key : dangerousProps.keySet()) {
if (line.contains(key)) {
String badValue = dangerousProps.get(key);
badValue = "[" + badValue + "]";
if (line.contains(badValue)) {
return true;
}
}
}
}
return false;
}
private boolean checkForRWPaths() {
String[] lines = mountReader();
for (String line : lines) {
String[] args = line.split(" ");
if (args.length < 4) {
continue;
}
String mountPoint = args[1];
String mountOptions = args[3];
for (String pathToCheck : pathsThatShouldNotBeWrtiable) {
if (mountPoint.equalsIgnoreCase(pathToCheck)) {
for (String option : mountOptions.split(",")) {
if (option.equalsIgnoreCase("rw")) {
return true;
}
}
}
}
}
return false;
}
private boolean checkSuExists() {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[]{"which", "su"});
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
return in.readLine() != null;
} catch (Throwable t) {
return false;
} finally {
if (process != null) process.destroy();
}
}
}
but now to increase security I want to do this root detection logic in native C++ JNI code. I managed to migrate package detection code to JNI C but am not able to find anything regarding these 3 functions
checkForDangerousProps(),checkForRWPaths(),checkSuExists()
these 3 use Runtime.getRuntime().exec which am not able to find. can someone help me in converting this 3 logics to JNI C one from above code? Help would be really appreciated.
Pls guys help.

Bouncy castle gives unknown HashAlgorithm

I am trying to use bouncy castle for DTLS Handshake.
I have generated key by following this link. I am working by extending DefaultTlsClient. It can generate client_hello packet. But when the server_hello packet arrives it gives org.bouncycastle.crypto.tls.TlsFatalAlert: internal_error(80) Caused by: java.lang.IllegalArgumentException: unknown HashAlgorithm. Can anyone give any hint?
Update:
From Wireshark: In the Certificate Request, there are 9 Signature Hash Algorithms. One of them is rsa_pss_sha256(0x0804). In the public static Digest createHash(short hashAlgorithm) function in TlsUtils.java there is no matching for it. That's why it is giving Unknown hash Algorithm. What does that mean? Using Bouncy Castle, is it possible to establish DTLS with that server?
Here is the code for loading the keystore:
public static void initKeyStore() {
char password[] = "bbtone".toCharArray();
if( !isKeystoreLoaded) {
try {
FileInputStream fis = new FileInputStream("bbtone");
KeyMgmt key = new KeyMgmt();
key.open(fis, password);
fis.close();
crt = key.getCRT("bbtone").getEncoded();
fingerprintSHA256 = KeyMgmt.fingerprintSHA256(crt);
ArrayList<byte[]> chain = new ArrayList<byte[]>();
chain.add(crt);
java.security.cert.Certificate root = key.getCRT("root");
if (root != null) {
chain.add(root.getEncoded());
}
privateKey = key.getKEY("bbtone", password).getEncoded();
initDTLS(chain, privateKey, false);
isKeystoreLoaded = true;
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Generating private key and certificate:
public static boolean initDTLS(java.util.List<byte []> certChain, byte privateKey[], boolean pkRSA) {
try {
org.bouncycastle.asn1.x509.Certificate x509certs[] = new org.bouncycastle.asn1.x509.Certificate[certChain.size()];
for (int i = 0; i < certChain.size(); ++i) {
x509certs[i] = org.bouncycastle.asn1.x509.Certificate.getInstance(certChain.get(i));
}
dtlsCertChain = new org.bouncycastle.crypto.tls.Certificate(x509certs);
if (pkRSA) {
RSAPrivateKey rsa = RSAPrivateKey.getInstance(privateKey);
dtlsPrivateKey = new RSAPrivateCrtKeyParameters(rsa.getModulus(), rsa.getPublicExponent(),
rsa.getPrivateExponent(), rsa.getPrime1(), rsa.getPrime2(), rsa.getExponent1(),
rsa.getExponent2(), rsa.getCoefficient());
} else {
dtlsPrivateKey = PrivateKeyFactory.createKey(privateKey);
}
return true;
} catch (Exception e) {
return false;
}
}
Starting DTLS Handshake:
public void startDTLS() {
socket.connect(recvPacket.getAddress(), recvPacket.getPort());
try {
dtlsClient = new DTLSClientProtocol(new SecureRandom());
} catch (Exception e) {
e.printStackTrace();
dtlsClient = null;
return;
}
tlsClient = new DefaultTlsClient2() {
protected TlsSession session;
public TlsSession getSessionToResume()
{
return this.session;
}
public ProtocolVersion getClientVersion() {
return ProtocolVersion.DTLSv12;
}
public ProtocolVersion getMinimumVersion() {
return ProtocolVersion.DTLSv10;
}
public Hashtable getClientExtensions() throws IOException {
//see : http://bouncy-castle.1462172.n4.nabble.com/DTLS-SRTP-with-bouncycastle-1-49-td4656286.html
logger.debug("Extending getClientExtensions\n");
Hashtable table = super.getClientExtensions();
if (table == null) table = new Hashtable();
//adding the protection profiles
int[] protectionProfiles = {
SRTPProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_80 //this is the only one supported for now
// SRTPProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_32
// SRTPProtectionProfile.SRTP_NULL_HMAC_SHA1_32
// SRTPProtectionProfile.SRTP_NULL_HMAC_SHA1_80
};
byte mki[] = new byte[0]; //do not use mki
UseSRTPData srtpData = new UseSRTPData(protectionProfiles, mki);
TlsSRTPUtils.addUseSRTPExtension(table, srtpData);
return table;
}
public TlsAuthentication getAuthentication() throws IOException {
return new TlsAuthentication() {
public void notifyServerCertificate(org.bouncycastle.crypto.tls.Certificate serverCertificate)
throws IOException
{
//info only
}
public TlsCredentials getClientCredentials(CertificateRequest certificateRequest)
throws IOException
{
short[] certificateTypes = certificateRequest.getCertificateTypes();
if (certificateTypes == null) return null;
boolean ok = false;
for(int a=0;a<certificateTypes.length;a++) {
if (certificateTypes[a] == ClientCertificateType.rsa_sign) {
ok = true;
break;
}
}
if (!ok) return null;
SignatureAndHashAlgorithm signatureAndHashAlgorithm = null;
Vector sigAlgs = certificateRequest.getSupportedSignatureAlgorithms();
if (sigAlgs != null)
{
for (int i = 0; i < sigAlgs.size(); ++i)
{
SignatureAndHashAlgorithm sigAlg = (SignatureAndHashAlgorithm) sigAlgs.elementAt(i);
if (sigAlg.getSignature() == SignatureAlgorithm.rsa)
{
signatureAndHashAlgorithm = sigAlg;
break;
}
}
if (signatureAndHashAlgorithm == null)
{
return null;
}
}
return new DefaultTlsSignerCredentials(context, dtlsCertChain, dtlsPrivateKey, signatureAndHashAlgorithm);
}
};
}
public void notifyHandshakeComplete() throws IOException
{
logger.debug("SRTPChannel:DTLS:Client:Handshake complete");
super.notifyHandshakeComplete();
TlsSession newSession = context.getResumableSession();
if (newSession != null)
{
this.session = newSession;
}
getKeys();
}
};
try {
logger.debug("SRTPChannel:connecting to DTLS server");
dtlsTransport = dtlsClient.connect(tlsClient, new UDPTransport(socket, 1500 - 20 - 8));
} catch (Exception e) {
e.printStackTrace();
}
}
Error:
org.bouncycastle.crypto.tls.TlsFatalAlert: internal_error(80)
at org.bouncycastle.crypto.tls.DTLSClientProtocol.connect(DTLSClientProtocol.java:75)
at processor.ClientMediaHandler.startDTLS(ClientMediaHandler.java:459)
at processor.ClientMediaHandler.run(ClientMediaHandler.java:538)
Caused by: java.lang.IllegalArgumentException: unknown HashAlgorithm
at org.bouncycastle.crypto.tls.TlsUtils.createHash(TlsUtils.java:1184)
at org.bouncycastle.crypto.tls.DeferredHash.checkTrackingHash(DeferredHash.java:203)
at org.bouncycastle.crypto.tls.DeferredHash.trackHashAlgorithm(DeferredHash.java:68)
at org.bouncycastle.crypto.tls.TlsUtils.trackHashAlgorithms(TlsUtils.java:1358)
at org.bouncycastle.crypto.tls.DTLSClientProtocol.clientHandshake(DTLSClientProtocol.java:241)
at org.bouncycastle.crypto.tls.DTLSClientProtocol.connect(DTLSClientProtocol.java:60)
... 2 more
I have solved the problem using DTLS1.0. It can now finish the handshake.
I replaced
public ProtocolVersion getClientVersion() {
return ProtocolVersion.DTLSv12;
}
with the following code:
public ProtocolVersion getClientVersion() {
return ProtocolVersion.DTLSv10;
}
#Rashed, downgrading TLS version is not a good choice. There is already comment from #bbaldino but I think it should be added as answer - version 1.60 of bouncy castle has a bug. Instead of downgrading TLS, you should upgrade bouncy castle to at least 1.61
https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on

Pass input to bash script using java input stream and collect bash script output to java output stream using thread

I am trying to pass input to bash script using java input stream and collect bash script output to java output stream using two different thread.
my bash script is:
#!/bin/sh
echo "added at start"
while read LINE; do
echo $LINE
done
and my Java code is:
public class NewRedirector implements Runnable {
private static final int BULK_BUFFER_SIZE = 500000;
private static final int READ_BUFFER_SIZE = 250000;
private static final int OFFSET = 0;
private final OutputStream targetStream;
private final InputStream sourceStream;
private final boolean useChannel;
public NewRedirector(InputStream sourceStream , OutputStream targetStream, boolean useChannel) {
this.sourceStream = sourceStream;
this.targetStream = targetStream;
this.useChannel = useChannel;
}
#Override
public void run() {
byte[] readbyte = new byte[READ_BUFFER_SIZE];
int dataSize = 0;
try {
if(targetStream instanceof FileOutputStream && useChannel) {
FileChannel targetFC = ((FileOutputStream) targetStream).getChannel();
try {
if(sourceStream instanceof FileInputStream && useChannel) {
FileChannel sourceFC = ((FileInputStream) sourceStream).getChannel();
ByteBuffer bb = ByteBuffer.allocateDirect(BULK_BUFFER_SIZE);
bb.clear();
dataSize = 0;
while ((dataSize = sourceFC.read(bb)) > 0) {
bb.flip();
while (bb.hasRemaining()) {
targetFC.write(bb);
}
bb.clear();
}
} else {
ByteBuffer bb = ByteBuffer.allocateDirect(BULK_BUFFER_SIZE);
dataSize = 0;
while ((dataSize = sourceStream.read(readbyte)) > 0) {
if(BULK_BUFFER_SIZE > bb.position() + dataSize) {
bb.put(readbyte, OFFSET, dataSize);
continue;
} else {
bb.flip();
targetFC.write(bb);
bb.clear();
}
bb.put(readbyte, OFFSET, dataSize);
}
if(bb.position() > 0) {
bb.flip();
targetFC.write(bb);
bb.clear();
}
}
} catch(IOException e) {
System.out.println("Got Exception: " + e);
} finally {
if(targetFC != null && targetFC.isOpen()) {
targetFC.close();
targetFC = null;
}
}
} else {
BufferedOutputStream btarget = new BufferedOutputStream(targetStream);
try {
if (sourceStream instanceof FileInputStream && useChannel) {
FileChannel sourceFC = ((FileInputStream) sourceStream).getChannel();
ByteBuffer bb = ByteBuffer.allocateDirect(BULK_BUFFER_SIZE);
bb.clear();
dataSize = 0;
while ((dataSize = sourceFC.read(bb)) > 0) {
bb.position(OFFSET);
bb.limit(dataSize);
while (bb.hasRemaining()) {
dataSize = Math.min(bb.remaining(), READ_BUFFER_SIZE);
bb.get(readbyte, OFFSET, dataSize);
btarget.write(readbyte, OFFSET, dataSize);
}
btarget.flush();
bb.clear();
}
} else {
dataSize = 0;
while ((dataSize = sourceStream.read(readbyte)) > 0) {
btarget.write(readbyte, OFFSET, dataSize);
}
btarget.flush();
}
} catch(IOException e) {
System.out.println("Got Exception: " + e);
} finally {
if(btarget != null) {
btarget.close();
btarget = null;
}
}
}
} catch (IOException e) {
System.out.println("Got Exception: " + e);
}
}
}
and
public class NewProcessExecutor {
public static void main(String ... args) throws IOException, InterruptedException {
NewProcessExecutor pe = new NewProcessExecutor();
pe.startProcessinputfromstreamoutputtostreamintwothread();
}
private void startProcessinputfromstreamoutputtostreamintwothread()
throws IOException, InterruptedException {
String lscriptLocation = "/scratch/demo/RunScript/append.sh";
File inFile = new File("/scratch/demo/Source/inFile");
File outFile = new File("/scratch/demo/Source/outFile");
ProcessBuilder processBuilder = new ProcessBuilder(lscriptLocation);
/*processBuilder.redirectInput(Redirect.PIPE);
processBuilder.redirectOutput(Redirect.PIPE);*/
Process process = processBuilder.start();
if(Redirect.PIPE.file() == null && Redirect.PIPE.type() == Redirect.Type.PIPE) {
System.out.println("IO connected over PIPE");
}
//startStreamRedirector(new FileInputStream(inFile), process.getOutputStream());
startStreamRedirector(process.getInputStream(), new FileOutputStream(outFile));
int exitvalue = process.waitFor();
System.out.println("Exit value: " + exitvalue);
if (exitvalue != 0) {
System.out.println("Script execution failed with error: "
+ readErrorStream(process.getErrorStream()));
return;
} else {
System.out.println("Script executed successfully, please see output file: " + outFile.getAbsolutePath());
}
}
private String readErrorStream(InputStream errorStream) {
StringBuilder sb = new StringBuilder();
try (BufferedReader buffR = new BufferedReader(new InputStreamReader(
errorStream))) {
String line = null;
while ((line = buffR.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
System.out.println("Got Exception: " + e);
}
return sb.toString();
}
private void startStreamRedirector(InputStream inputStream, OutputStream outputStream) {
new Thread(new NewRedirector(inputStream, outputStream, true)).start();
}
}
Now the problem is this code sometime runs perfectly but some times it creates zero size file.
Can someone point out what could be the issue?
As per my information default redirect is PIPE so hope I don't need set redirect input and output to PIPE.
processBuilder.redirectInput(Redirect.PIPE)

xmpp connection blackberry java

Im able to connect with xmpp server and login authentication is done but when im sending roster the inputstream is.read() giving me -1 and thrown an exception i dont know what to do now.please help me out.
My XMppCOnnection class:
package mypackage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.io.ConnectionNotFoundException
import javax.microedition.io.SecureConnection;
import javax.microedition.io.StreamConnection;
import net.rim.device.api.io.File;
import net.rim.device.api.io.FileInputStream;
import net.rim.device.api.io.FileOutputStream;
public class XMPPConnection extends XMPPThread {
private XmlReader reader;
private XmlWriter writer;
private InputStream is;
private OutputStream os;
FileInputStream fis;
FileOutputStream fos;
File file;
/**
* If you create this object all variables will be saved and the
* method {#link #run()} is started to log in on jabber server and
* listen to parse incomming xml stanzas. Use
* {#link #addListener(XmppListener xl)} to listen to events of this object.
*/
// jid must in the form "username#host"
// to login Google Talk, set port to 5223 (NOT 5222 in their offical guide)
public XMPPConnection(Connection connection) {
super(connection);
this.host = connection.getHost();
this.port = connection.getPort();
this.username = connection.getUsername();
this.password = connection.getPassword();
this.resource = "mobile";
this.myjid = this.username + "#" + this.host;
if (connection.getServer() == null)
this.server = host;
else
this.server = connection.getServer();
this.use_ssl = connection.isSSL();
this.connectionMaskIndex = connection.getNetworkType();
}
/**
* The <code>run</code> method is called when {#link XMPPConnection} object is
* created. It sets up the reader and writer, calls {#link #login()}
* methode and listens on the reader to parse incomming xml stanzas.
*/
public void run() {
try {
this.connect();
} catch (final IOException e) {
e.printStackTrace();
this.connectionFailed(e.getMessage());
return;
} catch (Exception e) {
e.printStackTrace();
this.connectionFailed(e.getMessage());
return;
}
// connected
try {
boolean loginSuccess = this.login();
if (loginSuccess) {
this.parse();
}
} catch (final Exception e) {
// hier entsteht der connection failed bug (Network Down)
java.lang.System.out.println(e);
this.connectionFailed(e.toString());
}
}
protected void connect() throws IOException, Exception {
if (!use_ssl) {
//final StreamConnection connection = (StreamConnection) Connector.open("http://" + this.server + ":" + this.port+this.connectionMask, Connector.READ_WRITE);
ConnectionFactory connectionFactory = new ConnectionFactory("socket://" + this.server + ":" + this.port, this.connectionMaskIndex);
StreamConnection connection = null;
try {
connection = (StreamConnection) connectionFactory.getNextConnection();
} catch (NoMoreTransportsException e) {
throw new Exception("Connection failed. No transport available.");
} catch (ConnectionNotFoundException e) {
throw new Exception("ConnectionNotFoundException:" + e.getMessage());
} catch (IllegalArgumentException e) {
throw new Exception("IllegalArgumentException: " + e.getMessage());
} catch (IOException e) {
throw new Exception("IOException: " + e.getMessage());
}
is = connection.openInputStream();
os = connection.openOutputStream();
this.reader = new XmlReader(is);
this.writer = new XmlWriter(os);
} else {
//final SecureConnection sc = (SecureConnection) Connector.open("ssl://" + this.server + ":" + this.port+this.connectionMask, Connector.READ_WRITE);
ConnectionFactory connectionFactory = new ConnectionFactory("ssl://" + this.server + ":" + this.port, this.connectionMaskIndex);
SecureConnection sc = null;
try {
sc = (SecureConnection) connectionFactory.getNextConnection();
} catch (NoMoreTransportsException e) {
throw new Exception("Connection failed. No transport available.");
} catch (ConnectionNotFoundException e) {
throw new Exception("ConnectionNotFoundException: " + e.getMessage());
} catch (IllegalArgumentException e) {
throw new Exception("IllegalArgumentException: " + e.getMessage());
} catch (IOException e) {
throw new Exception("IOException: " + e.getMessage());
}
if (sc != null) {
//sc.setSocketOption(SocketConnection.DELAY, 1);
//sc.setSocketOption(SocketConnection.LINGER, 0);
is = sc.openInputStream();
os = sc.openOutputStream();
this.reader = new XmlReader(is);
this.writer = new XmlWriter(os);
}
}
}
/**
* Opens the connection with a stream-tag, queries authentication type and
* sends authentication data, which is username, password and resource.
* #return
* #throws Exception
*/
protected boolean login() throws Exception {
String msg = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='" + this.host + "' version='1.0'>";
os.write(msg.getBytes());
os.flush();
do {
reader.next();
if (reader.getType() == XmlReader.START_TAG && reader.getName().equals("stream:features")) {
this.packetParser.parseFeatures(reader);
}
} while (!(reader.getType() == XmlReader.END_TAG && reader.getName().equals("stream:features")));
boolean loginSuccess = this.doAuthentication();
msg = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='" + this.host + "' version='1.0'>";
os.write(msg.getBytes());
os.flush();
reader.next();
while (true) {
if ((reader.getType() == XmlReader.END_TAG) && reader.getName().equals("stream:features")) {
break;
}
reader.next();
}
if (resource == null) {
msg = "<iq type='set' id='res_binding'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/></iq>";
} else {
msg = "<iq type='set' id='res_binding'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>" + resource + "</resource></bind></iq>";
}
os.write(msg.getBytes());
os.flush();
return loginSuccess;
}
protected void parse() throws IOException {
while (true) {
int nextTag = this.reader.next();
switch (nextTag) {
case XmlReader.START_TAG:
final String tmp = this.reader.getName();
if (tmp.equals("message")) {
this.packetParser.parseMessage(this.reader);
} else if (tmp.equals("presence")) {
this.packetParser.parsePresence(this.reader);
} else if (tmp.equals("iq")) {
this.packetParser.parseIq(this.reader, this.writer);
} else {
this.packetParser.parseIgnore(this.reader);
}
break;
case XmlReader.END_TAG:
this.reader.close();
throw new IOException("Unexpected END_TAG "+this.reader.getName());
default:
this.reader.close();
throw new IOException("Bad XML tag");
}
}
}
protected boolean doAuthentication() throws Exception {
boolean loginSuccess = false;
Vector mechanismList = this.packetParser.getMechanism();
System.out.println(mechanismList.toString());
if (mechanismList.contains("X-GOOGLE-TOKEN")) {
// X-GOOGLE-TOKEN authorization doing. User can disable
// google features using by deselecting corresponding
// checkbox in profile
String resp = this.packetParser.getGoogleToken(this.myjid, this.password);
String msg = "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"X-GOOGLE-TOKEN\">" + resp + "</auth>";
os.write(msg.getBytes());
//os.flush();
reader.next();
if (reader.getName().equals("success")) {
loginSuccess = true;
while (true) {
if ((reader.getType() == XmlReader.END_TAG) && reader.getName().equals("success")) {
break;
}
reader.next();
}
}
}
if (mechanismList.contains("PLAIN") && loginSuccess == false) {
String msg = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>";
byte[] auth_msg = (username + "#" + host + "\0" + username + "\0" + password).getBytes();
msg = msg + MD5.toBase64(auth_msg) + "</auth>";
os.write(msg.getBytes());
os.flush();
reader.next();
if (reader.getName().equals("success")) {
loginSuccess = true;
while (true) {
if ((reader.getType() == XmlReader.END_TAG) && reader.getName().equals("success")) {
break;
}
reader.next();
}
}
}
if (loginSuccess == false) {
for (Enumeration e = listeners.elements(); e.hasMoreElements();) {
XmppListener xl = (XmppListener) e.nextElement();
xl.onAuthFailed(reader.getName() + ", failed authentication");
}
return false;
}
return loginSuccess;
}
public void getRosterVCard(String tojid) throws IOException {
this.writer.startTag("iq");
this.writer.attribute("id", "vc2");
this.writer.attribute("to", tojid);
this.writer.attribute("type", "get");
this.writer.startTag("vCard");
this.writer.attribute("xmlns", "vcard-temp");
this.writer.endTag(); // vCard
this.writer.endTag(); // iq
this.writer.flush();
}
/**
* Sends a roster query.
*
* #throws java.io.IOException is thrown if {#link XmlReader} or {#link XmlWriter}
* throw an IOException.
*/
public void getRoster() throws IOException {
this.writer.startTag("iq");
// this.writer.attribute("id", "roster");
this.writer.attribute("type", "get");
this.writer.startTag("query");
this.writer.attribute("xmlns", "jabber:iq:roster");
this.writer.endTag(); // query
this.writer.endTag(); // iq
this.writer.flush();
//<iq id="qxmpp7" from="919700424402#213.204.83.20/QXmpp" type="get"><query xmlns="jabber:iq:roster"/></iq>
}
/**
* Sends a message text to a known jid.
*
* #param to the JID of the recipient
* #param msg the message itself
*/
public void sendMessage(final String to, final String msg, final String id) {
try {
this.writer.startTag("message");
this.writer.attribute("type", "chat");
this.writer.attribute("to", to);
this.writer.startTag("body");
this.writer.text(msg);
this.writer.endTag();
this.writer.endTag();
this.writer.flush();
} catch (final IOException e) {
java.lang.System.out.println(e);
this.connectionFailed();
}
}
/**
* Requesting a subscription.
*
* #param to the jid you want to subscribe
*/
public void subscribe(final String to) {
this.sendPresence(to, "subscribe", null, null, 0);
}
/**
* Remove a subscription.
*
* #param to the jid you want to remove your subscription
*/
public void unsubscribe(final String to) {
this.sendPresence(to, "unsubscribe", null, null, 0);
}
/**
* Approve a subscription request.
*
* #param to the jid that sent you a subscription request
*/
public void subscribed(final String to) {
this.sendPresence(to, "subscribed", null, null, 0);
}
/**
* Refuse/Reject a subscription request.
*
* #param to the jid that sent you a subscription request
*/
public void unsubscribed(final String to) {
this.sendPresence(to, "unsubscribed", null, null, 0);
}
/**
* Sets your Jabber Status.
*
* #param show is one of the following: <code>null</code>, chat, away,
* dnd, xa, invisible
* #param status an extended text describing the actual status
* #param priority the priority number (5 should be default)
*/
public void setStatus(String show, String status, final int priority) {
if (show.equals("")) {
show = null;
}
if (status.equals("")) {
status = null;
}
if (show.equals("invisible")) {
this.sendPresence(null, "invisible", null, null, priority);
} else {
this.sendPresence(null, null, show, status, priority);
}
}
/**
* Sends a presence stanza to a jid. This method can do various task but
* it's private, please use setStatus to set your status or explicit
* subscription methods subscribe, unsubscribe, subscribed and
* unsubscribed to change subscriptions.
*/
public void sendPresence(final String to, final String type, final String show, final String status, final int priority) {
try {
this.writer.startTag("presence");
if (type != null) {
this.writer.attribute("type", type);
}
if (to != null) {
this.writer.attribute("to", to);
}
if (show != null) {
this.writer.startTag("show");
this.writer.text(show);
this.writer.endTag();
}
if (status != null) {
this.writer.startTag("status");
this.writer.text(status);
this.writer.endTag();
}
if (priority != 0) {
this.writer.startTag("priority");
this.writer.text(Integer.toString(priority));
this.writer.endTag();
}
this.writer.endTag(); // presence
this.writer.flush();
} catch (final IOException e) {
java.lang.System.out.println(e);
this.connectionFailed();
}
}
/**
* Closes the stream-tag and the {#link XmlWriter}.
*/
public void logoff() {
try {
this.writer.endTag();
this.writer.flush();
this.writer.close();
} catch (final IOException e) {
java.lang.System.out.println(e);
this.connectionFailed();
}
}
/**
* Save a contact to roster. This means, a message is send to jabber
* server (which hosts your roster) to update the roster.
*
* #param jid the jid of the contact
* #param name the nickname of the contact
* #param group the group of the contact
* #param subscription the subscription of the contact
*/
public void saveContact(final String jid, final String name, final Enumeration group, final String subscription) {
try {
this.writer.startTag("iq");
this.writer.attribute("type", "set");
this.writer.startTag("query");
this.writer.attribute("xmlns", "jabber:iq:roster");
this.writer.startTag("item");
this.writer.attribute("jid", jid);
if (name != null) {
this.writer.attribute("name", name);
}
if (subscription != null) {
this.writer.attribute("subscription", subscription);
}
if (group != null) {
while (group.hasMoreElements()) {
this.writer.startTag("group");
this.writer.text((String) group.nextElement());
this.writer.endTag(); // group
}
}
this.writer.endTag(); // item
this.writer.endTag(); // query
this.writer.endTag(); // iq
this.writer.flush();
} catch (final IOException e) {
java.lang.System.out.println(e);
this.connectionFailed();
}
}
/**
* This method is used to be called on a parser or a connection error.
* It tries to close the XML-Reader and XML-Writer one last time.
*
*/
private void connectionFailed() {
if (this.writer != null)
this.writer.close();
if (this.reader != null)
this.reader.close();
for (Enumeration e = listeners.elements(); e.hasMoreElements();) {
XmppListener xl = (XmppListener) e.nextElement();
xl.onConnFailed("");
}
}
private void connectionFailed(final String msg) {
if (this.writer != null)
this.writer.close();
if (this.reader != null)
this.reader.close();
for (Enumeration e = listeners.elements(); e.hasMoreElements();) {
XmppListener xl = (XmppListener) e.nextElement();
xl.onConnFailed(msg);
}
}
};
xml reader looks like this:
public class XmlReader {
private InputStream is;
public final static int START_DOCUMENT = 0;
public final static int END_DOCUMENT = 1;
public final static int START_TAG = 2;
public final static int END_TAG = 3;
public final static int TEXT = 4;
//private Stack tags;
private boolean inside_tag;
private boolean left_angle;
private String tagName;
private String text;
private final Hashtable attributes = new Hashtable();
private int c;
private int type = START_DOCUMENT;
//public XmlReader(final InputStream in) throws IOException, UnsupportedEncodingException {
public XmlReader(final InputStream in) throws IOException {
//reader = new InputStreamReader(in, "UTF-8");
this.is = in;
//this.tags = new Stack();
this.inside_tag = false;
this.left_angle = false;
}
//http://discussion.forum.nokia.com/forum/showthread.php?t=76814
//by abirr
private int getNextCharacter() throws IOException {
int a = is.read();
int t=a;
if((t|0xC0)==t){
int b = is.read();
if( b == 0xFF ){ // Check if legal
t=-1;
}else if( b < 0x80 ){ // Check for UTF8 compliancy
throw new IOException("Bad UTF-8 Encoding encountered");
}else if((t|0xE0)==t) {
int c = is.read();
if( c == 0xFF ){ // Check if legal
t=-1;
}else if( c < 0x80 ){ // Check for UTF8 compliancy
throw new IOException("Bad UTF-8 Encoding encountered");
}else
t=((a & 0x0F)<<12) | ((b & 0x3F)<<6) | (c & 0x3F);
}else
t=((a & 0x1F)<<6)|(b&0x3F);
}
return a;
}
public void close() {
if (is != null) {
try {
is.close();
is = null;
} catch (IOException e) {
e.printStackTrace();
}
/*try {
reader.close();
} catch (IOException e) {}*/
}
}
public int next() throws IOException {
/* while (!this.ready())
try {
java.lang.Thread.sleep(100);
} catch (InterruptedException e) {}*/
this.c = getNextCharacter();
if (this.c <= ' ') {
while (((this.c = getNextCharacter()) <= ' ') && (this.c != -1)) {
;
}
}
if (this.c == -1) {
this.type = END_DOCUMENT;
return this.type;
}
if (this.left_angle || (this.c == '<')) {
this.inside_tag = true;
// reset all
this.tagName = null;
this.text = null;
this.attributes.clear();
if (this.c == '<') {
this.left_angle = true;
this.c = getNextCharacter();
}
if (this.left_angle && this.c == '/') {
this.left_angle = false;
this.type = END_TAG;
this.c = getNextCharacter();
this.tagName = this.readName('>');
} else if (this.left_angle && ((this.c == '?') || (this.c == '!'))) {// ignore xml heading & // comments
this.left_angle = false;
while ((this.c = getNextCharacter()) != '>') {
;
}
this.next();
} else {
this.left_angle = false;
this.type = START_TAG;
this.tagName = this.readName(' ');
String attribute = "";
String value = "";
while (this.c == ' ') {
/*this.c = getNextCharacter();
attribute = this.readName('=');
int quote = getNextCharacter();//this.c = this.read(); // '''
BTalk.debugConsole.addDebugMsg("quote: " + quote);
this.c = getNextCharacter();
value = this.readText(quote); //change from value = this.readText(''');
this.c = getNextCharacter();
this.attributes.put(attribute, value);
BTalk.debugConsole.addDebugMsg("attributes: " + attributes);*/
this.c = getNextCharacter();
attribute = this.readName('=').trim();
int quote = getNextCharacter();//this.c = this.read(); // '''
if (quote == 32) {
while (quote == 32) {
quote = getNextCharacter();//this.c = this.read(); // '''
}
this.c = getNextCharacter();
value = this.readText(quote); //change from value = this.readText(''');
this.c = getNextCharacter();
this.attributes.put(attribute, value);
} else {
this.c = getNextCharacter();
value = this.readText(quote); //change from value = this.readText(''');
this.c = getNextCharacter();
this.attributes.put(attribute, value);
}
}
if (this.c != '/') {
this.inside_tag = false;
}
}
} else if ((this.c == '>') && this.inside_tag) // last tag ended
{
this.type = END_TAG;
this.inside_tag = false;
} else {
this.tagName = null;
this.attributes.clear();
this.type = TEXT;
this.text = this.readText('<');
// fix the < dismatching problem
this.left_angle = true;
}
return this.type;
}
// NOTICE: this is only for debug use
public void parseHtml() throws IOException {
while (true) {
char c;
c = (char) this.getNextCharacter();
System.out.print(c);
}
}
public int getType() {
return this.type;
}
public String getName() {
return this.tagName;
}
public String getAttribute(final String name) {
return (String) this.attributes.get(name);
}
public Enumeration getAttributes() {
return this.attributes.keys();
}
public String getText() {
return this.text;
}
private String readText(final int end) throws IOException {
final StringBuffer output = new StringBuffer("");
while (this.c != end) {
if (this.c == '&') {
this.c = getNextCharacter();
switch (this.c) {
case 'l':
output.append('<');
break;
case 'g':
output.append('>');
break;
case 'a':
if (getNextCharacter() == 'm') {
output.append('&');
} else {
output.append('\'');
}
break;
case 'q':
output.append('"');
break;
case 'n':
output.append(' ');
break;
default:
output.append('?');
}
while ((this.c = getNextCharacter()) != ';') {
;
}
// NOTICE: Comment out these mystical codes
// } else if (this.c == '\\') {
// // NOTICE: What this means?
// if ((this.c = getNextCharacter()) == '<') {
// output.append('\\');
// break;
// } else {
// output.append((char) this.c);
// }
} else {
output.append((char) this.c);
}
this.c = getNextCharacter();
}
// while((c = read()) != end);
System.out.println(output.toString()+"");
return output.toString();
}
private String readName(final int end) throws IOException {
final StringBuffer output = new StringBuffer("");
do {
output.append((char) this.c);
} while (((this.c = getNextCharacter()) != end) && (this.c != '>') && (this.c != '/'));
return output.toString();
}
};
the problem is with session we need to create session before roster
String msg = "<iq type=\"set\" id=\"session_1\"><session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/></iq>";
try {
os.write(msg.getBytes());
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.next();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (reader.getName().equals("iq")) {
while (true) {
if((reader.getType() == XmlReader.END_TAG) && reader.getName().equals("iq"))
{
session=true;
break;
}
try {
reader.next();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//
now the problem is solved.thank you

java.io.StreamCorruptedException: invalid type code: 4C - replicationstream tomcat

I have following code
The function writes objects to the replicationstream provided by tomcat. IF the object is not serializable then I am trying to write "Misssing value".
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeInt(getType());
out.writeInt(getAction());
out.writeUTF(getName());
out.writeBoolean(getValue()!=null);
try
{
out.writeObject(getValue());
}
catch (Exception e)
{
System.out.println("Missing Value");
}
}
Following code reads object. Similar to read if the object is not serializable I try to read again to get read "Missing Value"
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
this.type = in.readInt();
this.action = in.readInt();
this.name = in.readUTF();
boolean hasValue=in.readBoolean();
try{
this.value = in.readObject();
}
catch(Exception er)
{
System.out.println("Missing Value");
}
}
I am getting following error, and I am not quite sure what does it mean. Both of the functions are being called for multiple times. First the writeExternal function is called for all the objects and then the readExternal.
java.io.StreamCorruptedException: invalid type code: 4C
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2480)
at java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2515)
at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2587)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2792)
at java.io.ObjectInputStream.readInt(ObjectInputStream.java:967)
EDIT
*Here is the code*
public class DeltaRequest
implements Externalizable
{
private LinkedList actions = new LinkedList();
private LinkedList actionPool = new LinkedList();
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
AttributeInfo info = null;
if (this.actionPool.size() > 0) {
info = (AttributeInfo)this.actionPool.removeFirst();
info.readExternal(in);
this.actions.addLast(info);
}
}
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeUTF(getSessionId());
out.writeBoolean(this.recordAllActions);
out.writeInt(getSize());
for (int i = 0; i < getSize(); i++) {
AttributeInfo info = (AttributeInfo)this.actions.get(i);
info.writeExternal(out);
}
}
protected byte[] serialize()
throws IOException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
writeExternal(oos);
oos.flush();
oos.close();
return bos.toByteArray();
}
private static class AttributeInfo implements Externalizable {
private String name = null;
private Object value = null;
private int action;
private int type;
public AttributeInfo() {
}
public AttributeInfo(int type, int action, String name, Object value) {
init(type, action, name, value);
}
public void init(int type, int action, String name, Object value)
{
this.name = name;
this.value = value;
this.action = action;
this.type = type;
}
public int getType() {
return this.type;
}
public int getAction() {
return this.action;
}
public Object getValue() {
return this.value;
}
public int hashCode() {
return this.name.hashCode();
}
public String getName() {
return this.name;
}
public void recycle() {
this.name = null;
this.value = null;
this.type = -1;
this.action = -1;
}
public boolean equals(Object o) {
if (!(o instanceof AttributeInfo)) return false;
AttributeInfo other = (AttributeInfo)o;
return other.getName().equals(getName());
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
this.type = in.readInt();
this.action = in.readInt();
this.name = in.readUTF();
boolean hasValue=in.readBoolean();
try{
this.value = in.readObject();
}
catch(Exception er)
{
out.writeObject("Value Missing");
}
}
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeInt(getType());
out.writeInt(getAction());
out.writeUTF(getName());
out.writeBoolean(getValue()!=null);
try
{
out.writeObject(getValue());
}
catch (Exception e)
{
out.writeObject("Value Missing");
}
}
public String toString()
{
StringBuffer buf = new StringBuffer("AttributeInfo[type=");
buf.append(getType()).append(", action=").append(getAction());
buf.append(", name=").append(getName()).append(", value=").append(getValue());
buf.append(", addr=").append(super.toString()).append("]");
return buf.toString();
}
}
}
Code:
This is how the above function are called.
protected DeltaRequest deserializeDeltaRequest(DeltaSession objbb, byte[] data)
throws ClassNotFoundException, IOException
{
try
{
objbb.lock();
ReplicationStream ois = getReplicationStream(data);
objbb.getDeltaRequest().readExternal(ois);
ois.close();
return objbb.getDeltaRequest();
} finally {
objbb.unlock();
}
}
protected byte[] serializeDeltaRequest(DeltaSession objbb, DeltaRequest objAA)
throws IOException
{
try
{
objbb.lock();
return objAA.serialize();
} finally {
objbb.unlock();
}
}
DeltaManager
public class DeltaManager extends ClusterManagerBase
{
public Session createSession(String sessionId)
{
return createSession(sessionId, true);
}
public Session createSession(String sessionId, boolean distribute)
{
if ((this.maxActiveSessions >= 0) && (this.sessions.size() >= this.maxActiveSessions)) {
this.rejectedSessions += 1;
throw new IllegalStateException(sm.getString("deltaManager.createSession.ise"));
}
DeltaSession session = (DeltaSession)super.createSession(sessionId);
if (distribute) {
sendCreateSession(session.getId(), session);
}
if (log.isDebugEnabled())
log.debug(sm.getString("deltaManager.createSession.newSession", session.getId(), new Integer(this.sessions.size())));
return session;
}
protected void sendCreateSession(String sessionId, DeltaSession session)
{
if (this.cluster.getMembers().length > 0) {
SessionMessage msg = new SessionMessageImpl(getName(), 1, null, sessionId, sessionId + "-" + System.currentTimeMillis());
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.sendMessage.newSession", this.name, sessionId));
msg.setTimestamp(session.getCreationTime());
this.counterSend_EVT_SESSION_CREATED += 1L;
send(msg);
}
}
protected DeltaRequest deserializeDeltaRequest(DeltaSession session, byte[] data)
throws ClassNotFoundException, IOException
{
try
{
session.lock();
ReplicationStream ois = getReplicationStream(data);
session.getDeltaRequest().readExternal(ois);
ois.close();
return session.getDeltaRequest();
} finally {
session.unlock();
}
}
protected byte[] serializeDeltaRequest(DeltaSession session, DeltaRequest deltaRequest)
throws IOException
{
try
{
session.lock();
return deltaRequest.serialize();
} finally {
session.unlock();
}
}
protected void deserializeSessions(byte[] data)
throws ClassNotFoundException, IOException
{
ClassLoader originalLoader = Thread.currentThread().getContextClassLoader();
ObjectInputStream ois = null;
try
{
ois = getReplicationStream(data);
Integer count = (Integer)ois.readObject();
int n = count.intValue();
for (int i = 0; i < n; i++) {
DeltaSession session = (DeltaSession)createEmptySession();
session.readObjectData(ois);
session.setManager(this);
session.setValid(true);
session.setPrimarySession(false);
session.access();
session.setAccessCount(0);
session.resetDeltaRequest();
if (findSession(session.getIdInternal()) == null) {
this.sessionCounter += 1;
} else {
this.sessionReplaceCounter += 1L;
if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.loading.existing.session", session.getIdInternal()));
}
add(session);
}
} catch (ClassNotFoundException e) {
log.error(sm.getString("deltaManager.loading.cnfe", e), e);
throw e;
} catch (IOException e) {
log.error(sm.getString("deltaManager.loading.ioe", e), e);
throw e;
}
finally {
try {
if (ois != null) ois.close();
}
catch (IOException f)
{
}
ois = null;
if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader);
}
}
protected byte[] serializeSessions(Session[] currentSessions)
throws IOException
{
ByteArrayOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
fos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
oos.writeObject(new Integer(currentSessions.length));
for (int i = 0; i < currentSessions.length; i++) {
((DeltaSession)currentSessions[i]).writeObjectData(oos);
}
oos.flush();
} catch (IOException e) {
log.error(sm.getString("deltaManager.unloading.ioe", e), e);
throw e;
} finally {
if (oos != null) {
try {
oos.close();
}
catch (IOException f) {
}
oos = null;
}
}
return fos.toByteArray();
}
public void start()
throws LifecycleException
{
if (!this.initialized) init();
if (this.started) {
return;
}
this.started = true;
this.lifecycle.fireLifecycleEvent("start", null);
generateSessionId();
try
{
Cluster cluster = getCluster();
if (cluster == null) {
Container context = getContainer();
if ((context != null) && ((context instanceof Context))) {
Container host = context.getParent();
if ((host != null) && ((host instanceof Host))) {
cluster = host.getCluster();
if ((cluster != null) && ((cluster instanceof CatalinaCluster))) {
setCluster((CatalinaCluster)cluster);
} else {
Container engine = host.getParent();
if ((engine != null) && ((engine instanceof Engine))) {
cluster = engine.getCluster();
if ((cluster != null) && ((cluster instanceof CatalinaCluster)))
setCluster((CatalinaCluster)cluster);
}
else {
cluster = null;
}
}
}
}
}
if (cluster == null) {
log.error(sm.getString("deltaManager.noCluster", getName()));
return;
}
if (log.isInfoEnabled()) {
String type = "unknown";
if ((cluster.getContainer() instanceof Host))
type = "Host";
else if ((cluster.getContainer() instanceof Engine)) {
type = "Engine";
}
log.info(sm.getString("deltaManager.registerCluster", getName(), type, cluster.getClusterName()));
}
if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.startClustering", getName()));
cluster.registerManager(this);
getAllClusterSessions();
}
catch (Throwable t) {
log.error(sm.getString("deltaManager.managerLoad"), t);
}
}
public synchronized void getAllClusterSessions()
{
if ((this.cluster != null) && (this.cluster.getMembers().length > 0)) {
long beforeSendTime = System.currentTimeMillis();
Member mbr = findSessionMasterMember();
if (mbr == null) {
return;
}
SessionMessage msg = new SessionMessageImpl(getName(), 4, null, "GET-ALL", "GET-ALL-" + getName());
this.stateTransferCreateSendTime = beforeSendTime;
this.counterSend_EVT_GET_ALL_SESSIONS += 1L;
this.stateTransfered = false;
try
{
synchronized (this.receivedMessageQueue) {
this.receiverQueue = true;
}
this.cluster.send(msg, mbr);
if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.waitForSessionState", getName(), mbr, Integer.valueOf(getStateTransferTimeout())));
waitForSendAllSessions(beforeSendTime);
} finally {
synchronized (this.receivedMessageQueue) {
for (Iterator iter = this.receivedMessageQueue.iterator(); iter.hasNext(); ) {
SessionMessage smsg = (SessionMessage)iter.next();
if (!this.stateTimestampDrop) {
messageReceived(smsg, smsg.getAddress() != null ? smsg.getAddress() : null);
}
else if ((smsg.getEventType() != 4) && (smsg.getTimestamp() >= this.stateTransferCreateSendTime))
{
messageReceived(smsg, smsg.getAddress() != null ? smsg.getAddress() : null);
}
else if (log.isWarnEnabled()) {
log.warn(sm.getString("deltaManager.dropMessage", getName(), smsg.getEventTypeString(), new Date(this.stateTransferCreateSendTime), new Date(smsg.getTimestamp())));
}
}
this.receivedMessageQueue.clear();
this.receiverQueue = false;
}
}
}
else if (log.isInfoEnabled()) { log.info(sm.getString("deltaManager.noMembers", getName())); }
}
protected void registerSessionAtReplicationValve(DeltaSession session)
{
if ((this.replicationValve == null) &&
((this.container instanceof StandardContext)) && (((StandardContext)this.container).getCrossContext())) {
Cluster cluster = getCluster();
if ((cluster != null) && ((cluster instanceof CatalinaCluster))) {
Valve[] valves = ((CatalinaCluster)cluster).getValves();
if ((valves != null) && (valves.length > 0)) {
for (int i = 0; (this.replicationValve == null) && (i < valves.length); i++) {
if ((valves[i] instanceof ReplicationValve)) this.replicationValve = ((ReplicationValve)valves[i]);
}
if ((this.replicationValve == null) && (log.isDebugEnabled())) {
log.debug("no ReplicationValve found for CrossContext Support");
}
}
}
}
if (this.replicationValve != null)
this.replicationValve.registerReplicationSession(session);
}
protected Member findSessionMasterMember()
{
Member mbr = null;
Member[] mbrs = this.cluster.getMembers();
if (mbrs.length != 0) mbr = mbrs[0];
if ((mbr == null) && (log.isWarnEnabled())) log.warn(sm.getString("deltaManager.noMasterMember", getName(), ""));
if ((mbr != null) && (log.isDebugEnabled())) log.warn(sm.getString("deltaManager.foundMasterMember", getName(), mbr));
return mbr;
}
public void messageDataReceived(ClusterMessage cmsg)
{
if ((cmsg != null) && ((cmsg instanceof SessionMessage))) {
SessionMessage msg = (SessionMessage)cmsg;
switch (msg.getEventType()) {
case 1:
case 2:
case 3:
case 4:
case 13:
synchronized (this.receivedMessageQueue) {
if (this.receiverQueue) {
this.receivedMessageQueue.add(msg);
return;
}
}
break;
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12: } messageReceived(msg, msg.getAddress() != null ? msg.getAddress() : null);
}
}
public ClusterMessage requestCompleted(String sessionId)
{
return requestCompleted(sessionId, false);
}
public ClusterMessage requestCompleted(String sessionId, boolean expires)
{
DeltaSession session = null;
try {
session = (DeltaSession)findSession(sessionId);
DeltaRequest deltaRequest = session.getDeltaRequest();
session.lock();
msg = null;
boolean isDeltaRequest = false;
synchronized (deltaRequest) {
isDeltaRequest = deltaRequest.getSize() > 0;
if (isDeltaRequest) {
this.counterSend_EVT_SESSION_DELTA += 1L;
byte[] data = serializeDeltaRequest(session, deltaRequest);
msg = new SessionMessageImpl(getName(), 13, data, sessionId, sessionId + "-" + System.currentTimeMillis());
session.resetDeltaRequest();
}
}
if (!isDeltaRequest) {
if ((!expires) && (!session.isPrimarySession())) {
this.counterSend_EVT_SESSION_ACCESSED += 1L;
msg = new SessionMessageImpl(getName(), 3, null, sessionId, sessionId + "-" + System.currentTimeMillis());
if (log.isDebugEnabled()) {
log.debug(sm.getString("deltaManager.createMessage.accessChangePrimary", getName(), sessionId));
}
}
}
else if (log.isDebugEnabled()) {
log.debug(sm.getString("deltaManager.createMessage.delta", getName(), sessionId));
}
if (!expires)
session.setPrimarySession(true);
long replDelta;
if ((!expires) && (msg == null)) {
replDelta = System.currentTimeMillis() - session.getLastTimeReplicated();
if (replDelta > getMaxInactiveInterval() * 1000) {
this.counterSend_EVT_SESSION_ACCESSED += 1L;
msg = new SessionMessageImpl(getName(), 3, null, sessionId, sessionId + "-" + System.currentTimeMillis());
if (log.isDebugEnabled()) {
log.debug(sm.getString("deltaManager.createMessage.access", getName(), sessionId));
}
}
}
if (msg != null) {
session.setLastTimeReplicated(System.currentTimeMillis());
msg.setTimestamp(session.getLastTimeReplicated());
}
return msg;
}
catch (IOException x)
{
SessionMessage msg;
log.error(sm.getString("deltaManager.createMessage.unableCreateDeltaRequest", sessionId), x);
return null;
} finally {
if (session != null) session.unlock();
}
}
protected void messageReceived(SessionMessage msg, Member sender)
{
if ((doDomainReplication()) && (!checkSenderDomain(msg, sender))) {
return;
}
ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
try
{
ClassLoader[] loaders = getClassLoaders();
if ((loaders != null) && (loaders.length > 0)) Thread.currentThread().setContextClassLoader(loaders[0]);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.eventType", getName(), msg.getEventTypeString(), sender));
switch (msg.getEventType()) {
case 4:
handleGET_ALL_SESSIONS(msg, sender);
break;
case 12:
handleALL_SESSION_DATA(msg, sender);
break;
case 14:
handleALL_SESSION_TRANSFERCOMPLETE(msg, sender);
break;
case 1:
handleSESSION_CREATED(msg, sender);
break;
case 2:
handleSESSION_EXPIRED(msg, sender);
break;
case 3:
handleSESSION_ACCESSED(msg, sender);
break;
case 13:
handleSESSION_DELTA(msg, sender);
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
}
} catch (Exception x) { log.error(sm.getString("deltaManager.receiveMessage.error", getName()), x);
} finally {
Thread.currentThread().setContextClassLoader(contextLoader);
}
}
protected void handleALL_SESSION_TRANSFERCOMPLETE(SessionMessage msg, Member sender)
{
this.counterReceive_EVT_ALL_SESSION_TRANSFERCOMPLETE += 1;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.transfercomplete", getName(), sender.getHost(), new Integer(sender.getPort())));
this.stateTransferCreateSendTime = msg.getTimestamp();
this.stateTransfered = true;
}
protected void handleSESSION_DELTA(SessionMessage msg, Member sender)
throws IOException, ClassNotFoundException
{
this.counterReceive_EVT_SESSION_DELTA += 1L;
byte[] delta = msg.getSession();
DeltaSession session = (DeltaSession)findSession(msg.getSessionID());
if (session != null) {
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.delta", getName(), msg.getSessionID())); try
{
session.lock();
DeltaRequest dreq = deserializeDeltaRequest(session, delta);
dreq.execute(session, this.notifyListenersOnReplication);
session.setPrimarySession(false);
} finally {
session.unlock();
}
}
}
protected void handleSESSION_CREATED(SessionMessage msg, Member sender)
{
this.counterReceive_EVT_SESSION_CREATED += 1L;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.createNewSession", getName(), msg.getSessionID()));
DeltaSession session = (DeltaSession)createEmptySession();
session.setManager(this);
session.setValid(true);
session.setPrimarySession(false);
session.setCreationTime(msg.getTimestamp());
session.setMaxInactiveInterval(getMaxInactiveInterval());
session.access();
if (this.notifySessionListenersOnReplication) {
session.setId(msg.getSessionID());
} else {
session.setIdInternal(msg.getSessionID());
add(session);
}
session.resetDeltaRequest();
session.endAccess();
}
protected void handleALL_SESSION_DATA(SessionMessage msg, Member sender)
throws ClassNotFoundException, IOException
{
this.counterReceive_EVT_ALL_SESSION_DATA += 1L;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataBegin", getName()));
byte[] data = msg.getSession();
deserializeSessions(data);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataAfter", getName()));
}
protected void handleGET_ALL_SESSIONS(SessionMessage msg, Member sender)
throws IOException
{
this.counterReceive_EVT_GET_ALL_SESSIONS += 1L;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingBegin", getName()));
Session[] currentSessions = findSessions();
long findSessionTimestamp = System.currentTimeMillis();
if (isSendAllSessions()) {
sendSessions(sender, currentSessions, findSessionTimestamp);
}
else {
int len = currentSessions.length < getSendAllSessionsSize() ? currentSessions.length : getSendAllSessionsSize();
Session[] sendSessions = new Session[len];
for (int i = 0; i < currentSessions.length; i += getSendAllSessionsSize()) {
len = i + getSendAllSessionsSize() > currentSessions.length ? currentSessions.length - i : getSendAllSessionsSize();
System.arraycopy(currentSessions, i, sendSessions, 0, len);
sendSessions(sender, sendSessions, findSessionTimestamp);
if (getSendAllSessionsWaitTime() > 0)
try {
Thread.sleep(getSendAllSessionsWaitTime());
}
catch (Exception sleep)
{
}
}
}
SessionMessage newmsg = new SessionMessageImpl(this.name, 14, null, "SESSION-STATE-TRANSFERED", "SESSION-STATE-TRANSFERED" + getName());
newmsg.setTimestamp(findSessionTimestamp);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionTransfered", getName()));
this.counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE += 1;
this.cluster.send(newmsg, sender);
}
protected void sendSessions(Member sender, Session[] currentSessions, long sendTimestamp)
throws IOException
{
byte[] data = serializeSessions(currentSessions);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingAfter", getName()));
SessionMessage newmsg = new SessionMessageImpl(this.name, 12, data, "SESSION-STATE", "SESSION-STATE-" + getName());
newmsg.setTimestamp(sendTimestamp);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionData", getName()));
this.counterSend_EVT_ALL_SESSION_DATA += 1L;
this.cluster.send(newmsg, sender);
}
}
The problem here is that you are calling
this.writeExternal(oos);
instead of
oos.writeObject(this);
so the ObjectOutputStream never gets the chance to write the object preamble.
Similarly, you must call
Object o = ois.readObject();
rather than
Object o = this.readExternal(ois);
Re your non-serializable object, you should write a special object. At the moment you are treating every possible exception as just a missing object, when it could be a huge number of other things.

Categories

Resources