Wednesday, June 16, 2010
Mercurial behind a proxy server
Mercurial (hg) stores its config information in an ini file. Type
hg help config
to see the details.
Based on this its possible to have a config file per repo with differetn setting (e.g. email addresses).
The format of the config file is explained at
http://www.selenic.com/mercurial/hgrc.5.html
So to set a proxy server I used the follwoing ini file
[ui]
username = My Name <my.name@myemail.com>
verbose = True
[http_proxy]
host=http://<proxyhost>:<proxyport>
no=192.168.*
user=<optionalusername>
passwd=<optionalpassword>
Wednesday, May 26, 2010
ScreenScraping with Groovy
#!/usr/bin/env groovy
// Depends on tagsoup library:
// http://ccil.org/~cowan/XML/tagsoup/
def slurper = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser())
def url = new URL("http://fcd.mcw.edu/?module=faculty&func=view&id=1674")
url.withReader { reader ->
html = slurper.parse(reader)
//we should now have a parsed file
def value = html.body.div.div.div[2].ul.li
value.list().each { f ->
println "\nPub : " << f.toString()[0..80] << "..."
}
}
This is super simple and works really well.
My problem was I needed to also post data to the websites (e.g. to login, enter data etc).
For that you need to incorporate HttpClient. For Groovy there is a HttpBuilder library that wraps HttpClient libraries with Groovy syntax. It also allows you to use GPath expressions to quickly identify locations in the response page.
I needed to go through a proxy and this proved the first hurdle. After much messing this code worked.
(Note I added an if statement to get the current IP address of the machine, so this script would work in work (where we use a proxy), and at home (where I don't have a proxy)
#N.B. Also that httpBuilder can be got using grapes. However I had some problems getting this to work from behind a proxy. Check out this page for some tips
http://groovy.codehaus.org/modules/http-builder/download.html
Also worth of note is that when using grab (grapes) all files are pulled down to $HOME/.groovy/grapes
So you could also manually download the latest version of the HttpBuilder and manualyl install it
Eventually this worked for me (this was after grape resolve failed.. Not sure why.. Obviously it worked once it was installed)
>grape install org.codehaus.groovy.modules.http-builder http-builder 0.6
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.2' ) import groovyx.net.http.* import static groovyx.net.http.ContentType.* import static groovyx.net.http.Method.*
def http = new HTTPBuilder( 'http://www.twitter.com' )
def ip=java.net.InetAddress.getLocalHost().getHostAddress()
println "IP = $ip" if(ip.startsWith("10.5.") || ip.startsWith("10.2.")){
def proxy = "10.5.0.250" def proxyPort = 80 //Required for HttpClient
http.setProxy(proxy, proxyPort, "http") //http.setProxy(proxy, proxyPort, "https")
http.auth.basic( proxy, proxyPort, System.properties["user.name"], System.getenv("user.password") )
}
http.get( path: '/', query:[id:'httpbuilder'] ) { resp, xml ->
println resp.status
println xml
xml.status.each { // iterate over each XML 'status' element in the response:
println it.created_at.text()
println " " + it.text.text()
}
}
- HTML response data will also be parsed automatically, by using NekoHTML which corrects the XML stream before it is passed to the XmlSlurper. The resulting behavior is that you can parse HTML as if it was well-formed XML.
Monday, March 22, 2010
Web effects
Tuesday, February 09, 2010
Strange error from Sql Server
Friday, January 15, 2010
Weblogic slow to start (and slow cryptography) on linux (unix),
Turns out Weblogic uses random number generator during start up. Because of the bug in java it reads ‘randomness’ from /dev/random. /dev/random is very good random numbers generators but it is extremely slow. It takes sometimes 10 minutes or more to generate one number. /dev/urandom is not that good, but it is instant.
Java somehow maps /dev/urandom file to /dev/random. That’s why default settings in $JAVA_HOME/jre/lib/security/java.security are useless.
Possible solutions:
1) Add “-Djava.security.egd=file:/dev/./urandom” (/dev/urandom does not work) to java parameters.
Worse but working solution is:
2) mv /dev/random /dev/random.ORIG ; ln /dev/urandom /dev/random
3) Best solution is to change $JAVA_HOME/jre/lib/security/java.security
Replace securerandom.source with
securerandom.source=file:/dev/./urandom
This problem does not happen under windows because it uses different implementation of /dev/random.
It takes seconds to start weblogic server now.
Wednesday, January 13, 2010
Using AES from Java
Monday, December 14, 2009
Keytool keystore Cannot store non-PrivateKeys
Tuesday, November 10, 2009
Xquery to mask CreditCard number
Detect Java method name from code
Tuesday, October 20, 2009
Mvn Mojo architype type
Friday, September 04, 2009
USB drive won't go
Wednesday, July 08, 2009
Grails cheatsheet
- GORM Non numeric ID field
- Dependency Injection.
Monday, June 15, 2009
Shutdown hook in Groovy... Inner Classes in Groovy
http://groovy.codehaus.org/Groovy+Alternatives+to+Inner+Classes
I had to tweak the script slightly to get it to work for the shutdown hook (see below).
To implement the shutdown hook in Java a Thread instance is passed to the addShutdownHook() method of the Runtime instance.
In Java we could create an Inner class that extends Thread, or that implements Runnable.
In Groovy we must create a Map. The Map contains a list of key/ values. These correspond to method names (key), and method implementations (closure). For this case the closure will represent the Thread that we pass to the Runtime.addShutdownHook() method. Therefore we are implmenting the run() method, so the key in the map must be run().
The ProxyGenerator is then used to dynamically add the interface to the close. Finally since Runtime.addShutdownHook() expects a Thread instance (not simply a class that implements Runnable) ,we must add the Thread.class to the call to ProxyGenerator.instantiateAggregate().
def shutdownClosureMap = [run: {
outputFile.close();
println "Shutting down";
}
]
def interfaces = [Runnable]
def shutdownListener = ProxyGenerator.instantiateAggregate(shutdownClosureMap, interfaces, Thread.class)
Runtime.getRuntime().addShutdownHook((Thread)shutdownListener);
Friday, June 12, 2009
Groovy GString/ STring
GStrings and Strings
Be careful with Groovy Strings and Sql.
Make sure you know the rules of when Strings become GStrings, and therefore can support dynamic variable replacements.
GString docs can be found
http://docs.codehaus.org/display/GROOVY/Strings+and+GString
These rules are listed here: (Note this doc is aproposal for changnig GString)
http://docs.codehaus.org/display/GroovyJSR/Groovy+String+Handling
For example in the code below, if you simply use "def" to declare your variable, you will not see explicitly which types get converted to GStrings and which get converted to plain Strings.
By been explicit in your definitions however you can see that sql6 will not cast by default to a GString. This is becausei t is a multiline java.lang.String (see rules in link above). You will get this exception.
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object "..." with class 'java.lang.String' to class 'groovy.lang.GString'
To fix it.
Date startDate = new Date() -1;
Date endDate = new Date();
def Format = "yyyy-MM-dd"
def OFormat = "YYYY-MM-DD"
String startString = startDate.format(Format);
String endString = endDate.format(Format);
println "Running between $startString and $endString";
def sql = []
def sql1 ="""
select * from prov_auditing_master m where EVENTTIMECOMPLETED > to_date($startString,$OFormat) and EVENTTIMECOMPLETED < sql2 =""> to_date($startString,$OFormat) and EVENTTIMECOMPLETED < sql3 =""> to_date($startString,$OFormat)"+
" and EVENTTIMECOMPLETED < sql4 =""> to_date($startString,$OFormat) and EVENTTIMECOMPLETED < sql5 =" "> to_date($startString,$OFormat) and EVENTTIMECOMPLETED < sql6 = ""> to_date($startString,$OFormat)"+
" and EVENTTIMECOMPLETED < db =" int" i="1">
println i+": $sq"
i++
}
To fix
GString sql7 = "$sql6" ;
sql <<>
Tuesday, May 05, 2009
DB/ Database notes (sql tips)
JDBC Format
Limit Rows
// mysqlselect col from tbl limit 20;
//Sybase / SqlServer
select top 10 * from people
//AlsoSET ROWCOUNT 10 // use SET ROWCOUNT 0 to turn off // Oracle
select col from tbl where rownum <=20;
select col1,col2 from (select rank() over (order by col1) r , col1,col2 from TABLE) where r<11 For bottom 10 rows use select col1,col2 from (select rank() over (order by col1 DESC) r , col1,col2 from TABLE) where r<11
Select unique
//Sybase / SqlServerselect distinct col from table
Oracle
MySql
Outer Join
// Oracle left outer Joinselect * from Customer, Order where Order.customerId (+) = Customer.id
//right join
select * from Customer, Order where Order.customerId = Customer.id (+)
Backup
Mysql
>mysqldump --host vc2c09mmk0326.fmr.com --port=3306 -u datasift2 -p
- This will create a sql with all the tables. Note the --set-gtid-purged=OFF is required on newer versions of the client. If you are running on vc2c09mmk0326 it is probably not required.
- Note the sql will be over 100MB in size
Oracle drop all tables
BEGIN
FOR cur_rec IN (SELECT object_name, object_type
FROM user_objects
WHERE object_type IN
('TABLE',
'VIEW',
'PACKAGE',
'PROCEDURE',
'FUNCTION',
'SEQUENCE'
))
LOOP
BEGIN
IF cur_rec.object_type = 'TABLE'
THEN
EXECUTE IMMEDIATE 'DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '" CASCADE CONSTRAINTS';
ELSE
EXECUTE IMMEDIATE 'DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '"';
END IF;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ( 'FAILED: DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '"'
);
END;
END LOOP;
END;
/
// HSQL
from Customer left join Order where Order.customerId = Customer.id
Could only get this working by explicitly linking the join in the hbm file, and marking it as optional e.g.
Need some more testing to see if this can be done without updating the hbm file
<class name="AdjustmentCode" table="adjustment_code">
<id name="id" column="adjustment_code" type="string">
<generator class="native">
<property name="description" column="description" type="string">
<property name="adjustmentCode" column="adjustment_code" type="string" insert="false" update="false">
<join table="adjustment_message">optional="true">
<key column="adjustment_code">
</join>
<class>
Insert if row not Exists
// MySql
if not exists (select * from url where url = ...)
insert into url...
//Oracle (where not exists)
insert into <table> (<row1>, <row2>)
select <value1>, <value2> from dual
where not exists (
select * from <table> where <col1> = <value1>)
//SQL Server
if not exists (select * from url where url = ...)
insert into url...
Date Operations
GetDate
//MySql
DATE() see (http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html)
//Oracle
SYSDATE
// Sql Server
getDate()
To Date
//Oracle
to_date('2009-01-01','YYYY-MM-DD')
to_date('2009-05-19 18:32','YYYY-MM-DD HH24:MI')
http://www.dba-oracle.com/f_to_date.htm
Detecting Duplicates (group by criteria)
Say you want to detect duplicates (instances of more than one value) in a column. This is how to do it
select dupCol, count(dupCol) from table group by dupCol having count(dupCol)>1
Listing Constrainsts
Oracle
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'myTable';
Wednesday, April 15, 2009
Online XPath Tester
Online XPath Tester
The following articles were helful in getting it running
Javascript Xpath tutorial
Friday, April 10, 2009
Weblogic Jms error.. "Peer Gone"
This error had been causing me grief for a long time.
The problem was fixed by updating my etc hosts file on the client machine... (/windows/system32/drivers/etc/hosts on windows).
Some of our weblogic servers display the server name including domain name e.g. server.domain.com and some only display the server name (e.g. servername). By adding an entry for the target weblogic server in the etc/hosts the problem was fixed.
e.g.
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
127.0.0.1 localhost
192.168.1.10 servername servername.domain.com
Bea Articles on Oracle
Problem of course is that a lot of good articles are referenced on the web to their old original Bea urls.
This page lists where the equivilent sections exist on the oracle site
Overview of migration -> http://wiki.oracle.com/page/Dev2Dev+%2F+Arch2Arch+Status+and+Migration+Update?t=anon
Dev2dev and arch2arch -> http://www.oracle.com/technology/pub/articles/dev2arch/index.html
Weblogic JMS rollback
####<10-apr-2009> <info> <ejb> <vmmiddleware11> <mwalsb11> <[ACTIVE] ExecuteThread: '11' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <> <1239355884374> <bea-010213> <message-driven xid="BEA1-23F28F44E9B311BE176F(110581804),Status="Rolled" reason="weblogic.transaction.internal.AppSetRollbackOnlyException],numRepliesOwedMe="0,numRepliesOwedOthers="0,seconds" begin="0,seconds" left="60,XAServerResourceInfo[WLStore_MWALSBDomain_JDBCStore_MWALSB11]="(ServerResourceInfo[WLStore_MWALSBDomain_JDBCStore_MWALSB11]="(state="rolledback,assigned="MWALSB11),xar="WLStore_MWALSBDomain_JDBCStore_MWALSB1146900074,re-Registered" state="rolledback),OwnerTransactionManager="ServerTM[ServerCoordinatorDescriptor="(CoordinatorURL="MWALSB11+vmmiddleware11:7011+MWALSBDomain+t3+," xaresources="{WLStore_MWALSBDomain_JDBCStore_MWALSB11," nonxaresources="{})],CoordinatorURL="MWALSB11+vmmiddleware11:7011+MWALSBDomain+t3+).">
First steps are to get more informative error messages by enabling debugging for JTA
This is done by adding the following switches to weblogic on startup
-Dweblogic.debug.DebugJDBCJTA=true
-Dweblogic.log.StdoutSeverity="Debug"
This article give a list of other possible switches available on Weblogic
http://www.questtech.co.uk/index.php?option=com_content&view=article&id=163&Itemid=40