Wednesday, November 30, 2011

Resetting Weblogic Server Admin Password

Resetting Weblogic Server Admin Password:

Steps to reset the admin password of weblogic server.

  • cd <DOMAIN_HOME>/security
  •  Rename DefaultAuthenticatorInit.ldift file to DefaultAuthenticatorInit.ldift_BKP
  • Set the Environment - <DOMAIN_HOME>/bin/setDomainEnv.cmd
  • java -cp <WLS_HOME>;/server/lib/weblogic.jar:$CLASSPATH weblogic.security.utils.AdminAccount NewAdminUser NewAdminPassword . (Note the . at the end of the command)
  Make sure you are running the above command is executed from    DOMAIN_HOME>/security,   if you are executing the command from other location copy the   DefaultAuthenticatorInit.ldift file created in the current location to <DOMAIN_HOME>/security
e.g java -cp C:\Oracle\MiddlewareSOA\wlserver_12.1\server\lib\weblogic.jar;%CLASSPATH% weblogic.security.utils.AdminAccount albin albin123  
  • Move data directory under $DOMAIN_HOME/servers/<serverName>/datato another directory like data.bak
  •  Edit user name and password in the following file - <DOMAIN_HOME>/servers/<Server Name>/security/boot.properties
  • Restart the admin server


Adding main class and jar files to Class-Path in manifest through ANT script

Adding main class and jar files to Class-Path in manifest through ANT script

The below ANT script will help us to add main class and jar files to Class-Path in manifest of the JAR file.

<?xml version="1.0" encoding="iso-8859-1"?>
<project name="jar with libs" default="compile and build" basedir=".">

<target name="compile and build">
<delete dir="bin" />
<mkdir dir="bin"/>

<!-- copy the JARs that should be added to MANIFEST class-path to "bin" directory -->
<copy todir="bin">
<fileset dir="." includes="**/lib/*.jar" />
</copy>

<!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
<jar destfile="SampleJar.jar" basedir="bin" duplicate="preserve">
<manifest>
<!-- Who is building this jar? -->
<attribute name="Built-By" value="Albin I" />
<!-- Information about the program itself -->
<attribute name="Implementation-Vendor" value="Company" />
<attribute name="Implementation-Title" value="Albin" />
<attribute name="Implementation-Version" value="1.0.0beta1" />
<attribute name="Class-Path" value="lib/bpm-services.jar lib/ldapjclnt11.jar lib/ojdbc14.jar lib/xmlparserv2.jar"/>

<!-- this tells which class should run when executing your jar -->
<attribute name="Main-class" value="com.import.ImportUtility" />
</manifest>
</jar>
</target>

</project>


JAVA utility class to encrypt/decrypt data using password based encryption(PBEWithMD5AndDES)

JAVA utility class to encrypt/decrypt data using password based encryption(PBEWithMD5AndDES)

The below code snippet will help us to encrypt/decrypt data using password based encryption(PBEWithMD5AndDES).

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEParameterSpec;


public class RdsCryptoLibrary {

private static final String PBE_KEY = "gZWKbHnijPAxrH+Sxw4fqp0FoVj6Ia2zA==qlPsn33wsz"
+ "ExumaDburVAw==PiU+p0wzGH2IbpQrpR6C7g==ld1"
+ "XwIUXYbSIBlPjTUYotg==CYm5rNsRA5KrGdPTvsrWuQ==";

private static final String PBE_ALGORITHM = "PBEWithMD5AndDES";

private static final String PBE_PROVIDER = "PBEWithMD5AndDES/CBC/PKCS5Padding";

private Cipher encryptCipher;

private Cipher decryptCipher;

private sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();

private sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();

public RdsCryptoLibrary( ) throws SecurityException {
//java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE());
java.security.Security.addProvider(new com.ibm.crypto.provider.IBMJCE());
char[] pass = PBE_KEY.toCharArray();
byte[] salt = { (byte) 0xa3 , (byte) 0x21 , (byte) 0x24 , (byte) 0x2c ,
(byte) 0xf2 , (byte) 0xd2 , (byte) 0x3e , (byte) 0x19 };
int iterations = 3;
init(pass, salt, iterations);
}

public void init(char[] pass, byte[] salt, int iterations)
throws SecurityException {
try {
PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt,
20);

SecretKeyFactory kf = SecretKeyFactory.getInstance(PBE_ALGORITHM);
SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(
pass));

encryptCipher = Cipher.getInstance(PBE_PROVIDER);
encryptCipher.init(Cipher.ENCRYPT_MODE, k, ps);

decryptCipher = Cipher.getInstance(PBE_PROVIDER);
decryptCipher.init(Cipher.DECRYPT_MODE, k, ps);
}
catch (Exception e) {
throw new SecurityException("Could not initialize CryptoLibrary: "
+ e.getMessage());
}
}

