0

Truncate time part from date [ ORACLE TRUNC equivalent in MySQL ]

In Oracle TRUNC(data_time_var) returns only the date portion of a date_time data type.

In MySQL to truncate time part from date we have to use

SELECT DATE_FORMAT(date_time_var, '%Y-%m-%d')
Try different date formate.

Further date time function in mysql can be found in
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html

|
0

How to know which method you are in?

  1. public class MethodName {  
  2.    
  3.  public String methodOne() {  
  4.   return new Exception().getStackTrace()[0].toString();  
  5.  }  
  6.    
  7.  public String methodTwo() {  
  8.   return Thread.currentThread().getStackTrace()[2].toString();  
  9.  }  
  10.   
  11.  public static void main(String[] args) {  
  12.   MethodName name = new MethodName();  
  13.     
  14.   long start = System.currentTimeMillis();  
  15.   for (int i = 0; i < 100000; i++) {  
  16.    name.methodOne();  
  17.   }  
  18.   System.out.printf("First method - new Exception() - in %d millis\n",  
  19.      System.currentTimeMillis() - start);  
  20.     
  21.   start = System.currentTimeMillis();  
  22.   for (int i = 0; i < 100000; i++) {  
  23.    name.methodTwo();  
  24.   }  
  25.     
  26.   System.out.printf("Second method - Thread.currentThread() - in %d millis\n",  
  27.      System.currentTimeMillis() - start);  
  28.  }  
  29. }  

|
1

JasperReport Export to Excel Snippet code

Sample code that will export JasperReport(.jasper) to excel, pay attention to the bold code
that's all the tricks. The sample servlet will accept two parameter the date and the name of the report.


/*
* JasperToExcel.java
*/

import bean.report.RowStatistics;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.*;
import javax.servlet.http.*;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

/**
*
* @author amontejo
* @version
*/
public class JasperToExcel extends HttpServlet {

public static final String REPORT_DIRECTORY = "/reports";

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String reportName = request.getParameter("reportname");
String selectedyear = request.getParameter("SelectedYear");
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("/" + REPORT_DIRECTORY + "/" + reportName + ".jasper");

ServletContext context = this.getServletConfig().getServletContext();
JasperPrint jasperPrint = null;
HashMap parameterMap = new HashMap(); 

parameterMap.put("parayear", new String(selectedyear));

try {
ServletOutputStream servletOutputStream = response.getOutputStream(); 
JRDataSource dataSource = createReportDataSource(request, selectedyear, reportName);
jasperPrint = JasperFillManager.fillReport(reportStream, new HashMap(), dataSource);
generateXLSOutput(reportName, jasperPrint, response);
} catch (Exception e) {
}
}

private String tagreport(String string) {
java.util.Calendar calendar = java.util.Calendar.getInstance();
return string + calendar.get(calendar.MONTH) + calendar.get(calendar.DAY_OF_MONTH) + calendar.get(calendar.YEAR);
}

private void generateXLSOutput(String reportname,
JasperPrint jasperPrint,
HttpServletResponse resp)
throws IOException, JRException {
String reportfilename = tagreport(reportname) + ".xls";
JExcelApiExporter exporterXLS = new JExcelApiExporter();

exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, resp.getOutputStream());
resp.setHeader("Content-Disposition", "inline;filename=" + reportfilename);
resp.setContentType("application/vnd.ms-excel");

exporterXLS.exportReport();
}


