http://feeds.feedburner.com/SpendYourTimeHere-Once

Current Affiares

Tuesday, August 14, 2012

How to make the properties file in java?

How to make the properties file in java?

//name it db.properties OR FILENAME.properties


jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;databaseName=xyz
jdbc.username=abc
jdbc.password=abc@123



// secondfile.properties



name=sdgfdsgffdsgfds dghfdsgdsgds
title=Welcome
footermsg=Design & developed by xyz || Best visible on internet explorer 8.0 or above, google chrome
footermsg2=Best visible resolution is 1024*728 or more
sortingmsg=For Sorting >>> Click the columns heading



   

Sample of beans.xml file in java?

Sample of beans.xml file in java?


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

Sample of applicationContext.xml file in java?

Sample of applicationContext.xml file in java?


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
">
    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>WEB-INF/classes/config/database/db.properties</value>
        </property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">    
        <property name="dataSource" ref="dataSource"/>   
    </bean>
    <bean id="loginBo" class="testlab.bo.impl.LoginBoImpl" >
        <property name="loginDao" ref="loginDao" />
    </bean>
    <bean id="loginDao" class="testlab.dao.impl.LoginDaoImpl" >
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
  
<!--    Begin for Test Declaration-->
    <bean id="testDetailBo" class="testlab.bo.impl.TestDetailBoImpl" >
        <property name="testDetailDao" ref="testDetailDao" />
    </bean>
    <bean id="testDetailDao" class="testlab.dao.impl.TestDetailDaoImpl" >
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
   <!--     End for Test Declartion-->
<!--    Begin for Admin Declaration-->
    <bean id="adminBo" class="testlab.bo.impl.AdminBoImpl" >
        <property name="adminDao" ref="adminDao" />
    </bean>
    <bean id="adminDao" class="testlab.dao.impl.AdminDaoImpl" >
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
  
<!--     End for Admin Declartion-->
    
   
</beans>

Monday, August 13, 2012

Sample of faces-config.xml file??

Sample of faces-config.xml file??


<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -->

<faces-config version="2.0"
              xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
    <application>
    
        <el-resolver>
            org.springframework.web.jsf.el.SpringBeanFacesELResolver
        </el-resolver>
        <resource-bundle>
            <base-name>testlab.properties.labtest</base-name>
            <var>address</var>
        </resource-bundle>
        <message-bundle>testlab.ui.MyMessages</message-bundle>
    </application>
    <managed-bean>
        <managed-bean-name>utilsDb</managed-bean-name>
        <managed-bean-class>testlab.utils.TestlabUtilsDb</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
        <managed-property>
            <property-name>jdbcTemplate</property-name>
            <value>#{jdbcTemplate}</value>
        </managed-property>
    </managed-bean>
    <managed-bean>
        <managed-bean-name>user</managed-bean-name>
        <managed-bean-class>testlab.beans.UserBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
        <managed-property>
            <property-name>loginBo</property-name>
            <value>#{loginBo}</value>
        </managed-property>
    </managed-bean>
   
    <managed-bean>
        <managed-bean-name>tdbean</managed-bean-name>
        <managed-bean-class>testlab.beans.TestDetailBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
        <managed-property>
            <property-name>testDetailBo</property-name>
            <value>#{testDetailBo}</value>
        </managed-property>
    </managed-bean>
   
    <lifecycle>
        <phase-listener>testlab.utils.SessionPhaseListener</phase-listener>
    </lifecycle>
    <managed-bean>
        <managed-bean-name>adminBean</managed-bean-name>
        <managed-bean-class>testlab.beans.AdminBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
        <managed-property>
            <property-name>adminBo</property-name>
            <value>#{adminBo}</value>
        </managed-property>
    </managed-bean>
</faces-config>

Sample of web.xml file ?

Sample of web.xml file ?

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <!-- Add Support for Spring -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Production</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>30</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
    <filter>
        <filter-name>restrict</filter-name>
        <filter-class>testlab.utils.RestrictPageFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>restrict</filter-name>
        <url-pattern>*.xhtml</url-pattern>
    </filter-mapping>
<!--    <filter>
        <filter-name>MyFacesExtensionsFilter</filter-name>
        <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyFacesExtensionsFilter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>
-->   
    <filter>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
        <init-param>
            <param-name>uploadDirectory</param-name>
            <param-value>C:\upload</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>
</web-app>




How to get the current date in java

How to get the current date in java?

