Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Monday, April 6, 2009

Jax-ws on Tomcat: reconnect from Hibernate to MySQL using c3p0 connection pool

You are on this page because you have seen the following error:

org.hibernate.util.JDBCExceptionReporter: The last packet successfully received from the server was 56697 seconds ago. The last packet sent successfully to the server was 56697 seconds ago, which  is longer than the server configured value of ‘wait_timeout’. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property ‘autoReconnect=true’ to avoid this problem.

I guess you have already using ?autoReconnect=true in the JDBC URL (this evidently wasn’t working) and wonder why.

I also guess that you have tried google tons of articles trying to solve this problem. Well, you have come to the right place. I spend sometime on this issue and finnally solved this problem, almost encountered every bit of chaos.

Firstly, I would like to reference few good posts:

  • http://www.databasesandlife.com/automatic-reconnect-from-hibernate-to-mysql/
    • This one throws some light, but it is a bit old, so the connection pool was old fation and the author suggest to “ create a file c3p0.properties which must be in the root of the classpath with content c3p0.testConnectionOnCheckout=true” , which is expensive and not used anymore. Read it yourself for details. 
  • c3p0 - JDBC3 Connection and Statement Pooling This is offical document so refer to this when you can’t decide what to do! 
    • Hibernate's C3P0ConnectionProvider explicitly sets 7 c3p0 configuration properties, based on your hibernate configuration, overriding any configuration you may have set in a c3p0.properties file. If you are using Hibernate's C3P0ConnectionProvider you must set the following properties in your hibernate configuration, using hibernate-specific configuration keys. All other properties must be defined as usual in a c3p0.properties file. This is confusing, and will hopefully be simplified some time in the future, but for now...
    • The following properties must be set in your hibernate configuration:
    • 未命名
    • Remember -- these, and only these, properties must be defined in your hibernate configuration, or else they will be set to hibernate-specified defaults. All other configuration properties that you wish to set should be defined in a c3p0.properties file.
    • The easiest way to set these are actually using myeclipse hibernate.cfg.xml configuration editer. Make sure you set all config related to c3p0 and add “hibernate.” before the setting. For instance, change “c3p0.min_size” to “hibernate.c3p0.min_size”. See above table as well. If you are not using myeclipse, just edit the xml in text editor.

With the above information, You are almost there, except you need the jar files in the classpath. Otherwise, you will get exception java.lang.NoClassDefFoundError for HibernateSessionFactory. In myeclipse, jar is not included as default hibernate support, so you need to add advanced support.

This problem annoying me for almost two weeks, and everytime I check my log4j and tomcat log, I saw this warning. Not sure if it really is a serious problem, but using connection pool definately enhance Hibernate performace.

Wednesday, March 25, 2009

java how to convert int to Byte array, and how to assign int value to Byte

Byte only have a constructor which takes Byte itself, so anything like

Byte b = new Byte(1);

or

Byte b = 1;

will all fail;

 

The easiest way to assign int to Byte is using the empty constructor, then = operator.

Byte b;

b = 1;

To convert int to Byte array, try the following:

t[0] =(Byte)( foo >> 24 );
t[1] =(Byte)( (foo << 8) >> 24 );
t[2] =(Byte)( (foo << 16) >> 24 );
t[3] =(Byte)( (foo << 24) >> 24 );

Monday, August 25, 2008

How to Convert between byte and Hex string

Please see the function below:




/// Convert a string of hex digits (ex: E4 CA B2) to a byte array.
/// The string containing the hex digits (with or without spaces).
/// Returns an array of bytes.
private byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}

/// Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)
/// The array of bytes to be translated into a string of hex digits.
/// Returns a well formatted string of hex digits with spacing.
private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
}


Sunday, August 24, 2008

Margin Lending Tips

1. Beat rising interest rates
Prepaying interest on a margin loan may produce interest savings in a rising interest rate environment. By locking at a competitive fixed interest rate for three, six or nine months, potential variable rate rises over the rest of the financial year can be avoided.

