Investing

Thursday, January 28, 2016

Sunday, December 30, 2012

DI idioms


Setter injection has advantages in being flexible, particularly if you don't need every dependency set all of the time. However, it has significant drawbacks since fields can't be made immutable (constant), which is important to preserving object graph integrity. Constructor injection is a compelling alternative, since it does allow you to set immutable fields. It is also useful since you can't accidentally forget to set a dependency (such configuration fails early and fast). Constructor injection is also less verbose and prevents accidental overwriting of previously set dependencies.
However, it too has some drawbacks: If you have several dependencies (or worse, several similar ones), it is difficult to tell them apart. Furthermore, a circular reference (where two components depend on each other) is impossible to resolve with simple constructor wiring. Setter injection helps here, since both objects can be constructed in an incomplete state and later wired to one another. Setter injection also helps avoid the constructor pyramid, which is a design issue when you have multiple profiles of a component, in other words, where a component uses different subsets of its dependencies in different scenarios. Setters are also explicit about the dependencies they wire and thus make for more browsable code.
Constructor injection can be used to solve the circular reference problem, but it requires an intermediary placeholder known as a proxy. Some DI libraries (such as Guice) provide this out of the box, without any additional coding on your part. A related issue, the in-construction problem, where circular interdependents are used before the proxied wiring can complete, can be solved by combining constructor and setter injection or purely with setter injection. Better yet, you can solve this by using a special initializing hook.
However, the drawbacks of field mutability and the vulnerability that setter injection has to accidental invalid construction are too great to ignore. Non-final fields are also potentially unsafe to multiple interleaving threads (more on that in chapter 9). So, always try constructor injection first and fall back to setter injection only where you must.
There are also other injection idioms:
  • Interface injection—This involves exposing role interfaces that are effectively setter methods in their own interface. It has the advantage of being explicit just like setters, and it can be given meaningful names. However, interface injection is extremely verbose and requires several single-use interfaces to be created for the sole purpose of wiring. It is also not supported by many DI libraries.
  • Method decoration—This involves intercepting a method call and returning an injector-provided value instead. In other words, method decoration turns an ordinary method into a Factory method, but importantly, an injector-backed Factory method. This is useful in some rare cases, but it is difficult to test without an injector and so should be carefully weighed first.
  • Other idioms—Field injection is a useful utility, where fields are set directly using reflection. This makes for compact classes and is good in tutorial code where space is at a premium. However, it is nearly impossible to test (or replace with mocks) and so should be avoided in production code. Object enhancement is a neat idea that removes the injector from the picture altogether, instead enhancing objects via source code or otherwise leaving them to inject themselves. This is different from Factories or Service Location because it does not pollute source code at development time. There are very few such solutions in practice.
Some components "use up" their dependencies and need them reinjected (within their lifetimes). This introduces a problem, namely reinjection. Reinjection can be solved by the only, which involves the use of a single-method interface that encapsulates the work of constructing a dependency by hand or looks it up from the injector by service location. Providers let you abstract away infrastructure logic from dependent components and are thus a compelling solution to reinjection.
Contextual injection is a related problem. Here, a component may need new dependencies on each use, but more important it needs to provide them with context. This is a form of dependency that is known only at the time of use. Assisted injection can help. A slight variation of the Provider pattern, an Assisted Provider does the same job but passes in the context object to a partially constructed dependency. Since this can quickly get out of hand if you have more than one context object, try looking at the Builder pattern instead. The Builder incrementally absorbs dependencies (context objects or otherwise) and then decides how to construct the original service. It may use constructor wiring or a series of setters or indeed a combination as appropriate. The builder is also an easy solution to the reinjection problem and in such cases is very similar to a provider.
Some code is beyond your control, either third-party libraries, frozen code, or code that can't be changed for some other reasons (such as time constraints). You still need these components, so you need a way to bring them into a modern architecture with dependency injection. DI is really good at this work and at neutralizing such undulations in a large code base. One solution is to use external metadata (if your injector supports it) such as an XML file. This leaves the sealed classes unaffected but still provides them with requisite dependencies. However, if sealed code uses factories or unconventional setter methods, this may be difficult. In this case, the Adapter pattern is a powerful solution. You inject the Adapter as per usual, and then the Adapter decides how to wire the original component. Adapters are a strong solution because they can leave client code unaffected. They are also a transparent alternative to the reinjection problem, though they are sometimes verbose compared to providers.

