Tuesday, July 19, 2016

java.net.BindException


 

Tomcat: java.net.BindException: Address already in use: bind

Recently we started getting a problem while restarting the tomcat.

java.net.BindException: Address already in use: bind
 at sun.nio.ch.Net.bind0(Native Method)
 at sun.nio.ch.Net.bind(Net.java:444)
 at sun.nio.ch.Net.bind(Net.java:436)
 at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
 at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
 at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:340)
 at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:742)
 at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:458)
 at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:120)
 at org.apache.catalina.connector.Connector.initInternal(Connector.java:960)
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
 at org.apache.catalina.core.StandardService.initInternal(StandardService.java:568)
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
 at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:851)
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
 at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
 at org.apache.catalina.startup.Catalina.load(Catalina.java:599)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:606)
 at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:310)
 at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:484)
7 19, 2016 5:39:55 午後 org.apache.catalina.core.StandardService initInternal
重大: Failed to initialize connector [Connector[HTTP/1.1-8080]]
org.apache.catalina.LifecycleException: Failed to initialize component [Connector[HTTP/1.1-8080]]
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106)
 at org.apache.catalina.core.StandardService.initInternal(StandardService.java:568)
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
 at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:851)
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
 at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
 at org.apache.catalina.startup.Catalina.load(Catalina.java:599)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:606)
 at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:310)
 at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:484)
Caused by: org.apache.catalina.LifecycleException: プロトコルハンドラの初期化に失敗しました
 at org.apache.catalina.connector.Connector.initInternal(Connector.java:962)
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
 ... 12 more
Caused by: java.net.BindException: Address already in use: bind
 at sun.nio.ch.Net.bind0(Native Method)
 at sun.nio.ch.Net.bind(Net.java:444)
 at sun.nio.ch.Net.bind(Net.java:436)
 at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
 at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
 at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:340)
 at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:742)
 at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:458)
 at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:120)
 at org.apache.catalina.connector.Connector.initInternal(Connector.java:960)
 ... 13 more

1. First you need to check which two processes running on same port number 8080 (for tomcat). First, identify which Process is binding the desired port by running this from the Command Prompt: You can use 

netstat -o -n -a | findstr 8080
 
to find the PID and check what process it is.
You should get an output like this.

findport

2. Next, use the ProcessID (value in the last column) to kill the process which is holding the same port:

taskkill /F /PID 7844

Monday, July 18, 2016

ORA-01034: ORACLE not available


java.sql.SQLRecoverableException: ORA-01034: ORACLE not available


重大: Servlet.service() for servlet [Faces Servlet] in context with path threw exception [javax.el.ELException: org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection] with root cause
java.sql.SQLRecoverableException: ORA-01034: ORACLE not available
ORA-27101: shared memory realm does not exist
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
 at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:389)
 at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:382)
 at oracle.jdbc.driver.T4CTTIoauthenticate.processError(T4CTTIoauthenticate.java:444)
 at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
 at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
 at oracle.jdbc.driver.T4CTTIoauthenticate.doOSESSKEY(T4CTTIoauthenticate.java:407)
 at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:416)
 at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:553)
 at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:254)
 at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
 at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:528)
 at org.apache.tomcat.dbcp.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
 at org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:255)
 at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2303)
 at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2289)
 at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2038)
 at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1532)
 at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
 at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:382)
 at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:87)
 at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:112)
 at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:488)
 at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:447)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
 at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
 at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
 at com.sun.proxy.$Proxy86.findUser(Unknown Source)
 at com.login.LoginForm.login (LoginForm.java:303) 
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:606)
 at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
 at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
 at org.apache.myfaces.view.facelets.el.ContextAwareTagMethodExpression.invoke(ContextAwareTagMethodExpression.java:96)
 at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:74)
 at javax.faces.component.UICommand.broadcast(UICommand.java:120)
 at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:1172)
 at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:365)
 at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1658)
 at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:862)
 at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:42)
 at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:196)
 at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:143)
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:357)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
 at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
 at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
 at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
 at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
 at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
 at java.lang.Thread.run(Thread.java:745)

Solution is:

That error means that the database is down. Check your
 
$ORACLE_BASE/{instnace}/admin/bdump/alert_{instance}.log
 
for errors regarding the instance crash. If you restart your server, it may works. Even though still it is not working, make sure that both ORACLE_HOME and ORACLE_SID are written correctly.

 Reference: https://community.oracle.com/thread/262554?start=0&tstart=0

