Interface analog in Swift for callbacks realization - swift

Please, help me to make interface in Swift to use it for callbacks purposes.
Example in Java:
public interface ErrorListener {
void onError(String errorMsg);
}
class SomeUiClass implements ErrorListener {
public SomeUiClass () {
SomeWorkingClass s = new SomeWorkingClass();
s.setErrorListener(this);
s.doSomething(true);
}
#Override
void onError(String errorMsg) {
System.out.println("Error msg: " + errorMsg);
}
}
class SomeWorkingClass {
ErrorListener listener;
void setErrorListener (ErrorListener listener) {
this.listener = listener;
}
void doSomething (boolean withError) {
if (withError) listener.onError("Test error");
}
}
//....
SomeUiClass ui = new SomeUiClass(); // prints: Error msg: Test error
So, I tried to use protocol in Swift for this purpose, but I didn't understand, how to use it properly.

It would look like this in swift
protocol ErrorListener {
func onError(errorMsg:String)
}
class SomeUiClass : UIViewController , ErrorListener {
func onError(errorMsg:String)
print("Error msg: ", errorMsg)
}
}
class SomeWorkingClass : UIViewController{
weak var listener:ErrorListener?
func setErrorListener (listener:ErrorListener) {
self.listener = listener
}
}
let ui = SomeUiClass() // prints: Error msg: Test error

Related

vertx.executeBlocking failing

I am new to vertx and am trying to execute a function1 using vertx.executeBlocking from ABCHandler.java
public class ABCHandler implements Handler<RoutingContext> {
public ABCHandler( Vertx vertx)
{this.vertx =vertx;}
#Override
public void handle(RoutingContext routingContext) {
vertx.executeBlocking(future -> {
function1(routingContext, as ->
{
if (as.failed()) {
future.fail(as.cause());
} else {
future.complete(as.result());
}
});
}, rs -> {
if (rs.failed()) {
routingContext.response().putHeader(CONTENT_TYPE,
"application/json").setStatusCode(Integer.valueOf(401)).end("error");
} else {
routingContext.put("key_1", rs.result());
routingContext.next();
}
});
}
}
ABCHandler is meant to validate some data before request is routed to actual URI. But after routingContext.next(); I am getting 500 (Internal server error).
WebClientCreator.getWebClient(vertx);
Router router = Router.router(vertx);
router.route().handler(new ABCHandler(vertx));
router.post(AgentBindingConstants.AGENT_ENROLLMENT_URI).handler(
BodyHandler.create().setBodyLimit(10000));
router.post("/abc").handler(routingContext -> {
//some code
});
Also, when I run same code as non blocking it works.
Any help here is much appreciated.

Xamarin WebView Not loading stream which comes from webrtc

class MyWebViewRenderer : WebViewRenderer
{
Activity mContext;
public MyWebViewRenderer(Context context) : base(context)
{
this.mContext = context as Activity;
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
Control.Settings.JavaScriptEnabled = true;
Control.ClearCache(true);
Control.Settings.DomStorageEnabled = true;
Control.Settings.PluginsEnabled = true;
Control.Settings.SetAppCacheEnabled(true);
Control.Settings.CacheMode = CacheModes.NoCache;
Control.Settings.SetRenderPriority(WebSettings.RenderPriority.High);
Control.Settings.LightTouchEnabled = true;
Control.SetWebChromeClient(new MyWebClient(mContext));
Control.SetWebViewClient(new SSLTolerentWebViewClient());
Control.LoadUrl(Control.Url);
}
public class MyWebClient : WebChromeClient
{
Activity mContext;
public MyWebClient(Activity context)
{
this.mContext = context;
}
[TargetApi(Value = 21)]
public override void OnPermissionRequest(PermissionRequest request)
{
mContext.RunOnUiThread(() =>
{
request.Grant(request.GetResources());
});
}
}
private class SSLTolerentWebViewClient : WebViewClient
{
public override void OnReceivedSslError(Android.Webkit.WebView view, SslErrorHandler handler, SslError error)
{
handler.Proceed(); // Ignore SSL certificate errors
}
public override void OnLoadResource(Android.Webkit.WebView view,string url)
{
}
}
}
Unfortunately, Android doesn't support WebRTC on its native webview yet, as you can see in the official documentation: https://developer.chrome.com/multidevice/webview/overview
It's not your code. You would have to find a way around it.

