Java Package/Class Dependency

Hi, friends,
I would like to get a list of packages that a given package depends on. If it is possible, I would also know which class of the given package depends on which classes.
Is there any software to do this?
If I would like to write a Java utility for that purpose, how can I proceed?
Best regards,
Youbin

in the HTML fles of the java doc, you can know the class hierarchy and antecedents of each class. For example, class JComponent :
java.lang.Object
|
--java.awt.Component
|
--java.awt.Container
|
--javax.swing.JComponent
Moreover, the java doc also show the inner classes, fields and methods inherited from those super classes...
you may also know which classes extends this one. For example JComponent :
All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable
Direct Known Subclasses:
AbstractButton, BasicInternalFrameTitlePane, Box, Box.Filler, JColorChooser,
JComboBox, JFileChooser, JInternalFrame, JInternalFrame.JDesktopIcon, JLabel,
JLayeredPane, JList, JMenuBar, JOptionPane, JPanel, JPopupMenu, JProgressBar,
JRootPane, JScrollBar, JScrollPane, JSeparator, JSlider, JSpinner, JSplitPane,
JTabbedPane, JTable, JTableHeader, JTextComponent, JToolBar, JToolTip, JTree,
JViewport
vincent

Similar Messages

  • Java packages and dependency

    When java was being developed, what was the philosophy behind allowing packages to be mutually dependent?

    Hello Steve,
    The Acyclic Dependencies Principle tells us that no cycles should exit in a model depicting the dependencies between packages. From what I can gather this is useful when developing large software systems, as each package becomes a viable work unit for an engineer or small group of engineers to control as a series of releases. If the ADP is not complied with, cycles may exist in the dependencies between packages. If a change is made to one of those packages within a cycle, then an ugly situation develops as the repercussions of the change are looped through the cycle back to its source and so on.
    The thing is though, during my readings I came across a statement that said Java packages were mutually dependent. I was just wanting to know why a language that utilises object oriented technology, left the practice of the ADP up to the descretion of the developer? Is the full implementation of ADP on a software system an ideal world scenario?
    Anders.

  • Compiling java package class referring a default package class.

    I am trying to compile a java class having a package defination referring a java class with a default package.
    The code for the default package class is .
    public class Test{.
    public static void main(String[] args){
    System.out.println("Hello World!");
    This class compiles fine.
    I have another class called PackJava, whose code is :
    package test;
    import Test;
    public class PackJava{
    public static void main(String[] args){
    Test test = new Test();
    System.out.println("Hello World!");
    I have Test file in the windows path
    D:\development\packagetest\example
    and the PackJava java file in the path
    D:\development\packagetest\example\test
    I have set the CLASSPATH environment varibale as
    D:\development\packagetest\example;.
    When I try to compile the PackJava from the
    D:\development\packagetest\example path giving the command as
    javac -classpath . test\PackJava.java
    or
    javac -classpath %CLASSPATH% test\PackJava.java
    it gives me error,
    Do any of you have an idea of the parameter i should pass
    to the -classpath option
    Thanks

    There is a way around all this. The classes in the default packages need to implement an interface with the methods require. The interface can be in any package you want ie. com.work.around.interf.MyInterface1. Next, make this interface available in a Singleton. - The only catch here is that, the main method must reside in default package as well. And o, on start of main, instantiate the class you want and put it in the singleton. There after, you may refer to it from the singleton.
    Enjoy.

  • Java package class access

    Hi All,
    I have two packages in a webapplication. com.mycompany.myapp and com.mycompany.myapp.classbank.
    I set up the application so I have a package for re-usable classes(myapp.classbank) and the other for the backing beans for my pages and the session bean and application bean etc(myapp).
    I can get access to any objects methods from the classes in myapp but I cannot get access to the methods in say the sessionbean from the classbank classes.
    Code completion shows access to the sessionbeans methods but I always get a null pointer exception when the app is run / debugged.
    Any insight would be most helpful.
    Regards
    Jim

    Thanks All,
    I can access any of the sessionbeans variables through the public getters and setters from any other class in the same package. If I try to access any of the same member variables from any class in the second package I get the null pointer... I can see each time the line of code that throws the exception. Its always the first line of code to try to access a getter or setter in the session bean from the second package.
    An example error (Tomcat 5.5.17 NetBeans 5.5) from today below :
    Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
    at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:150)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:92)
    ... 29 more
    Caused by: java.lang.NullPointerException
    at com.mycompany.imageshop.classbank.ShoppingBasket.setNumberOfPictures(ShoppingBasket.java:498)
    at com.mycompany.imageshop.viewBasket.incSmallQuantityButton_action(viewBasket.java:1094)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:146)
    ... 30 more
    Oct 15, 2007 11:36:24 AM org.apache.catalina.core.ApplicationContext log
    SEVERE: #{viewBasket.incSmallQuantityButton_action}: javax.faces.el.EvaluationException: java.lang.NullPointerException
    javax.faces.FacesException: #{viewBasket.incSmallQuantityButton_action}: javax.faces.el.EvaluationException: java.lang.NullPointerException

  • Where should i add the java packages class path in the ORACLEJDeveloper 10g

    Hello friends,
    I have created a BPEL Program using java embedding activity.
    In it i have added some java code.
    I want to attach path of some java class packages.
    So can any one tell me solution for this.
    Thanks and regards.
    Ram Krishna Tripathi
    [email protected]

    Hello friends,
    I have made a Bpel program in oracle process manager 10.1.2 . using java
    embedding activity.
    (i) I have put the java class files in BPEL-INF /classes folder and
    SYSTEM/classes folder but still compiler is giving error that classes
    couldnot be found.
    I have set the class path in Project -> properties
    So please tell me what could be solution for this problem..
    (ii) Can the import package statements can be written in BPEL program in the
    java embedding activity ?
    Thanks and regards
    Ram Krishna Tripathi
    [email protected]

  • How to find classes in a java package

    i am writing a java IDE. i want to extract all class names from a java package eg. java.lang (through coding). how can i do that.
    Thanks in advance

    File file = new File("path to your jar file");
    JarFile jf = new JarFile(file);
    Enumeration e = jf.entries();
    ZipEntry ze = null;
    while(e.hasMoreElements()){
    ze = (ZipEntry) e.nextElement();
    ze.toString(); // gives you the file name
    you have to understand java.util.jar java.util.zip packages for working with jar/zip files.
    Hope this helps

  • In search of java class dependency utility

    Folks,
    We have developed a J2EE application where the "client" is a java
    application. In other words, we have created a JAR file that a user
    uses to launch our application. The manifest for this JAR file has a
    "Main-Class" attribute, so the following command is used to launch the
    (client side of) the application:
    java -jar our.jarOur entire application (both client-side and server-side) consists of
    several hundred classes. Our problem is that we don't have an accurate
    list of which classes are client-side only, which classes are
    server-side only, and which classes are required by both (client-side
    and server-side). I want our client-side JAR to only contain classes
    required by the client. Currently, we are simply bundling all the
    classes into "our.jar".
    I have found (and tried) several utilities, including:
    http://depfind.sourceforge.net/
    http://www.clarkware.com/software/JDepend.html
    http://www.horstmann.com/articles/BetterCleaner.html
    However, I don't think these are suitable. You need to supply a class
    name, and they only tell you the classes that either depend on the
    given class, or that the given class depends on. What I want is a
    "recursive" dependency finder.
    For example, let's say I have class "A". Class "A" depends on class "B"
    (in other words, class "A" needs to import class "B"). Now class "B"
    depends on class "C" and class "C" depends on class "D". Also, we have
    class "E" that depends on class "A" (in other words, class "E" needs to
    import class "A").
    The tools I mentioned above will only return (at most), classes "B" and
    "E" (when I supply them with class "A"), but what I really need them to
    return is classes "B","C" and "D" (and not necessarily class "E").
    Does anyone know how I can achieve this?
    Thanks (in advance),
    Avi.

    ClassDep from jini provides the same functionality as GenJar but I have found it better to work with. You do not need ant to run it although it does come with an ant task. ClassDep.java has a public static void main (String[] args ).
    http://java.sun.com/products/jini/2.0/doc/api/com/sun/jini/tool/ClassDep.html provides the documentation on how to use it.

  • Does Java package has Model class?

    I found the following code below from http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/web-tier/web-tier5.html. The problem is there is no Model class during the java compilation. I thought it is included in the Java package. Anyway, I was fail to import the Model class from java.lang.Object, java.awt, java.awt.event.*, javax.swing.*, java.util.*, and so on. Does Model class belong to Java package or self create?
    // Action.java:
    public abstract class Action {
      protected Model model;
      public Action(Model model) { this.model = model; }
      public abstract String getName();
      public abstract Object perform(HttpServletRequest req);
    // CreateUserAction.java:
    public class CreateUserAction extends Action {
      public CreateUserAction(Model model) {
        super(model);
      public String getName() { return "createUser"; }
      public Object perform(HttpServletRequest req) {
        return model.createUser(req.getAttribute("user"),
                      req.getAttribute("pass"));
    }

    No, it's not a Java SDK class, and it doesn't self-create. It must be part of the blueprints download, so you'll have to find where it is (a JAR file you've downloaded, perhaps) and put it in the CLASSPATH.

  • Instance of one of implementations of abstract class depending on context??

    Hi all,
    I just wonder if it is possible in Java to call creation of a new instance of an implementation of an abstract class depending on context.
    I mean something like:
    abstract class Abstract
    //1st implementation of Abstract class
    class Concrete1 extends Abstract
    //2nd implementation of Abstract class
    class Concrete2 extends Abstract
    }And now, somewhere else in the code, I would really need to call something like this:
    Abstract test1 = new ...(); //here I need sometimes to be created instance of Concrete1, sometimes instance of Concrete2
    Is there a way how to do this??

    Some more concrete code if it helps:
    Abstract class:
    * Individual.java
    * Created on 21. leden 2007, 1:08
    package genetics;
    * Abstract class defining fields and methods of one individual for genetic algorithms
    * This class is supposed to be implemented according to problem to be solved
    * @author Richard V�tek
    * @version 1.0
    abstract public class Individual implements Comparable<Individual>
       * Create random chromosomes for this individual
      protected abstract void createRandomChromosomes();
       * Count fitness of this individual
       * This number says how good is this individual (the higher number the better).
       * Better fitness means that this individual is closer to solution.
       * @return  int   Fitness of this individual
      protected abstract int getFitness();
       * Cross-breed this individual with another individual
       * This leaves untouched number of chromosomes to certain (randomly generated) position.
       * From this position on, it will swap chromosomes between this and another individual.
       * So this individual gets changed (cross-breeded) as well as the other, which is returned
       * as result of this method.
       * @param   other              The other individual to cross-breed with
       * @return  Individual         Hybrid of this and another individual (in fact, the other individual
       *                             after cross-breed (this (source) individual gets changed too after cross-breed)
      protected abstract Individual crossbreed(Individual other);
       * Mutate this individual
       * Mutate chromosomes of this individual; every chromosome is mutated
       * with probability set in settings of evolution.
       * This probability is supposed to be quite low number, roughly 1 %.
      protected abstract void mutate();
       * Check this individual
       * Check if this individual still suits the assignment.
       * If not, repair this individual to suit it again.
      protected abstract void check();
       * Implementation of Comparable: comparing of individuals by fitness
       * @param other Another individual to compare
      public int compareTo(Individual other)
        return this.getFitness() - other.getFitness();
    One implementation class:
    * KnapsackIndividual.java
    * Created on 21. leden 2007, 1:41
    package genetics;
    import java.util.Random;
    import java.util.TreeMap;
    import knapsack.KnapsackProblem;
    * This is practically the same as KnapsackProblem class but designed specially
    * for solving knapsack problem with genetic algorithm so all unnecessary fields
    * and methods are removed.
    * @author Richard V�tek
    * @version 1.0
    public class KnapsackIndividual extends Individual
       * Chromosomes of this individual
       * In case of knapsack problem, they are things currentl in knasack
      protected boolean[] arrChromosomes;
       * Cached value of fitness of this individual
       * Used to not to count fitness of this individual everytime when needed
       * (and it is often needed); once counted, it will be read from this cached value
      private int intFitnessCache = Integer.MIN_VALUE;
       * Randomizer for random-driven methods (like mutation, etc.)
      private Random randomizer = new Random();
       * Reference to evolution to read mutation probability from
      protected Evolution evolution;
       * Assignment of problem instance
      protected KnapsackProblem assignment;
       * Create a new Individual instance
       * @param   assignment  Object representing assignment of particular problem
       * @param   evolution   Reference to evolution object to be able to read evolution's settings from
      public KnapsackIndividual(KnapsackProblem assignment, Evolution evolution)
        this.assignment = assignment;
        this.evolution = evolution;
        this.arrChromosomes = new boolean[assignment.getNumberOfThings()];
       * Create random chromosomes for this individual
       * @see Individual#createRandomChromosomes()
      protected void createRandomChromosomes()
        int intChromosomeCount = this.arrChromosomes.length;
        for (int i = 0; i < intChromosomeCount; i++)
          this.arrChromosomes[i] = this.randomizer.nextBoolean();
       * Get fitness of this individual
       * In case of knapsack, fitness is sum of prices of all things currently in knapsack
       * @see Individual#getFitness()
      protected int getFitness()
        //if cached value exist, return it
        if (this.intFitnessCache != Integer.MIN_VALUE)
          return this.intFitnessCache;
        //otherwise, count fitness of this individual
        int intChromosomeCount = this.arrChromosomes.length;
        int intSumOfValues = 0;
        //in case of knapsack, fitness is value of all things currently in knapsack
        //(sum of values of all things in knapsack)
        for (int i = 0; i < intChromosomeCount; i++)
          intSumOfValues = this.assignment.arrPrices;
    //save counted fitness to cache
    this.intFitnessCache = intSumOfValues;
    return intSumOfValues;
    * Cross-breed two individuals
    * @param other The other individual for cross-breed
    * @return The other individual after cross-breed (but this individual is affected too)
    * @see Individual#crossbreed()
    protected Individual crossbreed(Individual other)
    int intChromosomeCount = this.arrChromosomes.length;
    //position from which on swap chromosomes of this and the other individual
    int intCrossbreedPosition = this.randomizer.nextInt(intChromosomeCount);
    boolean booTemp;
    //swap chromosomes from cross-breed position on
    for (int i = intCrossbreedPosition; i < intChromosomeCount; i++)
    booTemp = ((KnapsackIndividual) this).arrChromosomes[i];
    ((KnapsackIndividual) this).arrChromosomes[i] = ((KnapsackIndividual) other).arrChromosomes[i];
    ((KnapsackIndividual) other).arrChromosomes[i] = booTemp;
    return other;
    * Mutate individual chromosomes of this individual with certain probability
    * In case of knapsack, particular thing is just inserted/taken out of the knapsack
    * @see Individual#mutate()
    protected void mutate()
    //probability of mutation (in percents)
    int intMutationProbability = this.evolution.getMutationProbability();
    int intChromosomeCount = this.arrChromosomes.length;
    //iterate through all chromosomes, mutating them with certain (set) probability
    for (int i = 0; i < intChromosomeCount; i++)
    //mutation probability passed => mutate this chromosome
    if (this.randomizer.nextInt(100) < intMutationProbability)
    this.arrChromosomes[i] = !this.arrChromosomes[i];
    //when mutation finished, we must check if this individual still suits the assignment;
    //if not, repait it
    this.check();
    * Check if this individual still suits the assignment; if not, repair it
    * In case of knapsack it means that sum of weights of things currently in knapsack
    * will not exceed capacity of backpack; if exceeds, take out as many things as necessary
    * to not to exceed again; choose things to be taken out according to worst weight to price ratio
    * @see Individual#check()
    protected void check()
    int intSumOfWeights = 0;
    //list of things in the knapsack sorted by weight to price ratio
    //key: index of thing in knapsack
    //value: weight/price ratio
    TreeMap<Integer, Float> things = new TreeMap<Integer, Float>();
    for (int i = 0; i < this.arrChromosomes.length; i++)
    //thing in the knapsack
    if (this.arrChromosomes[i] == true)
    //add its weight to sum of weights
    intSumOfWeights += this.assignment.arrWeights[i];
    //add it to the list of things sorted by weight to price ratio
    things.put(i, (((float) this.assignment.arrWeights[i]) / ((float) this.assignment.arrPrices[i])));
    //sum of weights exceeds knapsack capacity => take out as many things as necessary
    while (intSumOfWeights > this.assignment.getKnapsackCapacity())
    //take out thing with worst weight/price ratio from all things currently in knapsack
    this.arrChromosomes[things.lastKey()] = false;
    //update sum of weights of things currently in knapsack
    intSumOfWeights -= things.get(things.lastKey());
    //also remove this thing from list of things
    things.remove(things.lastKey());
    And another class, where i need this feature (tried to use generics for that, but they can't be used in this way):
    * Evolution.java
    * Created on 21. leden 2007, 2:47
    package genetics;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
    * Class for algorithms using simulated evolution to deal with a problem
    * Tried to be designed general enough to allow to be used for every genetic algotihm.
    * If true, only class Individual must be implemented according to problem to be solved,
    * the rest of genetic algorithm stays the same.
    * @author Richard V�tek
    * @version
    public class Evolution<Problem, IndividualClass extends Individual>
       * Number of generations of evolution to finish
      protected int intGenerationCount;
       * Number of individuals in each generation
      protected int intGenerationSize;
       * Elite individual count
       * All elite individuals are just copied from one generation to another with no change
      protected int intGenerationEliteCount;
       * Number of individuals participating a tournament
       * To select an good individual for next generation, tournaments are hold.
       * This affects number of individuals which one good individual is selected
       * from in one tournament.
       * @see <a href="http://cs.felk.cvut.cz/%7Exobitko/ga/example_f.html">Genetic Algorithm Example Applet</a>
      protected int intGenerationTournamentSize;
       * Probability of mutation (in percents)
      protected int intMutationProbability;
       * Current generation of individuals in evolution
      protected Generation<IndividualClass> thisGeneration;
       * Next generation of individuals in evolution
      protected Generation<IndividualClass> nextGeneration;
       * Fitness of best individual in this generation
      private int intIndividualBestFitness;
       * Sum of fitnesses of all individuals in this generation
      private int intIndividualsSumFitness;
       * Fitness of worst individual in this generation
      private int intIndividualWorstFitness;
       * Fitness of best elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteBestFitness;
       * Sum of fitnesses of all elite individuals in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualElitesSumFitness;
       * Fitness of worst elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteWorstFitness;
       * Create a new instance of Evolution (settings passed through parameters)
       * @param   intGenerationCount            Number of generation of evolution to finish
       * @param   intGenerationSize             Number of individuals in each generation
       * @param   intGenerationEliteRatio       Elite individuals to generation size ratio (in percents)
       * @param   intGenerationTournamentRatio  Members of tournament to generation size ratio (in percents)
       * @param   intMutationProbability        Probability of mutation of each chromosome of each individual of generation (in percents)
       * @see     #intGenerationEliteCount
       * @see     #intGenerationTournamentSize
      public Evolution(
        int intGenerationCount, int intGenerationSize,
        int intGenerationEliteRatio, int intGenerationTournamentRatio,
        int intMutationProbability)
        this.intGenerationCount = intGenerationCount;
        this.intGenerationSize = intGenerationSize;
        this.intGenerationEliteCount = (int) (intGenerationSize * (intGenerationEliteRatio / 100.0));
        this.intGenerationTournamentSize = (int) (intGenerationSize * (intGenerationTournamentRatio / 100.0));
        this.intMutationProbability = intMutationProbability;
       * Create a new instance of Evolution (settings loaded from settings file)
       * @param   strSettingFile  Name of file containing settings for evolution
       * @throws  IOException     File does not exist, cannot be read, etc.
       * @throws  Exception       Another exception occured during loading of file
      public Evolution(String strSettingFile)
        BufferedReader settings;
        String settingsLine;
        int intLineCounter = 0;
        int intSetting;
        try
          settings = new BufferedReader(new FileReader(strSettingFile));
          while ((settingsLine = settings.readLine()) != null)
            intLineCounter++;
            settingsLine = settingsLine.substring(0, settingsLine.indexOf("\t"));
            intSetting = Integer.parseInt(settingsLine);
            switch (intLineCounter)
              case 1:
                this.intGenerationCount = intSetting;
                break;
              case 2:
                this.intGenerationSize = intSetting;
                break;
              case 3:
                this.intGenerationEliteCount = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 4:
                this.intGenerationTournamentSize = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 5:
                this.intMutationProbability = intSetting;
                break;
            } //switch
          } //while
          //after reading has been completed, let's close the stream
          settings.close();
        } //try
        //IO exception - file not found, cannot be read, etc.
        catch (IOException ioe)
          System.out.println("Vyskytl se I/O probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru " + strSettingFile);
        //Exception - another problem during reading of file
        catch (Exception e)
          System.out.printf("Vyskytl se n&#283;jak� divn� probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru %s. V�pis vyj�mky:\n", strSettingFile);
          e.printStackTrace();
       * Vivify first generation for evolution
       * Necessary number of individuals is created with random chromosomes.
       * Their chromosomes must then be checked if they suit the assignment
       * and if not so, repaired.
      private Generation<IndividualClass> vivifyFirstGeneration()
        //create a brand-new generation
        Generation generation = new Generation<IndividualClass>(this);
        int intTemp;
        //for all individual of this generation
        for (int i = 0; i < this.intGenerationSize; i++)
    //create an individual with no chromosomes
    generation.arrIndividuals[i] = new IndividualClass(this, Problem);
          //create a set of random chromosomes
          neration.arrIndividuals.createRandomChromosomes();
    //if these chromosomes does not suit assignment, repair them
    generation.arrIndividuals[i].check();
    //sort Individuals by fitness so elite individuals get to first positions of array
    Arrays.sort(generation.arrIndividuals);
    //now count statistics for elite individuals (it is enough to count them once,
    //elite don't get changed so their statistics don't get changed either)
    this.intIndividualEliteBestFitness = Integer.MIN_VALUE;
    this.intIndividualElitesSumFitness = 0;
    this.intIndividualEliteWorstFitness = Integer.MAX_VALUE;
    //count statistics for elite individuals
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    intTemp = generation.arrIndividuals[i].getFitness();
    //better fitness than best fitness so far
    if (intTemp > this.intIndividualEliteBestFitness)
    this.intIndividualEliteBestFitness = intTemp;
    //worse fitness than worst fitness so far
    else if (intTemp < this.intIndividualEliteWorstFitness)
    this.intIndividualEliteWorstFitness = intTemp;
    this.intIndividualElitesSumFitness += intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //count generation's statistics also from rest of individuals
    for (int i = this.intGenerationEliteCount; i < this.intGenerationSize; i++)
    updateGenerationStatistics(generation.arrIndividuals[i].getFitness());
    return generation;
    * Get next generation in evolution
    * Core method for all evolution; Through this method, new generation is obtained.
    * Every next generation should contain better individuals than the previous one
    * (till certain point) so with growing number of iterations in evolution, we
    * get better results (till certain point).
    * Everytime all elite individuals are copied to next generation, then hold needed number of
    * tournaments to choose a pair of good-looking individuals, cross-breed individuals in these
    * pairs, mutate them (and repair if necessary) and finally add to next generation.
    * @return Generation Next generation in evolution
    * @see Generation#tournament()
    * @see Generation#crossbreed()
    * @see Generation#mutate()
    private Generation getNextGeneration()
    Generation nextGeneration = new Generation(this);
    //number of pairs of individuals to select for next generation
    int intIndividualPairsToSelect = (this.intGenerationSize - this.intGenerationEliteCount) / 2;
    int intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //just copy all elite individuals from this generation to another
    //(they are on first positions of array of individuals)
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    nextGeneration.arrIndividuals[i] = this.thisGeneration.arrIndividuals[i];
    //hold as many tournaments as necessary to select remaining number of pairs
    //of good-looking individuals for next generation (apart from the elite ones)
    for (int i = 0; i < intIndividualPairsToSelect; i++)
    this.thisGeneration.tournament();
    this.thisGeneration.crossbreed();
    this.thisGeneration.mutate();
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i] = this.thisGeneration.nextGenerationIndividual01;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual01.getFitness());
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i + 1] = this.thisGeneration.nextGenerationIndividual02;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual02.getFitness());
    //next generation is complete => return it
    return nextGeneration;
    * Update statistics of current generations
    * @param intFitness Fitness that may possibly update generation's statistics
    * (best fitness, worst fitness, sum of fitnesses)
    private void updateGenerationStatistics(int intFitness)
    //better fitness than best fitness so far
    if (intFitness > this.intIndividualBestFitness)
    this.intIndividualBestFitness = intFitness;
    //worse fitness than worst fitness so far
    else if (intFitness < this.intIndividualWorstFitness)
    this.intIndividualWorstFitness = intFitness;
    //update sum of fitnesses as well (for average fitness)
    this.intIndividualsSumFitness += intFitness;
    * Execute evolution process
    * Vivify first generation and then as many next generations as set in settings of evolution
    public void evolution()
    this.thisGeneration = vivifyFirstGeneration();
    //output generation's statistics
    System.out.printf("Generace 0:\t%d\t%d\t%d", this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    for (int i = 0; i < this.intGenerationCount; i++)
    this.nextGeneration = getNextGeneration();
    this.thisGeneration = this.nextGeneration;
    //output generation's statistics
    System.out.printf("Generace %d:\t%d\t%d\t%d", i, this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    * Get best fitness of all individuals in this generation
    public int getIndividualBestFitness()
    return intIndividualBestFitness;
    * Get average fitness of all individuals in this generation
    public float getIndividualAverageFitness()
    return (this.intIndividualsSumFitness / (float) this.intGenerationSize);
    * Get worst fitness of all individuals in this generation
    public int getIndividualWorstFitness()
    return intIndividualWorstFitness;
    * Get probability of mutation
    * @return Probability of mutation of each chromosome of every individual in generation (in percents)
    public int getMutationProbability()
    return intMutationProbability;

  • I need the Java IDoc Class Library

    Hi,
    I'm desperately looking for the Java IDoc Class Library. What for? I'm doing a project for university and I have a test version running on my own computer (Mini WAS 6.20 with the FlightBooking example installed). The SAP Service Marketplace is for registered customers only. Since I only have a test environment (mentioned above) I can't register there and download it.
    Could anyone please send me this library by mail, to [email protected] Since I don't know how big this package is: my mail provider has a 15MB/per single mail limit. If biiger, please split.
    Yes, I'm asking for much. But I'm pretty desperate and I have to get going, since I'm running out of time.
    If there are other ways to get this library, please tell.
    Thanks
    Jonny

    Hi Johannes
    The SAP Java IDoc Class Library consists of two parts, the SAP Java Base IDoc Class Library and the SAP Java Connector IDoc Class Library. The SAP Java Base IDoc Class Library provides an API which helps navigating, reading, filling, and modifying IDocs. This base package is middleware independent. Creating, sending, and receiving IDocs is middleware dependent. To make use of the SAP Java Base IDoc Class Library you will need an additional middleware dependent add-on package implementing the defined interfaces like the SAP Java Connector IDoc Class Library.
    The SAP JCo can be downloaded from the   
    https://websmp101.sap-ag.de/~form/sapnet?_SHORTKEY=01100035870000463649
    of SAP JCo. The SAP JCo package includes the software as well as documentation, tutorial, and examples. The SAP Java IDoc Class Library can be downloaded from the same URL, and then follow the link to SAP Java IDoc Class Library. The SAP Java IDoc Class Library packages include the software as well as documentation.

  • Help! How to create Jar file for a packaged class?

    Hi!
    I am new in jar complexities. I made a swing frame that just prompts a JOptionPane when executed. I accomplished the same using jar without packaging my class SwingTest.
    But when i package it, it doesn't run. Can any one tell me how to make jar file of packaged classes and include images in the jar files too!
    Really Thanx!

    Call the Jar from the commandline to see the exceptions thrown.
    java -jar <jarFileName> <className>

  • Error: could not be converted to [class java.lang.Class].

    I am newbie to JDeveloper (10.1.2) on winxp and i was trying to setup the example from the following url http://radio.weblogs.com/0129487/2003/09/19.html
    It is a how to on "Executing Toplink Queries using JavaBean DataControl "
    Any help would be greatly appreciated.
    Near the bottom on step "In StrutsPageFlow diagram, select allEmpsDA Data Action, right mouse and chooe Run" i get a the following runtime errors:
    Validation Error
    You must correct the following error(s) before proceeding:
    JBO-29000: Unexpected exception caught: oracle.jbo.JboException, msg=JBO-29000: Unexpected exception caught: oracle.toplink.exceptions.ConversionException, msg= Exception Description: The object [mypackage.Employees], of class [class java.lang.String], could not be converted to [class java.lang.Class]. Please ensure that the class [class java.lang.Class] is on the CLASSPATH. You may need to use alternate API passing in the appropriate class loader as required, or setting it on the default ConversionManager Internal Exception: java.lang.ClassNotFoundException: mypackage.Employees
    JBO-29000: Unexpected exception caught: oracle.toplink.exceptions.ConversionException, msg= Exception Description: The object [mypackage.Employees], of class [class java.lang.String], could not be converted to [class java.lang.Class]. Please ensure that the class [class java.lang.Class] is on the CLASSPATH. You may need to use alternate API passing in the appropriate class loader as required, or setting it on the default ConversionManager Internal Exception: java.lang.ClassNotFoundException: mypackage.Employees
    Exception Description: The object [mypackage.Employees], of class [class java.lang.String], could not be converted to [class java.lang.Class]. Please ensure that the class [class java.lang.Class] is on the CLASSPATH. You may need to use alternate API passing in the appropriate class loader as required, or setting it on the default ConversionManager Internal Exception: java.lang.ClassNotFoundException: mypackage.Employees

    This error is happening on a read.
    Here is the mapping descriptor:
    <database-mapping>
    <attribute-name>SuppItemCollection</attribute-name>
    <read-only>false</read-only>
    <reference-class>package.SuppItem</reference-class>
    <is-private-owned>false</is-private-owned>
    <uses-batch-reading>false</uses-batch-reading>
    <indirection-policy>
    <mapping-indirection-policy>
    <type>oracle.toplink.internal.indirection.NoIndirectionPolicy</type>
    </mapping-indirection-policy>
    </indirection-policy>
    <container-policy>
    <mapping-container-policy>
    <container-class>java.util.Vector</container-class>
    <type>oracle.toplink.internal.queryframework.ListContainerPolicy</type>
    </mapping-container-policy>
    </container-policy>
    <source-key-fields>
    <field>SUPP.REQ_NUM</field>
    </source-key-fields>
    <target-foreign-key-fields>
    <field>SUPP_ITEM.REQ_NUM</field>
    </target-foreign-key-fields>
    <type>oracle.toplink.mappings.OneToManyMapping</type>
    </database-mapping>
    Object model has a Supp class that has a collection of SuppItem(s). I was allowing the Mapping Workbench to create the Java Source. I'm not to fond of that, but I thought it would be easiest to get things going.
    The datamodel is similiar to the class model.
    Thanks for the help,
    Mike

  • Java Error in RFC Lookup in XSLT Mapping usinf Java helper class

    Hi All,
    I am doing RFC Lookup in XSLT Mapping using Java Helper class.
    The Lookup works fine when called one RFC at a time However my requirement is I want to do 2 Lookups.
    Both Lookups works when done individually however when I call both lookups in one mapping I get following error "javax.xml.transform.TransformerException: DOMSource whose Node is null."
    Following is the code I have written in XSLT for the lookup:
         <xsl:template name="Lookup_1">
              <xsl:param name="STDPN"/>
                   <rfc:RFC_READ_TABLE>
                        <QUERY_TABLE>KNA1</QUERY_TABLE>
                        <OPTIONS><item><TEXT>
                                  <xsl:value-of select="$STDPN"/>
                             </TEXT></item>
                        </OPTIONS>
                        <FIELDS>
                             <item>
                                  <FIELDNAME>KUNNR</FIELDNAME>
                             </item>
                        </FIELDS>
                   </rfc:RFC_READ_TABLE>
              </xsl:variable>
              <xsl:variable name="response" xmlns:lookup="java:urn.mt.pi" select="lookup:execute($request, 'BS_D, 'cc_RfcLookup', $inputparam)"/>
              <xsl:element name="STDPN">
                   <xsl:value-of select="$response//DATA/item/WA"/>
              </xsl:element>
         </xsl:template>
         <xsl:template name="Lookup_2">
              <xsl:param name="BELNR"/>
                   <xsl:variable name="Query">AGMNT = '<xsl:value-of select="$BELNR"/>'</xsl:variable>
                   <xsl:variable name="request1">
                        <rfc:RFC_READ_TABLE>
                             <QUERY_TABLE>ZTABLE</QUERY_TABLE>
                             <OPTIONS><item><TEXT>
                                  <xsl:value-of select="$Query"/>
                                  </TEXT></item>
                             </OPTIONS>
                             <FIELDS>
                                  <item>
                                       <FIELDNAME>KUNAG</FIELDNAME>
                                  </item>
                             </FIELDS>
                        </rfc:RFC_READ_TABLE>
                   </xsl:variable>
                   <xsl:variable name="response1" xmlns:lookup="java:urn.mt.pi" select="lookup:execute($request1, 'BS_D','cc_RfcLookup', $inputparam)"/>
                   <xsl:element name="BELNR">
                        <xsl:value-of select="$response1//DATA/item/WA"/>
                   </xsl:element>
         </xsl:template>
    My Question: Am I doing anything wrong? Or Is it possible to call multiple lookups in one XSLT?
    Thanks and Regards,
    Atul

    Hi Atul,
    I had the same problem like you had.
    The main Problem is that with the example code the request variable is created as NodeList object. In XSLT a variable is somekind of a constant and can't be changed. As the request object is empty after the first request the programm fails at the following line:
    Source source = new DOMSource(request.item(0));
    So I've created a workaround for this problem.
    In the call of the template I've put the request as a parameter object at the template call:
    <xsl:with-param name="req">
    <rfc:PLM_EXPLORE_BILL_OF_MATERIAL xmlns:rfc="urn:sap-com:document:sap:rfc:functions">
      <APPLICATION>Z001</APPLICATION>
      <FLAG_NEW_EXPLOSION>X</FLAG_NEW_EXPLOSION>
      <MATERIALNUMBER><xsl:value-of select="value"/></MATERIALNUMBER>
      <PLANT>FSD0</PLANT>
      <VALIDFROM><xsl:value-of select="//Recordset/Row[name='DTM-031']/value"/></VALIDFROM>
      <BOMITEM_DATA/>
    </rfc:PLM_EXPLORE_BILL_OF_MATERIAL>
    </xsl:with-param>
    With this change the request will be provided as a String object and not as a NodeList object.
    Afterwards the RfcLookup.java has to be changed to the following:
    package com.franke.mappings;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import com.sap.aii.mapping.lookup.Channel;
    import com.sap.aii.mapping.api.StreamTransformationConstants;
    import com.sap.aii.mapping.api.AbstractTrace;
    import com.sap.aii.mapping.lookup.RfcAccessor;
    import com.sap.aii.mapping.lookup.LookupService;
    import com.sap.aii.mapping.lookup.XmlPayload;
    * @author Thorsten Nordholm Søbirk, AppliCon A/S
    * Helper class for using the XI Lookup API with XSLT mappings for calling RFCs.
    * The class is generic in that it can be used to call any remote-enabled
    * function module in R/3. Generation of the XML request document and parsing of
    * the XML response is left to the stylesheet, where this can be done in a very
    * natural manner.
    * TD:
    * Changed the class that request is sent as String, because of IndexOutOfBound-exception
    * When sending multiple requests in one XSLT mapping.
    public class RfcLookup {
         * Execute RFC lookup.
         * @param request RFC request - TD: changed to String
         * @param service name of service
         * @param channelName name of communication channel
         * @param inputParam mapping parameters
         * @return Node containing RFC response
         public static Node execute( String request,
                 String service,
                 String channelName,
                 Map inputParam)
              AbstractTrace trace = (AbstractTrace) inputParam.get(StreamTransformationConstants.MAPPING_TRACE);
              Node responseNode = null;
              try {
                  // Get channel and accessor
                  Channel channel = LookupService.getChannel(service, channelName);
                  RfcAccessor accessor = LookupService.getRfcAccessor(channel);
                   // Serialise request NodeList - TD: Not needed anymore as request is String
                   /*TransformerFactory factory = TransformerFactory.newInstance();
                   Transformer transformer = factory.newTransformer();
                   Source source = new DOMSource(request.item(0));
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                   StreamResult streamResult = new StreamResult(baos);
                   transformer.transform(source, streamResult);*/
                    // TD: Add xml header and remove linefeeds for the request string
                    request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+request.replaceAll("[\r\n]+", ""); 
                    // TD: Get byte Array from request String to send afterwards
                    byte[] requestBytes = request.getBytes();
                   // TD: Not used anymore as request is String
                    //byte[] requestBytes = baos.toByteArray();
                    trace.addDebugMessage("RFC Request: " + new String(requestBytes));
                    // Create input stream representing the function module request message
                    InputStream inputStream = new ByteArrayInputStream(requestBytes);
                    // Create XmlPayload
                    XmlPayload requestPayload =LookupService.getXmlPayload(inputStream);
                    // Execute lookup
                    XmlPayload responsePayload = accessor.call(requestPayload);
                    InputStream responseStream = responsePayload.getContent();
                    TeeInputStream tee = new TeeInputStream(responseStream);
                    // Create DOM tree for response
                    DocumentBuilder docBuilder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
                    Document document = docBuilder.parse(tee);
                    trace.addDebugMessage("RFC Response: " + tee.getStringContent());
                    responseNode = document.getFirstChild();
              } catch (Throwable t) {
                   StringWriter sw = new StringWriter();
                   t.printStackTrace(new PrintWriter(sw));
                   trace.addWarning(sw.toString());
              return responseNode;
         * Helper class which collects stream input while reading.
         static class TeeInputStream extends InputStream {
               private ByteArrayOutputStream baos;
               private InputStream wrappedInputStream;
               TeeInputStream(InputStream inputStream) {
                    baos = new ByteArrayOutputStream();
                    wrappedInputStream = inputStream;
               * @return stream content as String
               String getStringContent() {
                    return baos.toString();
              /* (non-Javadoc)
              * @see java.io.InputStream#read()
              public int read() throws IOException {
                   int r = wrappedInputStream.read();
                   baos.write(r);
                   return r;
    Then you need to compile and upload this class and it should work.
    I hope that this helps you.
    Best regards
    Till

  • Servlet cannot invoke package classes

    I have two class which is authenticateController and userAuthentication store in authencation package with path WEB-INF/class/authentication/.
    My jvm is unable compile authenticateController in authentication directory but it is not problem in path WEB-INF/class/.
    authenticateController.java
    package authentication;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import authentication.*;
    public class authenticateController extends HttpServlet {
         //Initialize global variables
         public void init() throws ServletException {
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              doPost(request,response);   
         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              //RequestDispatcher dispatcher = request.getRequestDispatcher("userAuthentication");
              //dispatcher.forward(request,response);     
              String usrnme = request.getParameter("usrnme");
              String password = request.getParameter("password");
              userAuthentication obj = new userAuthentication(usrnme, password);
              if(obj.getResult()) {
                   HttpSession session = request.getSession();
                   session.setAttribute("authenticateUser",usrnme);
                   response.sendRedirect("/developmentLine/userId/authentication/queryresult.jsp");
              else {
                   response.sendRedirect("/developmentLine/userId/authentication/login.jsp");
         //Clean up resources
             public void destroy() {
    }Any problem in my code?

    ok, this is compile error msg. I am using notepad and window cmd to compile. I able compile in classes directory (/WEB-INF/classes/) but once i move it into authentication subdirectory (/WEB-INF/class/authentication/), the authenticateController occur error msg as below.
    C:\WebJsp\servletlibrary\WEB-INF\classes\authentication>javac authenticateController.java
    authenticateController.java:28: cannot find symbol
    symbol  : class userAuthentication
    location: class authentication.authenticateController
                    userAuthentication obj = new userAuthentication(usrnme, password
                    ^
    authenticateController.java:28: cannot find symbol
    symbol  : class userAuthentication
    location: class authentication.authenticateController
                    userAuthentication obj = new userAuthentication(usrnme, password
                                                 ^
    2 errors
    C:\WebJsp\servletlibrary\WEB-INF\classes\authentication>This is the userAuthentication.java
    package authentication;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.Hashtable;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import javax.naming.*;
    public class userAuthentication{
         private int totalResults;
         public userAuthentication(String usrnme, String password) {
              Hashtable env = new Hashtable();          
              String adminName = "MyCompany\\"+usrnme;
              String adminPassword = password;
              String ldapURL = "ldap://LDAPSERVER";
              //Access the keystore, this is where the Root CA public key cert was installed
              //Could also do this via the command line option java -Djavax.net.ssl.trustStore....
              //No need to specifiy the keystore password for read operations
              env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
              //set security credentials
              env.put(Context.SECURITY_AUTHENTICATION,"simple");
              env.put(Context.SECURITY_PRINCIPAL,adminName);
              env.put(Context.SECURITY_CREDENTIALS,adminPassword);
              //connect to my domain controller
              env.put(Context.PROVIDER_URL,ldapURL);
              try {
                   // Create the initial directory context
                   DirContext ctx = new InitialLdapContext(env,null);
                   //Create the search controls           
                   SearchControls searchCtls = new SearchControls();
                   //Specify the attributes to return
                   String returnedAtts[]={"sn","givenName","mail","sAMAccountName","userPrincipalName","mailNickname","streetAddress"};
                   searchCtls.setReturningAttributes(returnedAtts);
                   //Specify the search scope
                   searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                   //specify the LDAP search filter
                   //mailNickname and sAMAccountName is same, but sAMAccountName is Old NT 4.0 logon name and it may confuse to CN attribute.
                   String searchFilter = "(&(objectClass=user)(mailNickname="+usrnme+"))";
                   //Specify the Base for the search
                   String searchBase = "DC=MyCompany,DC=com,DC=my";
                   //initialize counter to total the results
                   totalResults = 0;
                   // Search for objects using the filter
                   NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
                   //Loop through the search results
                   while (answer.hasMoreElements()) {
                            SearchResult sr = (SearchResult)answer.next();
                        totalResults++;
                   ctx.close();
              catch (NamingException e) {
                   System.err.println("Problem searching directory: " + e);
         public boolean getResult() {
              if(totalResults == 0)
                   return false;
              else
                   return true;
    }Edited by: webster on Nov 17, 2008 4:49 PM
    Edited by: webster on Nov 17, 2008 4:51 PM

  • Import Java package in JSP

    I hope this is an appropriate forum for this query.
    I want to be able to access a user-created Java package in JSP.
    I have this code:
    <%@page import="TPClass.*" %>
    <%
    xxx = TPClass
    session.setAttribute("response",xxx.GetTPResponse());
    %>
    The error display points to TPClass in the import statement with the message "TPClass not found".
    TPClass files are in the same location as the other project files.
    I have creatyed and compiled the TPClass package.
    Is there more I need to do?
    Brenton

    I think you are very new to java....
    anyway
    <%@page import="class name with full qualified package name"%>
    like
    <%@page import="com.x1.x2.TPClass"%>
    <%
    TPClass cls =new TPClass();
    //then do whatever you want...
    %>
    hope u understand now.....

Maybe you are looking for