Few thoughts about DI


Constructor Injection Vs Setter Injection.
   1. Allows dependencies to be declared as final, and the constructor is the only way to initialize the final variables.  When an object is intended to be used across multiple threads it is always required that the shared variables be either declared as final or volatile.  Setter injection cannot fix this issue of final variables. By default Spring DI creates a singleton instance unless specified to create an instance for each call, via the attribute prototype. If it is required for different threads  to use different instances, then Constructor injection is not mandatory. The requirement of declaring the variables as final is relaxed and  so  setter injection can provide different threads with different instances of the class.

2. Recursive dependencies, such as A depends on B and B depends on A can be solved by using a proxy.  Constructor injection cannot be used with this. Guice creates a dynamic proxy that solves the issue. 

3. In-constructor problem: Initialization requires a dependency  in  a circular dependency, which is not yet ready for use. (constructor calls the member function of the dependency.). There is no solution for this kind of mess when Constructor injection is used. Use Setter injection.

4. Constructor Pyramid Problem:  If a class has a significant number of decencies and if it uses several different constructors to initialize into several different forms, it is said to have constructor pyramid problem. It is difficult to understand what constructor does what in such a scenario. Number of constructors needed grows exponentially in proportional to number of dependencies. Setter injection is ideal in such a scenario.

5. Setter injection is unusable in default singleton situation where an object instance is  shared across multiple threads, as the decencies cannot be declared final.

6. Setter injection is error prone as it is not guaranteed to have all setters set in the object before being used, and it is not easy to detect that an object is not properly initialized until the method requiring that uninitialized decency is called during runtime.

7. In automatically generated code for the constructors,  parameter names would be name1, name2 etc rather than the actual field names. This is hard to catch bugs where two different parameters are initialized or called in different order. If setter methods are used, this problem is easier to catch as fields names are obvious in setter methods.

Thursday, April 09, 2009

Regular Expressions

^$ -> empty line
[a-z3-7] -> small alpha or a number between 3 and 7
a*b -> b, ab, aab
a?b -> b, ab
a+b -> ab, aab
^a$b -> line starting with letter a and ending with letter b
[^a-f] -> except for a to f
ab. > ab followed by any character except for new line
35\{4\} -> 35555
re(ab)d -> read, rebd
\ -> exact word "sin"
a\$ => a$
a$ => line ending with a
[:upper:] [:lower:] [:alpha:] [:print:] [:digit:] [:cntrl:][:blank:][:space:][:xdigit:]

Bash

Bourne Again Shell

1. File operations

if [ -e "filename" ]; : -> exists
r -> readable, w -> writable, h -> link, -x executable,

PROGRAM_NAME= $0
basename = `basename $PROGRAM_NAME`

Appending to a file:
cat "At the end" >> $filename

Prepending to a file:
cat "At the beginning" > $tempfile
cat $filename >> $tempfile
cat $tempfile > $filename


for file in `ls $PWD`
do
echo $file
done

if [ ! -f "/var/opt/myfile.txt" ]; then
mkdir -p "/var/opt"
cat $content >> /var/opt/myfile.txt
fi

2. String operations
if [ -n "$var" ]; to check whether var is null
if [ -z "$var" ]; to check whether var is empty
if [ -z "$var" ]; then
:
else
echo ok var is not null
fi