ABP EF Core multiple DbContext access in IDomainService throws transaction error

The specified transaction is not associated with the current connection. Only transactions associated with the current connection may be used.
How do I use multiple DbContext in one transaction?
Update 1
If I use ExistingConnection,
then all the DbContext will use the same connection string.
Did I add multiple DbContext in the wrong way?
In EntityFrameworkModule:
public override void PreInitialize()
{
var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
Configuration.Modules.AbpEfCore().AddDbContext<BPDbContext>(options =>
{
if (options.ExistingConnection != null)
{
options.DbContextOptions.UseSqlServer(options.ExistingConnection);
}
else
{
options.DbContextOptions.UseSqlServer(configuration.GetConnectionString(ABPCoreConsts.BPConnectionStringName));
}
//options.DbContextOptions.UseSqlServer(
// configuration.GetConnectionString(ABPCoreConsts.BPConnectionStringName));
});
Configuration.Modules.AbpEfCore().AddDbContext<EPlusDBConext>(options =>
{
if (options.ExistingConnection != null)
{
options.DbContextOptions.UseSqlServer(options.ExistingConnection);
}
else
{
options.DbContextOptions.UseSqlServer(configuration.GetConnectionString(ABPCoreConsts.EECPlusConnectionStringName));
}
//options.DbContextOptions.UseSqlServer(
// configuration.GetConnectionString(ABPCoreConsts.EECPlusConnectionStringName));
});
Configuration.Modules.AbpEfCore().AddDbContext<ProjectManageDbContext>(options =>
{
if (options.ExistingConnection != null)
{
options.DbContextOptions.UseSqlServer(options.ExistingConnection);
}
else
{
options.DbContextOptions.UseSqlServer(configuration.GetConnectionString(ABPCoreConsts.PMConnectionStringName));
}
//options.DbContextOptions.UseSqlServer(
// configuration.GetConnectionString(ABPCoreConsts.PMConnectionStringName));
});
RegisterGenericRepositories();
}
Update 2
I got it to work by implementing IConnectionStringResolver for custom connections:
public class MyDBConnectionStringResolver : DefaultConnectionStringResolver
{
public override string GetNameOrConnectionString(ConnectionStringResolveArgs args)
{
var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
switch (args["DbContextType"].ToString())
{
case "ABPCore.EPlusDBConext":
return configuration.GetConnectionString(ABPCoreConsts.EECPlusConnectionStringName);
case "ABPCore.BPDbContext":
return configuration.GetConnectionString(ABPCoreConsts.BPConnectionStringName);
case "ABPCore.ProjectManageDbContext":
return configuration.GetConnectionString(ABPCoreConsts.PMConnectionStringName);
}
return string.Empty;
}
}
Don't forget to replace service in EntityFrameworkModule's PreInitialize method:
Configuration.ReplaceService<IConnectionStringResolver, MyDbConnectionStringResolver>(DependencyLifeStyle.Transient);
Add this in *DbContextConfigurer.cs:
public static void Configure(DbContextOptionsBuilder<*DbContext> builder, DbConnection connection)
{
builder.UseSqlServer(connection);
}
Change this in *EntityFrameworkModule.cs:
public override void PreInitialize()
{
if (!SkipDbContextRegistration)
{
Configuration.Modules.AbpEfCore().AddDbContext<*DbContext>(options =>
{
if (options.ExistingConnection != null)
{
options.DbContextOptions.UseSqlServer(options.ExistingConnection);
}
else
{
options.DbContextOptions.UseSqlServer(options.ConnectionString);
}
});
}
}
Reference: https://github.com/aspnetboilerplate/module-zero-core-template/commit/da522e76ca2ecefdb7670f009f78575c5b97b4a0
Important
If each DbContext has its own connection string, you need to implement IConnectionStringResolver as explained here and replace the service:
Configuration.ReplaceService<IConnectionStringResolver, MyConnectionStringResolver>(DependencyLifeStyle.Transient);

