~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

As already noted, you can't use the 'new' expression to create a new object at runtime given the way generics are implemented in Java. IMO, the cleanest (type-safe without any warning) approach you can come across can be achieved by passing in the class of the object you have to create. E.g.

private static <T> T addToList(List<T> list, Class<T> klass) {
    T t = null;
    try {
        t = klass.newInstance();
        list.add(t);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return t;
}

But then again, I personally think that having a method given the arbitrary responsibility of creating objects and inserting into Lists is a bit off. Any "practical" scenario you have in mind which requires you to have true generics?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Every example I've seen, the stream has to be flushed, but I don't know why

Some implementations of the OutputStream/Writer (e.g. BufferedWriter) buffer the data written to them and write it to the underlying actual stream only when the buffer is full. This is so as to avoid doing IO for each and every `write` call made and improve performance (IO is typically magnitudes slower than CPU bound operations). `flush` forces the implementation to write the data which it has buffered to the underlying stream.

Read the section 4.1.1 of this document.
http://java.sun.com/docs/books/performance/1st_edition/html/JPIOPerformance.fm.html

Also, as far as your question is concerned, if you are anyways writing objects, instead of owning the headache of mapping values to their respective variables, write out a single object. For e.g. if you want to send across a long value named phoneNumber, a string value named 'name', instead of doing something like:

oos.write("name"); oos.write("string"); oos.write(yourName);
oos.write("phone"); oos.write("long"); oos.write(longValue);

prefer something like this:

Person p = new Person(yourName, longValue);
oos.write(p);
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> Can anyone give me an idea on how to insert multiple record into a database.

Search for "Batch insert JDBC". Links which might interest you:
http://www.java2s.com/Code/Java/Database-SQL-JDBC/BatchUpdateInsert.htm
http://www.jguru.com/faq/view.jsp?EID=5079

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Oh wait, I guess I remember that thread. Wasn't it the one having the contents same as this thread for which you had given a neg rep? It was deleted since it was a dupe, which kinda explains why you couldn't find it. :-)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

What was that thread about? Thread moving / deletion as duplicate is quite frequent around these parts so unless you can remember the contents of the thread or its context, not much can be done. :-)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

AFAIK, you can neither check for the up/down votes given by you nor for the reputation awarded to other members. A real pity, I know, but... :-)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Please do not, I repeat, do not link to any roseindia material. These guys are content thieves and more concerned about driving traffic to their site than imparting knowledge; a bad sign indeed. BTW, the original article is here.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

You always require the fully qualified class name when referring to your class. Try something like:

c:\jcreator>java uniKEY.myLoader
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Your class 'myUI' creates a new 'myFunctions' object and your class 'myFuntions' creates a new 'myUI' object resulting in a never ending loop and hence the program running out of stack space. You need to decide which one comes first, 'myUI' or 'myFunctions' although logically it should be the UI class which gets created first which in turn instantiates the helper 'myFunctions' class object.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Before passing in the File object to the ImageIO#read method, print out its absolute path (File#getAbsolutePath)and verify whether it is the same as the path where you have stored your images.

Edit: Oops, didn't see Norm1's reply. But yes, print out the full path using the getAbsolutePath()

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Search the codebase for "new BookDBAO(" ? But ideally, since you are retrieving the DAO from teh servlet context, the instantiation should have happened in the class which ServletContextListener. Look into your web.xml if you have any listener tags and search in those classes.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

You still haven't answered the question "Where are you initializing the `_myFObj` object"?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Where are you initializing the `_myFObj` object? If the root exception cause is `_myFObj.loadDB();` throwing an exception, then it's pretty clear that `_myFObj` is NULL.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

SOS, I have learned a lot from your poster. The answers are highly appreciated.

You are welcome. Please make sure you mark the thread as solved if your queries have been answered.

Also, it's "post" and not "poster". "Poster" is someone who makes the "post". :-)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

One should declare a String paker[][]= new String[4][13]; to store all (52) the cards