// 
/** Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// 

}

|
7

Alternate Background colour of rows in JasperReport

There are few methods to alternate background colour of rows in jasperreport.

Use conditional style.

A conditional style has two elements: a Boolean condition expression and a style. The
style is used only if the condition evaluates to true.

We have following code snippet to get alternating row color.

<style name="alternateStyle" fontName="Arial" backcolor="red">
<conditionalStyle>
<conditionExpression>
new Boolean($V{REPORT_COUNT}.intValue() % 2 == 0)
</conditionExpression>

<style backcolor="blue"/>
</conditionalStyle>
</style>



In this example, element with this style will get red backcolor. But the presence of conditional style changes the behaviour and when rendered on an even row, the same element will have blue backcolor.

A conditional style override the properties of parent style.



OR

just put the a rectangle with a different background color and set the printwhenexpression to :

new Boolean(($V{REPORT_COUNT} mod 2) == 0)



OR

Set up a new java.lang.Integer variable called BACKGROUND. Set its Calculation Type to DistinctCount, Reset typeto None, Increment type to None, Variable Expression to a field that will always contain unique values (eg. $F{PortNumber} ), and an Initial Value Expression of new java.lang.Integer(0). That will give you an auto-incrementing variable.


In the Detail section make sure all the existing elements are set to Transparent.


Now in the Detail section of your report create a new Static Text box. Size it to cover the full extents of the detail section. If you are using multiple columns size it to the full extent of just one column. Set its background colour to be whatever you want it to be. Put a single space in the Static Text area.


To make it toggle on and off you use a Print When expression based on your BACKGROUND variable. Set it to be new java.lang.Boolean(($V{BACKGROUND}.intValue() % 2)==1)


Now all you need to do is send it to the back. Under the Format Menu choose the Send to Back option, and your done.


|
4

Error Page Handling In JSP

The error-page element declares a mapping between an error and a resource in the Web application that is called when that error occurs. Ther errors can be caused by HTTP errors (such as 404 Not Found) and Web application exceptions (like a ServletException). The errors can be mapped to any vali resource in the Web application, so it may be handled by a static HTML page, a JSP page, or a sevlet.

In web deployment descriptor put following

<web-app>
<error-page>
<error-code>404</error-code&gt
<location>/file-not-found.html<location>
</error-page>

<error-page>
<error-code>javax.servlet.ServletException</error-code&gt
<location>/oopsy.jsp<location>
</error-page>

.. while using action

<error-page>
<error-code>404</error-code&gt
<location>/showError.do<location>
</error-page>
</web-app>


|
0

How to check null String

First thing to remember is that the == operator compares two object references to see whether they refer to the same instance whereas equals() method compares the chars inside a String object.

Thus, str.equals(null) will always return false because there is no such object reference as null in reality.
So only str==null can help you.

However, a more strong way to check if a str object contains any char or not is

if str==null str.equals("")
{
...
}

Other way is just perform the operation on the str in a try-catch block catching the NullPointerException like
try {
str.substring(0, 2);
}catch(NullPointerException)
{
e.printStackTrace();
}

|
0

Getting values of textbox in Javascript

In javascript, do not use, document.getElementById("ID"); to get value from the input elements. It works in IE but not in FF.

so use like

var value = doucment.forms[0].txtName.value;

|
1

Using Kaptcha in JSP page within WEB-INF folder

Since our JSP page in inside WEB-INF folder, we need to give path starting from the context path.

in JSP page

instead of <img=kaptcha/>

place

<img=<%request.getContextPath()%>/kaptcha/>

|
0

Java ClassPath Problem

If NoClassDefFoundError occurs when we execute a class, it might be a classpath error.

It can be solved by placing .; before each path

where '.' refers that classpath is accessible from any folder

|
0

load-on-startup (load-on-startup tag) in Servlet

Used to decide whether servlet will be " lazily " or " eagerly " loaded.
Specified in web.xml file. If the value is not specified or is a Number < 0 then it means " lazy loading "

What " lazy loading " means is that servlet is NOT loaded by container on startup Servlet in this case is loaded on the first client request - so the first client can experience poor performance

" Eager " loading means that the servlet is initialised on container startup If there are two servelts A & B with values 0 & 1 than it means that Servlet A ( having value = 0 ) will be loaded first So if there are more than one servlet this element specifies the order of loading - lower integer values ( including zero ) are loaded first

If you specify this element but do not provide the value - even then the servlet will be the first servlet that gets loaded

To ensure that servlet follows " lazy loading " - do not provide this entry at all in web.xml file OR provide a negative number

|
0

IllegalStateException : Error: Attempt to clear a buffer that is already been flushed

Sometimes <logic:forward/> give IllegalStateException: including error message like

Error: Attempt to clear a buffer that is already been flushed


This is related to the buffer overflow error. To solve this error, you can just set the page directive parameter autoflush to true or increase the buffer size by setting the buffer parameter.
By default the buffer size is 8K, and all the HTML output is stored in this buffer before JSPWriter flushes it to the output. If the content size exceeds this default size, then there will be an exception, like the one you are getting.
If the value of "autoflush" parameter is true, then whenever the buffer is full then the contents of this buffer will be automatically flushed.

|
0

Getting Execution Function name for debugging.

FROM: JAVA FORUM

The "standard" way to accomplish this is to raise an Exception and then parse its stack-trace. If you encapsulate that inside your "myDebugger()" call, you'd want the second method on the stack. Take a look at StackElement (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StackTraceElement.html) for the kind of info you can get.There are aspect-oriented libraries out there that hide this from you - you could look at them for entry/exit debuging.Or, you could use CPP and just plug __FILE__ and __LINE__ into your code...Grant

class Debugger {
public static String getWhoCalledMe() {
StackTraceElement
stack[] = new Throwable().getStackTrace();
return
(stack[1].getMethodName());
}
}

|
0

Maintining CheckBox State during Pagination

SOURCE :EXPERT EXCHANGE

Given the zone and the phrasing of the question, I understand this to be a question about a JSP web application, rather than a Swing or AWT-based desktop application. If that's the case, here's how I would approach it.

First of all, to clarify the assumptions I'm making, I'll explain my understanding of your application. You are paging through a set of records, and each record has as one of its elements a checkbox. As the pages through the records, he can check some items, indicating that they should be acted on in some way. At some point, the user has checked all the desired records on several pages, and wants to submit them all at once for some action.

I'm assuming that each record has some sort of unique identifier, and when the user has browsed through the record set and checked all of the necessary records, the submit action can use these unique identifiers to process the correct records. I'm assuming you're using EL and JSTL tags, and not scriptlets, since that's the best practice. In the example code, you can change the "name" attributes on the form controls; I'm just using what seems natural to me. Same goes for EL variable names. If you need clarification, please ask. I'm not sure what framework you're using on the server side, so I'll just show the standard servlet API implementation. It should be easy to adapt that to whatever framework one might use, but that's outside the scope of this question.

Here's a skeleton of the form I'd use:

<c:url var="action" value="/viewpage" /><form
action="${action}"
method="post"><fieldset><table><tbody>
<c:forEach items="${records}" var="rec">
<tr>
<td>

<!-- Display the
records fields as desired --><c:out value="${rec.id}" />

</td>
<td>

<!-- Here's
the crucial part... -->

<input type="hidden"
name="records" value="${rec.id}" />

<c:choose>
<c:when test="${sessionScope.myCheckBoxes[rec.id]}">
<checkbox checked="checked" name="checks" value="${rec.id}" />

</c:when>

<c:otherwise>
<checkbox name="checks" value="${rec.id}" />
</c:otherwise>
</c:choose>


</td>
</tr>

</c:forEach>
</tbody>
</table>
</fieldset>

<fieldset>
<button type="submit" name="page"
value="${page - 1}">
Previous
</button>

<button type="submit" name="page" value="${page + 1}">
Next
</button>

<button type="submit"
name="process" value="true">
Done
</button>
</fieldset>
</form>

Then, on the
servlet (mapped to /viewpage) , doPost would contain something like this:

protected void doPost(HttpServletRequest req, HttpServletResponse res){

...String[] records = req.getParameterValues("records");

if
(records != null)Set checks = new HashSet();
String[] tmp =
req.getParameterValues("checks");
if (tmp != null) {
for (int idx = 0;
idx < tmp.length; ++idx)
checks.add(tmp[idx]);
}

Map
myCheckBoxes = (Map) req.getSession().getAttribute("myCheckBoxes");

if
(myCheckBoxes == null)
myCheckBoxes = new HashMap();

for (int idx =
0; idx < records.length; ++idx) {
if (checks.contains(records[idx]))
myCheckBoxes.put(records[idx], Boolean.TRUE);
else
myCheckBoxes.remove(records[idx]);
}
...

if
(Boolean.valueOf(req.getParameter("process")).booleanValue()) {

/* The
user pressed the "Done" button; do your work here. */

