Help with understanding multi-threaded code
Hi Everyone,
I am currently reading a book on multi-threading and up until recently I have been able to understand what is going on. The thing is the complexity of the code has just jumped up about two gears without warning. The code is now using inner classes which I am trying to develop an understanding of but I am not finding it easy going, and the book has been lite on explanations. If anybody can help with the following code it will be really appreciated.
public class SetPriority extends Object
private static Runnable makeRunnable()
Runnable r = new Runnable()
public void run()
for(int i=0; i<5; i++)
Thread t = Thread.currentThread();
System.out.println("in run() - priority=" + t.getPriority() +
", name=" + t.getName());
try{
Thread.sleep(2000);
}catch(InterruptedException x){
//ignore
return r;
public static void main(String[] args)
Thread threadA = new Thread(makeRunnable(), "threadA");
threadA.setPriority(8);
threadA.start();
Thread threadB = new Thread(makeRunnable(), "threadB");
threadB.setPriority(2);
threadB.start();
Runnable r = new Runnable()
public void run()
Thread threadC = new Thread(makeRunnable(), "threadC");
threadC.start();
Thread threadD = new Thread(r, "threadD");
threadD.setPriority(7);
threadD.start();
try{
Thread.sleep(3000);
}catch(InterruptedException x){
//ignore
threadA.setPriority(3);
System.out.println("in main() - threadA.getPriority()=" + threadA.getPriority());
}My greatest challenge is understanding how the makeRunnable() method works. I don't understand how this inner class can be declared static and then multiple "instances" created from it. I know that I have no idea what is going on, please help!!!
Thanks for your time.
Regards
Davo
P.S.: If you know of any really good references on inner classes, particularly URL resources, please let me know. Thanks again.
Yikes!! The good news is that you're unlikely to see such convoluted code in real life. But here we go.
"private static Runnable makeRunnable()" declares a method that returns objects of type Runnable. The fact that the method is declared "static" is pretty irrelevant - I'll describe what that means later.
The body of the method creates and returns an object of type Runnable. Not much special about it, except that you can give such an object to the constructor of class Thread and as a result the run() method of this Runnable object will be called on a new thread of execution (think - in parallel).
Now the way it creates this Runnable object is by using the "anonymous inner class" syntax. In effect the method is doing the same as
public class MyNewClass implements Runnable {
public void run() {
// All the same code inside run()
public class SetPriority {
private static Runnable makeRunnable() {
Runnable r = new MyNewClass();
return r;
// The rest of the original code
}Except you don't bother declaring MyNewClass. You're not interested in defining any new method signatures. You just want to create an object that implements Runnable and has certain instructions that you want inside the run() method. Think of the whole approach as shorthand.
Think about this for a while. In the mean time I'll write up the "static".
Similar Messages
-
What's wrong with my multi-threaded Matrix Mult. code? 1 thread is fastest
For some reason, 1 thread performs the best. What's wrong with my implementation?
import java.util.Random;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Matrix {
private int values[][];
private int rows;
private int columns;
public Matrix(int r, int c) {
this.rows = r;
this.columns = c;
this.values = new int[r][c];
private void randomize() {
Random generator = new Random();
for (int r = 0; r < this.rows; r++) {
for (int c = 0; c < this.columns; c++) {
this.values[r][c] = generator.nextInt(10);
public String toString() {
String out = "";
for (int r = 0; r < this.rows; r++) {
for (int c = 0; c < this.columns; c++) {
if (c == 0) out += "[";
else out += "\t";
out += this.values[r][c];
out += "]\n";
return out;
public boolean equals(Object obj) {
Matrix other = (Matrix) obj;
if (this.columns != other.columns || this.rows != other.rows) {
return false;
for (int r = 0; r < this.rows; r++) {
for (int c = 0; c < this.columns; c++) {
if (this.values[r][c] != other.values[r][c]) {
return false;
return true;
// matrix multiplication using single thread
public Matrix times(Matrix other) {
assert(this.columns == other.rows);
Matrix out = new Matrix(this.rows, other.columns);
for (int r = 0; r < this.rows; r++) {
for (int c = 0; c < other.columns; c++) {
int dotProduct = 0;
for (int z = 0; z < this.columns; z++) {
dotProduct += this.values[r][z] * other.values[z][c];
out.values[r][c] = dotProduct;
return out;
// matrix multiplication with many threads
public Matrix ptimes(Matrix other, int numberOfThreads) throws InterruptedException { // parallel
assert(this.columns == other.rows);
Matrix out = new Matrix(this.rows, other.columns);
ExecutorService threadExecutor = Executors.newFixedThreadPool(numberOfThreads);
for (int r = 0; r < this.rows; r++) {
for (int c = 0; c < other.columns; c++) {
threadExecutor.execute(new HelperThread(r, c, this, other, out));
threadExecutor.shutdown();
threadExecutor.awaitTermination(2, TimeUnit.DAYS);
return out;
private class HelperThread implements Runnable {
private int row;
private int col;
private Matrix a;
private Matrix b;
private Matrix out;
HelperThread(int r, int c, Matrix a, Matrix b, Matrix o) {
this.row = r;
this.col = c;
this.a = a;
this.b = b;
this.out = o;
public void run() {
int dotProduct = 0;
for (int z = 0; z < a.columns; z++) {
dotProduct += this.a.values[row][z] * this.b.values[z][col];
this.out.values[row][col] = dotProduct;
public static void main(String[] args) throws InterruptedException {
int size = 100;
Matrix a = new Matrix(size, size);
a.randomize();
Matrix b = new Matrix(size, size);
b.randomize();
for (int t = 1; t < 15; t++) {
long start = new Date().getTime();
System.out.print(t + " threads: ");
Matrix c = a.ptimes(b, t);
//System.out.println(c);
long finish = new Date().getTime();
System.out.println((finish - start) + " milliseconds");
Matrix d = a.times(b);
assert(c.equals(d));
}This one is even faster. On my dual core I get:
Warmup
Single Threaded
5.20616 milliseconds
5.52872 milliseconds
5.12708 milliseconds
5.59048 milliseconds
5.16104 milliseconds
5.1838 milliseconds
5.37104 milliseconds
5.1788 milliseconds
5.18636 milliseconds
5.15736 milliseconds
Multi Threaded with 2 threads
3.22184 milliseconds
2.86552 milliseconds
2.86284 milliseconds
3.67032 milliseconds
3.08032 milliseconds
2.97388 milliseconds
2.93084 milliseconds
3.44012 milliseconds
2.89744 milliseconds
2.88136 milliseconds
As you can see the Multi-Threaded versions are now faster.
// matrix multiplication with many threads
ExecutorService threadExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public Matrix ptimes(Matrix other) throws InterruptedException, ExecutionException {
assert (this.columns == other.rows);
Matrix out = new Matrix(this.rows, other.columns);
Future futures[] = new Future[rows];
for (int r = 0; r < this.rows; r++) {
futures[r] = threadExecutor.submit(new HelperThread(r, this, other, out));
for(Future f : futures) {
f.get();
return out;
private class HelperThread implements Callable<Object> {
private int row;
private Matrix a;
private Matrix b;
private Matrix out;
HelperThread(int r, Matrix a, Matrix b, Matrix o) {
this.row = r;
this.a = a;
this.b = b;
this.out = o;
public String call() throws Exception {
int dotProduct = 0;
for (int c = 0; c < b.columns; c++) {
for (int z = 0; z < a.columns; z++) {
dotProduct += this.a.values[row][z] * this.b.values[z][c];
this.out.values[row][c] = dotProduct;
return null;
public static void main(String[] args) throws InterruptedException, ExecutionException {
int size = 100;
Matrix a = new Matrix(size, size);
a.randomize();
Matrix b = new Matrix(size, size);
b.randomize();
System.out.println("Warmup");
for (int t = 0; t < 1000; t++) {
Matrix c = a.ptimes(b);
Matrix d = a.times(b);
assert (c.equals(d));
System.out.println("Single Threaded");
for (int t = 0; t < 10; t++) {
long start = System.nanoTime();
Matrix d = a.times(b);
long finish = System.nanoTime();
System.out.println((finish - start)/1000000.0 + " milliseconds");
System.out.println("Multi Threaded with " + Runtime.getRuntime().availableProcessors() + " threads");
for (int t = 0; t < 10; t++) {
long start = System.nanoTime();
Matrix c = a.ptimes(b);
long finish = System.nanoTime();
System.out.println((finish - start)/1000000.0 + " milliseconds");
Matrix d = a.times(b);
assert (c.equals(d));
System.exit(0);
} -
Help with Understanding Regular Expressions
Hello Folks,
I need some help in understanding the Regular Expressions.
-- This returns the Expected string from the Source String. ", Redwood Shores,"
SELECT
REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA,aa',
',[^,]+,', 1, 1) "REGEXPR_SUBSTR"
FROM DUAL;
REGEXPR_SUBSTR
, Redwood Shores,
However, when the query is changed to find the Second Occurrence of the Pattern, it does not match any. IMV, it should return ", CA,"
SELECT
REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA,aa',
',[^,]+,', 1, *2*) "REGEXPR_SUBSTR"
FROM DUAL;
REGEXPR_SUBSTR
NULLCan somebody help me in understanding Why Second Query not returning ", CA,"?
I did search this forum and found link to thread "https://forums.oracle.com/forums/thread.jspa?threadID=2400143" for basic tutorials.
Regards,
P.PurveshK wrote:
Can somebody help me in understanding Why Second Query not returning ", CA,"?With your query...
SELECT
REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA,aa',
',[^,]+,', 1, *2*) "REGEXPR_SUBSTR"
FROM DUAL;You are looking for patterns of "comma followed by 1 or more non-comma chrs followed by a comma."
So, let's manually pattern match that...
'500 Oracle Parkway, Redwood Shores, CA,aa'
^ ^
| |
|
|
Here to here is the
first occurence.So the second occurance will start searching for the same pattern AFTER the first occurence.
'500 Oracle Parkway, Redwood Shores, CA,aa'
^
|
i.e. the search for the second occurence starts heretherefore the first "," from that point is...
'500 Oracle Parkway, Redwood Shores, CA,aa'
^
|
hereand there is nothing there matching the pattern you are looking for because it only has the
"comma follwed by 1 or more non-comma chrs"... but it doesn't have the "followed by a comma"
...so there is no second occurence, -
Help with understanding key event propagation
Hello,
I am hoping someone can help me understand a few things which are not clear to me with respect to handling of key events by Swing components. My understanding is summarized as:
(1) Components have 3 input maps which map keys to actions
one for when they are the focused component
one for when they are an ancestor of the focused component
one for when they are in the same window as the focused component
(2) Components have a single action map which contains actions to be fired by key events
(3) Key events go to the currently focused component
(4) Key events are consumed by the first matching action that is found
(5) Key events are sent up the containment hierarchy up to the window (in which case components with a matching mapping in the WHEN_IN_FOCUSED_WINDOW map are searched for)
(6) The first matching action handles the event which does not propagate further
I have a test class (source below) and I obtained the following console output:
Printing keyboard map for Cancel button
Level 0
Key: pressed C
Key: released SPACE
Key: pressed SPACE
Level 1
Key: pressed SPACE
Key: released SPACE
Printing keyboard map for Save button
Level 0
Key: pressed SPACE
Key: released SPACE
Level 1
Key: pressed SPACE
Key: released SPACE
Printing keyboard map for Main panel
Event: cancel // typed SPACE with Cancel button having focus
Event: save // typed SPACE with Save button having focus
Event: panel // typed 'C' with panel having focus
Event: panel // typed 'C' with Cancel button having focus
Event: panel // typed 'C' with Save button having focus
I do not understand the following aspects of its behaviour (tested on MacOSX although I believe the behaviour is not platform dependent):
(1) I assume that the actions are mapped to SPACE since the spacebar clicks the focused component but I don't explicitly set it?
(2) assuming (1) is as I described why are there two mappings, one for key pressed and one for key released yet the 'C' key action only has a key pressed set?
(3) assuming (1) and (2) are true then why don't I get the action fired twice when I typed the spacebar, once when I pressed SPACE and again when I released SPACE?
(4) I read that adding a dummy action with the value "none" (i.e. the action is the string 'none') should hide the underlying mappings for the given key, 'C' the my example so why when I focus the Cancel button and press the 'C' key do I get a console message from the underlying panel action (the last but one line in the output)?
Any help appreciated. The source is:
import javax.swing.*;
public class FocusTest extends JFrame {
public FocusTest () {
initComponents();
setTitle ("FocusTest");
setLocationRelativeTo (null);
setSize(325, 160);
setVisible (true);
public static void main (String[] args) {
new FocusTest();
private void initComponents()
JPanel panTop = new JPanel();
panTop.setBackground (java.awt.Color.RED);
JLabel lblBanner = new javax.swing.JLabel ("PROPERTY TABLE");
lblBanner.setFont(new java.awt.Font ("Lucida Grande", 1, 14));
lblBanner.setHorizontalAlignment (javax.swing.SwingConstants.CENTER);
panTop.add (lblBanner);
JPanel panMain = new JPanel ();
JLabel lblKey = new JLabel ("Key:");
lblKey.setFocusable (true);
JLabel lblValue = new JLabel ("Value:");
JTextField tfKey = new JTextField(20);
JTextField tfValue = new JTextField(20);
JButton btnCancel = new JButton (createAction("cancel")); // Add a cancel action.
JButton btnSave = new JButton (createAction("save")); // Add a sve action.
panMain.add (lblKey);
panMain.add (tfKey);
panMain.add (lblValue);
panMain.add (tfValue);
panMain.add (btnCancel);
panMain.add (btnSave);
add (panTop, java.awt.BorderLayout.NORTH);
add (panMain, java.awt.BorderLayout.CENTER);
setDefaultCloseOperation (javax.swing.WindowConstants.EXIT_ON_CLOSE);
// Add an action to the panel for the C key.
panMain.getInputMap (JComponent.WHEN_IN_FOCUSED_WINDOW).put (KeyStroke.getKeyStroke (java.awt.event.KeyEvent.VK_C, 0), "panel");
panMain.getActionMap ().put ("panel", createAction("panel"));
// FAILS ???
// Add an empty action to the Cancel button to block the underlying panel C key action.
btnCancel.getInputMap().put (KeyStroke.getKeyStroke (java.awt.event.KeyEvent.VK_C, 0), "none");
// Print out the input map contents for the Cancel and Save buttons.
System.out.println ("\nPrinting keyboard map for Cancel button");
printInputMaps (btnCancel);
System.out.println ("\nPrinting keyboard map for Save button");
printInputMaps (btnSave);
// FAILS NullPointer because the map contents are null ???
System.out.println ("\nPrinting keyboard map for Main panel");
// printInputMaps (panMain);
private AbstractAction createAction (final String actionName) {
return new AbstractAction (actionName) {
public void actionPerformed (java.awt.event.ActionEvent evt) {
System.out.println ("Event: " + actionName);
private void printInputMaps (JComponent comp) {
InputMap map = comp.getInputMap();
printInputMap (map, 0);
private void printInputMap (InputMap map, int level) {
System.out.println ("Level " + level);
InputMap parent = map.getParent();
Object[] keys = map.allKeys();
for (Object key : keys) {
if (key.equals (parent)) {
continue;
System.out.println ("Key: " + key);
if (parent != null) {
level++;
printInputMap (parent, level);
Thanks,
Tim MowlemUse the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.
1) In the Metal LAF the space bar activates the button. In the Windows LAF the Enter key is used to activate the button. Therefore these bindings are added by the LAF.
2) The pressed binding paints the button in its pressed state. The released binding paint the button in its normal state. Thats why the LAF adds two bindings.
In your case you only added a single binding.
3) The ActionEvent is only fired when the key is released. Same as a mouse click. You can hold the mouse down as long as you want and the ActionEvent isn't generated until you release the mouse. In fact, if you move the mouse off of the button before releasing the button, the ActionEvent isn't even fired at all. The mouse pressed/released my be generated by the same component.
4) Read (or reread) the [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html#howto]How to Remove Key Bindings section. "none" is only used to override the default action of a component, it does not prevent the key stroke from being passed on to its parent. -
Help with understanding initial admin account vs. directory admin
Hello,
I am hoping someone can help me understand the initial admin account created when I was first configuring my server, and the directory admin.
I have setup an advanced server, and when I was going through the initial setup I created an account that for this discussion I'll call "admin." Once the initial setup was finished I started using Workgroup manager to create accounts. I was informed that I should create a different directory admin so I did and for this discussion we'll call that account "diradmin."
I am curious why the initial account of admin does not show up in workgroup manager, and why it does not show up as an option in Server Admin to assign permissions.
Is this making any sense?
Any explanation is greatly appreciated.
Thank you,
ScottHi
Presumably you used the Server Setup Assistant to configure Services prior to bringing the Server online?
Not a good idea really. When choosing Advanced after the Server Software has been installed don't enable/configure any service apart from Remote Desktop. Once the Server setup is complete run all available updates. Once you've done that begin to configure required Services using Server Admin. Once you've done that begin to populate your directory nodes with users using WorkGroup Manager.
The key to understanding the two accounts (a) System Administrator (admin UID 501) and (b) Directory Administrator (diradmin UID 100) is understanding which directory node you want to provide services to. The 'Local' node and the server in general (putting aside the super user 'root') will always be admin. Once you promote the Server from Standalone to OD Master you effectively create another Directory in addition to the Local one. This LDAP Directory can be used for all sorts of things. Principally enabling directory and contact information (amongst other things) to be shared/accessed with users that exist in that node with an enhanced authentication system (Kerberos) not available in the Local node and if the Server is in a Standalone Role. This LDAP Directory is controlled by diradmin. You won't be able to use admin for the LDAP node but you can use diradmin for the server in general - although I would not advise it. You can use root for both nodes - again I would not advise it unless absolutely necessary. Basically use admin to log into the Server and do the day to day stuff and use diradmin for the LDAP. Get into the habit of never having both applications open unless you are going to use them. Once you are done, quit out of them and leave them alone.
To toggle between the two Directory nodes launch Workgroup Manager and click on the small blue globe below the main set of icons at the top and above the Users/Groups/Machines tabs. You should see at least 4 selections: Local, /LDAPv3/127.0.0.1, Search Policy and Other. If you don't see /LDAPv3/127.0.0.1 select Other and browse for it. If you still don't see it then you effectively don't have an OD Master. This will severely limit the ability of server to provide auot-mounting networked home folders as well as access to iCal Server's features amongst other things.
Finally if you truly want LDAP and everything that goes with it then your DNS Service - wherever its placed - has to be correctly conigured and tested. This link is for a post that explains how to achieve this simply using the interface:
http://discussions.apple.com/thread.jspa?threadID=1251475&tstart=45
Depending on your network environment it might not be appropriate for you? However stick with it as it is a long post and you may find it useful?
Tony -
HELP WITH AN OLDER VERSION CODE!!!!!
I am trying to figure out how to convert a code from an older version into JDK1.3.1_01.
Please HELP!
Here is my code............
mport java.awt.*;
import java.applet.*;
public class Race extends Applet {
private Button myButton; //use a button to start the race.
int race_square; //record the race square 70.
int t_square; //record the tortoise's position.
int h_square; //record the hare's position.
int clock; //record clock ticks.
public void init()
myButton=new Button("Start Clock") ; //add button to the top of panel.
add("North",myButton);
reset_v();
public void reset_v()
race_square=70; // total squares is 70
t_square=1; //start point =1
h_square=1; //start point=1
clock=0; //reset the clock to zero.
public void race() {
int i=0; //set some integer varibles.
int t_random=0; //random number for tortoise.
int h_random=0; //random number for hare.
Graphics g=getGraphics(); //define graphics.
Rectangle r = bounds(); //define painting boundary.
g.drawString("BANG !!!!!",100,r.height/2-80);
g.drawString("AND THEY'RE OFF !!!!!",100,r.height/2-70);
g.drawString(Integer.toString(clock),r.width/2,50); //show the zero clock time.
do{
try { Thread.sleep(1000);} //clock ticks 1 second.
catch (InterruptedException e){}
clock++;
g.setColor(Color.lightGray); //clear all the old drawings
g.fillRect(0,0,r.width,r.height);
g.setColor(Color.black);
g.drawString(Integer.toString(clock),r.width/2,50); //show the clock time.
t_random=getrandom(); // FOR TORTOISE
if (t_random<=5) t_square+=3; // 50% fast plod: 3 squares to the right.
else if (t_random>5 && t_random<=7)t_square-=6; // 20% slip: 6 squares to the left.
else t_square+=1; // 30% slow plod: 1 square to the right.
h_random=getrandom(); //FOR HARE
if (h_random<=2) {} // 20% sleep: not move at all.
else if (h_random>2 && h_random<=4)h_square+=9;// 20% big hop: 9 squares to the right.
else if (h_random==5) h_square-=12; // 10% big slip: 12 squares to the left.
else if (h_random>5 && h_random<=8)h_square+=1;// 30% slow hop: 1 square to the right.
else h_square-=2; // 20% small slip: 2 aquares to the left.
if(t_square<=0) t_square=1; //always start from 1.
if(t_square>race_square)t_square=race_square;
if(h_square<=0) h_square=1; //always start from 1.
if(h_square>race_square)h_square=race_square;
g.setColor(Color.red); //draw the tortoise's path: use red color.
g.fillRect(5,r.height/2-5,5*t_square,5);
g.drawString("T",5*t_square,r.height/2-7);
g.setColor(Color.blue); //draw the hare path: use blue color.
g.fillRect(5,r.height/2+1,5*h_square,5);
g.drawString("H",5*h_square,r.height/2+17);
g.setColor(Color.black); //draw the race squares.
g.drawLine(5,r.height/2,5+5*race_square,r.height/2);
for(i=5;i<=5+5*race_square;i+=5)
g.drawLine(i,r.height/2-5,i,r.height/2+5);
if (t_square==h_square &&t_square!=race_square) // tortoise bites the hare.
g.drawString("OUCH!!!",5+5*h_square,r.height/2-16);
}while ( t_square=race_square && h_square=race_square && t_square<=5+5*race_square;i+=5)
g.drawLine(i,r.height/2-5,i,r.height/2+5);
g.drawString("T",5,r.height/2-7); //mark tortoise
g.drawString("H",5,r.height/2+17); //mark hare
public int getrandom()
return( 1+(int)(Math.random()*10)); // generating the random number 1 to 10.
public boolean action(Event e, Object arg)
if (e.target instanceof Button)
reset_v(); //reset the initial variables.
race(); //use the button the start the race.
return true;You posted this yesterday, at
http://forum.java.sun.com/thread.jsp?forum=54&thread=185330
The code you've posted doesn't seem to include Ilikejava's suggested changes - which are, as far as I can tell, the major changes required to bring your applet in line with Java 1.3.
It will be easier to help if you show what is wrong with your code, if it's generating a compiler error message or throwing an exception.
Regards,
-Troy -
Query Help with Item Master & Warehouse Code
Forum,
I would like help with a query to identify any items within a database where a particular warehouse code does NOT exist against it. At present I have the following:
select T0.ItemCode, T1.WhsCode from OITM T0
INNER JOIN OITW T1 on T0.ItemCode = T1.ItemCode
where T0.ItemCode NOT IN ('WHS1')
This is returning all other instance and not just a list of item codes where 'WHS1' is missing from within the 'Stock Data' tab.
Thanks,
SarahHi Sarah...
Try This
SELECT T0.ItemCode, T0.ItemName, T1.WhsCode
FROM OITM T0 INNER JOIN OITW T1 ON T0.ItemCode = T1.ItemCode
WHERE T1.WhsCode not in ( 'WHS1')
Regards
Kennedy -
Help with java digital signing code
hello people.
can anybody help me?
i have find a java code to resolve my problem with sending pay in soap envelope with digital signature and attached certificate. i compiled it with jdk jdk1.6.0_37. and it works.
i need it to work in built-in jvm in oracle 9i. in oracle 9i jvm release is 1.3.1. Java code does not work there. there is an error
class import com.sun.org.apache.xerces.internal.impl.dv.util.Base64 not found in import.
i did not find this class in network.
can anybody help with rewriting it for jvm 1.3.1?
thanks in advance.
code below:
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.*;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.Certificate;
public class Sign {
public static void main(String[] args) throws Exception {
// TODO code application logic here
BufferedReader reader = new BufferedReader(new FileReader("c:\\cert.p12"));
StringBuilder fullText = new StringBuilder();
String line = reader.readLine();
while (line != null) {
fullText.append(line);
line = reader.readLine();
KeyStore p12 = KeyStore.getInstance("pkcs12");
p12.load(new FileInputStream("c:\\cert.p12"), "Hfrtnf$5".toCharArray());
//????????? ????????? ????, ??? ????? ????? ???????????? alias ? ??????
//Key key = p12.getKey("my kkb key", "ryba-mech".toCharArray());
Key key = (Key) p12.getKey("my kkb key", "Hfrtnf$5".toCharArray());
Certificate userCert = (Certificate) p12.getCertificate("my kkb key");
String base64Cert = new String(Base64.encode(userCert.getEncoded()));
//signing
Signature signer = Signature.getInstance("SHA1withRSA");
signer.initSign((PrivateKey) key);
signer.update(fullText.toString().getBytes());
byte[] digitalSignature = signer.sign();
String base64sign = new String(Base64.encode(digitalSignature));
String base64Xml = new String(Base64.encode(fullText.toString().getBytes()));
System.out.println("<certificate>" + base64Cert+"</certificate>");
System.out.println("<xmlBody>" + base64Xml+"</xmlBody>");
System.out.println("<signature>" + base64sign+"</signature>");
Edited by: user13622283 on 22.01.2013 22:08My first search is to see if there is an Apache commons project that provides it. Lo and behold:
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html
commons-codec. -
Help with running multiple threads
I'm new to programming with threads. I want to know how to run
multiple threads at the same time. Particularly for making games
in Java which I'm also begining to learn. For running multiple
threads at the same time, do you have to put two run() methods
in the source? If not then how do you make two threads or more
run at the same time?
Thanks for helping.For running multiple
threads at the same time, do you have to put two run()
methods
in the source? Hi there,
Each thread is presumably performing a task. You may be performing the same task multiple times or be performing different tasks at once. Either way, each task would typically be contained within the run() method of a class. This class would either be a subclass of java.lang.Thread (extends Thread) or would be an implementation of java.lang.Runnable (implements Runnable). In either case, you would define a method with signature (public void run()...). The difference comes into play when you wish to actually perform one of these tasks. With a subclass of Thread, you would simply perform:
new MyTask().start();
With an implementation of Runnable, you would do this:
new Thread(new MyTask()).start();
This assumes you don't need to monitor the threads, won't be sending any messages to your tasks or any such thing. If that were the case, you would need to tuck away those returns to new MyTask() for later access.
In order to launch two threads simultaneously, you would have something along the lines of:
new MyTask().start();
new MyOtherTask().start();
Now it is perfectly possible that MyTask() would complete before MyOtherTask() managed to start in which case it wouldn't appear as if you had actually had multiple threads running, but for non-trivial tasks, the two will likely overlap. And of course, in a game, these tasks would likely be launched in response to user input, which means that you wouldn't have any control over when or in what order they executed.
Anyhow, it's as simple as that. You should also consider following the Java Threading trail which shows a simple example of using multiple threads. You can find it at:
http://java.sun.com/docs/books/tutorial/essential/threads/index.html
Regards,
Lynn -
Help with some java login code
hey,
I am a new member but used to visit the site regularly. I am undergoing a java project and I cannot seem to get my head around how to code when users log in, there name must appear at the top of each page they visit.
User enters name into a text box. Do I use getter and setter methods? any bit of help would be of some advantage to me.
Thanks for your time and I'll help with anyone else who is stuck.if JSP or servlet use Session...
if you are using frame you have to consider... which frame is a top parent. that top frame will have the set and get method.. for you to set and retrieve the user name.. bear in mind that different object will have different user...
so you have to play fair game ...hehehehe :-) -
Need help with this Pascal Triangle code....
Hey everyonr i am totally new to Java... so need your help with this code...
the function makeRows gives me problems... main is correct ... can someone fix my makeRows... i don't see what's wrong
public class Pascal {
/** Return ragged array containing the first nRows rows of Pascal's
* triangle.
public static int[][] makeRows(int nRows) {
int[][] mpr = new int[nRows+1][];
int l=0; int r=0;
for (int row = 0; row < nRows; row++) {
mpr[row] = new int[row+1]; //index starts at 0
if (row==0) {
mpr[0][0]= 1;
if (row==1) {
mpr[1][0]= 1;
mpr[1][1]= 1;
if (row>=2) {
for (int j = 0; j <= row; j++) {
if (j==0) {l=0;} else {l=mpr[row-1][j-1];}
if (j==mpr[row].length-1) {r=0;} else{r=mpr[row-1][j];}
mpr[row][j] = l + r;
return mpr;
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("usage: java " + Pascal.class.getName() + " N_ROWS");
System.exit(1);
int nRows = Integer.parseInt(args[0]);
if (nRows > 0) {
int[][] pascal = makeRows(nRows);
for (int[] row : pascal) {
for (int v : row) System.out.print(v + " ");
System.out.println("");
}this makeRows function should return ragged array containing the first nRows rows of Pascal's triangle
thanks
Edited by: magic101 on May 9, 2008 4:03 PMmagic,
i think corlettk meant that some people might not know what pascal's triangle is.
also, you didnt say what was wrong with your code, just that it was wrong.
asking smart questions is about giving as much information you can to get the
best answer. i would throw a System.out.print between every line of your
algorithm. i would also supply us with the values you are getting for each row.
also, this question is asked all the time here. do a forum search.
1
11
121
1331
14641 -
Elasticity: help with converting Flash 5 code to Flash 8
Hello
because I have to make a flash menu with elasticity effect I
came upon this tutorial:
http://www.kirupa.com/developer/actionscript/spring.htm
All OK but the code there works only with Flash 5. I somehow
managed to concoct code that works for Flash 6 but still I didn't
come even close to a code working in Flash 8. I'm using
Actionscript only from version 7, I do not know anything about
Flash 5 and 6. So please, the more experienced guys, help me!!
The code I concocted is:
MovieClip.prototype.move = function (centerx, centery,
inertia, k) {
this.x = -this._x+centerx;
this.y = -this._y+centery;
this.xp = this.xp*inertia+this.x*k;
this.yp = this.yp*inertia+this.y*k;
this._x += this.xp;
this._y += this.yp;
onEnterFrame=function() {
this.move (_root._xmouse,_root._ymouse,0.9,0.1) ;
This whole code is on the timeline of the MC being moved.
So now the only thing I need is to make this code work for
Flash 8
Please, helpJust managed to do it !
-
Need help with HD Multi-cam editing...
So it is my understanding that you can't view a multi-cam sequence unless the footage you are viewing is unrendered/unlimited...
So my question is... how do I take rendered footage and de-render it so its unlimited... I tried adding an effect but even color corrector just makes the footage go from rendered to "needs render" which is no good.
For those who understand multi-cam editing better... could you provide some pointers. Thanks!nvm i figured it out.
-
Helpful hint while multi-threading
Hi all
This had me stupmed for a little while. A multi-threaded program I'd been working didn't appear to be working correctly. I noticed this was because it looked like the thread never made it to its run() method. The cause of this was the fact id overridden the start() method of the thread without including this.run() at the end. The symptoms of this happening aren't obvious though, and it can be quite puzzling. I hope this gets added to any FAQs etc, or solves someones problem.And if, for whatever reason, you do need to override start(), you should not call this.run() at the end, you should call super.start() !!!
If you call this.run() at the end, you are having the current thread go and do the run method.
Maybe you are looking for
-
Setting Cursor - For a window and application wide
Hi, Can somebody please help with a cursor problem ? I am not able to set the busy cursor for a frame when the application is doing some work. I have tried many methods of doing this (some of them from these forums...) but still I am not able to make
-
I can't access the software updates available. I'm getting the message: (NSURLErrorDomain error-1012.). What can I do to find resolution to the problem?
-
Resource Bundles and Embedded fonts - best practice
Hello, I am in digging into creating a localized app and I would like to use embedded fonts. Ideally, I would like to have two locales (for example), each with a different embedded font and/or unicode range. For example, how do I set up my localized
-
Premiere Pro CC 2014 update and Media Encoder update fail to install
Hi - I've been updating my CC applications. But PP CC 2014 and media Encoder say: "UPDATE FAILED". Naturally I cannot get through to Abobe. Does anyone have a suggestion? Harry
-
Project resources with different working weeks
Hi All, I have a project with resources in different locations (Australia and the Middle East) who have different work weeks. Australia (Monday-Friday) Middle East (Sunday-Thursday) Basically, common work week is Monday-Thursday, while the Australi