How to use an Event Hub Trigger in a Java Azure Function - java

I am attempting to create a Java Azure Function that triggers off of an Azure Event Hub. I am following these code snippets: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs-trigger?tabs=java#example
Here is my code:
package com.function;
import com.microsoft.azure.functions.*;
import com.microsoft.azure.function.annotation.*;
import java.util.Optional;
public class function {
#FunctionName("MTI")
public void EventHubProcess(
#EventHubTrigger(name = "msg", eventHubName = "mticallhub", connection = "EHubConnectionString"), String message, final ExecutionContext context)
{
context.getLogger().info("Java HTTP trigger processed a request: " + message);
}
}
Here is the error I get when building:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project func-MTI-test-zyg-001: Compilation failure
[ERROR] /C:/JavaStuff/FunctionApps/func-MTI-test-zyg-001/src/main/java/com/function/Function.java:[34,105] illegal start of type
Here is the error popup in VSCode:
I've been looking for hours and exhausted page after page of Google searches. What am I doing wrong?

Please change
#EventHubTrigger(name = "msg", eventHubName = "mticallhub", connection = "EHubConnectionString"), String message, final ExecutionContext context)
to
#EventHubTrigger(name = "msg", eventHubName = "mticallhub", connection = "EHubConnectionString") String message, final ExecutionContext context)

Related

cdktf - HdinsightKafkaCluster - No stack could be identified for the construct at path

I'm trying to build cdktf - Java Infrastructure as Code for Azure.
On the HdInsight Kafka Cluster i'm not able to produce the correct cdktf classes.
I'm always running in:
Caused by: software.amazon.jsii.JsiiException: No stack could be identified for the construct at path 'dev-name-cluster'
Error: No stack could be identified for the construct at path 'dev-name-cluster'
My Code looks like:
public class KafkaAnnonymous extends TerraformStack {
public KafkaAnnonymous(Construct scope, String id, final Environment environment,`your text`
ResourceGroup rg, String storageAccount, Network network, KeyVault kv) {
super(scope, id);
AzurermProvider.Builder.create(this, "azureProvider")
.features(AzurermProviderFeatures.builder()
.build())
.subscriptionId("<SUBSCRIPTION_ID>")
.build();
AzurermBackend.Builder.create(this)
.resourceGroupName("g_rg")
.storageAccountName("g_storage_account_name")
.containerName("terraform")
.key(String.format("%s.terraform.tfstate", id))
.build();
create(scope, id, environment, rg, storageAccount, network, kv);
}
private final void create(Construct scope, String id, final Environment environment,
ResourceGroup rg, String storageAccount, Network network, KeyVault kv) {
HdinsightKafkaCluster.Builder
.create(scope, id)
.clusterVersion("2.4.1")
.resourceGroupName(rg.getResourceGroup().getName())
.name(id)
.location("westeurope")
.tier("Standard")
.componentVersion(componentVersion())
.gateway(gateway(password))
.storageAccount(storage(storageAccount))
.roles(roles(network, password))
.build();
}
...
}
}
Where is my fault?
Are you initialising this stack somewhere? e.g. in your Main.java? This part seems to be missing: https://github.com/hashicorp/terraform-cdk/blob/main/examples/java/aws/src/main/java/com/mycompany/app/Main.java#L50

Error while Streaming data from twitter using Spark Streaming