How implement akka actor in functional style with java

I have simple counter actor implemented in java:
public class CounterJavaActor extends UntypedActor {
int count = 0;
#Override
public void onReceive(Object message) throws Exception {
if (message.equals("incr")) {
count += 1;
} else if (message.equals("get")) {
sender().tell(count, self());
}
}
}
In courses on coursera "Functional reactive programming in scala", I saw functional impementation of counter:
/**
* Advantages:
* state change is explicit
* state is scoped to current behaviour
*/
class CounterScala extends Actor{
def counter(n: Int) : Receive = {
case "incr" => context.become(counter(n+1))
case "get" => sender ! n
}
def receive = counter(0)
}
Upd:
My problem, that in java i can't make recourse functional call like in scala counter(n+1). What it means:
public class CounterJava8Actor extends AbstractActor {
//counter(0) in scala
private PartialFunction<Object, BoxedUnit> counter;
private int n = 0;
public CounterJava8Actor() {
counter =
ReceiveBuilder.
matchEquals("get", s -> {
sender().tell(n, self());
}).
matchEquals("inc", s -> {
//become(counter(n+1) in scala
context().become(counter);
}).build();
receive(counter);
}
}
It is possible to implement it in functional style with java?
According to docs you can use become/unbecome in java 8
http://doc.akka.io/docs/akka/snapshot/java/lambda-actors.html#become-unbecome
here is the sample code copied from there
public class HotSwapActor extends AbstractActor {
private PartialFunction<Object, BoxedUnit> angry;
private PartialFunction<Object, BoxedUnit> happy;
public HotSwapActor() {
angry =
ReceiveBuilder.
matchEquals("foo", s -> {
sender().tell("I am already angry?", self());
}).
matchEquals("bar", s -> {
context().become(happy);
}).build();
happy = ReceiveBuilder.
matchEquals("bar", s -> {
sender().tell("I am already happy :-)", self());
}).
matchEquals("foo", s -> {
context().become(angry);
}).build();
receive(ReceiveBuilder.
matchEquals("foo", s -> {
context().become(angry);
}).
matchEquals("bar", s -> {
context().become(happy);
}).build()
);
}
}
Or you can use UntypedActor like explained in the docs here
http://doc.akka.io/docs/akka/snapshot/java/untyped-actors.html
public class Manager extends UntypedActor {
public static final String SHUTDOWN = "shutdown";
ActorRef worker = getContext().watch(getContext().actorOf(
Props.create(Cruncher.class), "worker"));
public void onReceive(Object message) {
if (message.equals("job")) {
worker.tell("crunch", getSelf());
} else if (message.equals(SHUTDOWN)) {
worker.tell(PoisonPill.getInstance(), getSelf());
getContext().become(shuttingDown);
}
}
Procedure<Object> shuttingDown = new Procedure<Object>() {
#Override
public void apply(Object message) {
if (message.equals("job")) {
getSender().tell("service unavailable, shutting down", getSelf());
} else if (message instanceof Terminated) {
getContext().stop(getSelf());
}
}
};
}
To know how to add parameter to Procedure you can see this answer:
Akka/Java getContext().become with parameter?
and here is actual solution with java 8
private PartialFunction<Object, BoxedUnit> counter(final int n) {
return ReceiveBuilder.
matchEquals("get", s -> {
sender().tell(n, self());
}).
matchEquals("inc", s -> {
context().become(counter(n + 1));
}).build();
}
public CounterJava8Actor() {
receive(counter(0));
}

Netbeans QuickSearch Result to Lookup