3. Arithmetic expressions
(( a=$a+1 ))
(( ++$a ))
a=`$a + 1`
count=0
while [ $count <>
do
echo "Type your name 10 times"
done
4. Logical operations
if [ ! $a ]
if [ $a -ne 0 ]
if [ $a -gt 20 ]
if [ $a -a $b ]
if [ $a -o $b ]
[ -z "$a" ] && exit 0

4. functions:
exit 0 is success, non-zero exit is failure
status is checked by $?
if [ $? = 0 ] -> success
Call by value mechanism (Use \ for referencing )
arguments count $#
arguments: $@ or $*
shift operator
while


5. Execution modes of shell scripts

set -x ... set +x will enable tracing

sh -x script.sh

set -o errexit

set -e -> Froces shell to quit if a command fails. With out, a program has to be written this way

command

if [ $? <> 0 ]; then

echo blah blah command failed

exit 1

fi

with set -e, the result checking is automatically enforced. The script exits when the command fails

set -e

....

comand

But some commands may be interspersed with important commands, that we really donot care of.

In such cases, automatic exit under set -e can be escaped by using the idiom

dontcarecommand true

dontcarecommand { echo command failed! ; exit 1 }

Or if a block of code node needs to be ignored

set +e

block of code

set -e

Some commands inherently possess this option. When executed under -e mode, the -f option of rm will remian silent if the file does not exist.

set -u :-> enforces the program to exit when an undeclared variable is encountered in the script

set -u; rmdir $TMP/etc/hosts -> Will exit if $TMP is not declared




5. Regular Expressions

6. Some sed commands:

7. Some awk commands


id -nu -> username
[ $UID = 0 ] -> root
$$ -> current process id
tr '[:lower:]' '[:upper:]' -> lowerToUpper
IFS -> Internal Field Separator (defaults to space)
set $IFS=':'
read -t 4 name; SECONDS -> number of seconds passed
$LINENO -> Line number with in the script, usefule for debug statements
echo $FUNCNAME -> current function name
SHLVL->Shell Level
function f()
{
local k
while [ $# -ne 0 ];
do
k=$1$k
shift
done
return $k
}
while read line
do
echo eval f $line
done

Development Tools

Gathering some development tools commonly used:
Open VPN, Poderosa, password less ssh, ultra vnc, nomachine's nxclient, VSphere, SQLTools, WinSCP, nmap, chatzilla, nav tool

Saturday, February 03, 2007

Through the eyes of an analyst



Behind Organizational Management Efficiency:


Companies incur expenditure to add assets. Assets can be fixed assets, that can be valuable or they can be depreciating assets which are no longer of value. Companies can use depreciation amount for tax deduction. At the end of the depreciation period the depreciated asset can still be productible. But it is not shown in the net assets. So, organizations can have real assets which may not be reflected in the real assets. An asset which is sold, if yields more income than the net worth or salvage price claimed in the depreciation, then that amount is considered as capital gains. Companies can take advantage of this tax deduction as a way of tax deferral. Captial Loss can be claimed as tax deductible tooo.... Amortization is applicable to intangible assets.

Every quarter or year, periodically we see that these amounts keep changing.
1) Assets can increase. This results in expenditure. Assets bought will decrease net profits and assets sold could add to net profits. If there are any captial gains or captial losses on the assets sold they should be filed/claimed in taxes.
2) Debt: A company may borrow money or reduce the debt. This change in amount of outstanding debt results in changes in interest amount paid hence reflecting changes in net income.
3) Equity: A = E + L. Assets by itslef does not reflect the wealth of the company. Equity removes liaility from asset to give the true worth. A company can increase equity by reducing debt or by increasing assets. A company should strive to increase the net equity. A company when goes to raise the additional money via shares, then it is diluting the equity. If the raised money is used to reduce the debt, then the equity is increased. Companies can benefit from this from time to time during high interest periods. They can reduce the interest paid amount.