I am writing twitter connector to get data from twitter but i got following Exception while running.
i have create application for prints tweets and learn how to do spark streaming with twitter.
20/09/25 05:53:18 ERROR ReceiverTracker: Deregistered receiver for stream 0: Restarting receiver with delay 2000ms: Error starting Twitter stream - java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/en/configuration.html for details. See and register at http://apps.twitter.com/
at twitter4j.TwitterBaseImpl.ensureAuthorizationEnabled(TwitterBaseImpl.java:219)
at twitter4j.TwitterStreamImpl.sample(TwitterStreamImpl.java:161)
at org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:93)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.$anonfun$restartReceiver$1(ReceiverSupervisor.scala:198)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:659)
at scala.util.Success.$anonfun$map$1(Try.scala:255)
at scala.util.Success.map(Try.scala:213)
at scala.concurrent.Future.$anonfun$map$1(Future.scala:292)
at scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:33)
at scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:33)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:64)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Below is the code for this Application
package SparkStreaming
import org.apache.log4j.{Level, Logger}
import org.apache.spark.streaming.twitter.TwitterUtils
import org.apache.spark.streaming.{Seconds, StreamingContext}
import scala.io.Source
object Tweets {
Logger.getLogger("org").setLevel(Level.ERROR)
def main(args: Array[String]): Unit = {
setTweeter()
val ssc = new StreamingContext("local[*]","Tweets", Seconds(3))
val tweets = TwitterUtils.createStream(ssc,None)
val statuses = tweets.map(status => status.getText)
statuses.print()
ssc.start()
ssc.awaitTermination()
}
def setTweeter() : Unit = {
for ( line <- Source.fromFile("src/data/tweeter.txt").getLines())
{
val fields = line.split(" ")
if(fields.length == 2)
{
System.setProperty("tweeter4j.oauth." + fields(0), fields(1))
}
}
}
}
Can anyone Assist me to Resolve this problem ???

client for webservicex.net from WSDL

How do I actually get the weather from webservicex.net?
thufir#dur:~/NetBeansProjects/javaClientGlobalWeather$
thufir#dur:~/NetBeansProjects/javaClientGlobalWeather$ gradle clean shadowJar;java -jar build/libs/weather.jar
> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
- No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.
BUILD SUCCESSFUL in 2s
3 actionable tasks: 3 executed
Feb 16, 2018 2:42:10 AM net.bounceme.dur.java.soap.weather.App run
INFO: begin
Feb 16, 2018 2:42:11 AM net.bounceme.dur.java.soap.weather.Weather getWeather
INFO: Data Not Found
thufir#dur:~/NetBeansProjects/javaClientGlobalWeather$
java code:
package net.bounceme.dur.java.soap.weather;
import java.util.logging.Logger;
import net.webservicex.GetCitiesByCountry;
import net.webservicex.GetWeather;
import net.webservicex.GetWeatherResponse;
import net.webservicex.GlobalWeather;
import net.webservicex.GlobalWeatherSoap;
import net.webservicex.ObjectFactory;
public class Weather {
private static final Logger log = Logger.getLogger(App.class.getName());
public void getWeather(String country, String city) {
GlobalWeather gw = new GlobalWeather();
GlobalWeatherSoap gws = gw.getGlobalWeatherSoap();
String w = gws.getWeather(city, country);
log.info(w);
}
public void getWeather3(String country, String city) {
ObjectFactory o = new ObjectFactory();
GetWeather gw = o.createGetWeather();
gw.setCountryName(country);
gw.setCityName(city);
GetWeatherResponse gwr = o.createGetWeatherResponse();
gwr.setGetWeatherResult(city);
String r = gwr.getGetWeatherResult();
log.info(r);
}
public void getWeather2(String country, String city) {
log.info("getting weather");
GetCitiesByCountry g = new GetCitiesByCountry();
g.setCountryName(country);
log.fine(g.getCountryName());
GetWeather getWeather = new GetWeather();
getWeather.setCountryName(country);
getWeather.setCityName(city);
log.fine(getWeather.getCountryName());
log.fine(getWeather.getCityName());
log.info(getWeather.toString());
GetWeatherResponse weatherResponse = new GetWeatherResponse();
log.info("weather response result:\t" + weatherResponse.getGetWeatherResult());
log.info("end");
}
}
the stubs were generated by wsimport http://www.webservicex.net/globalweather.asmx?WSDL -Xnocompile. Looking through the generated classes, not sure how to actually use this service from Java.
Do Need to pass the WSDL to GlobalWeather or GlobalWeatherSoap? That would be odd, since they were generated with wsimport. Is this just a matter of knowing how to read the WSDL?
See also:
Working Soap client example