Well, I'd like to provide QuickSearch result inside application, and, of course, through the lookup.
Searching works well, but found result is not visible through global lookup.
Can someone help to overcome this issue ?
Here is th code for a quicksearch :
public class QSERSCompany implements SearchProvider {
#Override
public void evaluate(SearchRequest request, SearchResponse response) {
try {
for (Company k : queries.ERSQuery.allCompanies()) {
if (k.getCompanyName().toLowerCase().contains(request.getText().toLowerCase())) {
if (!response.addResult(new SearchResult(k), k.getCompanyName())) {
return;
}
}
}
} catch (NullPointerException npe) {
}
}
private static class SearchResult implements Runnable, Lookup.Provider {
private final Company company;
private final InstanceContent ic = new InstanceContent();
private final Lookup lookup = new AbstractLookup(ic);
public SearchResult(Company c) {
this.company= c;
}
#Override
public void run() {
ic.add(company);
try {
StatusDisplayer.getDefault().setStatusText(
company.getCompanyName()
+ ", " + company.getAddress()
+ ", " + company.getCity());
} catch (NullPointerException npe) {
}
}
#Override
public Lookup getLookup() {
return lookup;
}
}
}
And this is partof the code which listens for a Company object :
public final class ManagementPodatakaTopComponent extends TopComponent {
private Lookup.Result<Company> companyLookup = null;
...
private Company selectedCompany;
...
#Override
public void componentOpened() {
companyLookup = Utilities.actionsGlobalContext().lookupResult(Company.class);
companyLookup .addLookupListener(new LookupListener() {
#Override
public void resultChanged(LookupEvent le) {
Lookup.Result k = (Lookup.Result) le.getSource();
Collection<Company> cs = k.allInstances();
for (Company k1 : cs) {
selectedCompany = k1;
}
setCompanyTextFields(selectedCompany);
jTP_DataManagement.setVisible(true);
jPanel_Entiteti.setVisible(true);
}
});
}
A SearchResult which provides a lookup? Never seen this in the wild.
Please ask at nbdev#netbeans.org to get better feedback (probably from one of the NB devs)
I finally managed somehow to get what I want :
First off, define interface:
public interface ICodes {
public Code getCode();
}
Then, we implement quick search :
#ServiceProvider(service = ICodes.class)
public class ClientServicesQS implements SearchProvider, ICodes {
private static Code code = null;
#Override
public void evaluate(SearchRequest request, SearchResponse response) {
try {
for (Code c : INFSYS.queries.INFSistemQuery.ByersByName(request.getText())) {
if (!response.addResult(new SearchResult(c),
c.getName() + " ,Code: " + c.getByerCode()
+ (c.getAddress() != null ? ", " + c.getAddress() : ""))) {
return;
}
}
} catch (NullPointerException npe) {
StatusDisplayer.getDefault().setStatusText("Error." + npe.getMessage());
}
}
#Override
public Code getCode() {
return ClientServicesQS.sifra;
}
private static class SearchResult implements Runnable {
private final Code code;
public SearchResult(Code code) {
this.code= code;
}
#Override
public void run() {
try {
ClientServicesQS.code= this.code;
OpenTopComponent("ClientServicesTopComponent");
} catch (NullPointerException e) {
Display.messageBaloon("Error.", e.toString() + ", " + e.getMessage(), Display.TYPE_MESSAGE.ERROR);
}
}
}
}
Finally, we implement lookup in other module through platform.
Because I want to call lookup whenever componentOpen, oe componentActivated is invoked, it is usefull first to define :
private void QSCodeSearch() {
try {
ICode ic= Lookup.getDefault().lookup(ICode.class);
if ((code = ic.getCode()) != null) {
.
.
.
// setup UI components with data from lookup
.
.
.
}
} catch (Exception e) {
}
}
And when topcomponent is activated, we call QSCodeSearch() in :
#Override
public void componentOpened() {
...
QSCodeSearch()
...
}
...
#Override
public void requestActive() {
...
QSCodeSearch()
...
}