Iterator recIds =
myCheckBoxes.keySet().iterator();
while (recIds.hasNext()) {
String id =
(String) recIds.next();...
}
/* Clear the check state from the session
(probably, depends on your requirements. */
req.getSession().removeAttribute("myCheckBoxes");
}
else {
req.getSession().setAttribute("myCheckBoxes", myCheckBoxes);
}
...
}




NOTE : Sorry, I missed some braces in the code; the block guarded by "if (records != null)" should extend to the end of the "for" loop over "records"

|
0

Using Oracle Sequence in Hibernate

For using sequence create in oracle in hibernate, make following confguration

<class name="className" table="tableName"schema="databasename">
<id name="id" type="java.lang.Long"unsaved-value="null" column="ID">
<generatorclass="sequence">
<paramname="sequence">USERS_SEQ</param>
</generator>
</id>

|
0

Using Cancel button in struts

Cancel button is a type of submit button which bypasses validation during submission of the form. So, cancel button can be used for submitting a form without validation and to reset form.

  1. Using Cancel button for bypassing validation

    Reset button is also available in struts but reset button resets to the form fields to default if the form has not been submitted or has not be passed through validator. Once the validation has occured and validation failed, the form fields are populated with the values we have send for validation. Now by pressing reset button will retain the typed and not default values. In this case, struts cancel button is used. Struts cancel button can be rendered through
    <html:cancel/>.

    It is rendered in html as
    <input type="reset" value="Reset"><input type="submit"
    name="org.apache.struts.taglib.html.CANCEL" value="Cancel"
    onclick="bCancel=true;">

    The onclick="bCancel=true;" in generated reset button plays a great role for bypassing clientside validation.

    If you are using dispactch action, create a method called 'cancelled' and get the form field values inside that method.

    Cancel button bypassed both serverside and clientside validation.
  2. Using Cancel button as reset button
    If you're using Struts 1.2.9 or above, you must specify cancellable="true" in the Action mapping as;


    <action
    attribute="registrationForm"
    input="..."
    ...
    ...
    <set-property property="cancellable" value="true"/>
    ...
    ...
    </action>
    now its time to reset form fields through action like;

    if(isCancelled(request)){
    registrationForm.set("firstname",
    "");
    }
    [I'm using DynaValidatorForm here]

    If you are using DispatchAction then you have to create a method named cancelled and reset forms there.



|
0

Select initial value in struts

Suppose, you want a default value to be selected during the page load while using DynaValidatorForm or DynaValidatorActionForm, use initial attribute of field-property to define the value that is to be selected by default.

eg; you have a SEX porperty whose value can be either male or female and you use radio button. If you wish male to be selected by default, then put inial=male.

Here is my form-bean definition

<form-bean name="consumerRegistrationForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="firstname" type="java.lang.String" />
...
...
<form-property name="sex" type="java.lang.String"
initial="male" />
...
...
<form-property
name="userType" type="java.lang.String" initial="homeUser"/>
</form-bean>

Then, while rendering the form, male is initially selected for SEX property.

|
0

Use of formula to concate fields

Suppose you have two fields holding firstname and lastname. And there is a property called fullname which is expected to hold the concatinated firstname and lastname. Then you have to do like follows...


Define a property called fullname in its class

Then in .hbm file, put a porperty like

<property name="fullName" formula="concat(FIRST_NAME,
LAST_NAME)"/>