2. Can you claim 'professional trader' deductions?
Those who claim share trading as their profession rather than just being an investor must convince the Australian Taxation Office before they can claim trading losses as tax deductions. The ATO warns there are strict criteria to be met for someone to be classed as a share trader following confusion amongst investors who have incurred losses and then tried to offset these against their other income.


3. Caution needed on protected equity loans
Protected equity loan products allow investors to gain leveraged exposure to the sharemarket with a built-in safety net if their portfolio stocks take a dive. Investors can't lose their base capital but can keep dividends and capital gains. They also benefit from tax concessions with 100 per cent deductibility for their interest and capital protection costs. But not all financial planners and tax experts are convinced that these products are the best way to achieve a solid investment return. They say their high buy-in costs and uncertainty about when the Tax Office might change the deductibility treatment make them unattractive. Experts say the costs can run as high as 17 per cent in addition to paying loan interest when investors pay for embedded put options to protect the products' downside.

4. Don't try the prepay fiddle
If focussing on the tax benefits of prepaid interest, don't try and pull a swifty by taking out a loan, prepaying interest, then cancelling the loan and getting a refund of the interest after claiming the deduction. It won't work. Prepaid interest cannot be refunded. As a tax strategy, margin loans and prepaying interest are only beneficial if you plan on actually investing the borrowed funds.

5. Establishment fee protection
Under a protected equity loan arrangement, some lenders include the value of the establishment fee in the capital guaranteed amount. For example, if you borrow and invest $100,000 and $1000 is taken out in establishment fees, some lenders will still provide a capital guarantee over $100,000, others will only guarantee $99,000.

6. Fixed interest rates
Interest rates on protected equity products are fixed but not necessarily for the full term of the loan. Some products have a rate fixed for the full term, others reset the fixed rate each year of the loan term. These resets will reflect the interest rate environment at the time.

7. Is the interest on protected equity loans tax deductible?
There has been much debate about the deductibility of the interest payments on capital protected loans because of the difficulty in distinguishing between the capital protection component and pure loan interest component of the payments. Only the interest component is tax deductible. The amount of interest available for deduction will be the lower of:

* the amount determined by the Reserve Bank's Indicator Rate for personal unsecured loans
* the amount determined on a sliding scale depending on the term of the product (85 per cent for five years, 82.5 per cent for four years, 80 per cent for three years, 72.5 per cent for two years and 60 per cent for one year)


8. Loans for interest
Some protected equity lenders offer a separate, secondary loan to cover the first year's interest payment on a protected equity loan. These loans will have different rates, terms and conditions than the primary investment loan.

9. Prepay interest for tax benefits
Most borrowers are able to claim margin loan interest and other costs of investment as tax deductions - depending on personal circumstances. Prepaying twelve months in advance just before the end of the tax year is the way to make the most of the tax benefits. By paying a year's interest in June, the deduction can be enjoyed almost immediately in your upcoming tax return in July. But be aware that this really only amounts to tax deferment, not tax reduction. Investors are only bringing forward a tax deduction by one year, not reducing overall tax in the long run.

10. Tax advantages of borrowing to invest
There are several tax advantages when you borrow to invest in shares:

* you can claim your interest payments against your taxable income and if you earn less on the share investments than the interest payments you can claim the interest against other assessable income;
* you can prepay the interest up to 13 months ahead, prior to June 30, which is helpful for cash-flow planning and also allows you to claim the deduction a full year in advance;
* you can defer any capital gains tax liability until the shares are sold;
* as you're geared into the market you will own more shares than if you had paid cash, so you will receive more dividend payments. If the shares are franked then you can offset the franking credits against your assessable income.


11. The trade off between loan cost and share growth
Protected equity lenders broadly offer two different ways to reduce the high interest costs of their capital protected loans. 'Shared upside' simply offers the borrower a lower interest rate in return for sharing any capital growth at the end of the loan term with the borrower at a set proportion, eg. 25 or 50 per cent. Alternatively, some borrowers offer investors the ability to write call options over the stocks in their loan portfolio at preset "strike" prices. The sale proceeds from these options can be used to help fund the loan interest. But this also means that if the price of a stock in the portfolio rises above the option strike price, the buyers of the call options can then buy the stock outright from the investor, leaving the investor with only the capital growth up to the strike price.

