Web service client (applet) keeps asking for "/META-INF/services/javax.xml.ws.spi.provider" - applet

Consider the following snippet running in an applet insdie a browser:
WebServiceClient s = MyWS_Service.class.getAnnotation(WebServiceClient.class);
String servicePath = pathName;
String wsdlLocation = "http//host.dns.name:80/MYWSAPP/MyWS?wsdl";
MyWS_Service service = null;
WebServiceClient s = MyWSService.class.getAnnotation(WebServiceClient.class);
try{
wsdlURL = new URL(wsdlLocation);
service = new myWSService(wsdlURL, new QName(s.targetNamespace(), s.name()));
myWS = service.getMyWSSOAP();
}catch (MalformedURLException e){
System.out.println ("unable to create wsdlURL = "+wsdlLocation);
}
If myWS was created without problems, I use it to make calls to the web service methods (the web service uses Metro and runs on Tomcat).
Everything works fine except that I noticed the following two irritants:
It takes a long time to execute the chunk of code quoted above
Network traces show the client sends HTTP GET requests for:
/MYWSAPP/META-INF/services/javax.xml.ws.spi.provider and /MYWSAPP/META-INF/services/javax.xml.stream.XMLInputFactory.
The reply for these GET requests is HTTP/1.1 404 Not Found.
Any thoughts on how to prevent these needless HTTP GET requests? Also is it reasonable that the code above takes roughly 3 seconds to execute while the actual web service calls take less than 100ms to execute?

Pass this parameter to the applet:
codebase_lookup = false

Related

vertx timeout if async result is failed

I am seeing a timeout in the browser when the server-side service ends in a failed result. Everything works fine if the service call succeeds but it seems as though the browser never receives a response if the call fails.
My service passes a result handler to a DAO containing the following code:
final SQLConnection conn = ar.result();
conn.updateWithParams(INSERT_SQL, params, insertAsyncResult -> {
if (insertAsyncResult.failed()) {
conn.close();
resultHandler.handle(ServiceException.fail(1, "TODO"));
} else {
resultHandler.handle(Future.succeededFuture());
}
});
I'm not sure where to go from here. How do I debug what the framework is sending back to the client?
The problem was that I needed to register a ServiceExceptionMessageCodec in an intermediate Verticle, one that was sitting between the browser and the Verticle that was performing the database operation.

Sharepoint REST getfilebyid sometimes returns - 404 - not found

I'm trying to download the file by it's unique id (GUID) and in 99% it's working fine, but there some cases where I'm getting http not found - 404. But I know that file is exists and I know it's unique id, from the metadata I got from the document library.
How file can't be found if I have it's metadata in hands ?
I'm doing the next (Java):
//itemID is taken from the library listing (using web service) as uniqueid (guid)
String requestUrl = site + "/_api/web/GetFileById('" + itemID.substring(1, itemID.lastIndexOf('}')) + "')/$value"; //Remove {} from the unique id
HttpGet request = new HttpGet(requestUrl);
// setting auth credentials to the request.
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).build();
request.setConfig(requestConfig);
request.addHeader("accept", "application/json; odata=verbose");
HttpResponse result = httpClient.execute(request);
int iRet = result.getStatusLine().getStatusCode(); //Here iRet = 404, sometimes.
Thanks
From previous experience I would look for a lock by concurrent connections. I see you have a 60 s timeout (setConnectTimeout(60000)) in your code. For instance, have you tried if having a single query returns a valid result, and after (say 120s) you try twice within the 60s timeout, it returns the 404?

Jena API with REST webservice using Jersey

