e hënë, 25 qershor 2007

Implementing serializable singleton

public class MySingleton implements Serializable {
static MySingleton singleton = new MySingleton();

private MySingleton() {
}

// This method is called immediately after an object of this class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return singleton;
}
}

Deserializing an Object

try {
// Deserialize from a file
File file = new File("filename.ser");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
javax.swing.JButton button = (javax.swing.JButton) in.readObject();
in.close();

// Get some byte array data
byte[] bytes = getBytesFromFile(file);
// see e36 Reading a File into a Byte Array for the implementation of this method

// Deserialize from a byte array
in = new ObjectInputStream(new ByteArrayInputStream(bytes));
button = (javax.swing.JButton) in.readObject();
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}

Serializing an Object.

Object object = new javax.swing.JButton("push me");

try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();

// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();

// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}

Forcing updates to a file to a disk.

try {
// Open or create the output file
FileOutputStream os = new FileOutputStream("outfilename");
FileDescriptor fd = os.getFD();

// Write some data to the stream
byte[] data = new byte[]{(byte)0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE};
os.write(data);

// Flush the data from the streams and writers into system buffers.
// The data may or may not be written to disk.
os.flush();

// Block until the system buffers have been written to disk.
// After this method returns, the data is guaranteed to have
// been written to disk.
fd.sync();
} catch (IOException e) {
}

Getting and Setting modification time of file or a directory.

File file = new File("filename");

// Get the last modified time
long modifiedTime = file.lastModified();
// 0L is returned if the file does not exist

// Set the last modified time
long newModifiedTime = System.currentTimeMillis();
boolean success = file.setLastModified(newModifiedTime);
if (!success) {
// operation failed.
}

Renaming a file or directory.

// File (or directory) with old name
File file = new File("oldname");

// File (or directory) with new name
File file2 = new File("newname");

// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}

Creating a temporary file.

try {
// Create temp file.
File temp = File.createTempFile("pattern", ".suffix");

// Delete temp file when program exits.
temp.deleteOnExit();

// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}

Copy file from one location to another location

// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}

e martë, 19 qershor 2007

JSP Scripting Elements

Scripting Elements are basically used to add contents to the HTML page dynamically.
Lets you add java code inside the HTML/JSP.

1) JSP Comments
- used to comments for user information.

2) JSP Expressions
- used to insert dynamic results to the output page.
- FORMAT - <%= expression %>
- they are printed directly to the output page.
- e.g. Thanks for ordering <%= request.getParameter("title") %>
- e.g. Current time: <%= new java.util.Date() %>
- XML SYNTAX - Java Expression

3) JSP Scriptlets
- used to insert java code into the method that handles request for the page.
- FORMAT - <% code %>
- they are inserted into the _jspservice(called by service) method of the servlet.
- they have access to implicit objects automatically.
- e.g. <% String q = request.getQueryString(); out.println("GET data: " + q);%>
- they can be used for setting response headers and status codes, invoking side effects such as writing to the server log or updating a database, or executing code that contains loops, conditionals, or other complex constructs.
- XML SYNTAX - Code

4) JSP Declaraions
- used to add methods and field declarations to the servlet that corresponds to the JSP page.
- FORMAT - <%! Java Code %>
- they are inserted to the main body of the servlet class, outside the _jspService() and called by service to process the request.
- XML SYNTAX - Code
- implicit objects wont be accessible within declarations.

Tag Library Descriptor File Format.


1.0
1.1
csajsp


A tag library from Core Java Files & Pages,
http://javablues.blogspot.com/.





prime

com.tags.PrimeTag

Outputs a random N-digit prime.

EMPTY


length
false



Components to make up Tag Library.

1) Tag Handler Class -- holds logic for the tag implementation
- need to implement Tag interface, can be achieved by extending TagSupport or BodyTagSupport class.
- some important methods
--- doStartTag() -- basic method called for tag found in JSP, called for non-attribute tags the logic can be implemented over here.
--- doEndTag()
--- can have setter/getter methods of the tag attributes, so whenever an attribute is passed from a JSP it calls setter method to set the value in Tag handler class and later be used by doStartTag() or other business/logic methods.

2) Tag Library Descriptor File -- maps XML element names to the tag implementations
- maps tag to tag handler class
- defines tag attributes (required/optional)

3) JSP file -- uses the tag
- define the taglib directive to point to tag library descriptor file.
--- <%@ taglib uri="abc\def\xyz.tld" prefix="xyz" %>
---

e hënë, 18 qershor 2007

How to handle multiple submit by user?

For multiple submit
---------------------------
1) disable the submit button,
- once the request has been submitted or started processing, user cant submit it again.

2) generate a token, when data gets committed.
- Once data is committed or token is generated, the user cant resubmit the page or the request wont be fulfilled.

3) generate a token when request processing gets started, so that user cant resubmit.
- if the commit fails, user can go to last successful page and get ActionForm, and process the request and go forward.

Define Business Delegate Pattern.

Business Delegate Pattern.
--------------------------------------

Define Transfer Object Pattern.

Transfer Object Pattern.
---------------------------------

Define Session Facade pattern.

Session Facade pattern is all about remove complexities and provide a single interface to user for business calls.

- e.g. for a amount transfer across bank accounts functionality, rather than providing all the mentioned methods in AAAAA, session facade pattern provides a single interface to users as in BBBBB.

AAAAA.
-- checkSourceAcct()
-- checkDestAcct()
-- debitAmountFromSource()
-- CreditAmountToDest()

BBBBB.
-- transferFromSourceToDestAcct()

Advantages
--------------------
- User wont have to be dragged to the complexities of the business.
- User will have to handle a single method for calling the business method, rather than a bunch of methods.