// in java file
public static String DateDemo() {
        Date dNow = new Date();
       
        //SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
       // SimpleDateFormat ft = new SimpleDateFormat("M/d/yyyy hh:mm:ss a");
        SimpleDateFormat ft = new SimpleDateFormat("d/M/yyyy");

        System.out.println("Current Date: " + ft.format(dNow));
        return ft.format(dNow);
    }

or


public static String GetCurrentDateAndTime() {
        int day, month, year;
        int second, minute, hour, ampm;

        GregorianCalendar date = new GregorianCalendar();

        day = date.get(Calendar.DAY_OF_MONTH);
        month = date.get(Calendar.MONTH);
        year = date.get(Calendar.YEAR);

        second = date.get(Calendar.SECOND);
        minute = date.get(Calendar.MINUTE);
        hour = date.get(Calendar.HOUR);
        ampm = date.get(Calendar.AM_PM);
        char ampm1 = (char) ampm;
        System.out.println("Current date is  " + day + "/" + (month + 1) + "/" + year);
        System.out.println("Current time is  " + hour + " : " + minute + " : " + second + ampm1);
        return month + "/" + day + "/" + year + " " + +hour + ":" + minute + ":" + second + " " + ampm1;
    }


How to get the max value of a primary key field in java

How to get the max value of a primary key field in java?

// in java file


package testlab.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.jdbc.core.JdbcTemplate;


public class TestlabUtilsDb {

    private JdbcTemplate jdbcTemplate;

  
    public  void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
// maxquery could be select Max(id) as id from tablename

