Wednesday, July 8, 2015

How to Solve: SQL Developer can’t start because MSVCR71.dll is missing (On Windows)


I have installed SQL Developer (with JDK) on Windows first time,I facing the system error bellow when trying to execute it.




We can easily fix this issue by following these simple steps:
  1. Run regedit (remember to run it as the administrator)
  2. Expand HKEY_LOCAL_MACHINE
  3. Expand SOFTWARE
  4. Expand Microsoft
  5. Expand Windows
  6. Expand CurrentVersion
  7. Expand App Paths
  8. At App Paths, add a new KEY called sqldeveloper.exe
  9. Expand sqldeveloper.exe
  10. Modify the (DEFAULT) value to the full pathway to the sqldeveloper executable (See example below step 11)
  11. Create a new STRING VALUE called Path and set it value to the sqldeveloper pathway + \jdk\jre\bin




  12. After the step 11 is completed, please enjoy your SQLDEVELOPER

Monday, June 1, 2015

How To Modify Server Banner in JBoss 6 & 7

By default JBoss application server will have its own identity in HTTP response header. For security reason, if you don’t want to expose – you can modify.

Default Configuration will display Server banner as following HTTP response header
Server: Apache-Coyote/1.1
JBossAS 6:
  Open JBoss_HOME/deploy/jbossweb.sar/server.xml 
 <Connector protocol="HTTP/1.1" port="${jboss.web.http.port}" address="${jboss.bind.address}" 
         redirectPort="${jboss.web.https.port}" server="JbossSecureServer" xpoweredBy="false"/>
Jboss 7 : 
Implementation:
  • Go to JBoss/bin folder
  • Add following in standalone.conf under JAVA_OPTS variable
-Dorg.apache.coyote.http11.Http11Protocol.SERVER=JbossSecureServer
Ex:
JAVA_OPTS="-Xms512m -Xmx512m -XX:MaxPermSize=256m -Xss168K 
-Djava.net.preferIPv4Stack=true -Dorg.jboss.resolver.warning=true 
-Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 
-Dfile.encoding=UTF-8 
-Dorg.apache.coyote.http11.Http11Protocol.SERVER=JbossSecureServer"
  • Restart JBoss 7 Application server and you should see Server banner is changed as following in HTTP response header now.
Server: JbossSecureServer

Friday, May 29, 2015

Redirect HTTP to HTTPS using Servlet Filter

Method - I
1. Write a filter to redirect from http to https
package com.sample.servlet;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class HTTPSFilter implements Filter {
 
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws java.io.IOException, ServletException {
 
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
 
String uri = req.getRequestURI();
String getProtocol = req.getScheme();
String getDomain = req.getServerName();
String getPort = Integer.toString(req.getServerPort());
 
if (getProtocol.toLowerCase().equals("http")) {
 
// Set response content type
response.setContentType("text/html");
 
// New location to be redirected
String httpsPath = "https" + "://" + getDomain + ":" + getPort
+ uri;
 
String site = new String(httpsPath);
res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
res.setHeader("Location", site);
}
 
// Pass request back down the filter chain
chain.doFilter(req, res);
 
}
 
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
 
}
 
@Override
public void destroy() {
// TODO Auto-generated method stub
 
}
 
}
2. Compile above filter and create following entries in web.xml


HTTPS
com.sample.servlet.HTTPSFilter


HTTPS
/*

Method - II
1. Add the below snippet to your Web.xml


SessionTest
/*


CONFIDENTIAL


I preferably use Method - II , if not work's for some servers like Trifork 4.1.3.6 go for Method -I . I hope this article will helps you.

Sunday, May 17, 2015

StaxEventItemWriter writes extra end document tag


I using spring batch for reading data from db and writing to XML file i am choosed the "StaxEventItemWriter" writes. it generating the xml file fine but with extra end document tag at the end. You can find the bug Here, due to this my batch process was failed to read the same XML file. I surf the internet and i found the one of the solution and  implemented the below. Now my XML files are generated without the extra end document tag. Now all my batches are working fine.

Solution:

import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;

import org.springframework.batch.item.xml.StaxEventItemWriter;

/**
 * @author sunilkumar.gutti
 * 
 */