IMO better to have a "Card" class with "rank" and "suit" as member variables. The toString() of this class would take care of concatenating the toString() method output of the respective "card" and "rank" enum members. Here is a simple example taken from the Java specification:

import java.util.*;
public class Card implements Comparable<Card>, java.io.Serializable {
    public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,JACK, 
QUEEN, KING, ACE }
    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
    private final Rank rank;
    private final Suit suit;
    private Card(Rank rank, Suit suit) {
        if (rank == null || suit == null)
            throw new NullPointerException(rank + ", " + suit);
        this.rank = rank;
        this.suit = suit;
    }
    public Rank rank() { return rank; }
    public Suit suit() { return suit; }
    public String toString() { return rank + " of " + suit; }
    // Primary sort on suit, secondary sort on rank
    public int compareTo(Card c) {
        int suitCompare = suit.compareTo(c.suit);
        return (suitCompare != 0 ? suitCompare : rank.compareTo(c.rank));
    }
    private static final List<Card> prototypeDeck = new ArrayList<Card>(52);
    static {
        for (Suit suit : Suit.values())
            for (Rank rank : Rank.values())
                prototypeDeck.add(new Card(rank, suit));
    }
    // Returns a new deck
    public static List<Card> newDeck() {
        return new ArrayList<Card>(prototypeDeck);
    }
}

In API one may see Enum class while in coding one sees enum. Hence I would ask what is the differences between Enum and …

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
I know there's more to this than just helping the OP, etc. But seriously, could this be done? The profile panel of an idiot would then have some sort of icon (only visible to the idiot-applying user of course).

Use the ignore list feature provided by vBulletin. If I've added a member to the ignore list, all the posts by that user would be hidden by default and a message would be shown. Something like:

Access the ignore list feature here .

BTW, you are not on my ignore list, it was just for demonstration purposes. ;-)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

also it gives me nullpointerxception though i have used a if condition specifying (c==null)

This is because the condition is executed after the length check of the for loop. The condition cookie == null needs to be placed outside the FOR loop and not inside it.

when i close my browser and open it for the next time, i should be able to get the value stored in the cookie

Set the maxAge of the cookie accordingly. Have you looked at the docs for the setMaxAge method? It says that the cookie is persisted for the number of seconds you pass in to the setMaxAge method which in your case is only 20. Set it to something higher like 60 * 60 * 24 for persisting the cookie for an entire day.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

No, the data is not "damaged" if the serialization is successful. You can use a debugger to confirm the same (inspect the fields of your de-serialized object). Also, it's not that the == "does not work", it's just that it has a difference purpose than the one which you seek.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

== compares object references or stands for reference equality which would never hold true for objects which are loaded from a serialized file after being saved. The serialization mechanism uses the serialized byte stream to create a *new* object having the same state as the original saved object. Override the equals method of the Object class for your custom classes if you need logical equality.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Yes. Simply put, you have an object (your application) whose behaviour needs to change based on the state of that object (password valid or not). Going back to the example I posted, the 'Application' object has a variable (part of application state) called `validationState`. In order to modify the behaviour of our application, we need to do a couple of things.

Create a common state interface which would the super-type for all the state objects created. So what method should this State interface have? This interface normally harbours methods which are called on your application object. In our case, the method is called `setValidationStage`. This method would be called whenever you need to modify the "state" of your validationStage variable. Since it is the behaviour of this "state change" which we want to abstract, internally, this method would call the relevant "State" object by passing in a reference to self. The difference between the `setValidationStage` method of the `Application` object and the `State` object is that, the State object requires a reference to the `Application` also called as "context" in the wiki article, to modify its behaviour. Hence our State object would have a method called `setValidationStage(Application, ValidationStage)`.

Notice that the reference to state object in the Application is of type `PasswordIndicatorState`. This property would be set to the default state when the application initializes; which in our case is the `DefaultPasswordIndicatorState`. So, how is all this put in action? When the user clicks on the "Validate" button, …

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