Remember: FIRST_NAME and LAST_NAME are the database field name and not the class properties. Only two fields can be concatinated. No. of arguments mismatched exception may occur if more than two fields are concatinated.


|
0

Preventing Form Resubmission (due refreshing)

To prevent form resubmission due to page refresh we can use HTTP redirect

To use HTTP redirect feature, the forward is set as follows:



However there is one catch in this method, the actual jsp name is shown.

Therefore we can change the forward action as following:

<forward redirect="true" path="/gotoSuccess.do" name="success">

where gotoSuccess.do is another action mapping using forward action as follows:
<action path="/gotoSuccess" validate="false" parameter="/success.jsp" type="org.apache.actions.ForwardAction">

|
0

Struts Forward redirect=true

excerpted from : Struts : The complete Reference

The forward tag looks up a forward from the Struts configuration file and redirects to it. Based on the way that the forward is defined in the configuration file, this tag will either forward to the URL specified by the forward or perform a redirect to it. If the forward has its redirect attribute set to “true”, as shown in the following example, this tag will perform a redirect:

A redirect sends a response to the user’s browser instructing it to load another page. A forward, on the other hand, simply “forwards” control (on the server side) to another URL without having the browser make another request.

Note that only URLs residing on the same server can be forwarded to, whereas any URL can be redirected to.

|

Copyright © 2009 So That I Can Remember All rights reserved. Theme by Laptop Geek. | Bloggerized by FalconHive.