@SuppressWarnings("rawtypes")
public class ShipmentStaxEventItemWriter extends StaxEventItemWriter {
    @Override
    protected void endDocument(XMLEventWriter writer) throws XMLStreamException {
        XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        if (outputFactory.isPropertySupported("com.ctc.wstx.autoCloseElements")) {
            outputFactory.setProperty("com.ctc.wstx.autoCloseElements", false);
        }
    }

}

Spring batch restrict single instance of job only

I have one spring batch job which can be kicked of by rest URL. I want to make sure only one job instance is allowed to run. and if another instance already running then don't start another. even if the parameters are different.
I searched and found nothing out of box solution. thinking of extending SimpleJobLauncher. to check if any instance of the job running or not.
Answers
You could try to intercept the job execution, implementing the JobExecutionListener interface:
public class MyJobExecutionListener extends JobExecutionListener {

//active JobExecution, used as a lock.
private JobExecution _active;

public void beforeJob(JobExecution jobExecution) {
    //create a lock
    synchronized(jobExecution) {
        if(_active!=null && _active.isRunning()) {
            jobExecution.stop();
        } else {
            _active=jobExecution;
        }
    }
}

public void afterJob(JobExecution jobExecution) {
      //release the lock
      synchronized(jobExecution) {
          if(jobExecution==_active) {
            _active=null; 
          }
      }
}
}
And then, inject to the Job definition:
<job id="myJobConfig">
    <listeners>
        <listener ref="myListener"/>
    </listeners>
</job>

Or, in response to REST URL, check using JobExplorer if your job is running using job's specifics business rules

I solved this by creating an JobExecutionListner and with the help of JobExplorer I checked if any other instance is running if running then stop current job.I created listener so that it can be plugged in to any job that requires this kind of scenario.
Set<JobExecution> jobExecutions = ((SimpleJobExplorer) jobExplorer.getObject()).findRunningJobExecutions(jobExecution.getJobInstance().getJobName());
            if(jobExecutions.size()>1){
                Long currentTime = (new Date()).getTime();
                for(JobExecution execution : jobExecutions ){
                    if(execution.getJobInstance().getId().compareTo(jobExecution.getJobInstance().getId())!=0 && (currentTime - execution.getStartTime().getTime()) <lockOverideTime){
                        jobExecution.stop();
                        throw new IllegalStateException("Another instance of the job running job name : " +jobExecution.getJobInstance().getJobName() );

                    }
                }

            }

source : here

[Solved] :Spring Batch Stax XML reading job is not ending when out of input

Spring Batch Stax XML reading job is not ending when out of input

I'm using Spring Batch to set up a job that will process a potentially very large XML file. I think I've set it up appropriately, but at runtime I'm finding that the job runs, processes its input, and then just hangs in an executing state (I can confirm by viewing the JobExecution's status in the JobRepository).
I've read through the Batch documentation several times but I don't see any obvious "make the job stop when out of input" configuration that I'm missing.
Here's the relevant portion of my application context:
<job id="pickupDataExtractionJob" xmlns="http://www.springframework.org/schema/batch">
        <step id="read" next="write">
            <tasklet>
                <chunk reader="jdbcItemReader" writer="xmlItemWriter" commit-interval="5" retry-limit="3" >
                    <retryable-exception-classes>
                        <include class="java.lang.Exception"/>
                        <include class="java.sql.SQLException"/>
                        <include class="org.springframework.dao.DeadlockLoserDataAccessException"/>
                    </retryable-exception-classes>
                </chunk>
            </tasklet>
        </step>
        <step id="write" next="rename">
            <tasklet>
                <chunk reader="xmlItemReader" writer="jdbcItemWriter" commit-interval="5"  retry-limit="3" >
                    <retryable-exception-classes>
                        <include class="java.io.FileNotFoundException"/>                       
                        <include class="java.sql.SQLException"/>
                        <include class="org.springframework.dao.DeadlockLoserDataAccessException"/>
                    </retryable-exception-classes>
                </chunk>
            </tasklet>
        </step>
        <step id="rename" next="deleteDir">
            <tasklet ref="renameTaskLet" />
        </step>
        <!-- <step id="email" next="deleteDir">
            <tasklet ref="emailTaskLet" />
        </step> -->
        <step id="deleteDir">
            <tasklet ref="fileDeletingTasklet" />
        </step>
    <listeners>
        <listener ref="processShutdownListener"></listener>
    </listeners> 
    </job>
    <bean id="renameTaskLet"
        class="com.kewill.bluedart.pos.batch.tasklet.SimpleRenameFileTaskletStep" />
    <bean id="emailTaskLet" class="com.kewill.bluedart.pos.batch.tasklet.SendEMailTasklet" />
    <bean id="fileDeletingTasklet" class="com.kewill.bluedart.pos.batch.tasklet.FileDeletingTasklet">
        <property name="directory" value="file:${batch.path}" />
    </bean>