    public  int maxId(String maxquery) {
        int maxid = 0;
        PreparedStatement pstmt = null;
        Connection con = null;
        ResultSet rs;
        try {
            con = jdbcTemplate.getDataSource().getConnection();
            pstmt = con.prepareStatement(maxquery);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                maxid = rs.getInt(1);
            }
            if (maxid == 0) {
                maxid = 1;
            } else {
                maxid = (maxid + 1);
            }
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException ex) {
                    Logger.getLogger(TestlabUtilsDb.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ex) {
                    Logger.getLogger(TestlabUtilsDb.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return maxid;

    }
}

How to find the bean name in java jsf?

How to find the bean name in java jsf?

// in java file

@SuppressWarnings("unchecked")
    public static <T> T findBean(String beanName) {
        FacesContext context = FacesContext.getCurrentInstance();
        return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
    }

// and how to use
// use below line wr u want to find the bean name & their respective values

BeanFile beanFile = javafile.findBean("user");

How to convert the string to UPPER case letter in java

How to convert  the string to UPPER case letter in java?

// in java file

public static String convertStringToUpperCase(String str) {
        String strValue = "";
        if (str == null) {
            strValue = "NA";
        } else {
            strValue = str.trim().toUpperCase();
        }
        return strValue;
    }

// in set & get java file
private String brcode;

public String getBrcode() {
        return brcode;
    }

    public void setBrcode(String brcode) {
        this.brcode = javafile.convertStringToUpperCase(brcode);
    }



How to redirect to the index page if session expired or time out occurs as per the session-timeout at any page in java, jsf?

How to redirect to the index page if session expired or time out occurs as per the session-timeout at any page in java, jsf?

// in web.xml

<session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>


// in faces-config.xml

<lifecycle>
        <phase-listener>testlab.utils.SessionPhaseListener</phase-listener>
    </lifecycle>

// in SessionPhaseListener.java

package xyz.utils;

import javax.faces.FacesException;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class SessionPhaseListener implements PhaseListener {

    private static final String homepage = "faces/index.xhtml";

    @Override
    public void afterPhase(PhaseEvent event) {
        //Do anything
    }

    @Override
    public void beforePhase(PhaseEvent event) {


        FacesContext context = event.getFacesContext();
        ExternalContext ext = context.getExternalContext();
        HttpSession session = (HttpSession) ext.getSession(false);
        boolean newSession = (session == null) || (session.isNew());
        boolean postback = !ext.getRequestParameterMap().isEmpty();
        System.out.println("newSession::" + newSession + " postback::" + postback);
        boolean timedout = postback && newSession;
        if (timedout) {
          
            Application app = context.getApplication();
            ViewHandler viewHandler = app.getViewHandler();
            UIViewRoot view = viewHandler.createView(context, "/" + homepage);
            context.setViewRoot(view);
            context.renderResponse();
          
            try {
              
                viewHandler.renderView(context, view);
              
                context.responseComplete();
              
            } catch (Throwable t) {
                throw new FacesException("Session timed out", t);
            }
        }
    }

    @Override
    public PhaseId getPhaseId() {
      
        return PhaseId.RESTORE_VIEW;
    }
}

How to check the requested page has a valid user with filter class IN JAVA, JSF?

How to check the requested page has a valid user with filter class IN JAVA, JSF?

 // login validation method && set attribute
// UserBean.java

public String reuestedUrl() {
               boolean check = loginBo.validateLogin(getUsername(), getPassword(), testlabConstants.USER_TYPE_ADMIN);
        if (check) {
            ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
            HttpSession session = (HttpSession) ectx.getSession(false);
            session.setAttribute("VALID_USER", "YES");

            return "reuestedUrl?faces-redirect=true";
        } else {

            String msg = "Invalid Username/Password.";
            setLoginfailuremsg(msg);

            return "index?faces-redirect=true";

        }
    }


// filter class for every page & this will work for every page by include filter in web.xml file


RestrictPageFilter.java

package xyz.utils;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class RestrictPageFilter implements Filter{
    FilterConfig fc;
       @Override
    public void init(FilterConfig filterConfig) throws ServletException{
        fc=filterConfig;
    }
    @Override
    public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException{
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp=(HttpServletResponse) response;
        HttpSession session=req.getSession();
        String pageRequested=req.getRequestURL().toString();
           //  System.out.println("pageRequested::"+pageRequested);
      //  System.out.println("Valid user::"+session.getAttribute("VALID_USER"));
        if(session.getAttribute("VALID_USER")==null){
            RequestDispatcher rd=req.getRequestDispatcher("/faces/index.xhtml?faces-redirect=true");
            rd.forward(request, response);
            //resp.sendRedirect("/faces/index.xhtml?faces-redirect=true");
        }else{
            chain.doFilter(request, response);
        }
       
    }
    @Override
    public void destroy(){
       
    }
}





// web.xml file



<filter>
        <filter-name>restrict</filter-name>
        <filter-class>testlab.utils.RestrictPageFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>restrict</filter-name>
        <url-pattern>*.xhtml</url-pattern>
    </filter-mapping>

How to make the log off button working in java ?

How to make the log off button working in java ?


import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

public String logoff() {
        ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
        HttpSession session = (HttpSession) ectx.getSession(false);
        session.invalidate();

        return "index?faces-redirect=true";
    }

// using the method with command button of primefaces
<p:commandButton type="submit" icon="ui-icon-power" value="Log-off" immediate="true" 
action="#{user.logoff()}" ajax="false"/>

How to validate email & uploaded file in java?

How to validate email in java?

import javax.faces.context.FacesContext;
import javax.faces.component.UIComponent;
import javax.faces.validator.ValidatorException; 

public void validateEmail (FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
        String eMail = (String) value;
        if (!"".equals(eMail)) {
            if (eMail.indexOf("@") < 0) {
                FacesMessage message = new FacesMessage("Invalid email address!");
                throw new ValidatorException(message);
            }
        }
    }


//Using the above method with primefaces input text field
<p:inputText id="memail" value="#{addmem.memail}"  validator="#{user.validateEmail}"  required="false" label="memail" size="35"  />

How to validate uploaded file or check file existence in disk in java?

import javax.faces.validator.ValidatorException;
import javax.faces.context.FacesContext;
import javax.faces.component.UIComponent; import javax.faces.context.ExternalContext;
import org.primefaces.model.UploadedFile;

public void validateFile(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
 ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

        UploadedFile uFile = (UploadedFile) value;

       String uploadfilename = uFile.getFileName().substring(uFile.getFileName().lastIndexOf("\\") + 1, uFile.getFileName().length());
       
       String serverfileaddress = servletContext.getRealPath("") + File.separator + testlabConstants.FOLDER_NAME_OF_UPLOADED_FILE + File.separator + uploadfilename;

         File f = new File(serverfileaddress);

            if (f.exists()) {
            FacesMessage message = new FacesMessage("File already exist !");
            throw new ValidatorException(message);
        }

    }


 // Using the above method with primefaces file upload component

  <p:fileUpload label="Upload File" id="uploadfile" validator="#{tdbean.validateFile}" required="true" value="#{tdbean.file}"   mode="simple"/> 

My Blog List

Popular Posts

All Rights Reserved To SYTHONCE. Ethereal theme. Powered by Blogger.