Wednesday, August 29, 2012

Book review: PIMP, by Iceberg Slim



far from admiring the guy, once can only be impressed by his sharp perception of reality, his determination to escape from prison, his extreme acumen and psychological insights.
A very enjoyable book, from cover to cover. Better still if you can listen to the AudioBook read by a black american, it renders the original accent.

Sunday, August 26, 2012

Book review: "Against the Grain" by Richard Manning




Richard Manning doesn't have the historical knowledge of a Jared Diamond, but still does a good job at giving us a broad overview of the anthropological impact of agriculture - proving us over and over that life was a lot better BEFORE agriculture, when people were living in nomadic tribes of hunter-gatherers. I am deeply convinced of that. "Civilization" sucks, and it's destroying the Earth - fast.

Saturday, August 25, 2012

WebLogic, detecting stuck threads with JMX and Java

Surprisingly, the "Health" reported in the Servers monitoring tab





is NOT the ServerRuntime.HealthState, but rather the

/serverRuntime/ThreadPoolRuntime/ThreadPoolRuntime.HealthState

the parent of this MBean is com.bea:Name=osbpl1ms1,Type=ServerRuntime, its type and name are ThreadPoolRuntime

which also contains a weblogic.health.HealthState

For this reason, to the code of the previous post I have added a new method:

    public static String getThisServerThreadPoolHealth() throws Exception {
 MBeanServerConnection connection = initConnection();
 ObjectName runtimeService = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
 String managedServerName = (String) connection.getAttribute(runtimeService, "ServerName");
 ObjectName serverRT = new ObjectName("com.bea:Name=" + managedServerName + ",Type=ServerRuntime");
 System.out.println("serverRT=" + serverRT);
 ObjectName serverTP = (ObjectName)connection.getAttribute(serverRT, "ThreadPoolRuntime");
 weblogic.health.HealthState tpHealthState = (weblogic.health.HealthState) connection.getAttribute(serverTP, "HealthState");
 return healthStateToString(tpHealthState.getState());
    }





IT as climbing: being able to find the easiest path is as important as being technically strong

Recently I was confronted with the challenge of monitoring a GridLink Datasource through Hyperic.
Neither Hyperic was able to autodiscover it, nor I was able to create a custom JMX plugin.
Finally an Oracle consultant came up with the idea of using the WebApplication (provided by Oracle) to connect directly to the DB with a "Select 1 from DUAL" and returning success or failure. Good enough for our needs. And Hyperic can very easily do a HTTP GET and parse the HTTP response.
I felt like an idiot. I tend to hammer a problem by all possible means until I break it, rather than finding workaround. I think this tendency is tied to one's personality. But it teaches me a lesson: if the wall is too hard for your head, look for a window...








Poll Result: If I could go back in time, would I choose again IT as a profession?



I suspect that most of the voters are from Asian countries, where IT still offers a lot of opportunities. My perception is that in "the West" (Europe, USA) IT has lost most of its appeal, after the immense wave of offsourcing which has taken place in the last 10 years.... almost impossible to join a large development project.

For me, IT was a VERY exciting field in the late 1990.... I have been on really large projects and one had the sensation of changing the world... most of my colleagues were really bright professionals, and they have been very successful in professional life.

Now one has really to struggle to find a challenging project, and the market is flooded with unqualified demotivated resources.

Friday, August 24, 2012

Windows Explorer: disable drag and drop

One of the zillion reasons why I hate windows is Windows Explorer, one of the biggest failures in the File Management tools galaxy. It's so pathetic that you can't even disable the drag and drop - one of the most common causes of file loss - especially when using the touchpad.

Here is a workaround:

regedit

HKEY_CURRENT_USER\Control Panel\Desktop

DragHeight=999999 (original value 4)
DragWidth=999999 (original value 4)


restart computer

It works!

Googling around I also found this post:


"You can set the drag and drop or copy and paste files
confirmation prompt

Localy:
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersio
n\Internet Settings\Zones\0]

"1802"=dword:00000001

AND on the intranet:
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersio
n\Internet Settings\Zones\1]

"1802"=dword:00000001

"

but I haven't tried....


WebLogic finding health state through JMX