Tuesday, April 21, 2015

Solution:IE 10 and below + Escape twice form values are clearing

Problem: IE 10 and below + Escape twice form values are clearing all input values/ Reset the form values.

Solution:

Add the below script to your document ready function.

$('input[type="text"]').keydown(function(e){
               var ingnore_key_codes = [27];
               if ($.inArray(e.keyCode, ingnore_key_codes) >= 0){
                  e.preventDefault();
               }
        });

Monday, April 20, 2015

Spring @PathVariable mapping incomplete path when dots are included

Spring @PathVariable mapping incomplete path when dots are included

In all my projects this happens at least once, and I'm surprised over and over again: a controller will not map just anything to @PathVariable by default. Contrary to intuition, the annotation's argument is a regular expression which excludes some characters per default. For instance the url

http://localhost:8080/myapp/api/user/testuser@example.com

when mapped to a controller:

@RequestMapping(value = "/getProxyUserDetails/{email}")
ModelAndView findUserByEmail(@PathVariable("email") String email){

// email = testuser@example

 
}
will result in "testuser@example" ... missing the ".com" suffix.

The correct mapping is:

@RequestMapping(value = "/getProxyUserDetails/{email:.*}")
ModelAndView findUserByEmail(@PathVariable("email") String email){

// email = testuser@example.com

 
}

Tuesday, April 14, 2015

Weblogic (10.3.6.0): Caused by: java.lang.ClassCastException: org.eclipse.persistence.jpa.PersistenceProvider cannot be cast to javax.persistence.spi.PersistenceProvider