Discovering test with JUnit 5 doesn't execute LoggingListener (implementation of TestExecutionListeners)

I'm using JUnit Jupiter version 5.0.0 (Release version) and I'm trying to use the test discovery feature.
The documentation of Junit can be found in 7.1.1. Discovering Tests from http://junit.org/junit5/docs/5.0.0/user-guide/#launcher-api-discovery
My implementation is:
import static org.junit.platform.engine.discovery.ClassNameFilter.includeClassNamePatterns;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.LoggingListener;
public class MainPrueba {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
System.out.println("Runing thread INI");
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
.selectors(
selectPackage("org.package.qabootfx.test.ping")
//,selectClass(QabootfxApplicationTests.class)
)
.filters(
//includeClassNamePatterns(".*Test")
includeClassNamePatterns(".*")
)
.build();
Launcher launcher = LauncherFactory.create();
TestPlan testPlan = launcher.discover(request);
for (TestIdentifier root : testPlan.getRoots()) {
System.out.println("Root: " + root.toString());
for (TestIdentifier test : testPlan.getChildren(root)) {
System.out.println("Found test: " + test.toString());
}
}
// Register a listener of your choice
//TestExecutionListener listener = new SummaryGeneratingListener();
TestExecutionListener listener = LoggingListener.forJavaUtilLogging(); //new LoggingListener();
launcher.registerTestExecutionListeners(listener);
launcher.execute(request);
System.out.println("Runing thread END");
};
new Thread(task).start();
Thread.sleep(5000);
System.out.println("END");
}
}
Examining LoggingListener class implementation we can see that this must print to the console the results. For example:
package org.junit.platform.launcher.listeners;
#API(status = MAINTAINED, since = "1.0")
public class LoggingListener implements TestExecutionListener {
....
#Override
public void testPlanExecutionStarted(TestPlan testPlan) {
log("TestPlan Execution Started: %s", testPlan);
}
#Override
public void testPlanExecutionFinished(TestPlan testPlan) {
log("TestPlan Execution Finished: %s", testPlan);
}
...
}
and my Test class is:
public class QabootfxApplicationTest {
#Test
public void testAbout() {
System.out.println("TEST Execution.... QabootfxApplicationTests.testAbout()");
assertEquals(4, 5, "The optional assertion message is now the last parameter.");
}
}
I'm expecting see in the console something similar to:
2017-09-20 10:53:48.041 INFO 11596 --- TestPlan Execution Started: ....
2017-09-20 10:53:48.041 INFO 11596 --- TestPlan Execution Finished: ....
but I can't see nothing similar to "... TestPlan Execution Started...".
The console output is:
Runing thread INI
Root: TestIdentifier [uniqueId = '[engine:junit-jupiter]', parentId = null, displayName = 'JUnit Jupiter', legacyReportingName = 'JUnit Jupiter', source = null, tags = [], type = CONTAINER]
Found test: TestIdentifier [uniqueId = '[engine:junit-jupiter]/[class:org.package.qabootfx.test.ping.QabootfxApplicationTest]', parentId = '[engine:junit-jupiter]', displayName = 'QabootfxApplicationTest', legacyReportingName = 'org.package.qabootfx.test.ping.QabootfxApplicationTest', source = ClassSource [className = 'org.package.qabootfx.test.ping.QabootfxApplicationTest', filePosition = null], tags = [], type = CONTAINER]
TEST Executon.... QabootfxApplicationTests.testAbout()
Runing thread END
END
Could be a bug? or I'm implementing something wrong?
Why would you expect the listener created by LoggingListener.forJavaUtilLogging() to log anything at log level INFO... when the documentation explicitly states the following?
Create a LoggingListener which delegates to a java.util.logging.Logger using a log level of FINE.
If you want the LoggingListener to log messages at level INFO, you'll have to create it using the other factory method which accepts a log level like this LoggingListener.forJavaUtilLogging(Level.INFO).

