Programmatically sending mule message (formerly: Accessing mule http endpoint from java) - java

Scroll towards the end for the solution to the topic's problem. The original question was asking for a somewhat different thing.
As a part of a larger process, I need to fetch and link two related sets of data together. The way that the data is retrieved(dynamics crm, n:n relationships..) forces us retrieve the second set of the data again so that it will have all the necessary information. During a part of larger transformation of this data, I would like to access the http endpoint that is used to fetch the data from the crm, retrieve the second set of data and process it. I can get the endpoint through DefaultEndPointFactory like so:
DefaultEndpointFactory def = new DefaultEndpointFactory();
def.getInboundEndpoint("uri").getConnector;
But there is no method to actually send the mulemessage.
Solved:
The problem is that you can not set inbound properties on the MuleMessage, and the flow is depending on some of those to function(path, query params etc).
It seems you are able to inbound scoped properties with this:
m.setProperty("test", (Object)"test", PropertyScope.INBOUND);
Is there a way to make this approach work, or an alternative way to access the flow? I tried using mulecontext to get the flow:
muleContext.getRegistry().lookupFlowConstruct("myflow");
But it did not contain anything that looked useful.
Solution:
As David Dossot suggested in a comment of his answer, I was able to solve this with muleClients request method.
muleContext.getClient().request(url, timeout);
Then constructing the url as usual with GET parameters etc.

I'm not 100% sure about what you're trying to achieve but anyway, the correct way of using Mule transports from Java code is to use the MuleClient, which you can access with muleContext.getClient().
For example, the send method allow you to pass a properties map that are automatically added to the inbound scope. Behind the scene, Mule takes care of creating the endpoint needed for the operation.
Regarding the flow: what are you trying to do with it? Invoke it?

Related

Using POST method instead of GET in a rest API

Is there a specific scenario where we use a POST instead of GET, to implement the functionality of get operation ?
GET is supposed to get :) and POST is used to mainly add something new or sometimes often used for updates as well (although PUT is recommended in such scenarios). There is no specific scenario where we use a POST instead of a GET, if we require this, that means we are probably doing it wrong, although nothing stops you doing this but this is bad design and you should take a step back and plan your API carefully.
There are 2 important cases for a POST i.e. POST is more secure than a GET and POST can send large amount of data but even with this I won't recommend why one will use POST to simulate a GET behaviour.
Lets understand usage of get and post :
What is GET Method?
It appends form-data to the URL in name/ value pairs. The length of the URL is limited by 2048 characters. This method must not be used if you have a password or some sensitive information to be sent to the server. It is used for submitting the form where the user can bookmark the result. It is better for data that is not secure. It cannot be used for sending binary data like images or word documents. It also provides $_GET associative array to access all the sent information using the GET method.
What is POST Method?
It appends form-data to the body of the HTTP request in such a way that data is not shown in the URL. This method does not have any restrictions on data size to be sent. Submissions by form with POST cannot be bookmarked. This method can be used to send ASCII as well as binary data like image and word documents. Data sent by the POST method goes through HTTP header so security depends on the HTTP protocol. You have to know that your information is secure by using secure HTTP. This method is a little safer than GET because the parameters are not stored in browser history or in web server logs. It also provides $_POST associative array to access all the sent information using the POST method.
Source: https://www.edureka.co/blog/get-and-post-method/
So both the methods have their specific usage.
POST method is used to send data to a server to create or update a resource.
GET method is used to request data from a specified resource.
If you want to fetch some data you can use the GET method. But if you want to update an existing resource or create any new resource you should use POST. GET will not help you to create/update resources. So exposing the api should be specific to your needs.
UPDATE
So your main question is in what scenario we can use POST to implement the functionality of GET.
To answer that, as you understand what GET and POST does, so with GET request you will only fetch the resource. But with POST request you are creating or updating the resource and also can send the response body containing the form data in the same request response scenario. So suppose you are creating a new resource and the same resource you want to see, instead of making a POST call first and making a GET call again to fetch the same resource will cost extra overhead. You can skip the GET call and see your desired response from the POST response itself. This is the scenario you can use POST instead of making an extra GET call.

Java HTTP Pooling Custom Header

I was able to implement the HTTP Connection Pooling sample defined on this website. But I want the ability to pass each request a certain unique value and then store that value in a custom header called "Foo".
I understand that I can modify the ClientHttpRequestInterceptor to set a custom header like this...
request.getHeaders().add("Foo", "ASDAS");
But I want the ability to pass a value so that it's not always ASDAS with each HTTP request. Any help would be helpful because I been pulling my hair for hours now.
Side Note: I need to use HTTP Pooling due to high data volume rate
request.getHeaders().add("Foo", "Value");
You can generate Value by other way,for example
MD5("Unique String" + System.currentTimeMillis() + index + ....)
I'm not sure I can solve your problem.
After a good night of sleep, I got it to work. After reading up more on the RestTemplate JavaDoc, I found out that they have a exchange method which lets you pass custom headers. You don't need to do anything within the ClientHttpRequestInterceptor class

