how to execute c++ code at server side using tomcat server? - c++

I am a beginner in writing web application, so please co-operate if its a silly question. Our web application is hosted using tomcat 6. I have some C++ code to be executed in server when user click on corresponding button. Client side is written in html/JS and hosted using tomcat.
So, My problem is I dont know how this C++ code will be executed when a button is clicked in html page. Can anyone please help me?
[updated]
I can change from tomcat to any other server but code has to be in c++. So if you have any other server(wamp or smthing) or links to do the same. Please let me know

Tomcat, a Java Servlet container is definitely not the most appropriate vehicle to execute C++ code in. You could try to use JNI to make a servlet run the C++ code, but it seems to me that there are much easier and reliable ways, like good old CGI's. Tomcat can do CGI, as explained here, with some limitations and restrictions.
Update: I think we can agree that the CGI route is the way to go. Most webservers allow you to run cgi's, and it will definitely be simpler than with Tomcat. I also suggest you delegate the work of connecting your code to the web server to a library, like gnu cgicc (nice tutorial here) or cgic. A plain old WAMP (you'll just use the WA part here) and that sample code should get you up to speed in no time. The rest will be pretty standard Web development.

https://stackoverflow.com/questions/175507/c-c-web-server-library answers may well help you out.
Given that Tomcat is no longer a requirement, using a different http front end may well make your life easier.
If you do decide to use Tomcat Which C++ Library for CGI Programming? may help you pick a library.
Barring that, if you use Apache, you can write a plugin module itself, instead of CGI, which will give you much better performance. (Other web servers generally have similar plug-in methodologies also...)
Good Luck

