Java JCE Problem

I am now making a secure mail application which can encrypt plaintext mail and send to a mail server. Also, decrypt encrypted mail to plaintext. I�m using Java to develop the application.
However, I am facing the following problem:
I tried using AES of JCE to encrypt a message. As you know, the doFinal( ) will return encrypted result as a byte[ ]. Then I turned the result byte[ ] into String (The String will be treated as mail content in further development).
Next, I decrypted the String. First of all, I turned the String back to byte[ ] and decrypted it using doFinal( ). However the program flew this exception:
javax.crypto.BadPaddingException: Given final block not properly padded
If I haven�t changed the resulted byte[] into String, it can be properly decrypted.
Does anyone know how to solve it? I know that the problem may be triggered by the byte[] to String conversion.
Here is my source code:
import javax.crypto.*;
import javax.crypto.spec.*;
public class TestingAES {
   public static void main(String[] args) throws Exception {
      String message = "This is just an example";     
      System.out.println("message : " + message);
      // Get the KeyGenerator          
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(128);
      // Generate the secret key specs.
      SecretKey skey = kgen.generateKey();
      byte[] raw = skey.getEncoded();          
      SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
      // Instantiate the cipher          
      Cipher cipher = Cipher.getInstance("AES");          
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      //get the result enrypted byte[]
      byte[] encrypted = cipher.doFinal(message.getBytes());
      //turn the result enrypted byte[] to String
      //As the result will be store in server, it must be turned to String
      String encryptedString = new String(encrypted);
      //turn the String into byte[] and decrypt it
      byte[] encryptedByte = encryptedString.getBytes();
      cipher.init(Cipher.DECRYPT_MODE, skeySpec);
      byte[] plainByte = cipher.doFinal(encryptedByte);
      String plainText = new String(plainByte);
      System.out.println("plainText : " + plainText);
}

" I know that the problem may be triggered by the byte[] to String conversion."
That is correct, so one answer is to use an encoding (not encrypting) algorithm. The most common encodings I know of for crypto are Base64, ASCIII armor ala PGP, and ASCII hexadecimal. There is a Base64 encoder in Java, but it is not officially supported. However, lots of folks use it. You need to import the sun.misc.BASE64Encoder package,. For example in your code you have the lines
     //get the result enrypted byte[]
      byte[] encrypted = cipher.doFinal(message.getBytes());
      //turn the result enrypted byte[] to String
      //As the result will be store in server, it must be turned to String
      String encryptedString = new String(encrypted);these would become instead
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
     //get the result enrypted byte[]
      byte[] encrypted = cipher.doFinal(message.getBytes());
      //turn the result enrypted byte[] to String
      //As the result will be store in server, it must be turned to String
      String encryptedString = new String(new BASE64Encoder().encodeBuffer(encrypted));and then you must reverse the process to decrypt., i.e. you decryption code becomes
      //turn the String into byte[] and decrypt it
      byte[] encryptedByte = new BASE64Decoder().decodeBuffer(encryptedString).getBytes();

Similar Messages

  • Java Session problem while sending mail(using javamail) using Pl/SQL

    Hello ...
    i am using Java stored procedure to send mail. but i'm getting java session problem. means only once i can execute that procedure
    pls any help.

    props.put("smtp.gmail.com",host);I doubt javamail recognizes the 'smtp.gmail.com' property. I think it expects 'mail.host'. Of course since it cannot find a specified howt it assumes by default localhost
    Please format your code when you post the next time, there is a nice 'code' button above the post area.
    Mike

  • Java Programming Problem

    Hi all,
    I was looking for this java programming problem which had to do with a large building and there was some gallons of water involved in it too somehow and we had to figure out the height of the buiding using java. This problem is also in one of the java books and I really need to find out all details about this problem and the solution. NEED HELP!!
    Thanks
    mac

    Yes, it will. The water will drain from the bottom of
    the tank until the pressure from the water inside the
    tank equals the pressure from the pipe. In other
    words, without a pump, the water will drain out until
    there is the same amount of water in the tank as in
    the pipe The water pressure depends on the depth of the water, not the volume. So once the depth of the water inside the pipe reaches the same depth as the water inside the tank it will stop flowing. This will never be above the height of the tank.
    I found this applet which demonstrates our problem. If you run it you can drag the guy up to the top, when water in his hose reaches the level of the water in the tank it will stop flowing out.