I am using Jena API to get RDF data from Allegrograph Server. I have written a REST webservice using Jersey jar to get this data.
My java code for the webservice is as shown below:
#GET
#Path("/JENA")
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String getData() throws RepositoryException {
AGGraphMaker maker = new AGGraphMaker(conn);
AGGraph graph = maker.getGraph();
AGModel model = new AGModel(graph);
AGQuery agQuery = AGQueryFactory.create(query);
QueryExecution qe = AGQueryExecutionFactory.create(agQuery, model);
String result = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
ResultSet rs = qe.execSelect();
While(rs.hasNext()){
byteArrayOutputStream = new ByteArrayOutputStream();
if("JSON".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsJSON(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
System.out.println("Result is "+result);
} else if("XML".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsXML(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
}else if("CSV".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsCSV(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
I get no results for the SPARQL query when I deploy this web service on Tomcat server and test it using REST client app on Chrome and firefox.
But the same code(absolutely no difference in webservice code and this main method code) if I write in a plain java class and run its main method, i am getting 36 results. I am not sure what the issue is.
Please help me in this regard.
You need to separate the concerns:
Move the service logic - the bit that actually queries Allegro graph - to a separate class so that it's properly encapsulated. The API for the class should reflect its responsibilities in your application, not the way that it happens to be working at the moment.
Write JUnit tests for the service class. This is important - it gives you confidence that your service is performing its job correctly, and keeps on doing so as you develop your application.
Write your Jersey method to invoke any service object that conforms to the API of your service class.
Write one or more HTTPUnit (or similar) tests to invoke your REST API. Ideally, you'll use a mock or test double instead of the actual service. What you want to test is whether the HTTP request reaches the right method, and that method delegates to the service object with the right arguments. You're then testing (and debugging!) a smaller number of concerns.
It's much better to work with small units of functionality with a clear idea of what their responsibilities are. And you should definitely learn to work with tests - it's a big win in the medium term, even if it means a bit more learning up front!

gwt: making remote calls fails - sop?

I am writing some interface for users to collect data and send to a server. I went for GWT for various reasons.
Now, when I try to call my server:
String url = "http://127.0.0.1:3000/data/collection.xml";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
Request request = builder.sendRequest(data, new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
result.setText("SUCCESS!");
} else {
result.setText("ERROR with code: " + response.getStatusCode());
My server gets the request (a POST with some data) but I get ERROR with code: 0 (!) all the time. I guess this has to do with SOP. I read lots about this SOP but I am even more confused now. I tried to follow this tutorial but that's using a different approach (I managed to adapt it to issue GET calls only, but return objects are always null).
Can anyone point me into the right direction? thanks
You can not call any service from another server because of SOP. What you can do, you can use your original server as proxy to other servers.. I would recommend you to read this tutorial.

Help with a Windows Service/Scheduled Task that must use a web browser and file dialogs

What I'm Trying To Do
I'm trying to create a solution of any kind that will run nightly on a Windows server, authenticate to a website, check a web page on the site for new links indicating a new version of a zip file, use new links (if present) to download a zip file, unzip the downloaded file to an existing folder on the server, use the unzipped contents (sql scripts, etc.) to build an instance of a database, and log everything that happens to a text file.
Forms App: The Part That Sorta Works
I created a Windows Forms app that uses a couple of WebBrowser controls, a couple of threads, and a few timers to do all that except the running nightly. It works great as a Form when I'm logged in and run it, but I need to get it (or something like it) to run on it's own like a Service or scheduled task.
My Service Attempt
So, I created a Windows Service that ticks every hour and, if the System.DateTime.Now.Hour >= 22, attempts to launch the Windows Forms app to do it's thing. When the Service attempts to launch the Form, this error occurs:
ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.
which I researched and tried to resolve by either placing the [STAThread] attribute on the Main method of the Service's Program class or using some code like this in a few places including the Form constructor:
webBrowseThread = new Thread(new ThreadStart(InitializeComponent));
webBrowseThread.SetApartmentState(ApartmentState.STA);
webBrowseThread.Start();
I couldn't get either approach to work. In the latter approach, the controls on the Form (which would get initialized inside IntializeComponent) don't get initialized and I get null reference exceptions.
My Scheduled Task Attempt
So, I tried creating a nightly scheduled task using my own credentials to run the Form locally on my dev machine (just testing). It gets farther than the Service did, but gets hung up at the File Download Dialog.
Related Note: To send the key sequences to get through the File Download and File Save As dialogs, my Form actually runs a couple of vbscript files that use WScript.Shell.SendKeys. Ok, that's embarassing to admit, but I tried a few different things including SendMessage in Win32 API and referencing IWshRuntimeLibrary to use SendKeys inside my C# code. When I was researching how to get through the dialogs, the Win32 API seemed to be the recommended way to go, but I couldn't figure it out. The vbscript files was the only thing I could get to work, but I'm worried now that this may be the reason why a scheduled task won't work.
Regarding My Choice of WebBrowser Control
I have read about the System.WebClient class as an alternative to the WebBrowser control, but at a glance, it doesn't look like it has what I need to get this done. For example, I needed (or I think I needed) the WebBrowser's DocumentCompleted and FileDownload events to handle the delays in pages loading, files downloading, etc. Is there more to WebClient that I'm not seeing? Is there another class besides WebBrowser that is more Service-friendly and would do the trick?
In Summary
Geez, this is long. Sorry! It would help to even have a high level recommendation for a better way to do what I'm trying to do, because nothing I've tried has worked.
Update 10/22/09
Well, I think I'm closer, but I'm stuck again. I should end up with a decent-sized zip file with several files in it, but the zip file resulting from my code is empty. Here's my code:
// build post request
string targetHref = "http://wwwcf.nlm.nih.gov/umlslicense/kss/login.cfm";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetHref);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// encoding to use
Encoding enc = Encoding.GetEncoding(1252);
// build post string containing authentication information and add to post request
string poststring = "returnUrl=" + fixCharacters(targetDownloadFileUrl);
poststring += getUsernameAndPasswordString();
poststring += "&login2.x=0&login2.y=0";
// convert to required byte array
byte[] postBytes = enc.GetBytes(poststring);
request.ContentLength = postBytes.Length;
// write post to request
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
// get response as stream
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// writes stream to zip file
FileStream writeStream = new FileStream(fullZipFileName, FileMode.Create, FileAccess.Write);
ReadWriteStream(responseStream, writeStream);
response.Close();
responseStream.Close();
The code for ReadWriteStream looks like this.
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
// taken verbatum from http://www.developerfusion.com/code/4669/save-a-stream-to-a-file/
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
The building of the post string is taken from my previous forms app that works. I compared the resulting values in poststring for both sets of code (my working forms app and this one) and they're identical.
I'm not even sure how to troubleshoot this further. Anyone see anything obvious as to why this isn't working?
Conclusion 10/23/09
I finally have this working. A couple of important hurdles I had to get over. I had some problems with the ReadWriteStream method code that I got online. I don't know why, but it wasn't working for me. A guy named JB in Claudio Lassala's Virtual Brown Bag meeting helped me to come up with this code which worked much better for my purposes:
private void WriteResponseStreamToFile(Stream responseStreamToRead, string zipFileFullName)
{
// responseStreamToRead will contain a zip file, write it to a file in
// the target location at zipFileFullName
FileStream fileStreamToWrite = new FileStream(zipFileFullName, FileMode.Create);
int readByte = responseStreamToRead.ReadByte();
while (readByte != -1)
{
fileStreamToWrite.WriteByte((byte)readByte);
readByte = responseStreamToRead.ReadByte();
}
fileStreamToWrite.Flush();
fileStreamToWrite.Close();
}
As Will suggested below, I did have trouble with the authentication. The following code is what worked to get around that issue. A few comments inserted addressing key issues I ran into.
string targetHref = "http://wwwcf.nlm.nih.gov/umlslicense/kss/login.cfm";
HttpWebRequest firstRequest = (HttpWebRequest)WebRequest.Create(targetHref);
firstRequest.AllowAutoRedirect = false; // this is critical, without this, NLM redirects and the whole thing breaks
// firstRequest.Proxy = new WebProxy("127.0.0.1", 8888); // not needed for production, but this helped in order to debug the http traffic using Fiddler
firstRequest.Method = "POST";
firstRequest.ContentType = "application/x-www-form-urlencoded";
// build post string containing authentication information and add to post request
StringBuilder poststring = new StringBuilder("returnUrl=" + fixCharacters(targetDownloadFileUrl));
poststring.Append(getUsernameAndPasswordString());
poststring.Append("&login2.x=0&login2.y=0");
// convert to required byte array
byte[] postBytes = Encoding.UTF8.GetBytes(poststring.ToString());
firstRequest.ContentLength = postBytes.Length;
// write post to request
Stream postStream = firstRequest.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length); // Fiddler shows that post and response happen on this line
postStream.Close();
// get response as stream
HttpWebResponse firstResponse = (HttpWebResponse)firstRequest.GetResponse();
// create new request for new location and cookies
HttpWebRequest secondRequest = (HttpWebRequest)WebRequest.Create(firstResponse.GetResponseHeader("location"));
secondRequest.AllowAutoRedirect = false;
secondRequest.Headers.Add(HttpRequestHeader.Cookie, firstResponse.GetResponseHeader("Set-Cookie"));
// get response to second request
HttpWebResponse secondResponse = (HttpWebResponse)secondRequest.GetResponse();
// write stream to zip file
Stream responseStreamToRead = secondResponse.GetResponseStream();
WriteResponseStreamToFile(responseStreamToRead, fullZipFileName);
responseStreamToRead.Close();
sl.logScriptActivity("Downloading update.");
firstResponse.Close();
I want to underscore that setting AllowAutoRedirect to false on the first HttpWebRequest instance was critical to the whole thing working. Fiddler showed two additional requests that occurred when this was not set, and it broke the rest of the script.
You're trying to use UI controls to do something in a windows service. This will never work.
What you need to do is just use the WebRequest and WebResponse classes to download the contents of the webpage.
var request = WebRequest.Create("http://www.google.com");
var response = request.GetResponse();
var stream = response.GetResponseStream();
You can dump the contents of the stream, parse the text looking for updates, and then construct a new request for the URL of the file you want to download. That response stream will then have the file, which you can dump on the filesystem and etc etc.
Before you wonder, GetResponse will block until the response returns, and the stream will block as data is being received, so you don't need to worry about events firing when everything has been downloaded.
You definitely need to re-think your approach (as you've already begun to do) to eliminate the Forms-based application approach. The service you're describing needs to operate with no UI at all.
I'm not familiar with the details of System.WebClient, but since it
provides common methods for sending
data to and receiving data from a
resource identified by a URI,
it will probably be your answer.
At first glance, WebClient.DownloadFile(...) or WebClient.DownloadFileAsync(...) will do what you need.
The only thing I can add is that once you have scraped your screen and have the fully qualified name of the file you want to download, you could pass it along to the Windows/DOS command 'get' which will fetch files via HTTP. You can also script a command-line FTP client if desired. It's been a long time since I tried something like this in Windows, but I think you're almost there. Once you have fetched the correct file, building a batch file to do everything else should be pretty easy. If you are more comfortable with Unix, google "unix services for windows" just keep an eye on the services they start running (DHCP, etc). There are some nice utilities which will let your treat dos as a unix-like shell (ls -l, grep, etc) Finally, you could try another language like Perl or Python but I don't think that's the kind of advice you were looking for. :)