Thursday, December 14, 2017

Encryption and Decryption of files in Java using BouncyCastle as provider

Following example shows how to encrypt and decrypt files using BouncyCastle jars

Download and add these jars to project classpath
bcmail-jdk15on-158.jar
bcpkix-jdk15on-158.jar
bcprov-ext-jdk15on-158.jar
bcprov-jdk15on-158.jar




package abcd;

import org.bouncycastle.cms.*;
import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;
import org.bouncycastle.jcajce.provider.symmetric.DES;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.OutputEncryptor;

import java.io.*;
import java.nio.file.Files;
import java.security.*;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;

public class EncryptAndDecrypt {

    private static final String WORK_DIR = "/C:/Users/xyz/apps/workspace/ABCD";

    private static final File SOURCE_PDF = new File(WORK_DIR, "running-log.txt");
    private static final File DESTINATION_FILE = new File(WORK_DIR, "running-log123.txt");
    private static final File DECRYPTED_FILE = new File(WORK_DIR, "decrypted.txt");

    public static void main(final String[] args) throws Exception {
        if (!new File(WORK_DIR).exists()) {
            throw new RuntimeException("Update WORK_DIR to point to the directory the project is cloned into.");
        }
        Files.deleteIfExists(DESTINATION_FILE.toPath());
        Files.deleteIfExists(DECRYPTED_FILE.toPath());

        Security.addProvider(new BouncyCastleProvider());

        //X509Certificate certificate = getX509Certificate(new File(WORK_DIR, "myp12file.p12"));
        X509Certificate certificate = getX509Certificate(new File(WORK_DIR, "xyzTestCert.cert"));
        PrivateKey privateKey = getPrivateKey(new File(WORK_DIR, "myp12file.p12"), "changeit");

        encrypt(certificate, SOURCE_PDF, DESTINATION_FILE);
        decrypt(privateKey, DESTINATION_FILE, DECRYPTED_FILE);
    }

    private static void decrypt(PrivateKey privateKey, File encrypted, File decryptedDestination) throws IOException, CMSException {
        byte[] encryptedData = Files.readAllBytes(encrypted.toPath());

        CMSEnvelopedDataParser parser = new CMSEnvelopedDataParser(encryptedData);

        RecipientInformation recInfo = getSingleRecipient(parser);
        Recipient recipient = new JceKeyTransEnvelopedRecipient(privateKey);

        try (InputStream decryptedStream = recInfo.getContentStream(recipient).getContentStream()) {
            Files.copy(decryptedStream, decryptedDestination.toPath());
        }

        System.out.println(String.format("Decrypted '%s' to '%s'", encrypted.getAbsolutePath(), decryptedDestination.getAbsolutePath()));
    }

    private static void encrypt(X509Certificate cert, File source, File destination) throws CertificateEncodingException, CMSException, IOException {
        CMSEnvelopedDataStreamGenerator gen = new CMSEnvelopedDataStreamGenerator();
        gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(cert));
        //OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME).build();
        OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME).build();
        
        try (FileOutputStream fileStream = new FileOutputStream(destination);
             OutputStream encryptingStream = gen.open(fileStream, encryptor)) {

            byte[] unencryptedContent = Files.readAllBytes(source.toPath());
            encryptingStream.write(unencryptedContent);
        }

        System.out.println(String.format("Encrypted '%s' to '%s'", source.getAbsolutePath(), destination.getAbsolutePath()));
    }

    private static X509Certificate getX509Certificate(File certificate) throws IOException, CertificateException {
        try (InputStream inStream = new FileInputStream(certificate)) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            return (X509Certificate) cf.generateCertificate(inStream);
        }
    }

    private static PrivateKey getPrivateKey(File file, String password) throws Exception {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (FileInputStream fis = new FileInputStream(file)) {
            ks.load(fis, password.toCharArray());
        }

        Enumeration<String> aliases = ks.aliases();
        String alias = aliases.nextElement();
        return (PrivateKey) ks.getKey(alias, password.toCharArray());
    }

    private static RecipientInformation getSingleRecipient(CMSEnvelopedDataParser parser) {
        Collection recInfos = parser.getRecipientInfos().getRecipients();
        Iterator recipientIterator = recInfos.iterator();
        if (!recipientIterator.hasNext()) {
            throw new RuntimeException("Could not find recipient");
        }
        return (RecipientInformation) recipientIterator.next();
    }
}