How depreciation helps for a company:
1) tax incentive
2) Most important: Depreciation reduces equity in the book. And at the same time company can defer tax, and use it for expenses. Now assuming that there is no real depreciation for the asset, a company can give a perception that the return on equity is more even though it is not.
3) Company can show increase in net income through this tax deferral. At first look it might sound correct. But it will catch the analysts eye. They will remove this tax deferral amount, to calculate the net income. If the net income does benefit from tax deferral only, then the stock will be down graded.

Most companies can choose to charge high depreciation in early years and reduce it during subsequent years. They deduct this depreciation amount from earned income, to publish net income. The trick here is that by deducting higher depreciation in the beginning and reducing depreciation amounts later on, the company can show improved net earnings,save tax money. This may skew investors perceptions if he looks only for net earnings. More problems when the depreciation amount deducted reduces significantly, because investors feel happy that there is nothing more depreciating and it may also give a feeling that the returns on equity are more during later years.

What would a company do with the earnings, borrowed money or raised income ?
The efficiency of the management of a company lies with what they do with the profits.
A company can do any of the following things in case it thinks it can expand:
a) Invest in cutting edge technology to remain competetive. This does not necessarily improve margins. Atleast management do not foresee that.
b) Invest in better technologies to increase productivity and improve margins.
c) Become a minority iinterest holder in some other company.
d) Buy a company to diversify the business and hedge against unfavorable economic and tax legislations.
e) Buy a competitor (Merger, consolidation, acquisitions) to improve the market share. HP and Compaq marriage.
f) Buy a complementary product manufacturer to become a turn key solution provider. Eg: Cisco bought Scientific Atlanta to enhance the suite of Triple Play products. Arris Networks bought Tandem TV to compete against Cisco.
g) Increase revenues by advertising.
h) Attract and retain highly talented people.
i) Settle litigations. This will improve the company's focus on current operations than on past litigations.
j) Invest in R&D or buy patents or pay royalties.
k) Clear short term, higher interest debt.
For a growing company, it can invest the profits. If additional money is required then it can raise it by
k) by issuing secondary shares.
l) by issuing bonds.
m) by raising short term debt. The short term debt will be cleared with the subsequent profits.
If a company thinks that it cannot better the share holders value or if it considers that growth is significantly achieved with reducing progress, it can do the following:
a) Reduce the outstanding number of shares floated. This increases the per share equity of a share, and hence per share earnings, finally increasing the share price.
b) Reduce the outstanding debt, in a growing economy to reduce the interest expenses.
c) Giving a dividend.



Understanding Earnings and Interpreting Management efficacy:


Gross Margins: Gross Margins are calculated by removing cost of production from total sales. This cost of production is often skewed because, it only calculates direct costs. It does not account indirect costs, such as operating expenses which include Administration costs required to run the business such as compensation to CEO, President, marketing and advertising expenses. If a company has many cost centers then the administration expenses to organize these cost centers is not accounted in Costs.
Gross margins are nevertheless useful in comparing apples to apples, that is companies with in the same domain. A company with better gross margins generally means that it has an edge over its competitors.
Operating margins: Operating margins include both direct and indirect costs. This reflect the true value of a business for an investor. It shows how much an enterprise is able to generate. One quick look at comparing gross to operating margins can show whether the administration is very expensive... If gross margins are high but operating margins are less, it would mean little value for the investor. It could either mean that operating costs are too high or administration at higher levels are excessively paid (CEO compensations).
Gross Margins and Operating margins show the competetiveness of a business. Different industries will have different operating and gross margin ratios. For software companies gross margins will be high (70 %), but operating margins will not be that high (30%). There is significant difference between gross margins and operating margins. This reflects that it costs more to market and sale the product than it costs to manufacture the product. For an airline industry gross margins will be less (5%), because the cost for airlines (renting fleet, crew wages, fuel expenses, ticketing costs), but difference between gross margins and operating margins will be less, unless CEO's are paid hefty pay checks (American Airlines).
A company can improve operating margins by reducing compensations and hence decreasing operational expenses at higher executive positions. A nice example is Cisco during 2001 down turn. The company slashed executive compensations by 10% and company made economy travel as business policy by going frugal. This resulted in better operating margins and also corresponding increase in gross margins. This helped Cisco to remain competitive during the dot com bubble burst.
Gross Margins and Operating margins show the competetiveness of a business. What they do not show is the underlying health of a business by it self. Because they are not accounting: Interest from short term debt and Interest from Long term debt, Taxes, Depreciation. To get a true picture of a business as itself rather than in comparison to its peers, other expenses such as interest expenses, depreciation and taxes need to be looked at.
Companies have to reinvest the earnings to remain competetive. This expenditure could be either in the form of increasing assets or by increased advertising. Advertising may result in increased revenues and could correspondingly increase net income if advertising expenditures are lesser than increased gain in net income. On the other hand if a company tries to increase productivity by investing in cutting edge technology, it may improve on increasing gross margins. This improvement in gross margin can trickle down to operating margins if there is no significant increase in wages/compensation/advertising, Or if the ratio of increase in wages is lesser compared to increase in sales.
When an economy is booming it can result in increased sales. If this increase in gross margins is negated by increase in operating margins, by the way of increased expenditure on wages and compensation then it is not good for the future business. In a downward economy gross margins will come under pressure as more and more consumers will be cutting down on their expenses. But operating margins are not directly dependent on economy, but they are either inherent to the business or show operational inefficiency of the business. So, in a downward economy net margins will suffer.
If taxes are high then it means that a business is operating in a higher taxing areas of the world and business areas. So, when comparing business with in same sector, it is better to look for a business that is having lesser taxes, as in a long run that business can save more... Or if taxes are significant portion of the net income, then it could mean that the health of the business unit is dependent upon the tax rate, which can change... If the current taxing is the highest, then the only direction is for ease of tax rates, which could mean that the business could be more efficient in future. But if current taxing is to encourage businesses, by temporary reduction of taxes. then when the taxes are restored then the business may not sustain these profits...
Taxes should be compared with net profits.. If they are insignificant, then well and good. But if they are significant, then check whether the reported taxes have any temporary tax benefits. If there are, then the business may not sustain the profits when the taxes are restored... If a company is exposed to higher taxing states like CA then their net profits will not be good even though their EBITDA margins, Operating margins and Gross margins are good.
Debt: A company can secure long term debt by issuing senior notes, bonds, by issuing secondary shares etc.. and Short term debt from financial institutions or money lenders. The interest expenses on short term debt are higher, but they can be cleared in a short term from the profits.... if there are any. If the company cannot reduce its short term debt, then it may go for longer term debt. A company may seek long term lending to eliminate short term finances... example: Sun Microsystems recently borrowed money from KPR.. And some companies will issue additional company shares to raise the money for clearing debt both long term and short term. This is not actually reducing the existing share holders equity, as it might look though at the first instance. That debt is already part of the existing share holders equity.
In general, a company which has a significant debt, is not attractive. Unless they earn a lot more money on money borrowed, i.e., if the return on money borrowed is significant to the interest paid. It is important to see how it is using the earnings. Are they investing profits earned to result in increased equity, and further increasing share holders equity. Then if it is so, over a period of time, the companies equity should be more than the debt. If the debt to equity ratio is decreasing at a good rate that means the company is doing good, but if it is increasing, (if it increases or does not improve consistently, then it shows that there are periods where the borrowed money is more expensive than the returns on that money... not good. Because, if it decreases in one quarter, it effectively erases gains from the earlier quarter.)
The more the debt, the more are interest expenses in comparision to gross profits. When the economy is sinking, fed will lower the interest rate to boost the economy and increasing money flow by making money look very attractive to borrow. During these low interest rate periods these companies can do better. But when the economy is good, fed will obviously hike the interest rates to reduce the inflation, Then these companies net profits will suffer. The axiom is that the interest will never remain steady. They need to be tuned to keep economy afloat. For more information on why should fed tinker with interest rate, please google and get a grasp on concepts of increasing inflation, decreasing inflation, deflation, unemployment rate, cpi, cci fed rate cut/hike, manufacturing index, retail sales index etc.
The other two margins of interest are Net Margins and EBITDA margins(Earnings before interest, tax, depreciation and amortization) . Net earnings are also called GAAP (Generally agreed accounting principles) earnings. All analysts will be concerned more about EBITDA margins as they are less skewed and do not benefit from interest rates, tax rates and tax deferrals.