secuesocial 3.0-M1 on play2.1.0?

I've been using play 2.1.0 for a while and I've been having trouble looking for a way to get securesocial to work. I tried different versions, even downloaded the latest typesafe activator to try to use it with play2.4 but no luck.
Does anyone know if can I use securesocial 3.0-M1 with play 2.1.0?
my controllers\application.java
package controllers;
import play.Logger;
import play.libs.F;
import play.mvc.Controller;
import play.mvc.Result;
import securesocial.core.BasicProfile;
import securesocial.core.RuntimeEnvironment;
import securesocial.core.java.SecureSocial;
import securesocial.core.java.SecuredAction;
import securesocial.core.java.UserAwareAction;w
import service.DemoUser;
import views.html.index;
import views.html.linkResult;
public class Application extends Controller {
public static Logger.ALogger logger =
Logger.of("application.controllers.Application");
private RuntimeEnvironment env;
public Application(RuntimeEnvironment env) {
this.env = env;
}
public Result index() {
if(logger.isDebugEnabled()){
logger.debug("access granted to index
DemoUser user = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);
return ok(index.render(user, SecureSocial.<DemoUser>env()));
}
#UserAwareAction
public Result userAware()
{
DemoUser demoUser = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);
String userName ;
if ( demoUser != null ) {
BasicProfile user = demoUser.main;
if ( user.firstName().isDefined() ) {
userName = user.firstName().get();
} else if ( user.fullName().isDefined()) {
userName = user.fullName().get();
} else {
userName = "authenticated user";
}
} else {
userName = "guest";
}
return ok("Hello " + userName + ", you are seeing a public page");
}
#SecuredAction(authorization = WithProvider.class, params = {"twitter"})
public Result onlyTwitter() {
return ok("You are seeing this because you logged in using Twitter");
}
#SecuredAction
public Result linkResult() {
DemoUser current = (DemoUser) ctx().args.get(SecureSocial.USER_KEY
}
public F.Promise currentUser() {
return SecureSocial.currentUser(env).map( new F.Function<Object, Result>() {
#Override
public Result apply(Object maybeUser) throws Throwable {
String id;
if ( maybeUser != null ) {
DemoUser user = (DemoUser) maybeUser;
id = user.main.userId();
} else {
id = "not available. Please log in.";
}
return ok("your id is " + id);
}
});
}
}
my routes
Home page
GET / #controllers.Application.index
GET /userAware #controllers.Application.userAware
GET /only-twitter #controllers.Application.onlyTwitter
GET /link-result #controllers.Application.linkResult
GET /current-user #controllers.Application.currentUser
GET /assets/*file controllers.Assets.at(path="/public", file)
-> /auth securesocial.Routes
my error
[info] Set current project to playMongoDemooo (in build file:/C:/Users/kayjee%20
lahong/demo2/)
[info] Updating {file:/C:/Users/kayjee%20lahong/demo2/}playMongoDemooo...
[info] Resolving org.hibernate.javax.persistence#hibernate-jpa-2.0-api;1.0.1.Fin
[info] Done updating.
--- (Running the application from SBT, auto-reloading is enabled) ---
[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
(Server started, use Ctrl+D to stop and go back to the console...)
[info] Compiling 6 Scala sources and 6 Java sources to C:\Users\kayjee lahong\de
mo2\target\scala-2.10\classes...
[error] C:\Users\kayjee lahong\demo2\conf\routes:10: Cannot use a method returni
ng play.libs.F.Promise[play.mvc.Result] as an Handler
[error] GET /current-user #controllers.Application.currentUser
[error] C:\Users\kayjee lahong\demo2\conf\routes:10: Cannot use a method returni
ng play.libs.F.Promise[play.mvc.Result] as an Handler
[error] GET /current-user #controllers.Application.currentUser
[error] two errors found
[error] (compile:compile) Compilation failed
[error] application -
thank you
For Play 2.4 compatibility use 3.0-M4 or newer. The version you were trying to use does not work with 2.4.

Categories

Resources