PKCS7 signing in Java using BouncyCastle as provider

Following example shows how to sign a string text using BouncyCastle jars

Download and add these jars to project classpath
bcmail-jdk15on-158.jar
bcpkix-jdk15on-158.jar
bcprov-ext-jdk15on-158.jar
bcprov-jdk15on-158.jar




package abcd;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;
import org.bouncycastle.util.encoders.Base64;

public final class PKCS7Signer {

    private static final String PATH_TO_KEYSTORE = "c:/users/xyz/selfsignedxyz.jks";
    private static final String KEY_ALIAS_IN_KEYSTORE = "xyzCertAlias";
    private static final String KEYSTORE_PASSWORD = "xyz";
    private static final String SIGNATUREALGO = "SHA1withRSA";

    public PKCS7Signer() {
    }

    KeyStore loadKeyStore() throws Exception {

        KeyStore keystore = KeyStore.getInstance("JKS");
        InputStream is = new FileInputStream(PATH_TO_KEYSTORE);
        keystore.load(is, KEYSTORE_PASSWORD.toCharArray());
        return keystore;
    }

    CMSSignedDataGenerator setUpProvider(final KeyStore keystore) throws Exception {

        Security.addProvider(new BouncyCastleProvider());
        Certificate[] certchain = (Certificate[]) keystore.getCertificateChain(KEY_ALIAS_IN_KEYSTORE);
        final List<Certificate> certlist = new ArrayList<Certificate>();
        for (int i = 0, length = certchain == null ? 0 : certchain.length; i < length; i++) {
            certlist.add(certchain[i]);
        }

        Store certstore = new JcaCertStore(certlist);

        Certificate cert = keystore.getCertificate(KEY_ALIAS_IN_KEYSTORE);

        ContentSigner signer = new JcaContentSignerBuilder(SIGNATUREALGO).setProvider("BC").
                build((PrivateKey) (keystore.getKey(KEY_ALIAS_IN_KEYSTORE, KEYSTORE_PASSWORD.toCharArray())));

        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").
                build()).build(signer, (X509Certificate) cert));

        generator.addCertificates(certstore);

        return generator;
    }

    byte[] signPkcs7(final byte[] content, final CMSSignedDataGenerator generator) throws Exception {

        CMSTypedData cmsdata = new CMSProcessableByteArray(content);
        CMSSignedData signeddata = generator.generate(cmsdata, true);
        return signeddata.getEncoded();
    }

    public static void main(String[] args) throws Exception {

        PKCS7Signer signer = new PKCS7Signer();
        KeyStore keyStore = signer.loadKeyStore();
        CMSSignedDataGenerator signatureGenerator = signer.setUpProvider(keyStore);
        String content = "some bytes to be signed";
        byte[] signedBytes = signer.signPkcs7(content.getBytes("UTF-8"), signatureGenerator);
        System.out.println("Signed Encoded Bytes: " + new String(Base64.encode(signedBytes)));
    }
}

AWS Linux port forwarding and IPTABLES commands

Port forwarding from 80/443 to 3000

List
iptables -t nat -nvL

List
sudo cat /etc/sysconfig/iptables

Insert
sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 3000
sudo iptables -t nat -I PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 3000

Save
sudo /sbin/service iptables save

delete

sudo iptables -t nat -D PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 3000

Ruby on Rails - Useful Commands

