Ï am Taking data From server written in "C" using Sockets .
My java class name is ReceivingData, and here's the code for receiving the data and storing it in ArrayList and passing the ArrayList to other Class's Constructor.
package pack.exp;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ReceivingData implements Runnable
{
public static void main(String[] args)
{
Thread t = new Thread(new ReceivingData());
t.start();
}
public List<String> obj1;
#Override
public void run()
{
Socket s;
InputStream stream;
try
{
s = new Socket("10.9.211.22", 6870);
stream = s.getInputStream();
byte[] data = new byte[13];
int read;
String can_Id= null;
while((read = stream.read(data)) != -1)
{
String can_Data=
String.format("%02X:%02X:%02X:%02X,
data[0], data[1], data[2], data[3]);
List<String> obj1= new ArrayList<String>();
obj1.add(can_Data.substring(0, 2));
obj1.add(can_Data.substring(3, 5));
obj1.add(can_Data.substring(6, 8));
obj1.add(can_Data.substring(9, 11));
Receiving_At_Regular_IntervalServlet rari= new
Receiving_At_Regular_IntervalServlet(obj1);
Thread.sleep(3000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This is the Servlet which is receiving the data from ArrayList passed by the above File.
and storing this data from the arraylist in to the Entity for datastore and deploys it on the Google App engine.
package pack.exp;
#SuppressWarnings("serial")
public class Receiving_At_Regular_IntervalServlet extends HttpServlet
{
List<String> obj2= new ArrayList<String>();
public Receiving_At_Regular_IntervalServlet(List<String> obj2) throws
IOException
{
this.obj2= obj2;
System.out.println("Receiving in Web Project" + obj2);
System.out.println("");
System.out.println("");
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException
{
Key k1 = KeyFactory.createKey("C","0D F0 0800 1");
String parameter1 = obj2.get(0);
Entity can1 = new Entity(k1);
can1.setProperty("First Parameter", parameter1);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(can1);
Entity can11 = null;
try
{
can11= datastore.get(k1);
}
catch (EntityNotFoundException e)
{
e.printStackTrace();
}
String first_P= (String) can11.getProperty("First Parameter");
resp.setContentType("text/plain");
resp.getWriter().println("Parameter--- " + first_P);
}
}
The ReceivingData code evidently runs a thread and reads data from 10.9.211.22 port 6870 using Socket from a local computer. That's fine. It converts four bytes to a List and passes that to Receiving_At_Regular_IntervalServlet. Fine but not what you need.
This part might work on a development computer but won't work if deployed to the cloud. AppEngine servers does not permit developers to define main(), use Socket or communicate with private IP subnet 10. Forget about deploying that code to AppEngine.
Receiving_At_Regular_IntervalServlet has a custom constructor. AppEngine does not call your constructor because its servlet code expects only the default constructor. That is probably when your 503 error occurs.
With servlets the data is not supposed to come in via a constructor. Data must come in via members of the request parameter of the doGet method (though to be RESTful you should rather use doPut in this example). You insert the data into the request parameter but sending a correctly constructed http request to the server. Your code lacks that web application design.
Build your main program and your AppEngine code in separate projects and make main talk to servlet using http.
HTTP ERROR 503 error
You can't help anything when a server throws this error. It is only thrown when a service from the server is unavailable.
You need explicit handling on such error codes, other than 200 OK, in the client app and appropriate message has to be shown or as the alternate requirement suggestion.
Refer to:
Status Code definitions
Java - 503 - SC_SERVICE_UNAVAILABLE
Related
So I have been looking around for days and I still can't find a simple working method. This is what I am trying to do:
1 - Search and find web services registered in UDDI based on keywords
2 - Decide which service fits and use/call it
All this using Java (Eclipse).
I don't want to create my own uddi nor do I want to publish services, just find existing services stored in the public UDDI (I believe there's one, right?). I thought that these two tasks (find WS, call WS) would be easy and that it would be possible to find sample code to use, but I can't find any.
I came across Juddi while searching, but not sure if it works for my case and if it's worth installing.
Any tutorials? suggestions ? I found the following code, but can't find the jar file to use its libraries:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package uddi.createbulk;
import javax.xml.bind.JAXB;
import org.apache.juddi.v3.client.config.UDDIClient;
import org.apache.juddi.v3.client.config.UDDIClientContainer;
import org.apache.juddi.v3.client.transport.Transport;
import org.apache.juddi.v3_service.JUDDIApiPortType;
import org.uddi.api_v3.*;
import org.uddi.v3_service.UDDIInquiryPortType;
import org.uddi.v3_service.UDDIPublicationPortType;
import org.uddi.v3_service.UDDISecurityPortType;
/**
*
* #author Alex
*/
public class UddiFindService {
private static UDDISecurityPortType security = null;
private static JUDDIApiPortType juddiApi = null;
private static UDDIPublicationPortType publish = null;
private static UDDIInquiryPortType inquiry = null;
public UddiFindService() {
try {
// create a manager and read the config in the archive;
// you can use your config file name
UDDIClient clerkManager = new UDDIClient("META-INF/simple-publish-uddi.xml");
// register the clerkManager with the client side container
UDDIClientContainer.addClient(clerkManager);
// a ClerkManager can be a client to multiple UDDI nodes, so
// supply the nodeName (defined in your uddi.xml.
// The transport can be WS, inVM, RMI etc which is defined in the uddi.xml
Transport transport = clerkManager.getTransport("default");
// Now you create a reference to the UDDI API
security = transport.getUDDISecurityService();
juddiApi = transport.getJUDDIApiService();
publish = transport.getUDDIPublishService();
inquiry = transport.getUDDIInquiryService();
} catch (Exception e) {
e.printStackTrace();
}
}
public void find() {
try {
// Setting up the values to get an authentication token for the 'root' user ('root' user has admin privileges
// and can save other publishers).
GetAuthToken getAuthTokenRoot = new GetAuthToken();
getAuthTokenRoot.setUserID("root");
getAuthTokenRoot.setCred("root");
// Making API call that retrieves the authentication token for the 'root' user.
AuthToken rootAuthToken = security.getAuthToken(getAuthTokenRoot);
System.out.println("root AUTHTOKEN = " + rootAuthToken.getAuthInfo());
GetServiceDetail fs = new GetServiceDetail();
fs.setAuthInfo(rootAuthToken.getAuthInfo());
fs.getServiceKey().add("mykey");
ServiceDetail serviceDetail = inquiry.getServiceDetail(fs);
if (serviceDetail == null || serviceDetail.getBusinessService().isEmpty()) {
System.out.println("mykey is not registered");
} else {
JAXB.marshal(serviceDetail, System.out);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
UddiFindService sp = new UddiFindService();
sp.find();
}
}
I'm using the atmosphere framework in my application.
https://github.com/Atmosphere/atmosphere
I've extended the AbstractReflectorAtmosphereHandler class and implemented the
-onRequest
-destroy
-onstatechanged
methods.
When a client wants to send a message to the server:
subSocket.push(jQuery.stringifyJSON({ data: "blahblah", source:"client" }));
The onRequest function is called; however the message
Object message = atmosphereResource.getAtmosphereResourceEvent().getMessage();
Is empty.
Than I tried using the onstatechanged which is called every time
(1) The remote connection gets closed, either by a browser or a proxy
(2) The remote connection reach its maximum idle time (AtmosphereResource.suspend))
(3) Everytime a broadcast operation is executed (broadcaster.broadcast)
However even after filtering out 1 and 2
public void onStateChange(AtmosphereResourceEvent event)
throws IOException {
if (source.equals("client") && !event.isResumedOnTimeout() && !event.isResuming()){
System.out.println("message form client");
System.out.println(message.toString());
} else {
//normal onstatechanged code from AbstractReflectorAtmosphereHandler
}
However the message is printed randomly between 2 and 4 times. It should only be called once.
So my question is: Can I acces the message inside the onRequest method or why is the onStateChange called so many times.
edit: from the answer given by jF I've been able to acces the message inside the onRequest function. (I'm not sure however if that is what he actually meant).
public void onRequest(AtmosphereResource resource) throws IOException {
//Object message = resource.getAtmosphereResourceEvent().getMessage(); //is empty why?
//leave connection open
resource.suspend();
BufferedReader reader = resource.getRequest().getReader();
Object message = reader.readLine();
if (message !=null){
System.out.println("**onRequest: "+message.toString());
}
}
You need to read the request's body by doing, in your onStateChange:
atmosphereResource.getRequest().getReader (or getInputStream).
Maybe this helpes other people:
public void onRequest(AtmosphereResource resource) throws IOException {
//Object message = resource.getAtmosphereResourceEvent().getMessage(); //is empty why?
//leave connection open
resource.suspend();
BufferedReader reader = resource.getRequest().getReader();
Object message = reader.readLine();
if (message !=null){
Object obj = JSONValue.parse(message.toString());
JSONObject jsonObject = (JSONObject) obj;
Object source = jsonObject.get("source");
System.out.println("**onRequest: "+message.toString());
ArrayList frame = new ArrayList();
frame.add(jsonObject.get("type"));
frame.add(jsonObject.get("data"));
writeQueue.add(frame);
}
}
I have a very simple JavaFX Controller with a simple Username, Password and Logon button.
What I want to do is when the user clicks Logon, I want the disable the inputs - which I do in code with:
this.gridPanelLogon.setDisabled(true);
And - this works but my issue is - it appears to be threaded, in that after this call I then make a JerseyClient call to a web REST service - and once that code completes it then updates the UI and disables the gridPanel. But what I would like is for the gridPanel to first disable THEN to call and it seems the UI is only updated after all the code runs (not right when it hits the line of code above).
If I explained this poorly I apologize, and I'd be happy to help clarify more but was hoping maybe someone has experienced this and could either help explain why or a work around. I also tried one other work around, putting a change listener to the gridPanel's disabled property - this didn't work and resulted in the same delay as mentioned above.
Any help would be greatly appreciated - and thanks!!
Don't run client => server calls on the JavaFX application thread, instead run them in their own thread via a Task or Service.
Thank you again to jewelsea - he answers many of these JavaFX questions so well. I wanted to share this solution, which in my testing works well for my application. I was making a Jersey-Client REST request, and was placing this inside my JavaFX application (without creating a separate class extending javafx.concurrent.Service).
So what I've done below is provide the solution that worked well for me, taking into account the links jewelsea provided above. This Service class will return a ClientResponse object after successfully POSTing to the url provided. I have tried to provide more notes about this in comments below.
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
/**
* This Service class will make REST calls to a given URL,
* with a JSON encoded request string.
*
* OnSucceeded will return a ClientResponse object - will be
* null if an exception occurred - if no exception is the
* ClientResponse result of the Jersey-Client call.
*/
public class JerseyClientPostService extends Service<ClientResponse> {
private StringProperty url = new SimpleStringProperty();
private StringProperty json = new SimpleStringProperty();
public JerseyClientPostService() {
super();
}
public JerseyClientPostService(String url, String json) {
super();
this.url.set(url);
this.json.set(json);
}
public final String getUrl() {
return this.url.get();
}
public final String getJson() {
return this.json.get();
}
public final void setJson(String json) {
this.json.set(json);
}
public final void setUrl(String url) {
this.url.set(url);
}
#Override protected Task<ClientResponse> createTask() {
final String _url = getUrl();
final String _json = getJson();
return new Task<ClientResponse>() {
#Override protected ClientResponse call() {
Client client = Client.create();
WebResource webResource = client.resource(_url);
ClientResponse response;
try {
response = webResource.type("application/json").post(ClientResponse.class, _json);
}
catch (ClientHandlerException che) {
System.err.println("ClientHandlerException connecting to Server: "+che.getMessage());
return null;
}
catch (Exception ex) {
System.err.println("Exception getting response Json: "+ex.getMessage());
return null;
}
return response;
}
};
}
}
i have used axis web service client wizard + develop client slider for generating files as :
Mage_Api_Model_Server_HandlerBindingStub
Mage_Api_Model_Server_HandlerPortType
Mage_Api_Model_Server_HandlerPortTypeProxy
MagentoService
MagentoServiceLocator
please look at my post
i am trying to make a client some thing like this:
package Magento;
public class MyClient {
public static void main(String[] args) {
try{
MagentoServiceLocator msl = new MagentoServiceLocator();
MagentoService ms = (MagentoService) msl.WHICH_METHOD_TO_CALL();
double product_list = ms.catalogProductList;
System.out.println("Product List: " + product_list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
any help i have tried to the best of mine but not getting which method should i call for accessing a php webservice method.
any help?
Create a client for the given wsdl and try this:
WebServiceSoapBindingStub stub = new WebServiceSoapBindingStub();
stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, wsdlUrl);
WebService service = (WebService) stub;
service.authenticateUser(username,password); //service.yourservicename
More information that will help you.
http://www.codeproject.com/KB/java/edujini_webservice_java.aspx
I'm trying to figure out how to upload one file using GWTs FileUpload widget. I'm using GWT and Google AppEngine with Java but I would like to upload file to my own Linux server.
I have the following code already but now I can't figure out how to submit my file to the Google AppServer server and save it to another server:
public class FileUploader{
private ControlPanel cp;
private FormPanel form = new FormPanel();
private FileUpload fu = new FileUpload();
public FileUploader(ControlPanel cp) {
this.cp = cp;
this.cp.setPrimaryArea(getFileUploaderWidget());
}
#SuppressWarnings("deprecation")
public Widget getFileUploaderWidget() {
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// form.setAction(/* WHAT SHOULD I PUT HERE */);
VerticalPanel holder = new VerticalPanel();
fu.setName("upload");
holder.add(fu);
holder.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.log("You selected: " + fu.getFilename(), null);
form.submit();
}
}));
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event) {
if (!"".equalsIgnoreCase(fu.getFilename())) {
GWT.log("UPLOADING FILE????", null);
// NOW WHAT????
}
else{
event.cancel(); // cancel the event
}
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert(event.getResults());
}
});
form.add(holder);
return form;
}
}
Now, what do I need to do next? What do i need to put in web.xml and how do I write my servlet so i can store file and return url of that object (if possible)
Here's the code from my app:
1) I created a class to accept http request:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10*(1024*1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
}
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
2) Then in my web.xml I've added these lines:
<servlet>
<servlet-name>fileUploaderServlet</servlet-name>
<servlet-class>com.testapp.server.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUploaderServlet</servlet-name>
<url-pattern>/testapp/fileupload</url-pattern>
</servlet-mapping>
3) And for form.action did this:
form.setAction(GWT.getModuleBaseURL()+"fileupload");
I would suggest using GWTUpload because it's dead simple to use and extend. You can add it to your project in less than 10 minutes and it supports GAE right out of the box (using GWTUpload-GAE). See the examples for some common usage scenarios.
In GWT, you can post the file to the server using http form methods, and you must use the supplied HttpServlet to accept and save the data as binary blogs in the Appengine BigTable.
Then, you need a second HttpServlet to read the file from bigtable, SET THE MIME TYPE IN THE HTTP HEADER {and caching options}, and then stream the file to the user.
Although RPC isn't NECESSARILY needed, you must let the client know what the generated fileId is so they can access it {unless you want to let user's supply the id and force them to worry about name overrides... ...ick}. Either you can use rpc to ask for a list of / single id {like "newest file id by user"}, or you can return that id in the body of the UploadServlet's response... but then you must make sure your post target is an in-page iframe, poll to make sure the iframe has a body between the submit event and the actual server response, and then parse and use that id in gwt to create an img or object tag that uses the file.
The key part is having one servlet for upload, and another to download. Remember, BigTable just stores binary blobs, so you also need your data entity to have a mime/content Type that can be read from the input file {never rely on file extensions!}. Also, there's a 1MB per entity in the BigTable, and a 10MB request limit for free accounts. You may wish to have your data entity contain a list of 1-10 blobs, each of which are a max 1024bytes.
Basically, your best bet is to find a working, free copy, like Google File Service, and extend it to learn how the system works.
If you wish, I will be posting my own open-source version of file handling, once I finish the gwt control widgets and can consider it all stable enough to be useful to anyone. Email x AT aiyx DOT info if you want me to send you a jar of betalicious code.
Here you go with a complete GWT fileupload with Progress bar
Here you can DOWNLOAD the source