This allows you to compress the whiole interface/mutiple state classes thing into a single enum

...thereby making it view dependent and reducing its general purpose usability. IMO, enums are much more useful if treated as data containers rather than behaviour containers since a given enum can be applicable to more than one scenarios. Enum methods generally operate on their state variables without any dependence on the application state.

Also, how would the `paintBox` in your code exactly work? Won't it require some kind of reference to the paint component?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

also I don't understand the point of having this setStatus. it just sets a string right?

I posted an example for your understanding which you'd need to adjust according to your specific needs. The state class normally has an extra parameter which is the reference to the class whose behaviour you would want to control.

I was wondering if I could take up 3 static ints in my UI and use them as enums?

Yes, but enums are better for a lot others reasons, the most important being type safety.

is my code, as you can see the setState has 2 parameters, and my function has only 1 parameter within it. what do you suggest that I do?

It seems that you are still struggling with the concept behind using the state pattern otherwise you wouldn't have asked this question. Read the wiki article again along with this article.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I have an interface with a function, and 3 classes implementing interface...each class doing its own work. now I have to call up interface by making an object of it. then I utilize the function in my frame to call up different class via interface. thats what im assuming.. :/

Sounds good. You just have to make sure that any processing related to state variable which triggers change in state should be delegated to your current state implementation. A trivial example would look something like:

interface PasswordIndicatorState {
    void setValidationStage(Application app, ValidationStage stage);
}

class OkPasswordIndicatorState implements PasswordIndicatorState {
    @Override
    public void setValidationStage(Application app, ValidationStage stage) {
        if(stage == ValidationStage.DEFAULT) {
            app.setStatus("DEFAULT");
            app.setState(new DefaultPasswordIndicatorState());
        }
    }
}

class WrongPasswordIndicatorState implements PasswordIndicatorState {
    @Override
    public void setValidationStage(Application app, ValidationStage stage) {
        if(stage == ValidationStage.DEFAULT) {
            app.setStatus("DEFAULT");
            app.setState(new DefaultPasswordIndicatorState());
        }
    }
}

class DefaultPasswordIndicatorState implements PasswordIndicatorState {
    @Override
    public void setValidationStage(Application app, ValidationStage stage) {
        if(stage == ValidationStage.OK) {
            app.setStatus("OK");
            app.setState(new OkPasswordIndicatorState());
        } else if(stage == ValidationStage.WRONG) {
            app.setStatus("WRONG");
            app.setState(new WrongPasswordIndicatorState());
        }
    }
}

enum ValidationStage {
    DEFAULT, OK, WRONG
}

class Application {

    private PasswordIndicatorState state;

    private String status;

    private ValidationStage validationStage;

    private Application() {
        setState(new DefaultPasswordIndicatorState());
        setValidationStage(ValidationStage.DEFAULT);
    }

    public static Application newApplication() {
        return new Application();
    }

