Problems with jumping ball in Java applet

The ball is supposed to jump to the same height from which it fell down, someway it always gets higher and higher. My question is why?
import java.applet.*;
import java.awt.*;
public class Bug extends Applet implements Runnable
   private int y_pos = 200;
   private int y_speed = 0;
   private int radius = 20;
   private int appletSize_x = 400;
   private int appletSize_y = 400;
   private Image dbImage;
   private Graphics dbg;
   public void run(){
       while(true){
           y_speed++;
           if ((y_pos > appletSize_y)&& (y_speed > 0))
                y_speed = (-1)*(y_speed);
           y_pos += y_speed; 
           repaint();
           //controls the time
           try{
               Thread.sleep(20);
          catch (InterruptedException ex){}
    public void update (Graphics g){
        if (dbImage == null)
            dbImage = createImage (this.getSize().width, this.getSize().height);
            dbg = dbImage.getGraphics ();
        dbg.setColor (getBackground ());
        dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);//erase this line to understand better
        dbg.setColor(getForeground());
        paint(dbg);
        g.drawImage (dbImage, 0, 0, this);
    public void stop(){}
    public void destroy(){}
    public void start(){
        Thread th = new Thread(this);
        th.start();
    public void paint(Graphics g){
     g.setColor(Color.green);
     g.fillOval (30 - radius, y_pos - radius, 2 * radius, 2 * radius);
}

Shurik007.5 wrote:
The ball is supposed to jump to the same height from which it fell down, someway it always gets higher and higher. My question is why?
g.fillOval (30 - radius, y_pos - radius, 2 * radius, 2 * radius);There are variables here involved in what gets drawn, no? And do (some of) these variables change during the lifetime? Yes. So, there should be no question about why the display changes.
Edit: I guess your question is more about "why doesn't y_pos keep cycling back and forth between the same two values?" I'd suggest you do some debugging, to make the computer tell you what the values are at each step until you understand what is going on. The simple answer is "It did what you told (programmed) it to do", of course.

Similar Messages

  • Having problem with spinning ball using final cut pro x with new macbook pro with retina screen

    Having problem with spinning ball using final cut pro x with new macbook pro with retina screen

    Update the software. There is no reason to run a two year old version.
    Russ

  • Problem with compilation of HelloWorld.java

    hi,
    getting problem with compilation of HelloWorld.java
    CLASSPATH--- C:\java
    PATH--- C:\j2sdk1.4.2_04\bin
    HelloWorld.java source code in: C:\java
    On cmd prompt:
    C:\java>javac HelloWorld.java
    error: cannot read: HelloWorld.java
    1 error
    pls help me with this
    rgds,
    sanlearns

    What does this command yield?
    dir HelloWorld.java

  • Problem with jump query

    Hello ,
       iam having problem with jump query when i execute the web report but the same jump query is working fine in Bex analyzer.i think there are some settings need to be done in SAP WAS for web report. if it so can anybody tell me how to maintain these settings so that i can execute the my web report.
    Regards
    Komal

    Hi Komal,
    What is the problem you are facing while executing the report.
    Are you working on WAD? Explain clearly about your problem you are facing.
    Regards,
    KK.

  • Problem with display of images in applets

    Hi all,
    When I run this program, the appletviewer window is showing no output (i.e. no image). I'm using the netbeans IDE 5.0.
    Blue hills.jpg is present in both the src folder and build folder.
    * <applet code="image" width =800 height=600>
    * <param name="img" value="Blue hills.jpg">
    * <\applet>
    import java.awt.*;
    import java.applet.*;
    public class image extends Applet {
    Image img;
    public void init() {
    img=getImage(getDocumentBase(), getParameter("img"));
    public void paint(Graphics g){
    g.drawImage(img,0,0,this);
    Please help in figuring out the problem....

    It will be looking for it in the folder with the HTML that invokes the applet.
    If you want to pack the image in with the applet then use getResource instead.
    And spaces in the name are probably not the best idea.

  • Help with creating an animated java applet...

    Hello, everyone! I'm working on a homework assignment for my Intro to Java class, and I'm having a problem I've never run into before. My assignment is to create a animated Java applet which displays an image of an alien spaceship which travels in diagonal lines across the applet area. My main problem is that when I try to compile my code, I get three "cannot find symbol" errors about my variable "alien." I can't figure out why declaring it as a class variable hasn't solved my problem. The errors pop up for the repaint() method, as well as the pane.add and the paintIcon. Here's my code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.Timer;
    class DrawAlien extends JPanel
    public class Alien extends JApplet implements ActionListener
      ImageIcon alien;
      public void init()
        Container pane = getContentPane();
        alien = new ImageIcon(getClass().getResource("alien.gif"));
        pane.setBackground(Color.black);
        pane.add(alien);
        Timer timer = new Timer(30, this);
        timer.start();
      public void actionPerformed(ActionEvent e)
        alien.repaint();
    }I've only posted the section which I think is relevant to my problem, but I can post the rest if anyone thinks it's necessary.
    I'm aware that the code isn't ready yet in several other ways, but I don't think I can move on until I figure out what's up with the "alien" variable. I don't need anyone to write code for me or anything like that, I just lack perspective here. A couple hints in the right direction would be invaluable. Thanks!
    Edited by: springer on Nov 25, 2007 10:46 PM

    You can?t add ImageIcon into pane, you can do like below.
    alien = new ImageIcon(getClass().getResource("alien.gif"));
        pane.setBackground(Color.black);
        JLabel label = new JLabel(alien);
        pane.add(label);

  • Problem with Logger setLevel() method in applet

    I am executing the following line of code in an applet:
    Logger.getLogger("Debug.log").setLevel(Level.ALL);
    I receive an AccessControlException, with e.getPermission()="java.util.logging.LoggingPermission control"
    When I do this in the policy file (following the manual, and the above direction):
    grant codeBase "file://C:/Documents and Settings/All Users/Documents/XMLEHT-Develop"
    permission java.util.logging.LoggingPermission control;
    I get this:
    java.security.policy: error parsing file:/C:/Documents%20and%20Settings/John/.java.policy:
         line 3: expected [;], found [control]
    When I do this in the policy file (incorrect, but following the above error message):
    grant codeBase "file://C:/Documents and Settings/All Users/Documents/XMLEHT-Develop"
    permission java.util.logging.LoggingPermission ;
    I get this:
    java.security.policy: error adding Permission, java.util.logging.LoggingPermission:
         java.lang.NullPointerException: name can't be null
    This problem occurs with JRE 1.5.0_14 installed. I also attempted re-installing Java, to no avail.
    Thanks in advance for any help you may provide.
    Edited by: John L. on Oct 26, 2012 12:33 PM

    As all are aware Java Applets run on the client and except in a corporate environment it is difficult to edit the policy file. Added to this is the problem caused by explicitly defining where the log file is to be written since even if only targetting at Windows the "Documents and Settings" may not be on the "C" drive and on Windows 7 "Documents and Settings" is not used.
    Since modifications to the policy file are not specific to a particular Applet they can be a security nightmare. When working with Applets it is normally best sign the Applet and then to only use a users home directory (System.getProperty("user.home")) or the temp directory (System.getProperty("java.io.tmpdir")) since these are pretty much guaranteed to be available.
    I'm not overly keen on Logging especially in Applets. To my mind Logging is primarily creating an audit trail (especially when things go wrong) and if the log file is on the client how is the Applet writer going to access the log file?

  • Problem in display file in java applet embeded browser

    hi, i am facing problem to display the file from local drive in java applet embeded browser. here is the error message i get:
    Exception loading file from path:java.security.AccessControlException: access denied (java.util.PropertyPermission user.dir read)
    i think it should be the java security problem and i have try to get the solution from internet. i try to solve by using the fllowing method:
    keytool -genkey -keyalg rsa -alias yourkey
    keytool -export -alias yourkey -file yourcert.crt
    javac yourapplet.java
    jar cvf yourapplet.jar yourapplet.class
    jarsigner yourapplet.jar yourkey
    but the command prompt ask me to enter the keystore password. i try to enter any password. but i show me the error:
    keytool error: java.io.IOException: Keystore was tampered with, or password was incorrect.
    So may i know what is the problem actually?Thanks a lot.

    Hi,
    here is the sample coding :
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import com.sun.j3d.utils.geometry.ColorCube;
    import com.sun.j3d.utils.applet.MainFrame;
    import com.sun.j3d.utils.universe.*;
    import com.sun.j3d.utils.behaviors.mouse.MouseRotate;
    import com.sun.j3d.utils.behaviors.mouse.MouseZoom;
    import com.sun.j3d.utils.behaviors.mouse.MouseTranslate;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    import org.web3d.j3d.loaders.VRML97Loader;
    import com.sun.j3d.loaders.Scene;
    public class SimpleVrml extends Applet implements ActionListener {
    String           location;
    String           initLocation;
    Canvas3D     canvas;
    SimpleUniverse     universe;
    TransformGroup     vpTransGroup;
    VRML97Loader     loader;
    View          view;
    Panel          panel;
    Label          label;
    BranchGroup     sceneRoot;
    TransformGroup     examineGroup;
    BranchGroup     sceneGroup;
    BoundingSphere     sceneBounds;
    DirectionalLight     headLight;
    AmbientLight     ambLight;
    TextField      textField;
    Cursor          waitCursor;
    Cursor          handCursor;
    public SimpleVrml() {
    initLocation="cylinder.wrl";     
         setLayout(new BorderLayout());
         GraphicsConfiguration config =SimpleUniverse.getPreferredConfiguration();     
         setLayout(new BorderLayout());
         canvas = new Canvas3D(config);
         add("Center",canvas);
         panel = new Panel();
         panel.setLayout(new FlowLayout(FlowLayout.LEFT));
         textField = new TextField(initLocation,60);     
         textField.addActionListener(this);
         label = new Label("Location:");
         panel.add(label);
         panel.add(textField);
         add("North",panel);
         waitCursor = new Cursor(Cursor.WAIT_CURSOR);
         handCursor = new Cursor(Cursor.HAND_CURSOR);
         universe = new SimpleUniverse(canvas);
         ViewingPlatform viewingPlatform = universe.getViewingPlatform();
         vpTransGroup = viewingPlatform.getViewPlatformTransform();
         Viewer viewer = universe.getViewer();
         view = viewer.getView();
         setupBehavior();
         loader = new VRML97Loader();
         gotoLocation(initLocation);
    public void actionPerformed(ActionEvent ae) {
         gotoLocation(textField.getText());
    void gotoLocation(String location) {
         canvas.setCursor(waitCursor);
         if (sceneGroup != null) {
         sceneGroup.detach();
         Scene scene = null;
         try {
         URL loadUrl = new URL(location);
         try {
              // load the scene
              scene = loader.load(new URL(location));
         } catch (Exception e) {
              System.out.println("Exception loading URL:" + e);
         } catch (MalformedURLException badUrl) {
         // location may be a path name     
         try {
              // load the scene
              scene = loader.load(location);
         } catch (Exception e) {
              System.out.println("Exception loading file from path:" + e);
         if (scene != null) {
         // get the scene group
         sceneGroup = scene.getSceneGroup();
         sceneGroup.setCapability(BranchGroup.ALLOW_DETACH);
         sceneGroup.setCapability(BranchGroup.ALLOW_BOUNDS_READ);
         // add the scene group to the scene
         examineGroup.addChild(sceneGroup);
         // now that the scene group is "live" we can inquire the bounds
         sceneBounds = (BoundingSphere)sceneGroup.getBounds();
         // set up a viewpoint to include the bounds
         setViewpoint();
         canvas.setCursor(handCursor);
    void setViewpoint() {
         Transform3D viewTrans = new Transform3D();
         Transform3D eyeTrans = new Transform3D();
         // point the view at the center of the object
         Point3d center = new Point3d();
         sceneBounds.getCenter(center);
         double radius = sceneBounds.getRadius();
         Vector3d temp = new Vector3d(center);
         viewTrans.set(temp);
         // pull the eye back far enough to see the whole object
         double eyeDist = 1.4*radius / Math.tan(view.getFieldOfView() / 2.0);
         temp.x = 0.0;
         temp.y = 0.0;
         temp.z = eyeDist;
         eyeTrans.set(temp);
         viewTrans.mul(eyeTrans);
         // set the view transform
         vpTransGroup.setTransform(viewTrans);
    private void setupBehavior() {
         sceneRoot = new BranchGroup();
         examineGroup = new TransformGroup();
         examineGroup.setCapability(TransformGroup.ALLOW_CHILDREN_EXTEND);
         examineGroup.setCapability(TransformGroup.ALLOW_CHILDREN_READ);
         examineGroup.setCapability(TransformGroup.ALLOW_CHILDREN_WRITE);
         examineGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
         examineGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
         sceneRoot.addChild(examineGroup);
         BoundingSphere behaviorBounds = new BoundingSphere(new Point3d(),
              Double.MAX_VALUE);
         MouseRotate mr = new MouseRotate();
         mr.setTransformGroup(examineGroup);
         mr.setSchedulingBounds(behaviorBounds);
         sceneRoot.addChild(mr);
         MouseTranslate mt = new MouseTranslate();
         mt.setTransformGroup(examineGroup);
         mt.setSchedulingBounds(behaviorBounds);
         sceneRoot.addChild(mt);
         MouseZoom mz = new MouseZoom();
         mz.setTransformGroup(examineGroup);
         mz.setSchedulingBounds(behaviorBounds);
         sceneRoot.addChild(mz);
         BoundingSphere lightBounds =
         new BoundingSphere(new Point3d(), Double.MAX_VALUE);
    ambLight = new AmbientLight(true, new Color3f(1.0f, 1.0f, 1.0f));
    ambLight.setInfluencingBounds(lightBounds);
    ambLight.setCapability(Light.ALLOW_STATE_WRITE);
    sceneRoot.addChild(ambLight);
    headLight = new DirectionalLight();
    headLight.setCapability(Light.ALLOW_STATE_WRITE);
    headLight.setInfluencingBounds(lightBounds);
    sceneRoot.addChild(headLight);
         universe.addBranchGraph(sceneRoot);
    public static void main(String[] args) {
    new MainFrame(new SimpleVrml(), 780, 780);
    cylinder.wrl :
    #VRML V2.0 utf8
    # A cylinder
    Shape {
    appearance Appearance {
    material Material { }
    geometry Cylinder {
    height 2.0
    radius 1.5
    view.html:
    <html>
    <applet code="SimpleVrml.class" width=600 height=600>
    </applet>
    </html>
    error msg that i get :
    Exception loading file from path:java.security.AccessControlException: access denied (java.util.PropertyPermission user.dir read)
    i can display the wrl file in applet itself but i can't display in the browser.is it any problem with my code?Urgent, please help me. Thanks.

  • Some problem with bouncing balls animation

    can some body tell how would i move the balls and also detect when a ball is bouncing with other ball or wall in my applet or stand alone application.my program is supposed to generate atleast 2 balls and start moving around .they should reverse their direction,when they get bounced with other balls or walls.

    Hmmm....
    It's really as easy as you've made it - except that when you have intensive graphics calls you should Thread it and try to use a timer to smooth the animation.
    Basically you should :
    paint the balls
    then move them.
    if they're touching/outside the bounds or touching each other reverse their direction but make sure they're within the limits before you repaint
    You should checkout http://www.javagaming.org
    There's alot of code samples and questions related to this kind of thing.
    If you're still in trouble mail me at [email protected] and I'll send you code for a single ball simply bouncing around

  • Problem with n 79 instal java software

    hi
    i have one problem with my nokia n 79
    when i install a java software or game my device ask me where do u wana install? in memory card or memory phone.its natural.but if i select memory card when the installation finished autorun to start the program and software is disable and when i go to the application list are no icon of that progran to run.but in installation list there is it.so there is any icon andany way to run it.
    its just abouy java program and install to memroy card
    i dont have any problem with symbian in 2 memory and  java when i install it in memory phone
    please help me
    thanks

    dear alzaeem i ran java in before this time when i installed it in memory card
    i dont know whay u say it doesnt run in memory card
    before this i installed every application of java and symbian in memory card with out any problem and after installation icon of them were in application list
    when i install java in memry card i dont have problem with installation and its complete installation and there is the name of that software java in installation list but my problem is that there is any icon of software in application list or every where to start or run it.

  • Problem with XMLEncoder for complex java object i

    Hi All.
    My problem with XMLEncoder is it doesnt transfrom java objects without default no arguement constructor. I was able to resolve this in my main java object class, by setting a new persistence delegate, but for other classes that are contained in the main class, they are not being encoded.
    Thanks in advance for your answers

    Better to put this in java forum :-)
    Just check, if this helps.
    http://forum.java.sun.com/thread.jspa?threadID=379614&messageID=1623434

  • In case of problems with SAP GUI for Java  ...

    Hello all,
    in case of having problems (errors, ABAP dumps etc.) with SAP GUI for Java, please create an OSS message on component BC-FES-JAV with information described in OSS note 326558
    http://www.service.sap.com/~form/sapnet?_FRAME=CONTAINER&_OBJECT=011000358700010521522001.
    This makes sure our official support channels get aware of your problem.
    Thanks and best regards
    Rolf-Martin

    Hello Rolf-Martin,
    i don't have access to this website to view the note.
    The version of the Suse libc is:
    GNU C Library stable release version 2.3.2, by Roland McGrath et al.
    Copyright (C) 2003 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.
    There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
    PARTICULAR PURPOSE.
    Compiled by GNU CC version 3.3 20030226 (prerelease) (SuSE Linux).
    Compiled on a Linux 2.4.20 system on 2003-03-13.
    Best Regards,
    Piotr Brostovski

  • Problems with PL/SQL Calling Java Function that returns String []

    Hi,
    I have written the following code. It's not compiling OK.
    DECLARE
    TYPE Tokens_Type IS VARYING ARRAY(20) OF VARCHAR2(20);
    s1 Tokens_Type DEFAULT NULL;
    SQL_STR VARCHAR2(2000) DEFAULT NULL;
    BEGIN
    SQL_STR := 'CREATE OR REPLACE FUNCTION Schema1.SPLIT_STR (S2 VARCHAR2(20)) ' ||
    'RETURN s1 ' ||
    'AS LANGUAGE JAVA ' ||
    'NAME ''String_Mani.split_it (String) return java.lang.String []''';
    EXECUTE IMMEDIATE SQL_STR;
    END;
    What's the problem with this?

    You cannot create a function with a locally defined return type. As soon as this script is executed, Oracle no longer knows what the TOKEN_TYPE type is any more, so the function will be invalid.
    You need to use a collection type defined at the database level or defined in a package - somewhere where it will persist.

  • Problems with importing classes in Java

    Hello,
    i have some problems with a simple project.
    The structure is like this:
    web-inf/classes/databeans/loginexistinguserform.java
    web-inf/classes/formactions/loginexistinguseraction.java
    loginexistinguserform.java :
    package databeans;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionError;
    import org.apache.struts.action.ActionMapping;
    import javax.servlet.http.HttpServletRequest;
    public class LoginExistingUserForm extends ActionForm
         String userid;
         String password;
         public String getUserid(){return userid;}
         public void setUserid(String newUserid){userid=newUserid;}
         public String getPassword(){return password;}
         public void setPassword(String newPassword) {password=newPassword;}
         public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){
              ActionErrors errors=new ActionErrors();
              if(this.userid==null||this.userid.equals(""))
                   errors.add("user",new ActionError("error.userid.required"));
              if(this.password==null||this.password.equals(""))
                   errors.add("pass",new ActionError("error.password.required"));
              return errors;
    }loginexistinguseraction.java
    package formactions;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import databeans.LoginExistingUserForm;
    public class LoginExistingUserAction extends Action
         public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
         throws IOException, ServletException
              LoginExistingUserForm loginData=(LoginExistingUserForm)form;
              if(loginData.getUserid().equals("Admin")&&loginData.getPassword().equals("Parola"))
                   return mapping.findForward("successLogin");
              else
                   return mapping.findForward("failureLogin");
    }I can complie succesfully loginexisitinguserform.java but problems appears when i want to compile the second file, loginexistinguseraction.java with command: javac loginexistinguseraction.java
    C:\ApacheGroup\Tomcat\webapps\PersonalWeb\WEB-INF\classes\formactions>javac loginexistinguseraction.java
    loginexistinguseraction.java:10: package databeans does not exist
    import databeans.LoginExistingUserForm;
    ^
    loginexistinguseraction.java:17: cannot find symbol
    symbol : class LoginExistingUserForm
    location: class formactions.LoginExistingUserAction
    LoginExistingUserForm loginData=(LoginExistingUserForm)form;
    ^
    loginexistinguseraction.java:17: cannot find symbol
    symbol : class LoginExistingUserForm
    location: class formactions.LoginExistingUserAction
    LoginExistingUserForm loginData=(LoginExistingUserForm)form;
    ^
    3 errors
    I have the CLASSPATH variable setup tu C:/Sun/Appserver/lib/j2ee.jar
    Can someone help me ? Thank you in advance !

    Thank you very much ! It worked. I'm really new in Jav a programming.
    Now i have encoutered another problem. When i want to login, and enter user name and password i am redirected to a login.do page, instead of Welcome.jsp
    Here is Login.jsp:
    <%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@page contentType="text/html; charset=ISO-8859-1"%>
    <html>
    <head><title>Login Form</title></head>
    <body>
    <html:errors/>
    <html:form action="/login">
    <table border="0" width="200">
    <tr>
         <td>User Name:</td>
         <td><html:text property="userid" maxlength="13"/></td>
    </tr>
    <tr>
         <td>Password:</td>
         <td><html:password property="password" maxlength="13"/></td>
    </tr>
    </table>
    <br />
    <html:submit value="Login"/>
    </html:form>
    </body>
    </html>and here is struts-config.xml :
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE struts-config PUBLIC
              "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
              "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
    <struts-config>
    <!--========================beans for HTML form data=======================-->
    <form-beans>
         <form-bean name="loginBean" type="databeans.LoginExistingUserForm"/>
    </form-beans>
    <!--========================Action Mappings================================-->
    <action-mappings>
         <action path="/login" type="formactions.LoginExistingUserAction" name="loginBean" input="/Login.jsp" scope="session">
              <forward name="succesLogin" path="/pages/Welcome.jsp" redirect="true"/>
              <forward name="failureLogin" path="/pages/Diverse.jsp" redirect="true"/>
         </action>
    </action-mappings>
        <message-resources parameter="MessageResources" />
    </struts-config>

  • Problems with WLST embedded in java app.

    Hi,
    I have a problem with the WLST embedded in a java app.
    I want to programatically create or reconfigure a domain from a java application. Following is a simple example of what I want to do.
    import weblogic.management.scripting.utils.WLSTInterpreter;
    public class DomainTester {
      static WLSTInterpreter interpreter = new WLSTInterpreter();
      private void processDomain() {
        if(domainExists()) {
          System.out.println("Should now UPDATE the domain");
        } else {
          System.out.println("Should now CREATE the domain");
      private boolean domainExists() {
        try {
          interpreter.exec("readDomain('d:/myDomains/newDomain')");
          return true;
        }catch(Exception e) {
          return false;
    }The output of this should be one of two possibles.
    1. If the domain exists already it should output
    "Should now UPDATE the domain"
    2. If the domain does not exist it should output
    "Should now CREATE the domain"
    However, if the domain does not exist the output is always :
    Error: readDomain() failed. Do dumpStack() to see details.
    Should now UPDATE the domain
    It never returns false from the domainExists() method therefor always states that the exec() worked.
    It seams that the exec() method does not throw ANY exceptions from the WLST commands. The catch clause is never executed and the return value from domainExists() is always true.
    None of the VERY limited number of examples using embedded WLST in java has exception or error handling in so I need to know what is the policy to detect failures in a WLST command executed in java??? i.e. How does my java application know when a command succeeds or not??
    Regards
    Steve

    Hi,
    I did some creative wrapping for the WLSTInterpreter and I now have very good programatic access to the WLST python commands.
    I will put this on dev2dev somewhere and release it into the open source community.
    Don't know the best place to put it yet, so if anybody sees this and has any good ideas please feel free to pass them on.
    Here is the wrapper class. It can be used as a direct replacement for the weblogic WLSTInterpreter. As I can't overload the actual exec() calls because I want to return a String from this call I created an exec1(String command) that will return a String and throw my WLSTException which is a RuntimeException which you can handle if you like.
    It sets up stderr and stdout streams to interpret the results both from the Python interpreter level and at the JVM level where dumpStack() just seem to do a printStackTrace(). It also calls the dumpStack() command should the result contain this in its text. If either an exception is thrown from the lower level interpreter or dumpStack() is in the response I throw my WLSTException containing this information.
    package eu.medsea.WLST;
    import java.io.ByteArrayOutputStream;
    import java.io.PrintStream;
    import weblogic.management.scripting.utils.WLSTInterpreter;
    public class WLSTInterpreterWrapper extends WLSTInterpreter {
         // For interpreter stdErr and stdOut
         private ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
         private ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
         private PrintStream stdErr = new PrintStream(baosErr);
         private PrintStream stdOut = new PrintStream(baosOut);
         // For redirecting JVM stderr/stdout when calling dumpStack()
         static PrintStream errSaveStream = System.err;
         static PrintStream outSaveStream = System.out;
         public WLSTInterpreterWrapper() {
              setErr(stdErr);
              setOut(stdOut);
         // Wrapper function for the WLSTInterpreter.exec()
         // This will throw an Exception if a failure or exception occures in
         // The WLST command or if the response containes the dumpStack() command
         public String exec1(String command) {
              String output = null;
              try {
                   output = exec2(command);
              }catch(Exception e) {
                   try {
                        synchronized(this) {
                             stdErr.flush();
                             baosErr.reset();
                             e.printStackTrace(stdErr);
                             output = baosErr.toString();
                             baosErr.reset();
                   }catch(Exception ex) {
                        output = null;
                   if(output == null) {
                        throw new WLSTException(e);
                   if(!output.contains(" dumpStack() ")) {
                        // A real exception any way
                        throw new WLSTException(output);
              if (output.length() != 0) {
                   if(output.contains(" dumpStack() ")) {
                        // redirect the JVM stderr for the durration of this next call
                        synchronized(this) {
                             System.setErr(stdErr);
                             System.setOut(stdOut);
                             String _return = exec2("dumpStack()");
                             System.setErr(errSaveStream);
                             System.setOut(outSaveStream);
                             throw new WLSTException(_return);
              return stripCRLF(output);
         private String exec2(String command) {
              // Call down to the interpreter exec method
              exec(command);
              String err = baosErr.toString();
              String out = baosOut.toString();
              if(err.length() == 0 && out.length() == 0) {
                   return "";
              baosErr.reset();
              baosOut.reset();
              StringBuffer buf = new StringBuffer("");
              if (err.length() != 0) {
                   buf.append(err);
              if (out.length() != 0) {
                   buf.append(out);
              return buf.toString();
         // Utility to remove the end of line sequences from the result if any.
         // Many of the response are terminated with either \r or \n or both and
         // some responses can contain more than one of them i.e. \n\r\n
         private String stripCRLF(String line) {
              if(line == null || line.length() == 0) {
                   return line;
              int offset = line.length();          
              while(true && offset > 0) {
                   char c = line.charAt(offset-1);
                   // Check other EOL terminators here
                   if(c == '\r' || c == '\n') {
                        offset--;
                   } else {
                        break;
              return line.substring(0, offset);
    }Next here is the WLSTException class
    package eu.medsea.WLST;
    public class WLSTException extends RuntimeException {
         private static final long serialVersionUID = 1102103857178387601L;
         public WLSTException() {
              super();
         public WLSTException(String message) {
              super(message);
         public WLSTException(Throwable t) {
              super(t);
         public WLSTException(String s, Throwable t) {
              super(s, t);
    }And here is the start of a wrapper class for so that you can use the WLST commands directly. I will flesh this out later with proper var arg capabilities as well as create a whole Exception hierarchy that better suites the calls.
    package eu.medsea.WLST;
    // Provides methods for the WLSTInterpreter
    // just to make life a little easier.
    // Also provides access to the more generic exec(...) call
    public class WLSTCommands {
         public void cd(String path) {
              exec("cd('" + path + "')");
         public void edit() {
              exec("edit()");
         public void startEdit() {
              exec("startEdit()");
         public void save() {
              exec("save()");
         public void activate() {
              exec("activate(block='true')");
         public void updateDomain() {
              exec("updateDomain()");
         public String state(String serverName) {
              return exec("state('" + serverName + "')");
         public String ls(String dir) {
              return exec("ls('" + dir + "')");
         // The generic wrapper for the interpreter exec() call
         public String exec(String command) {
              return interpreter.exec1(command);
         private WLSTInterpreterWrapper interpreter = new WLSTInterpreterWrapper();
    }Lastly here is some example code using these classes:
    its using both the exec(...) and cd(...) wrapper commands from the WLSTCommand.class shown above.
        String machineName = ...; // get name from somewhere
        try {
         exec("machine=create('" + machineName + "','Machine')");
         cd("/Machines/" + machineName + "/NodeManager/" + machineName);
         exec("set('ListenAddress','10.42.60.232')");
         exec("set('ListenPort', 5557)");
        }catch(WLSTException e) {
            // Possibly the machine object already exists so
            // lets just try to look it up.
         exec("machine=lookup('" + machineName + "','Machine')");
    ...After this call a machine object is setup that can be allocated later like so:
         exec("set('Machine',machine)");Regards
    Steve

Maybe you are looking for

  • How do you find the serial number from subscription?

    I recently bought the one year subscription Adobe Acrobat Pro. I tried to download the app onto my laptop, and it asks for a serial number that I was never provided with. I have spoken to customer service and they said it should just install since I

  • Availability Check at Storage Location Level.

    Hi All, Currrently we have the availability check functionality happenin at the plant level. If the stock is available in the plant, then the sales order is getting confirmed. But, the requirement is if the stock is insufficient then system should ch

  • Movement Types in Consignment Processing ?

    Hello SAPains, What are the movement types used in Consigment Processing ? ie  - CF, CI, CP & CONR . Please write back, Points will be awarded. Thank you.

  • Aperture 3.0.2 Databaseproblem

    Hi, maybe thats the cause yet not the solution for the library problem. All masters/version which cause problems (no creation of previews) have an empty Import session metadata field. This can´t be filled manually either. If I export one of these mas

  • How I can change the theme using with css

    How I can change the flex theme and images  using with css ?