Hi friends i am new to web services, their is requirement in my project that a webservice should be created which does some database interaction process and business logic than it has to send an excel file to the requested client [file should be downloaded on to client meachine].
I know we can send attachment in both SOAP and RESTFULL. i want to know which is the best method to send excel file and how to send it sample code so that i can get idea.
I know web service communicate through xml i want to know that convert excel file to xml and send it to client from their client convert it again to excel is that method ok from both performance and efficient point of view.
Finally i want to know which is the best method to achieve it and sample code so that i can work on it.
Updated question
This is my web service method in project A
#Path("/todo")
public class TodoResource
{
#GET
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getfile(){
File file =new File("D:\\Test.xls"); // Initialize this to the File path you want to serve.
return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM).build();
}
}
This in project B where i created client
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
System.out.println(">>>>>>>>>>>>>>>>>Starting of Project Test Call >>>>>>>>>>>>>>>>>");
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
//Get Excel Download
System.out.println(":::::: The Application APPLICATION_OCTET_STREAM Response :::::: ");
System.out.println(service.path("rest").path("todo").accept(MediaType.APPLICATION_OCTET_STREAM).get(String.class));
System.out.println(">>>>>>>>>>>>>>>>>Ending of Project Test Call >>>>>>>>>>>>>>>>>");
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/WebService_XML").build();
}
my requirement is the client will send some info like parameter 1,parameter 2 etc. based on that it will interact with database and a file will be created. and that file should be send to client.like on click call webservice process it send that file to client, browser download popup window will appear to save or open should appear. on click save save it.
Got The Solution check here
but what about client,can any client[.net, php etc] can access this.
Related
On button click I would like to call my Service to query database and generate csv file and return in back to user. This process is long running (can take up to 40 sec) I would like not to block user . I would lik to create Progress page, where user can tack a progress of report generation:
My idea is:
Take input from user and submit createReport request to the Service.
Do not wait for the response, return report ID back to user.
The new tab will be open, where user can monitor the status of report generation
User can check the report page to see the status of his request
When request is ready - downloading of report will start in browser.
I would like to have smth like this:
a. Controller method that save the file and return file id.
After that, in this contorller the new thread will call Service and write data to the given file
b. Controller method that show report's status using request params - fileId
Check if file generated or not
If file is generated - write file to the HttpServletResponse response
Question is:
Where should I store file ID and how to connect file ID and file itself? (cache? database?)
How can I check report status? I think about sending AJAX request every 1-2 sec?
Any ideas and recommendations ?
According to me, you can create a servlet to respond with CSV file download. Consider the following process:
On button click open new tab with url (append url with reportId or so)
window.open('/downloadCSV/15646', '_blank');
And then write a servlet for this downloading operation
#RequestMapping(path = "/downloadCSV/{reportId}", method =
RequestMethod.GET)
public void getCSV(#PathVariable String reportId, HttpServletRequest
request, HttpServletResponse response) throws Exception {
byte[] fileContent;
//write your logic or call service to generate csv report and get
bytes of file
response.setContentType("provide content type");
ServletOutputStream out = response.getOutputStream();
out.write(fileContent);
out.flush();
return;
}
this will download the file in opened tab
I have written a java program with HttpRequest using HttpURLConnection to download/upload a file of any format(XML, Image, Documents) from a specific server using it's authentication API-KEY. This program works fine. Now i need to upload this java program file in to my website as a cloud service and need to be able to download the file from that server using this java program file which is uploaded into this website. How can i do it? One thing to make sure is the java program that i wrote is not a web application, it is just a java program.
For Downloading a file Create a function like this as follows:
private void exportExcel(HttpServletResponse response, HSSFWorkbook workbook) throws CpaServiceException{
try{
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + workbook.getSheetAt(0).getSheetName()+".xls");
workbook.write(response.getOutputStream());
}catch(IOException e){
throw new CpaServiceException(CpaConstants.APPLICATION_GENERAL_ERROR);
}
}
Then Call the function as:
#RequestMapping(value = "/"+ControllerPaths.GET_EXCEL_FOR_COMMON_PROCESS_SYSTEM_REPORT, method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public void getExcelForCommonProcessSystemReport(HttpServletRequest request, HttpServletResponse response, CpaReportFilterDTO filterDTO) throws Exception{
exportExcel(response, reportService.generateExcelForReport(filterDTO));
}
The above code is a sample one. You can do it the similar way to download a document form the browser.
I'm working with an organization's payment API. The API automatically posts a soap request to our server when a customer makes payment and I response with an acknowledgement message in xml. (Check out the screenshots show a simple demonstration in SOAP UI)
SOAP UI Test Response
SOAP UI Test Raw XML
I made this code in Java to receive the soap request and send a response.
`public class testsoap extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/xml;charset=UTF-8");
ServletInputStream out = request.getInputStream();
String xmlrpc = "";
int c = 0;
while((c = out.read()) != -1 ){ xmlrpc += (char)c; }
int startTag = xmlrpc.indexOf("<TransID>");
int endTag = xmlrpc.indexOf("</TransID>");
String parameter = xmlrpc.substring(startTag,endTag).replaceAll("<TransID>","");
String result="";
//result +="<?xml version=\"1.0\"?>\n";
result +="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:c2b=\"http://cps.huawei.com/cpsinterface/c2bpayment\">\n";
result +="<soapenv:Header/>\n";
result +="<soapenv:Body>\n";
result +="<c2b:C2BPaymentConfirmationResult>C2B Payment Transaction "+parameter+" result received.</c2b:C2BPaymentConfirmationResult>\n";
result +="</soapenv:Body>\n";
result +="</soapenv:Envelope>\n";
response.getWriter().println(result);
}
}`
Now I need to add the location of my keystore and truststore.
Should I add this code just before I start preparing a response?
` System.setProperty("javax.net.ssl.keyStore",path_to_keystore);
System.setProperty("javax.net.ssl.keyStorePassword",akeystorepassword);
System.setProperty("javax.net.ssl.trustStore",path_to_your_cacerts_file);
System.setProperty("javax.net.ssl.trustStorePassword",atrustsorepassword)`
Or do I need to make a snippet that makes secure connection using the keystore and truststore rather than just setting a system property?
Create a Java class and write all the functionalities that you need to publish as a methods. Then you need to publish those functionalities as a WSDL to be consumed by your clients. See the following tutorial that will take you in step by step to publish a web services:
Step by Step JAX-WS Web Services with Eclipse, TomEE, and Apache CXF
Building a Simple Web Service ? A Tutorial
Implementing a simple web service
Further based on your requirements you can have complex object as an input parameter like C2BPaumentConfirmationRequest and KYCInfo in your case
I'm doing a project in java in which I implemented a chat, everything works perfectly only when I receive messages I can not print the web page.
In my Servlet I have a callback method that is invoked when messages arrive, in fact if you see mold them in the console, but if you are sending them to the jsp using the RequestDispatcher can not get them to see.
I would like to know if there is a system that the jsp page listens for a callback method in the servlet?
Obviously, this system should not be constantly invoke the class I have something absurd like that.
So that I can print the messages I receive.
This is my code I put a comment where I should print eventually find in jsp page, or do a redirect by passing parameters post or get
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strJid = (String) request.getParameter("jid");
String strMessage = (String) request.getParameter("textMessage");
Connection connection = (Connection)getServletContext().getAttribute("classConnection");
ChatManager chatManager = connection.getChatManager();
Chat newChat = chatManager.createChat(strJid, new MessageListener(){
#Override
public void processMessage(Chat chat, Message message){
//from here I have to print the message.getBody () in jsp page,
//how can I do? I'm happy also reload the page and pass as a parameter to get or post
}
});
try{
newChat.sendMessage(strMessage);
}
catch(XMPPException e){
System.out.println("Errore invio messaggio");
}
}
To implement a callback method in your servlet to receive chat messages is the wrong approach. A servlet will be called once for a browser request, creates the HTML page and send it back to the browser. After that there is no such kind of a connection between the servlet and the web page.
In traditional web programming all communication between browser and server is intiated by the client. There is no way for the server to send a message to the client. Workarounds are long polling requests.
But nowadays you can use Websockets. There are several frameworks supporting Websockets both for client and server side. One of them is Atmosphere. Their tutorial is a chat application.
I am looking for an example on deploying a report unit to JasperServer using it's SOAP Services, preferably with a java client.
I found a way to do that with JasperServer WebServices (Set of SOAP services for managing server and data on it).
So ... the unit of data used to communicate with the server is com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor... which represents a resource... implementation of client is the following com.jaspersoft.jasperserver.irplugin.wsclient.WSClient...
to make it a bit clearer here is the code :
public void publishImage() throws Exception {
ResourceDescriptor rd = new ResourceDescriptor();
rd.setName("coffeepicture");
rd.setLabel("Coffee picture from java");
rd.setResourceType(ResourceDescriptor.TYPE_IMAGE);
rd.setMainReport(true);
rd.setParentFolder("/Samples");
rd.setUriString(rd.getParentFolder() + rd.getName());
rd.setWsType(ResourceDescriptor.TYPE_IMAGE);
rd.setIsNew(true);
rd.setHasData(true);
File image = new File("/home/coffee.jpg");
client.addOrModifyResource(rd, image);
}
The code above shows how to upload an image to the server, to deploy a report you will need to create separate ResourceDescriptors for .jrxml file and datasource if any...
Regards!