I am creating a web app where I want to show a excel icon in my results. When user clicks on icon, it should open up a spread sheet on clients machine with some data sent by server (clients will have excel installed).
I wrote some code to create excel on my local machine from the webservice.
public class App
{
public static void main( String[] args )
{
try {
URL oracle = new URL("http://someService.com");
URLConnection yc =null;
yc = oracle.openConnection();
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
int rowNum =0;
while ((inputLine = in.readLine()) != null) {
Row row = sheet.createRow(rowNum++);
String[] coloumns = inputLine.split("\t");
int cellNum =0;
for(String coloumn: coloumns){
coloumn.
Cell cell = row.createCell(cellNum++);
cell.setCellValue(coloumn);
}
System.out.println(inputLine);
}
in.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\libraries\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This works fine.
All it does is it reads data coming from web service and creates a spreadsheet in my machine at C:\libraries\new.xls.
Now if I am on web app I want to open a spread sheet on clients machine. I don't have to save the sheet. Just open with the data.
How can I open spread sheet on client machine with this data from web service?
EDIT
Here is my new server code:
#RequestMapping(value = "/Excel")
public void getFile(HttpServletResponse response){
OutputStream out =null;
try {
out = response.getOutputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
response.setContentType("application/x-ms-excel");
try {
URL oracle = new URL("http://someService.com");
URLConnection yc =null;
yc = oracle.openConnection();
//Get the workbook instance for XLS file
IOUtils.copy(yc.getInputStream(),out);
out.flush();
System.out.println("Excel written successfully..");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So now i ran the web app and nothing happened? Should i do something on front end to invoke this stream.
You can do something like this inside a Spring MVC controller to send the file to the client's computer:
#RequestMapping(value = "/myexcelreport")
public void getFile(
HttpServletResponse response) {
OutputStream out=response.getOutputStream();
response.setContentType("application/x-ms-excel");
... Same code a before, just use out instead of a FileOutputStream , and don't close out.
out.flush();
}
Related
I have been trying to display nearby locations from my current location. But when i run it and click the button to view the nearby locations nothing appears. The first time i ran it, it displayed but when i backed out and came back in, it didnt display anything. i tried cleaning the project and other methods.
this is the method in my main class:
public void findRestaurants(View v){
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
stringBuilder.append("location="+latLngCurrent.latitude + "," +latLngCurrent.longitude);
stringBuilder.append("&radius="+5000);
stringBuilder.append("&keyword="+"restaurant");
stringBuilder.append("&key="+getResources().getString(R.string.google_map_keyy));
String url = stringBuilder.toString();
Object dataTransfer[] = new Object[2];
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
}
public class getNearbyPlaces extends AsyncTask<Object,String,String> {
GoogleMap mMap;
String url;
InputStream is;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String data;
#Override
protected String doInBackground(Object... objects) {
mMap = (GoogleMap)objects[0];
url = (String)objects[1];
try {
URL myurl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) myurl.openConnection();
httpURLConnection.connect();
is = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
stringBuilder = new StringBuilder();
while((line = bufferedReader.readLine() ) != null){
stringBuilder.append(line);
}
data = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject parentObject = new JSONObject(s);
JSONArray resultsArray = parentObject.getJSONArray("results");
for (int i = 0; i<resultsArray.length(); i++){
JSONObject jsonObject = resultsArray.getJSONObject(i);
JSONObject locationObj = jsonObject.getJSONObject("geometry").getJSONObject("location");
String latitude = locationObj.getString("lat");
String longitude = locationObj.getString("lng");
JSONObject nameObject = resultsArray.getJSONObject(i);
String name_restaurant = nameObject.getString("name");
String vicinity = nameObject.getString("vicinity");
LatLng latLng = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
MarkerOptions markeroptions = new MarkerOptions();
markeroptions.title(vicinity);
markeroptions.position(latLng);
mMap.addMarker(markeroptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
it worked the first time when i lunched it. Did i do something wrong?
hope you are doing fine. Can you replace the lines
new getNearbyPlaces().execute(dataTransfer);
instead of these 2 lines
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
I am not sure whether this is going to impact much, but this is the way AsyncTask class should be called.
If this is not working, can you share the entire code of this java page, so we can look at how findRestaurant() method is called.
How to write data from edit text into excel file in android?
I want to bypass data from editText into excel file without opening it from storage. Can i know how to do it?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity = this;
scanBtn = (Button) findViewById(R.id.BtnScn);
resultSC = (TextView) findViewById(R.id.SC_text);
ExelWrite = (Button) findViewById(R.id.ExelWrite);
SetTemp = (EditText) findViewById(R.id.SetTemp);
scanBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
startActivity(new Intent(getApplicationContext(),ScanCodeActivity.class));
}
});
ExelWrite.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.ExelWrite:
saveExcelFile(this,"Staff_Temperature.xls");
break;
}
}
private static boolean saveExcelFile(MainActivity context, String fileName) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.e(TAG, "Storage not available or read only");
return false;
}
boolean success = false;
This is where I create The workbook for the excel
//New Workbook
Workbook wb = new HSSFWorkbook();
Cell c = null;
//Cell style for header row'
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//New Sheet
Sheet sheet1 = null;
sheet1 = wb.createSheet("RiSE");
// Generate column headings
Row row = sheet1.createRow(0);
c = row.createCell(0);
c.setCellValue("Staff Credential");
c.setCellStyle(cs);
c = row.createCell(1);
c.setCellValue("Staff Temperature");
c.setCellStyle(cs);
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
This is where I create Path for the file. I think It should be here, but I dont know how to call it
// Create a path where we will place our List of objects on external storage
File file = new File(context.getExternalFilesDir(null), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
return success;
}
public static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
I have a client/server app to manage a line of some sort.
all the clients add objects to my line.
I want the server to send a screen capture of the jpanel to the clients every time there is a change in the line, line inserted or removed.
I managed to capture the jpanel to a jpeg and even send it.
but the flow of my app is stopped, after the first update I get eofexception that terminates my listening server socket.
what is the correct way to update a client ? should I set a serversocket to always listen on the client side too ?
please help, im stuck with this for like 2 weeks.
This is my listening thread (Server):
public class ListeningThread implements Runnable {
static boolean listening = true;
public BufferedReader in;
public void run() {
ServerSocket echoServer = null;
String line;
DataInputStream is = null;
PrintStream os = null;
Socket clientSocket = null;
try {
echoServer = new ServerSocket(RequestReciever._communicationPort);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
// As long as we receive data, send it to be phrased to a request.
while (true) {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// An option for a stop listening button. currently not available !
if( listening==true ) {
line = is.readUTF();
os.println(line);
System.out.println(line);
RequestReciever.pharseToRequest(line);
// clientSocket = null;
}
else {
echoServer.close();
is.close();
os.close();
break;
}
}
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Listening Thread Unknown error");
}
}
}
This is my Pharse Method:
public static void pharseToRequest(String input) {
List<String> list = new ArrayList<String>(Arrays.asList(input.split(";;;")));
if (list.get(0).equalsIgnoreCase("Login") && list.get(1).equalsIgnoreCase ("Login") && list.get(2).equalsIgnoreCase("5"))
{
_adminClients.add(list.get(4));
updateScreenCapture();
AdminClientUpdate tmp = new AdminClientUpdate(list.get(4));
Thread aCU = new Thread (tmp);
aCU.start();
}
else
{
ServerRequest newReq = new ServerRequest(list.get(0), list.get(1), Integer.parseInt(list.get(2)),list.get(3),list.get(4));
addRequest(newReq);
}
}
and This is the AdminClientUpdate Class
public class AdminClientUpdate implements Runnable {
static boolean listening = true;
public BufferedReader in;
public String _ip;
public AdminClientUpdate(String ip)
{
_ip = ip;
}
public void run() {
try {
Socket socket = new Socket(_ip, RequestReciever._communicationPort);
InputStream in = new FileInputStream("Capture/tmp.jpg");
java.io.OutputStream out = socket.getOutputStream();
copy(in, out);
System.out.println("Sent Image !");
socket.close();
out.close();
in.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("Cant find tmp.jpg");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void copy(InputStream in, java.io.OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
eliminate this
echoServer.close();
this line closes the socket. due which the connection is aborted.
After a few brain meltdowns , I have decided that putting a server socket on the client side to listen for updates from the server is the best way.
I fixed a few things :
* The server should start a new thread to handle every accepted connection, instead of processing each one in-line in the accept thread.
* I tried to get the first update via the server socket instead of the login initialization.
now, after getting the 1st update while logging in, I added a Server Socket on the client side so it will keep listening for further updates from server.
I'm getting Stream is closed Exception when I'm going to save the uploaded image.
I'm tring to preview graphicImage of uploaded image the before save. This operation is working. But I can't save the image. Here is my code:
private InputStream in;
private StreamedContent filePreview;
// getters and setters
public void upload(FileUploadEvent event)throws IOException {
// Folder Creation for upload and Download
File folderForUpload = new File(destination);//for Windows
folderForUpload.mkdir();
file = new File(event.getFile().getFileName());
in = event.getFile().getInputstream();
filePreview = new DefaultStreamedContent(in,"image/jpeg");
FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void setFilePreview(StreamedContent fileDownload) {
this.filePreview = fileDownload;
}
public StreamedContent getFilePreview() {
return filePreview;
}
public void saveCompanyController()throws IOException{
OutputStream out = new FileOutputStream(getFile());
byte buf[] = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
FileMasterDO fileMasterDO=new FileMasterDO();
fileMasterDO.setFileName(getFile().getName());
fileMasterDO.setFilePath(destination +file.getName());
fileMasterDO.setUserMasterDO(userMasterService.findUserId(UserBean.getUserId()));
fileMasterDO.setUpdateTimeStamp(new Date());
in.close();
out.flush();
out.close();
fileMasterService.save(filemaster);
}
The bean is in the session scope.
You're trying to read an InputStream twice (the first time is in DefaultStreamedContent constructor of upload method and the second time is in the copy loop of the save method). This is not possible. It can be read only once. You need to read it into a byte[] first and then assign it as a bean property so that you can reuse it for both the StreamedContent and the save.
Make sure that you never hold external resources such as InputStream or OutputStream as a bean property. Remove them all from the current and other beans where applicable and use byte[] to hold the image's content as property.
In your particular case, you need to fix it as follows:
private byte[] bytes; // No getter+setter!
private StreamedContent filePreview; // Getter only.
public void upload(FileUploadEvent event) throws IOException {
InputStream input = event.getFile().getInputStream();
try {
IOUtils.read(input, bytes);
} finally {
IOUtils.closeQuietly(input);
}
filePreview = new DefaultStreamedContent(new ByteArrayInputStream(bytes), "image/jpeg");
// ...
}
public void saveCompanyController() throws IOException {
OutputStream output = new FileOutputStream(getFile());
try {
IOUtils.write(bytes, output);
} finally {
IOUtils.closeQuietly(output);
}
// ...
}
Note: IOUtils is from Apache Commons IO, which you should already have in the classpath as it's a dependency of <p:fileUpload>.
I am new to jsf and I am setting up a basic reporting tool (sql queries) which shows a list of reports in the home page. I want to put an excel export commandbutton in the home page and export the report selected by the user or drive the user to a different execution page to show results in a datatable for the selected report. How can I achieve that? datatable with query results, of course, is visible only in the execution page and is dynamically created during query execution (this part works fine). Am I going crazy for nothing? Thanks in advance for any suggestion.
If you want to export data to Excel you need to use a third party library. There are free ones like JExcelApi and Apache POI. Also, there are commercial libraries like Aspose. If you're going to choose an open source library check this question: Choosing an excel java api.
When you export data to Excel, you must create the Excel file and download the content for the client. You can check how to download a file using JSF by #BalusC (JSF expert).
One more advice, when you're downloading a file don't add ajax functionality to the command link/button.
You can use under code this code block provide excel export as genericly way. You can send any List and send any fileName
public class ExcelUtils {
public static <T> void writeToExcel(String fileName, List<T> data) {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
response.setHeader("Pragma", "no-cache");
OutputStream fos = null;
try {
fos = response.getOutputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
XSSFWorkbook workbook = null;
try {
// File file = new File(fileName);
workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
List<String> fieldNames = getFieldNamesForClass(data.get(0).getClass());
int rowCount = 0;
int columnCount = 0;
Row row = sheet.createRow(rowCount++);
for (String fieldName : fieldNames) {
if (!fieldName.equals("serialVersionUID")) {
Cell cell = row.createCell(columnCount++);
cell.setCellValue(fieldName);
}
}
Class<? extends Object> classz = data.get(0).getClass();
for (T t : data) {
row = sheet.createRow(rowCount++);
columnCount = 0;
for (String fieldName : fieldNames) {
if (!fieldName.equals("serialVersionUID")) {
Cell cell = row.createCell(columnCount);
Method method = null;
try {
method = classz.getMethod("get" + capitalize(fieldName));
} catch (NoSuchMethodException nme) {
method = classz.getMethod("get" + fieldName);
}
Object value = method.invoke(t, (Object[]) null);
if (value != null) {
if (value instanceof String) {
cell.setCellValue((String) value);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
} else if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
}
}
columnCount++;
}
}
}
workbook.write(fos);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
context.responseComplete();
context.renderResponse();
}
} catch (IOException e) {
}
try {
if (workbook != null) {
workbook.close();
}
} catch (IOException e) {
}
}
}
// retrieve field names from a POJO class
private static List<String> getFieldNamesForClass(Class<?> clazz) throws Exception {
List<String> fieldNames = new ArrayList<String>();
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fieldNames.add(fields[i].getName());
}
return fieldNames;
}
// capitalize the first letter of the field name for retriving value of the
// field later
private static String capitalize(String s) {
if (s.length() == 0)
return s;
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}