Google
 

Friday, January 30, 2009

How to Upload Multiple Files in Java

package com.mp.ws;

/**
*
* @author nitinaggarwal
*
*/
public interface IFileUpload {

public byte[] get1File(String name);

public byte[][] getMulitpleFiles(String names[]);

public String getXmlFile(String name);

}

package com.mp.ws;

/**
*
* @author nitinaggarwal
*
*/
public class FileUpload implements IFileUpload {

public byte[] get1File(String name) {
byte data[] = null;

FileReader fr = new FileReader();
try {
data = fr.readBinFilePath(name);
} catch (Exception e) {
e.printStackTrace();
}

return data;
}

public String getXmlFile(String name) {
String data = null;
FileReader fr = new FileReader();
try {
data = fr.readTextFile(name);
} catch (Exception e) {
e.printStackTrace();
}
return data;
}

public byte[][] getMulitpleFiles(String[] fnames) {

byte[][] data = new byte[fnames.length][];
for (int i = 0; i < fnames.length; i++) {
FileReader fr = new FileReader();
try {
data[i] = fr.readBinFilePath(fnames[i]);

System.out.println("abc" + data[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
return data;
}

}

package com.mp.ws;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
*
* @author nitinaggarwal
*
*/
public class FileReader {

public String readTextFile(final String name) throws Exception {
StringBuffer xmlFromFile = new StringBuffer();
InputStream instr = null;
//instr = getFilePath2(name);

instr = new FileInputStream(name);

if (instr == null)
throw new FileNotFoundException();
InputStreamReader streamreader = null;

try {

streamreader = new InputStreamReader(instr);
int x = 0;
x = streamreader.read();

while (x != -1) {
xmlFromFile.append((char) x);
x = streamreader.read();

}

} catch (Exception e) {

System.out.println("Exception " + e.getMessage());
throw e;

} finally {
streamreader.close();

}

return xmlFromFile.toString();

}

public byte[] readBinFileFromClassPath(final String name) throws Exception {

byte bytearray[] = null;
FileInputStream fileinputstream = null;
try {

fileinputstream = new FileInputStream(getFilePath(name));
int numberBytes = fileinputstream.available();
bytearray = new byte[numberBytes];
fileinputstream.read(bytearray);

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

} finally {
if (fileinputstream != null)
fileinputstream.close();
}

return bytearray;
}

public byte[] readBinFilePath(final String name) throws Exception {

byte bytearray[] = null;
FileInputStream fileinputstream = null;
try {

fileinputstream = new FileInputStream(name);
int numberBytes = fileinputstream.available();
bytearray = new byte[numberBytes];
fileinputstream.read(bytearray);

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

} finally {
if (fileinputstream != null)
fileinputstream.close();
}

return bytearray;
}

public void writeBinFileToPath(String name, byte data[]) throws IOException {

FileOutputStream fileoutputstream = new FileOutputStream(name);

try {
fileoutputstream.write(data);

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

} finally {
if (fileoutputstream != null)
fileoutputstream.close();
data = null;
}

}

private InputStream getFilePath2(String filename) {
return this.getClass().getClassLoader().getResourceAsStream(filename);

}

private String getFilePath(String filename) throws FileNotFoundException {
String path = this.getClass().getClassLoader().getResource(filename)
.getPath();
if ("".equals(path))
throw new FileNotFoundException();
return path;

}

}

package com.mp.ws;

/**
*
* @author nitinaggarwal
*
*/
@javax.jws.WebService(targetNamespace = "http://ws.mp.com/", serviceName = "FileUploadService", portName = "FileUploadPort")
public class FileUploadDelegate {

com.mp.ws.FileUpload fileUpload = new com.mp.ws.FileUpload();

public byte[] get1File(String name) {
return fileUpload.get1File(name);
}

public byte[][] getMulitpleFiles(String[] fnames) {
return fileUpload.getMulitpleFiles(fnames);
}

public String getXmlFile(String name) {
return fileUpload.getXmlFile(name);
}

}

package com.mp.ws;
/**
*
* @author nitinaggarwal
*
*/
public class FileUploadTester {

public static void main(String[] args) {
FileUpload fu = new FileUpload();
String fnames[]= {"c:/uploadme.doc","c:/uploadme.doc","c:/uploadme.doc"};

byte[][] data = fu.getMulitpleFiles(fnames);

}
}

Tuesday, January 27, 2009

Pagination: Server Side or Client Side?

What is it best way to handle pagination/sorting and filtering? Server side or at the client side?

Numerous times in your projects you might have to face a situation where you need to pull chunks of data dynamically. The obvious issue that you then face is pagination\sorting and filtering. You then start to think if it would be better to handle it all at the server side or should hold back and handle it on the client side.

Well there is no clear winner amongst the two; neither there is a right or wrong approach.

The right answer depends on your priorities and the size of the data set to be paginated.

If you have large number of pages doing it on client side will make your user download all the data at first which might not be needed, and will defeat the primary benefit of pagination. In such a scenario you are better of requesting pages in chunks from the server via AJAX. So let the server do the pagination. You can also pre-fetch the next few pages the user will likely view to make the interface seem more responsive. However, when implementing it, you need to make sure that you're optimizing your SQL properly. For instance, I believe in MySQL, if you use the LIMIT option it doesn't use the index so you need to rewrite your SQL to use the index properly.

If there are only few pages, grabbing it all up-front and paginating on the client may be a better choice. That gives you the obvious benefit of faster subsequent page loads. Unless really required we should not choose the Server side pagination in such a case.

Server side pagination is better for:

  • Large data set
  • Faster initial page load
  • Accessibility for those not running JavaScript
  • Complex view business logic
  • Resilience to concurrent changes

Client side pagination is better for:

  • Small data set
  • Faster subsequent page loads
  • Sort & filter requirements supported fully (unless results greater than max size).

To sum up, if you're paginating for primarily cosmetic reasons, it makes more sense to handle it client side. And if you're paginating to reduce initial load time, server side is the obvious choice. Of course, client side's advantage on subsequent page load times diminishes if you utilize Ajax to load subsequent pages.

Click here For More details and comments

Also refer to http://nitinaggarwal.wordpress.com/

Comments\suggestions are welcome.

Friday, January 23, 2009

Reason for the continuous fall of the Pound.

How bad is this fall in the pound? In a word: hideous.

Measured against a basket of other currencies – the best way in this globalised era to test a currency's strength – the pound has fallen in the past year by around a quarter.

This is more than any previous devaluation in the past century – greater even than in 1931, when, under Ramsay MacDonald, the UK was forced to abandon the gold standard and saw the pound plummet by more than 24 per cent against the dollar. Greater than after Black Wednesday and the abandonment of the Exchange Rate Mechanism; worse than in 1967, when Harold Wilson was forced to make an extraordinary televised statement to the nation claiming that the "pound in your pocket" would not be worth any less after his devaluation.

As anyone who has been overseas recently will know, it has fallen from over $2 against the dollar to under $1.40. This week it touched the lowest level since the Plaza Accord of 1985 – in which year the pound very nearly went to parity against the US currency. Against the euro, the pound has slid from €1.35 to just above €1 in the past year.

In practice this means that anyone travelling to the Continent will find it tough to get anything more than a euro for every pound they want exchanged, after the bureau de change has taken its cut and commission.

For Gordon Brown, who mocked the Conservatives in 1992, it is acutely embarrassing. Back then, he said: "A weak currency arises from a weak economy which in turn is the result of a weak Government." This time he is staying conspicuously quiet about the whole thing.

But why is sterling sliding?

In large part because it reflects Britain's economic prospects. The UK is facing a nasty recession – one that is likely to be as bad as any experienced by the Western world. House prices are falling at the fastest rate
since the 1930s, unemployment is on the rise and will soon climb beyond two million, consumer spending is sliding.

In such circumstances, investors are naturally likely to withdraw their money from the UK. On the one hand, they will sell sterling shares and investments since they are likely to fall in value as a result of the recession. On the other, those who invest their cash in the UK will pull it out of the country, since the Bank of England is cutting interest rates as a response to the slump. Any money in sterling in a UK bank account is earning very little interest, so overseas investors calculate they might as well take it elsewhere.

How worried ought we to be?

If the above was all that was happening, not unduly. In a world of floating exchange rates, the falling pound is not merely a symptom of the disease (the recession) but its cure. All else being equal, a weak pound should boost the exports of British companies, since it makes their products cheaper than those of their overseas rivals.

Machinery produced in the north of England is fast becoming cheaper than that produced in eastern Europe. And this goes not just for visible trade – actual physical goods – but for invisible trades such as legal or financial services.

So, although Britain's manufacturing sector has shrunk significantly since the 1980s and 1990s, the comparative value of UK products should nevertheless help boost the economy. The same goes for tourism, which has already picked up significantly as foreigners come to the UK to pick up bargains. London's days as Europe's most expensive city are well behind it.

The problem, however, is that all else is not equal at the moment: the appetite abroad for exports of any type has dried up in a way never before experienced. From Europe to the Americas to Asia, trade has almost entirely seized up as the recession has turned global. And let's not mention financial and legal services – the appetite for which has evaporated.

In the 1990s and the 2000s, successive governments decided to focus the UK's economy on financial services. A decision was taken to put almost all our economic eggs in one basket. Unfortunately, that basket has come crashing to the ground.

So is this now a full-blown sterling crisis?

Until recently, it wasn't a crisis. There are, broadly speaking, two types of devaluation – one benign, the other far less so. The good one is much as described above – a competitive devaluation in the pound which, over time, provides a cure. After the pound fell in 1992, it ushered in years of recovery and then prosperity for the economy.

The bad version is a full-scale crisis – a run on the pound. It is a vote of no-confidence in a country's economic policies, and occurs when investors start pulling their cash out of the UK not because of a temporary period of recession but because they are worried about the direction the economy is taking (over years and decades rather than months).

In the months up until this week it was possible to argue that this represented a competitive devaluation, and would be a boon for exporters. All of that changed on Monday. Following Gordon Brown and Alistair Darling's announcement of a second bail-out package for struggling banks, the pound suffered what can be described as a minor run. Investors took fright that the UK was drawing closer to insolvency, and as a response sold off their stocks of government debt.

It is difficult to overstate the significance of this. Britain's power and prosperity since the earliest days of the Union have been founded on its reputation for being a good risk.

Whereas other countries, such as Argentina and Russia, have occasionally defaulted on their debts, Britain's government has always been among the best borrowers in the world. For the first time in decades this is being questioned.

The rumour around the market this week was that Standard & Poor's, a ratings agency which tells traders what has and does not have the stamp of approval, was set to downgrade Britain's government sovereign debt. The agency has since denied this, but the UK fulfils many of the criteria for such a humiliating decision.

Does it really matter if Britain's creditworthiness comes under question?

Yes – immensely. Britain has a large current account deficit – of about £7.7 billion. This means we, as a nation, spend more money than we generate each year. This is no problem while we can borrow the difference, but that £7.7 billion chunk has to come from overseas investors. Should they stop lending to the UK, Britons would face a sudden, painful jolt and their living standards would fall even faster and more painfully than they are at the moment.

The Government would have to seek assistance from the International Monetary Fund which would, most likely, dole out a baleful dose of economic medicine – higher interest rates, lower government spending and immediate austerity.

Although, in the long run, Britain does need to borrow less and save more, such an adjustment should ideally take place over years, not weeks.

Isn't this all really the fault of the bankers as well as the Government?

Indeed it is. Now that the majority of the banking system is effectively nationalised (and the Government has promised to insure the nastiest debts of the remaining private banks) the taxpayer is effectively standing behind another massive liability. The banking system has about $4.4 trillion of foreign debts, and most analysts predict that around £200 billion of these could default.

What scared investors this week was the sudden realisation that the Government, rather than the banks, will have to pay the bill. The UK, unlike Iceland, does not have the luxury of being able to default on those foreign debts (remember the fracas when Britons faced losing their savings in Icelandic banks?)

Were the UK to do the same as Iceland, the size of Britain's liabilities are such that it would trigger an international panic and financial meltdown worse than when Lehman Brothers collapsed last year.

This all sounds unremittingly gloomy. Is there any solution?

Mainly to hope that the economic medicine served up by the Bank of England and its fellow central banks does the trick. As long as house prices are falling and unemployment is rising, the liabilities of the Government will swell and the pound will remain weak. But when, eventually, the economic backdrop improves, so should the financial outlook, and, eventually, the pound.

However, there is little hope of returning to the heady days of a near-80p euro and a $2 pound. The pound was significantly stronger than it ought to have been over the previous decade. It is probably undervalued now, and if all goes well it should bounce back in the coming years.

However, everything now depends on trust: that trust will return to the beleaguered financial system; that investors will start to trust the Government again and that Britons trust that there will be life after the recession.

Source: www.telegraph.co.uk