Rails DB Rebuilding
rake db:drop && rake db:create && rake db:migrate && rake db:seed (Windows)
rake db:drop;rake db:create;rake db:migrate;rake db:seed (Unix)

rake db:drop RAILS_ENV=production; rake db:create RAILS_ENV=production;rake db:migrate RAILS_ENV=production;rake db:seed RAILS_ENV=production
  
rake db:drop RAILS_ENV=development; rake db:create RAILS_ENV=development;rake db:migrate RAILS_ENV=development

Rails precompile
rake assets:clean && rake assets:precompile environment=development
rake assets:clean && rake tmp:clear && rake assets:clobber && rake assets:precompile

Rails Generate artifacts
rails generate scaffold Promotion name:string code:string startdate:datetime enddate:datetime
rails generate migration AddColumnToAppointments

Rails DB Console
rails dbconsole
.headers on

select * from users where profile_id = 17;

Financial mistakes by new NRIs in USA


  1. Not contributing 100% to 401K plan
  2. Sending too much money to India
  3. Buying properties in India - not able to take care of properties
  4. Giving loans to people in India 
  5. Buying life insurance in India not knowing if it covers NRIs
  6. Continuing to maintain regular bank accounts in India
  7. Not converting bank accounts to NRI accounts


Saturday, August 27, 2016

ruby on rails installation and configuration on Amazon EC2 Linux instance


  1. sudo yum install -y git-core zlib zlib-devel gcc-c++ patch readline readline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison curl sqlite-devel
  2. git clone git://github.com/sstephenson/rbenv.git .rbenv
  3. echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
  4. echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
  5. exec $SHELL
  6. git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
  7. echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bash_profile
  8. exec $SHELL
  9. rbenv install -v 2.2.4
  10. ruby --version
  11. rbenv global 2.2.4
  12. git clone git://github.com/nodejs/node.git
  13. cd node
  14. git checkout v6.0.0
  15. ./configure
  16. make
  17. sudo make install
  18. sudo su
  19. git clone https://github.com/isaacs/npm.git
  20. cd npm/
  21. exit
  22. sudo make install
To access webapp running on Amazon instance from laptop, make sure you start rails with "-b 0.0.0.0" option to bind it on all interfaces and configure security groups to allow custom tcp traffic on whichever port rails is listening

Thursday, March 12, 2015

WebLogic patching

cd /appserver/Oracle/Middleware-10.3.6/utils/bsu/cache_dir
unzip /tmp/p17246737_1036_Generic.zip
./bsu.sh -prod_dir=/appserver/Oracle/Middleware-10.3.6/wlserver_10.3  -patchlist=H6RZ -verbose -install
./bsu.sh -report -patch_id_mask=H6RZ

Sunday, January 25, 2015

Kirana best price delivery application

Problem to solve: People have to go to multiple shops for checking best price. Then, they buy stuff they needed and wait for an auto/rikshaw to bring those goods home. They often need to go to multiple shops for different items


  1. Buyer builds an order list and places the order from a mobile device
  2. XYZ receives the order and finds optimal prices/shops to buy those items
  3. XYZ sends "order picking boys" to gather items by pooling items from different orders
  4. "order picking boys" bring items to XYZ warehouse where they pack each order
  5. "order delivery boys" deliver orders, bring cash
  6. XYZ gets feed from local big shops and distributors containing item prices for that day
  7. XYZ and distributors settle finances later by reconciling transactions 

Small business order and inventory management system

Problem to solve: Automate the ordering of items in a small grocery/kirana merchant.
Usecase: 
  1. A kirana merchant owner orders items from wholesale distributor 
  2. #1 can be a onetime or recurrent order
  3. Kirana merchant can select items, adds them to the order and specifies quantity
  4. kirana merchant adds address and phone number for delivery
  5. Wholesale distributor is notified whenever there is a new order
  6. Wholesale distributor has ability to cancel/fulfill/deliver/getPaymentConfirmation order