  • Java Uninstall Problem

    Java Uninstall Problem
    This all came about because of a failed uninstall, using Your Uninstaller.
    The {Java runtime which is all I want) is not listed now & I tried all the other fix bad uninstall type features, all to no avail.} )
    When I DL & run the latest package (jxpiinstall-6u11-fcs-bin-b90-windows-i586-25_nov_2008.exe}
    & run it I get:
    1st message:
         "This software has already been installed on your computer.
         Would you like to install it?"
    If I say no, it exits.
    If I say yes, I get this second message:
         :This action is only valid for products that are currently installed."
    So Now I have no Java & have no idea what to do.
    Any help would be greatly appreciated.
    Thanks, Neuromancer23

    Sorry...after posting it i realized there was a more appropriate forum, of which it took quiet awhile to find.)
    Now that I know where to find the forum list I will never double-post again.
    I'll close the question if I can

  • Sun Java security problems

    Please any one tel me about Sun Java security problems
    with Desktop application

    Hi.
    If you're using SSGD 4.41, please download the Admin guide from here:
    http://docs.sun.com/app/docs/doc/820-4907
    There, at page #41 you'll find useful info concerning "Client Connections and Security Warnings".
    Hope this helps,
    Rob

  • OS X Lion - JAVA SCRIPT PROBLEM

    I recently updated from Snow Leopard to OS X Lion. Now I seem to have a JAVA Script problem. Where do I start fixing this issue. I have checked updates etc etc but it seems to be updated. However, when I login to my web site backend, I have a problem. Any advice please?

    Would you please write some more details? explain the problem and what web site backend you use. Thanks.

  • JCE Problem(not signed by a trusted signer) with J2RE 1.4.1 IBM Windows usi

    The application is working fine with J2RE 1.3 but is giving the following error with J2RE 1.4.1.
    java.security.NoSuchProviderException: JCE cannot authenticate the provider SunJCE java.util.jar.JarException: file:/C:/Workspace5.1/ukfnwLOCALHOST/ukfnwWeb/WebContent/WEB-INF/lib/sunjce_provider.jar is not signed by a trusted signer.
    I am facing the same problem with IAIK, Cryptix and SunJCE Providers.
    Thanks for your help.

    I was facing the same issue. Some where on the web I read that the following would fix it-
    Move <j2sdk dir>/jre/lib/jce.jar to some other location. I did this and restarted the web server and my servlet works fine with cryptix and jsse libraries.
    Seonie

  • Is that an JCE problem? Please help!

    Hi,
    I have followed the JWSDP1.4 tutorial to setup and run the "xws-security\samples\simple" sample with
    Tomcat as the container and assembla_msks_jce.jar as the JCE provider, but always got the exception
    shown below when running the TestClient.
    I have put assembla_msks_jce.jar under %JAVA_HOME%\jre\lib\ext and set
    security.provider.2=se.assembla.jce.provider.ms.MSProvider
    in java.security.
    Could someone kindly tell me what else should I do except what has been described in the README.txt?
    Thanks!
    ================================================
    run-sample:
    [echo] Running the simple.TestClient program....
    [java] Service URL=http://localhost:8080/securesimple/Ping
    [java] java.lang.NullPointerException
    [java] at com.sun.org.apache.xml.security.encryption.XMLCipher.getInstance(Unknown Source)
    [java] at com.sun.xml.wss.filter.ExportEncryptedKeyFilter.process(ExportEncryptedKeyFilter.java:186)
    [java] at com.sun.xml.wss.SecureCorrespondent.filterMessage(SecureCorrespondent.java:30)
    [java] at com.sun.xml.wss.SecureCorrespondent.filterMessageInContext(SecureCorrespondent.java:42)
    [java] at com.sun.xml.wss.SecurityAnnotator.annotateHeader(SecurityAnnotator.java:36)
    [java] at com.sun.xml.rpc.security.SecurityPluginUtil._preRequestSendingHook(SecurityPluginUtil.java:145)
    [java] at simple.PingPort_Stub._preRequestSendingHook(PingPort_Stub.java:197)
    [java] at com.sun.xml.rpc.client.StreamingSender._send(StreamingSender.java:87)
    [java] at simple.PingPort_Stub.ping(PingPort_Stub.java:80)
    [java] at simple.TestClient.main(TestClient.java:37)
    [java] Exception in thread "main"
    [java] Java Result: 1

    I tried to use Sun One Application Server as the container and still got the same exception.
    [java] java.lang.NullPointerException
    [java] at com.sun.org.apache.xml.security.encryption.XMLCipher.getInstance(Unknown Source)
    Seems that I got a AccessControl problem but I can't tell why.
    The server.log print out the exception as follows:
    ======================================================
    [#|2004-07-26T11:59:51.684+0800|���i|sun-appserver-pe8.0.0_01|javax.enterprise.system.stream.err|_ThreadID=10;|java.security.AccessControlException: access denied (javax.security.auth.AuthPermission modifyPrincipals)
         at java.security.AccessControlContext.checkPermission(AccessControlContext.java:269)
         at java.security.AccessController.checkPermission(AccessController.java:401)
         at java.lang.SecurityManager.checkPermission(SecurityManager.java:524)
         at javax.security.auth.Subject$SecureSet.add(Subject.java:1055)
         at com.sun.xml.wss.impl.DefaultSecurityEnvironmentImpl.initializeSubject(DefaultSecurityEnvironmentImpl.java:660)
         at com.sun.xml.wss.impl.DefaultSecurityEnvironmentImpl.<init>(DefaultSecurityEnvironmentImpl.java:208)
         at com.sun.xml.wss.impl.DefaultSecurityEnvironmentImpl.<init>(DefaultSecurityEnvironmentImpl.java:228)
         at com.sun.xml.wss.impl.ContainerSecurityEnvironment.<init>(ContainerSecurityEnvironment.java:115)
         at com.sun.xml.wss.impl.SJSASSecurityEnvironment.<init>(SJSASSecurityEnvironment.java:25)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
         at java.lang.Class.newInstance0(Class.java:308)
         at java.lang.Class.newInstance(Class.java:261)
         at com.sun.xml.wss.impl.SecurityEnvironmentFactory.createEnvironment(SecurityEnvironmentFactory.java:45)
         at com.sun.xml.rpc.security.SecurityPluginUtil.setSecurityEnvironment(SecurityPluginUtil.java:208)
         at com.sun.xml.rpc.security.SecurityPluginUtil.<init>(SecurityPluginUtil.java:74)
         at simple.PingPort_Tie.<clinit>(PingPort_Tie.java:36)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:219)
         at com.sun.xml.rpc.server.http.JAXRPCRuntimeInfoParser.loadClass(JAXRPCRuntimeInfoParser.java:189)
         at com.sun.xml.rpc.server.http.JAXRPCRuntimeInfoParser.parseEndpoints(JAXRPCRuntimeInfoParser.java:73)
         at com.sun.xml.rpc.server.http.JAXRPCRuntimeInfoParser.parse(JAXRPCRuntimeInfoParser.java:39)
         at com.sun.xml.rpc.server.http.JAXRPCContextListener.contextInitialized(JAXRPCContextListener.java:73)
         at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3659)
         at org.apache.catalina.core.StandardContext.start(StandardContext.java:4120)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1089)
         at org.apache.catalina.core.StandardHost.start(StandardHost.java:760)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1089)
         at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:467)
         at org.apache.catalina.startup.Embedded.start(Embedded.java:986)
         at com.sun.enterprise.web.WebContainer.start(WebContainer.java:490)
         at com.sun.enterprise.web.PEWebContainer.startInstance(PEWebContainer.java:506)
         at com.sun.enterprise.web.PEWebContainerLifecycle.onStartup(PEWebContainerLifecycle.java:54)
         at com.sun.enterprise.server.ApplicationServer.onStartup(ApplicationServer.java:295)
         at com.sun.enterprise.server.PEMain.run(PEMain.java:220)
         at com.sun.enterprise.server.PEMain.main(PEMain.java:172)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at org.apache.commons.launcher.ChildMain.run(ChildMain.java:269)
    |#]
    [#|2004-07-26T11:59:51.684+0800|�Y����|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=10;|WebModule[/securesimple]Exception sending context initialized event to listener instance of class com.sun.xml.rpc.server.http.JAXRPCContextListener
    java.lang.ExceptionInInitializerError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:219)
         at com.sun.xml.rpc.server.http.JAXRPCRuntimeInfoParser.loadClass(JAXRPCRuntimeInfoParser.java:189)
         at com.sun.xml.rpc.server.http.JAXRPCRuntimeInfoParser.parseEndpoints(JAXRPCRuntimeInfoParser.java:73)
         at com.sun.xml.rpc.server.http.JAXRPCRuntimeInfoParser.parse(JAXRPCRuntimeInfoParser.java:39)
         at com.sun.xml.rpc.server.http.JAXRPCContextListener.contextInitialized(JAXRPCContextListener.java:73)
         at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3659)
         at org.apache.catalina.core.StandardContext.start(StandardContext.java:4120)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1089)
         at org.apache.catalina.core.StandardHost.start(StandardHost.java:760)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1089)
         at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:467)
         at org.apache.catalina.startup.Embedded.start(Embedded.java:986)
         at com.sun.enterprise.web.WebContainer.start(WebContainer.java:490)
         at com.sun.enterprise.web.PEWebContainer.startInstance(PEWebContainer.java:506)
         at com.sun.enterprise.web.PEWebContainerLifecycle.onStartup(PEWebContainerLifecycle.java:54)
         at com.sun.enterprise.server.ApplicationServer.onStartup(ApplicationServer.java:295)
         at com.sun.enterprise.server.PEMain.run(PEMain.java:220)
         at com.sun.enterprise.server.PEMain.main(PEMain.java:172)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at org.apache.commons.launcher.ChildMain.run(ChildMain.java:269)
    Caused by: java.lang.RuntimeException: java.security.AccessControlException: access denied (javax.security.auth.AuthPermission modifyPrincipals)
         at simple.PingPort_Tie.<clinit>(PingPort_Tie.java:39)
         ... 24 more
    Caused by: java.security.AccessControlException: access denied (javax.security.auth.AuthPermission modifyPrincipals)
         at java.security.AccessControlContext.checkPermission(AccessControlContext.java:269)
         at java.security.AccessController.checkPermission(AccessController.java:401)
         at java.lang.SecurityManager.checkPermission(SecurityManager.java:524)
         at javax.security.auth.Subject$SecureSet.add(Subject.java:1055)
         at com.sun.xml.wss.impl.DefaultSecurityEnvironmentImpl.initializeSubject(DefaultSecurityEnvironmentImpl.java:660)
         at com.sun.xml.wss.impl.DefaultSecurityEnvironmentImpl.<init>(DefaultSecurityEnvironmentImpl.java:208)
         at com.sun.xml.wss.impl.DefaultSecurityEnvironmentImpl.<init>(DefaultSecurityEnvironmentImpl.java:228)
         at com.sun.xml.wss.impl.ContainerSecurityEnvironment.<init>(ContainerSecurityEnvironment.java:115)
         at com.sun.xml.wss.impl.SJSASSecurityEnvironment.<init>(SJSASSecurityEnvironment.java:25)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
         at java.lang.Class.newInstance0(Class.java:308)
         at java.lang.Class.newInstance(Class.java:261)
         at com.sun.xml.wss.impl.SecurityEnvironmentFactory.createEnvironment(SecurityEnvironmentFactory.java:45)
         at com.sun.xml.rpc.security.SecurityPluginUtil.setSecurityEnvironment(SecurityPluginUtil.java:208)
         at com.sun.xml.rpc.security.SecurityPluginUtil.<init>(SecurityPluginUtil.java:74)
         at simple.PingPort_Tie.<clinit>(PingPort_Tie.java:36)
         ... 24 more

  • Oracle JCE problem

    Hi,
    I am recently trying to enable SSL support for OAS which I sucessfully managed. As a next step I wanted to get mutual authentication up and running. Which also I got setup. After this my issues started to popup.
    I used the oracle wallet manager to create self signed certificates to use in the setup. Java's JCE I found is no good with PKCS12 that oracle wallet manager uses. So I went for an alternative from Bouncy Castle (BC). It works fine but only for a wierd case which is completely wrong. What goes wrong with BC is that is does not find the truststore in the client wallet (although it is there). But if as a truststore I give the path to the server's wallet which contains the server's certificate, everything works fine. Any idea what could be causing this. I just figured it must be some other format of the pKCS12 certificate the Oracle wallet manager generates and the BC JCE is reading.
    Then I found out at java forums someone saying that phaos was excellent for PKCS12 certificates. Going there I found out its oracle's sdk now and seeing that I though using oracle's JCE will solve all my incompatability problem. Anyways turns out the Oracle JCE uses the JCE 1.2.1 framework which works with the JDK 1.2 uptil 1.3. Any when I use it with the my JDK 5.0, I get a Stackoverflow exception. I need to use jdk 5 and I need a solution for https. Any suggestions of how should I proceed.
    Regards,
    Ahsan

    Hi,
    Using eclipse I changed the jre environment to 1.2 and 1.3 to see if that was really the problem. But I still get the stack overflow exception. I paste a portion of this exception as below and if anyone is interested I can post the complete stack trace as well :
    Exception in thread "main" java.lang.StackOverflowError
    at sun.reflect.GeneratedConstructorAccessor2.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
    at java.lang.Class.newInstance0(Class.java:350)
    at java.lang.Class.newInstance(Class.java:303)
    at java.security.Provider$Service.newInstance(Provider.java:1130)
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:220)
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:147)
    at java.security.SecureRandom.getInstance(SecureRandom.java:251)
    at java.security.SecureRandom.getDefaultPRNG(SecureRandom.java:187)
    at java.security.SecureRandom.<init>(SecureRandom.java:150)
    at com.phaos.crypto.SREntropySource.<init>(SREntropySource)
    at com.phaos.crypto.EntropySource.getDefault(EntropySource)
    at com.phaos.jce.provider.PhaosSecureRandomSpi.<init>(Unknown Source)
    at com.phaos.jce.provider.MD5SecureRandomSpi.<init>(Unknown Source)
    at sun.reflect.GeneratedConstructorAccessor2.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Class.java:303)
    at java.security.Provider$Service.newInstance(Provider.java:1130)
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:220)
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:147)
    at java.security.SecureRandom.getInstance(SecureRandom.java:251)
    at java.security.SecureRandom.getDefaultPRNG(SecureRandom.java:187)
    at java.security.SecureRandom.<init>(SecureRandom.java:150)
    at com.phaos.crypto.SREntropySource.<init>(SREntropySource)
    at com.phaos.crypto.EntropySource.getDefault(EntropySource)
    at com.phaos.jce.provider.PhaosSecureRandomSpi.<init>(Unknown Source)
    at com.phaos.jce.provider.MD5SecureRandomSpi.<init>(Unknown Source)
    at sun.reflect.GeneratedConstructorAccessor2.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
    at java.lang.Class.newInstance0(Class.java:350)
    Any ideas what I am doing wrong.
    Regards,
    Ahsan.
    Message was edited by:
    user539705

  • Adobe Dreamweaver CS5.5 - Windows 7 - Java Script Problem

    I am having trouble with Anchor.htm.
    When I try to insert an anchor in the text (Insert > Named Anchor> I get this error message:
    "While executing insertObject in Anchor.htm a Java Script error occurred."
    I recently downloaded both the 32- and 64-bit Java Script applications when I received a message that the existing version of Java Script was out-of-date. Anchor.htm worked before I installed the update.
    The files I downloaded and installed are:
    jre-7u9-windows-i586.exe
    jre-7u9-windows-x64.exe
    Please can anyone help me with this problem?

    From Dreamweaver FAQ
    http://forums.adobe.com/thread/429114
    "If Dreamweaver is acting erratically, or if you see a message saying "the following JavaScript error(s) occurred",  it's usually a sign of a corrupt cache file. The first thing to try should always be to delete the file cache. If that doesn't work, delete your personal Configuration folder. Full instructions are in Deleting a corrupted cache file.
    http://forums.adobe.com/thread/494811"
    Nancy O.

  • Java application problem

    I am using JDK1.4 and working on Windows Xp.
    I have written a code for application in java as follows:
    import javax.swing.*;
    public class sample
    JPanel panel;
    static JFrame frame;
    JButton but;
    public sample()
    frame=new JFrame("frame");
    panel=new JPanel();
    frame.getContentPane().add(panel);
    but=new JButton("click");
    panel.add(but);
    public static void main(String args[])
    sample s=new sample();
    frame.setSize(300,300);
    frame.setVisible(true);
    on executing program application window has appeared and it ran properly.
    Then I closed that application window.But after that in command prompt window curser was just blinking and it was not allow to enter also.
    I have tried pressing CTRL+C also.But situation in command prompt was same i.e curser in command prompt was just blinking.
    Then I closed cmd window ;but one error has occured saying that cmd window can not close .
    My friend has told me that she is also having windows xp and JDK1.4 ; ctrl+c is working properly in her command prompt.She has written the above same code in her computer and it executes properly.
    Even though she has not written following statement:
    "frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);"
    when she exits from application window ,her cmd window gave same problem of only blinking curser.But when she press CTRL+C ; her command prompt starts responding by giving root.But my command prompt is not giving
    positive responce to "ctrl+c" when I am exiting java application.
    Is it possible to solve this problem without giving statement
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ?
    Why my command prompt is not responding to CTRL+c?
    How can I tackle this problem ?
    Is there any other key which can be used in command prompt of Windows Xp?

    Is it possible to solve this problem without giving
    statement
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ?this is because Swing have started some non-daemon helper threads for its internal purposes and the default close operation for frame is just HIDE_ON_CLOSE. So, the system will not exit because those non-daemon thread still not terminated.
    What is the problems setting the default close operation to JFrame.EXIT_ON_CLOSE ?

  • Java threading problem... threads only work on 1 processor

    I've got a iterative deepening problem that i have to parallelize. As far as i know i did everything correctly however everything seems to be running on 1 processor instead of 2 processors. As far as i know i am using threads (-Xprof either defines them as thread-1 thread-2 or pool1-thread1,depending on the method used for issueing)
    the worker thread is:
    public int solutionsT(Board board, int currentDepth) {
            int temp = 0;
            int result = 0;
            if (board.distance() == 0) {
               return 1;
            if (board.distance() > board.bound()) {
                return 0;
            Board[] children = board.makeMoves();
            result = 0;
            for (int i = 0; i < children.length; i++) {
                if (children[i] != null) {
                    temp = solutionsT(children, currentDepth + 1);
    if(temp != 0){
    result += temp;
    return result;
    public void run() {
    int temp =0;
    int i = 0;
    while(true){
    while(bag.size() !=0){
    bag.putSolution(solutionsT(bag.get(),1));
    try{   
    barrier.await();
    }catch(Exception e){}
    it get's it's input from a bag that is filled before the iteration begins. (once the bag is filled it trips a barrier) this worker thread is a implementation of Runnable
    This piece of code is used to make the thread object and to issue it
    public SolutionThread(int numberOfThreads) {
       thread = numberOfThreads;
       bag = new bagOfBoards();
       barrier = new CyclicBarrier(thread+1);
       if(thread > 1){
          ExecutorService threadExecutor = Executors.newFixedThreadPool( thread );
          solution = new ThreadTest[thread];
          bag = new bagOfBoards();
          for(int i = 0;i<thread;i++){
             solution[i] = new ThreadTest(bag, lock, barrier, i);
             threadExecutor.execute(solution);
    finally this is the code which is used to acces the bag and get a board.
    synchronized public Board get() {
                if (size > 0) {
                size--;
                Board result = bag[size];
                return result;
            } else {
             return null;
        }since this method is synchronized and it always returns something (either null or a board) and the worker tests for this. there is no race condition here.
    furter more. the main thread is a loop. It fills te bags with an intial state. then it trips the barrier and waits for the workers to do the work. the workers then process the bag until it hits zero and then trip the barrier so that the main thread can do the next iteration (and fill the bag)
    p.s. i know the code is a bit messy, but i want to get the threading to work. As of now i relaly don't understand why the threads are just running on 1 processor instead of 2 processors. not only that. the excecution time is nearly the same as that of a sequential equivalent.
    p.s.2 the code is parallisable. and it is run on a smp system.
    Message was edited by:
    jstrike

    i'm very sure that the jvm and os support smp. the
    problem really should be in the code.I don't see how this can be the case. There's nothing in the Java language that deals with how threads are assigned to processors (at least not as far as I know) so there isn't anything you can do in your code to affect that.
    Or did you meant that i have to tell the jvm in the class that
    there is support for multiple processorsThat would be the only possibility. I have no idea whether it can be done or not, though.

  • Java Threads Problem

    Hi, I am trying to write a simple java threads program where in one thread reads a file and another thread writes the data into a second file....
    Here is my code, although i think i am correct, my program still runs in a sequential fashion help help help!!!
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    class MyThread extends Thread{
    private int a;
    private int c;
    FileInputStream in;
    FileOutputStream out;
    public MyThread(int a){
    this.a = a;
    public void run(){
    if(this.a==5)
         try {
         in = new FileInputStream("Britney.txt");
    } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    try {
         while((c=in.read())!=-1)
              a = (char) c;
              System.out.println(a);
    catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    if(this.a==10)
         try {
              out = new FileOutputStream("romi.txt");
         } catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
         for(int i = 0;i<50;i++)
              try {
                   System.out.println(c);
                   out.write(c);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    class MainMyThread{
    public static void main(String args[]){
    MyThread thr1, thr2;
    thr1 = new MyThread(5);
    thr2 = new MyThread(10);
    thr1.start();
    thr2.start();
    }

    Encephalopathic wrote:
    malcolmmc wrote:
    ... Chances of getting any kind of reply except "me too" can be pretty remote. ....there's actually a better chance of getting a reply on a general forum like this one, ....Can't you just post in both the narrow and the general forum, but include links one to the other in each thread? Or is that against the forum rules/etiquette? Most people here are ok with a crosspost IF those links are included.
    I would also ask that the OP designate one of those threads as the real discussion thread and just direct folks there from the other threads, so that we have one coherent discussion. If he does that, there's no problem with trying to reach out to as broad an audience as possible.
    I would figure that if the poster were upfront about what they are doing, folks wouldn't mind, but I could be wrong.I think that's generally the case. As long as the discussion is confined to one thread (and pointed there from the crossposts) or at the very least all the participants can see all the discussions, I think most people don't have a problem with it. It's when we waste our time answering when he's already got the answer elsewhere that's annoying.

  • SAP NetWeaver 04s SP9 for JAVA Installation problem on Windows Vista

    Hi Guys,
    Firstly, anyone installed WAS on Windows Vista home version?
      I have gone thru couple of postings in the SDN and disabled firewall but no use.
    here is link :   Port 21212 error : Couldn't install 2004s
      When I am trying to install, getting below problem.
    Error log
    <b>SAPinst is not available on localhost:21200
    Connection to SAPinstAdapter could not be established, see following messages.
    Could not connect to host localhost on port 21200
    Java.net.ConnectionException : Connection refused: connect</b>
    Thanks in advance for your quick reply....
    Prs.

    Hi Anand & Mahesh,
      Thanks for the quick reply.
    Any one of you got a chance to install NW04S 2007 or New York on Windows Vista?
    I think suggested one not available in SDN I guess.
      If I am not wrong, I can get it from Service.sap.com....
    Can you give me the complete path in the service.sap.com if you know....
    If this would not click, alternatively I am planning to change my operating system to Windows XP, this is not a good idea but I dont have option.
    Thanks in advance for quick reply.
    Regards
    Prs

  • Java installation problem on solaris

    Hi
    IAm a new born baby to solaris .I have installed
    java on solaris sparc machine 2.7 by using Solaris_JDK_1.2.2_sparc.bin.
    If i have done anything wrong ,Please correct me .My problem is :
    i have to include the rt.jar file in the classpath bcoz it contains all
    the class files .Then iam running command javac Test.java .Then i got error
    message as segmentation violation error and abort core dumped .I dont why i got this error .Please help me as soon possible .My email id is
    [email protected] .
    Thanks in advance
    bala

    The Solaris*.bin file should have unpacked everything and installed all the JDK in a directory off of the directory where you ran the .bin file. Inside this subdirectory will be a bin subdirectory where the java executables, etc are installed.

Maybe you are looking for