Monday, December 30, 2013

OSB, WebLogic and Logback / SLF4j

Being totally fed up with the OSB reporting provider, I am setting up logback.
Maven:
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-core</artifactId>
  <version>1.0.13</version>
</dependency>
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.0.13</version>
</dependency>
             
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-parent</artifactId>
  <version>1.0.13</version>
  <type>pom</type>
</dependency>
 
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
</dependency>



vi /opt/oracle/fmw11_1_1_5/wlserver_10.3/common/bin/commEnv.sh

add this to WEBLOGIC_CLASSPATH:

${CLASSPATHSEP}/opt/oracle/fmw11_1_1_5/wlserver_10.3/server/lib/slf4j-api-1.7.5.jar${CLASSPATHSEP}/opt/oracle/fmw11_1_1_5/wlserver_10.3/server/lib/logback-core-1.0.13.jar${CLASSPATHSEP}/opt/oracle/fmw11_1_1_5/wlserver_10.3/server/lib/logback-classic-1.0.13.jar

and copy the JARs:

cd /opt/oracle/fmw11_1_1_5/wlserver_10.3/server/lib/

this only if you have Nexus, otherwise.... copy them manually:

wget http://nexus.nespresso.com/service/local/repositories/adobe-ext/content/ch/qos/logback/logback-core/1.0.13/logback-core-1.0.13.jar

wget http://nexus.nespresso.com/service/local/repositories/adobe-ext/content/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar

wget http://nexus.nespresso.com/service/local/repositories/adobe-ext/content/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar

vi /opt/oracle/domains/osbpl1do/config/osb/logback.xml

<configuration debug="true" scan="true" scanPeriod="30 seconds">
    <jmxConfigurator />
 
    <property name="LOG_DIR" value="/opt/var/log/weblogic/server/" />
 
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder
            by default -->
        <encoder>
            <pattern>%d %-5level [%thread] %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>
 
    <appender name="GM"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_DIR}GM.log</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
              <fileNamePattern>GM.%i.log.zip</fileNamePattern>
              <minIndex>1</minIndex>
              <maxIndex>10</maxIndex>
            </rollingPolicy>
            <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
              <maxFileSize>50MB</maxFileSize>
            </triggeringPolicy>
            <encoder>
                <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
                </pattern>
            </encoder>
    </appender>
 
 
    <logger name="POC_LOG4j" additivity="false" level="INFO">
        <appender-ref ref="GM" />
    </logger>
 
    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
    </root>
 
 
</configuration>


I provide a custom XPath to log :
package com.acme.osb.logging;
import org.apache.xmlbeans.XmlObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Used by OSB to report an Event
 *
 * @author NNVernetPI
 *
 */
public class MessageTrackerSLF4J {
    public static String logMessage(String technicalMessageid,
            String businessId, String eventType, String interfaceName,
            XmlObject payload) {
        Logger projectLogger = LoggerFactory.getLogger(interfaceName);
        StringBuilder sb = new StringBuilder();
        if (projectLogger.isDebugEnabled()) {
            sb.append(" ::InterfaceName::  ").append(interfaceName)
                    .append(" ::Payload:: ").append(payload.xmlText())
                    .append(" ::BusinessID::  ").append(businessId);
        } else {
            sb.append(" ::TechnicalMessageID::  ").append(technicalMessageid)
                    .append(" ::BusinessID::  ").append(businessId)
                    .append(" ::InterfaceName::  ").append(interfaceName)
                    .append(" ::EventType::  ").append(eventType)
                    .append(" ::ServerName:: ")
                    .append(System.getProperty("weblogic.Name"));
        }
        projectLogger.info(sb.toString());
        String logmessage = "Info Message Logged for:: " + interfaceName;
        return logmessage;
    }
    public static String errorLogger(String technicalMessageid,
            String businessId, String interfaceName, XmlObject payload,
            String priority, XmlObject fault) {
        Logger projectLogger = LoggerFactory.getLogger(interfaceName);
        StringBuilder sb = new StringBuilder();
        sb.append("::TechnicalMessageID::  ").append(technicalMessageid)
                .append("  ::InterfaceName::  ").append(interfaceName)
                .append("  ::BusinessID::  ").append(businessId)
                .append(" ::Payload:: ").append(payload.xmlText())
                .append(" ::Priority::  ").append(priority)
                .append(" ::FaultDescription:: ").append(fault.xmlText())
                .append(" ::ServerName:: ")
                .append(System.getProperty("weblogic.Name"));
        projectLogger.error(sb.toString());
        String responseMessage = "Error Message Logged for:: " + interfaceName;
        return responseMessage;
    }
}