Thursday, January 15, 2015

Simple Android Application using Activities and Maps

This is a simple Android app that uses two activities. This app uses Google Maps API.


  1. Download Android studio and install
  2. Create a new blank activity - this is the launcher activity
  3. Login to google and enable Maps API by providing SHA-1 value of your client
    1. C:\Users\xyz>keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
    2. Register ssh-1 key in google API console along with application package name
    3. Get the key and save it in android manifest
  4. Launcher activity creates a new private class that extends AsyncTask
  5. This class is responsible to call the API to retrieve JSON rest call
  6. JSON output is parsed and we only retrieve few values we needed from the json hierarchy
  7. There is a second button that invokes a MapsActivity when clicked by passing latitude and longitude via intent
  8. This app uses free http://api.openweathermap.org weather API
Important file contents

google_maps_api.xml
<resources>
    <string name="google_maps_key_instructions" templateMergeStrategy="replace">
    <string name="google_maps_key" templateMergeStrategy="preserve">GoogleAPIKeyHere</string>
</resources>
MainActivity.java
package com.example.xyz.myapplication;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;


public class MainActivity3 extends ActionBarActivity  implements View.OnClickListener {

    public static final String RESTAPI_URL = "http://api.openweathermap.org/data/2.5/weather?q=";

    public static final String UNITS = "&units=metric";

    EditText result;
    EditText cityCountry;
    ProgressBar pb;
    Button button;

    String longitude;
    String latitude;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity3);

        pb = (ProgressBar) findViewById(R.id.progressBar2);
        pb.setVisibility(View.GONE);

        button = (Button) findViewById(R.id.show);
        button.setOnClickListener(this);

        Button mapButton = (Button) findViewById(R.id.showMap);
        mapButton.setOnClickListener(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main_activity3, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {

        if( v.getId() ==  R.id.showMap ) {
            Intent intent = new Intent(this, MapsActivity.class);
            intent.putExtra("lat", Double.parseDouble(latitude));
            intent.putExtra("long", Double.parseDouble(longitude));
            startActivity(intent);
        }
        //else

            result = (EditText)findViewById(R.id.result);
            cityCountry = (EditText)findViewById(R.id.cityCountry);
            pb = (ProgressBar) findViewById(R.id.progressBar2);
            pb.setVisibility(View.VISIBLE);

            //call web service
            AsyncTaskService service = new AsyncTaskService();
            service.execute(cityCountry.getText().toString());

    }


    private class AsyncTaskService extends AsyncTask<String, Integer, String> {

        String jSonContent;
        String resultToDisplay;

        @Override
        protected String doInBackground(String... params) {
            postData(params[0]);
            return null;
        }

        protected void onPostExecute(String serviceResult){
            pb.setVisibility(View.GONE);
            result.setText(resultToDisplay);
        }

        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }

        public void postData(String valueIWantToSend) {
            // HTTP Get
            BufferedReader reader = null;
            try {
                URL url = new URL(RESTAPI_URL+valueIWantToSend+UNITS);

                StringBuilder sb = new StringBuilder();
                String line = null;

                reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
                // Read Server Response
                while((line = reader.readLine()) != null)
                {
                    // Append server response in string
                    sb.append(line + "");
                    System.out.println("Response:"+ line);
                }

                // Append Server Response To Content String
                jSonContent = sb.toString();

                parseJson(jSonContent);

            } catch (Exception e ) {
                System.out.println(e.getMessage());
            }
        }


        private void parseJson(String rawJson) {
            JSONObject jsonResponse;

            StringBuffer sb = new StringBuffer();
            try {
                jsonResponse = new JSONObject(rawJson);

                JSONObject coord = jsonResponse.getJSONObject("coord");
                longitude = coord.getString("lon");
                latitude = coord.getString("lat");

                sb.append("Latitude:" + latitude);
                sb.append("\nLongitude:" + longitude);

                JSONObject sys = jsonResponse.getJSONObject("sys");
                String countryCode = sys.getString("country");
                sb.append("\nCountry Code:" + countryCode);

                JSONObject main = jsonResponse.getJSONObject("main");
                String minTemp = main.getString("temp_min");
                String maxTemp = main.getString("temp_max");

                sb.append("\nMin Temp:" + minTemp);
                sb.append("\nMax Temp:" + maxTemp);

                String cityName = jsonResponse.getString("name");
                sb.append("\nCity Name:" + cityName);

                resultToDisplay = sb.toString();

            } catch (Exception e ) {

            }

        }

    }
}