This post is excellent and explains how to connect remotely (I don't like the static block thing).

This one covers better the "Local" case.

If you want to connect LOCALLY, things are explained here:

"Make Local Connections to the Runtime MBean Server.
Local clients can access a WebLogic Server instance's Runtime MBean Server through the JNDI tree instead of constructing a JMXServiceURL object"

The code is:
import javax.management.MBeanServer;
....
InitialContext ctx = new InitialContext();
MBeanServer server = (MBeanServer)ctx.lookup("java:comp/env/jmx/runtime"); 


Javadoc of the MBeanServer here:
http://docs.oracle.com/javase/6/docs/api/javax/management/MBeanServer.html


Here is the code for the "local" case (I have also removed the static initialization block):


package tests.monitoring;

import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ServerHealthStateMonitorLocal {

    private static MBeanServerConnection connection;
    private static JMXConnector connector;
    private static ObjectName service;
    private static String combea = "com.bea:Name=";
    private static String service1 = "DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean";


    public static void initConnection() throws NamingException, MalformedObjectNameException, NullPointerException {
 service = new ObjectName(combea + service1);
 InitialContext ctx = new InitialContext();
 MBeanServer server = (MBeanServer)ctx.lookup("java:comp/jmx/runtime");
  
 connection = server;
 System.out.println("connection = " + connection);
    }

    public static ObjectName[] getServerRuntimes() throws Exception {
 if (connection == null) {
     System.out.println("null connection");
 }
 
 return (ObjectName[]) connection.getAttribute(service, "ServerRuntimes");
    }

    public void printNameAndState() throws Exception {
 ObjectName arr[] = getServerRuntimes();
 for (ObjectName temp : arr)
     System.out.println("\n\t servers: " + temp);
 ObjectName domain = (ObjectName) connection.getAttribute(service, "DomainConfiguration");
 System.out.println("Domain: " + domain.toString());
 ObjectName[] servers = (ObjectName[]) connection.getAttribute(domain, "Servers");
 for (ObjectName server : servers) {
     String aName = (String) connection.getAttribute(server, "Name");
     try {
  ObjectName ser = new ObjectName("com.bea:Name=" + aName + ",Location=" + aName + ",Type=ServerRuntime");
  String serverState = (String) connection.getAttribute(ser, "State");
  System.out.println("\n\t Server: " + aName + "\t State: " + serverState);
  weblogic.health.HealthState serverHealthState = (weblogic.health.HealthState) connection.getAttribute(ser, "HealthState");
  int hState = serverHealthState.getState();
  if (hState == weblogic.health.HealthState.HEALTH_OK)
      System.out.println("\t Server: " + aName + "\t State Health: HEALTH_OK");
  if (hState == weblogic.health.HealthState.HEALTH_WARN)
      System.out.println("\t Server: " + aName + "\t State Health: HEALTH_WARN");
  if (hState == weblogic.health.HealthState.HEALTH_CRITICAL)
      System.out.println("\t Server: " + aName + "\t State Health: HEALTH_CRITICAL");
  if (hState == weblogic.health.HealthState.HEALTH_FAILED)
      System.out.println("\t Server: " + aName + "\t State Health: HEALTH_FAILED");
  if (hState == weblogic.health.HealthState.HEALTH_OVERLOADED)
      System.out.println("\t Server: " + aName + "\t State Health: HEALTH_OVERLOADED");
     } catch (javax.management.InstanceNotFoundException e) {
  System.out.println("\n\t Server: " + aName + "\t State: SHUTDOWN (or Not Reachable)");
     }
 }
    }

    public static void main(String[] args) throws Exception {
 printHealthStatus();
    }
    
    public static void printHealthStatus() throws Exception {
 ServerHealthStateMonitorLocal s = new ServerHealthStateMonitorLocal();
 initConnection();
 s.printNameAndState();
 connector.close();
    }

}





HealthState is described here, and the meaning of the integer values is

HEALTH_OK  0
HEALTH_WARN  1
HEALTH_CRITICAL  2
HEALTH_FAILED  3
HEALTH_OVERLOADED  4





The first time I get:



com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean
javax.management.InstanceNotFoundException: com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getMBean(DefaultMBeanServerInterceptor.java:1094)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getAttribute(DefaultMBeanServerInterceptor.java:662)
at com.sun.jmx.mbeanserver.JmxMBeanServer.getAttribute(JmxMBeanServer.java:638)
at weblogic.management.jmx.mbeanserver.WLSMBeanServerInterceptorBase$12.run(WLSMBeanServerInterceptorBase.java:326)
at java.security.AccessController.doPrivileged(Native Method)
at weblogic.management.jmx.mbeanserver.WLSMBeanServerInterceptorBase.getAttribute(WLSMBeanServerInterceptorBase.java:324)
at weblogic.management.mbeanservers.internal.JMXContextInterceptor.getAttribute(JMXContextInterceptor.java:157)
at weblogic.management.jmx.mbeanserver.WLSMBeanServerInterceptorBase$12.run(WLSMBeanServerInterceptorBase.java:326)
at java.security.AccessController.doPrivileged(Native Method)
at weblogic.management.jmx.mbeanserver.WLSMBeanServerInterceptorBase.getAttribute(WLSMBeanServerInterceptorBase.java:324)
at weblogic.management.mbeanservers.internal.SecurityInterceptor.getAttribute(SecurityInterceptor.java:299)
at weblogic.management.jmx.mbeanserver.WLSMBeanServer.getAttribute(WLSMBeanServer.java:279)
at tests.monitoring.ServerHealthStateMonitorLocal.getServerRuntimes(ServerHealthStateMonitorLocal.java:34)



the connection is found, but the ObjectName
"DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean" is not available in the MBeanServer

the offending code is:

return (ObjectName[]) connection.getAttribute(service, "ServerRuntimes");

I try then in the Domain configuration to set "Platform MBean Server Enabled"
I restart the servers.
Still same error.



Then I try:

MBeanServer server = (MBeanServer)ctx.lookup("java:comp/jmx/runtime");
instead of
MBeanServer server = (MBeanServer)ctx.lookup("java:comp/env/jmx/runtime");

and still the same error...

The problem is that the Domain Runtime MBean Server is registered only on the Admin.... the code works on the Admin, but NOT on a Managed Server.

The issue is that we want to be able to retrieve the Server Health even if the Admin is not available (besides, it's a pain to store the weblogic credentials for a local call...).

Ok, my dear, then how do I get a reference to the ServerRuntime, if I don't have a reference of the DomainRuntime?

Here they explain it:

you need a ObjectName "RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean"

"Provides an entry point for navigating the hierarchy of WebLogic Server runtime MBeans and active configuration MBeans for the current server."

The utilization is quite rounbdaboutish and not at all intuitive, but here is something that definitely works:

package tests.monitoring;

import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.naming.InitialContext;

public class ServerHealthStateMonitorLocal {

    public static MBeanServerConnection initConnection() throws Exception {
 MBeanServerConnection connection;
 System.out.println("initConnection");
 InitialContext ctx = new InitialContext();
 System.out.println("ctx");
 try {
     connection = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");
 }
 catch (Exception e) {
     e.printStackTrace();
     try {
  connection = (MBeanServer) ctx.lookup("java:comp/jmx/runtime");
     }
     catch (Exception e2) {
  e2.printStackTrace();
  throw e2;
     }
 }

 System.out.println("connection=" + connection);
 return connection;
    }

    private static ObjectName getServerRuntime(MBeanServerConnection connection, String aName) throws Exception {
 System.out.println("getServerRuntime");
 ObjectName serverObjectName = new ObjectName("com.bea:Name=" + aName + ",Type=ServerRuntime");
 return (ObjectName) connection.getAttribute(serverObjectName, "ServerRuntime");
    }


    public static String getHealthOfThisServer() throws Exception {
 ServerHealthStateMonitorLocal s = new ServerHealthStateMonitorLocal();
 MBeanServerConnection connection = initConnection();
 String serverName = System.getProperty("weblogic.Name");
 return s.getHealthOfServer(serverName);
    }

    private String getHealthOfServer(String aName) throws Exception {
 String result = "NOT_FOUND";
 MBeanServerConnection connection = initConnection();
 ObjectName ser = getServerRuntime(connection, aName);
 String serverState = (String) connection.getAttribute(ser, "State");
 result = serverState;
 weblogic.health.HealthState serverHealthState = (weblogic.health.HealthState) connection.getAttribute(ser, "HealthState");
 int hState = serverHealthState.getState();
 result = result + "_" + hState;
 return result;
    }
    
    public static String getThisServerName() throws Exception {
 ServerHealthStateMonitorLocal s = new ServerHealthStateMonitorLocal();
 MBeanServerConnection connection = initConnection();
 ObjectName runtimeService = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
 String managedServerName = (String) connection.getAttribute(runtimeService, "ServerName");
 return managedServerName;
 
 /*
 ObjectName msServerRuntime = new ObjectName("com.bea:Name="+ managedServerName + ",Type=ServerRuntime");
   administrationURL = (String) mBeanServer.getAttribute(msServerRuntime, "AdminServerHost");
   adminPort = (Integer) mBeanServer.getAttribute(msServerRuntime, "AdminServerListenPort");
   System.out.println(administrationURL + adminPort);
 */  
    } 
    
    public static String getThisServerState() throws Exception {
 MBeanServerConnection connection = initConnection();
 ObjectName runtimeService = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
 System.out.println("runtimeService=" + runtimeService);
 ObjectName serverRT = (ObjectName) connection.getAttribute(runtimeService, "ServerRuntime");
 System.out.println("serverRT=" + serverRT);
 String serverState = (String) connection.getAttribute(serverRT, "State");
 return serverState;
    }

    public static String getThisServerHealth() throws Exception {
 MBeanServerConnection connection = initConnection();
 ObjectName runtimeService = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
 String managedServerName = (String) connection.getAttribute(runtimeService, "ServerName");
 ObjectName serverRT = new ObjectName("com.bea:Name=" + managedServerName + ",Type=ServerRuntime");
 System.out.println("serverRT=" + serverRT);
 weblogic.health.HealthState serverHealthState = (weblogic.health.HealthState) connection.getAttribute(serverRT, "HealthState");
 return healthStateToString(serverHealthState.getState());
    }
    
    private static String healthStateToString(int state) {
 String result = "HEALTH_UNKNOWN";
 switch (state) {
 case 0:
     result = "HEALTH_OK";
     break;
 case 1:
     result = "HEALTH_WARN";
     break;
 case 2:
     result = "HEALTH_CRITICAL";
     break;
 case 3:
     result = "HEALTH_FAILED";
     break;
 case 4:
     result = "HEALTH_OVERLOADED";
     break;

 default:
     break;
 }
 return result;
    }
    
    
}




where:

runtimeService=com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean
serverRT=com.bea:Name=osbpl2ms1,Type=ServerRuntime




Eclipse: change autoformat settings

I hate almost everything in Eclipse, including the way it autoformats Java code.
I simply hate seeing code split in multiple lines. Good coders should know how to write decently short lines, and there should never be the case for line wrapping.

So, here we go:

Windows/Preferences/Java/Code Style/Formatter
create a new Active Profile based on the "Java Conventions (built in)",
edit the profile, go to Line Wrapping tab, "Maximum line width" = 1000.

Especially, stay away from the Eclipse templates, they break all possible coding conventions (who the f... wants a curly brace alone in a new line??? )

Thursday, August 23, 2012

WebLogic: using encrypted passwords

useful post here

These are the commands to encrypt the password "weblogic1" :

cd /opt/oracle/domains/osbpl1do
. ./bin/setDomainEnv.sh
java weblogic.security.Encrypt weblogic1

result is:
{AES}B5eEjwtHcq7eg3xyq7m5u3ZHcW8/QvENN8DlxrnXixo=

Same thing if you do
java weblogic.WLST
print encrypt('weblogic1')

The funny thing is that each time you get a different value.

WebLogic doesn't let you connect with an encrypted password:

THIS WILL NOT WORK:
connect('weblogic', '{AES}B5eEjwtHcq7eg3xyq7m5u3ZHcW8/QvENN8DlxrnXixo=', 't3://localhost:7001')




For JDBC passwords, WebLogic will store them in the $DOMAIN_HOME/config/jdbc/DATASOURCENAME-nnnn-jdbc.xml file in encrypted format.

<?xml version='1.0' encoding='UTF-8'?>
<jdbc-data-source xmlns="http://xmlns.oracle.com/weblogic/jdbc-data-source" xmlns:sec="http://xmlns.oracle.com/weblogic/security" xmlns:wls="http://xmlns.oracle.com/weblogic/security/wls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/jdbc-data-source http://xmlns.oracle.com/weblogic/jdbc-data-source/1.0/jdbc-data-source.xsd">
  <name>SOADataSource</name>
  <jdbc-driver-params>
    <url>jdbc:oracle:thin:@acme.com:1551:dosb01</url>
    <driver-name>oracle.jdbc.OracleDriver</driver-name>
    <properties>
      <property>
        <name>user</name>
        <value>pl1_soainfra</value>
      </property>
    </properties>
    <password-encrypted>{AES}hJ3eMa5bAzP8Oq1LbGMN+ZsUAWDCErZYuiBTfi2S2vg=</password-encrypted>
  </jdbc-driver-params>
  <jdbc-connection-pool-params>
    <test-table-name>SQL SELECT 1  FROM DUAL</test-table-name>
  </jdbc-connection-pool-params>
  <jdbc-data-source-params>
    <jndi-name>jdbc/SOALocalTxDataSource</jndi-name>
  </jdbc-data-source-params>
</jdbc-data-source>



This post shows how to create a DataSource with encrypted password. You can user either

drBean = jdbcResource.getJDBCDriverParams()
drBean.setPassword("{3DES}IQHx+vYPxQI5k1W1Dbwubw==")

or

drBean = jdbcResource.getJDBCDriverParams()
drBean.setPassword("cleartextpw")

and it works the same way.

If you encrypt the password on one domain and use it for a DataSource in another domain you will get this error:


weblogic.application.WrappedDeploymentException: Could not perform unpadding: invalid pad byte.
at com.rsa.jsafe.c.a(Unknown Source)
at com.rsa.jsafe.JSAFE_SymmetricCipher.decryptFinal(Unknown Source)
at weblogic.security.internal.encryption.JSafeEncryptionServiceImpl.decryptBytes(JSafeEncryptionServiceImpl.java:124)
at weblogic.security.internal.encryption.JSafeEncryptionServiceImpl.decryptString(JSafeEncryptionServiceImpl.java:184)
at weblogic.security.internal.encryption.ClearOrEncryptedService.decrypt(ClearOrEncryptedService.java:96)
at sun.reflect.GeneratedMethodAccessor95.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at weblogic.descriptor.DescriptorManager$SecurityServiceImpl$SecurityProxy._invokeServiceMethod(DescriptorManager.java:173)
at weblogic.descriptor.DescriptorManager$SecurityServiceImpl$SecurityProxy.decrypt(DescriptorManager.java:192)
at weblogic.descriptor.DescriptorManager$SecurityServiceImpl.decrypt(DescriptorManager.java:114)
at weblogic.descriptor.internal.AbstractDescriptorBean._decrypt(AbstractDescriptorBean.java:1092)
at weblogic.j2ee.descriptor.wl.JDBCDriverParamsBeanImpl.getPassword(JDBCDriverParamsBeanImpl.java:337)
at weblogic.jdbc.common.internal.DataSourceConnectionPoolConfig.getDriverProperties(DataSourceConnectionPoolConfig.java:355)
at weblogic.jdbc.common.internal.DataSourceConnectionPoolConfig$2.run(DataSourceConnectionPoolConfig.java:291)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.jdbc.common.internal.DataSourceConnectionPoolConfig.initJDBCParameters(DataSourceConnectionPoolConfig.java:287)
at weblogic.jdbc.common.internal.DataSourceConnectionPoolConfig.access$000(DataSourceConnectionPoolConfig.java:24)
at weblogic.jdbc.common.internal.DataSourceConnectionPoolConfig$1.run(DataSourceConnectionPoolConfig.java:78)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.jdbc.common.internal.DataSourceConnectionPoolConfig.getPoolProperties(DataSourceConnectionPoolConfig.java:75)
at weblogic.jdbc.common.internal.ConnectionPool.doStart(ConnectionPool.java:1154)
at weblogic.jdbc.common.internal.ConnectionPool.start(ConnectionPool.java:154)
at weblogic.jdbc.common.internal.ConnectionPoolManager.createAndStartPool(ConnectionPoolManager.java:454)
at weblogic.jdbc.common.internal.ConnectionPoolManager.createAndStartPool(ConnectionPoolManager.java:372)
at weblogic.jdbc.module.JDBCModule.prepare(JDBCModule.java:255)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:199)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:517)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:159)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:45)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:613)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:184)
at weblogic.application.internal.SingleModuleDeployment.prepare(SingleModuleDeployment.java:43)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:154)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.createAndPrepareContainer(ActivateOperation.java:207)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:98)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:217)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:747)
at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1216)
at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:218)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:159)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:171)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.prepare(DeploymentReceiverCallbackDeliverer.java:41)
at weblogic.deploy.service.internal.statemachines.targetserver.AwaitingContextUpdateCompletion.callDeploymentReceivers(AwaitingContextUpdateCompletion.java:164)
at weblogic.deploy.service.internal.statemachines.targetserver.AwaitingContextUpdateCompletion.handleContextUpdateSuccess(AwaitingContextUpdateCompletion.java:66)
at weblogic.deploy.service.internal.statemachines.targetserver.AwaitingContextUpdateCompletion.contextUpdated(AwaitingContextUpdateCompletion.java:32)
at weblogic.deploy.service.internal.targetserver.TargetDeploymentService.notifyContextUpdated(TargetDeploymentService.java:225)
at weblogic.deploy.service.internal.DeploymentService$1.run(DeploymentService.java:189)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:528)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:178)