Friday, August 22, 2008

How to add smecontribs repository

Log into SME Server console as root.

Issue the following command

yum update smeserver-yum

Thats all. It will add the repository on completion

Sunday, August 17, 2008

Create startup script in SMEServer

SME Server is a pre-configured Linux server designed for small to medium businesses!
It used Red Hat Enterprise Linux kernel, or CentOS kernel.

When creating packages, I wanted a script to be running when the system boot up. For example, an auto usb drive mounting script. I started with something that running in the background, and didn't work quite well. Using & straight away is not a clever way because script in init.d folder should follow certain standard, and can be managed by the boot up program manager( it might be called something else).

Firstly, you can write a normal script and wrap it as the following example:



#!/bin/sh
#
# description: usbMountWrapper is the daemon to xxxxxx
#

. /etc/rc.d/init.d/functions

function start()
{
printf "Starting %s: " "usbMountWrapper"
daemon /opt/smebackup/usbMountWrapper &
echo
touch /var/lock/subsys/usbMountWrapper
}

function stop()
{
printf "Stopping %s: " "usbMountWrapper"
killproc usbMountWrapper
echo
rm -f /var/lock/subsys/usbMountWrapper
}

function reload()
{
pid=`pidof ulogd`
if [ "x$pid" != "x" ]; then
kill -HUP $pid 2>/dev/null
fi
touch /var/lock/subsys/usbMountWrapper
}

case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
reload)
reload
;;
status)
status usbMountWrapper
;;
*)
printf "Usage: %s {start|stop|status|restart|reload}\n" "usbMountWrapper"
exit 1
esac

exit 0




This is a much nice way of writing boot up script and you can start or stop them like this:
/etc/rc.d/init.d/usbMountWrapper start
/etc/rc.d/init.d/usbMountWrapper stop
/etc/rc.d/init.d/usbMountWrapper restart

Sunday, August 10, 2008

Vi: Start-up, Modes, Save and Quit

Vi: Start-up, Modes, Save and Quit

Vi: Start-up, Modes, Save and Quit

To enter Vi type:

 vi FILENAME

Vi has two modes: Normal (command) mode and edit mode.

 Switch to normal mode:     <ESC>
Switch to edit mode: i or a

Getting out of Vi (change to normal mode <ESC>):

 Exit Vi:                       :q
Exit Vi (ignore changes): :q!
Save: :w
Save and Exit: :wq

Switch to (edit) an other file:

:edit FILENAME

Getting help:

:help topic

Thursday, July 24, 2008

C# convert between int and byte array

BitConverter is a native way of converting int and byte[]. In fact, converting byte array into float(single in C#), double, Int16,Int32 etc....

For example:
int tmp = 10;
byte[] b = BitConverter.GetBytes(tmp);

// convert to float
byte[] b = new byte[4];
BitConverter.ToSingle(b, 0);

Depending on how you want the byte[] to be converted, BitConverter has whole lot functions to do that.Only to remember, if you are about to convert 8 bit byte array, you can simply cast it to int.

One interesting thing is that when you wanted to receive bytes from network, you might need to worry about big endian and little endian issue. I saw some hard solutions, but found a simple way of doing it.

byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
Array.Reverse(receiveBytes);

Enjoy

Tuesday, July 22, 2008

Windows From ----- Only one instance of the program can be started

Don't want user to start your application twice ? Use the code below:

static void Main()
{
bool instanceCountOne = false;

using (Mutex mtex = new Mutex(true, "MYApplication", out instanceCountOne))
{
if (instanceCountOne)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

using(login l = new login())
{
if (l.ShowDialog() == DialogResult.OK)
{
l.Dispose();

if (Properties.Settings.Default.from_database == true && Properties.Settings.Default.Start_CommitChanges == true)
{
Connecter c = new Connecter();
commit_changes(c);
}

Application.Run(new GUI());
}
else
{
l.Dispose();
//MessageBox.Show("Login Cancelled.");
}
}

mtex.ReleaseMutex();
}
else
{
MessageBox.Show("An application instance is already running");
}
}
}