MapsActivity.java

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    double latitude;
    double longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        Intent intent = getIntent();
        latitude = intent.getDoubleExtra("lat", 0);
        longitude = intent.getDoubleExtra("long", 0);

        System.out.println("******Latitude"+latitude);
        System.out.println("******Longitude:"+longitude);

        setUpMapIfNeeded();
        mMap.setMyLocationEnabled(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p/>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p/>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p/>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        //mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));

        LatLng position = new LatLng(latitude, longitude);
        // create marker
        MarkerOptions marker = new MarkerOptions().position(position).title("Hello Maps ");

        // adding marker
        mMap.addMarker(marker);

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 4));
    }
}



WLST script to create JMS resources

This script creates JMS servers, JMS module, JMS subdeployment, one connection factory and one UDQ.

Before you run this script, you need to set environment by running following command.

. $DOMAIN_HOME/bin/setDomainEnv.sh

>>>> java weblogic.WLST jms_queue.py



import sys

from java.util import *
from javax.management import *   
from java.io import FileInputStream


print "@@@ creating JMS resources ..."

propInputStream1 = FileInputStream("jms.properties")
domainProps = util.Properties()
domainProps.load(propInputStream1) 

adminURL='t3://'+domainProps.get('adminServer')+':'+domainProps.get('adminPort')
adminUserName='weblogic'
adminPassword=domainProps.get("adminPassword")
clusterName=domainProps.get('clusterName')
 
try:
    connect(adminUserName, adminPassword, adminURL)
    edit()
    startEdit()

    #build JMS Server1 - target to managed server
    cd('Clusters/'+clusterName)
    managedServers=cmo.getServers()

    i = 1
    for managedServer in managedServers:
        managedServerName=managedServer.getName()    
        cd('/')
        cmo.createJMSServer('JmsServer'+str(i))
        cd('/Deployments/JmsServer'+str(i))
        cmo.setPersistentStore(getMBean('/JDBCStores/JDBCStore_'+str(i)))
        msObjectName='com.bea:Name='+managedServerName+',Type=Server'
        set('Targets', jarray.array([ObjectName(msObjectName)], ObjectName))
        print "@@@ created JMS Server"
        i = i + 1
     
    # Build JMS Module - target preferrable cluster
    cd('/')
    cmo.createJMSSystemResource('JmsModule1')
    cd('/JMSSystemResources/JmsModule1')
    set('Targets',jarray.array([ObjectName('com.bea:Name='+clusterName+',Type=Cluster')], ObjectName))
    print "@@@ creating JMS module ..." 
     
    # Build JMS Connection Factory XA - target to cluster
    cd('/JMSSystemResources/JmsModule1/JMSResource/JmsModule1')
    cmo.createConnectionFactory('ConnFactoryGenericXYZXA')
    cd('/JMSSystemResources/JmsModule1/JMSResource/JmsModule1/ConnectionFactories/ConnFactoryGenericXYZXA')
    cmo.setJNDIName('jms/cf/XYZGenericXA')
    cd('/JMSSystemResources/JmsModule1/JMSResource/JmsModule1/ConnectionFactories/ConnFactoryGenericXYZXA/TransactionParams/ConnFactoryGenericXYZXA')
    #cmo.setAttachJMSXUserId(false)
    cmo.setXAConnectionFactoryEnabled(true)
    cd('/JMSSystemResources/JmsModule1/JMSResource/JmsModule1/ConnectionFactories/ConnFactoryGenericXYZXA')
    cmo.setDefaultTargetingEnabled(true)
    print "@@@ creating JMS connection factory ..."

    # Build JMS Subdeployment - target to all JMS servers
    cd('/JMSSystemResources/JmsModule1')
    cmo.createSubDeployment('JMSSubDeploy')
    cd('/JMSSystemResources/JmsModule1/SubDeployments/JMSSubDeploy')
    print "@@@ creating JMS subdeployment ..."
    
    ######
    list=[]
    cd('/')
    cd('Clusters/'+clusterName)
    managedServers=cmo.getServers()
    
    i = 1
    for managedServer in managedServers:
        managedServerName=managedServer.getName()
        s='com.bea:Name=JmsServer'+str(i)+',Type=JMSServer'
        list.append(ObjectName(str(s)))
        i = i + 1
    
    cd('/JMSSystemResources/JmsModule1/SubDeployments/JMSSubDeploy')
    set('Targets',jarray.array(list, ObjectName))
     
    print "@@@ created JMS subdeployment ..."
    
    #Email queue - XYZ_QUEUE
    cd('/JMSSystemResources/JmsModule1/JMSResource/JmsModule1')
    cmo.createUniformDistributedQueue('XYZ_QUEUE')
    cd('/JMSSystemResources/JmsModule1/JMSResource/JmsModule1/UniformDistributedQueues/XYZ_QUEUE')
    cmo.setJNDIName('jms/xyzQueue')
    cmo.setLoadBalancingPolicy('Round-Robin')
    cmo.setSubDeploymentName('JMSSubDeploy')
     
    print "@@@ completed creating JMS resources ..."
    save()
    activate(200000, block='true')
    