Wednesday, August 22, 2012

WLST and getopt - parsing command line arguments

This is far from ideal but it works:

import getopt
env = None
password = None
list = None

opts, args = getopt.getopt(sys.argv[1:], "e:p:l:")
for opt, arg in opts:
    print opt, arg
    if opt in "-e":
        env = arg
    if opt in "-p":
        password = arg
    if opt in "-l":
        list = arg


print "env", env
print "password", password
print "list", list


java weblogic.WLST testgetopts.py -e pippo -l cino,cano

the output is:


-e pippo
-l cino,cano
env pippo
password None
list cino,cano


Later, you can check if an argument has been passed by

if password is None:
    print "missing argument password"        



Oracle Virtual Assembly Builder

http://www.oracle.com/technetwork/middleware/ovab/downloads/index.html


An interview:



which explains quite a lot.

An interesting (no sound) presentation on P2V (physical to virtual) here:



"This illustrates the process of performing a physical to virtual introspection of an Oracle WebLogic Server instance resulting in the creation of a new appliance which is subsequently used in the creation of a new three tier assembly."

How fascinating!

more in general ExalogicTV is a great source of information!

Tuesday, August 21, 2012

Itinerary to visit Rome

I am often asked by colleagues to provide a list of sight to see in Rome.
I had the luck of living in Rome for 1 year, so here is a list of my strongest memories.

