Archive | August, 2012

In log4j, output INFO logs of classes only from your package.

29 Aug

Been awhile since I’ve been using log4j for most of my projects. I wanted to output INFO statements only from my package and block log statements from all other packages i was using. Using the following log4j.properties you will see only ERROR statements from other packages and INFO statements from your package.

#Give root logger ERROR level, so that we get only ERROR output from ‘other’ packages
log4j.rootLogger=ERROR, stdout

#Only appender is stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller’s file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) – %m%n

#Give all loggers in my package INFO level, so that we see get all our messages
log4j.logger.my.com.package=INFO

 

NachOS academic projects

19 Aug

We had the option of implementing 1.) Multi programming, 2.) Virtual Memory Management or 3.) File System in Not Another Completely Heuristic Operating System, or Nachos. I remember choosing to  implement virtual memory management, it was one of my favorite academic projects till date.

Statement vs. Prepared Statement (when using oracle)?

17 Aug

When do we use Statement vs. Prepared Statement? In my opinion unless you are executing DDL statements (which don’t allow variable binding) you are better of always using  Prepared Statement.

Why? To understand this we need to know how oracle queries are executed. Without getting into too much detail the steps (that we would be most concerned about) in executing a query in oracle are:-

1. Parsing
2. Shared pool check (part of parsing step).
3. Development of execution plan. (Most Expensive Step).
4. Execution

Development of execution plan is the most expensive step and using Prepared Statement helps us avoid calling that step often.

Issue with using static queries:-
When you send a static query using Statement (select * from table where name = ‘whatever’), 1.) the query is parsed, 2.) oracle checks for the execution plan in its shared pool (just think of it as some accessible location in memory). It will contain the execution plan if the query was executed before. If yes it jumps to execution (soft parse) else it would develop an execution plan and then execute the query (hard parse). It’s ok as long as you send select * from table where name = ‘whatever’ again however as soon as you change the where clause oracle would need to create another execution plan.

Advantage using dynamic queries:-
Using Prepared statement creates a query using bind variables (select * from table where name = ‘?’). The execution steps are the same, only difference is when an execution plan is created its created using bind variables. Bind variables are substituted with values before the execution phase. So, when you send another query to the database in the form of select * from table where name = ‘?’ with another value, the 1.) query is parsed, 2). oracle checks for the execution plan in its shared pool (and finds it, making it a soft parse), replaces the bind variable with an actual value and executes the query avoiding the 3rd step altogether.

Hard Parse Vs Soft Parse? When queries avoid the development of execution plan stage, we call it a soft parse. When they have to go through the development of execution plan stage we call that a hard parse.

Here is a great link explaining this concept with related performance data. Specially read about No Parse (avoid even soft parse!) and Statement Caching (have JDBC cache your prepared statements, avoiding soft parse).

Oracle password expired

8 Aug

Oracle passwords can expire and if your application uses any of those users it could suddenly stop working. You can check status of your user from the dba_users table using the following query

select username, account_status, expiry_date, profile from dba_users;

To solve this, you could:-

1.) Run the sql query alter profile default limit password_life_time unlimited; which will change the password_life_time to unlimited for users with default profile (you can check which profile your user belongs to from the dba_users table). Your password will never expire.

OR

2.) If the above query doesn’t re-enable the user, you may need to manually reset passwords by logging into sqlplus.

After re-enabling the log-in, its a good idea to confirm the expiry_date and account_status by checking it out in the dba_users table.

Here is a link to a more detailed explaination

Function minima and maxima recap.

7 Aug

Came accross interesting problem in some GATE computer science paper.

Consider the function f(x) = sin (x) in the interval x ∈ [π/4, 7π/4]. The number and location(s) of
the local minima of this function are
(A) One, at π/2
(B) One, at 3π/2
(C) Two, at π/2 and 3π/2
(D) Two, at π/4 and 3π/2

Was quick to answer (B). Here is the plot of the graph, one of the minima is clearly 3π/2. However, in this case π/4 is a local minimum too (definitely clearer if we draw the function just within the ranges). So the answer is (D).

Note that this is only true when the interval is closed i.e. including points π/4 and 7π/4. If the problem was x ∈ (π/4, 7π/4) then π/4 is NOT a local minima as its NOT part of the function domain. Also, no matter what point we pick close to π/4 as our local minimum there will be a number lower than that. In that case this function would have just one minimum at 3π/2.

