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;
}
};
}
}
Related
I am facing issue while calling an azure function developed in java with VS Code. Everything goes fine except the run command. When I run the command 'mvn azure-functions:run', it starts properly. But I am not able to hit it from postman. Here is my code.
public class Function {
#FunctionName("hello")
public HttpResponseMessage hello(#HttpTrigger(name = "req", methods = {"get", "post"}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage req,
final ExecutionContext context) {
context.getLogger().info("Java HTTP triger processed a request.");
String query = req.getQueryParameters().get("name").toString();
return req.createResponse(200, "hELLO "+query);
}
}
Update:
Thank's for Satya Panigrahy's sharing, the solution is to run mvn generate to generate azure function. By the way, azure function tools dont have a template of java language. For more information, please have a look of this doc:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-first-kotlin-maven?tabs=cmd#generate-a-new-functions-project
Original Answer:
Please have a look of this offcial template:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=java#example
I think the HttpRequestMessage dont have a method named createResponse. If you want to achieve, please have a try of the below codes, it works fine on my side:
package com.function;
import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
public class Function {
#FunctionName("hello")
public HttpResponseMessage run(
#HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> req,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a request.");
String query = req.getQueryParameters().get("name").toString();
return req.createResponseBuilder(HttpStatus.OK).body("hELLO " + query).build();
}
}
Please have a try, and let me know if you have some troubles.:)
For a unity game I need to use libs in android-plugin that will send websocket requests. I found out that I have no idea how make the c# code wait for the async operation in android plugin!
I provide a proof of concept case (with simple http get request) to ask my quesiton the simple way. Here are my code that didnt' work:
package com.example.plug2unity1;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Plug1Class {
static OkHttpClient client = new OkHttpClient();
static String doGetRequest(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static String GetPlug2Text() throws IOException {
String res = "";
try {
res = doGetRequest("http://www.google.com");
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}
Unity script will have to call the plugin:
void Start () {
TextMesh txtm = GetComponent<TextMesh> ();
var plugin = new AndroidJavaClass("com.example.plug2unity1.Plug1Class");
txtm.text = plugin.CallStatic<string>("GetPlug1Text");
}
Edit:
The question is "not" how to make http call, it is obvious that from c# I can do it, I would like to learn "how c# could wait an async operation result from plugin, being it an http call or an I/O operation, same way we do by "promises" in javascript.
Result:
My TextMesh does not change the text, while if I do a POC without any async in plugin side, it works. How could I get this to work?
Use a callback to do this. Call the Java unction from C#. In the Java function, start new Thread to perform that task. When that task has finished, do a callback from Java to C# to let you know that the task has finished.
C# sample code:
void makeRequestOnJava()
{
TextMesh txtm = GetComponent<TextMesh> ();
var plugin = new AndroidJavaClass("com.example.plug2unity1.Plug1Class");
txtm.text = plugin.CallStatic<string>("GetPlug1Text");
}
//Will be called from C# when the request is done
void OnRequestFinished()
{
}
Then on the Java side when your task has finished, use UnityPlayer.UnitySendMessage to call the OnRequestFinished function on the C# side.
UnityPlayer.UnitySendMessage("GameObjectName", "OnRequestFinished", null);
You can see how to setup and use the UnityPlayer.UnitySendMessage function here.
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();
}
}
Ï 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
I'm working on upgrading our existing Wicket webapp to 1.5 and have hit a snag in our renderPage function that we use to render our HTML emails.
Previously we used the code referenced/listed in this StackOverflow question and this (currently broken but maybe fixed later) link but that code no longer works as a lot of those classes don't exist in 1.5.
I also found this email thread but it is light on the details and I don't know how to create the WebPage from my pageClass and parameters.
http://apache-wicket.1842946.n4.nabble.com/Render-WebPage-to-String-in-Wicket-1-5-td3622130.html
Here is my code:
// Renders a page under a temporary request cycle in order to get the rendered markup
public static String renderPage(Class<? extends Page> pageClass, PageParameters pageParameters)
{
//get the servlet context
WebApplication application = (WebApplication) WebApplication.get();
ServletContext context = application.getServletContext();
//fake a request/response cycle
MockHttpSession servletSession = new MockHttpSession(context);
servletSession.setTemporary(true);
MockHttpServletRequest servletRequest = new MockHttpServletRequest(application, servletSession, context);
MockHttpServletResponse servletResponse = new MockHttpServletResponse(servletRequest);
//initialize request and response
servletRequest.initialize();
servletResponse.initialize();
WebRequest webRequest = new ServletWebRequest(servletRequest);
BufferedWebResponse webResponse = new BufferedWebResponse(servletResponse);
webResponse.setAjax(true);
WebRequestCycle requestCycle = new WebRequestCycle(application, webRequest, webResponse);
requestCycle.setRequestTarget(new BookmarkablePageRequestTarget(pageClass, pageParameters));
try
{
requestCycle.getProcessor().respond(requestCycle);
if (requestCycle.wasHandled() == false)
{
requestCycle.setRequestTarget(new WebErrorCodeResponseTarget(HttpServletResponse.SC_NOT_FOUND));
}
}
finally
{
requestCycle.detach();
requestCycle.getResponse().close();
}
return webResponse.toString();
}
Specifically, the code breaks because the WebRequestCycle and BookmarkablePageRequestTarget classes no longer exist. I feel like I should be able to use the StringResponse class some how but I'm missing the link that would help me trigger a render on that response.
Any help would be appreciated. Thanks.
My Final Solution
Using the example that I was directed to by the answer below I ended up with the following code. I'm pasting it here as well so that if that link disappears or is changed with a future version of Wicket then people from the future will still be able to get the answer they need.
I ended up passing in a PageProvider because in some cases I needed to pass in an instantiated Page and in others a pageClass + parameters.
public static String renderPage(final PageProvider pageProvider)
{
final RenderPageRequestHandler handler = new RenderPageRequestHandler(pageProvider, RedirectPolicy.NEVER_REDIRECT);
final PageRenderer pageRenderer = Application.get().getPageRendererProvider().get(handler);
RequestCycle requestCycle = RequestCycle.get();
final Response oldResponse = requestCycle.getResponse();
BufferedWebResponse tempResponse = new BufferedWebResponse(null);
try
{
requestCycle.setResponse(tempResponse);
pageRenderer.respond(requestCycle);
}
finally
{
requestCycle.setResponse(oldResponse);
}
return tempResponse.getText().toString();
}
Check the source code of http://www.wicket-library.com/wicket-examples/mailtemplate/ example.