Wednesday, July 13, 2016

Double precision issue



Problem


I want to get double value same as input that we have given, but unexpectedly the output was:
 
Required value is : 9.999E7 

public class DoubleDemo {
 
   public static void main(String[] args) {
 
      double value = 99999999.9;
      System.out.println("Required value is : " + value);
   }
}

Solution

 
public class DoubleDemo {
 
   public static void main(String[] args) {
 
      double value = 99999999.9;
      System.out.println("Required value is : " + BigDecimal.valueOf(value));
   }
}
 
Here we can get exact output ,

Output is : 99999999.9

spring multiple transaction manager issue CannotCreateTransactionException


Problem

In this tutorial you will learn how to resolve CannotCreateTransactionException when you have multiple transaction managers in context file.

org.springframework.transaction.CannotCreateTransactionException:
 Could not open Hibernate Session for transaction;
nested exception is java.lang.IllegalStateException: Already value 
[org.springframework.jdbc.datasource.ConnectionHolder@ebac27] for key 
[org.apache.tomcat.dbcp.dbcp2.BasicDataSource@9266ae] bound to thread
 [http-nio-8080-exec-10] 

public class MyServiceImpl implements MyService {
   public void method1() {
     //code here
   }

   public void method2() {
    //code here
   }
}

This normally happens when you have multiple transaction managers in place. Let us explain it in more detail about having multiple transaction managers in applicationContext.xml  file.

First TransactionManager

<tx:annotaion-driven />

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
 <property name="sessionFactory" ref="sessionFactory"/>
</bean>

When you define <tx:annotaion-driven />  and  @Transactional  annotation, usually it will target bean named transactionManager   i.e HibernateTransactionManager.

HibernateTransactionManager ,
 Binds a Hibernate Session from the specified factory to the thread, potentially allowing for one thread-bound Session per factory. SessionFactory.getCurrentSession() is required for Hibernate access code that needs to support this transaction handling mechanism, with the SessionFactory being configured with SpringSessionContext.
Second TransactionManager

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <property name="dataSource" ref="dataSource"/>
</bean>

<tx:advice id="txAdvice" transaction-manager="txManager">
 <tx:attributes>
  <tx:method name="get*" read-only="true"/>
  <tx:method name="*"/>
    </tx:attributes>
</tx:advice>

<aop:config>
 <aop:pointcut id="serviceOperation" expression="
 execution(* com.myapp.service.MyServiceImpl.*(..)) || 
 --------------------------
 <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
</aop:config>
 
The error comes from DataSourceTransactionManager :

TransactionSynchronizationManager.bindResource(getDataSource(), connectionHolder);

i.e DataSourceTransactionManager is trying to bind the datasource (not the Hibernate Session) to the thread, but the datasource is already there and this is unexpected.

 Note that the transaction manager had not started yet to bind the  Hibernate Session  to the thread, that would happen next at  HibernateTransactionManager :

There are two possible explanations:
  • Somebody (another transaction manager?) is adding the datasource to the thread before the transaction manager and this is unexpected.
  • Or none is adding the datasource to the transaction manager, is just that at the end of the task execution none cleans the thread before returning it to the pool, maybe due an error or an unhandled exception.
If you add @Transactional annotation to your service class, then it will target bean named transactionManager in context file. i.e HibernateTransactionManager here, so that it will bind Hibernate Session to thread not datasource.

Solution

@Transactional
public class MyServiceImpl implements MyService {
   public void method1() {
     //code here
   }

   public void method2() {
    //code here
   }
}

Or without using transactional manager in  applicationContext.xml  file, use @TransactionalManager  annotation in service class.

@Transactional
@TransactionalManager("txManager")
public class MyServiceImpl implements MyService {
   public void method1() {
     //code here
   }

   public void method2() {
    //code here
   }
}

Thursday, July 7, 2016

Custom Validator For Long



Custom Long Validator

JSF makes it very easy to create a custom validator class and tag. Your custom validator class must implement the javax.faces.validator.Validator interface which will require a validate method. Next you will need to register your validator in faces-config.

package com.hello.webapp;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import com.hello.webapp.util.MessageUtil;

public class MyLongRangeValidator implements Validator, StateHolder {
    
