Classloader difference in init() and destroy()?

I was getting a ClassNotFoundException (see below) inside a log4j call from my servlet destroy() method. To test, I attempted the same log4j call from my servlet init() method and it works just fine. In fact, in this test, since the class is already loaded at init time it finds it successfully at destroy time (ie. the log4j call is successful). But, if I take the call out of init and the class in not loaded anywhere prior to destroy(), it fails with the ClassNotFoundException in destroy(). Anybody have any insight on this one? Thanks.
          The exception stack dump:
          java.lang.NoClassDefFoundError: org/apache/log4j/spi/ThrowableInformation
               at org.apache.log4j.spi.LoggingEvent.<init>(LoggingEvent.java:145)
               at org.apache.log4j.Category.forcedLog(Category.java:372)
               at org.apache.log4j.Category.info(Category.java:691)
          I'm using log4j version 1.2.7.
          I'm importing org.apache.log4j.Logger;
          I instantiate in my class: private Logger theLog = Logger.getLogger(this.getClass());
          I'm calling: theLog.info(String s, Throwable e);

Where do you have the log4j.jar? It sounds like the ClassFinder for that jar has already been closed (as part of the undeployment) by the time your destroy is called.
          -- Rob
          WLS Blog http://dev2dev.bea.com/blog/rwoollen/