except Exception, e:
       dumpStack() 
       print "@@@ exception occured"
       print e
       cancelEdit('y')


Contents of jms.properties


#jms.properties
adminServer=abc.xyz.com
adminPort=7101
adminPassword=xyz
clusterName=xyz_dev_cluster
dataSourceName=JMSDataSource


WLST Script to create persistent stores

This script creates persistent stores targeted to a cluster. Input properties are specified in jms.properties

Before this script is run, set the environment using following command.

. $DOMAIN_HOME/bin/setDomainEnv.sh

>>>java weblogic.WLST createDBStore.py

import sys

from java.util import *
from javax.management import *   
from java.io import FileInputStream


print "@@@ creating JDBC persistence stores ..."

propInputStream1 = FileInputStream("jms.properties")
domainProps = util.Properties()
domainProps.load(propInputStream1) 

adminURL='t3://'+domainProps.get('adminServer')+':'+domainProps.get('adminPort')
adminUserName='weblogic'
adminPassword=domainProps.get("adminPassword")
clusterName=domainProps.get('clusterName')
dataSourceName=domainProps.get("dataSourceName")

try:

      connect(adminUserName, adminPassword, adminURL)
      edit()
      startEdit()

###################Create JDBC Stores for cluster####################

      cd('Clusters/'+clusterName)
      managedServers=cmo.getServers()

      i = 1
      for managedServer in managedServers:
    managedServerName=managedServer.getName()
    cd('/')
    cmo.createJDBCStore('JDBCStore_'+str(i))
    cd('/JDBCStores/JDBCStore_'+str(i))
    cmo.setDataSource(getMBean('/SystemResources/'+dataSourceName))
    cmo.setPrefixName('JMS'+str(i))
    msObjectName='com.bea:Name='+managedServerName+',Type=Server'
    set('Targets',jarray.array([ObjectName(msObjectName)], ObjectName))
    print "@@@ created JDBC persistence store"
    i = i + 1

      print "@@@ script completed"
      save()
      activate()

except:
       print "@@@ exception in wlst script"
       dumpStack()