    public void setState(PasswordIndicatorState state) {
        this.state = state;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setValidationStage(ValidationStage stage) {
        this.validationStage = stage;
        this.state.setValidationStage(this, stage);
    }

}
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Depends on the scope of your bean and how your flow is structured. Does the JPS/Servlet which creates the bean is in the same flow as the JSP in which you want to access your bean? Is the bean placed in request/session scope?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

As of Java 6, @Override annotation also works with interface methods implemented by classes.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> How could i post the entire stack trace,

By copy pasting the entire error trace you see in your console. Anyways, have you tried out the suggestions from my previous post? If it still doesn't work, there is nothing I can do from here since this might very well be a firewall/OS configuration issue/any-other-thing.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

It works at my place so it obviously has got something to do with the IP address you are using. Also, try a higher port value, like 8080, to make sure the problem isn't with lower ports being blocked. Also, like I said, post the *entire* stack trace unmodified and not just the first line.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Use getByAddress instead of getByName since you are passing an IP address and not a host name.

byte[] ipBytes = new byte[] { 192, 192, 192, 192 };
InetAddress ip = InetAddress.getByAddress(ipBytes);
ServerSocket server = new ServerSocket(9090, -1, ip);
while(true) {
  Socket client = server.accept();
  // do stuff
}
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

"Crashes the server" isn't a very good description. Post the relevant code along with complete stack trace. Also, you don't pass in your WAN IP but *your* IP (assigned by your ISP or your network).

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> That code wouldn't print anything, you can use Strings and equals

That code will always print "Hello" since both s and the literal "Hello" would refer to the same interned string.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The problem isn't with port but with the host. If you don't pass in a host, it defaults to 0.0.0.0 or 127.0.0.1 (not very sure here); which again gives rise to the scenario I explained in my previous post. Refer the three arg constructor of ServerSocket class for more details.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Are you by any chance spawing the server process by passing in the host as "localhost" or "127.0.0.1"? If yes, then AFAIK you need to replace the same with the IP address assigned by your network in case your friend is in the same network or the IP address assigned by your ISP in case he isn't.

Edit: Don't bump posts, at least not within 24 of posting your post. It'll just make you look demanding/impatient and will detract those trying to help you out.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

So what exactly is EJB? I know the definition, but I can't get what exactly is! Is it the framework?

EJB (Enterpries Java Beans) is a specification drafted for creating "re-usable" business components, in the same way as "Servlet Specification" is used for creating "web components". Think of it as something which enables you develop and package your critical business functionality. The underlying mechanism uses a binary protocol (RMI/IIOP though I'm not sure) as opposed to the verbose and textual HTTP protocol.

A lot of smart people have debated over the uses/mis-uses of EJB; even I could have written down a couple of things but in the end it would just confuse you if you have just started with Java. I'd recommend staying away from EJB's unless you are pretty comfortable with other "more" useful things like the core language, servlet specification etc. :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Yes, that's correct.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

No, I meant i1 since it is the variable which is initialized. Removing or adding the `final` quantifier to i1 changes the way the compiler treats the presented source code. If i1 is made final, the uninitialized state of i2 is acceptable since it is anyways going to get initialized in teh IF block. If not, the user is presented with a compile time error.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

If i1 is not declared `final`, the compiler has no way of knowing in advance that the value of i1 won't change; hence it complains if you don't provide an ELSE clause. When i1 is declared as `final`, the compiler knows for sure that i1 will *always* be 9 and never change hence it stops complaining.

Even if you know for sure that i1 never changes before the IF check, the compiler is not *that* smart.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

the error is a compile time error.The error is:
VARIABLE MIGHT NOT HAVE BEEN INITIALISED

But after declaring the variable 'i as final' the code runs just fine. Y??

Because when you declare a variable as `final`, the compiler ensures that re-assignment to that variables never happens. Using static program analysis, the compiler can infer that the value of i1 will *always* be 9 in the given scope and can in turn infer that i2 will always be set to 8. In fact, a smart compiler might reduce the code to something like:

final int i1 = 9;
int i2 = 8;

// OR even this if i1 is never used again in the scope
int i2 = 8;
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

You are trying to print out a variable(i2) which is possibly uninitialized (depends on rutime, i2 won't be initialized if i1 < 3). Either provide an initial value for i2 or write an else statement which takes care of the same.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

You might have multiple ways of representing cards; for e.g. 4H or IV Hearts or 4 Hearts or 4 1 (where 1 is a code for hearts). Given the multiple ways in which a single card can be expressed, why not have a contract defined which deals with parsing a card based on the representation? In the absence of a CardParser interface, the parser class would contain a lot of IF's to check for the format which the user has used and then parse the Card accordingly, something which can be elegantly dealt with by polymorphism. A generic parser class would be something of a "god" class is the sense that it would need to "know" about "all" the possible representations.

Also, it would violate the basic principle of "cohesion". Any new representation added or any change in existing one would require a change in the method which is already dealing with other representations thereby increasing the possibility of a change impact. But that's just me, YMMV. :-)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> I don't believe enums would be a smart move here

Enums are a natural fit here IMO. It's a different thing if you are confused on how to get things rolling with enums. One possible OO solution would be:

  • Create a enum CardSuit (e.g. SPADE, HEART, DIAMOND, CLUB)
  • Create an enum CardRank (e.g. ACE, KING, TWO, THREE etc)
  • Create an interface CardParser having a method Card parseCard(String representation)
  • Create a concrete class AbbreviatedNameCardParser which parses the passed in String and create a Card instance out of it
  • Create a Card class which has two members; suit and rank both of enum types. Add a toString method which would print out the entire card name based on the suit and rank.
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

AFAIK, there is no way to customize the MFF since it is decided based on your usage patterns. Subscribing to forums and tracking them via your CP is one way of watching selected forums irrespective of your usage/posting history.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

This doesn't seem to be a problem with JUnit code but more with the way data is retrieved and its size calculated. Are you sure the DataBank and DataBuilder classes are not holding some sort of global state?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

This is how very large numbers are by default displayed in an excel file. Try pasting the same number (123456789123456789123456789) in a fresh excel worksheet and the result should probably be the same. You need to set the column/cell type of that excel sheet to "Text" instead of "General" which is selected by default. Look into the API of your excel exporting library for setting the same. In excel, this can be done by right clicking the cell/column -> selecting format cells -> Text.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The functionality you require is not present in HashTable (predictable iteration order; i.e. iterating over keys in the order which they were inserted) hence you'd have to use LinkedHashMap. If you are feeling adventurous, you can extend HashTable to mimic LinkedHashMap but that would be *really* unwieldy and not recommended.

BTW, why is it that you don't want to use a LinkedHashMap?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

If you need predictable iteration order, use a hashtable implementation which supports the same. Drop HashTable in favour of LinkedHashMap.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> oos.writeObject("" + new VarnaPacket(player));

This line means you are sending across a string object and not a VernaPacket object hence the cast on the receiving end fails.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> ... or should I be using native2ascii in some way?

AFAIK, native2ascii is normally used when dealing with properties file since the specification says that properties file can contain only ASCII characters as mentioned here. IMO, instead of modifying the program text, you are better off setting the -encoding flag when compiling via command line.

BTW, are these locale sensitive strings part of the key or value part of the map? If used as keys, won't it be better to just use the ASCII characters. If used as values, would you be displaying them at any point in your application? In that case, you are better off placing them in a properties files.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> ... or should I be using native2ascii in some way?

AFAIK, native2ascii is normally used when dealing with properties file since the specification says that properties file can contain only ASCII characters as mentioned here. IMO, instead of modifying the program text, you are better off setting the -encoding flag when compiling via command line.

BTW, are these locale sensitive strings part of the key or value part of the map? If used as keys, won't it be better to just use the ASCII characters. If used as values, would you be displaying them at any point in your application? In that case, you are better off placing them in a properties files.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Yes.

In most applications, a common class instance (singleton) is used to keep track of global state. The advantage here is ease of use; just refer that class from any part of the application. The downfall is that tracking *which* part of your code changed the *global* state is difficult for an application having sizeable application logic.

In Java, it is a commonplace occurrence to rely on instance fields to be used in class methods. In languages where functions are the only units of abstraction and complex abstractions are built upon simple ones, making a function relying on some global piece of information limits its reuse.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Idempotent methods are also called pure methods; methods whose output purely depends on the passed in arguments and not any external state. Pure functions play a critical role in "pure functional languages". The wikipedia entry for pure functions describes them pretty well:

The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change as program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices

Examples:

// Pure
public int add(int a, int b) {
  // computation uses only the passed in arguments
  // all resources used are exclusive to the function stack
  // on which they were created (except shared global resources)
  int result = a + 10 - 233 * 23 / 2 + b;
  return result;
}

// Impure
public int add(int a, int b) {
  // computation uses global state; not pure
  int result = a + 10 - 233 * 23 / 2 + b;
  result = result * CommonConstants.MODIFIER;
  return result;
}