I have coded the following client which is only connecting to the local host, the ip on which the machine is connected, but not a server running on different ip on a different machine.
The error I get when I connect to outside is Connection refused
How to make it connect outside local host?
My code is as follows
public ChatClient(JTextField address, JTextField port, JTextField user,
JTextField text, JTextArea tapane3, JTextArea tapane4) {
// TODO Auto-generated constructor stub
this.address=address;
this.user=user;
this.text=text;
this.port=port;
add=address.getText();
textarea=tapane3;
showusers=tapane4;
}
public void sendToPort(String str) throws IOException {
Socket socket = null;
//String str = "Hello World";
try {
out.write(str, 0, str.length());
out.flush();
} catch (IOException e) {
System.err.print(e);
} finally {
}
}
#SuppressWarnings("deprecation")
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Send"))
{
try {
textarea.append(SendMessage()+"\n");
System.out.println(SendMessage());
sendToPort("x");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if(e.getActionCommand().equals("Connect"))
{
try {
String prt=port.getText();
cs = new Socket(add, Integer.parseInt(prt));
out =new OutputStreamWriter(cs.getOutputStream(), "UTF-8");
showusers.setText(user.getText());
//sendToPort(Integer.parseInt(prt), Address);
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if(e.getActionCommand().equals("Disconnect"))
{
try {
cs.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public void Connect() throws NumberFormatException, UnknownHostException, IOException {
// TODO Auto-generated method stub
}
public String SendMessage() {
// TODO Auto-generated method stub
{
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String getdate=(dateFormat.format(date));
String content = text.getText();
String from = String.format(user.getText());
String all = "START:" + getdate + ":" + from + ":"+"MESSAGE:" + content + ":END";
//textarea.setText(all);
try {
out.write(all);
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return all;
}
Related
I am trying through HWCryto - https://github.com/open-eid/hwcrypto.js/wiki/ModernAPI - to add support in a Struts2 application to digital signing.
Trying to follow Bruno Lowagie's book first i create an empty signature
CertificateFactory certFactory;
try {
certFactory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream in = new ByteArrayInputStream(certDecoded);
cert = (X509Certificate) certFactory.generateCertificate(in);
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Calendar cal = Calendar.getInstance();
int estimatedSize = 8192;
PdfSignatureAppearance sap = pdfStamper.getSignatureAppearance();
sap.setVisibleSignature("sig");
sap.setCertificate(cert);
sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
sap.setSignDate(cal);
ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE,
PdfName.ADBE_PKCS7_DETACHED);
try {
MakeSignature.signExternalContainer(sap, external, 8192);
pdfStamper.close();
pdfReader.close();
} catch (GeneralSecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
After that i get the pdf output and create a new hash that i will send to smartcard
byte [] alteredPDF=output.toByteArray();
ExternalDigest externalDigest = new ExternalDigest() {
#Override
public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException {
return DigestAlgorithms.getMessageDigest(hashAlgorithm, "BC");
}
};
PdfSignatureAppearance sapFinal = null;
try {
ByteArrayOutputStream outputFinal = new ByteArrayOutputStream();
pdfReader = new PdfReader(new ByteArrayInputStream(alteredPDF));
pdfStamper = PdfStamper.createSignature(pdfReader, outputFinal, '\0');
sapFinal = pdfStamper.getSignatureAppearance();
sapFinal.setVisibleSignature("sig");
sapFinal.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
sapFinal.setCertificate(cert);
sapFinal.setSignDate(cal);
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
dic.setReason(sap.getReason());
dic.setLocation(sap.getLocation());
String certInfo = cert.getSubjectX500Principal().getName();
dic.setName(certInfo.substring(certInfo.indexOf("CN=") + 3,
certInfo.indexOf(",OU", certInfo.indexOf("CN=") + 3)));
dic.setSignatureCreator(sap.getSignatureCreator());
dic.setContact(sap.getContact());
dic.setCert(certDecoded);
dic.setDate(new PdfDate(sap.getSignDate()));
sapFinal.setCryptoDictionary(dic);
HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));
sapFinal.preClose(exc);
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
byte[] sh = null;
byte[] hashVal = null;
PdfPKCS7 sgn = null;
try {
sgn = new PdfPKCS7(null, new Certificate[] { cert }, "SHA256", null, externalDigest, false);
InputStream data = sapFinal.getRangeStream();
hashVal = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
sh = sgn.getAuthenticatedAttributeBytes(hashVal, cal, null, null, CryptoStandard.CMS);
sh = MessageDigest.getInstance("SHA256", "BC").digest(sh);
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And finally having the generated sig
sgn.setExternalDigest(sig, null, "RSA");
byte[] encodedSign = null;
try {
System.out.println(Arrays.toString(Hex.decodeHex(hash.toCharArray())));
encodedSign = sgn.getEncodedPKCS7(Hex.decodeHex(hash.toCharArray()), cal, null, null, null,
CryptoStandard.CMS);
} catch (DecoderException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
MakeSignature.signDeferred(pdfReader, "sig", output,
new MyExternalSignatureContainer(encodedSign));
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (GeneralSecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("called sign pdf");
try {
FileOutputStream outputStream = new FileOutputStream("d:\\debug.pdf");
output.writeTo(outputStream);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Can anyone please point me to what i am doing wrong?
Finally managed to solve my issue. Storing an empty signature into the PDF and recreating the outputstream was being the culprit. Managed to use the same outputstream from beginning to end and it worked.
This link - https://github.com/sueastside/BEIDSign/blob/master/beidsign-service/src/main/java/be/redtree/beid/services/SignatureServiceImpl.java -surely helped me.
Thank you mkl for your time.
public void mediaPlayer(final String path, final JPanel panel) {
new Thread() {
public void run() {
try {
Player p = Manager.createRealizedPlayer(new File(path).toURL());
Component ctrlpanel = p.getControlPanelComponent();
Component player = p.getVisualComponent();
player.setBounds(10, 20, 300, 170);
ctrlpanel.setBounds(10, 191, 300, 20);
panel.add(player);
panel.add(ctrlpanel);
panel.repaint();
p.start();
System.out.println(" Player Started");
} catch (NoPlayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CannotRealizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
I try the code play video file but get some error.
Unable to handle format: MPEG, 352x288, FrameRate=25.0, Length=152064
Failed to realize: com.sun.media.PlaybackEngine#c7f314
Error: Unable to realize com.sun.media.PlaybackEngine#c7f314
javax.media.CannotRealizeException
at javax.media.Manager.blockingCall(Manager.java:2005)
at javax.media.Manager.createRealizedPlayer(Manager.java:528)
at buffer.Action$1.run(Action.java:74)
A Client(botnet server) is trying to send continuous messages over TCP socket to a server(disruptor), but only one message is received at the disruptor. Disruptor is a thread which is created by the botnet server.
code: Botnet server
public static void main(String[] args) {
// TODO Auto-generated method stub
Jedis jedis = new Jedis("localhost");
String pattern = new String("TKproject");
input = new Disruptor(30001,1024,jedis,pattern);
int count = 0;
Thread start = new Thread(input);
start.start();
try {
request = new Socket("localhost",30001);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Random rand = new Random();
Message msg = new Message();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(request.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
System.out.println("count is : " + count);
count++;
if(count == 5)
break;
if(count % 15 == 0)
jedis.rpush(pattern,Integer.toString(count));
int next = rand.nextInt(3);
msg.setMessageId(count);
switch (next){
case 0: msg.setType(MessageType.HELLO);
break;
case 1: msg.setType(MessageType.REQUEST);
break;
case 2: msg.setType(MessageType.REPLY);
break;
default: msg.setType(MessageType.REQUEST);
break;
}
//System.out.println("Message id "+msg.Messageid);
try {
oos.writeObject(msg);
//oos.flush();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Disruptor run()
public void run() {
// TODO Auto-generated method stub
while(true){
System.out.println("Disruptor Running");
Socket receipt = null;
try {
receipt = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ObjectInputStream recv = null;
try {
recv = new ObjectInputStream(receipt.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
byte [] rcvbytes = new byte[2048];
try {
recv.read(rcvbytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
storage.write((Message)recv.readObject());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
receipt = server.accept();
You need to perform this just once to connect your server to a client, try and move that instruction before the while(true).
The same needs to be done for the ObjectInputStream declaration.
Either:
send a new Message object each time instead of refreshing the old one
send it using `writeUnshared()’, or
call ObjectOutputStream.reset() before sending a refreshed Message object.
this code works correctly on Java runtime.
public static void main(String[] args) {
// TODO Auto-generated method stub
extendedList array=new extendedList();//extendedList:class extendedList extends ArrayList<XXX> implements Serializable
//....unimportant code...
FileOutputStream out;
ObjectOutputStream oout;
try {
out=new FileOutputStream("Data.dat");
oout=new ObjectOutputStream(out);
oout.writeObject(array);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fin;
ObjectInputStream ofin;
try {
fin=new FileInputStream("Data.dat");
ofin=new ObjectInputStream(fin);
extendedList ret=(extendedList) ofin.readObject();
for(int i=0;i<ret.size();i++)
System.out.print(ret.get(i).getnum()+":"+ret.get(i).getename()+":"+ret.get(i).getfname()+"\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
but when I want to read Data.dat in android.it throws ClassNotFoundException.What is wrong?
ObjectInputStream object;
InputStream input;
try {
Log.d("adapter","befor Open");
input=assets.open("Data.dat");
Log.d("adapter","after Open");
object= new ObjectInputStream(input);
Array=(extendedList) object.readObject();
//........hidden code
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("adapter","IOException has detected");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
Log.d("adapter","ClassNotFoundException has detected");
e.printStackTrace();
}
also when I replace InputStream with FileInputStream and cast asset.open("Data.dat").when debugger arrive to that line.Source not found occurs.
I have a problem with my code.
It keeps on crashing when i have a blank editText field.
This bit of code is in the settings of my app and works the data fine but when there is a blank field it crashes the program.
Here's the code for it.
Please don't be harsh because it is my 1st android app. So if anyone knows how to solves the blank edit text field problem that would be greatly appreciated! (Any other comments on how to improve the app would be a help to).
Cheers
package com.cleanyet.cyv100fp;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class sTasks extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tasks);
/*Sets Up the Variables*/
Button done = (Button) findViewById(R.id.done1);
EditText t1 = (EditText)findViewById(R.id.tbTask1);
EditText t2 = (EditText)findViewById(R.id.tbTask2);
EditText t3 = (EditText)findViewById(R.id.tbTask3);
EditText t4 = (EditText)findViewById(R.id.tbTask4);
EditText t5 = (EditText)findViewById(R.id.tbTask5);
String FILENAME1 = "stask1";
String FILENAME2 = "stask2";
String FILENAME3 = "stask3";
String FILENAME4 = "stask4";
String FILENAME5 = "stask5";
String task1 = null;
String task2 = null;
String task3 = null;
String task4 = null;
String task5 = null;
String edit = "Edit Task";
/*Fixes the Blank Field bug*/
/*Sets up the file input*/
FileInputStream fis = null;
/*Gets the tasks set previously*/
/*Task 1 set up*/
try {
fis = openFileInput(FILENAME1);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task1 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task1.toString().length() < 0) {
task1.toString();
t1.setText(task1);
}
else {
t1.setText(edit);
}
/*Task 2 set up*/
try {
fis = openFileInput(FILENAME2);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task2 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task2.toString().length() < 0) {
task2.toString();
t2.setText(task2);
}
else {
t2.setText(edit);
}
/*Task 3 set up*/
try {
fis = openFileInput(FILENAME3);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task3 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task3.toString().length() < 0) {
task3.toString();
t3.setText(task3);
}
else {
t3.setText(edit);
}
/*Task 4 set up*/
try {
fis = openFileInput(FILENAME4);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task4 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task4.toString().length() < 0) {
task4.toString();
t4.setText(task4);
}
else {
t4.setText(edit);
}
/*Task 5 set up*/
try {
fis = openFileInput(FILENAME5);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task5 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task5.toString().length() < 0) {
task5.toString();
t5.setText(task5);
}
else {
t5.setText(edit);
}
/*When changes have been made and done is clicked*/
done.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/*Sets up the Variables*/
EditText t1 = (EditText)findViewById(R.id.tbTask1);
EditText t2 = (EditText)findViewById(R.id.tbTask2);
EditText t3 = (EditText)findViewById(R.id.tbTask3);
EditText t4 = (EditText)findViewById(R.id.tbTask4);
EditText t5 = (EditText)findViewById(R.id.tbTask5);
String tasks1 = t1.getText().toString();
String tasks2 = t2.getText().toString();
String tasks3 = t3.getText().toString();
String tasks4 = t4.getText().toString();
String tasks5 = t5.getText().toString();
String FILENAME1 = "stask1";
String FILENAME2 = "stask2";
String FILENAME3 = "stask3";
String FILENAME4 = "stask4";
String FILENAME5 = "stask5";
String task1 = tasks1;
String task2 = tasks2;
String task3 = tasks3;
String task4 = tasks4;
String task5 = tasks5;
String edit = "Go to settings to make this task.";
if (t1 != null){
t1.setText(edit);
/*t2.setText(edit);
t3.setText(edit);
t4.setText(edit);
t5.setText(edit);*/
};
/*Put if statement here to catch the empty field*/
/*Makes The Changes to the Tasks*/
try {
FileOutputStream fos1 = openFileOutput(FILENAME1, Context.MODE_PRIVATE);
fos1.write(task1.getBytes());
fos1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos2 = openFileOutput(FILENAME2, Context.MODE_PRIVATE);
fos2.write(task2.getBytes());
fos2.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos3 = openFileOutput(FILENAME3, Context.MODE_PRIVATE);
fos3.write(task3.getBytes());
fos3.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos4 = openFileOutput(FILENAME4, Context.MODE_PRIVATE);
fos4.write(task4.getBytes());
fos4.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos5 = openFileOutput(FILENAME5, Context.MODE_PRIVATE);
fos5.write(task5.getBytes());
fos5.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent("com.checkin.cyv100fp.settings"));
}
});
}
}
if (task1.toString().length() < 0) {
task1.toString();
t1.setText(task1);
}
else {
t1.setText(edit);
}
The above makes no sense at all.
Firstly task1 IS a string so there's no need to call toString() to convert it to one.
Secondly, your conditional statement (if) is checking to see if task1 has a length less than zero....think about it.
Thirdly, if it does have an impossible length less than zero you then call toString() on it again (with no variable to receive the impossible less than zero result) and you then try to set the text of your t1 EditText.
The chances are that your file reading is failing (probably because you only save the strings later in the onClick(...) method). Because your task strings will be null if the file reading fails then you need to test for null before trying to use them.
In other words you're doing this in your code...
String task1 = null;
To fix the bit of code I enclosed at the beginning, use...
if (task1 != null) {
t1.setText(task1);
}
else {
t1.setText(edit);
}
...but most importantly, make sure your files have the strings in them that you need to read.