Return an integer from server to client in response to a REST call

I have a situation where the client (.js) initiates a REST request and it is processed on the server side (.java). After processing, I would like to return a count to the client, which will be shown in a popup box if it is positive. How can such a construction be done? The idea I had was to set a named parameter on the HttpServletResponse object, but even this object is no where in scope in the .js code. Any ideas? I should also clarify that the primary purpose of the REST call is to download a file to the client. Thanks!
Do you want to send two things to your client - sending a file and also additional data? You haven't mentioned what framework (if any) you are using in backend to do this. You can use response header.
From your question, it seems like you don't have a good general-purpose way of responding to client requests on your server. I'd recommend you decide on a data format you'd like to use for all calls (e.g., JSON, XML, etc.) and stick with that across the board.
Once you've made that decision, you can encode your integer using whatever makes sense in your chosen format. For example, in JSON you might return: {"count":6}.

How to add a flag to existing POST api

I have a REST api built for creating orders. The behavior is such that the person who creates an order received an email back saying "You created an order XXX". This email is triggered all the time.
The api appears like this
http://api.mytestevnt.com/ordering/orders - POST with request body as the order entity json.
Now i want to give a feature to the api caller to indicate if the email notification is necessary or not. What's the best way to do this?
I think it depends on whether email notification is data or metadata. If it's part of the order, then definitely add it to the request body. If it's metadata, you have two choices. If you think there will be lots of metadata, you can either edit the order to have a metadata section or you can POST the metadata separately. If there will only be a limited amount of metadata, I would suggest using a query parameter.
You should avoid using a header unless you control the entire path from the client to the server, because proxies or load balancers are allowed to strip non-standard headers.
Include in the POST body a send_email=1 or send_email=0 param. You'll extract that, and see what the user wants to do.
Search "how to get POST variables in JAVA".
Accessing post variables using Java Servlets
You can do like this:
Add a new Java attribute(like boolean emailEnabled) in your Java Request Object for your REST service.
Client side which invokes your REST service need to provide that parameter you added in your server side, you can set a default value for that too.

Loading GWT Messages from a Database

In GWT one typically loads i18n strings using a interface like this:
public interface StatusMessage extends Messages {
String error(String username);
:
}
which then loads the actual strings from a StatusMessage.property file:
error=User: {0} does not have access to resource
This is a great solution, however my client is unbendable in his demand for putting the i18n strings in a database so they can be changed at runtime (though its not a requirement that they be changed realtime).
One solution is to create a async service which takes a message ID and user locale and returns a string. I have implemented this and find it terribly ugly (it introduces a huge amount of extra communication with the server, plus it makes property placeholder replacement rather complicated).
So my question is this, can I in some nice way implement a custom message provider that loads the messages from the backend in one big swoop (for the current user session). If it can also hook into the default GWT message mechanism, then I would be completely happy (i.e. so I can create a interface like above and keep using the the nice {0}, {1}... property replacement format).
Other suggestions for clean database driven messages in GWT are also welcome.
GWT's in-built Dictionary class is the best way to move forward. Here's the official documentation on how to use it.
Let's say your application has 500 messages per locale at an average of 60 chars per message. I wouldn't think twice about loading all of these when the user logs in or selects his language: it's <50k of data and should not be an issue if you can assume broadband connectivity being available...your "one swoop" suggestion. I already do that in one GWT application, although it's not messages, but properties that are read from the database.
i think you might find this article useful:
http://googlewebtoolkit.blogspot.com/2010/02/putting-test-data-in-its-place.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+blogspot/NWLT+(Google+Web+Toolkit+Blog)&utm_content=Google+Reader
What you could do is set up a TextResource and then, you could just change the text at runtime. I haven't tried this but I am very confident that this would work.
To optimize the performance, you can put your messages in a js resource, for example: http://host.com/app/js/messages.js?lang=en, then map this resource to a servlet which will take the messages dictionary from your cache (a singleton bean, for instance) and write it to the response.
To optimize even more, you can:
- put a parameter to the resource URL, for example: .../messages.js?lang=en&version={last updated date of messages}
- {last updated date of messages} is stored somewhere in DB
- whenever user updates the messages, {last updated date of messages} will change
- in the response to browser, set Cache-control as you want to tell browser to cache your messages.

Categories

Resources