    public static final String VALIDATOR_ID    = "MyLongRangeValidator";
    public static final String NOT_IN_RANGE_MESSAGE_ID = "NotInRangeID";
    public static final String MINIMUM_MESSAGE_ID = "MinId";
    public static final String MAXIMUM_MESSAGE_ID = "MaxId";
    public static final String TYPE_MESSAGE_ID = "javax.faces.validator.LongRangeValidator.TYPE_detail";
    private Long minimum = null;
    private Long maximum = null;

    // CONSTRUCTORS
    public LongRangeValidator() {
    }

    /**
    *
    * @param facesContext
    * @param uiComponent
    * @param value
    */
    public void validate(FacesContext facesContext,
    UIComponent uiComponent,
    Object value)
    throws ValidatorException {
        if (facesContext == null) throw new NullPointerException("facesContext");
        if (uiComponent == null) throw new NullPointerException("uiComponent");
        if (value == null){
            return;
        }
        //set maximum and minimum values
        if(uiComponent.getAttributes().get("minimum") != null) {
            setMinimum(Long.valueOf((String)uiComponent.getAttributes().get("minimum")));
        }
        if(uiComponent.getAttributes().get("maximum") != null) {
            setMaximum(Long.valueOf((String)uiComponent.getAttributes().get("maximum")));
        }
        long lvalue = parseLongValue(facesContext, uiComponent,value);
        if (minimum != null && maximum != null) {
            if (lvalue < minimum.longValue() || lvalue > maximum.longValue()) {
                List list = new ArrayList();
                list.add(uiComponent.getClientId());
                list.add(minimum);
                list.add(maximum);
                throw new ValidatorException(new FacesMessage(MessageUtil.getMessage(NOT_IN_RANGE_MESSAGE_ID,list,facesContext)));
            }
        } else if (minimum != null) {
            if (lvalue < minimum.longValue()) {
                List list = new ArrayList();
                list.add(uiComponent.getClientId());
                list.add(minimum);
                list.add(maximum);
                throw new ValidatorException(new FacesMessage(MessageUtil.getMessage(MINIMUM_MESSAGE_ID,list,facesContext)));
            }
        } else if (maximum != null) {
            if (lvalue > maximum.longValue()) {
                List list = new ArrayList();
                list.add(uiComponent.getClientId());
                list.add(minimum);
                list.add(maximum);
                throw new ValidatorException(new FacesMessage(MessageUtil.getMessage(MAXIMUM_MESSAGE_ID,list,facesContext)));
            }
        }
    }
    private long parseLongValue(FacesContext facesContext, UIComponent uiComponent, Object value)
    throws ValidatorException {
        if (value instanceof Number) {
            return ((Number)value).longValue();
        } else {
            try {
                return Long.parseLong(value.toString());
            }
            catch (NumberFormatException e) {
                List list = new ArrayList();
                list.add(uiComponent.getClientId());
                list.add(minimum);
                list.add(maximum);
                throw new ValidatorException(new FacesMessage(MessageUtil.getMessage(TYPE_MESSAGE_ID,list,facesContext)));
            }
        }
    }
    // GETTER & SETTER
    public long getMaximum() {
        return maximum != null ? maximum.longValue() : Long.MAX_VALUE;
    }
    public void setMaximum(long maximum){
        maximum = new Long(maximum);
    }
    public long getMinimum() {
        return minimum != null ? minimum.longValue() : Long.MIN_VALUE;
    }
    public void setMinimum(long minimum) {
        minimum = new Long(minimum);
    }
}
 

faces-config.xml:


<validator>
 <validator-id>myLongRangeValidator</validator-id>
 <validator-class>com.hello.webapp.MyLongRangeValidator</validator-class>
</validator>

Page Usage:

<h:inputText id="year" size="2" required="true" maxlength="2" value="Year" styleClass="validatecomp alignR imeDisabled" readonly="#{myForm.allReadonly and myForm.notReadonly}">
 <!-- validateLongRange start -->
 <f:validator validatorId="insCoreLongRangeValidator" />
 <f:attribute name="minimum" value="1" />
 <f:attribute name="maximum" value="99" />
 <f:attribute name="labelId" value="yearLabel"/>
 <!-- validateLongRange end -->
</h:inputText>

Requiring a Value


If a UIInput component does not have the required attribute set to  true  and the user does not enter a value, then the validator will not be called. Remember to set  required="true" , if you want to force validation.