Saint Peter Cathedral (Metro Vaticano) : it's compulsory to WALK all the way up the Dome, there is an affordable fee if you don't use the elevator. The second stage of stairs leading to the top is breathtaking. You will be able to enjoy a wonderful view of Rome from the top.
Also, inside the Cathedral don't miss La Pieta', probably the most dramatic and touching sculptures in history.

From Vaticano (map here), walk to Colosseo (maýbe 5 Km), passing through:
Castel Sant'Angelo
Ponte Sant'Angelo and its wonderful statues

via dei Coronari until Piazza Navona, then to the Pantheon - one of the most perfect and daring buildings in the entire history.
Walk then to Trevi Fountain, where you can relax at the sound of water.
Next comes Piazza di Spagna with its funny Fountain of Barcaccia

Go also to Appia Antica and the Cecilia Metella tomb.
The best museums are: Etruscan Museum, Musei Capitolini, Museo del Palazzo dei Conservatori, Mercati di Traiano, Centrale Montemartini....and of course Musei Vaticani.

Outside Rome, don't miss Ostia Antica, Villa Adriana and if you can the Etruscan Necropolis of Cerveteri. ... more to come...

Then of course Foro Romano, Terme di Caracalla...

WebLogic shutdown when work completes

If you go to Control-Shutdown-when work completes

status is SUSPENDING for 15 minutes...

so I do "force shutdown now" and shortly after WLS dies and status becomes FORCE_SHUTTING_DOWN.

With WLST you can do shutdown :

shutdown('${SERVER_NAME}','Server', ignoreSessions='true', timeOut=120, force='true')


Official doc:

http://docs.oracle.com/cd/E21764_01/web.1111/e13708/server_life.htm#START217



Why WLS doesn't exit the SUSPENDING status? My theory is that there are active threads for the FileAdapter and DbAdapter poller.
So how to do a graceful shutdown?
I would propose a WLST SUSPEND followed by a FORCE SHUTDOWN.






OSB Group to create session

I was struggling to find out which Group I can assign to a Principal to allow him to create a OSB sesson. It turned out that only the Administrators group allows us to create OSB Session - which is quite a pity.

. /opt/oracle/domains/osbpl2do/bin/setDomainEnv.sh
java weblogic.WLST
#Pierluigi is member of the group "Administrators"
connect('Pierluigi', 'weblogic1', 't3://acme.com:7101')
domainRuntime()
SessionMBean = findService("SessionManagement", "com.bea.wli.sb.management.configuration.SessionManagementMBean")
print SessionMBean
 [MBeanServerInvocationHandler]com.bea:Name=SessionManagement,Type=com.bea.wli.sb.management.configuration.SessionManagementMBean

sessionName='pippo'
SessionMBean.createSession(sessionName)

SessionMBean.discardSession(sessionName)

#Praveen is member of no group
disconnect()

connect('Praveen', 'weblogic1', 't3://acme.com:7101')
domainRuntime()
SessionMBean = findService("SessionManagement", "com.bea.wli.sb.management.configuration.SessionManagementMBean")
print SessionMBean
 [MBeanServerInvocationHandler]com.bea:Name=SessionManagement,Type=com.bea.wli.sb.management.configuration.SessionManagementMBean

sessionName='pippo3'
SessionMBean.createSession(sessionName)


 Traceback (innermost last):
  File "", line 1, in ?
        at weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:234)
        at weblogic.rmi.internal.BasicRemoteRef.invoke(BasicRemoteRef.java:223)
        at javax.management.remote.rmi.RMIConnectionImpl_1035_WLStub.invoke(Unknown Source)
        at weblogic.management.remote.common.RMIConnectionWrapper$16.run(ClientProviderBase.java:919)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
        at weblogic.security.Security.runAs(Security.java:61)
        at weblogic.management.remote.common.RMIConnectionWrapper.invoke(ClientProviderBase.java:917)
        at javax.management.remote.rmi.RMIConnector$RemoteMBeanServerConnection.invoke(RMIConnector.java:993)
        at weblogic.management.jmx.MBeanServerInvocationHandler.doInvoke(MBeanServerInvocationHandler.java:544)
        at weblogic.management.jmx.MBeanServerInvocationHandler.invoke(MBeanServerInvocationHandler.java:380)
        at $Proxy15.createSession(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)

  