I'm not sure any of these answers addressed the question. Coding a CGI using C++ would mean reading environment variables that are set by the web server, regardless of whether or not you use a third party library or which web server is run, including tomcat. The following example is a quick-and-dirty way to grab the most interesting input, the query string. If you are starting out, it's I think better to start with basics so if you decide to use some sort of external library it will seem less mystical. This should give you enough to hit google and work out what's happening.
#include <stdlib.h>
#include <iostream>
using namespace std;
int
main(int argc, char** argv)
{
string method = getenv("REQUEST_METHOD");
string query;
if (method == "GET")
query = getenv("QUERY_STRING");
else if (method == "POST")
cin >> query;
else
query = "Not sure what to do with method " + method;
cout << "Content-Type: text/html" << endl << endl
<< "<html>" << endl
<< query << endl
<< "</html>" << endl;
}
Note Content-Type in the output. That's a HTTP header. You can add any number of headers before the double endl. For a light bulb moment try changing Content-Type to text/plain.
Compile the example code to shiney_cpp_cgi, copy it to your cgi dir (for tomcat that's generally tomcat_root/webapps/ROOT/WEB-INF/cgi), then hit it with your browser as such to use the GET method:
myserver.mydomain:myport/cgi-bin/shiney_cpp_cgi?foo=bar
To send in a post request, use CURL as such:
curl --data 'foo=bar' myserver.mydomain:myport/cgi-bin/shiney_cpp_cgi
To serve C++ from tomcat, you can edit tomcat_root/conf/web.xml and change executable to an empty string. By default, tomcat will try to run your C++ as a perl script, which perl will (hopefully!) not be able to parse.
<servlet>
<servlet-name>cgi</servlet-name>
<servlet-class>org.apache.catalina.servlets.CGIServlet</servlet-class>
...
<init-param>
<param-name>executable</param-name>
<param-value></param-value>
</init-param>
...
</servlet>

Related

c++ send request to API on webserver then receive json array response?

I'm wondering the most simple way to send a request to a API on my server then receive the API's response (json array) wihtout using any libraries. I've tried using libs like cURL & boost without any luck which is the reason i want to stay away from them. I've searched for many days for a answer and have not been able to find anything, which is why i've resorted to coming to the stack overflow community!
Even though the question is about not using a library I 'am taking this opportunity to show how easy it is to use a library than the user thinks.
Its better to use pre-built libraries and stop reinventing the wheel. You can use curlcpp library. Its a wrapper for libcurl. Using this library HTTP requests can be made easily. Learning curve is also less and it provides C++ style access which makes it more comfortable to work with.
The following code is taken from their gitHub page - https://github.com/JosephP91/curlcpp
It makes a simple GET request to Google and retrieves the HTML response. You can use this example to hit apis too.
#include "curl_easy.h"
#include "curl_exception.h"
using curl::curl_easy;
using curl::curl_easy_exception;
using curl::curlcpp_traceback;
int main(int argc, const char **argv) {
curl_easy easy;
// Add some option to the curl_easy object.
easy.add<CURLOPT_URL>("http://www.google.it");
easy.add<CURLOPT_FOLLOWLOCATION>(1L);
try {
// Execute the request.
easy.perform();
} catch (curl_easy_exception error) {
// If you want to get the entire error stack we can do:
curlcpp_traceback errors = error.get_traceback();
// Otherwise we could print the stack like this:
error.print_traceback();
// Note that the printing the stack will erase it
}
return 0;
}

Persisting data in an axis object

Forgive me if this is a dumb question, I unfortunately have an assignment due! I am running apache axis under tomcat and need to deploy a simple web service class, see below.
I installed the counter file below as "MyCounter.jws" in the /tomcat/webapps/axis/ folder. Tomcat finds it and makes a corresponding MyCounter.xml. I use WSDL2Java on the XML file and client calls seem to work, but internal state is not saved:
Every time I call MyCounter.call from the client side, the return value is always 1. It seems the constructor is always called before the method call. How can I make it so the mycounter integer persists across requests?
public class MyCounter
{
int mycounter;
public MyCounter()
{
mycounter = 0;
}
public int call()
{
mycounter++;
return mycounter;
}
}
I think persisting is maybe the wrong word, I think what you mean is that the Java Class is not instantiated every time you call the service.
See: https://axis.apache.org/axis/java/user-guide.html#Scoped_Services
So you would need to change the Service definition yo achieve this.
I don't think that with the JWS files you will be able to configure the session scope. As the docs say:
https://axis.apache.org/axis/java/user-guide.html#JWS_Java_Web_Service_Files_-_Instant_Deployment
Quote:
Important: JWS web services are intended for simple web services. You
cannot use packages in the pages, and as the code is compiled at run
time you can not find out about errors until after deployment.
Production quality web services should use Java classes with custom
deployment.
So if you want to use such features you should consider using some of the other ways Axis offers to setup a WebService.
Also I would strongly recommend using Axis2 instead of Axis1:
http://axis.apache.org/axis2/java/core/
Axis1 can be quite complicated with the WSDD files to setup. Apart from Axis1 no more actively developed/maintained.

How to call Soap\WSDL Service through a login required webpage using matlab?

I am new to the wsdl\soapmessage query\reply world( if i can put it in this way), and I am facing some difficulties using the following wsdl( which I really really hope, one will be so kind to look at at least one of the services described there)
http://almdemo.polarion.com/polarion/ws/services/TrackerWebService?wsdl
which was provided to me to develop a matlab webinterface. Right now my matlab code looks like this:
targetNamespace = 'http://ws.polarion.com/TrackerWebService';
method = 'queryWorkItems';
values= {'Query','Sort'}
names = {'query', 'sort'}
types ={'xsd:string','xsd:string'}
message = createSoapMessage( targetNamespace, method, values, names, types)
response = callSoapService('http://almdemo.polarion.com/polarion/ws/services',...
% Service's endpoint
'http://almdemo.polarion.com/polarion/#/workitems',...
% Server method to run
message)
% SOAP message created using createSoapMessage
author = parseSoapResponse(response)
Herewith to save you time I will just enonce my two problems:
Is the code correct?
Could someone tell me if such a wsdl link is just a definition of webservices or it is also a service's endpoint?
Normally to execute manually\per clicks this services on the weppage
http://almdemo.polarion.com/polarion, you have to login!
So how do I send a message in matlab which first log me in? Or must such a service be introduced into that wsdl for me to do it?? Could you be kind enough to write how it must be defined, because I don't really
write wsdl files, but I shall learn!**
I will be really thankful for your help and I wish you a happy week(-end) guys(& girls)!!!
Regards
Chrysmac
ps: I tried to use Soapui and gave that webpage as endpoint, but the toool crashes each time I enter my credentials! Maybe because of the dataload!??

Creating simple WebService in C++ / Qt (acting as server) providing JSON data

I need to create a simple web service (being the "server"). The goal is to provide some data I do read in an Qt / C++ application as JSON data. Basically a JavaScript application in the browser shall read its data from the Qt app. It is usually a single user scenario, so the user runs a Google Maps application in her browser, while additional data come from the Qt application.
So far I have found these libs:
Qxt: http://libqxt.bitbucket.org/doc/0.6/index.html but being a newbie on C++/Qt I miss some examples. Added: I have found one example here
gSoap: http://www.cs.fsu.edu/~engelen/soap.html has more examples and documentation and also seems to support JSON
KD SOAP: http://www.kdab.com/kdab-products/kd-soap/ with no example as far as I can tell, docu is here
Qt features itself, but it is more about acting as a client: http://qt-project.org/videos/watch/qt-networking-web-services
Checking SO gives me basically links to the above libs
webservice with Qt with an example I do not really get.
How to Create a webservice by Qt
So basically I do have the following questions:
Which lib would you use? I want to keep it as simple as possible and would need an example.
Is there another (easy!) way to provide the JSON data to the JavaScript Web page besides the WebService?
-- Edit, remarks: ---
Needs to be application intrinsic. No web server can be installed, no extra run time can be used. The user just runs the app. Maybe the Qt WebKit could be an approach....
-- Edit 2 --
Currently checking the tiny web servers as of SO " Qt HTTP Server? "
As of my tests, currently I am using QtWebApp: http://stefanfrings.de/qtwebapp/index-en.html This is one of the answers of Edit 2 ( Qt HTTP Server? )
Stefan's small WebServer has some well documented code, is written in "Qt C++" and easy to use, especially if you have worked with servlets already. Since it can be easily integrated in my Qt project, I'll end up with an internal WebServer.
Some demo code from my JSON tests, showing that generating the JSON content is basically creating a QString.
void WebServiceController::service(HttpRequest& request, HttpResponse& response) {
// set some headers
response.setHeader("Content-Type", "application/json; charset=ISO-8859-1");
response.setCookie(HttpCookie("wsTest","CreateDummyPerson",600));
QString dp = WebServiceController::getDummyPerson();
QByteArray ba = dp.toLocal8Bit();
const char *baChar = ba.data();
response.write(ba);
}
If someone has easy examples with other libs to share, please let me know.
QByteArray ba = dp.toLocal8Bit();
const char *baChar = ba.data();
You don't need to convert the QByteArray to char array. Response.write() can also be called with a QByteArray.
By the way: qPrintable(dp) is a shortcut to convert from QString to char array.

X-Requested-With/HTTP_X_REQUESTED_WITH weird problem

I'm building a Django site and trying to use the request.is_ajax() function... But it's only working locally and it's driving me crazy!
I'm at the point where I've just dumped the headers. Here (on the django test server) there's HTTP_X_REQUESTED_WITH but on the production server (cherokee+scgi) all I get is X-Requested-With.
I've used firebug to snoop the sent headers and it's X-Requested-With (on both versions of the site). I'm very, very confused. Can anybody explain what's happening and how I can work around it without losing my mind?
wrt/ the X-Requested-With => HTTP_X_REQUESTED_WITH stuff, it's in conformance with the CGI specifications. Since FastCGI, SCGI and WSGI are all based on the CGI specs, Django developpers choosed to stick to this convention (FWIW, the ModPythonRequest class do the same rewrite for consistency).
So it seems that your problem is that something in the cherokee/scgi chain doesn't rewrite the headers correctly. Which scgi implemetation are you using ?
I'm currently working around the issue with a tiny bit of MiddleWare that essentially looks for the "wrong" header and if it exists, appends a new header of the same value:
if 'X-Requested-With' in request.META:
request.META['HTTP_X_REQUESTED_WITH'] = request.META['X-Requested-With']
But I really wish I knew what was supposed to happen with these headers because X-Requested-With is always sent... I don't see why that should be translated in to HTTP_X_REQUESTED_WITH and why it's not.
Edit: The cause appears to be deep within the actual web server.
case 'X':
if (header_equals ("X-Forwarded-For", header_x_forwarded_for, begin, header_len)) {
ret = add_known_header (hdr, header_x_forwarded_for, val_offs, val_len);
} else if (header_equals ("X-Forwarded-Host", header_x_forwarded_host, begin, header_len)) {
ret = add_known_header (hdr, header_x_forwarded_host, val_offs, val_len);
} else
goto unknown;
break;
I've filed a bug to get my header added but should all X-* headers be converted into HTTP_X_* headers?