read a file inside a Jar file

Hi All,

In this article I will explain how to read a text or csv or prop file from jar. This is very helpful when you export  files and other resources into JAR files to distribute your Java application. So many time we face issues like FileNotFound while accessing the resources which are inside Jar file.

Always use ClassLoader to load any resource from the jar, the reason is thea whenever we are trying to invoke a class from jar, main jvm looks only to the relative position because it tries to load the same class into there, so by using the class loader means we have requested to extract more resources from the jar.
(Please correct me If any of you have some better explanation).

The below example will detailed.
Step 1: Add help.txt in the code base. e.g c:\mytest\help.txt, and add some data into it

Step 2: Write a class and add the below method

public void readFromFile() {
BufferedReader bufferedReader = null;
try {
//Construct Input Stream object, and use the java class classloader to find the resource
InputStream is = getClass().getResourceAsStream(“help.txt“); // pass the resource name
//[NOTE]: Beware that ClassLoader#getResourceAsStream returns null if the resource is not found. This will throw an ugly NPE. So always put a null check before going forward.

//Create a InputStream Reader Object from Input Stream
InputStreamReader isr = new InputStreamReader(is);

// Now pass the Input Stream into Buffered Reader, and read the input and display on the console
bufferedReader = new BufferedReader(isr);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

} catch (FileNotFoundException ex) {
ex.printStackTrace();

} catch (IOException ex) {
ex.printStackTrace();

} finally {
//Close the BufferedReader
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Note [Structure of Jar for this Example]
myjar.jar
|
– META-INF
– MyClass.class
– help.txt

Hope this helps.


Thanks
R Vashi

Advertisements

Connection Pool issue on weblogic…

Hi All,

Few moths back I have started facing problem with my connection pool, where intermittent message like “pool out of resource.. increase the pool size…” started coming in app UI, logs, causing issues with application functionality. To avoid that we thought of connection validation on Weblogic, by enabling “Test Connection on Reserve” but the real problem came just right after that when we started facing below error message in server logs.

<BEA-001112> <Test “SELECT 1 FROM DUAL” set up for pool “MyPool” failed with exception: “java.sql.SQLException: Closed Statement”.>

In our application we were using Oracle proxy connections. and then I came to know about one real fact of using Proxy connections on Weblogic. So i would like to share the same discussion with you all, hope this helps in case if you are struggling with the same.

http://forums.oracle.com/forums/message.jspa?messageID=4144460#4144460

Thanks
R Vashi


Configuring System property in weblogic

Hi All,

Sometime we need to configure few properties in server which we can easily read, without reading property files in java code/JSP code/Servlet.

Weblogic gives a very nice way to do that. Only thing we need to do is to configure the property with key value in server start options (i.e java options). We also called theses memory arguments. Just login to admin console, and go to server properties and add the below property.

-Dkey=MyValue

After setting the memory argument simply restart the server and access the property in your JSP/Java Code/Servlet

String keyValue=System.getProperty(“key”);
System.out.pritnln(“************** “+keyValue);

//output
// **************MyValue

Hope this helps.


Thanks
R Vashi

Controlling Deployment File Copying with Staging Modes in WebLogic

Hi All,

The deployment staging mode determines how deployment files are made available to target servers that must deploy an application or stand-alone module. WebLogic Server provides three different options for staging files: stage mode, nostage mode, and external_stage mode.

stage

The Administration Server first copies the deployment unit source files to the staging directories of target servers. (The staging directory is named stage by default, and it resides under the target server’s root directory.)

The target servers then deploy using their local copy of the deployment files.

  • Deploying small or moderate-sized applications to multiple WebLogic Server instances.
  • Deploying small or moderate-sized applications to a cluster.

java weblogic.Deployer -adminurl http://localhost:7001 -user weblogic
-password weblogic -name mydeploymentname
-targets myserver1,myserver2,myserver3 -stage
-deploy c:\localfiles\myapp.ear


nostage

The Administration Server does not copy deployment unit files. Instead, all servers deploy using the same physical copy of the deployment files, which must be directly accessible by the Administration Server and target servers.

With nostage deployments of exploded archive directories, WebLogic Server automatically detects changes to a deployment’s JSPs or Servlets and refreshes the deployment. (This behavior can be disabled if necessary.)

  • Deploying to a single-server domain.
  • Deploying to a cluster on a multi-homed machine.
  • Deploying very large applications to multiple targets or to a cluster where deployment files are available on a shared directory.
  • Deploying exploded archive directories that you want to periodically redeploy after changing content.
  • Deployments that require dynamic update of selected Deployment Descriptors via the Administration Console.


To use nostage mode, specify -nostage as an option to weblogic.Deployer, as in:

java weblogic.Deployer -adminurl http://localhost:7001 -user weblogic
-password weblogic -name mydeploymentname
-targets myserver1,myserver2,myserver3 -nostage
-deploy c:\localfiles\myapp.ear

external_stage

The Administration Server does not copy deployment files. Instead, the Administrator must ensure that deployment files are distributed to the correct staging directory location before deployment (for example, by manually copying files prior to deployment).

With external_stage deployments, the Administration Server requires a copy of the deployment files for validation purposes. Copies of the deployment files that reside in target servers’ staging directories are not validated before deployment.

You can use the -noversion option to turn off the requirement that deployment files be on the Administration Server, but the -noversion option causes versioning information to be ignored; therefore, you cannot use the -noversion option with versioned applications. For information, see Common Arguments.

  • Deployments where you want to manually control the distribution of deployment files to target servers.
  • Deploying to domains where third-party applications or scripts manage the copying of deployment files to the correct staging directories.
  • Deployments that do not require dynamic update of selected Deployment Descriptors via the Administration Console (not supported in external_stage mode).
  • Deployments that do not require partial redeployment of application components.

Changing the Default Staging Behavior for a Server

The server staging mode specifies the default deployment mode for a server if none is specified at deployment time. For example, the server staging mode is used if you deploy an application or stand-alone module using weblogic.Deployer and you do not specify a staging mode.

Notes: You can only change the server staging mode by using the Administration Console or by directly changing the ServerMBean via JMX.
Note: Changing the server staging mode does not affect existing applications. If you want to change the staging mode for an existing application, you must undeploy the application deployment and then redeploy it with the new staging mode.


Source URL : http://download.oracle.com/docs/cd/E11035_01/wls100/deployment/deploy.html#wp174377

Thanks

R Vashi



Reset Connection Pool on weblogic using Weblogic Admin Utility

Hi All,

The connection pool goes out of resource is very common issue we usually face across all types of applications. As there are plenty of reasons for the same like application is not closing the connections, concurrent user access of DB resources etc etc.

On Weblogic there is a very nice way to handle this situation in very fast manner using Admin utility. see below steps

Step 1: On Windows set WLS environment using setWLSENV.cmd(wls_home/wlserver.x.x/server/bin)

Step 2: Once environment gets ready, run the below weblogic admin utility.

java weblogic.Admin -url AdminHost:7001 -username weblogic -password weblogic RESET_POOL -poolName

After running this command, you will see a message on console stating the result of the operation.

****Note: This is just a workaround, not a solution, the action must be taken to handle this issue from application perspective, like making sure to close all the JDBC resources.

Happy learning.

Thanks
R Vashi

Redirect STDOUT logs to Server logs in weblogic.

Hi All,

Sometime we need to truncate the STDOUT Logs into parts as soon as it grows a certain limit. As STDOUT logs are controlled by JVM. But there are some tricks which we can use to achieve the same.

1. By Using Shell Script

2. By configuring one option in the Admin console of weblogic using JAVA_OPTIONS
-Dweblogic.log.RedirectStdoutToServerLogEnabled=true

Once we will start getting the STDOUT logs into server logs, we can easily rotate the server logs using Shell Script.


Thanks
R Vashi

Creating MultiDatasource on Weblogic 10

Hi All,

A JDBC multi data source is an abstraction around a group of data sources that provides load balancing and failover between data sources. As with data sources, multi data sources are also bound to the JNDI tree. Applications can look up a multi data source on the JNDI tree and then reserve a database connection from a data source. The multi data source determines from which data source to provide the connection. Below I will mention steps to create a MultiDataSource on weblogic 10.

Step 1: First of all create 2 data sources, and keep the connection max size 100 each.
DataSource 1 — Max Connections 100
DataSource 2 — Max Connections 100

Step 2: Login to the Admin Console->
Home >Summary of JDBC Multi Data Sources >Summary of JDBC Data Sources >Summary of JDBC Multi Data Sources >Summary of Services: JDBC End of repetitive links

Step 3: Click on MultiDataSource

Step 4:  Follow the below steps

Step 4.2

Also we can write one Java class to Handle any pool failover situation to send email alerts. By implementing ConnectionPoolFailoverCallback. I will post the same very soon…


Thanks
R Vashi

java.lang.OutOfMemoryError: PermGen space

Hi All,

Few days back I was reading one of the article of my all time favorite guru(Jaysen sharma), So I would like to share that in this article.

In case of OutOfMemoryError in PermGen Sapace …increasing only the Heap Size will not solve anything…

Formula:

(OS Level)Process Size = Java Heap Native Space (2-3% OS related Memory)

PermSize : It’s a Native Memory Area Outside of the Heap, Where ClassLoading kind of things happens…. In an operating System like Windows Default Process Size is 2GB (2048MB) default (It doesn’t matter How much RAM do u have 2GB or 4GB or more)…until we don’t change it by setting OS level parameter to increase the process size..Usually in OS like Solaris/Linux we get 4GB process size as well.

Now Lets take the default Process Size=2GB (Windows), Now if you have set the -Xmx512M, we can assume that rest of the memory 1536 Mb is available for Native codes.

(ProcessSize (-) HeapSize) = Native (+) (2-3% OS related Memory)

2048 MB (-) 512 MB = 1536 MB

THUMB RULES:

MaxPermSize = (Xmx/3) —- Very Special Cases (One Third of maximum Heap Size)

MaxPermSize = (Xmx/4) —- Recommended (One Fourth Of maximum Heap Size)

So finally you need to increase the PermGen Size… like -Xmx1024m -Xms1024m -XX:MaxPermSize256m

But again these are not the Final values … It depends on ther Environments

Thanks

R Vashi.

Generate PLAN.xml in weblogic for the deployed application

Hi All,

There is a very nice feature where we can generate PLAN.xml for the application.

Step 1: Place you app war file in location. e.g c:\mywar\app.war

Step2: Set the weblogic environment (setWLSEnv.cmd)

Step 3:  java weblogic.PlanGenerator -all c:\mywar\app.war

After the command you will notice the below messages in console.

Generating plan for application app.war
Export option is: all
Exporting properties…
Saving plan to C:\plan.xml…
<20-May-2010 12:08:40 o’clock BST> <Info> <J2EE Deployment SPI> <BEA-260072> <Saved configuration for application, app.war>


Thanks
R Vashi

Timezone settings in Weblogic

Hi All,

There is a very nice option where we can customize the timezone in webogic. Only thing which we need to do is to  add the TIMEZONE in JAVA_OPTION in Servers StartScript :

(on Windows)
set JAVA_OPTIONS=%JAVA_OPTIONS%    -Duser.timezone=BST

(on Unix Based OS)
JAVA_OPTIONS=${JAVA_OPTIONS}    -Duser.timezone=BST

Note: You can configure this in setWLSEnv.sh(unix) or setWLSEnv.cmd or you can define in admin console admin server startup settings.


Thanks
R Vashi