1st Attempt at crypto using Java
Hi,
It my first attempt at doing some programming around security so i thought I will attempt to write encrypted data to a file. The code is as follows:
CipherOutputStream cos = new CipherOutputStream( new FileOutputStream(
new File("cipherWrite.txt")),ci);
String myTxt = "This text will be cipher'ed and written to file";
byte[] cipherTxt = myTxt.getBytes();
cos.write(cipherTxt);
System.out.println("Data written...");
cos.flush();
System.out.println("Flushed...");
cos.close();
System.out.println("file closed...");
System.out.println("unENCRYPTED:"+ cipherTxt);
byte[] enryptTxt = ci.doFinal(cipherTxt);
System.out.println("ENCRYPTED:"+ enryptTxt);
The next peice of code generates the private key of a RSA type, which the cipher uses when initialized:
ci = Cipher.getInstance("RSA");
System.out.println("Cipher - BlockSize: "+ ci.getBlockSize() );
System.out.println("Cipher - Algorithm: "+ ci.getAlgorithm() );
System.out.println("Cipher - Provider: "+ ci.getProvider().getInfo() );
MyKey cipherKey = new MyKey();
ci.init(Cipher.PRIVATE_KEY, cipherKey.getPrivateKey() );
System.out.println("Done..Ready...");
I have tested the output and although it does not fire any exceptions i do not see any data written in the file. Also you may have noticed i tried to use the doFinal method to get an encrypted view of the string but there is fires an exception and displays the message:
Cipher Error message: Data must start with zero
does anyone know where i am going wrong and can help?
thanks,
Mani
1) CipherOutputStream does not handle exceptions properly and if anything goes wrong it just gives up without any warning.
2) RSA ciphers are not normally used to encrypt more than the length RSA modulus and using the SunJCE provider one gets an exception when one does.
These two together can explain your empty file BUT with your data length being only about 46 bytes then as long as your RSA modulus is greater than 368 bits then there should be no problem.
Your use of doFinal() is irrelevant since doFinal() will have been called when you close the CipherOutputStream so you are just re-using the Cipher. With you only having posted code fragments, it is difficult to see what you are doing wrong so you should turn your code into a fully functional self contained example and post it here. That way the forum members can test your code.
Finally, I would have expected you to use ci.init(Cipher.ENCRYPT, cipherKey.getPrivateKey() );
Similar Messages
-
Spawn a new PDF using Java Script within LC Designer
I am trying to spawn a new PDF file to be created from an existing PDF using Java Script within the LC designer
I have this example but I can't get it to work
function createPdf()
pdf = pdf$();
pdf.addText('Hello World');
pdf.writeToFile('c:/temp/hello_world.pdf');
window.open('file://c:/temp/hello_world.pdf');
Is it possible to create a PDF like this within LC Designer?Hi
I would like to see if it was possible. I thought it would be easy, as
there is a standard batch processing sequence (Print 1st page of all) using
Java that comes with Acrobat 7. This allows you to print the first page of
a number of files that you select when the sequence is run. Its code is:
/* Print 1st Page */
/* This sequence prints the first page of
each document selected to the default printer.
this.print
To my uninformed mind it seemed logical that the same code, slightly
modified to print all pages, should work from within a form.
Anyway, if there is a way to choose individual files, I would appreciate
that.
Thanks
Rob -
Print .PDT,.DOC,.XLS files using java print API
Hi,
I need to print different types of documents like pdf, word, excel files etc.
Please let me know how to proceed on this.
I tried using the following code, but it is printing all junk/html tags on the paper.
Please let me know how to resolve this.
Thanks in advance
import java.io.File;
import java.io.IOException;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
public class PrintDocument {
static public void main(String args[]) throws Exception {
try {
PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printerJob = defaultPrintService.createPrintJob();
File pdfFile = new File("C:\\temp\\sample.doc");
SimpleDoc simpleDoc = new SimpleDoc(pdfFile.toURL(), DocFlavor.URL.AUTOSENSE, null);
printerJob.print(simpleDoc, null);
} catch (IOException ie) {
ie.printStackTrace();
} catch (PrintException pe) {
pe.printStackTrace();
}Hi
I would like to see if it was possible. I thought it would be easy, as
there is a standard batch processing sequence (Print 1st page of all) using
Java that comes with Acrobat 7. This allows you to print the first page of
a number of files that you select when the sequence is run. Its code is:
/* Print 1st Page */
/* This sequence prints the first page of
each document selected to the default printer.
this.print
To my uninformed mind it seemed logical that the same code, slightly
modified to print all pages, should work from within a form.
Anyway, if there is a way to choose individual files, I would appreciate
that.
Thanks
Rob -
Last year I posted 4 programs that provided a simple client server using both stream sockets and NIO. I decided as an exercise in using Java 5 to port that code and try to use as many of the new features as possible. The following code is very long and does what all the previous example programs did. In replies do not repost the whole of this message.
It provides a simple chat like client and server. The user can request either a stream connection or a NIO connection or provide one of their own.
//========================== MsgSwitch.java ===========================//
package pkwnet.msgswitch;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.logging.Handler;
* main class for message switch
* command line arguments are
* -p port number for server
* -s run server
* -a server ip address including port for client
* -i idle timer in seconds
* -n use NIO
* -c specify connection class
public class MsgSwitch {
static private int errors = 0;
static private String address = "127.0.0.1:6060";
static private String connectionClass = "pkwnet.msgswitch.StreamConnection";
static public void main(String [] args) {
int port = 6060;
int idleTime = 600;
boolean server = false;
boolean nio = false;
Logger logger = Logger.getLogger("msgswitch");
for(String arg : args) {
if(arg.startsWith("-a")) {
address = arg.substring(2);
} else if(arg.startsWith("-p")) {
port = argToInt(arg);
server = true;
} else if(arg.startsWith("-i")) {
idleTime = argToInt(arg);
} else if (arg.startsWith("-s")) {
server = true;
} else if (arg.startsWith("-c")) {
connectionClass = arg.substring(2);
} else if (arg.startsWith("-n")) {
connectionClass = "pkwnet.msgswitch.NIOConnection";
} else {
String err = "unknown argument=" + arg;
logger.severe(err);
System.err.println(err);
errors++;
if (errors == 0) {
if (server) {
new Server().listen(port,idleTime, nio);
} else {
new Client().start(address, nio);
} else {
fail(errors + " errors encountered", null);
static private int argToInt(String arg) {
int val = 0;
try {
val = Integer.parseInt(arg.substring(2));
} catch (NumberFormatException e) {
String err = "invalid argument format: " + arg;
Logger.getLogger("msgswitch").severe(err);
System.err.println(err);
errors++;
return val;
static public void fail(String err, Throwable e) {
String msg = "Operation terminated: " + err;
Logger.getLogger("msgswitch").log(Level.SEVERE, msg, e);
System.err.println(msg);
System.exit(12);
static public Connection getConnection() {
Connection conn = null;
try {
conn = (Connection) Class.forName(connectionClass).newInstance();
} catch (Exception e) {
fail ("connection class error", e);
return conn;
static public void logCaller(Logger logger, Level level) {
String text = "CALLED";
if (logger.isLoggable(level)) {
try {
throw new Exception("logging stack");
} catch (Exception e) {
StackTraceElement [] st = e.getStackTrace();
if (st.length > 1) {
text += formatElement(st[1]);
if (st.length >2) {
text += formatElement(st[2]);
logger.log(level, text);
static private String formatElement(StackTraceElement ste) {
return "\n " + ste.getClassName() + "." + ste.getMethodName()
+ "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")";
//================= Client.java =============================================//
package pkwnet.msgswitch;
* a simple Swing chat GUI using Java 5 and sockets.
* @author PKWooster
* @version 1.0 August 31,2005
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.BorderLayout;
import static java.awt.BorderLayout.*;
client GUI class
public class Client extends JFrame implements ConnectionListener {
// swing GUI components
private JTextField userText = new JTextField(40);
private JTextArea sessionLog = new JTextArea(24,40);
private JTextField statusText = new JTextField(40);
private JPanel outPanel = new JPanel();
private JScrollPane sessionLogScroll = new JScrollPane(sessionLog);
private JMenuBar menuBar = new JMenuBar();
private JMenuItem startItem = new JMenuItem("Start");
private JMenuItem hostItem = new JMenuItem("Host");
private JMenuItem aboutItem = new JMenuItem("About");
private JMenuItem abortItem = new JMenuItem("Abort");
private JMenuItem exitItem = new JMenuItem("Exit");
private JMenu fileMenu = new JMenu("File");
private JMenu helpMenu = new JMenu("Help");
private Container cp;
private String address;
private Connection connection;
private boolean sendReady = false;
private boolean nio = false;
Client() {
public void start(String address, boolean nio) {
this.address = address;
this.nio = nio;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
runClient();
private void runClient() {
connection = MsgSwitch.getConnection();
connection.addConnectionListener(this);
buildMenu();
cp = getContentPane();
sessionLog.setEditable(false);
outPanel.add(new JLabel("Send: "));
outPanel.add(userText);
// enter on userText causes transmit
userText.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){userTyped(evt);}
cp.setLayout(new BorderLayout());
cp.add(outPanel,NORTH);
cp.add(sessionLogScroll,CENTER);
cp.add(statusText,SOUTH);
setStatus("Closed");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
mnuExit();
pack();
setVisible(true);
* attempt to send the contents of the user text field
private void userTyped(ActionEvent evt) {
if (sendReady) {
String txt = evt.getActionCommand()+"\n";
userText.setText("");
toSessionLog("> ", txt);
sendReady = false;
connection.send(txt);
* append text to the session log
private void toSessionLog(String prefix, String txt) {
sessionLog.append(prefix + txt);
sessionLog.setCaretPosition(sessionLog.getDocument().getLength() ); // force last line visible
* build the standard menu bar
private void buildMenu()
JMenuItem item;
// file menu
startItem.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent e){mnuStart();}});
fileMenu.add(startItem);
hostItem.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent e){mnuHost();}});
fileMenu.add(hostItem);
exitItem.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent e){mnuExit();}});
fileMenu.add(exitItem);
menuBar.add(fileMenu);
helpMenu.add(aboutItem);
aboutItem.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent e){mnuAbout();}});
menuBar.add(helpMenu);
setJMenuBar(menuBar);
* start and stop communications from start menu
private void mnuStart() {
if(connection.getState() == Connection.State.CLOSED) {
connection.connect(address);
} else {
connection.disconnect();
* prompt user for host in form address:port
private void mnuHost() {
String txt = JOptionPane.showInputDialog("Enter host address:port", connection.getAddress());
if (txt == null)return;
address = txt;
private void mnuAbout() {
JDialog dialog = new JDialog(this, "About Client");
JTextField text = new JTextField("Simple character client");
dialog.getContentPane().add(text);
dialog.pack();
dialog.setVisible(true);
// exit menu
private void mnuExit() {
exit();
private void exit() {
connection.disconnect();
System.exit(0);
private void setStatus(String st) {
statusText.setText(st);
private void setStatus(Connection.State state) {
switch(state) {
case OPENED:
startItem.setText("Stop");
setStatus("Connected to "+address);
break;
case CLOSED:
startItem.setText("Start");
setStatus("Disconnected");
break;
case OPENING:
setStatus("Connecting to "+address);
startItem.setText("Abort");
break;
case CLOSING:
setStatus("Disconnecting from "+address);
startItem.setText("Abort");
break;
public void stateChanged(final ConnectionEvent event) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setStatus(event.getState());
public void dataAvailable(final ConnectionEvent event) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setStatus(event.getState());
String txt = event.getData();
if (txt == null) {
txt = "$null$";
toSessionLog("< ", txt + "\n");
public void sendAllowed(final ConnectionEvent event) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setStatus(event.getState());
sendReady = true;
public void accept(ConnectionEvent event) {
//========================== Server.java ===============================//
package pkwnet.msgswitch;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
* a simple message switch using stream based socket i/o
* a very simple text message switching program
* user commands start with $ and consist of blank seperated arguments
* other lines sent by the user are forwarded
* $on nickname targets
* sign on as nickname, sending to targets
* $to targets
* change target list, reports current value
* $list nicknames
* list status of specified nicknames
* $list
* list all connected users
* $off
* sign off
* @author PKWooster
* @version 1.0 September 1, 2005
public class Server {
private ConcurrentHashMap<String, User> perUser = new ConcurrentHashMap<String,User>();
private Timer idleTimer;
private Connection conn;
public void listen(int port, final int idleTime, boolean nio) {
idleTimer = new Timer();
idleTimer.scheduleAtFixedRate(new TimerTask(){public void run(){oneSec();}},0,1000);
conn = MsgSwitch.getConnection();
conn.addConnectionListener(new ConnectionListener() {
public void stateChanged(ConnectionEvent event) {
public void dataAvailable(ConnectionEvent event) {
public void sendAllowed(ConnectionEvent event) {
public void accept(ConnectionEvent event) {
Connection uconn = event.getConnection();
new User(uconn, perUser, idleTime);
conn.listen(port);
idleTimer.cancel();
private void oneSec() {
Collection<User> uc = perUser.values();
for(User u : uc) {
u.oneSec();
//================= User.java ==============================================//
package pkwnet.msgswitch;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import java.util.logging.Level;
* defines the processing for a message switch user
* @author PKWooster
* @version 1.0 June 15,2004
public class User implements ConnectionListener {
private ConcurrentHashMap<String, User> perUser;
private String name;
private String address;
private boolean signedOn = false;
private String[] targets;
private AtomicInteger remainingTime;
private int idleTime;
Connection conn;
Logger logger;
* construct a user, link it to its connection and put it in the perUser table
User(Connection conn, ConcurrentHashMap<String,User>p, int idle) {
this.conn = conn;
logger = Logger.getLogger("msgswitch.user");
conn.addConnectionListener(this);
address = conn.getAddress();
logger.info("creating user " + address);
perUser = p;
idleTime = idle;
remainingTime = new AtomicInteger(idleTime);
rename(address);
targets = new String[0];
* process state changes
public void stateChanged(ConnectionEvent event) {
if(event.getState() == Connection.State.CLOSED) {
close(false);
* data is available, process commands and forward other data.
public void dataAvailable(ConnectionEvent event) {
String msg = event.getData();
if (msg.startsWith("$")) {
doCommand(msg);
} else {
forward(msg);
remainingTime.set(idleTime);
* do nothing for sendAllowed events
public void sendAllowed(ConnectionEvent event) {
* do nothing for accept events
public void accept(ConnectionEvent event) {
* called once per second by the server main thread.
public void oneSec() {
if(idleTime != 0 && 1 > remainingTime.decrementAndGet()) {
close(true);
* send a message
private void send(String msg) {
conn.send(msg);
remainingTime.set(idleTime);
* forward data messages to other users
* @param txt the message to send
private void forward(String txt) {
txt = name+": "+txt + "\n";
if(0 < targets.length) {
for(String target :targets) {
User user = perUser.get(target);
if(user != null) {
user.send(txt);
} else {
for (User user : perUser.values()) {
if (user != this) {
user.send(txt);
* execute command messages, commands start with a $
* and contain arguments delimited by white space.
* @param command the command string
private void doCommand(String command) {
boolean good = false;
command = command.substring(1).trim();
if(command.length() > 0) {
String [] args = command.split("\\s+");
if(args[0].equals("on")) {
good = signOn(args);
} else if(args[0].equals("off")) {
good = signOff(args);
} else if(args[0].equals("list")) {
good = listUsers(args);
} else if(args[0].equals("to")) {
good = setTargets(args,1);
} else if(args[0].equals("idle")) {
good = setIdle(args);
if(!good) {
send("invalid command=" + command + "\n");
* sign on command
private boolean signOn(String [] args) {
boolean good = false;
if(args.length >1) {
String nm = args[1];
logger.info("signing on as: " + nm);
if(rename(nm)) {
conn.setName(name);
send("Signed on as " + name + "\n");
signedOn = true;
good = true;
setTargets(args,2);
} else {
send("name="+nm+" already signed on\n");
return good;
* set forwarding targets
private boolean setTargets(String [] args, int start) {
if(start < args.length) {
targets = new String[args.length-start];
System.arraycopy(args, start, targets, 0, targets.length);
String str = "to=";
for(String target : targets) {
str += (target + " ");
send(str+"\n");
return true;
* set idle timeout
private boolean setIdle(String[] args) {
try {
idleTime = new Integer(args[1]).intValue();
remainingTime.set(idleTime);
send("idle time set to "+idleTime+"\r\n");
return true;
} catch(NumberFormatException exc) {
return false;
* sign off
private boolean signOff(String [] args) {
close(true);
return true;
* list connected users
private boolean listUsers(String [] args) {
TreeSet<String> allUsers = new TreeSet<String>(perUser.keySet());
HashSet<String> t = new HashSet<String>(Arrays.asList(targets));
LinkedList<String> users;
String response = "On,Target,Nickname\n";
if(args.length < 2) {
users = new LinkedList<String>(allUsers);
} else {
users = new LinkedList<String>();
for (int i = 1; i < args.length; i++) {
users.add(args);
for(String username : users) {
if(username.equals(name)) {
response += "*,";
} else {
response += (allUsers.contains(username) ? "y," : "n,");
response += (t.contains(username) ? "y," : "n,");
response += (username + "\n");
send(response);
return true;
* rename this user, first we attempt to add the new name then we remove
* the old one. Both names will be registered for a short while.
* @param newname the new name for this user
* @return true if the rename was successful
private boolean rename(String newname) {
boolean b = false;
logger.info("rename name="+name+" newname="+newname);
if (name != null && name.equals(newname)) {
b = true;
} else if (null == perUser.putIfAbsent(newname, this)) {
if (name != null) {
perUser.remove(name);
name = newname;
b = true;
return b;
* delete from perUser and close our connection
private void close(boolean disconnect) {
logger.info("closing user "+name);
perUser.remove(name);
if (disconnect) {
conn.disconnect();
//====================== Connection.java ===============================//
package pkwnet.msgswitch;
import java.util.HashSet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;
import java.util.logging.Level;
public abstract class Connection {
public enum State {CLOSED, OPENING, OPENED, CLOSING}
private HashSet<ConnectionListener> listeners = new HashSet<ConnectionListener>();
private State state = State.CLOSED;
private String host = "127.0.0.1";
private int port = 6060;
private String name = "unconnected";
public Connection() {
public abstract void listen(int port);
public abstract void connect(String address);
public abstract void disconnect();
public abstract void send(String message);
public void addConnectionListener(ConnectionListener listener) {
listeners.add(listener);
public void removeConnectionListener(ConnectionListener listener) {
listeners.remove(listener);
protected void fireDataAvailable(String data) {
for (ConnectionListener listener : listeners) {
listener.dataAvailable(new ConnectionEvent(this, state, data));
private void fireStateChanged() {
for (ConnectionListener listener : listeners) {
listener.stateChanged(new ConnectionEvent(this, state));
protected void fireSendAllowed() {
for (ConnectionListener listener : listeners) {
listener.sendAllowed(new ConnectionEvent(this, state));
protected void fireAccept(Connection conn) {
for (ConnectionListener listener : listeners) {
listener.accept(new ConnectionEvent(this, conn));
protected void setState(State state) {
if (this.state != state) {
this.state = state;
fireStateChanged();
public State getState() {
return state;
protected void setAddress(String address) {
int n = address.indexOf(':');
String pt = null;
setName(address);
if(n == 0) {
host = "127.0.0.1";
pt = address.substring(1);
else if(n < 0) {
host = address;
port = 5050;
} else {
host = address.substring(0,n);
pt = address.substring(n+1);
if (pt != null) {
try {
port = Integer.parseInt(pt);
} catch (NumberFormatException e) {
port = -1;
public String getName() {
return name;
public void setName(String value) {
name = value;
public String getAddress() {
return host + ":" + port;
public String getHost() {
return host;
public void setPort(int value) {
port = value;
public int getPort() {
return port;
//=================== ConnectionEvent.java ================================//
package pkwnet.msgswitch;
public class ConnectionEvent extends java.util.EventObject {
private final String data;
private final Connection.State state;
private final Connection conn;
public ConnectionEvent(Object source, Connection.State state, String data, Connection conn) {
super(source);
this.state = state;
this.data = data;
this.conn = conn;
public ConnectionEvent(Object source, Connection.State state, String data) {
this(source, state, data, null);
public ConnectionEvent(Object source, Connection.State state) {
this(source, state, null, null);
public ConnectionEvent(Object source, Connection conn) {
this(source, conn.getState(), null, conn);
public Connection.State getState() {
return state;
public String getData() {
return data;
public Connection getConnection() {
return conn;
//============================ ConnectionListener.java ===================//
package pkwnet.msgswitch;
public interface ConnectionListener extends java.util.EventListener {
public void stateChanged(ConnectionEvent event);
public void dataAvailable(ConnectionEvent event);
public void sendAllowed(ConnectionEvent event);
public void accept(ConnectionEvent event);
//============================ StreamConnection.java ===================//
package pkwnet.msgswitch;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;
import java.util.logging.Level;
* provides stream socket i/o of character strings
* @author PKWooster
* @version 1.0 September 1, 2005
public class StreamConnection extends Connection {
private Socket sock;
private BufferedReader in;
private BufferedWriter out;
private Thread recvThread = null;
private Thread sendThread = null;
protected LinkedBlockingQueue<String> sendQ;
Logger logger;
public StreamConnection() {
super();
logger = Logger.getLogger("msgswitch.stream");
sendQ = new LinkedBlockingQueue<String>();
* open a socket and start i/o threads
public void connect(String ipAddress) {
setAddress(ipAddress);
try {
sock = new Socket(getHost(), getPort());
connect(sock);
} catch (IOException e) {
logger.log(Level.SEVERE, "Connection failed to=" + ipAddress, e);
private void connect(Socket sock) {
this.sock = sock;
String ipAddress = getAddress();
try {
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
recvThread = new Thread(new Runnable() {
public void run() {
doRecv();
},"Recv." + getName());
sendThread = new Thread(new Runnable() {
public void run() {
doSend();
},"Send."+getName());
sendThread.start();
recvThread.start();
setState(State.OPENED);
} catch(IOException e) {
logger.log(Level.SEVERE, "Connection failed to="+ipAddress, e);
public void listen(int port) {
StreamConnection sconn;
setPort(port);
try {
ServerSocket ss = new ServerSocket(port);
while(true) {
Socket us = ss.accept();
sconn = new StreamConnection();
String ipAddress = us.getInetAddress() + ":" + us.getPort();
sconn.setAddress(ipAddress);
sconn.connect(us);
fireAccept(sconn);
} catch(Exception e) {
logger.log(Level.SEVERE, "listen failed", e);
* close the socket connection
public void disconnect() {
logger.fine("disconnect sock=" + sock + " state="+ getState());
if(getState() == State.OPENED) {
setState(State.CLOSING);
try {
sock.shutdownOutput();
} catch(IOException ie) {
logger.log(Level.SEVERE, "showdown failed", ie);
} else if(getState() != State.CLOSED) {
try {
sock.close();
} catch(Exception e) {
logger.log(Level.SEVERE, "close failed", e);
if (sendThread.isAlive()) {
sendThread.interrupt();
sendQ.clear();
setState(State.CLOSED);
public void send(String message) {
if (getState() == State.OPENED) {
try {
sendQ.put(message);
} catch(InterruptedException e) {
logger.log(Level.SEVERE, "sendQ put interrupted", e);
setState(State.CLOSING);
disconnect();
* sets the public name of this connection
public void setName(String name) {
super.setName(name);
if (sendThread != null) {
try {
recvThread.setName("recv." + name);
sendThread.setName("send." + name);
} catch(Exception e) {
logger.log(Level.SEVERE, "nameing threads failed", e);
* the main loop for the send thread
private void doSend() {
String msg;
boolean running = true;
while (running) {
if (sendQ.size() == 0) {
fireSendAllowed();
try {
msg = sendQ.take();
out.write(msg);
out.flush();
} catch(Exception e) {
if (getState() == State.OPENED) {
logger.log(Level.SEVERE, "write failed", e);
setState(State.CLOSING);
disconnect();
running = false;
* the main loop for the receive thread
private void doRecv() {
String inbuf;
while (getState() == State.OPENED) {
try {
inbuf = in.readLine();
} catch(Exception e) {
if (getState() == State.OPENED) {
logger.log(Level.SEVERE, "readline failed", e);
inbuf = null;
if(inbuf == null) {
logger.fine("null received on: " + getAddHere are three of them:
NIO server
NIO client
Multithreaded server
The stream based client example seems to have been deleted, probably lost in the troll wars. I also posted a new Simple multithreaded server that uses the same protocol. As the client is missing, I'll repost it. -
Creating a sample report using JAVA SDK
Hi,
I am trying to create a sample report using JAVA SDK.
I slelect 4 "free cells" and pass 4 different strings to it.
I even slelect the font colour and size. When i run the class and try to view the report in Infoview, I only seeblank blocks without any data. Now if I edit the report from infoview, and save the changes, I am able to see the data.
My issue is, Why am I not able to see the data when I run the java code.
Please find teh code below.
package com;
import java.awt.Color;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.businessobjects.rebean.wi.BinaryView;
import com.businessobjects.rebean.wi.DataProvider;
import com.businessobjects.rebean.wi.DataProviders;
import com.businessobjects.rebean.wi.DataSource;
import com.businessobjects.rebean.wi.DataSourceObject;
import com.businessobjects.rebean.wi.DocumentInstance;
import com.businessobjects.rebean.wi.DocumentLocaleType;
import com.businessobjects.rebean.wi.FontImpl;
import com.businessobjects.rebean.wi.FreeCell;
import com.businessobjects.rebean.wi.HTMLView;
import com.businessobjects.rebean.wi.OutputFormatType;
import com.businessobjects.rebean.wi.PageHeaderFooter;
import com.businessobjects.rebean.wi.Query;
import com.businessobjects.rebean.wi.Recordset;
import com.businessobjects.rebean.wi.Report;
import com.businessobjects.rebean.wi.ReportBody;
import com.businessobjects.rebean.wi.ReportCell;
import com.businessobjects.rebean.wi.ReportContainer;
import com.businessobjects.rebean.wi.ReportElement;
import com.businessobjects.rebean.wi.ReportEngine;
import com.crystaldecisions.sdk.framework.CrystalEnterprise;
import com.crystaldecisions.sdk.framework.IEnterpriseSession;
import com.crystaldecisions.sdk.framework.ISessionMgr;
import com.crystaldecisions.sdk.occa.infostore.IInfoObject;
import com.crystaldecisions.sdk.occa.infostore.IInfoObjects;
import com.crystaldecisions.sdk.occa.infostore.IInfoStore;
import com.crystaldecisions.sdk.plugin.CeKind;
public class Aug7th {
* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
String CMS = "pundl8136:6400";
String userID = "srivas";
String password = "morcom123";
String auth = "secEnterprise";
List<String> entire =new ArrayList<String>();
List<String> country =new ArrayList<String>();
List<String> resort =new ArrayList<String>();
IEnterpriseSession enterpriseSession;
try
ISessionMgr mySessionMgr = CrystalEnterprise.getSessionMgr();
enterpriseSession = mySessionMgr.logon(userID, password, CMS,auth);
if (enterpriseSession != null)
{//Create and store useful objects for the session.
IInfoStore iStore = (IInfoStore)enterpriseSession.getService("InfoStore");
ReportEngine reportEngine = (ReportEngine)enterpriseSession.getService("WebiReportEngine");
IInfoObject infoView = null;
String str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS WHERE (SI_KIND = '"+CeKind.WEBI+"' OR SI_KIND='FullClient') " +
"AND SI_INSTANCE = 'false' AND SI_NAME='Structure Test_001_Java' ORDER BY SI_NAME ASC ";
//String str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS ORDER BY SI_NAME ASC ";
IInfoObjects objInfoObjectsWIDs = (IInfoObjects) iStore.query(str);
System.out.println(objInfoObjectsWIDs.size());
IInfoObject objInfoObjectWID = (IInfoObject) objInfoObjectsWIDs.get(0);
DocumentInstance doc = reportEngine.openDocument(objInfoObjectWID.getID());
DataProviders dps = doc.getDataProviders();
// Retrieve the 1st data provider
DataProvider dp = dps.getItem(0);
// Retrieve the universe objects
DataSource ds = dp.getDataSource ();
Query q = dp.getQuery();
Recordset rs = dp.getResult(0);
// 0: assume query has one flow
rs.first();
// Print the column types. They can be Integer, String,
// or Date.
for (int i = 0; i < rs.getColumnCount(); i++) {
Class c = rs.getColumnType(i);
StringBuffer sbt = new StringBuffer();
if ( c.equals(Integer.class) )
sbt.append("Integer");
if ( c.equals(String.class) )
sbt.append("String");
if ( c.equals(Date.class) )
sbt.append("Date");
sbt.append(";");
System.out.println(sbt.toString());
System.out.println(rs.getColumnCount());
while (!rs.isLast()) {
// column names
StringBuffer sbn = new StringBuffer();
StringBuffer sbd = new StringBuffer();
for (int j = 0; j < rs.getColumnCount(); j++) {
sbn.append( rs.getColumnName(j).toString() );
sbn.append(";");
System.out.println("sbn "+sbn.toString());
// data
for (int k= 0; k< rs.getColumnCount(); k++) {
sbd.append( rs.getCellObject(k).toString() );
sbd.append(";");
entire.add(rs.getCellObject(k).toString());
System.out.println("sbd "+sbd.toString());
rs.next();
System.out.println(entire.size());
for(int i=0;i<entire.size();i++){
country.add(entire.get(i));
i++;
System.out.println("entireList "+entire.get(i));
resort.add(entire.get(i));
DataSourceObject city = ds.getClasses().getChildByName("Country");
DataSourceObject resorts = ds.getClasses().getChildAt(1);
dp.runQuery();
ReportContainer report = doc.createReport("Resort");
PageHeaderFooter header = report.getPageHeader();
FreeCell headerCell = header.createFreeCell("Resort Report");
PageHeaderFooter footer = report.getPageFooter();
FreeCell footerCell = footer.createFreeCell("Report Ends");
ReportBody body = report.createReportBody();
for(int k=0;k<resort.size();k++){
FreeCell res=body.createFreeCell(resort.get(k));
res.getAttachTo();
res.setHeight(15d);
res.setWidth(30d);
Color c = new Color(255,255,255);
Color c1 = new Color(255,0,0);
FontImpl fnt = (FontImpl)res.getFont();
fnt.getDecoration().setTextColor(c1);
res.setFont(fnt);
//res.deleteAttachment();
//res.setAttachTo(body,VAnchorType.BOTTOM,HAnchorType.NONE);
doc.applyFormat();
doc.refresh();
final String l_docToken = doc.getStorageToken();
final DocumentInstance l_docToSave = reportEngine.getDocumentFromStorageToken(l_docToken);
doc.saveAs("mor31",835,null,null);
doc.closeDocument();
str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS WHERE (SI_KIND = '"+CeKind.WEBI+"' OR SI_KIND='FullClient') " +
"AND SI_INSTANCE = 'false' AND SI_NAME='mor31' ORDER BY SI_NAME ASC ";
//String str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS ORDER BY SI_NAME ASC ";
objInfoObjectsWIDs = (IInfoObjects) iStore.query(str);
System.out.println(objInfoObjectsWIDs.size());
objInfoObjectWID = (IInfoObject) objInfoObjectsWIDs.get(0);
DocumentInstance doc1 = reportEngine.openDocument(objInfoObjectWID.getID());
String token = doc1.getStorageToken();
DocumentInstance doc2 = reportEngine.getDocumentFromStorageToken(token);
doc2.saveAs("123123", 835, null, null);
// doc.refresh();
//doc.save();
enterpriseSession.logoff();
catch(Exception e)
e.printStackTrace();duplicate post:
Sample report using JAVA SDK -
Suppressing Applet alerts when using java mail api
Hi,
Im using the following code to send email from my application. Im using JSF (tomahawk), Spring and hibernate in my application. I'm using spring email API classes to send email. This code works perfectly fine in the sense its parsing template and sending emails to the configured email id.
I have defined this class as a managed bean and i have a commanButton is UI which is bound to this sendEmail() method
<t:commandButton value="Send email" action= #{email.sendEmail}/>
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
import org.apache.velocity.runtime.resource.util.StringResourceRepository;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import au.gov.nsw.railcorp.onlineticketing.external.model.request.ServiceFees;
public class EmailService {
JavaMailSenderImpl sender;
VelocityEngine engine;
public EmailService(){
sender = new JavaMailSenderImpl();
sender.setHost("<smtp ip>");
sender.setPort(25);
sender.setUsername("<user id>");
sender.setPassword("<password>");
engine = new VelocityEngine();
Properties p = new Properties();
p.setProperty("resource.loader", "string");
p.setProperty("string.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.StringResourceLoader");
try {
engine.init(p);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
public VelocityEngine getEngine() {
return engine;
public void setEngine(VelocityEngine engine) {
this.engine = engine;
public JavaMailSenderImpl getSender() {
return sender;
public void setSender(JavaMailSenderImpl sender) {
this.sender = sender;
public static void main(String args[]){
EmailService emailService=new EmailService();
emailService.sendEmail();
public boolean sendEmail(){
try{
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo("<to email id>");
helper.setFrom("<from email id>");
helper.setSubject("Teting velocity");
VelocityContext context = new VelocityContext();
StringWriter writer = new StringWriter();
Template template =new Template();
StringResourceRepository repository =StringResourceLoader.getRepository();
String tempText="<html><body>Hi, ${username}...<p> this is a some template!</p></body></html>";
repository.putStringResource("myTemplate",tempText );
context.put("username", "Marc");
template = engine.getTemplate("myTemplate");
template.merge(context, writer);
System.out.println("VM Template:\n" + tempText);
System.out.println("Output:\n" + writer);
String body=writer.toString();
helper.setText(body,true);
sender.send(message);
catch (MessagingException ex) {
// simply log it and go on...
System.err.println(ex.getMessage());
catch (MailException ex) {
// simply log it and go on...
System.err.println(ex.getMessage());
} catch (ParseErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return true;
}The problem i have is when i try to invoke the function sendEmail() from my UI it is throwing a series of applet alerts (some 10 of them) . The following are the alerts that i get
1. The applet is attempting to invoke the java/lang/System.getProperty() operation on java.home
2. The applet is attempting to perform a read operation on the file C:\Program Files\java\jre1.5.0_14\javamail.providers
3. The applet is attempting to perform a read operation on the file C:\Program Files\java\jre1.5.0_14\javamail.address.map etc....
For ever applet alert i had to click on 'allow' for it to proceed. But there is no problem in sending mail after that. One more interesting this is i DONT get this alert when i try to execute this java class directly instead of calling the method from another class or from UI.
Can someone please let me know the reason for this applet alert and the way to suppress it?
Its really urgent .. please help
Thank you..Hi Subhadip,
Thanks for the quick response :)
Please help me understand this.. Im not explicitly using applet anywhere .I guess it should be used internally by one or many of the API classes i have used . In this scenario how can self sign the applet and which one?
I have included some jars like activation.jar,mail-1.4.2.jar,velocity-1.6.2.jar in my webapp lib . Is there a means to sign these jars and use? Is this what you are suggesting me to do?
One more doubt i have is how come the same method runs without any problem when executed as a standalone java class (with main() method)
Will be really helpful if you could help me understand this...
Thanks,
Swami -
How to use java output with other application
hi ,
I am using acme.crypto to encrypt data. this is completely written in java. i need to pass input to this using VB6 and return the output to VB6
how can i achieve the same, is there any readily available dll that can be used in vb?
I am rigorously searching solution, which i am not finding.
I need to know how should i place the java code so that it could be used with VB, as i am new to java world. Do i need to create component using java bean or how?
The code i refered above is nothing but encryption algorithm. I need to pass the input string from vb to java, which will process me the output which inturn should be passed to vb6.
Kindly guide me through this.Why not create a Java ServerSocket in your Java program.
Connect the VB program to this ServerSocket.
Send the input to the Java Program over this socket and have the Java Program encrypt the information and pass it back on the same socket.
Don't know how hard Sockets are in VB6 but a Server Socket in Java is simple.
No need for new DLLs, JNI, etc. -
Strange class error when using java
I've been attempting to use java.awt.robot to simulate a key press when a button is clicked however I'm getting a couple of errors that I can't figure out but I'm not so good when it comes to scripts. When the button "LetterButton" is pressed it should simulate a keypress, ideally to the desktop/operating sytem but the errors I'm getting are:-
1071: Syntax error: expected a definition keyword (such as function) after attribute public, not static.
1084: Syntax error: expecting rightbrace before leftbrace.
1131: Class must not be nested.
Here's the code:-
<?xml version="1.0" encoding="utf-8"?><mx:WindowedApplicationxmlns:mx="
http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class Main {
public static void main(String[] argv) throws Exception {
Robot robot =
new Robot();
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
]]>
</mx:Script>
<mx:VBox x="359" y="262" horizontalCenter="0" verticalCenter="0">
<mx:Button id="LetterButton" label="Button" click=""/>
<mx:TextInput id="txt"/>
</mx:VBox></mx:WindowedApplication>Sounds tricky. I may ask them to look for an alternative way of doing it as Java really isn't my thing, I'm merely just a flex beginner at the moment.
The reason I've been looking for this is that my app will be installed on a digital tv that also has a system connected to it using a Linux operating system so the user can switch between watching digital tv and the application seamlessly and at the moment a Linux professional who I'm working with has the Digital TV bound to the F12 key which is bound to a handheld remote control (being a tv there is no keyboard, just an 'air mouse' and the remote control).
So my client and my Linux guy have asked me to come up with a way of getting the app to communicate with the desktop/operating system. I have seen flex apps in the past where a user can drag and drop videos on their desktop into an air application from which they will be played so I thought it would be possible to interact with the exteral OS/Desktop from within an AIR app by using just flex but it doesn't seem so easy through my research.
Thanks for your help though. -
Trouble using Java on my MacBook
I have tried everything and I am STILL having trouble using Java and Javascript on my MacBook. I have attempted to delete and reinstall Java. I have run the update. I have checked that both Java and Javascript are turned on in Safari. I am unable to use Java and Javascript on several websites. For an example, I am unable to use the photo uploader on Facebook.com. I am using a MacBook with 2.2 GHz Intel chip and OSX 10.5.3
Hi all,
I've got probably the same problem. Got a MacBook (2.4GHz Intel Core 2 Duo, black) and did the Apple Migration App to get all data from a PowerBook (with Leopard on it). Did all updates.
Safari and Firefox don't want to show any JavaApplet.
Is there a problem between old PowerPC and Intel-Plattform.
Maybe it would be a good idea to reinstall Java, but how?
Thanks for suggestions!
Simon -
Hi ...
i have a tabular form
have two columns in that form, kept as a select list by selecting that 1st select list data the related datas has to be popup after selecting that it has to be displayed in the 2nd column by using
java script
eg:
1st column empno-----by selecting the empno the related empname has to be popup
dept no....by selecting the deptno the related deptname has to be popup
thanks in advance,
kishoreThis is a very common question, see
https://forums.oracle.com/thread/2359498 -
Why does my web browser constantly blink when in a site that uses java?
Hi
when visiting a site that uses java my web browser blinks when ever there is an update to the information on the screen. Is there something i should change in my java preferences?
thanksFor safety disable Jave in all your Browsers...
Disable Java in your Browser settings, not JavaScript.
http://support.apple.com/kb/HT5241?viewlocale=en_US
http://support.google.com/chrome/bin/answer.py?hl=en-GB&answer=142064
http://support.mozilla.org/en-US/kb/How%20to%20turn%20off%20Java%20applets
Little Snitch, stops/alerts outgoing stuff...
http://www.obdev.at/products/littlesnitch/index.html
Flashback - Detect and remove the uprising Mac OS X Trojan...
http://www.mac-and-i.net/2012/04/flashback-detect-and-remove-uprising.html
In order to avoid detection, the installer will first look for the presence of some antivirus tools and other utilities that might be present on a power user's system, which according to F-Secure include the following:
/Library/Little Snitch
/Developer/Applications/Xcode.app/Contents/MacOS/Xcode
/Applications/VirusBarrier X6.app
/Applications/iAntiVirus/iAntiVirus.app
/Applications/avast!.app
/Applications/ClamXav.app
/Applications/HTTPScoop.app
/Applications/Packet Peeper.app
If these tools are found, then the malware deletes itself in an attempt to prevent detection by those who have the means and capability to do so. Many malware programs use this behavior, as was seen in others such as the Tsunami malware bot.
MadMacs0 says...
This script from F-Secure is the only one I'm currently recommending http://www.f-secure.com/weblog/archives/00002346.html
http://reviews.cnet.com/8301-13727_7-57410096-263/how-to-remove-the-flashback-ma lware-from-os-x/
http://x704.net/bbs/viewtopic.php?f=8&t=5844&p=70660#p70660
Open DNS also blocks the FlashBack thing...
http://blog.opendns.com/2012/04/09/worried-about-mac-malware-just-set-up-opendns / -
How to make Visibroker's 'vbjc' use Java 1.3 by modifying the properties fi
Hi,
I am using Visibroker for java 4.0 to develop an application. The
java version that I am using is 1.4.1. Now, the naming service does
not start when I use 1.4.1. And I cannot do away with Java1.4.1
because I am using certain classes in javax.crypto which does not
exist at all in Java 1.3. I am left with the option of trying to
configure the properties file of 'vbjc' in such a way that it uses
Java 1.3 instead of 1.4. How can i do this? Can someone please help me
out?
Thanks in advance,
Shankar.HI!
you hasn't given more details ;
can you send me the command, by which you r trying to start the Naming service.
As well as send me the error that you are getting , when used jdk1.4.1 -
Benefits of the way using Java codes in Jdev 11.1.1.5
Hi,
I know there can be 2 ways to do these:
retrieve the file to the DB or take the file from the DB.
1) 1st way is to call DB procedure by passing parameter to it from the java class
2) 2nd way is use java codes to directly do that
What is the benefit of using the 2nd way? How about its details?Hua,
I don't see a connection between retrieve the file to the DB or take the file from the DB. and a stored procedure "getTestData(?, ?)".
As long as Frank (who's crystal ball is much bigger then mine) can guess what you really want to ask, I would appreciate a full use case which we all can understand.
Timo -
(Urgent) Using java to invoke other programs
Guys..
is there any way possible to use java to invoke other programs
eg. java.open(TextPad) or java.execute(NotePad)
something like this
Thx guysWell... im onli 19 and im an interm in a company. My
boss wanted me to help him look for some ways to do
some process.. So actually this is my 1st time trying
out this java forum. I didn't know that you guys took
such a serious views at screen nick... Forgive me for
my ignorance.I actually don't care that much about it, but you might consider changing it for the reasons I gave. You are only 19 now, and might not be an experienced developer, but you will become one later on (if you continue with Java development), and your account can in that case be an asset for you.
Kaj -
PMML Export using Java and ODM 10.2
I'm attempting to export a model I've built in ODM using Java and the example code in dmexpimpdemo.java. I'm getting an error when trying to set an additional attribute to export the data as PMML.
exportTask.setFormat(ImportExportFormat.PMML2_1);
If I call this method (with any ImportExportFormat) I get the exception:
javax.datamining.JDMUnsupportedFeatureException: Unsupported ExportTask for PMML2_1
What is the proper way to export a model as PMML using the JAVA APIs?PMML Export is not supported by the ODM 10.2. Hence you see unsupported exception.
ODM 10.2 supports only Oracle native format support for the mining model export and import. For more details about the usage refer to the demo program dmexpimpdemo.java.
To download sample programs from OTN http://www.oracle.com/technology/products/bi/odm/samples/odm_sample_code_0805.zip
For decision tree model you can export the model details in PMML format using the DBMS_DATA_MINING.get_model_details_xml. For example, the following query returns the PMML format decision tree model as an Oracle Database XMLType
select dbms_data_mining.get_model_details_xml('TREE_MODEL').extract('/') AS DT_DETAILS FROM dual
Regards
Sunil
Maybe you are looking for
-
After the last update, my IBM Clone computer does not close the session of firefox when clicking on "close" it clears the screen back to the desktop but firefox continues to hang there in the backround and will not allow another session of firefox to
-
Computer randomly shuts down and refuses to boot
Hello all. A while back I installed Win 7 Pro on this (I think I had to install it on an SSD via another machine then used that SSD in the T610 and used win repair to fix the installation). It's been going smoothly generally and it is on mor or less
-
How to display accounting periods in a fiscal year?
hi gurus, could you please tell me how to display accounting wise calculations like AP1, AP2 ... AP12 in a given fiscal year in Bex (BI7.0)? please tell me the logic? regards
-
hi, this might be a j2me-newbe's stupid question, but i have the following problem: in cldc 1.1 the method interrupt is defined for the class thread, while in cldc 1.0 it is not. in the javadoc of wtk20 the interrupt method is not available for threa
-
Where is the search facility on i tunes store
where on earth has the search facility gone on the itunes store