I am new to Mule and I need to call a flow from Java class. Can anyone give steps please?
you can do it by following below steps
1) In order to make a call, first your flow should have the VM as inbound endpoint.
2) in your java code, get the Mulecontext from MuleEventContext.
3) get the client() from MuleContext then use send method. below is the sample code
MuleContext mContext = eventContext.getMuleContext();
mContext.getClient().send(VM URL, payload);
The VM URL in the send() is the name of the VM Queue path (sometimes you may need to prefix it with 'vm://...' - example: 'vm://myVMQueuePath'.
Any issues let me know.
I have tried this is it did work. I have created java class inside any-point studio and called the java from a main flow. Java is calling the second flow using VMQ. Here is my Java Class. Hope this helps
package mulewithjava;
import org.mule.api.MuleContext;
import org.mule.api.MuleEventContext;
import org.mule.api.MuleMessage;
import org.mule.api.lifecycle.Callable;
public class CallMuleFlow implements Callable {
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
// TODO Auto-generated method stub
String payload = (String) eventContext.getMessage().getPayload();
MuleContext mContext = eventContext.getMuleContext();
MuleMessage msg= eventContext.getMessage();
mContext.getClient().send("vm://VMQ", msg);
return "After Flow Calling";
}
}
Related
Can I use the Bing Maps API with Java for geolocation? I have the API key but I can't find anything on the net.
I've found a method with an Excel Macro that works but isn't enough, I need a java console script to do it.
Cheers, Damiano.
There doesn't appear to be any official way to make use of the Maps API in Java.
However, there is an unofficial Java wrapper for the API located here. This hasn't been updated in a while, so there's no guarantee it will still work, but it should be a good starting point for implementing geocoding requests.
There is also a method for implementing reverse-geocoding requests in the same wrapper at client.reverseGeocode().
import net.virtualearth.dev.webservices.v1.common.GeocodeResult;
import net.virtualearth.dev.webservices.v1.geocode.GeocodeRequest;
import net.virtualearth.dev.webservices.v1.geocode.GeocodeResponse;
import com.google.code.bing.webservices.client.BingMapsWebServicesClientFactory;
import com.google.code.bing.webservices.client.geocode.BingMapsGeocodeServiceClient;
import com.google.code.bing.webservices.client.geocode.BingMapsGeocodeServiceClient.GeocodeRequestBuilder;
public class BingMapsGeocodeServiceSample {
public static void main(String[] args) throws Exception {
BingMapsWebServicesClientFactory factory = BingMapsWebServicesClientFactory.newInstance();
BingMapsGeocodeServiceClient client = factory.createGeocodeServiceClient();
GeocodeResponse response = client.geocode(createGeocodeRequest(client));
printResponse(response);
}
private static void printResponse(GeocodeResponse response) {
for (GeocodeResult result : response.getResults().getGeocodeResult()) {
System.out.println(result.getDisplayName());
}
}
private static GeocodeRequest createGeocodeRequest(BingMapsGeocodeServiceClient client) {
GeocodeRequestBuilder builder = client.newGeocodeRequestBuilder();
builder.withCredentials("xxxxxx", null);
builder.withQuery("1 Microsoft Way, Redmond, WA");
// builder.withOptionsFilter(Confidence.HIGH);
return builder.getResult();
}
}
I'm creating a Nativescript plugin. It includes a custom Android Library (AAR) and I want to use it from the Typescript code. When I run a demo (in device or emulator) I get a TypeError: sender.registerListener is not a function error when calling this registerListener method, which is weird because I'm able to call other methods of the same object.
I think that it could be because I am not implementing properly the interface required as parameter. I think that I can explain it better with code:
Sender.java: the public class I will use in Typescript:
package com.berriart.android.myplugin;
public class Sender {
public static final String TAG = "Sender";
private Context _context = null;
public Sender(Context context) {
_context = context;
}
public void send(final String messagePath, final String messageToSend) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "Send call: " + messagePath + " " + messageToSend);
}
}
public void registerListener(MessageListener listener) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "registerListener");
}
}
// Other code here
}
MessageListener.java: the interface that must be implemented by the registerListener parameter:
package com.berriart.android.myplugin;
public interface MessageListener {
void receive(String messagePath, String messageReceived);
}
This is the Typescript (Nativescript) code of the plugin ( to ):
import * as app from "tns-core-modules/application";
export class WearMessaging {
public static send(messagePath: string, messageToSend: string) {
let sender = new com.berriart.android.myplugin.Sender(app.android.context);
sender.send(messagePath, messageToSend);
}
public static registerListener(receiveCallback: (messagePath: string, messageReceived: string) => void) {
let messageListener = new com.berriart.android.myplugin.MessageListener({
receive: receiveCallback
});
let sender = new com.berriart.android.myplugin.Sender(app.android.context);
sender.registerListener(messageListener);
}
}
If I include WearMessaging.send("/demo", "Hola"); in my nativescript application it compiles and run properly, it's call the Java method successfuly. But if I run:
WearMessaging.registerListener((messagePath: string, messageReceived: string) => {
console.log(messagePath);
console.log(messageReceived);
});
The application stops at run time and throws: TypeError: sender.registerListener is not a function refering to the myplugin.android.ts file.
I'm getting crazy trying to make this work, so, let me know if you have any clue. As I say I think that is because I'm missing something when implementing the interface and because the parameter type do not match them method is not being recognized, but maybe I'm wrong.
Here you can see some official doc:
https://docs.nativescript.org/runtimes/android/generator/extend-class-interface
Thanks in advance.
Ok, I solved it :S
It seems that the incremental build was doing something wrong. After deleting manually the build files of the demo everything went fine:
rm -rf platforms/android/build/*
rm -rf platforms/android/app/build/*
# Then build & deploy again
So, question code seems to be fine if you need to do something similar.
I am having trouble finding the source of this error. I implemented a simple service using protobuf:
syntax = "proto3";
package tourism;
service RemoteService {
rpc Login(LoginUserDTO) returns (Response) {}
}
message AgencyDTO{
int32 id=1;
string name=2;
string email=3;
string password=4;
}
message LoginUserDTO{
string password=1;
string email=2;
}
message SearchAttractionsDTO{
string name=1;
int32 start_hour=2;
int32 start_minute=3;
int32 stop_hour=4;
int32 stop_minute=5;
AgencyDTO loggedUser=6;
}
message AttractionDTO{
int32 id=1;
string name=2;
string agency=3;
int32 hour=4;
int32 minute=5;
int32 seats=6;
int32 price=7;
}
message ReservationDTO{
int32 id=1;
string first_name=2;
string last_name=3;
string phone=4;
int32 seats=5;
AttractionDTO attraction=6;
AgencyDTO agency=7;
}
message Response{
enum ResponseType{
OK=0;
NOT_LOGGED_ID=1;
SERVER_ERROR=2;
VALIDATOR_ERROR=3;
}
ResponseType type=1;
AgencyDTO user=2;
string message=3;
}
When using a java client everything works fine, the server receives the request and responds appropriately. When using C# with the same .proto file for generating sources at the client.Login() I get the following errror: Grpc.Core.RpcException Status(StatusCode=Unimplemented, Detail="Method tourism.RemoteService/Login is unimplemented"). The server receives the request but does not have time to respond and throws:
INFO: Request from ex#ex.com
May 22, 2017 12:28:58 AM io.grpc.internal.SerializingExecutor run
SEVERE: Exception while executing runnable io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$2#4be43082
java.lang.IllegalStateException: call is closed
at com.google.common.base.Preconditions.checkState(Preconditions.java:174)
at io.grpc.internal.ServerCallImpl.sendHeaders(ServerCallImpl.java:103)
at io.grpc.stub.ServerCalls$ServerCallStreamObserverImpl.onNext(ServerCalls.java:282)
at ServiceImp.login(ServiceImp.java:20)
at tourism.RemoteServiceGrpc$MethodHandlers.invoke(RemoteServiceGrpc.java:187)
at io.grpc.stub.ServerCalls$1$1.onHalfClose(ServerCalls.java:148)
at io.grpc.internal.ServerCallImpl$ServerStreamListenerImpl.halfClosed(ServerCallImpl.java:262)
at io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$2.runInContext(ServerImpl.java:572)
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:52)
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:117)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Java server:
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import tourism.RemoteServiceGrpc;
import tourism.Service;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Andu on 21/05/2017.
*/
public class ServerGrpc {
Logger logger= Logger.getLogger(ServerGrpc.class.getName());
private final Server server;
private final int port;
public ServerGrpc(int p){
port=p;
server= ServerBuilder.forPort(port).addService(new ServiceImp()).build();
}
public void start() throws IOException {
server.start();
logger.info("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
// Use stderr here since the logger may has been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
ServerGrpc.this.stop();
System.err.println("*** server shut down");
}
});
}
public void stop() {
if (server != null) {
server.shutdown();
}
}
void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
private class ServiceImp extends RemoteServiceGrpc.RemoteServiceImplBase {
Logger log=Logger.getLogger(ServiceImp.class.getName());
#Override
public void login(Service.LoginUserDTO request, StreamObserver<Service.Response> responseStreamObserver){
super.login(request,responseStreamObserver);
log.log(Level.INFO,"Request from "+request.getEmail());
Service.Response response= Service.Response.newBuilder().setMessage("Hello "+request.getEmail()+", I know your password: "+request.getPassword()).build();
responseStreamObserver.onNext(response);
responseStreamObserver.onCompleted();
}
}
}
C# Client:
namespace testGrpc2
{
class MainClass
{
public static void Main(string[] args)
{
var channel = new Channel("127.0.0.1:61666",ChannelCredentials.Insecure);
var client = new RemoteService.RemoteServiceClient(channel);
Response response=client.Login(new LoginUserDTO{Email="ex#ex.com",Password="notmypassword"});
Console.WriteLine(response);
Console.ReadKey();
}
}
}
I managed to find the source of the problem. For anyone else having this problem:
Make sure your .proto file is identical for both client and server and it has the same package. When the client calls a method on the remote server, it uses the full name of the remote class and the package.
However this was not the reason why the method appeared as unimplemented to the client. It was this:
super.login(request,responseStreamObserver);
Calling the super method login sends an async UNIMPLEMENTED error code back to the client. This is the login() method in the generated class:
public void login(LoginUserDTO request,StreamObserver<Response> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_LOGIN, responseObserver);
}
So make sure in the implementation of your service methods you don't call the super method as it will appear to the client as UNIMPLEMENTED. If you generate #Override methods using IntelliJ IDEA it will add the super method call. Make sure to delete it.
For me it was that I forget adding endpoint of gRpc service in startup class.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
//Add your endpoint here like this
endpoints.MapGrpcService<YourProtoService>();
});
For me, using the C# client, the problem was that I wasn't overriding the generated service method.
Thanks to Alexandru - this helped solve my problem with Akka gRPC client and Python grPC server. In my case, I had same packages and preamble in .proto file but had eliminated message classes and gRPC functions not needed for this specific use case in the Python gRPC server. When I made the .proto files identical, everything worked and I no longer received UNIMPLEMENTED errors. This is needed for languages beyond the C#/Java example cited. Thanks again.
My server and client were both java, and the problem was removed after closing and opening the project in IntelliJ!!
I am using JPachube.jar and Matlab in order to send data to my datastream. This java code works on my machine:
package smartclassroom;
import Pachube.Data;
import Pachube.Feed;
//import Pachube.FeedFactory;
import Pachube.Pachube;
import Pachube.PachubeException;
public class SendFeed {
public static void main(String arsg[]) throws InterruptedException{
SendFeed s = new SendFeed(0.0);
s.setZainteresovanost(0.3);
double output = s.getZainteresovanost();
System.out.println("zainteresovanost " + output);
try {
Pachube p = new Pachube("MYAPIKEY");
Feed f = p.getFeed(MYFEED);
f.updateDatastream(0, output);
} catch (PachubeException e) {
System.out.println(e.errorMessage);
}
}
private double zainteresovanost;
public SendFeed(double vrednost) {
zainteresovanost = vrednost;
}
public void setZainteresovanost(double vrednost) {
zainteresovanost = vrednost;
}
public double getZainteresovanost() {
return zainteresovanost;
}
}
but I need to do this from Matlab. I have tried rewriting example (example from link is working on my machine): I have compile java class with javac and added JPachube.jar and SendFeed.class into path and then utilize this code in Matlab:
javaaddpath('C:\work')
javaMethod('main','SendFeed','');
pachubeValue = SendFeed(0.42);
I get an error:
??? Error using ==> javaMethod
No class SendFeed can be located on Java class path
Error in ==> post_to_pachube2 at 6
javaMethod('main','SendFeed','');
This is strange because, as I said example from the link is working.
Afterwards, I decided to include JPachube directly in Matlab code and to write equivalent code in Matlab:
javaaddpath('c:\work\JPachube.jar')
import Pachube.Data.*
import Pachube.Feed.*
import Pachube.Pachube.*
import Pachube.PachubeException.*
pachube = Pachube.Pachube('MYAPIKEY');
feed = pachube.getFeed(MYFEED);
feed.updateDatastream(0, 0.54);
And I get this error:
??? No method 'updateDatastream' with matching signature found for class 'Pachube.Feed'.
Error in ==> post_to_pachube2 at 12
feed.updateDatastream(0, 0.54);
So I have tried almost everything and nothing! Any method making this work will be fine for me. Thanks for help in advance!
This done trick for me (answer from here)
javaaddpath('c:\work\httpcore-4.2.2.jar');
javaaddpath('c:\work\httpclient-4.2.3.jar');
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
httpclient = DefaultHttpClient();
httppost = HttpPost('http://api.cosm.com/v2/feeds/FEEDID/datastreams/0.csv?_method=put');
httppost.addHeader('Content-Type','text/plain');
httppost.addHeader('X-ApiKey','APIKEY');
params = StringEntity('0.7');
httppost.setEntity(params);
response = httpclient.execute(httppost);
I would rather use built-in methods. Matlab hasurlread/urlwrite, which could work if all you wish to do is request some CSV data from Cosm API. If you do need to use JSON, it can be handled in Matlab via a plugin.
Passissing the Cosm API key, that can be done via key parameter like so:
cosm_feed_url = "https://api.cosm.com/v2/feeds/61916.csv?key=<API_KEY>"
cosm_feed_csv = urlread(cosm_feed_url)
However, the standard library methods urlread/urlwrite are rather limited. In fact, the urlwrite function is only designed for file input, and I cannot even see any official example of how one could use a formatted string instead. Creating a temporary file would reasonable, unless it's only a few lines of CSV.
You will probably need to use urlread2 for anything more serious.
UPDATE: it appears that urlread2 can be problematic.
I have a java we application that is working with velocity. I get two variables in the first page via url that I extract using ureq.getParameter() method. One of the other classes that has a velocity container and I need to send one of the variables from the url to this velocity container. I tried creating an instance of the first class in the second class and using getVariable name method to do that but it did not work. Can someone tell me how I can do this?
Class 1:
package org.olat.dispatcher;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.olat.core.gui.UserRequest;
public class RemoteLoginformDispatcher implements Dispatcher {
private static final String PARAM_newUrl = "ret";
private static String newURL;
#Override
public void execute(
final HttpServletRequest request,
final HttpServletResponse response,
final String uriPrefix) {
UserRequest ureq = null;
try {
ureq = new UserRequest(uriPrefix, request, response);
newURL = ureq.getParameter(PARAM_newUrl);
} catch () {
}
}
public String getURL(){
return newURL;
}
}
Class 2:
public class BaseChiefController extends DefaultChiefController implements ContentableChiefController {
//Velocity container mainvc created here. It interacts with a html file. Removed the code that would not really matter
//mainvc.contextPut("newURL", "something");
//The below statement works. When I try with something, the something appears in the html file.
mainvc.contextPut("newURL", myLogin.getURL());
}
To create an instance of another class, simply create a "public CLASSNAME" method, and inside define all class variables with the "this" modfier. Then, call out the function you wish to use from that method, and when you want to use the class, just do "new CLASSNAME(args);"
Although, I am not really sure I am understanding your question.
Maybe this is your answer. You can use variables from one class to another class by making the variable static, then doing "CLASSNAME.VARIABLENAME = WHATEVER".
EDITED:
Okay, so as far as I can tell, you are using a method to return a static value from the class, which is much slower than just doing "newURL", RemoteLoginformDispatcher.newURL);.
Why not try this, as it is probably faster, and it should always work if newURL is defined. Otherwise, you have a different problem, and newURL is not being defined. If this is the case, try printing the caught Exception.