which I expose as XPath this way:
  <xpf:function>
            <xpf:name>LOG_SLF_errorLogger</xpf:name>
            <xpf:comment>logs an error</xpf:comment>
            <xpf:namespaceURI>http://www.acme.com/acme2/xquery/xquery-functions</xpf:namespaceURI>
            <xpf:className>com.acme.osb.logging.MessageTrackerSLF4J</xpf:className>
            <xpf:method>java.lang.String errorLogger(java.lang.String, java.lang.String, java.lang.String, org.apache.xmlbeans.XmlObject, java.lang.String, org.apache.xmlbeans.XmlObject)</xpf:method>
            <xpf:isDeterministic>false</xpf:isDeterministic>
            <xpf:scope>Pipeline</xpf:scope>
            <xpf:scope>SplitJoin</xpf:scope>
        </xpf:function>     
        
  <xpf:function>
            <xpf:name>LOG_SLF_messageTracker</xpf:name>
            <xpf:comment>logs an event</xpf:comment>
            <xpf:namespaceURI>http://www.acme.com/acme2/xquery/xquery-functions</xpf:namespaceURI>
            <xpf:className>com.acme.osb.logging.MessageTrackerSLF4J</xpf:className>
            <xpf:method>java.lang.String logMessage(java.lang.String, java.lang.String, java.lang.String, java.lang.String, org.apache.xmlbeans.XmlObject)</xpf:method>
            <xpf:isDeterministic>false</xpf:isDeterministic>
            <xpf:scope>Pipeline</xpf:scope>
            <xpf:scope>SplitJoin</xpf:scope>
        </xpf:function>        


Since I have activated the jmxConfigurator, I can reload the logback.xml configuration file by connecting with JMX:

jconsole -J-Djava.class.path=C:\Oracle\MIDDLE~1\JDK160~1\lib\jconsole.jar;C:\Oracle\MIDDLE~1\JDK160~1\lib\tools.jar;C:\Oracle\Middleware\wlserver_10.3\server\lib\wlfullclient.jar -J-Djmx.remote.protocol.provider.pkgs=weblogic.management.remote -debug
and connect as:
service:jmx:iiop://myserver.acme.com:8001/jndi/weblogic.management.mbeanservers.runtime



The advantage is that I can also set programmatically the logger level for each logger, via JMX.



see here the doc, the first argument is the loggerName, the second is the level

A note: reloadByFileName() requires the FULL PATH : /opt/oracle/domains/osbpl1do/config/osb/logback.xml



Thursday, December 19, 2013

Adding JAR in the weblogic domain lib folder

The problem is: if I put a JAR in the $DOMAIN_HOME/lib folder, will it be actually added to the System classpath, and available to ANYTHING which turns inside WebLogic?
To test this, I create a class
public class Pippo {
 public static String ciao() {
  return "CIAO!";
 }
}


and export it to a file pvtestjava.jar, and put the jar in the domain/lib folder, and restart the whole thing.

IN THE SERVER STDOUT file (NOT in the log file...) I can see:

<Dec 19, 2013 11:23:38 AM CET> <Info> <Security> <BEA-090906> <Changing the default 
Random Number Generator in RSA CryptoJ from
 ECDRBG to FIPS186PRNG. To disable this change, specify -Dweblogic.security.allowCryptoJDefaultPRNG=true>
<Dec 19, 2013 11:23:38 AM CET> <Notice> <WebLogicServer> <BEA-000395>
 <Following extensions directory contents added to the end of the classpath:
/opt/oracle/domains/osbpl1do/lib/log4j_1.2.8.jar:
/opt/oracle/domains/osbpl1do/lib/pvtestjava.jar>
<Dec 19, 2013 11:23:39 AM CET> <Info> <WebLogicServer> <BEA-000377> <Starting WebLogic Server with Java HotSpot(TM) 64-Bit Server VM Version 20.8-b03 from Sun Microsystems Inc.>