Assessing growth and core competency:

A company can compete in several different areas. But there will be core competency areas that a company is graded against. For example Apple computers, competes in both computers (PC, laptop) and also consumer goods (iPod, iPhone, iTv...). But investor would like Apple to compete in the Computers area more than the consumer goods. Investors are happy that a company is doing well in other areas, but what finally counts is its competency in its core competency. If apple cannot increase its penetration from 1% of the existing computers towards 100%, then its vast revenue potential will be at stake. Because, the amount of revenues that can be earned in computers area are much more multiples than the consumer products. These other non core competency areas have less barrier for existing and new competitors. This is precisely the reason why Apple was downgraded after its blowout revenues in Jan 2007. The strategy for Apple should be to reduce margins on its computers a little or become efficient in reducing manufacturing costs and compete against others such as Microsoft in Personal computers area.


Assessing a fair stock value:

This is where the main problem with a stock. In evaluating a price of a stock, the historical net income growth of a company need to be considered. Unlike a traditional fixed CD, earnings for a company keep growing at a compounded rate. So one dollar in earning now could result in 3 dollar in earnings at the end of 10 years. Or the company could be no longer in existence. If the interest rates are attractive then fixed CD's will be attractive. So, stocks are attractive to enter into when interest rates are higher as more and more money will get into banks. When the interest rates are low, stocks look more attractive and their prices will be high.
The best way to earn money through stocks is to buy low sell high. Every novice investor will do a mistake of being attracted to a blown up stock. The stock looks very attractive as does a blown balloon. It looks irresistable. But the inevitable thing is for a stock price correction. An experienced investor will look for a dip in stock price to get into a company's stock.
To understand what a fair value for a stock, look at Market cap for a company. It is the total of number of shares floating and price of the share. See the net income for the Trailing Tweleve Months (TTM). If you divide the Net Income with Market Cap, we get the amount of earnings per dollar invested. This is not where it ends. We should consider the growth of the company. Let us say for last three years the annual compounded growth rate is 30 %. This could statistically suggest that for next three years this enterprise could sustain that growth rate (when coming to such conclusions we should check gross margins and see whether the enterprise is a monopoly)
Market cap of Apple Inc is 76 B. The net income for the Trailing Tweleve Months (TTM) is 2.2 B. That means that for every 76 dollars of investors amount the return is 2 dollars. It is approximately 2.89 % return. But if the company sustains that growth for next 10 years at a compounded rate of 30% then the returns on 100 $ invested 10 years later would be 2.89 * (1.3 to the power of 10). I guess it must be $24. So $100 invested now would return $24 at the end of 10 years. So thats the reason why stocks trade a higher premium than their current returns, because markets will pay the corresponding premium to enter the stock.
This return of $2.8 per $100 looks attractive when interest rates are low. But in a booming economy this rate would not interest investor as bonds and cd's will be attractive. So, an average joe like you and me should buy stocks when interest rates are high and wait for interest rates to come down significantly. Its just that simple.
We will take a hypothetical examples of growth rates for Apple Inc, and analyze the future possbile price of Apple next.......

Wednesday, April 05, 2006

Thursday, March 10, 2005

Java Security

Language Level: At the language level Java provides security via:
Disallowing pointer arithmetic
Checking ArrayBounds at runtime
Verifying bytecodes during classloading.
Verifying bytecodes and access during first method call.
Access Control of packages.