public synchronized String encrypt(String str) throws SecurityException {
try {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = encryptCipher.doFinal(utf8);
return encoder.encode(enc);
}
catch (Exception e) {
throw new SecurityException("Could not encrypt: " + e.getMessage());
}
}

public synchronized String decrypt(String str) throws SecurityException {
try {
byte[] dec = decoder.decodeBuffer(str);
byte[] utf8 = decryptCipher.doFinal(dec);
return new String(utf8, "UTF8");
}
catch (Exception e) {
throw new SecurityException("Could not decrypt: " + e.getMessage());
}
}
}


JAVA client to search and publish documents to Orace Service Registery

JAVA client to search and publish documents to Orace Service Registery

The below JAVA code snippet will help us to perform search and publish operations on OSR.

import javax.xml.registry.*;
import javax.xml.registry.infomodel.*;
import java.net.*;
import java.security.*;
import java.util.*;

public class OSRClient {
Connection connection = null;

public OSRClient() {
}

public static void main(String[] args) {


OSRClient jq = new OSRClient();

jq.makeConnection("http://<<OSR Host>>:<<OSR Port>>/registry/uddi/inquiry", "http://<<OSR Host>>:<<OSR Port>>/registry/uddi/publishing");

jq.executePublish("admin","Password123");

//jq.executeQuery("admin","Password123");
}

/**
* Establishes a connection to a registry.
*
* @param queryUrl the URnL of the query registry
* @param publishUrl the URL of the publish registry
*/
public void makeConnection(
String queryUrl,
String publishUrl) {
/*
* Specify proxy information in case you
* are going beyond your firewall.
*/


/*
* Define connection configuration properties.
* For simple queries, you need the query URL.
*/
Properties props = new Properties();
props.setProperty("javax.xml.registry.queryManagerURL", queryUrl);
props.setProperty("javax.xml.registry.lifeCycleManagerURL", publishUrl);

try {
// Create the connection, passing it the
// configuration properties
ConnectionFactory factory = ConnectionFactory.newInstance();
factory.setProperties(props);
connection = factory.createConnection();
System.out.println("Created connection to registry");
} catch (Exception e) {
e.printStackTrace();

if (connection != null) {
try {
connection.close();
} catch (JAXRException je) {
}
}
}
}

/**
* Searches for objects owned by the user and
* displays data about them.
*
* @param username the username for the registry
* @param password the password for the registry
*/
public void executeQuery(
String username,
String password) {
RegistryService rs = null;
BusinessQueryManager bqm = null;

try {
// Get registry service and query manager
rs = connection.getRegistryService();
bqm = rs.getBusinessQueryManager();
System.out.println("Got registry service and " + "query manager");

// Get authorization from the registry
PasswordAuthentication passwdAuth = new PasswordAuthentication(
username,
password.toCharArray());

HashSet<PasswordAuthentication> creds = new HashSet<PasswordAuthentication>();
creds.add(passwdAuth);
connection.setCredentials(creds);
System.out.println("Established security credentials");

// Get all objects owned by me
BulkResponse response = bqm.getRegistryObjects();

Collection objects = response.getCollection();

// Display information on the objects found
if (objects.isEmpty()) {
System.out.println("No objects found");
} else {
for (Object o : objects) {
RegistryObject obj = (RegistryObject) o;
System.out.println("Object key id: " + getKey(obj));
System.out.println("Object name is: " + getName(obj));
System.out.println(
"Object description is: " + getDescription(obj));

// Print spacer between objects
System.out.println(" --- ");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// At end, close connection to registry
if (connection != null) {
try {
connection.close();
} catch (JAXRException je) {
}
}
}
}

/**
* Returns the name value for a registry object.
*
* @param ro a RegistryObject
* @return the String value
*/
private String getName(RegistryObject ro) throws JAXRException {
try {
return ro.getName()
.getValue();
} catch (NullPointerException npe) {
return "No Name";
}
}

/**
* Returns the description value for a registry object.
*
* @param ro a RegistryObject
* @return the String value
*/
private String getDescription(RegistryObject ro) throws JAXRException {
try {
return ro.getDescription()
.getValue();
} catch (NullPointerException npe) {
return "No Description";
}
}

/**
* Returns the key id value for a registry object.
*
* @param ro a RegistryObject
* @return the String value
*/
private String getKey(RegistryObject ro) throws JAXRException {
try {
return ro.getKey()
.getId();
} catch (NullPointerException npe) {
return "No Key";
}
}

public void executePublish(String username, String password) {
RegistryService rs;
BusinessLifeCycleManager blcm;
BusinessQueryManager bqm;

try {
rs = connection.getRegistryService();
blcm = rs.getBusinessLifeCycleManager();
bqm = rs.getBusinessQueryManager();
System.out.println("Got registry service,query manager, and life cycle manager");

// Get authorization from the registry
PasswordAuthentication passwdAuth = new
PasswordAuthentication(username, password.toCharArray());
Set credits = new HashSet();
credits.add(passwdAuth);
connection.setCredentials(credits);
System.out.println("Established security credentials");

// Create organization name and description
// Replace this information with your organization information
Organization org = blcm.createOrganization("javacourses.com");
InternationalString s =
blcm.createInternationalString("Java training and consulting services");
org.setDescription(s);

// Create primary contact, set name
User primaryContact = blcm.createUser();
PersonName pName = blcm.createPersonName("Qusay H. Mahmoud");
primaryContact.setPersonName(pName);

// Set primary contact phone number
TelephoneNumber phoneNum = blcm.createTelephoneNumber();
phoneNum.setNumber("(604) 285-2000");
Collection phoneNums = new ArrayList();
phoneNums.add(phoneNum);
primaryContact.setTelephoneNumbers(phoneNums);

// Set primary contact email address
EmailAddress emailAddress =
blcm.createEmailAddress("[email protected]");
Collection emailAddresses = new ArrayList();
emailAddresses.add(emailAddress);
primaryContact.setEmailAddresses(emailAddresses);

// Set primary contact for organization
org.setPrimaryContact(primaryContact);

// Set classification scheme to NAICS
ClassificationScheme cScheme =
bqm.findClassificationSchemeByName(null,"ntis-gov:naics:1997");

// Create and add classification
Classification classification = (Classification)
blcm.createClassification(cScheme,
"Computer Training", "61142");
Collection classifications = new ArrayList();
classifications.add(classification);
org.addClassifications(classifications);

// Create services and service
Collection services = new ArrayList();
Service service =
blcm.createService("Buy a Java Course");
InternationalString is =
blcm.createInternationalString("This service allows you to register for a Java course and download its manuals.");
service.setDescription(is);

// Create service bindings
Collection serviceBindings = new ArrayList();
ServiceBinding binding = blcm.createServiceBinding();
is = blcm.createInternationalString("Service Binding "
+ "Access this services using the given URL.");
binding.setDescription(is);
binding.setAccessURI("http://javacourses.com/register");
serviceBindings.add(binding);

// Add service bindings to service
service.addServiceBindings(serviceBindings);

// Add service to services, then add services to organization
services.add(service);
org.addServices(services);

// Add organization and submit to registry
// Retrieve key if successful
Collection orgs = new ArrayList();
orgs.add(org);
BulkResponse response = blcm.saveOrganizations(orgs);
Collection exceptions = response.getExceptions();
if (exceptions == null) {
System.out.println("Organization saved");
Collection keys = response.getCollection();
Iterator keyIter = keys.iterator();
if (keyIter.hasNext()) {
javax.xml.registry.infomodel.Key orgKey =
(javax.xml.registry.infomodel.Key) keyIter.next();
String id = orgKey.getId();
System.out.println("Organization key is " + id);
org.setKey(orgKey);
}
} else {
Iterator excIter = exceptions.iterator();
Exception exception = null;
while (excIter.hasNext()) {
exception = (Exception) excIter.next();
System.err.println("Exception on save: " +
exception.toString());
}
}
} catch (Exception e) {
e.printStackTrace();
if (connection != null) {
try {
connection.close();
} catch (JAXRException je) {
System.err.println("Connection close failed");
}
}
}
}

}


Oracle BAM (Oracle Business Activity Monitoring) Features


Oracle BAM (Oracle Business Activity Monitoring) Features:

Oracle Business Activity Monitoring (Oracle BAM) is a complete solution for building interactive, real-time dashboards and proactive alerts for monitoring business processes and services.
Oracle BAM gives business executives and operation managers the information they need to make better business decisions and take corrective action if the business environment changes.
  • Able to monitor the BPEL process and other processes by integrating the processes with BAM.
  • Able to create live report for the process integrated
  • Able to alert the users based on the rules defined
  • We can able to call BPEL and other Webservices from BAM.

Oracle BAM is comprised of six components:

  • Data Integration
  • Data Caching
  • Analytics
  • Monitoring
  • Alerting
  • Reporting

Oracle BAM Event Engine:

  • Oracle BAM Event Engine monitors complex changing conditions in the data and the system in real-time and based upon user-defined rules.
  • Takes a variety of actions in response to those changes.
  • Notifying the appropriate user with an alert and/or report.

Oracle BAM Active Report Engine:

  • Oracle BAM Active Report Engine assembles and formats the data for a live report to be displayed in Oracle BAM’s thin and rich clients
  • Reports are available in a variety and combination of view types including charts

Oracle BAM –User Interfaces:

Oracle BAM Active Viewer
thin user interface for the business user
Oracle BAM Active Studio
thin user interface for the power user
the power user can create and edit reports
Oracle BAM Architect
thin user interface for the data designer focused on creating data objects in the Oracle BAM Active Data Cache
Oracle BAM Administrator
thin user interface for the system administrator who is responsible for user management and overall server management

Security Filter:

Security filters to data objects so that only specific users can view specific rows in the data object

Permissions:

Permissions for users and groups on data objects.


Installing shared printer remotely using VB Script

Installing shared printer remotely using VB Script

The below HTML code snippet can be used to install the shared printer remotely .

<html>
<title> Add Printer </title>
<head>
<script language="vbscript">
function AddPrinter()
Set WshNetwork = CreateObject("WScript.Network")
WshNetwork.AddWindowsPrinterConnection "<<Printer Path>>"
WshNetwork.SetDefaultPrinter "<<Printer Path>>"
Document.Write "Printer Installed Successfully , Please Close the Web Page"
end function
</script>
</head>
<body Onload="AddPrinter()">
Installing Selected Printer
</body>
</html>


Removing empty nodes from XML using xslt


Removing empty nodes from XML using xslt

The below XSLT can be used to remove the empty nodes from the XML file.

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output omit-xml-declaration="yes" indent="yes" />
<xsl:template match="node()|SDLT">
<xsl:if test="count(descendant::text()[string-length(normalize-space(.))>0] | @*[string-length(.)>0])">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:if>
</xsl:template>
<xsl:template match="@*">
<xsl:copy />
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)" />
</xsl:template>
</xsl:stylesheet>


Tuesday, November 29, 2011

Java client to post/consume message from Weblogic JMS Queue

Java client to post/consume message from Weblogic JMS Queue

Sample Java client to post the message and consume the message from the Weblogic JMS queue.

package com.jms.test.wl;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.jms.TextMessage;
import javax.naming.NamingException;

public class TestJMSQueue {

public static void main(String[] args) {
TestJMSQueue testApp = new TestJMSQueue();
testApp.post2Queue();
testApp.receiveFromQueue();
}

public void post2Queue() {
long l1 = System.currentTimeMillis();
javax.naming.Context jndiContext = null;
javax.jms.QueueConnectionFactory queueConnectionFactory = null;
javax.jms.QueueConnection queueConnection = null;
javax.jms.QueueSession queueSession = null;
javax.jms.Queue queue = null;
javax.jms.QueueSender queueSender = null;

javax.jms.TextMessage message = null;

java.util.Hashtable<String, String> env = new java.util.Hashtable<String, String>();
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
env.put(javax.naming.Context.PROVIDER_URL, "t3://localhost:7001");
env.put("weblogic.jndi.createIntermediateContexts", "true");

try {
jndiContext = new javax.naming.InitialContext(env);
} catch (NamingException e) {
System.out.println("Unable to create JNDI context "+e.toString());
e.printStackTrace();
}

try {
//queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("javax.jms.QueueConnectionFactory");
queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("jms/CustomerApplicationJMSConnectionFactory");
queue = (Queue) jndiContext.lookup("jms/CustomerApplicationRequestQueue");
} catch (NamingException e) {
System.out.println("JNDI lookup failed: " + e.toString());
e.printStackTrace();
}

try {
queueConnection = queueConnectionFactory.createQueueConnection();
queueSession = queueConnection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
queueSender = queueSession.createSender(queue);
long l2 = System.currentTimeMillis();
//for(int i=0; i<1000; i++) {
message = queueSession.createTextMessage("Hello There 1");
queueSender.send(message);
//}
long l3 = System.currentTimeMillis();

System.out.println("Time Taken for setup and due diligence: "+(l2 - l1));
System.out.println("Time taken to send 1 million messages: "+(l3 -l2));
System.out.println("Overall Time taken: "+(l3 - l1));

} catch (JMSException e) {
System.out.println("Exception occurred: " + e.toString());
e.printStackTrace();
} finally {
if(queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}

}



Common JAVA framework to invoke the Oracle SOA Suite Composite services

Common JAVA framework to invoke the Oracle SOA Suite Composite services:

There are different approaches to invoke the SOA Composites through java like DirectConnection, ADFBinding etc. But in both the approaches we have to add the additional configurations in the Composite.xml file.
Instead of using this approach, we can use the Apache Axis framework to invoke all the composites as a webservice.
We have implemented a Service Invocation Framework to invoke the composites through JAVA.
We have to set the endpoint and the operation name correspondingly to invoke the service.
I thought of sharing the framework as this may help somebody looking for same kind of framework.
Sample Client to Invoke the service(download the framework attached):
String endpoint="http://soahost:soaport/soa-infra/services/default/HelloWorld/helloworld_client_ep";

String xmlInput="<ns1:process xmlns:ns1=\"http://xmlns.oracle.com/EAIRules/HelloWorld/HelloWorld\">\n" +
" <ns1:input>Albin Issac</ns1:input>\n" +
" </ns1:process>";

InputObject inputParamObj = new InputObject();
System.out.println("End pint URL " +endpoint );
inputParamObj.setSServiceEndPoint(endpoint);
inputParamObj.setSOprName("sayHello");
inputParamObj.setInputPayload(xmlInput);
// Getting service invoker class to invoke service.
ServiceInvoker serviceInvoker =ServiceInvoker.getInstance();
try {
serviceInvoker.invokeService(inputParamObj, null);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Process Successfully Invoked!<br>");

DOWNLOAD WebServiceInvocationFramework.zip


Monday, November 28, 2011

Oracle SOA Suite – Local optimization for webservice calls

Oracle SOA Suite – Local optimization for webservice calls:

The property “oracle.webservices.local.optimization” instructs Composite to make the webservice calls via SOAP stack or not. This property will work both in Oracle SOA Suite 11g and Oracle SOA Suite 12c.
By default the value for the property “oracle.webservices.local.optimization” is true. If the value is true and composite invokes any other webservice on the same server/domain, it avoids soap overhead and calls natively.

There may be a situation that you want to invoke the services via Soap Stack and changing the value of “oracle.webservices.local.optimization” property to false will help us to do that.
We can set this property in Composite.xml for a specific partner link only that partner link invocation always happens via soap stack.
Open the Composite.xml in JDev and add the property - oracle.webservices.local.optimization to the corresponding partnerlink binding.



When the local optimization is true, the policies attached to the partnerlinks are also bypassed


Friday, November 25, 2011

Some of the utilities used for the Oracle SOA Suite 10g to 11g Migration.

Some of the utilities used for the Oracle SOA Suite 10g to 11g Migration.

I thought of sharing the pre and post migration utilities, we had used in our project.
Hope this may help somebody looking for the migration utilities.

Pre-Migration:

The below java program helps us to remove the space in the preference name(bpel file and bpel.xml) used in 10g code base before starting the migration, the migration will fails if there is any empty spaces in the preference name.

MigrationTask.java
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class MigrationTask {
public MigrationTask() { }
static FilenameFilter filterPreferences = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.equals("bpel.xml");
}
};
static FilenameFilter bpelProcess = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches(".*.bpel");
}
};

//Remove the empty spaces in the preference name in bpel.xml and
//chanage corresponding preference name in bpel file
public static void updatePreferences(String baseDir) throws Exception {
File[] fileList =
listFilesAsArray(new File(baseDir), filterPreferences, true);
for (int i = 0; i < fileList.length; i++) {
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
File f = fileList[i];
String fileName = f.getAbsolutePath();
// System.out.println(fileName);
Document document =
docBuilderFactory.newDocumentBuilder().parse(fileName);
String bpelFolder =
fileName.substring(0, fileName.lastIndexOf("\\"));
NodeList nodeList =
executeXPath(document, "//preferences/property");
File[] fileListBpel =
listFilesAsArray(new File(bpelFolder), bpelProcess, false);
for (int j = 0; j < nodeList.getLength(); j++) {
Node node =
nodeList.item(j).getAttributes().getNamedItem("name");
String preferenceValue = node.getNodeValue();
if (isSpaceAvilable(preferenceValue) &&
fileListBpel.length > 0) {
System.out.println(fileListBpel[0].getName());
String newpreferenceValue =
preferenceValue.replaceAll(" ", "");
node.setNodeValue(newpreferenceValue);
replaceStringInFile(fileListBpel[0], preferenceValue,
newpreferenceValue, "Pre");
}
}
Source source = new DOMSource(document);
File file = new File(fileList[i].getAbsolutePath());
Result result = new StreamResult(file);
Transformer xformer =
TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.transform(source, result);
}
}
public static NodeList executeXPath(Document doc, String xpathStr) {
XPath xpath = null;
NodeList value = null;
try {
XPathFactory xpathFactory = XPathFactory.newInstance();
xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile(xpathStr);
value = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
return value;
} catch (XPathExpressionException e) {
System.err.println("Exception while processing xpath ::" +
e.getMessage());
} catch (Exception e) {
System.err.println("Exception while processing xpath ::" +
e.getMessage());
}
return null;
}
public static boolean isSpaceAvilable(String preference) {
return preference.contains(" ");
}
public static void main(String[] args) throws Exception {
if (args[1].equals("updatePreferences")) {
updatePreferences(args[0]);
}
}
public static File[] listFilesAsArray(File directory,
FilenameFilter filter,
boolean recurse) throws Exception {
Collection<File> files = listFiles(directory, filter, recurse);
File[] arr = new File[files.size()];
return files.toArray(arr);
}
public static Collection<File> listFiles(File directory,
FilenameFilter filter,
boolean recurse) throws Exception {
Vector<File> files = new Vector<File>();
File[] entries = directory.listFiles();
for (File entry : entries) {
if (filter == null || filter.accept(directory, entry.getName())) {
files.add(entry);
}
if (recurse && entry.isDirectory()) {
files.addAll(listFiles(entry, filter, recurse));
}
}
return files;
}
public static void replaceStringInFile(File file, String searchText,
String replaceText,
String replacementtype) {
try {
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String fileName = file.getAbsolutePath();
String strLine;
StringBuffer sb = new StringBuffer();
while ((strLine = br.readLine()) != null) {
// if(strLine.contains(searchText)){
Pattern p = Pattern.compile(searchText);
Matcher m = p.matcher(strLine);
if (m.find()) {
strLine = strLine.replace(searchText, replaceText);
}
sb.append(strLine);
sb.append("\n");
}
in.close();
FileOutputStream fos = new FileOutputStream(fileName);
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
String outText = sb.toString();
out.write(outText);
out.close();
} catch (Exception e) { //Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

java MigrationTask <10g codebase location > updatePreferences