HOWEVER, refrain from rejoicing so soon. Not necessarily your application will see the JAR.
The documentation says
"" The JARS in the domain /lib directory will not be appended to the system classpath. The classloader that gets created is a child of the system classloader. Any classes that are in JARs in the domain /lib directory will only be visible to J2EE applications, such as EAR files. Classes in the system classpath cannot access classes in the domain /lib directory.""
For instance, the "Driver Interceptor:" to profile a Datasource will not be able to use this classpath extension mechanism. And if you dump the system classpath you will NOT see those domain/lib jars.

The EXTENSION classpath can be explicitly set with -Dweblogic.ext.dirs=$DOMAIN_HOME/lib

Tuesday, December 17, 2013

WebLogic "run as" webApplication

Here http://docs.oracle.com/cd/E11035_01/wls100/security/thin_client.html#wp1046373 you find an example on how to attach a principal to a webapp request, without having to explicitly passing it like in:

curl -u username:password url

it works like a breeze

weblogic.xml:

<?xml version = '1.0' encoding = 'windows-1252'?>
<weblogic-web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-web-app http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd" xmlns="http://www.bea.com/ns/weblogic/weblogic-web-app">
  <context-root>gridlinkha</context-root>
    <run-as-role-assignment>
       <role-name>hypericrole</role-name>
       <run-as-principal-name>weblogic</run-as-principal-name>
     </run-as-role-assignment>  
</weblogic-web-app>




web.xml:


<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
  <servlet>
    <servlet-name>FCFHAServlet</servlet-name>
    <servlet-class>oracle.support.ha.FCFHAServlet</servlet-class>
        <run-as>
      <role-name>hypericrole</role-name>
    </run-as>
  </servlet>
    <security-role>
    <role-name>hypericrole</role-name>
  </security-role>
  <servlet-mapping>
    <servlet-name>FCFHAServlet</servlet-name>
    <url-pattern>/fcfhaservlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>/index.html</welcome-file>
  </welcome-file-list>
</web-app>




OSB: wlsbjmsrpDataSource can be looked up only by an Admin or ALSBSystem user

The short way:
cd /opt/oracle/domains/osbdev1do/servers/osbdev1ms1/data/ldap/ldapfiles

less EmbeddedLDAP.data

search for wlsbjmsrpDataSource 


you will find the policy:

<Policy xmlns="urn:oasis:names:tc:xacml:2.0:policy:schema:os" PolicyId="urn:bea:xacml:2.0:entitlement:resource:type@E@Fjndi@G@M@Oapplication@E@M@Opath@E@VwlsbjmsrpDataSource@W" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"><Description>Rol(ALSBSystem) | Rol(Admin)</Description><Target><Resources><Resource><ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"><AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">type=<jndi>, application=, path={wlsbjmsrpDataSource}</AttributeValue><ResourceAttributeDesignator AttributeId="urn:oasis:names:tc:xacml:2.0:resource:resource-ancestor-or-self" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"/></ResourceMatch></Resource></Resources></Target><Rule RuleId="primary-rule" Effect="Permit"><Condition><Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:or"><Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-is-in"><AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">ALSBSystem</AttributeValue><SubjectAttributeDesignator AttributeId="urn:oasis:names:tc:xacml:2.0:subject:role" DataType="http://www.w3.org/2001/XMLSchema#string"/></Apply><Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-is-in"><AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Admin</AttributeValue><SubjectAttributeDesignator AttributeId="urn:oasis:names:tc:xacml:2.0:subject:role" DataType="http://www.w3.org/2001/XMLSchema#string"/></Apply></Apply></Condition></Rule><Rule RuleId="deny-rule" Effect="Deny"></Rule></Policy>



so if you are using the GridLink http://www.oracle.com/technetwork/articles/gridlink-rac-488352.zip monitoring application, you should make sure it runs with a technical id which is Admin or ALSBSystem .

Saturday, December 14, 2013

Bertrand Russel on Managers

"I once saw a photograph of a large herd of wild elephants in Central Africa seeing an airplane for the first time, and all in state of wild collective terror... As, however, there were no managers among them, the terror died down when the airplane was out of sight."

More Russel's quotes here. Good old Bertrand Russel, he was my adolescence hero, he inspired me to be a Conscience Objector against war, at a time when in Italy it was still a tough challenge.





(PS the original quote was "journalists", not "managers")

Wednesday, December 11, 2013

Git: SSL certificate problem: unable to get local issuer certificate

git clone https://stash.acme.com/scm/pup/biemond-orawls-vagrant.git

Cloning into 'biemond-orawls-vagrant'...
fatal: unable to access 'https://stash.acme.com/scm/pup/biemond-orawls-vagrant.git/': SSL certificate problem: unable to get local issuer certificate