Virtual Machine level: The notion is whether or not to allow/grant a code access/execute to JVM.
J2SE uses Java Policy based access control, policy file found in JAVA_HOME/lib/security or $HOME/.java.policy. For default applications there is no policy involved. But policy and the corresponding SecurityManager comes in picture for applets, classes downloaded from URL's. We can specify the policy in the policy file. This is a code based policy, meaning code downloaded from so and so location can execute or not. In summary, it controls 'WHAT' executes on the JVM.

Applets: Applets running in browsers are by default restricted to access only the host from which they are downloaded to avoid malicious applets trying to spy on ports inside a firewall or sending emails etc..
Applets(browsers) cannot access files on the users computer. Applets cannot read any system properties or can they start a new window. The dialogs from applets have a warning message saying that this is an applet, to save users from some spoofing login prompt dialogs

Signed Applets (CABS for IE) provide a way of releasing restrictions to an extent. They usually prompt the user for permission.

Application Level:


JAAS has 2 parts Authentication and authorization.
JAAS
Authentication: A subject can be either a single user or a group of users or a service.Principal is like a name and credential is like a password. Subjects have principals and credentials. Authenication involves autheticating subjects for a service by verifying provided credentials.

JAAS supports PAM (Pluggable Authentication Model). Authenication modules can be plugged transparently.
JAAS uses Java GSS-API for Single-SignOn. Java GSS-API uses Kerberos. Java-GSS uses Credentials as the cache for Kerberos TGT.

Concepts of interest: Principals, Subjects, Credentials, LoginContext, LoginModule.

Authorization: JAAS authorization is analogous to Java policy based access control, and extends the code based access control to include user based access control (controls WHO executes). Authorization is by default not enabled for applications. We can enable it by specifying on the command line during jvm startup to use the securityManager (-D java.security.Manager).Once enabled, the policy file needs to be edited to allow access to code, users for properties, resources (network, files).

Authentication:
LoginContext provides the abstraction from the underlying login modules for the application. LoginContext is the gateway for authentication. Login Modules can be specified in a configuration file and the name of the configuration file needs to be provided during the JVM start up (-Djava.security.auth.login.config==example.conf ).


LoginContext reads the login configuration and uses the specified login modules.

LoginModules are created with a CallBackHandler, that supports different callbacks. The callBack handler has a overloaded execute method that accepts array of different callback types, and we can handle the required callback type.
CallbackHandler fills the principal name, password etc in the correspondig callback object and returns. The login module uses those details to authenticate.
If all LoginModules successfully authenticate the Principal, the principal is added to the subject. and authentication is successful or authentication fails.
If authentication is succesful, then the subject can call the privileged action, an action that implements the privileged interface(basically should have a run() method) using doAs methods of Subject.

Message Digest: It is similar to CRC, a fixed size value computed from the message. This is used to ensure that message is arrived without tampering. But to avoid spoofing the message and message digest both, message digest can be encrypted(using the public key of sender).
Public key of the sender is known to the receiver, hence receiver can compute the message digest and encrypt using public key of sender and compare the encrypted message digests.

If the message needs to be encrypted as well, both message and encrypted message digest are encrypted using receivers public key, which will be decrypted at the receiver using receivers private key.

pk: public key, prk: private key, m:msg, md:message digest, s:sender, r:receiver

At sender:
  • md1 = messageDigest(m);// compute Message digest
  • e_md1 = pks(md1); // encryption step 1
  • M = m+ e_md1; // Full message
  • e_M = pkr(M): // encryption step 2

At receiver
  • M = m + e_md1 = decrypt_prkr(e_M);
  • md2 = messageDigest(m);
  • e_md2 = pks(md2);
  • e_md2 == e_md1