Loading properties files from classpath

6 Aug

You could load resources using ClassLoader.getResourceAsStream() or Class.getResourceAsStream(). Important thing to note is that Class.getResourceAsStream (String) delegates the call to ClassLoader.getResourceAsStream(String). You can see the same below.

public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader0();
if (cl==null) {
// A system class.
return ClassLoader.getSystemResourceAsStream(name);
}
return cl.getResourceAsStream(name);
}

resolveName(name) will add a package name prefix if the name is not absolute. Remove leading “/”  if name is absolute. What does this mean? This means that if we pass just “test.properties” to getResourceAsStream it will resolve it to “com/my/test.properties” (assuming your current package is com.my). If we pass “/test.properties” it will assume you’re passing an absolute path and remove “/” making it just “test.properties”. Remember your classpath must have “com/my/test.properties” or “test.properties” depending on what you pass to getResourceAsStream(). Now, if you are using ClassLoader.getSystemResourceAsStream() directly we know from the above code that it expects absolute paths without the “/” in the beginning.

Here is a sample folder structure and App.java the reads properties files from the classpath. Remember that the src/main/resources folder must be added (and usually is added) to the classpath.

package com.my;

import java.io.InputStream;
import java.util.Properties;

/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{

String var = null;
Properties properties = new Properties();
try {

InputStream in = App.class.getResourceAsStream(“test.properties”);
properties.load(in);
var = properties.getProperty(“my.prop”);
System.out.println(var);

in = App.class.getResourceAsStream(“/test2.properties”);
properties.load(in);
var = properties.getProperty(“my.prop”);
System.out.println(var);

} catch (Exception e) {
e.printStackTrace();
}

}
}

Issues with loading properties files using FileInputStream

4 Aug

Image

App.java

package com.my;

import java.io.FileInputStream;
import java.util.Properties;

/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{

String var = null;
Properties properties = new Properties();
try {

properties.load(new FileInputStream(“test.properties”));
var = (String) properties.get(“my.prop”);
System.out.println(var);

} catch (Exception e) {
e.printStackTrace();
}

}
}

In the above figure folder structure if we run App.java from C:\TestingApps\resourcetest i.e. the same directory which has test.properties using the following command, it will work ok.

C:\TestingApps\resourcetest>java -cp “.;target/classes” com.my.App
hello

However, if we ran App.java from a different directory it would throw an error.

C:\TestingApps\resourcetest\target\classes>java com.my.App
java.io.FileNotFoundException: test.properties (The system cannot find the file
specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at com.my.App.main(App.java:19)

So you see that even if you

1.  If you use FileInputStream to load properties.

2. Use relative paths to properties files.

3. And end up changing the running directory (like we did), then you will face issues.

Parametrize anything using maven Resource filtering.

3 Aug

Was trying to Parametrize persistence.xml in src/main/resources/META-INF .  Came accross concept of  Resource Filtering by maven Resources plugin.

1. Replace values with variables in whichever file you want.

<property name=”hibernate.connection.driver_class” value=”${my.driverClassName}” />
<property name=”hibernate.connection.url” value=”${my.url}” />
<property name=”hibernate.connection.username” value=”${my.user}” />
<property name=”hibernate.connection.password” value=”${my.password}” />
<property name=”hibernate.dialect” value=”${my.dialect}”/>

2. Create profile in pom xml

<profiles>
<profile>
<id>myprofile</id>
<properties>
<my.driverClassName>oracle.jdbc.driver.OracleDriver</my.driverClassName>
<my.url>jdbc:oracle:thin:@localhost:1521:orcl</my.url>
<my.user>myuser</my.user>
<my.password>mypass</my.password>
<my.dialect>org.hibernate.dialect.Oracle9iDialect</my.dialect>
</properties>
</profile>
</profiles>

3. Activate resource filtering

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

You need to do this, by default filtering is disabled. Even if your files are within subfolders of src/main/resources it will filter them. For example in this case  persistence.xml  is in src/main/resources/META-INF and it works ok.

4. Run maven like this:-

mvn clean install -Pmyprofile

 

http://www.sonatype.com/books/mvnref-book/reference/resource-filtering-sect-description.html

http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html