weblogic.management.NoAccessRuntimeException: weblogic.management.NoAccessRuntimeException: Access not allowed for subject: principals=[Praveen], on ResourceType: com.bea.wli.sb.management.configuration.SessionManagementMBean Action: execute, Target: createSession




Sunday, August 19, 2012

JSP to list all OSB Projects deployed on a WebLogic server

http://stackoverflow.com/questions/7607918/weblogic-alsbconfigurationmbean-initialization


ALSBConfigurationMBean



Make sure you also have

Oracle_OSB1\lib\sb-kernel-api.jar
Oracle_OSB1\modules\com.bea.common.configfwk_1.5.0.0.jar

in your classpath.


package com.pierre.osb.doc;

import java.util.Hashtable;
import java.util.Set;

import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;

import weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean;

import com.bea.wli.config.Ref;
import com.bea.wli.sb.management.configuration.ALSBConfigurationMBean;
import com.bea.wli.sb.management.configuration.SessionManagementMBean;

public class ListProjects {
 
 String hostname = "acme.com";
 int port = 7001;
 String username = "Pierluigi";
 String password = "weblogic1";

 public static void main(String[] args) throws Exception {
  ListProjects listProjects = new ListProjects();
  listProjects.display();
 }

 public void display() throws Exception {

  JMXServiceURL serviceURL = new JMXServiceURL("t3", hostname, port, "/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME);

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

  h.put(Context.SECURITY_PRINCIPAL, username);
  h.put(Context.SECURITY_CREDENTIALS, password);
  h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");

  JMXConnector conn = JMXConnectorFactory.connect(serviceURL, h);
  System.out.println("connected");   

  try {
   System.out.println("Opened JMX connection to " + hostname + ":" + port + " as " + username);

   // get mbean connection
   MBeanServerConnection mbconn = conn.getMBeanServerConnection();

   // Get SessionmanagementMBean
   SessionManagementMBean sm = 
    JMX.newMBeanProxy(mbconn, ObjectName.getInstance(SessionManagementMBean.OBJECT_NAME), SessionManagementMBean.class);

   // Create a session
   String sessionName = "MySession";           
   sm.createSession(sessionName);

   // Get the configuration MBean for the session, do stuff, and then discard the session.
   try
   {
    System.out.println("Session exists? : " + sm.sessionExists(sessionName));

    ALSBConfigurationMBean configMBean = 
     JMX.newMBeanProxy(
       mbconn, 
       ObjectName.getInstance("com.bea:Name=" + ALSBConfigurationMBean.NAME + "." + sessionName + ",Type=" + ALSBConfigurationMBean.TYPE), 
       ALSBConfigurationMBean.class
     );

    System.out.println("Got the config MBean for session: " + configMBean.getSession());

    Set<Ref> refs = configMBean.getRefs(Ref.DOMAIN);
    System.out.println("found " + refs.size() + " refs<br>");
    for (Ref ref : refs) {
     System.out.println(ref.getFullName() + " isProjectRef= " + ref.isProjectRef() + "<br>");
    }
   }
   finally
   {
    // use activateSession to commit session changes instead
    sm.discardSession(sessionName);
   }
  } finally {
   conn.close();
   System.out.println("Closed JMX connection");
  }      
 }
}



Actually it seems to work with these JARs:


CL3Export.jar
CL3Nonexport.jar
com.bea.common.configfwk_1.5.0.0.jar
com.bea.core.common.security.api_1.0.0.0_6-1-0-0.jar
com.bea.core.descriptor_1.9.0.0.jar
com.bea.core.descriptor.wl_1.3.3.0.jar
com.bea.core.logging_1.8.0.0.jar
com.bea.core.management.core_2.8.0.0.jar
com.bea.core.management.jmx_1.4.1.0.jar
com.bea.core.messaging.kernel_1.8.0.0.jar
com.bea.core.store_1.7.0.0.jar
com.bea.core.timers_1.7.0.0.jar
com.bea.core.transaction_2.7.0.0.jar
com.bea.core.utils.classloaders_1.8.0.0.jar
com.bea.core.utils.expressions_1.4.0.0.jar
com.bea.core.utils.full_1.9.0.0.jar
com.bea.core.utils.wrapper_1.4.0.0.jar
com.bea.core.weblogic.lifecycle_1.4.0.0.jar
com.bea.core.weblogic.rmi.client_1.8.0.0.jar
com.bea.core.weblogic.rmi.client.ja_1.8.0.0.jar
com.bea.core.weblogic.security_1.0.0.0_6-1-0-0.jar
com.bea.core.weblogic.security.digest_1.0.0.0.jar
com.bea.core.weblogic.security.identity_1.1.2.1.jar
com.bea.core.weblogic.security.wls_1.0.0.0_6-1-0-0.jar
com.bea.core.weblogic.socket.api_1.2.0.0.jar
com.bea.core.weblogic.workmanager_1.9.0.0.jar
com.bea.core.weblogic.workmanager.ja_1.9.0.0.jar
connector.jar
dhbcore.jar
fscontext.jar
javax.jms_1.1.1.jar
JAXBClassesGeneration.jar
jms.jar
jndi.jar
jstl.jar
jta.jar
ldap.jar
org.eclipse.persistence_1.0.0.0_2-1.jar
sb-kernel-api.jar
standard.jar
weblogic.jar
wlclient.jar



Saturday, August 18, 2012

Installing JIRA on Linux

Download here http://www.atlassian.com/software/jira/download the 30 days evaluation version

chosen the 64 bit for Linux

Here the installation manual for Linux

Once I download and copy it, I do
chmod a+x atlassian-jira-X.Y.bin


Since it's not recommended to use HSQLDB internal DB, I configure it to use Oracle DB - this option will appear during the first access to the console. The Schema provided must be empty, otherwise JIRA will refuse to proceed.

https://confluence.atlassian.com/display/JIRA/Connecting+JIRA+to+Oracle#ConnectingJIRAtoOracle-manually



On the whole, it's a very easy and straightforward setup. You don't need root access.


Parsing XML in Java, how frustrating...

<%@page import="java.net.*" %>
<%@page import="java.io.*" %>
<%@page import="javax.xml.xpath.*" %>
<%@page import="org.xml.sax.*" %>
<%@page import="javax.xml.parsers.*" %>
<%@page import="org.w3c.dom.*" %>

  

<% 
   String urlToRead = "http://acme.com:8101/sbresource?SCHEMA/httptest/version";
      URL url;
      HttpURLConnection conn;
      BufferedReader rd;
      String line;
      String xml = "";
      String version = "N/A";
      try {
         url = new URL(urlToRead);
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         while ((line = rd.readLine()) != null) {
          xml += line;
         }
         rd.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
      XPathFactory factory = XPathFactory.newInstance();
      XPath xpath = factory.newXPath();
      //String expression = "//xs:element[@name='version']/@id";
      String expression = "//*";
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      InputSource is = new InputSource(new StringReader(xml));
      Document document = builder.parse(is);
      out.write("parsed");
      Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
      out.write("evaluated");
      out.write(widgetNode.getTextContent());
      out.write("widgetNode is null? " + (widgetNode == null));
%>



I promise you, this is hell when you compare to XML Parsing in Groovy or Python...



Friday, August 17, 2012

Book. Scala for the impatient

Here the solution of the exercises for the first 2 chapters:

https://github.com/koevet/ScalaForTheImpatient-Solutions


I hear very good things about this book... will start reading it in the weekend, just to boast about "being knowledgeable in Scala" in interviews...

http://my.safaribooksonline.com/book/programming/scala/9780132761772

http://horstmann.com/scala/



Thursday, August 16, 2012

Oracle Data Modeler. Entity Relationship diagram from Oracle

Download here

It could hardly be easier.... import a DDL file, and it will generate the ER diagram for you...

Wednesday, August 15, 2012

PL-SQL logging info with DBMS_OUTPUT.PUT_LINE in SQL Developer

unless you explicitly enable the logging, you will never see anything...

SET SERVEROUTPUT ON;

BEGIN

  DBMS_OUTPUT.ENABLE;
 DBMS_OUTPUT.PUT_LINE('Hello...');

 DBMS_OUTPUT.PUT_LINE('Goodbye.');
 END;
 /



in a stored procedure, just do

dbms_output.enable (1000000);



PL-SQL difference of dates in seconds

this expression, as a difference of 2 dates:

TO_DATE('2012-08-13 11.20.00', 'YYYY-MM-DD HH24:MI:SS') - max(CREATIONTIME)

is a "INTERVAL DAY TO SECOND", not a "number".


This function provided by asktom

create or replace function datediff( p_what in varchar2, 
                                        p_d1   in date, 
                                        p_d2   in date ) return number 
   as 
       l_result    number; 
   begin 
       select (p_d2-p_d1) * 
              decode( upper(p_what), 
                      'SS', 24*60*60, 'MI', 24*60, 'HH', 24, NULL ) 
        into l_result from dual; 
  
       return l_result; 
   end; 
 


is very useful, you can do this:


select trunc(datediff('ss', TO_DATE('2012-08-13 11.20.00', 'YYYY-MM-DD HH24:MI:SS'), max(A.CREATIONTIME) ))

and you get the result as a numeric value!






PL-SQL function, the basics

There are Procedures and Functions.

A Function is declared like this:

CREATE OR REPLACE FUNCTION SHOULDALERT 
(
  p_technicalmessageid IN VARCHAR2  
) RETURN NUMBER IS 
v_count integer;
BEGIN
  select count(*) into v_count from nesoa2_alert_instances where technicalmessageid = p_technicalmessageid 
   and status in ('CREATED', 'PROCESSED') ;
  return v_count;
END SHOULDALERT;



and can be invoked as

select SHOULDALERT('BLABLA^PuO20111212_164122_1640.txt^AVE^1344962989697') from dual;



Sunday, August 12, 2012

WLST: difference between SystemResources and JMSSystemResources

I have created a JMS Module "GM_CommonOsbJMSModule", and if I do

cd GM_CommonOsbJMSModule

I can see it contains pretty much all the possible resources I can create in a Module:

ls /SystemResources/GM_CommonOsbJMSModule/JMSResource/GM_CommonOsbJMSModule

dr-- ConnectionFactories
dr-- DestinationKeys
dr-- DistributedQueues
dr-- DistributedTopics
dr-- ForeignServers
dr-- Queues
dr-- Quotas
dr-- SAFErrorHandlings
dr-- SAFImportedDestinations
dr-- SAFRemoteContexts
dr-- Templates
dr-- Topics
dr-- UniformDistributedQueues
dr-- UniformDistributedTopics


also if I do

cd /SystemResources/GM_CommonOsbJMSModule/Resource/GM_CommonOsbJMSModule

I get the same tree

The funny thing is that if I do:
cd /JMSSystemResources/GM_CommonOsbJMSModule/JMSResource/GM_CommonOsbJMSModule

I get very much the same picture... confusing... I don't quite like this...maybe I am simply stupid...

WLST set Targets : Array has at least one null element

Very often I struggle with the setTarget method:

this statement:
set('Targets', jarray.array(jmsServerArray, ObjectName))

often results in:

java.lang.IllegalArgumentException: Array has at least one null element
at weblogic.descriptor.internal.AbstractDescriptorBeanHelper._cleanAndValidateArray(AbstractDescriptorBeanHelper.java:730)
at weblogic.management.configuration.TargetInfoMBeanImpl.setTargets(TargetInfoMBeanImpl.java:240)


Now, the problem more often than not is NOT that some elements in jmsServerArray are null.... the problem lies in that they are the ObjectName of something that DOES NOT EXIST in the Domain/Server config.
So rather than trying to find out if an element is NULL, find out if it's a VALID RESOURCE.

Frustrating.... indeed...

Friday, August 10, 2012

WLST: No stack trace available

I am not a WLST pro, and I am still learning on the field...

something really frustrating is that I normally do:

try:
bla...
except:
dumpStack()


thinking that dumpStack would be the equivalent of e.printStackTrace() in Java...
but most of the time I get the message "No stack trace available".
How irritating...

So the only solution I have found is to use

except Exception, inst:
    print('unable to create     JMSModule ' + jmsModule)
    print inst
    print sys.exc_info()[0]


Thursday, August 9, 2012

SOAPUI: groovy script to choose a different line in a file for each test iteration

We have a Property test step containing 2 properties:
Hostname and linecount
We initialize linecount to 0

At each iteration, this Groovy test step will assign to Hostname the next value from a file C:/pierre/workspace/SSS_AutomatedTests/SOAPUIArtifacts/hostnames.txt
Arrived at the end of the file, it will restart from the first line.

linecount= testRunner.testCase.testSteps["Properties"].getPropertyValue( "linecount" )
linecountInt = linecount.toInteger() + 1
//increment property linecount by one
testRunner.testCase.testSteps["Properties"].setPropertyValue( "linecount", String.valueOf(linecountInt) )

def myhostnamesFile = new File("C:/pierre/workspace/SSS_AutomatedTests/SOAPUIArtifacts/hostnames.txt")

//find number of lines in hostnames file
hostnamesinthefile = 0;
myhostnamesFile.eachLine { hostnamesinthefile++ }
log.info( "hostnames in the file: " + hostnamesinthefile)

//divide modulo
theLineNumber = (linecountInt % hostnamesinthefile) + 1
log.info("theLineNumber to choose=" + theLineNumber)
theHostnameToChoose = ""
//scan all lines, line contains the text and lineNo the line number starting from 1
myhostnamesFile.eachLine() { line, lineNo ->
 if ( lineNo == theLineNumber) 
  theHostnameToChoose = line
}

log.info( "theHostnameToChoose=" + theHostnameToChoose)

testRunner.testCase.testSteps["Properties"].setPropertyValue( "Hostname", theHostnameToChoose )



Wednesday, August 8, 2012

SOAPUI Properties and Groovy Steps

Losing my mind for how a simple thing was turned into a complicated riddle.

See http://www.soapui.org/Functional-Testing/working-with-properties.html

If you do this:

testRunner.testCase.testSuite.setPropertyValue("Hostname", "02B3TEST0004")
log.info( testRunner.testCase.testSuite.getPropertyValue("Hostname"))

you will set a TestSuite level property:



After a lot of trial and error, I found out that if you want to get/set properties defined in a Properties Test Step, you must do this:

testRunner.testCase.testSteps["Properties"].setPropertyValue( "Hostname", "fanculo" )

log.info( testRunner.testCase.testSteps["Properties"].getPropertyValue( "Hostname" ))






very properly undocumented, thank you SmartBear... if this Bear is smart, I wonder the dummy ones...

So now we are ready to implement the DataSources in Groovy by reading a file and setting a property in a GroovyStep

Tuesday, August 7, 2012

I am proud for NOT having watched a single minute of Olympic Games



just as I am proud of NOT owning a car, of NOT having a TV set, of NOT drinking Coca Cola...trying by all possible means not to fuel this criminal system which has already destroyed half of the planet and will soon destroy the other half - including where you are living now. No safe heaven for the collapse of the world ecosystems.

More Bansky Olympic works here

Monday, August 6, 2012

Cool way to synchronize you local folder with a remote folder

I hate developing code directly on the target machine - I would much rather edit them locally in Eclipse, scp them and checking them into SVN when they are stable.
So this utility provided by WinSCP is quite handy at copying remotely the files for me whenever I save them to the local folder:

WinSCP.exe soa@remotehost.com /keepuptodate C:\pierre\
workspace\myscripts /home/soa/targetdir/scripts

keepuptodate is the magic option

Sunday, August 5, 2012

Useful WLST

not very elegant.... just a copy/paste of what is generated by the Record utility in WLS console...

#Variable declaration

username='weblogic'
password='weblogic1'
serverurl='t3://myhost:7101'

clustername='osbdv2cl'

#Connect with WLST to Admin

cd /opt/oracle/domains/osbdv2do
. ./bin/setDomainEnv.sh
java weblogic.WLST
connect(username, password, serverurl)

#create DataSource (non-RAC, no XA, no LLR)

datasource='JMSPerfTestDataSource'
datasource_jndi='jdbc.JMSPerfTestDataSource'
datasource_url='jdbc:oracle:thin:@dbhost.com:1551:dosb01'
datasource_driver='oracle.jdbc.OracleDriver'
datasource_username='dv1_soainfra'
datasource_password='dv1_pippo'

edit()
startEdit()

cmo.createJDBCSystemResource(datasource)
cd('/JDBCSystemResources/' + datasource + '/JDBCResource/' + datasource)
cmo.setName(datasource)
cd('/JDBCSystemResources/' + datasource + '/JDBCResource/' + datasource + '/JDBCDataSourceParams/' + datasource)
set('JNDINames',jarray.array([String(datasource_jndi)], String))
cd('/JDBCSystemResources/' + datasource + '/JDBCResource/' + datasource + '/JDBCDriverParams/' + datasource)
cmo.setUrl(datasource_url)
cmo.setDriverName(datasource_driver)
cmo.setPassword(datasource_password)

cd('/JDBCSystemResources/' + datasource + '/JDBCResource/' + datasource + '/JDBCConnectionPoolParams/' + datasource)
cmo.setTestTableName('SQL SELECT 1 FROM DUAL')
cd('/JDBCSystemResources/' + datasource + '/JDBCResource/' + datasource + '/JDBCDriverParams/' + datasource + '/Properties/' + datasource + '')

cmo.createProperty('user')
cd('/JDBCSystemResources/' + datasource + '/JDBCResource/' + datasource + '/JDBCDriverParams/' + datasource + '/Properties/' + datasource + '/Properties/user')
cmo.setValue(datasource_username)
cd('/JDBCSystemResources/' + datasource + '/JDBCResource/' + datasource + '/JDBCDataSourceParams/' + datasource)
cmo.setGlobalTransactionsProtocol('None')
cd('/SystemResources/' + datasource)
set('Targets',jarray.array([ObjectName('com.bea:Name=' + clustername + ',Type=Cluster')], ObjectName))

save()
activate()

#create File Store

filestore_name='LocalJMSPerfTestFileStore'
filestore_target='osbdv2ms1 (migratable)'
filestore_directory='/opt/oracle/domains/osbdv2do/servers/osbdv2ms1/data/store'

edit()
startEdit()

cd('/')
cmo.createFileStore(filestore_name)
cd('/FileStores/' + filestore_name)
cmo.setDirectory(filestore_directory)
set('Targets',jarray.array([ObjectName('com.bea:Name=' + filestore_target + ',Type=MigratableTarget')], ObjectName))

save()
activate()

#create JDBC Store

jdbcstore_name='JDBCStoreJMSPerfTest'
jdbcstore_datasource='JMSPerfTestDataSource'
jdbcstore_prefix='JMSPerfTest'
jdbcstore_target='osbdv2ms1 (migratable)'

edit()
startEdit()

cd('/')
cmo.createJDBCStore(jdbcstore_name)
cd('/JDBCStores/'+ jdbcstore_name)
cmo.setDataSource(getMBean('/SystemResources/' + jdbcstore_datasource))
cmo.setPrefixName(jdbcstore_prefix)
set('Targets',jarray.array([ObjectName('com.bea:Name=' + jdbcstore_target + ',Type=MigratableTarget')], ObjectName))

save()
activate()

#create JMS Server

cmo.createJMSServer('JMSServerPerfTest')
cd('/Deployments/JMSServerPerfTest')
cmo.setPersistentStore(getMBean('/FileStores/LocalPerfTestFileStore'))
set('Targets',jarray.array([ObjectName('com.bea:Name=osbdv2ms1,Type=Server')], ObjectName))

#create JMS Module

cd('/')
cmo.createJMSSystemResource('JMSPerfTestModule')
cd('/SystemResources/JMSPerfTestModule')
set('Targets',jarray.array([ObjectName('com.bea:Name=osbdv2cl,Type=Cluster')], ObjectName))
#create JMS SubDeployment

cmo.createSubDeployment('JMSPerfTestSD')
cd('/SystemResources/JMSPerfTestModule/SubDeployments/JMSPerfTestSD')

set('Targets',jarray.array([ObjectName('com.bea:Name=PippoCommonJmsServer1,Type=JMSServer')], ObjectName))

#create JMS Distributed Queue

cd('/JMSSystemResources/JMSPerfTestModule/JMSResource/JMSPerfTestModule')
cmo.createUniformDistributedQueue('JMSPerfDQueue')
cd('/JMSSystemResources/JMSPerfTestModule/JMSResource/JMSPerfTestModule/UniformDistributedQueues/JMSPerfDQueue')
cmo.setJNDIName('jms.JMSPerfDQueue')
cmo.setDefaultTargetingEnabled(true)
cmo.unSet('Template')
cmo.setLoadBalancingPolicy('Round-Robin')
cmo.setResetDeliveryCountOnForward(true)
cmo.setIncompleteWorkExpirationTime(-1)
cmo.setForwardDelay(-1)
cmo.setAttachSender('supports')
cmo.setSAFExportPolicy('All')
cmo.setProductionPausedAtStartup(false)
cmo.setDefaultUnitOfOrder(false)
cmo.setDefaultTargetingEnabled(false)
cmo.setUnitOfOrderRouting('Hash')
cmo.setUnitOfWorkHandlingPolicy('PassThrough')
cmo.setInsertionPausedAtStartup(false)
cmo.setMessagingPerformancePreference(25)
cmo.setConsumptionPausedAtStartup(false)

#assign SubDeployment

cmo.setSubDeploymentName('JMSPerfTestSD')

save()
activate()

WLST check for existence of a JMSModule

Often you must CONDITIONALLY do an operation based on the existence/non existence of a resource:

def deleteJMSModule(jmsModule):
    myBean = getMBean('/SystemResources/' + jmsModule)
    if myBean is not None:  
        edit()
        startEdit()
        try:
            cmo.destroyJMSSystemResource(getMBean('/SystemResources/' + jmsModule))
            print "deleted JMSModule " + jmsModule
            validate()    
            save()
            activate()
        except:
            print('unable to delete preexisting JMSModule ' + jmsModule)
            dumpStack()
            undo('true', 'y')
            cancelEdit('y')
    else:
        print 'JMSModule ' + jmsModule + ' does not exist, I will not delete it'



make sure you check for the existence of the MBean BEFORE you do the edit()... otherwise you will get an exception

Book review: Confessions of an Economic Hit Man

http://en.wikipedia.org/wiki/Confessions_of_an_Economic_Hit_Man



The book makes an interesting reading, but don't expect any shocking revelations.
It's a well known fact that secret services kill world leaders who are not "obedient", or they stage coup d'etat to get rid of them.
We know that Saudi Arabia was turned into a disgusting consumerist mall by US contracting companies, that Ecuador was destroyed by oil companies, that Iran and Iraq have been used and abused, we know how Hugo Chavez has been under attack for so long...that most Latin American leaders who had a vision died in air crashed or by the hands of CIA-staged golpe (Allende).

The book covers all these topics, adding some personal encounters of world leaders or destitute people in the 4 corners of the world.

What is really funny is that the author tries to preach and pass us a message, while he has been working for the worst goals for really huge amount of money for his entire life. I would rather choose myself a more coherent guru, thanks.

I have read also the other book of the same author, The Secret History Of the American Empire, again very well written but rather shallow in his analysis.

Thursday, August 2, 2012

Oracle DB: find table holding foreign key constraint on another table

sometimes you want to truncate table BLA, and you get an erro message such as
"unable to delete because of some foreign key constraint".... and you don't have a clue which table is pointing to BLA...

here is how to find out:

select owner,constraint_name,constraint_type,table_name,r_owner,r_constraint_name
  from all_constraints 
 where constraint_type='R'
   and r_constraint_name in (select constraint_name 
                               from all_constraints 
                              where constraint_type in ('P','U') 
                                and table_name='BLA');


Make sure you use the right CAPS.
(thanks to stackoverflow)

This is useful if you get a "ORA-02266: unique/primary keys in table referenced by enabled foreign keys".

soapui: browser component is disabled

http://www.eviware.com/forum/viewtopic.php?f=2&t=7797&hilit=disabled+browser


apparently if you want to use the SOAPUI embedded browser you must use the 32 bit JDK.

Just install a Java 7 32 bit, then put this in your soapui.bat:


@echo off

set SOAPUI_HOME=C:\pierre\SmartBear\soapUI-4.5.0\bin\

set JAVA=c:\pierre\jre32\bin\java

rem init classpath

set CLASSPATH=%SOAPUI_HOME%soapui-4.5.0.jar;%SOAPUI_HOME%..\lib\*;

rem JVM parameters, modify as appropriate
set JAVA_OPTS=-Xms128m -Xmx1024m -Dsoapui.properties=soapui.properties -Dsoapui.home=%SOAPUI_HOME%

if "%SOAPUI_HOME%" == "" goto START
    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.ext.libraries="%SOAPUI_HOME%ext"
    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.ext.listeners="%SOAPUI_HOME%listeners"
    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.ext.actions="%SOAPUI_HOME%actions"
                set JAVA_OPTS=%JAVA_OPTS% -Djava.library.path="%SOAPUI_HOME%\"
                set JAVA_OPTS=%JAVA_OPTS% -Dwsi.dir="%SOAPUI_HOME%..\wsi-test-tools"
rem uncomment to disable browser component
rem    set JAVA_OPTS=%JAVA_OPTS% -Dsoapui.jxbrowser.disable="true"

:START

rem ********* run soapui ***********

"%JAVA%" %JAVA_OPTS% com.eviware.soapui.SoapUI %*




where c:\pierre\jre32\bin\java is the location of your 32 bit JRE

Wednesday, August 1, 2012

Eclipse: Job found still running after platform shutdown.

There are 3 things to be borne in mind when working with Eclipse:

1) Eclipse is a piece of crap
2) Eclipse is a major piece of crap
3) Eclipse is a disgustingly fetid stinking piece of crap

Having said that, when you encounter this message "Job found still running after platform shutdown", just shutdown everything, rename your .metadata directory in the workspace and restart anew.
Remember also that Eclipse brilliantly writes its log into a .log file (invisible in Linux).... there you will find the real reason for the crash, which of course has NOTHING to do with the error message you get.




Oracle Instant Client on Linux

download from:

http://www.oracle.com/technetwork/database/features/instant-client/index-100365.html

or more specifically

http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html

download the RPM version

oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm

rpm -i oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
error: can't create transaction lock on /var/lib/rpm/__db.000

need to be root

String manipulation in Bash shell

I am really fed up by people who use unreadable sed and awk commands to perform basic string manipulations, like a find and replace on a string.

There are very nice expression you can use:

http://tldp.org/LDP/abs/html/string-manipulation.html

string length: ${#string}

expression matching: expr match "$string" '$substring'

index: expr index $string $substring

substring: ${string:position:length}

substring delete: ${string#substring}

find and replace: ${string//substring/replacement}


Please use awk and sed only if REALLY needed.

The only good code is readable code.