JCE java cryptography extensions cover the api for encryption and providers can provide different cryptography algorithms, cipher suites.
JSSE provides SSL and certificate store support. Use keytool to generate certificates. Use the same tool to import certificates into $JAVA_HOME/lib/secuirty/jssecerts . Certificate store contains certificates and trust store contains trusted certificates of clients. The name of a certificate can be referenced using an alias.
SSL Handshake involves Hello Protocol comprising of negotiating the cipher suites, and exchanging public keys etc...
A secure webserver request is forwarded to port 443. A resource configured in web.xml as "CONFIDENTIAL" will have to be requested using https. A http request for such a resource will be redirected to https. If the webserver cannot use port 443 and uses some other port then use iptables command on linux server to redirect requests on 443 port to the other actual port.

web server security.
Three web server security mechanisms: Basic, digest and HTTPS client authentication. Basic uses well known base 64 encoding; so no good. Digest is improvement over Base64. But not popular though. In a response to the protected resource request, web server sends, timestamp, url, etc and client uses MD5 to compute message digest. Anyway, in HTTPS client authentication web clients send their certificate when they connect the server, and server maintains client credentials till the connection is closed.
Servlet containers have to support 'Form based' authentication. This is similar to Basic, but allows a custom login page. To enhance security this can be combined with SSL.
J2EE security is based on roles and not users or groups. Users and groups can be configured outside either in database or standard xml file (server specific) and mapped to different roles.
Personalization of web pages can be achieved one possible way by checking roles using isUserInRole() method. Other than that both web server resources and ejb's should better be secured declaratively using web.xml and ejb deployment descriptors.

Wednesday, March 09, 2005

JMS Notes

PTP Messaging:
  1. Only one receiver. Queues
  2. Needs acknowledgement. Messages will be persistent till the acknowledgement is received by the sender.
  3. Receiver can go down and come back up, and the message will still be there.

Publish/Subscriber:
  1. Can be any number of receivers 0*. Topics
  2. Needs no acknowledgement. Messages will be persistent till all subscribed 'active' receivers receive message.
  3. Only 'active' are receivers that are up will receive message. If non active receivers do need the messages too, then they can go for durable subscriptions.

TIPS:

  1. A non-j2ee jms client application can use transactions for jms messages. These transactions are not meant to be used for request-reply scenario, rather they can be used for a series of send requests or a series of receive requests on a session and for a combination of requests and replies on different sessions.
  2. A j2ee jms client application can use JTA or container managed transactions. For bean managed transaction, the messages are not redelivered when a transaction rollsback, whereas for container managed transaction messages are redelivered after a transaction rollback.
  3. Message Driven Bean (MDB), does not have a remote or home interface. It has a setMessage- DrivenContext method. MDB differs from a regular JMS client, in a sense that most of the code required to initiate the message queues/sessions is automated for MDB, via deployment declarations. A MDB has to implement MessageListener and MessageDrivenBean interfaces.
  4. If a SessionBean or Entity bean wish to be a client for the JMS, they should create the Connection resource in the ejbCreate() and release it in ejbRemove() methods. Create the Session in the business method, then close the resource in finally method. For stateful and entity beans close the sessions in ejbPassivate() and create them again in ejbActivate().
  5. A session bean or entity bean should not block on a receive call as it will affect the performance of the ejb container.
Performance vs Reliability:

For performance reasons reliablity need be compromised. For applications where reliability is not a primary concern, and where it is affordable to loose some messages, like in performance data collection or statistics collection, it is advisable to use the following performance improvements:

  1. Use delivery mode to be NON_PERSISTENT. JMS Provider by default uses persistent mode so that messages will be delivered even in the case of failure of the JMS provider. This is acheived by saving the messages to a log file. By specifying non_persistent mode, this overhead can be eliminated, hence improving performance.
  2. Use time to live parameter that can specified either in MessageProducer interface or long form of pubish method to expire messages after certain interval. The default value of '0' implies messages will never expire.
  3. To have variable response times for messages with varying priorities, use priorities for messages.
  4. Set transaction attribute to "false" for sessions.