Similar Messages

  • Init and main

    can anybody help me understand the difference between init and main methods.
    I am a beginner,so please take it easy if thequestion seems stupid.
    thank you
    saumya

    init() comes into picture only in servlets !??That isn't what he said, that was just an example. The init() method is used by a lot of APIs, but all for the same basic principal:
    The class will be instantiated (the constructor will be called), but the process the class represents may run right away. There may be more initialisation needed. The init() method is called after all initialisation is done, and before the process begins to run. Thus, if you want to prepare your class you use the init() method (so you know it will always occur after full initialisation and before execution).
    but you mean,if i am developing an applet then no
    need to right main() ?That is correct. You do not need a main() unless your app is a stand-alone application.
    and if i am developing a stanalone application
    suppose in swing i need not right init() ?That depends. Generally no. But some classes/APIs may require you to.

  • IBooks display differences between iOS7 and iOS8

    I work for a music publisher where we build reflowable ePubs that mostly contain music and embedded audio/video files. It is critical that we deliver an eBook that keeps a/v controllers with the title, credits, music etc. and maintains proper spacing throughout. It's critical not only for the overall look but for the readability and usability of the musician. Clearly a user can increase the font size and destroy any well designed layout for ePub, but if the ePub is designed properly, targeting median font settings, our layouts are consistent from tablet to tablet.
    The recent release of iOS 8 has brought changes to iBooks once again and how it displays content. I've noticed differences with A/V controllers displaying more margin, troubles controlling the alignment and overall width of player. I've also noticed additional margin at the top of each "page" in iBooks which wasn't there in iOS 7.
    These changes may seem minor but they completely break our layouts. I have been trying to correct these issues using CSS, but haven't had any luck. What's even more frustrating is that iBooks for Mac on Mavericks doesn't have these issues. In fact, the audio controller has a completely different look and responds to CSS as it should. These small issues are causing major problems for us because we have thousands of ePubs with audio at Apple.
    We've seen changes in the past with our ePubs when iOS 6 went to 7, so we were expecting things like this to happen. But because our CSS modifications don't seem to work on the iOS side, I'm beginning to think that this is a bug or that there are new issues to contend with when developing ePubs for iBooks. If there have been changes, it would be great to have specs from Apple that would help identify what is happening within iBooks. It would also be great to have development tools for iBooks like there are for all modern browsers today.
    If anyone knows anything about these issues or has information as to where I can find the answers, I would be most grateful.

    This has been my headache since day one and a complete swing and a miss by Apple.  I haven't been able to get ANYTHING I have not explicitely purchased from iTunes to sync in iBooks across device.
    For example:  If I load an ePub or PDF into iTunes and "manually" add to a device, this works just fine.
    However, if I open a PDF file on my iPhone into iBooks, it doesn't show up in any of my other devices, including the new iBooks on my iMac with Maverick.  it doesn't matter which device it's added, nothing syncs if it's not purchased from iTunes.
    Please, someone make me a liar and tell me I've completely missed something.
    Apple:  Why or why can't I add PDF files to iBooks on my iMac and have them automagically show up in the collection I created on all my devices?  Because I didn't purchase them from you, you say?  Stupid, stupid, stupid.
    Then don't let me add it in the first place and stop advertising "my content anywhere on any device" because this has been broken from day one.

  • Differences between cookies and sessions

    Hi there,
    I want to learn the differences between sessions and cookies in PHP.Please help me.
    Please let me know if there any video demonstrations that explain sessions and cookies.
    Thanks in advance.

    Cookies and server side sessions are related in that they are both ways to persist data. This is required because of the fact that http is a stateless protocol, meaning that each request and response are independent transactions. Cookies are stored on the client. You might use them to store the contents of a shopping cart, or a user login id for a particular site. Or you could store a setting so that the user is automatically logged in, similar to what occurs here in the adobe site / forums. You can set various options for when cookies expire. Cookies that persist when the browser is closed are store in files, otherwise they could be store in memory only. Cookies can be created using either client or server side code.
    Server side sessions are created on the server with a server side scripting language. A session id is generated and stored as a token on the client (in an in memory cookie) so that the server can track requests from the same originating client. Session variables are ways to store data related to the session on the server. Sessions use server resources which is why you should only use them when necessary and destroy them when done. When the session is destroyed, the session variables are gone so if you want to keep them for later you can store them in a database or store them in a cookie.
    HTTP cookie - Wikipedia, the free encyclopedia
    Hope that helps

  • Difference between poh and pov in module pool programming

    hi all,
                       pls tell me difference between poh and pov and how i check validation in screen

    Hi,
    POV gives you F4 help.
    like:
    You can call dialog modules in the POV event using the event keyword PROCESS ON VALUE-REQUEST.
    PROCESS ON VALUE-REQUEST.
      FIELD f MODULE mod.
    After the PROCESS ON VALUE-REQUEST statement, you can only use the MODULE statement together with the FIELD statement. When the user chooses F4 for a field f, the system calls the module mod belonging to the FIELD statement. If there is more than one FIELD statement for the same field f, only the first is executed. The module mod is defined in the ABAP program like a normal PAI module. However, the contents of the screen field f are not available, since it is not transported by the FIELD statement during the PROCESS ON HELP-REQUEST event. You can now program your own value lists in the module. However, this procedure is only recommended if it really is not possible to use a search help. Defining search helps is much easier than PROCESS ON VALUE-REQUEST, since the system takes over some of the standard operations, such as getting field contents from the screen. It also ensures that the F4 help has a uniform look and feel throughout the system. Furthermore, it means that you do not have to reassign input help to fields on each screen.
    Despite the introduction of search helps (and search help exits), there are still cases in which you need to use parts of the standard F4 functions directly. In this case, there are some standard function modules that you can use in the POV event. They support search helps, as well as all other kinds of input help, and are responsible for data transport between the screen and the input help. These alll  have the prefix F4IF_. The most important are:
    ·        F4IF_FIELD_VALUE_REQUEST
    Calls the input help of the ABAP Dictionary dynamically. You can pass the component names of a structure or database table of the ABAP Dictionary to the function module in the import parameters TABNAME and FIELDNAME. The function module starts the ABAP Dictionary input help for this component. All of the relevant screen fields are read. If you specify the import parameters DYNPPROG, DYNPNR, and DYNPROFIELD, the user’s selection is returned to the corresponding field on the screen. If you specify the table parameter RETURN_TAB, the selection is returned into the table instead.
    ·        F4IF_INT_TABLE_VALUE_REQUEST
    This function module displays a value list that you created in an ABAP program. The self-programmed value list is passed to the function module as the table parameter VALUE_TAB. If you specify the import parameters DYNPPROG, DYNPNR, and DYNPROFIELD, the user’s selection is returned to the corresponding field on the screen. If you specify the table parameter RETURN_TAB, the selection is returned into the table instead.
    There are also two function modules - DYNP_VALUES_READ and DYNP_VALUES_UPDATE - that can read the values of screen fields and return values to them during the POV event. For further information, refer to the relevant function module documentation.
    Input help in dialog modules
    REPORT demo_dynpro_f4_help_module.
    TYPES: BEGIN OF values,
             carrid TYPE spfli-carrid,
             connid TYPE spfli-connid,
           END OF values.
    DATA: carrier(3) TYPE c,
          connection(4) TYPE c.
    DATA: progname TYPE sy-repid,
          dynnum   TYPE sy-dynnr,
          dynpro_values TYPE TABLE OF dynpread,
          field_value LIKE LINE OF dynpro_values,
          values_tab TYPE TABLE OF values.
    CALL SCREEN 100.
    MODULE init OUTPUT.
      progname = sy-repid.
      dynnum   = sy-dynnr.
      CLEAR: field_value, dynpro_values.
      field_value-fieldname = 'CARRIER'.
      APPEND field_value TO dynpro_values.
    ENDMODULE.
    MODULE cancel INPUT.
      LEAVE PROGRAM.
    ENDMODULE.
    MODULE value_carrier INPUT.
      CALL FUNCTION 'F4IF_FIELD_VALUE_REQUEST'
           EXPORTING
                tabname     = 'DEMOF4HELP'
                fieldname   = 'CARRIER1'
                dynpprog    = progname
                dynpnr      = dynnum
                dynprofield = 'CARRIER'.
    ENDMODULE.
    MODULE value_connection INPUT.
      CALL FUNCTION 'DYNP_VALUES_READ'
           EXPORTING
                dyname             = progname
                dynumb             = dynnum
                translate_to_upper = 'X'
           TABLES
                dynpfields         = dynpro_values.
      READ TABLE dynpro_values INDEX 1 INTO field_value.
      SELECT  carrid connid
        FROM  spfli
        INTO  CORRESPONDING FIELDS OF TABLE values_tab
        WHERE carrid = field_value-fieldvalue.
      CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
           EXPORTING
                retfield    = 'CONNID'
                dynpprog    = progname
                dynpnr      = dynnum
                dynprofield = 'CONNECTION'
                value_org   = 'S'
           TABLES
                value_tab   = values_tab.
    ENDMODULE.
    *POH gives you F1 documentation:*
    like:
    If data element supplement documentation is insufficient for your requirements, or you want to display help for program fields that you have not copied from the ABAP Dictionary, you can call dialog modules in the POH event:
    PROCESS ON HELP-REQUEST.
      FIELD  is defined in the ABAP program like a normal PAI module. The processing logic of the module must ensure that adequate help is displayed for the field in question. Instead of calling an extra screen with text fields, you should use one of the following function modules to display a suitable SAPscript document:
    HELP_OBJECT_SHOW_FOR_FIELD
    This function module displays the data element documentation for components of any structure or database table from the ABAP Dictionary. You pass the name of the component and structure or table to the import parameters FIELD and TABLE.
    HELP_OBJECT_SHOW
    Use this function module to display any SAPscript document. You must pass the document class (for example, TX for general texts, DE for data element documentation) and the name of the document to the import parameters DOKCLASS and DOKNAME. For technical reasons, you must also pass an empty internal table with the line type TLINE to the tables parameter of the function module.
    For further information about how to create SAPscript documents, refer to the  Documentation of System Objects documentation.
    Field help on screens.
    REPORT DEMO_DYNPRO_F1_HELP.
    DATA:  TEXT(30),
           VAR(4),
           INT TYPE I,
           LINKS TYPE TABLE OF TLINE,
           FIELD3, FIELD4.
    TABLES DEMOF1HELP.
    TEXT = TEXT-001.
    CALL SCREEN 100.
    MODULE CANCEL INPUT.
      LEAVE PROGRAM.
    ENDMODULE.
    MODULE F1_HELP_FIELD2 INPUT.
      INT = INT + 1.
      CASE INT.
        WHEN 1.
        VAR = '0100'.
        WHEN 2.
        VAR = '0200'.
        INT = 0.
      ENDCASE.
    ENDMODULE.
    MODULE F1_HELP_FIELD3 INPUT.
      CALL FUNCTION 'HELP_OBJECT_SHOW_FOR_FIELD'
           EXPORTING
                DOKLANGU                      = SY-LANGU
                DOKTITLE                      = TEXT-002
                CALLED_FOR_TAB                = 'DEMOF1HELP'
                CALLED_FOR_FIELD              = 'FIELD1'.
    ENDMODULE.
    MODULE F1_HELP_FIELD4 INPUT.
      CALL FUNCTION 'HELP_OBJECT_SHOW'
           EXPORTING
                DOKCLASS                      = 'TX'
                DOKLANGU                      = SY-LANGU
                DOKNAME                       = 'DEMO_FOR_F1_HELP'
                DOKTITLE                      = TEXT-003
           TABLES
                LINKS                         = LINKS.
    ENDMODULE.
    Regards,
    Renjith Michael

  • Clearing Images and Destroying Instances

    Two separate questions here.
    First I'd like to know how to clear an image that has been drawn, with it being on a random background with multiple colors, without having to redraw the background over and over again. I have an image that moves across the screen and I have the background update only when it needs to to save processing power, but now, obviously, the moving image remains drawn wherever it goes. That or if there's a way to "move" an already drawn image.
    Secondly, I'd like to know how to delete an instance of a class from within that class. I have a class that gets called a lot (example: Caller.java), and each time it's called, it creates a new instance of another class (example: NewClass.java), but when Caller.java is called, it is only used once, and I don't want all those instances to just remain there. I'd like to force GC to take care of them at the end of their tasks.
    If anyone can provide answers to either of those questions, thank you.

    hi,
    try to read this it may helpfor the subject:its from thinking in java 2nd edition by bruce eckel:
    Cleanup: finalization and
    garbage collection
    Programmers know about the importance of initialization, but often forget the importance of cleanup. After all, who needs to clean up an int? But with libraries, simply �letting go� of an object once you�re done with it is not always safe. Of course, Java has the garbage collector to reclaim the memory of objects that are no longer used. Now consider a very unusual case. Suppose your object allocates �special� memory without using new. The garbage collector knows only how to release memory allocated with new, so it won�t know how to release the object�s �special� memory. To handle this case, Java provides a method called finalize( ) that you can define for your class. Here�s how it�s supposed to work. When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the object�s memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection. [ Add Comment ]
    This is a potential programming pitfall because some programmers, especially C++ programmers, might initially mistake finalize( ) for the destructor in C++, which is a function that is always called when an object is destroyed. But it is important to distinguish between C++ and Java here, because in C++ objects always get destroyed (in a bug-free program), whereas in Java objects do not always get garbage-collected. Or, put another way: [ Add Comment ]
    Garbage collection is not destruction.
    If you remember this, you will stay out of trouble. What it means is that if there is some activity that must be performed before you no longer need an object, you must perform that activity yourself. Java has no destructor or similar concept, so you must create an ordinary method to perform this cleanup. For example, suppose in the process of creating your object it draws itself on the screen. If you don�t explicitly erase its image from the screen, it might never get cleaned up. If you put some kind of erasing functionality inside finalize( ), then if an object is garbage-collected, the image will first be removed from the screen, but if it isn�t, the image will remain. So a second point to remember is: [ Add Comment ]
    Your objects might not get garbage-collected.
    You might find that the storage for an object never gets released because your program never nears the point of running out of storage. If your program completes and the garbage collector never gets around to releasing the storage for any of your objects, that storage will be returned to the operating system en masse as the program exits. This is a good thing, because garbage collection has some overhead, and if you never do it you never incur that expense. [ Add Comment ]
    What is finalize( ) for?
    You might believe at this point that you should not use finalize( ) as a general-purpose cleanup method. What good is it? [ Add Comment ]
    A third point to remember is:
    Garbage collection is only about memory.
    That is, the sole reason for the existence of the garbage collector is to recover memory that your program is no longer using. So any activity that is associated with garbage collection, most notably your finalize( ) method, must also be only about memory and its deallocation. [ Add Comment ]
    Does this mean that if your object contains other objects finalize( ) should explicitly release those objects? Well, no�the garbage collector takes care of the release of all object memory regardless of how the object is created. It turns out that the need for finalize( ) is limited to special cases, in which your object can allocate some storage in some way other than creating an object. But, you might observe, everything in Java is an object so how can this be? [ Add Comment ]
    It would seem that finalize( ) is in place because of the possibility that you�ll do something C-like by allocating memory using a mechanism other than the normal one in Java. This can happen primarily through native methods, which are a way to call non-Java code from Java. (Native methods are discussed in Appendix B.) C and C++ are the only languages currently supported by native methods, but since they can call subprograms in other languages, you can effectively call anything. Inside the non-Java code, C�s malloc( ) family of functions might be called to allocate storage, and unless you call free( ) that storage will not be released, causing a memory leak. Of course, free( ) is a C and C++ function, so you�d need to call it in a native method inside your finalize( ). [ Add Comment ]
    After reading this, you probably get the idea that you won�t use finalize( ) much. You�re correct; it is not the appropriate place for normal cleanup to occur. So where should normal cleanup be performed? [ Add Comment ]
    You must perform cleanup
    To clean up an object, the user of that object must call a cleanup method at the point the cleanup is desired. This sounds pretty straightforward, but it collides a bit with the C++ concept of the destructor. In C++, all objects are destroyed. Or rather, all objects should be destroyed. If the C++ object is created as a local (i.e., on the stack�not possible in Java), then the destruction happens at the closing curly brace of the scope in which the object was created. If the object was created using new (like in Java) the destructor is called when the programmer calls the C++ operator delete (which doesn�t exist in Java). If the C++ programmer forgets to call delete, the destructor is never called and you have a memory leak, plus the other parts of the object never get cleaned up. This kind of bug can be very difficult to track down. [ Add Comment ]
    In contrast, Java doesn�t allow you to create local objects�you must always use new. But in Java, there�s no �delete� to call to release the object since the garbage collector releases the storage for you. So from a simplistic standpoint you could say that because of garbage collection, Java has no destructor. You�ll see as this book progresses, however, that the presence of a garbage collector does not remove the need for or utility of destructors. (And you should never call finalize( ) directly, so that�s not an appropriate avenue for a solution.) If you want some kind of cleanup performed other than storage release you must still explicitly call an appropriate method in Java, which is the equivalent of a C++ destructor without the convenience. [ Add Comment ]
    One of the things finalize( ) can be useful for is observing the process of garbage collection. The following example shows you what�s going on and summarizes the previous descriptions of garbage collection:
    //: c04:Garbage.java
    // Demonstration of the garbage
    // collector and finalization
    class Chair {
    static boolean gcrun = false;
    static boolean f = false;
    static int created = 0;
    static int finalized = 0;
    int i;
    Chair() {
    i = ++created;
    if(created == 47)
    System.out.println("Created 47");
    public void finalize() {
    if(!gcrun) {
    // The first time finalize() is called:
    gcrun = true;
    System.out.println(
    "Beginning to finalize after " +
    created + " Chairs have been created");
    if(i == 47) {
    System.out.println(
    "Finalizing Chair #47, " +
    "Setting flag to stop Chair creation");
    f = true;
    finalized++;
    if(finalized >= created)
    System.out.println(
    "All " + finalized + " finalized");
    public class Garbage {
    public static void main(String[] args) {
    // As long as the flag hasn't been set,
    // make Chairs and Strings:
    while(!Chair.f) {
    new Chair();
    new String("To take up space");
    System.out.println(
    "After all Chairs have been created:\n" +
    "total created = " + Chair.created +
    ", total finalized = " + Chair.finalized);
    // Optional arguments force garbage
    // collection & finalization:
    if(args.length > 0) {
    if(args[0].equals("gc") ||
    args[0].equals("all")) {
    System.out.println("gc():");
    System.gc();
    if(args[0].equals("finalize") ||
    args[0].equals("all")) {
    System.out.println("runFinalization():");
    System.runFinalization();
    System.out.println("bye!");
    } ///:~
    The above program creates many Chair objects, and at some point after the garbage collector begins running, the program stops creating Chairs. Since the garbage collector can run at any time, you don�t know exactly when it will start up, so there�s a flag called gcrun to indicate whether the garbage collector has started running yet. A second flag f is a way for Chair to tell the main( ) loop that it should stop making objects. Both of these flags are set within finalize( ), which is called during garbage collection. [ Add Comment ]
    Two other static variables, created and finalized, keep track of the number of Chairs created versus the number that get finalized by the garbage collector. Finally, each Chair has its own (non-static) int i so it can keep track of what number it is. When Chair number 47 is finalized, the flag is set to true to bring the process of Chair creation to a stop. [ Add Comment ]
    All this happens in main( ), in the loop
    while(!Chair.f) {
    new Chair();
    new String("To take up space");
    You might wonder how this loop could ever finish, since there�s nothing inside the loop that changes the value of Chair.f. However, the finalize( ) process will, eventually, when it finalizes number 47. [ Add Comment ]
    The creation of a String object during each iteration is simply extra storage being allocated to encourage the garbage collector to kick in, which it will do when it starts to get nervous about the amount of memory available. [ Add Comment ]
    When you run the program, you provide a command-line argument of �gc,� �finalize,� or �all.� The �gc� argument will call the System.gc( ) method (to force execution of the garbage collector). Using the �finalize� argument calls System.runFinalization( ) which�in theory�will cause any unfinalized objects to be finalized. And �all� causes both methods to be called. [ Add Comment ]
    The behavior of this program and the version in the first edition of this book shows that the whole issue of garbage collection and finalization has been evolving, with much of the evolution happening behind closed doors. In fact, by the time you read this, the behavior of the program may have changed once again. [ Add Comment ]
    If System.gc( ) is called, then finalization happens to all the objects. This was not necessarily the case with previous implementations of the JDK, although the documentation claimed otherwise. In addition, you�ll see that it doesn�t seem to make any difference whether System.runFinalization( ) is called. [ Add Comment ]
    However, you will see that only if System.gc( ) is called after all the objects are created and discarded will all the finalizers be called. If you do not call System.gc( ), then only some of the objects will be finalized. In Java 1.1, a method System.runFinalizersOnExit( ) was introduced that caused programs to run all the finalizers as they exited, but the design turned out to be buggy and the method was deprecated. This is yet another clue that the Java designers were thrashing about trying to solve the garbage collection and finalization problem. We can only hope that things have been worked out in Java 2. [ Add Comment ]
    The preceding program shows that the promise that finalizers will always be run holds true, but only if you explicitly force it to happen yourself. If you don�t cause System.gc( ) to be called, you�ll get an output like this:
    Created 47
    Beginning to finalize after 3486 Chairs have been created
    Finalizing Chair #47, Setting flag to stop Chair creation
    After all Chairs have been created:
    total created = 3881, total finalized = 2684
    bye!
    Thus, not all finalizers get called by the time the program completes. If System.gc( ) is called, it will finalize and destroy all the objects that are no longer in use up to that point. [ Add Comment ]
    Remember that neither garbage collection nor finalization is guaranteed. If the Java Virtual Machine (JVM) isn�t close to running out of memory, then it will (wisely) not waste time recovering memory through garbage collection. [ Add Comment ]
    The death condition
    In general, you can�t rely on finalize( ) being called, and you must create separate �cleanup� functions and call them explicitly. So it appears that finalize( ) is only useful for obscure memory cleanup that most programmers will never use. However, there is a very interesting use of finalize( ) which does not rely on it being called every time. This is the verification of the death condition[29] of an object. [ Add Comment ]
    At the point that you�re no longer interested in an object�when it�s ready to be cleaned up�that object should be in a state whereby its memory can be safely released. For example, if the object represents an open file, that file should be closed by the programmer before the object is garbage-collected. If any portions of the object are not properly cleaned up, then you have a bug in your program that could be very difficult to find. The value of finalize( ) is that it can be used to discover this condition, even if it isn�t always called. If one of the finalizations happens to reveal the bug, then you discover the problem, which is all you really care about. [ Add Comment ]
    Here�s a simple example of how you might use it:
    //: c04:DeathCondition.java
    // Using finalize() to detect an object that
    // hasn't been properly cleaned up.
    class Book {
    boolean checkedOut = false;
    Book(boolean checkOut) {
    checkedOut = checkOut;
    void checkIn() {
    checkedOut = false;
    public void finalize() {
    if(checkedOut)
    System.out.println("Error: checked out");
    public class DeathCondition {
    public static void main(String[] args) {
    Book novel = new Book(true);
    // Proper cleanup:
    novel.checkIn();
    // Drop the reference, forget to clean up:
    new Book(true);
    // Force garbage collection & finalization:
    System.gc();
    } ///:~
    The death condition is that all Book objects are supposed to be checked in before they are garbage-collected, but in main( ) a programmer error doesn�t check in one of the books. Without finalize( ) to verify the death condition, this could be a difficult bug to find. [ Add Comment ]
    Note that System.gc( ) is used to force finalization (and you should do this during program development to speed debugging). But even if it isn�t, it�s highly probable that the errant Book will eventually be discovered through repeated executions of the program (assuming the program allocates enough storage to cause the garbage collector to execute). [ Add Comment ]

  • What is the difference between HttpSessionBindingListener and HttpSessionLi

    What is the difference between HttpSessionBindingListener and HttpSessionListener?

    HttpSessionBindingListener gets notified if a value has been added to or remove from a session.
    HttpSessionListener gets notified if a session is created or destroyed.

  • Differences between awt and swing

    Ive written the following code, however Ive implemented the gui in awt rather then swing. Ive been told it hs too be in swing. What is the difference between swing and awt what will I need to change in my program so that its done using swing rather then the awt? Heres the code:
    // pp.java
    // Grant Brown
    // 22/02/02
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    // =========================================================
    // Class: pp
    // This class drives the customer manager. It contains the
    // main method which gets called as soon as this application
    // begins to run.
    // =========================================================
    class pp extends Frame implements ActionListener
    // Container of customer objects
    private Vector customers = new Vector (100);
    // List of names component. (Must specify java.awt in
    // front of List to distinguish the List class in the
    // java.awt package from the List class in the java.util
    // package.)
    private java.awt.List names = new java.awt.List ();
    // Delete and update button components.
    private Button delete;
    private Button update;
    // Default constructor.
    public pp ()
    // Assign "Paper Round Manager" to title bar of frame window.
    super ("Paper Round Manager");
    // Add a listener that responds to window closing
    // events. When this event occurs (by clicking on the
    // close box in the title bar), save customers and exit.
    addWindowListener (new WindowAdapter ()
    public void windowClosing
    (WindowEvent e)
    saveCustomers ();
    System.exit (0);
    // Place an empty label in the north part of the frame
    // window. This is done to correct an AWT positioning
    // problem.
    Label l = new Label ();
    add ("North", l);
    // Place the names component in the center part of the
    // frame window.
    add ("Center", names);
    // Create a panel object to hold four buttons.
    Panel p = new Panel ();
    Button b;
    // Add an Insert button to the Panel object and register
    // the current pp object as a listener for button events.
    p.add (b = new Button ("Insert"));
    b.addActionListener (this);
    // Add a Delete button to the Panel object and register
    // the current pp object as a listener for button events.
    p.add (delete = new Button ("Delete"));
    delete.addActionListener (this);
    // The Delete button should be disabled until there is at
    // least one customer to delete.
    delete.setEnabled (false);
    // Add an Update button to the Panel object and register
    // the current pp object as a listener for button events.
    p.add (update = new Button ("Update"));
    update.addActionListener (this);
    // The Update button should be disabled until there is at
    // least one customer to update.
    update.setEnabled (false);
    // Add a Finish button to the Panel object and register
    // the current customer object as a listener for button events.
    p.add (b = new Button ("Finish"));
    b.addActionListener (this);
    // Add the panel object to the frame window container.
    add ("South", p);
    // Set the background of the frame window container to
    // lightGray
    setBackground (Color.lightGray);
    // Set the size of the frame window container to 400
    // pixels horizontally by 200 pixels vertically.
    setSize (400, 200);
    // Allow the user to resize the frame window.
    setResizable (true);
    // Load all contacts.
    loadCustomers ();
    // Make sure that the frame window is visible.
    setVisible (true);
    public void actionPerformed (ActionEvent e)
    if (e.getActionCommand ().equals ("Delete"))
    delete ();
    else
    if (e.getActionCommand ().equals ("Finish"))
    saveCustomers ();
    System.exit (0);
    else
    if (e.getActionCommand ().equals ("Insert"))
    insert ();
    else
    update ();
    public Insets getInsets ()
    // Return an Insets object that describes the number of
    // pixels to reserve as a border around the edges of the
    // frame window.
    return new Insets (10, 10, 10, 10);
    public static void main (String [] args)
    // Create a new pp object and let it do its thing.
    new pp ();
    private void delete ()
    // Obtain index of selected contact item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot update
    // a contact if no contact item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Remove the contact item from the names component.
    names.remove (index);
    // Remove the Customer object from the contacts Vector
    // object.
    customers.remove (index);
    // If there are no more customers ...
    if (customers.size () == 0)
    delete.setEnabled (false);
    update.setEnabled (false);
    else
    // Make sure that the first contact item in the names
    // list is highlighted.
    names.select (0);
    private void insert ()
    // Create an Insert data entry form to enter information
    // for a new customer.
    DataEntryForm def = new DataEntryForm (this, "Insert");
    // If the bOk Boolean flag is set, this indicates the user
    // exited the form by pressing the Ok button.
    if (def.bOk)
    // Create a Contact object and assign information from
    // the form to its fields.
    Customer temp = new Customer ();
    temp.name = new String (def.name.getText ());
    temp.publication = new String (def.publication.getText ());
    temp.round = new String (def.round.getText ());
    temp.address = new String (def.address.getText ());
    temp.phone = new String (def.phone.getText ());
    // Add a new customer item to the names component.
    names.add (temp.name + ", " + temp.publication);
    // Add the Customer object to the contacts Vector
    // object.
    customers.add (temp);
    // Make sure that the Delete and Update buttons are
    // enabled.
    delete.setEnabled (true);
    update.setEnabled (true);
    // Destroy the dialouge box.
    def.dispose ();
    // Make sure that the first customer item in the names list
    // is highlighted.
    names.select (0);
    // ===========================================================
    // Load all contacts from contacts.dat into the contacts
    // Vector object. Also, make sure that the last name/first
    // name from each contact is combined into a String object and
    // inserted into the names component - as a contact item.
    // ===========================================================
    private void loadCustomers ()
    FileInputStream fis = null;
    try
    fis = new FileInputStream ("Customers.dat");
    DataInputStream dis = new DataInputStream (fis);
    int nCustomers = dis.readInt ();
    for (int i = 0; i < nCustomers; i++)
    Customer temp = new Customer ();
    temp.name = dis.readUTF ();
    temp.publication = dis.readUTF ();
    temp.round = dis.readUTF ();
    temp.address = dis.readUTF ();
    temp.phone = dis.readUTF ();
    names.add (temp.name + ", " + temp.publication);
    customers.add (temp);
    if (nCustomers > 0)
    delete.setEnabled (true);
    update.setEnabled (true);
    catch (IOException e)
    finally
    if (fis != null)
    try
    fis.close ();
    catch (IOException e) {}
    // Make sure that the first contact item in the names list
    // is highlighted.
    names.select (0);
    // ========================================================
    // Save all Customer objects from the customer Vector object
    // to customer.dat. The number of customerss are saved as an
    // int to make it easy for loadCustomers () to do its job.
    // ========================================================
    private void saveCustomers ()
    FileOutputStream fos = null;
    try
    fos = new FileOutputStream ("customers.dat");
    DataOutputStream dos = new DataOutputStream (fos);
    dos.writeInt (customers.size ());
    for (int i = 0; i < customers.size (); i++)
    Customer temp = (Customer) customers.elementAt (i);
    dos.writeUTF (temp.name);
    dos.writeUTF (temp.publication);
    dos.writeUTF (temp.round);
    dos.writeUTF (temp.address);
    dos.writeUTF (temp.phone);
    catch (IOException e)
    MsgBox mb = new MsgBox (this, "PP Error",
    e.toString ());
    mb.dispose ();
    finally
    if (fos != null)
    try
    fos.close ();
    catch (IOException e) {}
    private void update ()
    // Obtain index of selected customer item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot update
    // a customer if no customer item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Obtain a reference to the customer object (from the
    // customers Vector object) that is associated with the
    // index.
    Customer temp = (Customer) customers.elementAt (index);
    // Create and display an update entry form.
    DataEntryForm def = new DataEntryForm (this, "Update",
    temp.name,
    temp.publication,
    temp.round,
    temp.address,
    temp.phone);
    // If the user pressed Ok...
    if (def.bOk)
    // Update the customer information in the customers
    // Vector object.
    temp.name = new String (def.name.getText ());
    temp.publication = new String (def.publication.getText ());
    temp.round = new String (def.round.getText ());
    temp.address = new String (def.address.getText ());
    temp.phone = new String (def.phone.getText ());
    // Make sure the screen reflects the update.
    names.replaceItem (temp.name + ", " + temp.publication,
    index);
    // Destroy the dialouge box.
    def.dispose ();
    // Make sure that the first customer item in the names
    // list is highlighted.
    names.select (0);

    Ive doen pretty much what you said burt now my program isnt working at all. The window comes up but instead of doing something when you click the button it just throws shit loads of exceptions. Heres my abridged code
    // pp.java
    // Grant Brown
    // 22/02/02
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    // =========================================================
    // Class:PP
    // This class drives the Paper Round manager. It contains the
    // main method which gets called as soon as this application
    // begins to run.
    // =========================================================
    class pp extends JFrame implements ActionListener
    // Container of customer objects (one object per customer)
    private Vector customers = new Vector (100);
    // List of names component. (Must specify java.awt in
    // front of List to distinguish the List class in the
    // java.awt package from the List class in the java.util
    // package.)
    private java.awt.List names = new java.awt.List ();
    // Delete and update button components.
    private JButton delete;
    private JButton update;
    // Default constructor.
    public pp ()
    // Assign Contact Manager to title bar of frame window.
    super ("Paper Round Manager");
    // Add a listener that responds to window closing
    // events. When this event occurs (by clicking on the
    // close box in the title bar), save contacts and exit.
    addWindowListener (new WindowAdapter ()
    public void windowClosing
    (WindowEvent e)
    saveCustomers ();
    System.exit (0);
    // Place an empty label in the north part of the frame
    // window. This is done to correct an AWT positioning
    // problem. (One thing that you'll come to realize as
    // you work with the AWT is that there are lots of bugs.)
    JLabel l = new JLabel ();
    getContentPane().add ("North", l);
    // Place the names component in the center part of the
    // frame window.
    getContentPane().add ("Center", names);
    // Create a panel object to hold four buttons.
    JPanel p = new JPanel ();
    JButton b;
    // Add an Insert button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (b = new JButton ("Insert"));
    b.addActionListener (this);
    // Add a Delete button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (delete = new JButton ("Delete"));
    delete.addActionListener (this);
    // The Delete button should be disabled until there is at
    // least one contact to delete.
    delete.setEnabled (false);
    // Add an Update button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (update = new JButton ("Update"));
    update.addActionListener (this);
    // The Update button should be disabled until there is at
    // least one contact to update.
    update.setEnabled (false);
    // Add a Finish button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (b = new JButton ("Finish"));
    b.addActionListener (this);
    // Add the panel object to the frame window container.
    getContentPane().add ("South", p);
    // Set the background of the frame window container to
    // lightGray (to give a pleasing effect).
    setBackground (Color.lightGray);
    // Set the size of the frame window container to 400
    // pixels horizontally by 200 pixels vertically.
    setBounds (50, 100, 400, 200);
    // Do not allow the user to resize the frame window.
    loadCustomers ();
    // Load all contacts.
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Make sure that the frame window is visible.
    setVisible (true);
    public void actionPerformed (ActionEvent e)
    if (e.getActionCommand ().equals ("Delete"))
    delete ();
    else
    if (e.getActionCommand ().equals ("Finish"))
    saveCustomers ();
    System.exit (0);
    else
    if (e.getActionCommand ().equals ("Insert"))
    insert ();
    else
    update ();
    public Insets getInsets ()
    // Return an Insets object that describes the number of
    // pixels to reserve as a border around the edges of the
    // frame window.
    return new Insets (10, 10, 10, 10);
    public static void main (String [] args)
    // Create a new cm object and let it do its thing.
    new pp ();
    private void delete ()
    // Obtain index of selected customer item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot update
    // a contact if no contact item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Remove the customer item from the names component.
    names.remove (index);
    // Remove the Customer object from the contacts Vector
    // object.
    customers.remove (index);
    // If there are no more customers ...
    if (customers.size () == 0)
    delete.setEnabled (false);
    update.setEnabled (false);
    else
    // Make sure that the first contact item in the names
    // list is highlighted.
    names.select (0);
    private void insert ()
    // Create an Insert data entry form to enter information
    // for a new contact.
    DataEntryForm def = new DataEntryForm (this, "Insert");
    // If the bOk Boolean flag is set, this indicates the user
    // exited the form by pressing the Ok button.
    if (def.bOk)
    // Create a Customer object and assign information from
    // the form to its fields.
    Customer temp = new Customer ();
    temp.name = new String (def.name.getText ());
    temp.publication = new String (def.publication.getText ());
    temp.address = new String (def.address.getText ());
    temp.round = new String (def.round.getText ());
    temp.phone = new String
              (def.phone.getText ());
    // Add a new customer item to the names component.
    names.add (temp.publication + ", " + temp.address);
    // Add the Customer object to the contacts Vector
    // object.
    customers.add (temp);
    // Make sure that the Delete and Update buttons are
    // enabled.
    delete.setEnabled (true);
    update.setEnabled (true);
    // Destroy the dialog box.
    def.dispose ();
    // Make sure that the first customer item in the names list
    // is highlighted.
    names.select (0);
    // ===========================================================
    // Load all customers from customers.dat into the customers
    // Vector object. Also, make sure that the last name/first
    // name from each contact is combined into a String object and
    // inserted into the names component - as a contact item.
    // ===========================================================
    private void loadCustomers ()
    FileInputStream fis = null;
    try
    fis = new FileInputStream ("customers.dat");
    DataInputStream dis = new DataInputStream (fis);
    int nCustomers = dis.readInt ();
    for (int i = 0; i < nCustomers; i++)
    Customer temp = new Customer ();
    temp.name = dis.readUTF ();
    temp.publication = dis.readUTF ();
    temp.address = dis.readUTF ();
    temp.round = dis.readUTF ();
    temp.phone = dis.readUTF ();
    names.add (temp.publication + ", " + temp.address);
    customers.add (temp);
    if (nCustomers > 0)
    delete.setEnabled (true);
    update.setEnabled (true);
    catch (IOException e)
    finally
    if (fis != null)
    try
    fis.close ();
    catch (IOException e) {}
    // Make sure that the first customer item in the names list
    // is highlighted.
    names.select (0);
    // ========================================================
    // Save all customer objects from the contacts Vector object
    // to customers.dat. The number of contacts are saved as an
    // int to make it easy for loadCustomers () to do its job.
    // ========================================================
    private void saveCustomers ()
    FileOutputStream fos = null;
    try
    fos = new FileOutputStream ("customers.dat");
    DataOutputStream dos = new DataOutputStream (fos);
    dos.writeInt (customers.size ());
    for (int i = 0; i < customers.size (); i++)
    Customer temp = (Customer) customers.elementAt (i);
    dos.writeUTF (temp.name);
    dos.writeUTF (temp.publication);
    dos.writeUTF (temp.address);
    dos.writeUTF (temp.round);
    dos.writeUTF (temp.phone);
    catch (IOException e)
    MsgBox mb = new MsgBox (this, "PP Error",
    e.toString ());
    mb.dispose ();
    finally
    if (fos != null)
    try
    fos.close ();
    catch (IOException e) {}
    private void update ()
    // Obtain index of selected customer item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot update
    // a customer if no customer item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Obtain a reference to the Customer object (from the
    // customer Vector object) that is associated with the
    // index.
    Customer temp = (Customer) customers.elementAt (index);
    // Create and display an update entry form.
    DataEntryForm def = new DataEntryForm (this, "Update",
    temp.name,
    temp.publication,
    temp.address,
    temp.round,
    temp.phone);
    // If the user pressed Ok...
    if (def.bOk)
    // Update the customer information in the customers
    // Vector object.
    temp.name = new String (def.name.getText ());
    temp.publication = new String (def.publication.getText ());
    temp.address = new String (def.address.getText ());
    temp.round = new String (def.round.getText ());
    temp.phone = new String (def.phone.getText ());
    // Make sure the screen reflects the update.
    names.replaceItem (temp.publication + ", " + temp.address,
    index);
    // Destroy the dialog box.
    def.dispose ();
    // Make sure that the first customer item in the names
    // list is highlighted.
    names.select (0);
    // ========================================================
    // Class: Customer
    // This class describes the contents of a business customer.
    // ========================================================
    class Customer
    public String name;
    public String publication;
    public String address;
    public String round;
    public String phone;
    // ==========================================================
    // Class: DataEntryForm
    // This class provides a data entry form for entering customer
    // information.
    // ==========================================================
    class DataEntryForm extends JDialog implements ActionListener
    // bOk is a boolean flag. When true, it indicates that
    // the Ok button was pressed to terminate the dialog box
    // (as opposed to the Cancel button).
    public boolean bOk;
    // The following components hold the text that the user
    // entered into the visible text fields.
    public JTextField name;
    public JTextField publication;
    public JTextField address;
    public JTextField round;
    public JTextField phone;
    public void actionPerformed (ActionEvent e)
    // If the user pressed the Ok button, indicate this
    // by assigning true to bOk.
    if (e.getActionCommand ().equals ("Ok"))
    bOk = true;
    // Destroy the dialog box and return to the point
    // just after the creation of the DataEntryForm object.
    dispose ();
    public DataEntryForm (JFrame parent, String title)
    // Call the other constructor. The current constructor
    // is used for insert operations. The other constructor
    // is used for update operations.
    this (parent, title, "", "", "", "", "");
    public DataEntryForm (JFrame parent, String title,
    String name, String publication,
    String address, String round,
    String phone)
    // Initialize the superclass layer.
    super (parent, title, true);
    // Choose a grid bag layout so that components can be more
    // accurately positioned. (It looks nicer.)
    setLayout (new GridBagLayout ());
    // Add appropriate first name, last name, phone, fax, and
    // email components to the current DataEntryForm container.
    // (Remember, DataEntryForm is a subclass of Dialog.
    // Dialog is a container. Therefore, DataEntryForm
    // inherits the ability to be a container.)
    addComponent (this, new JLabel ("Name: "), 0, 0, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.name = new JTextField (15);
    addComponent (this, this.name, 1, 0, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.name.setText (name);
    addComponent (this, new JLabel ("Publications: "), 0, 1, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.publication = new JTextField (15);
    addComponent (this, this.publication, 1, 1, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.publication.setText (publication);
    addComponent (this, new JLabel ("Address "), 0, 2, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.address = new JTextField (15);
    addComponent (this, this.address, 1, 2, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.address.setText (address);
    addComponent (this, new JLabel ("Round No "), 0, 3, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.round = new JTextField (15);
    addComponent (this, this.round, 1, 3, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.round.setText (round);
    addComponent (this, new JLabel ("Phone Number "), 0, 4, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.phone = new JTextField (15);
    addComponent (this, this.phone, 1, 4, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("Update"))
    this.phone.setText (phone);
    addComponent (this, new JLabel (""), 0, 5, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    addComponent (this, new JLabel (""), 1, 5, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    JButton b;
    // Add an Ok button to this container.
    addComponent (this, b = new JButton ("Ok"), 0, 6, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    b.addActionListener (this);
    // Add a Cancel button to this container.
    addComponent (this, b = new JButton ("Cancel"), 1, 6, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    b.addActionListener (this);
    // Set the size of the dialog window to 250 pixels
    // horizontally by 200 pixels vertically.
    setSize (250, 200);
    // Do not allow users to resize the dialog window.
    setResizable (false);
    // Make sure that the dialog window is visible.
    setVisible (true);
    private void addComponent (Container con, Component com,
    int gridx, int gridy,
    int gridw, int gridh, int fill,
    int anchor)
    // Get the current layout manager. It is assumed to
    // be a GridBagLayout object.
    LayoutManager lm = con.getLayout ();
    // Create a GridBagConstraints object to make it
    // possible to customize component positioning.
    GridBagConstraints gbc = new GridBagConstraints ();
    // Assign the x and y grid positions.
    gbc.gridx = gridx;
    gbc.gridy = gridy;
    // Assign the number of grid blocks horizontally and
    // vertically that are occupied by the component.
    gbc.gridwidth = gridw;
    gbc.gridheight = gridh;
    // Specify the component's resize policy (fill) and
    // the direction in which the component is positioned
    // when its size is smaller than available space (anchor).
    gbc.fill = fill;
    gbc.anchor = anchor;
    // Set the new constraints that the grid bag layout
    // manager will use.
    ((GridBagLayout) lm).setConstraints (com, gbc);
    // Add the component to the container.
    con.add (com);
    // ===========================================================
    // Class: MsgBox
    // This class displays a message box to the user. The message
    // is usually an error message. The user must press the Ok
    // button to terminate the message box.
    // ===========================================================
    class MsgBox extends JDialog implements ActionListener
    public void actionPerformed (ActionEvent e)
    // Terminate the dialog box in response to the user
    // pressing the Ok button.
    dispose ();
    public MsgBox (JFrame parent, String title, String msg)
    // Initialize the superclass layer.
    super (parent, title, true);
    // Store the msg argument in a Label object and add
    // this object to the center part of the dialog window.
    JLabel l = new JLabel (msg);
    add ("Center", l);
    // Create a Button object and add it to the south part
    // of the dialog window.
    JButton b = new JButton ("Ok");
    add ("South", b);
    // Make the current object a listener to events that
    // occur as a result of the user pressing the Ok
    // button.
    b.addActionListener (this);
    // Make sure that the Ok button has the focus.
    b.requestFocus ();
    // Do not allow users to resize the dialog window.
    setResizable (false);
    // Allow the layout manager to choose an appropriate
    // size for the dialog window.
    pack ();
    // Make sure that the dialog window is visible.
    setVisible (true);
    }

  • Re: The difference between update() and doFinal() in ClassCipher

    Hi Guys,
    I found this topic,
    The difference between update() and doFinal() in ClassCipher
    during a Google Search. I need your help, because I'm working on a project for an university exam.
    It's about a Client FTP that sends and received files with the content crypted.
    I'm using DES Encryption with "DES/CBC/PKCS5Padding".
    I have this doubt: when it's correct to uso the doFinal method? At the last block of the file, or after it? (for encryption)
    And during the decryption, how can I use the result of the doFinal operation?

    Reposting with &#123;code} tags
    capagira87 wrote:
    Ok these are the functions:
    public void CodificaInvia (String cd, String filename, SecretKey Key) // it opens, codes and sends to the server the content of the file 512 bytes per time
    int returncode=0;
    Socket DataSock = null;
    FileInputStream fis = null;
    byte [] text = null;
    try {
    DataSock = new Socket (servAddress,22);
    ObjectInputStream cin = new ObjectInputStream (DataSock.getInputStream());
    ObjectOutputStream out = new ObjectOutputStream (DataSock.getOutputStream());
    byte[] iv = new byte[] { (byte) 0x8E, 0x12, 0x39, (byte) 0x9C, 0x07, 0x72, 0x6F, 0x5A };
    AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, Key, paramSpec);
    fis = new FileInputStream (cd+File.separator+filename);
    int size = fis.available();
    if ((size%8)==0)
    text = new byte [size];
    } else {
    do {
    size++;
    } while ((size%8)!=0);
    text = new byte [size];
    fis.read(text,0,fis.available());
    byte [] ciphertext = cipher.doFinal(text);
    out.writeInt(ciphertext.length);
    int numblock = ciphertext.length/512;
    int resto = ciphertext.length%512;
    out.writeInt(numblock);
    out.writeInt(resto);
    byte [] tempblock = new byte [512];
    for (int conta=0; conta<numblock; conta++)
    for (int i=0; i<512; i++)
    tempblock=ciphertext[(conta*512)+i];
    out.write(tempblock);
    out.flush();
    if (resto > 0) // this block works if the file size is not multiple of 512
    java.util.Arrays.fill (tempblock, (byte) 0);
    int h= numblock*512;
    for (int i=0; i<resto; i++)
    tempblock[i]=ciphertext[h+i];
    out.write (tempblock);
    out.flush();
    System.out.println ("OK!");
    } catch (Exception e)
    e.printStackTrace();
    public void RicezioneDecodifica (String filename, SecretKey Key) // in this function I receive the file blocks, I decrpyt them and I save the decrypted text into a file
    Socket DataSock = null;
    byte [] buffer=null; // it saves the received data
    String Plaintext = new String (); // it saves the deciphered text
    try {
    ServerSocket ss2 = new ServerSocket (TRANSMISSION_PORT);
    DataSock = ss2.accept();
    ObjectOutputStream out = new ObjectOutputStream (DataSock.getOutputStream());
    ObjectInputStream cin = new ObjectInputStream (DataSock.getInputStream());
    byte[] iv = new byte[] { (byte) 0x8E, 0x12, 0x39, (byte) 0x9C, 0x07, 0x72, 0x6F, 0x5A };
    AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
    Cipher dcipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    dcipher.init(Cipher.DECRYPT_MODE, Key, paramSpec);
    int size = cin.readInt();
    int numblock = cin.readInt();
    int resto = cin.readInt();
    if ((size%8)!=0)
    do{
    size++;
    } while ((size%8)!=0);
    int ByteLetti=0; // counter of read bytes
    buffer = new byte [size];
    for (int conta=0; conta<numblock; conta++)
    int a=cin.available();
    byte [] tempblock = new byte [a];
    cin.read(tempblock, 0, a);
    for (int i=0; i<a; i++)
    buffer[ByteLetti+i]=tempblock[i];
    ByteLetti=ByteLetti+a;
    byte[] texttmp=dcipher.update(tempblock);
    String tmp = new String (texttmp, "UTF8");
    Plaintext=Plaintext+tmp;
    if (resto>0)
    int a = cin.available();
    byte [] tempblock;
    if ((a%8)>0)
    do {
    a++;
    } while ((a%8)!=0);
    tempblock = new byte [a];
    cin.read(tempblock, 0, cin.available());
    byte[] texttmp = dcipher.doFinal(tempblock);
    String tmp = new String (texttmp, "UTF8");
    Plaintext = Plaintext+tmp;
    ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (filename));
    oos.writeChars(Plaintext);
    oos.flush();
    oos.close();
    } catch (Exception e)
    e.printStackTrace();

  • What is the programming (ABAP) difference between Unicode and non Unicode?

    What is the programming(ABAP) difference between Unicode and non Unicode?
    Edited by: NIV on Apr 12, 2010 1:29 PM

    Hi
    The difference between programming in Unicode or not Unicode is that you should consider some adjustments to make on the Program "Z" to comply with the judgments Unicode Standard.
    In the past, developments in SAP using multiple systems to encode the characters of different alphabets. For example: ASCII, EBCDI, or double-byte code pages.
    These coding systems mostly use 1 byte per character, which can encode up to 256 characters. However, other alphabets such as Japanese or Chinese use a larger number of characters in their alphabets. That's why the system using double-byte code page, which uses 2 bytes per character.
    In order to unify the different alphabets, it was decided to implement a single coding system that uses 2 bytes per character regardless of what language is concerned. That system is called Unicode.
    Unicode is also the official way to implement ISO/IEC 10646 and is supported in many operating systems and all modern browsers.
    The way of verifying whether a program was adjusted or not, is through the execution of the UCCHECK transaction. Additionally, you can check by controlling syntax (making sure that this asset verification check Unicode).
    The main decisions to adjust / replace are (examples):
    ASSIGN H-SY-INDEX TEXT TO ASSIGN <F1> by
    H-SY-INDEX TEXT (*) TO <F1>.
    DATA INIT (50) VALUE '/'. by
    DATA INIT (1) VALUE '/'.
    DESCRIBE FIELD text LENGTH lengh2 by
    DESCRIBE FIELD text LENGTH lengh2 in character mode.
    T_ZSMY_DEMREG_V1 = record_tab by
    record_tab TO MOVE-Corresponding t_zsmy_demreg_v1.
    escape_trick = hot3. by
    escape_trick-x1 = hot3.
    itab_txt TYPE wt by
    ITAB_TXT TYPE TABLE OF TEXTPOOL
    DATA: string3 (3) TYPE X VALUE B2023 '3 'by
    DATA: string3 (6) B2023 TYPE c VALUE '3 '.
    OPEN DATASET file_name IN TEXT MODE by
    OPEN DATASET file_name FOR INPUT IN TEXT MODE ENCODING NON-UNICODE.
    or
    OPEN DATASET file_name FOR INPUT IN TEXT MODE ENCODING DEFAULT.
    CODE FROM PAGE TRANSLATE a_codepage record by
    record TRANSLATE USING a_codepage.
    CALL FUNCTION 'DOWNLOAD' by
    CALL METHOD cl_gui_frontend_services => gui_download
    CALL FUNCTION 'WS_DOWNLOAD' by
    CALL METHOD cl_gui_frontend_services => gui_download
    CALL FUNCTION 'UPLOAD' by
    CALL METHOD cl_gui_frontend_services => gui_upload
    CALL FUNCTION 'WS_UPLOAD' by
    CALL METHOD cl_gui_frontend_services => gui_upload
    PERFORM USING HEAD APPEND_XFEBRE +2. by
    PERFORM USING HEAD APPEND_XFEBRE +2 (98).
    Best Regars
    Fabio Rodriguez

  • What's the difference between Main ( ) and Main { } ?

    I have been searching around, but still no luck finding the difference between Main ( ) and Main { }. I found that java uses ( ), and javafx uses { }. But in javafx I can still use ( ). Is there different meaning?
    Thanks.

    I am not sure what you mean, but I will take a guess.
    Remember just one thing:
    1) You can easily instantiate a class to an object in JAVAFX using a JAVA or JAVAFX class, but in JAVA you can only instantiate JAVA objects.
    (Not completely true. If you really want a headache then you can instantiate JAVAFX classes in JAVA, but it is not easy.)
    Let me give you the following class that contains some variable:
    JAVA
    class MainJava {
         int     blaInt;
         long    blaLong;
         String  someString;
         String  anotherString = "(First Bicycle) Look mom no Hands... Look Mom no teeth.";
         public MainJava() {
             // Before this contructor runs all variables will first be initializes to their default values or whatever you put in them above
             // Construct things :)
         } // END CONSTRUCTOR for MainJava
    } // END CLASS MainJavaJAVAFX
    class MainJavaFx {
         var     blaInt : Integer;
         var     blaLong : java.lang.Long; // The most usefull number made difficult in JAVAFX :(
         var     someString : String;
         var     anotherString = "(First Bicycle) Look mom no Hands... Look Mom no teeth."; // Thats nice. No need for a type :) Heaven ... I'm in Heaven
         init {
             // Before this contructor runs all variables will first be initializes to their default values or whatever you put in them above
             // Construct things :)
         } // END CONSTRUCTOR for MainJava
    } // END CLASS MainJavaFxThese 2 classes are affectively the same.
    One written in Java and one in JAVAFX.
    You already seem to know JAVA so I am going to talk in JAVAFX code from now on.
    1) To instantiate a JAVA class in JAVAFX is the same as in JAVA.
      var myNewObj = new MainJava();2) To instantiate a JAVAFX class in JAVAFX you do the following.
      var myNewObj = MainJavaFx{}; // Weeeee .. easy hey :) I likeThink of init{} as the contractor of the class in JAVAFX, because there is no more constructors in JAVAFX like in JAVA.
    Also in JAVA you can pass parameters to the class constructor, whereas in JAVAFX that is not possible anymore.
    So sad, but what JAVAFX taketh away ... JAVAFX giveth so muchth moreth ... th...
    Now witness the power of ... JAVAFX ...
    In JAVAFX you can instantiate any "var" variables when you create the object from the class.
    Therefore you do not need to pass parameters to the init constructor, most of the time you do not even need init.
    So lets say you want to give the class variable other default values in the JAVAFX class then you can do it like this:
      var myNewObj = MainJavaFx{ 
                                                   blaLong : java.lang.System.currentTimeMillis()
                                                   blaInt : 1234
                                                   someString : "Going to the Hospital I see"
                                                   anotherString : "Thorry Mom."
                                          }; // Weeeee .. easy hey :) I likeNow isn't that nice.
    Keep in mind that the init{} and postinit{} code blocks will only run if they exist after the object is created and therefore the variables will already be changed to the values you have given them when you instantiated the class.
    Cool hey :)
    You can not do that to a JAVA object, but then again if you need to change the class variables of a JAVA object then just create a constructor that takes paramaters and update the class variables in the constructor.

  • Diff bet init() and init(ServletConfig config)

    Hi,
    What is the difference between servlet init() and init(ServletConfig config) ?

    Under recent versions of the servlet spec, init(config) does some internal stuff (such as saving the config), then calls init().
    So under most circumstances, you should override init(), and won't have reason to override init(config). If you do override init(config), then you should make sure it invokes super(config).

  • Difference between Null and null?

    What is the difference between null and NULL?
    When is each used?
    Thanks,

    veryConfused wrote:
    There is a null in java, but no NULL. null means no value. However, when assigning value, the following is different:Although the empty String has no special role. Null means, the referential type is not assigned (doesn't refer) to a specific object. The empty String is just another object though, so seeing it or pointing it out as something special when it actually isn't at all (no more special than new Integer(0) or new Object[0]) just adds to the confusion.

  • Difference in Null and Empty String

    Hi,
    I have been wondering about the difference between Null and Empty String in Java. So I wrote a small program like this:
    public class CompareEmptyAndNullString {
         public static void main(String args[]) {
              String sNull = null;
              String sEmpty = "";
              try {
                   if (sNull.equalsIgnoreCase(sEmpty)) {
                        System.out.println("Null and Empty Strings are Equal");
                   } else {
                        System.out.println("Null and Empty Strings are Equal");
              } catch (Exception e) {
                   e.printStackTrace();
    This program throws Exception: java.lang.NullPointerException
         at practice.programs.CompareEmptyAndNullString.main(CompareEmptyAndNullString.java:10)
    Now if I change the IF Clause to if (sEmpty.equalsIgnoreCase(sNull)) then the Program outputs this: Null and Empty Strings are Equal
    Can anyone explain why this would happen ?
    Thanks in Advance !!

    JavaProwler wrote:
    Saish,
    Whether you do any of the following code, the JUnit Test always passes: I mean he NOT Sign doesnt make a difference ...
    assert (! "".equals(null));
    assert ("".equals(null));
    You probably have assertions turned off. Note the the assert keyword has nothing to do with JUnit tests.
    I think that older versions of JUnit, before assert was a language keyword (which started in 1.4 or 1.5), had a method called assert. Thus, if you have old-style JUnit tests, they might still compile, but the behavior is completely different from what it was in JUnit, and has nothing to do with JUnit at all.
    If you turn assertions on (-ea flag in the JVM command line, I think), the second one will throw AssertionError.

  • Difference between GUI_UPLOAD and WS_UPLOAD

    Hi,
    Please make me clear about the difference between GUI_UPLOAD and WS_UPLOAD. In which cases we need to use these modules...??
    Thanks,
    Satish

    I would suggest to always use the GUI_UPLOAD.  I say this because this is the function module which is used in the GUI_UPLOAD method of the class CL_GUI_FRONTEND_SERVICES.   Really, you should probably use the class/method instead of the function module.
      data: filename type string.
      filename = p_file.
      call method cl_gui_frontend_services=>gui_upload
             exporting
                  filename                = filename
                  filetype                = 'ASC'
             changing
                  data_tab                = iflatf
             exceptions
                  file_open_error         = 1
                  file_read_error         = 2
                  no_batch                = 3
                  gui_refuse_filetransfer = 4
                  no_authority            = 6
                  unknown_error           = 7
                  bad_data_format         = 8
                  unknown_dp_error        = 12
                  access_denied           = 13
                  others                  = 17.
    Regards,
    Rich Heilman

Maybe you are looking for

  • Mapping problem in idoc

    Hi   I had a source segment E1EDP20 (0---99 occurences), i need to pass a constant value to target field poitem.   the requirement is on every occurence of  E1EDP20, the constant value should be incremented by 1 and that constant should be passed to

  • [SOLVED] Refresh rate, nvidia and Quake Live

    I need help setting my monitor to 120HZ for 640*480, i have no idea how to do this using xorg.conf or nvidia-settings... nvidia-settings only shows as high as 85hz for this resolution. I'm not gonna be mean and say how simple doing this is in windows

  • Reservation reduction on production order without goods issue

    At our plants we have a kanban approach where component materials are issued to any available production order as an unplanned GI instead of to a specific production order as a planned GI. This causes component demand to be overstated because the res

  • Cannot download secure websites after upgrading. (had to register using IE)

    I was having a lot of problems with secure websites, getting messages that secure connection failed. Finally got message to upgrade to latest version to solve the problem. Now I cannot access 'any secure website ( banking, credit card, store checkout

  • Service order process step by step

    dear friends, pls explain service order process flow step by step reg   eswar