The secret is
set GIT_SSL_NO_VERIFY=true
git clone etc etc


Tuesday, December 10, 2013

Remove annoying debug info from wlst.sh

I normally run /opt/oracle/fmw11_1_1_5/osb/common/bin/wlst.sh for all WLST commands.

This print a page of debug information (mostly, twice the CLASSPATH and once the PATH.
It's a lot of unneeded info which clutters the logs.

The script will invoke in sequence:
/opt/oracle/fmw11_1_1_5/osb/common/bin/setHomeDirs.sh
/opt/oracle/fmw11_1_1_5/utils/config/10.3/setHomeDirs.sh
/opt/oracle/fmw11_1_1_5/oracle_common/common/bin/wlst.sh

...
and plenty of other scripts, but finally it will call /opt/oracle/fmw11_1_1_5/wlserver_10.3/common/bin/wlst.sh
it's interesting that we have 4 wlst.sh scripts:
/opt/oracle/fmw11_1_1_5/oracle_common/common/bin/wlst.sh
/opt/oracle/fmw11_1_1_5/osb/common/bin/wlst.sh
/opt/oracle/fmw11_1_1_5/osb/harvester/wlst.sh
/opt/oracle/fmw11_1_1_5/wlserver_10.3/common/bin/wlst.sh

One echo is in /opt/oracle/fmw11_1_1_5/wlserver_10.3/common/bin/wlst.sh
The other echo CLASSPATH=$CLASSPATH statement is in
/opt/oracle/fmw11_1_1_5/wlserver_10.3/server/bin/setWLSEnv.sh


Saturday, December 7, 2013

Getting started with Spring UI MVC, a basic WebApplication "download and play"

Something that literally runs me crazy is when you must spend one hour just to setup the basics just to be able to start working with a new product. Need to download a dozen files, manually hack a few XML... just to do a basic Hello World. So aggravating.

Existing tutorials also do their best to flood you with words and giving you only fragmentary instructions on how to get started.

In reality, nothing is more educational than having a ready environment to start playing with the product. Just give me that sandbox, a link to the documentation and shut up.

Here for instance there are instructions on how to get started with Spring Source Tooolkit.

Here is a "download and play" https://javatoolsforweblogic.googlecode.com/svn/trunk/wlavatar.zip Eclipse project. All you need is to install Maven and create the Eclipse variable MVN_REPO to point to your Maven repository, then open a prompt in the Project's root folder and type "mvn package". Have fun.



Wednesday, December 4, 2013

JMXTerm and WebLogic

Download the uberjar http://wiki.cyclopsgroup.org/jmxterm/download (I love that, no need to have complicated classpaths). This link worked for me.

On how to configure WebLogic for JMS see here.

This is a sample session:
java -jar jmxterm-1.0-alpha-4-uber.jar
#this will connect remotely
open myserver.acme.com:8888
#this will list all available beans
beans
#this will filter only com.bea stuff
domain com.bea
#this will set your current bean
bean com.bea:Name=wlsbjmsrpDataSource,ServerRuntime=osbpl1as,Type=JDBCDataSourceRuntime
#this will get an attrbute from current bean
get ActiveConnectionsCurrentCount


For a more complete example: Here a lot of useful commands.



Git: Received HTTP code 407 from proxy

I was cloning a git project:

git clone https://github.com/jiaqi/jmxterm

and I got
fatal: unable to access 'https://github.com/jiaqi/jmxterm/': Received HTTP code 407 from proxy after
 CONNECT


just do

git config --global http.proxy http://myusername:mypassword@proxy.acme.com:8080

and it will work (inshallah)

WLST: certificate parsing exception PKIX

"The loading of the trusted certificate list raised a certificate parsing exception PKIX: Unsupported OID in the AlgorithmIdentifier object"

it turned out that I had to add to the WLST trust store (wlsTrust.jks) the root certificate of the CA certifying the Identity Store of the domain

and add this to wlst.sh :

export WLST_PROPERTIES="-Dweblogic.security.SSL.ignoreHostnameVerification=true -Dweblogic.security.TrustKeyStore=CustomTrust -Dweblogic.security.CustomTrustKeyStoreFileName=/opt/oracle/certs/wlsTrust.jks -Dweblogic.security.CustomTrustKeyStorePassPhrase=bla -Dweblogic.security.CustomTrustKeyStoreType=JKS"



Monday, December 2, 2013

Puppet and WebLogic the Biemond way

I always follow Biemond post, on the the richest sources of inspiration for all Oracle Professionals.

Here he makes his WebLogic/Puppet module available to the public:
http://biemond.blogspot.ch/2013/11/new-puppet-3-weblogic-provisioning.html

I login as root on my vagrant VirtualBox (RHEL) and I type:
puppet --version
3.2.4 (Puppet Enterprise 3.0.1)

Then I type
puppet module install biemond/orawls

Notice: Preparing to install into /etc/puppetlabs/puppet/modules ...
Notice: Created target directory /etc/puppetlabs/puppet/modules
Notice: Downloading from https://forge.puppetlabs.com ...
Notice: Installing -- do not interrupt ...
/etc/puppetlabs/puppet/modules
âââ biemond-orawls (v0.2.1)

Cool!
I see that he has also provided a Vagrant box https://github.com/biemond/biemond-orawls-vagrant. I do a "git clone https://github.com/biemond/biemond-orawls-vagrant" and I got the biemond-orawls-vagrant folder with my vagrantfile in it. I cd biemond-orawls-vagrant and do vagrant up.

I get this nasty message
Vagrant has detected that you have a version of VirtualBox installed
that is not supported. Please install one of the supported versions
listed below to use Vagrant:

4.0, 4.1, 4.2

and in fact I have the latest 4.3.4 version of VirtualBox.
I do vagrant --version
Vagrant version 1.1.5
Ok let's download the latest 1.3.5 vagrant .
and install it (it takes a looooong time, reboot required )
I repeat "vagrant up" and this time Vagrant is happy and it downloads the centos-6.4-x86_64 base box (600 MB, it can take a long time depending on the connection speed)


The second attempt fails because there is no /vagrant/jdk-7u45-linux-x64.tar.gz file

I download the missing file from http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html and I put the jdk-7u45-linux-x64.tar.gz file in the same folder where I keep the vagrantfile (it will be synced by Vagrant, and mapped to /vagrant/jdk-7u45-linux-x64.tar.gz - after a vagrant destroy and another vagrant up... ).

When you connect to the VBOX, configure your putty with 127.0.0.1 port 2222 (note that in the VirtualBOx, it's also specified the IP 127.0.0.1, otherwise each time the IP of the host changes, you have to change the putty configuration...)

This time around, it complains that /data/install/wls1036_generic.jar is not found.

I download it from here http://download.oracle.com/otn/nt/middleware/11g/wls/1036/wls1036_generic.jar and manually copy it to /data/install and to the /vagrant share (melius abundare quam deficere) in the VBOX

I run "vagrant provision".

Again, p17071663_1036_Generic.zip is missing (ah if only I had read the doc before...)...
to get this file, you must log into support.oracle.com, click on "patches", specify the WebLogic 10.3.6 Product for Any platform and you will be presented with only one download: "SU Patch [BYJ1]: WLS PATCH SET UPDATE 10.3.6.0.6 (Patch) p17071663_1036_Generic.zip"

This time around I get a "Error: /Stage[main]/Bsu/Orawls::Bsu[BYJ1]/Exec[exec bsu ux BYJ1]/returns: change from notrun to 0 failed: Command exceeded timeout" after the extraction of the patchset.

For the OSB version, refer to:

https://github.com/matthewbaldwin/vagrant-osb

which is really well documented.

PS Important: don't run "vagrant up" because the node1 will copydomain from admin node BEFORE this is ready. You should first do "vagrant up admin", then "vagrant up node1" and vagrant up node2". After the "vagrant up admin" the admin server is running and accessble from the host machine with http://10.10.10.10:7001/console/ (this is not a global ip, it will work only locally)

OSB: disable enable status of Proxy Services

#There is a change to do to be able to run this WLST script:
#vi /opt/oracle/fmw11_1_1_5/osb/common/bin/wlst.sh
#change this:
#export CLASSPATH
#into this:
#CLASSPATH=/opt/oracle/fmw11_1_1_5/osb/lib/sb-kernel-api.jar:/opt/oracle/fmw11_1_1_5/osb/lib/sb-kernel-impl.jar:/opt/oracle/fmw11_1_1_5/osb/modules/com.bea.common.configfwk_1.5.0.0.jar:$CLASSPATH
#export CLASSPATH


import javax.management
import java.util
import javax.management.remote
import javax.naming
import weblogic.management.mbeanservers.domainruntime
import com.bea.wli.sb.management.configuration

from java.util import Hashtable
from java.util import HashSet
from javax.management.remote import JMXServiceURL
from weblogic.management.mbeanservers.domainruntime import DomainRuntimeServiceMBean
from javax.naming import Context
from javax.management.remote import JMXConnectorFactory
from javax.management import ObjectName
from com.bea.wli.sb.management.configuration import SessionManagementMBean
from com.bea.wli.sb.management.configuration import ALSBConfigurationMBean
from com.bea.wli.sb.management.configuration import CommonServiceConfigurationMBean
import weblogic.management.jmx.MBeanServerInvocationHandler
from com.bea.wli.config import Ref



from com.bea.wli.config.env import EnvValueQuery
from com.bea.wli.config.env import QualifiedEnvValue
from com.bea.wli.config.resource import DependencyQuery
from com.bea.wli.sb.management.query import ProxyServiceQuery
from com.bea.wli.sb.management.query import BusinessServiceQuery

from com.bea.wli.sb.util import EnvValueTypes
from java.util import Collection
from java.util import Collections

def readvarsDPCL(clargs):
    print "readvarsDPCL executed with clargs=", clargs
    domain = None
    password = None
    command = None
    list = None
    opts, args = getopt.getopt(clargs, "d:p:c:l:")
    for opt, arg in opts:
        if opt in "-d":
            domain = arg
        if opt in "-p":
            password = arg
        if opt in "-c":
            command = arg
        if opt in "-l":
            list = arg
    return domain, password, command, list



def enableDisableAllServices(command):
    refs = configMBean.getRefs(Ref.DOMAIN)
    refsList = ArrayList()
    refsList.addAll(refs)
    
    for ref in refsList :
        if ref.getTypeId() == "ProxyService" or ref.getTypeId() == "BusinessService" :
            if ref.getTypeId() == "ProxyService" :
                projectName = ref.getFullName()
                found = False
                for project in list.split(','):
                    if project in projectName:
                        found = True
                if (list == 'ALL') or found:
                    if command == 'enable':
                        print "enabling service for ", projectName
                        proxyServiceConfigurationMBean.enableService(ref)
                    if command == 'disable':
                        print "disabling service for ", projectName
                        proxyServiceConfigurationMBean.disableService(ref)
                    if command == 'status':
                        print "service ", projectName , " enabled=", proxyServiceConfigurationMBean.isEnabled(ref)


#reading command line parameters
domain, password, command, list = readvarsDPCL(sys.argv[1:])
print "domain=", domain

if (domain == None) :
    print('ERROR: invalid command, expected arguments "domain" ')
    exit()



#please enter here your parameters
adminUserName, adminPassword, adminURL = ["bla", "bla", "bla"]
LISTEN_ADDRESS_VIP = 'bla'
PORT = 'bla'

if (adminPassword == None) :
     sys.stderr.write("unable to proceed, password not set\n")
     sys.exit()

if (command == None):
    print "please provide a command (enable/disable)"
    exit()
         
if (list == None):
    print "please provide a comma separated list of projects (ALL for all projects)"
    exit()
             
sessionName = "EnabledChange"

serviceURL=JMXServiceURL("t3", LISTEN_ADDRESS_VIP, int(PORT), "/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME)

h=Hashtable()
h.put(Context.SECURITY_PRINCIPAL, adminUserName)
h.put(Context.SECURITY_CREDENTIALS, adminPassword)
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote")

conn = JMXConnectorFactory.connect(serviceURL, h)

mbconn = conn.getMBeanServerConnection()

sm = JMX.newMBeanProxy(mbconn, ObjectName.getInstance(SessionManagementMBean.OBJECT_NAME), SessionManagementMBean)

sm.createSession(sessionName)

try:
    configMBean = JMX.newMBeanProxy(mbconn, ObjectName.getInstance("com.bea:Name=" + ALSBConfigurationMBean.NAME + "." + sessionName + ",Type=" + ALSBConfigurationMBean.TYPE), ALSBConfigurationMBean)
    domainService = weblogic.management.jmx.MBeanServerInvocationHandler.newProxyInstance(mbconn, ObjectName(DomainRuntimeServiceMBean.OBJECT_NAME), DomainRuntimeServiceMBean, false)
    proxyServiceConfigurationMBean = domainService.findService(String("ProxyServiceConfiguration.").concat(sessionName),'com.bea.wli.sb.management.configuration.ProxyServiceConfigurationMBean', None)
    enableDisableAllServices(command)
    sm.activateSession(sessionName, "Complete enable/disable services")
    conn.close()

except Exception, inst:
    print inst
    print sys.exc_info()[0]
    dumpStack()
    if sm.sessionExists(sessionName):
        print "undoing session"
        sm.discardSession(sessionName)
    sys.stderr.write("unable to work on domain " + domain)



An alternative script - connecting with t3 and using the secureConfig files for authentication - is:

#There is a change to do to be able to run this WLST script:
#vi /opt/oracle/fmw11_1_1_5/osb/common/bin/wlst.sh
#change this:
#export CLASSPATH
#into this:
#CLASSPATH=/opt/oracle/fmw11_1_1_5/osb/lib/sb-kernel-api.jar:/opt/oracle/fmw11_1_1_5/osb/lib/sb-kernel-impl.jar:/opt/oracle/fmw11_1_1_5/osb/modules/com.bea.common.configfwk_1.5.0.0.jar:$CLASSPATH
#export CLASSPATH


import javax.management
import java.util
import javax.management.remote
import javax.naming
import weblogic.management.mbeanservers.domainruntime
import com.bea.wli.sb.management.configuration

from java.util import Hashtable
from java.util import HashSet
from javax.management.remote import JMXServiceURL
from weblogic.management.mbeanservers.domainruntime import DomainRuntimeServiceMBean
from javax.naming import Context
from javax.management.remote import JMXConnectorFactory
from javax.management import ObjectName
from com.bea.wli.sb.management.configuration import SessionManagementMBean
from com.bea.wli.sb.management.configuration import ALSBConfigurationMBean
from com.bea.wli.sb.management.configuration import CommonServiceConfigurationMBean
import weblogic.management.jmx.MBeanServerInvocationHandler
from com.bea.wli.config import Ref
from cmdbfile import connectSecureToAdmin
import getopt

verbose = False

def readvarsDCL(clargs):
    print "readvarsDPCL executed with clargs=", clargs
    domain = None
    password = None
    command = None
    list = None
    opts, args = getopt.getopt(clargs, "d:c:l:")
    for opt, arg in opts:
        if opt in "-d":
            domain = arg
        if opt in "-c":
            command = arg
        if opt in "-l":
            list = arg
    return domain, command, list



def enableDisableAllServices(command):
    refs = configMBean.getRefs(Ref.DOMAIN)
    refsList = ArrayList()
    refsList.addAll(refs)
    if verbose: print len(refsList), " Refs found"
    
    for ref in refsList :
        if ref.getTypeId() == "ProxyService" :
            projectName = ref.getFullName()
            if verbose: print "processing ", projectName
            found = False
            for project in list.split(','):
                if project in projectName:
                    found = True
            if (list == 'ALL') or found:
                if command == 'enable':
                    print "enabling service for ", projectName
                    proxyServiceConfigurationMBean.enableService(ref)
                if command == 'disable':
                    print "disabling service for ", projectName
                    proxyServiceConfigurationMBean.disableService(ref)
                if command == 'status':
                    print "service ", projectName , " enabled=", proxyServiceConfigurationMBean.isEnabled(ref)


#reading command line parameters
domain, command, list = readvarsDCL(sys.argv[1:])
print "domain=", domain

if (domain == None) :
    print('ERROR: invalid arguments, expected arguments "domain" ')
    exit()

if (command == None or command not in ['enable', 'disable', 'status']):
    print "please provide a valid command (enable/disable/status)"
    exit()
         
if (list == None):
    print "please provide a comma separated list of projects (ALL for all projects)"
    exit()
             

userConfigFile, userKeyFile, serverURL = connectSecureToAdmin(domain)
connect(userConfigFile=userConfigFile,userKeyFile=userKeyFile,url=serverURL)

domainRuntime()

sessionName = "DisableEnableProjects" + Long(System.currentTimeMillis()).toString()
sessionMBean = findService(SessionManagementMBean.NAME,SessionManagementMBean.TYPE)
sessionMBean.createSession(sessionName)
print 'Session was created … ' + sessionName

try:
    proxyServiceConfigurationMBean = findService("ProxyServiceConfiguration." + sessionName,"com.bea.wli.sb.management.configuration.ProxyServiceConfigurationMBean")
    configMBean = findService(ALSBConfigurationMBean.NAME, ALSBConfigurationMBean.TYPE)
    enableDisableAllServices(command)
    sessionMBean.activateSession(sessionName, "Complete enable/disable services")

except Exception, inst:
    print inst
    print sys.exc_info()[0]
    dumpStack()
    if sessionMBean.sessionExists(sessionName):
        print "undoing session"
        sessionMBean.discardSession(sessionName)
    sys.stderr.write("unable to work on domain " + domain)




JMS message delete in Java

destinationJNDI should contain the JNDI name of the queue, like "CommonJmsServer1@jms.jndi.dq.NL_Notifications.NLNotificationReprocessQ".


ctx should be a valid InitialContext like:
idlist should be a CSV list of message IDs that you want to delete


 Properties env = new Properties();
  env.put(javax.naming.Context.PROVIDER_URL, PROVIDER_URL);
  env.put(Context.SECURITY_PRINCIPAL, WL_USER);
  env.put(Context.SECURITY_CREDENTIALS, WL_PASSWORD);
  env.put(Context.INITIAL_CONTEXT_FACTORY, WL_INITIAL_CONTEXT_FACTORY);
  InitialContext ctx = new InitialContext(env);


 javax.jms.Queue queue = (javax.jms.Queue) ctx.lookup(destinationJNDI.toString());

  // lookup the queue connection factory
  QueueConnectionFactory queueConnFactory = (QueueConnectionFactory) ctx.lookup(WEBLOGIC_JMS_XA_CONNECTION_FACTORY);
  // create a queue connection
  QueueConnection queueConn = queueConnFactory.createQueueConnection();
  queueConn.start();

  // create a queue session
  Session queueSession = queueConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
  for (String id : idlist.split(",")) {
      if (id.startsWith("ID:") ) {
        MessageConsumer consumer = queueSession.createConsumer(queue, " JMSMessageID='" +   id + "'");
        Message message = consumer.receive(1000);
        out.write("message = " + message + " ");
        out.write("deleted ID " + id + " ");
      }
  }
  queueSession.close();
  queueConn.close();


(posted also on StackOverflow)

Sunday, December 1, 2013

Windows 8 is just plain horrible

I have made the big mistake of offering an acquaintance a brand new Laptop, to discover only too late it was mounting Windows 8.
It's like a computer turned into a IPhone. Plain stupid choice... the Iphone UI was meant for a small screen, while on a 17 inches screen you can afford a lot more ergonomics than an Iphone.

All the people who came to grip with it, simply hated the new User Interface.

There are tricks to make Windows 8 look more like its predecessors, but it's not going to be very effective IMHO.

I am sure you didn't need YET another reason to hate Microsoft, buy they are really doing their best to poison our life.
Do yourself a favour: refuse to buy anything who mounts Windows 8.
Better an old crappy laptop with Windows XP than this freak.

barefoot at office

I am a strong advocate of Primitivism - meaning by that from the invention of Agriculture (10k BC) onwards humanity has only experienced a degradation in the quality of life.

Small tribal units scattered over a vast territory and eking out a living my marginally cropping the fruits of Earth, was the real Zenith of civilization. Lascaux forever. No nuclear weapons, no pollution, no mass warfare, no electronic loneliness, no massive ecosystems destruction, no high-heels shoes with snotty women inside. Sometimes out might be eaten by a lion, but that's life - better a lion than scam capitalism.

Unfortunately in the corporate world it is believed that the more we complicate life, the better. So walking barefoot is not considered OK - although we have been doing that for million of years and it was quite OK since we did quite well as a species.

I am affected by flat feet because when a child I was made to wear the same shoes for several years until they busted my metatarsal arches. This flat feet condition can be extremely taxing on your quads and calves. Any kind of insoles or orthotics have proven useless if not harmful. When you are affected by flat-feet, the best thing you can do is walking barefoot. On grass, on sand, even on asphalt (but don't overdo it on asphalt or you will get painful blisters... asphalt is not natural and our feet were not engineered for it).

The second best alternative is to try some "special" minimalistic shoes, who get you as close as possible to the barefoot experience without management kicking you out: I am trying now this https://en.wikipedia.org/wiki/Vivobarefoot

I have tried also https://en.wikipedia.org/wiki/Vibram_FiveFingers but it's not really acceptable at office.... besides I hate accommodating each toe in a separate slot...

Healthy, primitive feet who have never known the imprisonment of a shoe: