Tuesday, April 19, 2016

Sql developer connection times out very frequently

Solution 1: (Didn't work)
  1. Download oracle instant client
    http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
  2. Unzip and put it somewhere within your directory
  3. Within your Sql Developer, Tools – Preferences –> Database->Advanced
    1. Check use oracle client 
    2. Click on configure
      1. client type: instant client
      2. client location: C:\javapps\oraclexe\instantclient-basic-windows.x64-12.1.0.2.0\instantclient_12_1
  4. Open sqlnet.ora file on server side and put this line
    SQLNET.EXPIRE_TIME=1
  5. Restart your Sql Developer and server, if necessary
That’s it. The connection between Sql Developer and Oracle XE should be fine now.

Solution 2: (This worked for my environment)
This can be caused by and Out Of Bands (OOB) error in the jdbc driver on the network.To ignore this error, add this to sqldeveloper.conf file
AddVMOption -Doracle.net.disableOob=true

Thursday, May 16, 2013

Query to return fresh data


import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;
...
@NamedQuery(name = "findSamplesById", 
query = "select s from Sample s where s.sample.id = :sampleId"), 
hints = {@QueryHint(name=QueryHints.REFRESH, value=HintValues.TRUE)}

Programmatical method

public List<Sample> getSamplesById() {
        try {
            Query query = em.createNamedQuery("findSamplesById");
            query.setParameter("sampleId", sampleId);
            query.setHint(QueryHints.REFRESH, HintValues.TRUE);
            return query.getResultList();
        } catch (Exception e) {
            log.error("getSamplesById() failed: " + e.getMessage());
            e.printStackTrace(System.err);
        }
 return null;
}

Tuesday, April 23, 2013

javascript submit is not a function

Javascript:
When you try to call submit() from javascript like the one below,
function addRule() {
var ff=document.forms["testForm"];
ff.wizardAction.value="ADD";
ff.submit();
}

Error Message:
submit is not a function

Resolution:
It means that you named your submit button or some other element submit. Rename such button(s) to some other name and your call will magically work.

When you name the button submit, you override the submit() function on the form.

dynamic id styleId struts html tag

If you want the html ids to be generated dynamically such as 
<input type="text" name="rule" id="rule0">

check this 
<% int index = 0; %>
<html:text property="rule" styleid='<%="rule"+index%>' />
<% index++;%>

Common mistake:
<html:text property="rule" styleid="rule<%=index%>">
shows up on html,
<input type="text" name="rule" id="rule<%=index%>">



Thursday, April 18, 2013

Gems Tibco JMS Putty Xming

Tibco Enterprise service (EMS) is a fully complaint JMS implementation from TIBCO with some added enhancements like load-balancing, routing, fault-tolerant configurations, which help improve performance and minimize failures in the server.

Gems is a graphical user interface utility for TIBCO Enterprise Message Service  (EMS). It can be used by JMS developers as a general purpose test debugging tool and by  administrative support staff as a management and monitorig tool.

What do we do with this ?? I am primarily using this to
  • Server Management. Including, general server configuration, JMS destinations,  JNDI factories, users/groups, permissions, bridges, routes etc.
  • JMS support. Messages may be sent/received, queues may be browsed and message  contents inspected. Selectors and filters may be specified.
  • JMS Message Monitoring. Messages may be monitored (snooped) as they pass trough  the server. Request and reply messages can be correlated to provide service  response times.
  • JMS Message Management. Eg; purging messages, copy messages from a queue to  another queue on a different server.
  • Security. SSL connectivity, view only mode.

    Can i access this gems from putty directly??? No, you need  Xming (http://sourceforge.net/projects/xming/)

    What is Xming??
    We can run graphical programs on Linux/Solaris machines remotely and display them on your desktop computer running Windows. We can do this by using running two applications together on your Windows machine: Xming and PuTTY.

    1. Navigate to the Files section and download:
    • Xming setup from the Xming folder
    • the fonts package installer from the Xming-fonts folder
    1. By default both programs will be installed into the same location, so don't the worry about over writing files. We cannot work without both packages.
    2. Once installed, running All Programs > Xming > XLaunch is a good idea to see what the configuration looks like. In most cases, the default options should be just fine.
    3. Finally run All Programs > Xming > Xming to start the PC X Server. The “X” icon should be visible on the Windows Taskbar. The X Server must be started before setting up a SSH connection to a remote system.
    What is PuTTY ?? 
    As we all know, PuTTY is a free SSH client. Through PuTTY we connect to a remote machine. 

    Any Configuration needed on PuTTY, to run GEMS??? Yes
    Under Session, enter the hostname, port 22, connection type is ssh
    Connection > SSH > X11. Check the box next to Enable X11 Forwarding. By default the X Display location is empty. You can enter localhost:0. The remote authentication should be set to MIT-Magic-Cookie-1

    navigate to the desired folder and run
    ./xxxxxx.sh &
    & runs the command in background so that you can work on your terminal and run the graphical application.


  • Wednesday, March 27, 2013

    extra white space in textarea

    <textarea>
    <c:forEach var="item" items="${items}">
    <c:out value="welcome"/>
    </c:forEach>
    </textarea>

    This gives unnecessary white spaces in the text area. Remove the extra white space between textarea tags. Although this might sound crazy, this works.

    <textarea><c:forEach var="item" items="${items}"><c:out value="welcome"/></c:forEach></textarea>



    Friday, March 15, 2013

    jmagick configuration


    1. Go to http://downloads.jmagick.org/6.3.9/
    2. Download ImageMagick-6.3.9-0-Q8-windows-dll.exe and jmagick-win-6.3.9-Q8.zip.
    3. Install the exe file. This will install ImageMagick which is a prerequisite for JMagick to work.
    4. Extract the zip file. This will give jmagick.dll and jmagick.jar
    5. Copy the jmagick.jar to you lib folder and include it in the classpath
    6. Copy the jmagick.dll to the root installation directory of ImageMagic and add it as an entry to the PATH environment variable

    Tuesday, March 5, 2013

    xmlbeans runtime error NoSuchMethodError


    You might get this run time error when you have two copies of proj-xmlbeans.jar on your classpath, one of which is a old one. 

    check your APP-INF directory. In my case, APP-INF is the culprit. It has the new generated xmlbeans version and the old one as well.


    Friday, December 14, 2012

    Weblogic start up problems

    weblogic.security.service.SecurityServiceRuntimeException: [Security:090399]Security Services Unavailable

    Was the weblogic admin password changed in boot.properties?
    If yes, then rename boot.properties (/Servers/AdminServer/security) to something else and try to start the server now. You can check for the logs under DOMAIN_DIR/Severs/AdminServer/log

    If it doesn't work, try to rename ldap directory (DOMAIN_HOME/Severs/AdminServer/data/ldap) and then try to start the server.

    Tuesday, October 25, 2011

    Timestamp problem with SQL Developer

    SQL developer doesn't display timestamp for any query result.

    Simple Fix:
    In Oracle SQLDeveloper Go to: Tools >> Preferences >> Database > NLS Parameters and update your Date Format field to DD-MON-RR HH:MI:SS value

    Wednesday, August 10, 2011

    toArray() class cast exception

    List<Record> recordsList = new ArrayList<Record>(2);
    ...
    Record[] records = (Record[]) recordsList.toArray() ; //incorrect
    Record[] records = (Record[]) recordsList.toArray(new Record[2]); //correct

    Why Class cast exception ?
    Recall that a Collection can contain objects of vastly different types. There's no 'general' rule that objects in a Collection must all be of the exact same type. So when toArray() is being calling, it allocates a typed array Object[] which has no sub-classes defined. Therefore casting it to any form such as (Record[]), will not work.

    toArray() method can't see your cast so you have to tell it what kind of array to make.

    Friday, May 20, 2011

    create a folder structure outside of your application directory



    private static final String UPLOAD_DIRECTORY = "uploads/img/"+now;

    Date date = new Date() ;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd") ;
    String now = dateFormat.format(date);

    File uploadsFolder = new File(UPLOAD_DIRECTORY);
    uploadsFolder.mkdirs();

    File uploadedFile = new File(uploadsFolder, "fileName");

    Replace Back slash with forward slash


    String location = "uploads\img";
    String backslash= System.getProperty(
    location.replace(backslash,

    or

    location.replace("\\", "/");"/");"file.separator") ;

    gwtupload - File Upload with GWT

    1. Download last version of the library: gwtupload-x.x.x.jar and include it in your classpath.

    2. Add these libraries to your application: commons-fileupload-1.2.jar, commons-io-1.3.1.jar and log4j.jar

    3. Edit your module file: Xxx.gwt.xml.
    <module>

     
    <!-- Include GWTUpload library -->
     
    <inherits name="gwtupload.GWTUpload"/>
     
    <!-- Load dinamically predefined styles in the library when the application starts -->
     
    <stylesheet src="Upload.css"/>
     
     
    <!-- Change this line with your project's entry-point -->
     
    <entry-point class="package.Xxx"/>
    </module>

    4. Edit your web.xml and include your customized servlet (extending ActionUpload and overriding executeAction). Be aware that the servlet provided depends on these libraries: commons-fileupload, commons-io and log4j, so include them in your package.
    <context-param>
       
    <!-- max size of the upload request -->
       
    <param-name>maxSize</param-name>
       
    <param-value>3145728</param-value>
     
    </context-param>
     
    <context-param>
       
    <!-- Useful in development mode to slow down the uploads in fast networks.
             Put the number of milliseconds to sleep in each block received in the server.
             false or 0, means don't use slow uploads  -->

       
    <param-name>slowUploads</param-name>
       
    <param-value>200</param-value>
     
    </context-param>

     
    <servlet>
       
    <servlet-name>uploadServlet</servlet-name>
       
    <!-- This is the default servlet, it puts files in session -->
       
    <servlet-class>xxxxx.server.servlet.UploadServlet</servlet-class>
     
    </servlet>
     
    <servlet-mapping>
       
    <servlet-name>uploadServlet</servlet-name>
       
    <url-pattern>/xxx/upload</url-pattern>
     
    </servlet-mapping>

      5. Create your client application
      public class MultipleUploadSample implements EntryPoint {

       
      // A panel where the thumbnails of uploaded images will be shown
       
      private FlowPanel panelImages = new FlowPanel();

       
      public void onModuleLoad() {
         
      // Attach the image viewer to the document
         
      RootPanel.get("thumbnails").add(panelImages);
         
         
      // Create a new uploader panel and attach it to the document
         
      MultiUploader defaultUploader = new MultiUploader();
         
      RootPanel.get("default").add(defaultUploader);

         
      // Add a finish handler which will load the image once the upload finishes
          defaultUploader
      .addOnFinishUploadHandler(onFinishUploaderHandler);
       
      }

       
      // Load the image in the document and in the case of success attach it to the viewer
       
      private IUploader.OnFinishUploaderHandler onFinishUploaderHandler = new IUploader.OnFinishUploaderHandler() {
         
      public void onFinish(IUploader uploader) {
           
      if (uploader.getStatus() == Status.SUCCESS) {

             
      new PreloadedImage(uploader.fileUrl(), showImage);
             
             
      // The server sends useful information to the client by default
             
      UploadedInfo info = uploader.getServerInfo();
             
      System.out.println("File name " + info.name);
             
      System.out.println("File content-type " + info.ctype);
             
      System.out.println("File size " + info.size);

             
      // You can send any customized message and parse it
             
      System.out.println("Server message " + info.message);
           
      }
         
      }
       
      };

       
      // Attach an image to the pictures viewer
       
      private OnLoadPreloadedImageHandler showImage = new OnLoadPreloadedImageHandler() {
         
      public void onLoad(PreloadedImage image) {
            image
      .setWidth("75px");
            panelImages
      .add(image);
         
      }
       
      };
      }

      6. create your customized servlet
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.IOException;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.Hashtable;
      import java.util.List;

      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;

      import org.apache.commons.fileupload.FileItem;
      import org.apache.commons.io.FilenameUtils;
      import org.apache.log4j.Logger;

      import gwtupload.server.UploadAction;
      import gwtupload.server.exceptions.UploadActionException;


      public class UploadServlet extends UploadAction {

       private static final long serialVersionUID = 1L;
       private static Logger log = Logger.getLogger(UploadServlet.class);

       Hashtable<String, String> receivedContentTypes = new Hashtable<String, String>();

       /**
        * Maintain a list with received files and their content types.
        */
       Hashtable<String, File> receivedFiles = new Hashtable<String, File>();

       /**
        * Override executeAction to save the received files in a custom place
        * and delete this items from session. 
        * @return
        */

       @Override
       public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
        String response = "";
           int cont = 0;
           System.out.println("In ExecuteAction - UploadServlet Called");
           for (FileItem item : sessionFiles) {
            if (false == item.isFormField()) {
             cont ++;
                try {


                 final String UPLOAD_DIRECTORY = "uploads/application/"+now;  
             
                 Date date = new Date() ;
                 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd") ;
                 String now = dateFormat.format(date);
               
                 File uploadsFolder = new File(UPLOAD_DIRECTORY);
                 uploadsFolder.mkdirs();
               
                 String fileName = item.getName();
               
                 // get only the file name not whole path
                 if (fileName != null) {
                  fileName = FilenameUtils. getName(fileName); // uploaded file filename
                 }
               
                 File uploadedFile = new File(uploadsFolder, fileName);
                 item.write(uploadedFile);
               
                 /// Save a list with the received files
                 receivedFiles.put(item.getFieldName(), uploadedFile);
                 receivedContentTypes.put(item.getFieldName(), item.getContentType());
               
                 /// Send a customized message to the client.
                 response += uploadedFile;
               
                } catch (Exception e) {
                 throw new UploadActionException(e);
                }
            }
           }
          
           /// Remove files from session because we have a copy of them
           removeSessionFileItems(request);
          
           /// Send your customized message to the client.
           return response;
       }
        
       /**
        * Get the content of an uploaded file.
        */
       @Override
       public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fieldName = request.getParameter(PARAM_SHOW);
           File f = receivedFiles.get(fieldName);
           if (f != null) {
            response.setContentType(receivedContentTypes.get(fieldName));
            FileInputStream is = new FileInputStream(f);
            copyFromInputStreamToOutputStream(is, response.getOutputStream());
           } else {
            renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND);
           }
         }
        
       /**
        * Remove a file when the user sends a delete request.
        */
       @Override
       public void removeItem(HttpServletRequest request, String fieldName)  throws UploadActionException {
        File file = receivedFiles.get(fieldName);
           receivedFiles.remove(fieldName);
           receivedContentTypes.remove(fieldName);
           if (file != null) {
            file.delete();
           }
       }

      }

      Tuesday, May 10, 2011

      Class cast exception while casting the list object to the domain object

      Problem:
      TestDomainObj test = (TestDomainObj) session.createSQLQuery(query).list();  // class cast exception occurs

      Solution:
      (TestDomainObj) session.createSQLQuery(query)
      .addEntity(TestDomainObj.class)
      .list();

      CreateQuery returns an java.lang.Object array. We can't cast it to our mapped object.
      AddEntity fills the mapped object to the appropriate value, so that we can now use our mapped object other than object array

      Thursday, April 28, 2011

      Unable to locate Spring NamespaceHandler

      Error:
      org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/tx] Offending resource: class path resource [applicationContext.xml]
      Solution: Add spring-tx.jar to WEB-INF/lib

      Error:
      org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security] Offending resource: class path resource [applicationContext.xml]
      Solution: Add spring-core, spring-acl, spring-config, spring-web, spring-taglibs jars to WEB-INF/lib

      Thursday, March 31, 2011

      To supress the class attribute 'sql-timestamp' in xstream

      I declared createdate as java.util.date in DTO and in the hibernate mapping its been declared as timestamp. So it is trying to marshal a timestamp while datamember is date.
      <createDate class="sql-timestamp"> .... </createDate>

      To suppress this, either change the date to timestamp in your dto class or
      you may set a java.sql.Timestamp as (another) default implementation for a java.util.Date or
      you may remove the class attribute completely, something like

      StringWriter writer = new StringWriter();
      xstream.marshal(this, new PrettyPrintWriter(writer) {
      @Override
      public void addAttribute(final String key, final String value) {
      if (!key.equals("class")) {
      super.addAttribute(key, value);
      }
      }
      });

      Thursday, March 24, 2011

      problem inserting timestamp into the database

      The equivalent hibernate type for Date is date, time, timestamp.

      So check your hibernate level of mapping the date fields.
      <property name="createDate" type ="timestamp">...</property>

      Wednesday, February 16, 2011

      Apache Tomcat V6x

      Issue: OutOfMemoryError: Java heap space, PermGen space
      To increase the memory in tomcat, edit catalina.bat file  (<tomcat-install>\bin\catalina.bat) and include
      -Xms256m
      -Xmx1024m
      -XX:MaxPermSize=512m

      Example:
      set JAVA_OPTS=%JAVA_OPTS% 
      -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
      -Djava.util.logging.config.file="%CATALINA_BASE%\conf\logging.properties"
      -Xms256m
      -Xmx1024m
      -XX:MaxPermSize=512m

      Thursday, January 20, 2011

      GWT with Maven

      1. Install the plugins depending on your eclipse version(my eclipse version is 3.5) - gwt for eclipse(http://dl.google.com/eclipse/plugin/3.5), m2eclipse(http://m2eclipse.sonatype.org/sites/m2e)
      2. To create a maven based gwt project with GWT's webAppCreator utility, simply specifiy send -maven -noant as options. Say for example, webAppCreator -maven -noant -out C:\sample -junit C:\eclipse\plugins\org.junit4_4.5.0.v20090824\junit.jar com.testing.sample.sample
      3. Once the folder structure is created, use mvn eclipse:eclipse and import the project to eclipse
      4. Apply the tool kit settings to your project: Select your project - Right click - Google -Web Toolkit settings - check the use Google Web Toolkit and select the appropriate gwt version
      5. Compile: Select your project - Right click - Google - GWT compile
      6. Run: Select your project - Right click - Run as - Web Application
      Maven Issues:
      [ISSUE] M2_REPO (non modifiable)

      Eclipse picks the value of M2_REPO from $MAVEN_HOME/conf/settings.xml using <localRepository> element. If nothing is specified, then ${user.home}/.m2 becomes the m2_repo path. Also verify the version of the maven from eclipse (preferences->maven->user settings).

      Build Issues:
      [ISSUE] The project doesn't have GWT SDK on its build path
      check the order of your GWT SDK in the 'order and export' tab on your project build path.  gwt sdk library must appear before the maven dependencies. so, move it up in the order.


      Compiler Issues:
      [ERROR] Line 12: No source code is available for type com.google.gwt.junit.client.GWTTestCase; did you forget to inherit a required module?
      add this to your *.gwt.xml <inherits name="com.google.gwt.junit.JUnit"/>

      Run Issues:
      [ERROR] Could not find host pages in the project 
      Go to the project properties -> build path -> configure build path -> Select Google - WebApplication -> check 'This project has a WAR directory' - specify war directory as 'src/main/webapp'