Problem : When performing the transaction in application (Deployed in web logic (10.3.6.0) Caused by: java.lang.ClassCastException: org.eclipse.persistence.jpa.PersistenceProvider cannot be cast to javax.persistence.spi.PersistenceProvider

Solution :

Web.xml:
 Add customer listener class to resolve the persistence provider.

<listener>
        <listener-class>com.kewill.bluedart.weblogic.POSWeblogicPresistenceListener</listener-class>
</listener>


POSWeblogicPresistenceListener.java (Customer Listener class):

package com.kewill.bluedart.weblogic;

import javax.servlet.ServletContextEvent;

public class POSWeblogicPresistenceListener implements javax.servlet.ServletContextListener {

    public void contextDestroyed(ServletContextEvent arg0) {

    }

    public void contextInitialized(ServletContextEvent arg0) {
        HibernatePersistenceProviderResolver.register();
    }
}


HibernatePersistenceProviderResolver.java (Custom Persistence provider resolver class):
package com.kewill.bluedart.weblogic;

import java.util.Collections;
import java.util.List;

import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceProviderResolver;
import javax.persistence.spi.PersistenceProviderResolverHolder;

import org.apache.log4j.Logger;
import org.hibernate.ejb.HibernatePersistence;

public class HibernatePersistenceProviderResolver implements
        PersistenceProviderResolver {
    private static final Logger LOGGER = Logger.getLogger(HibernatePersistenceProviderResolver.class.getName());

    private volatile PersistenceProvider persistenceProvider = new HibernatePersistence();

    @Override
    public List<PersistenceProvider> getPersistenceProviders() {
        return Collections.singletonList(persistenceProvider);
    }

    @Override
    public void clearCachedProviders() {
        persistenceProvider = new HibernatePersistence();
    }

    public static void register() {
        LOGGER.info("Registering HibernatePersistenceProviderResolver");
        PersistenceProviderResolverHolder
                .setPersistenceProviderResolver(new HibernatePersistenceProviderResolver());
    }
}


webloigc.xml (Weblogic delopyment descriptor):

<?xml version = '1.0' encoding = 'windows-1252'?>
<weblogic-web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.1/weblogic-web-app.xsd"
    xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app">
    <container-descriptor>
        <index-directory-enabled>true</index-directory-enabled>
        <prefer-application-packages>
            <package-name>antlr.*</package-name>
            <package-name>org.springframework.*</package-name>
            <package-name> org.apache.commons.*</package-name>
            <package-name>org.apache.xmlbeans.*</package-name>
            <package-name>org.hibernate.*</package-name>
            <package-name>org.hibernate.validator.*</package-name>
            <package-name>javax.persistence.*</package-name>

            <package-name>org.joda.*</package-name>
            <package-name>com.sun.xml.*</package-name>
        </prefer-application-packages>
        <prefer-application-resources>
            <resource-name>META-INF/services/javax.servlet.ServletContainerInitializer</resource-name>
            <resource-name>META-INF/spring.handlers</resource-name>
        </prefer-application-resources>
    </container-descriptor>
    <context-root>user context path</context-root>
</weblogic-web-app>


Do all the above changes. weblogic.xml : will change as per your project dependencies. No i resolved the above issue. I hope it will helps you to resolve the same.

Friday, February 20, 2015

CREATE DATASOURCE IN JBOSS AND INTEGRATE WITH SPRING + HIBERNATE + INTEGRATED + APPLICATION



Create JNDI – Data source in JBoss:
Step1:
ü  Create a folder structure Path: JBOSS_HOME\modules\system\layers\base\com\oracle\jdbc\main
ü  Copy oracle driver jar to this folder
ü  Create module.xml as below
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.oracle.jdbc">
    <resources>
        <resource-root path="oraclejdbc-11.2.0.4.jar"/>
        <!-- Insert resources here -->
    </resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.servlet.api" optional="true"/>
    </dependencies>
</module>
Step 2: configure data source in standalone:
ü  JBOSS_HOME\standalone\configuration\standalone.xml and the below code under the  <subsystem xmlns="urn:jboss:domain:datasources:1.1"> tag.
  <datasource jta="false" jndi-name="java:jboss/jdbc/OracleDSJNDI" pool-name="ORACLE" enabled="true" use-ccm="false">
            <connection-url>jdbc:oracle:thin:@192.168.74.98:1521:coredb</connection-url>
                    <driver>OracleJDBCDriver</driver>
                    <pool>
                        <min-pool-size>10</min-pool-size>
                        <max-pool-size>300</max-pool-size>
                        <flush-strategy>IdleConnections</flush-strategy>
                    </pool>
                    <security>
                        <user-name>BLDPOS_QA</user-name>
                        <password>bluedart</password>
                    </security>
                    <validation>
                        <validate-on-match>false</validate-on-match>
                        <background-validation>false</background-validation>
                    </validation>
                    <timeout>
                        <idle-timeout-minutes>100</idle-timeout-minutes>
                    </timeout>
                    <statement>
                        <track-statements>nowarn</track-statements>
                        <share-prepared-statements>false</share-prepared-statements>
                    </statement>
      </datasource>
ü  Add driver configuration under the <drivers> as below
                    <driver name="OracleJDBCDriver" module="com.oracle.jdbc">
                        <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
                    </driver>

Step 3: Star/Re-start your server to effect these changes

Ø  If you want to reconfigure connection pool navigate to pool tab à click Edit à save the changes and restart the server

Accessing – in Application:
Step1: Integrate your spring + hibernate with JNDI configured in jboss by changing your database configuration like below