how to resolve "java.lang.NoClassDefFoundError: org/apache/velocity/context/Context" - web-services

I'm a new learner of apache cxf. in the first program i implement, i encoutered the following exception( this is what my console display):
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/velocity/context/Context
The java code source i run is
package com.ttdev;
import org.apache.cxf.tools.wsdlto.WSDLToJava;
public class CodeGenerator {
/**
* #param args
*/
public static void main(String[] args) {
System.out.println("debug");
WSDLToJava.main(new String[] {
"-server",
"-d", "src/main/java",
"src/main/resources/Service.wsdl" });
System.out.println("Done!");
}
}
so how can i resolve this problem.

You need Apache Velocity on your classpath.

Check your Pom->DependencyHierarchy -> Filter "velocity"
In which package it is found , Probably it was not loaded properly.
In mycase it was C:\Users\MyUser.m2\repository\org\apache\velocity
Delete that and run "mvn clean package -DskipTests" from console, it will download all necessary packages.

Related

How to fix "java.lang.NoClassDefFoundError: com/microsoft/azure/eventhubs/EventHubClient$" error in Java

Java Version: 1.8
Azure EventHubs Version: 3.0.1
I'm trying to connect to my EventHubClient by calling:
EventHubClient.createFromConnectionStringSync(connStr.toString(), executorService)
However, this call is throwing a NoClassDefFoundError of the following:
java.lang.NoClassDefFoundError: com/microsoft/azure/eventhubs/EventHubClient$
Usually when I run into a NoClassDefFoundError, it is because I didn't import the corresponding package. However, in this case, I have the Azure EventHub package imported. The thing that is confusing me the most is the '$' at the end of EventHubClient.
Has anyone ran into this issue before and know what may be causing it?
Firstly, i suppose that the official code is totally right and nothing wrong with your jdk version and event hub package version because i tested the sample code with your environment and it works for me.
dependencies:
Sample code:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.microsoft.azure.eventhubs.ConnectionStringBuilder;
import com.microsoft.azure.eventhubs.EventData;
import com.microsoft.azure.eventhubs.EventHubClient;
import com.microsoft.azure.eventhubs.EventHubException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class SimpleSend {
public static void main(String[] args)
throws EventHubException, ExecutionException, InterruptedException, IOException {
final ConnectionStringBuilder connStr = new ConnectionStringBuilder()
.setNamespaceName("jaygongeventhub")
.setEventHubName("jaygong")
.setSasKeyName("RootManageSharedAccessKey")
.setSasKey("4RXaJ2NPwz635HYlOpKGMCh89N/9i1kz3PSAC9WeYq0=");
final Gson gson = new GsonBuilder().create();
final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
final EventHubClient ehClient = EventHubClient.createFromConnectionStringSync(connStr.toString(), executorService);
try {
for (int i = 0; i < 10; i++) {
String payload = "Message " + Integer.toString(i);
byte[] payloadBytes = gson.toJson(payload).getBytes(Charset.defaultCharset());
EventData sendEvent = EventData.create(payloadBytes);
ehClient.sendSync(sendEvent);
}
System.out.println(Instant.now() + ": Send Complete...");
System.out.println("Press Enter to stop.");
System.in.read();
} finally {
ehClient.closeSync();
executorService.shutdown();
}
}
}
Output:
Secondly, based on your error detail: NoClassDefFoundError,which is different with ClassNotFoundException. ClassNotFoundException comes when JVM tries to the load a class at runtime dynamically means you give the name of the class at runtime and then JVM tries to load it and if that class is not found in the classpath it throws java.lang.ClassNotFoundException. While in the case of NoClassDefFoundError the problematic class was present during Compile time and that's why the program successfully compiled but not available during runtime for any reason.
I suggest you checking below solutions or points to try to solving the issue:
1) The class is not available in Java Classpath.
2) You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
3) Any start-up script is overriding Classpath environment variable.
4) Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
4) Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
5) If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Read more: https://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz62y4liZ3G
Read more: https://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz62y4NPiEB

Android Studio Error : Cannot resolve symbol CreateTodoInput and CreateTodoMutation

I am trying to build an Android app using AWS Amplify CLI.
I am following the AWS documentation. However, I am getting this error, in Android Studio:
Cannot resolve symbol CreateTodoInput and CreateTodoMutation
I have pasted all the dependencies as present in the documentation in my app and project Gradle files.
I found a similar question (Can not resolve symbol CreateTodoInput), but the answer provided doesn't resolve my issue.
My entire code is in MainActivity.java:
package com.example.testamplify;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.amazonaws.mobile.config.AWSConfiguration;
import com.amazonaws.mobileconnectors.appsync.AWSAppSyncClient;
import com.apollographql.apollo.GraphQLCall;
import com.apollographql.apollo.exception.ApolloException;
import javax.annotation.Nonnull;
public class MainActivity extends AppCompatActivity {
private AWSAppSyncClient mAWSAppSyncClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAWSAppSyncClient = AWSAppSyncClient.builder()
.context(getApplicationContext())
.awsConfiguration(new AWSConfiguration(getApplicationContext()))
.build();
runMutation();
}
public void runMutation() {
CreateTodoInput createTodoInput = CreateTodoInput.builder()
.name("Use AppSync")
.description("Realtime and Offline")
.build();
mAWSAppSyncClient
.mutate(CreateTodoMutation.builder()
.input(createTodoInput).build()
)
.enqueue(mutationCallback);
}
private GraphQLCall.Callback<CreateTodoMutation.Data> mutationCallback =
new GraphQLCall.Callback<CreateTodoMutation.Data>() {
#Override
public void onResponse(#Nonnull Response<CreateTodoMutation.Data> response) {
Log.i("Results", "Added Todo");
}
#Override
public void onFailure(#Nonnull ApolloException e) {
Log.e("Error", e.toString());
}
};
}
Syncing my project with gradle files resolved the issue !!
I had the same problem as I'm new and experimenting with this too. I think CreateTodo is a type of variable. Download this example of an android app provided by AWS, found here. Open the ListEventsActivity, on line 77. You will see this same code, hope it helps you understand, it helped me.
Retry the tutorial again, and when you use amplify add api, after amplify push.
It'll ask the follow Do you want to generate code for your newly created GraphQL API. At first i choose no, and the folder graphql was not generated.
So, when the prompt ask
Do you want to generate code for your newly created GraphQL API
You have to answer yes and configure with the default values.
At least, that was wrong wit me, give it a try.

Custom Execution Function in WSO2

I am trying to write a simple custom function extension for WS02 (4.2.0). My function basically takes in a String and returns the upper case. This is meant to be a first step POC for a more advanced custom function.
I implemented a class that extended the org.wso2.siddhi.core.executor.function.FunctionExecutor class, and created a ams.siddhiext file. I then packaged the class and the siddhiext in a JAR file using the maven-bundle plugin.
My function class looks like this
public class AnomalyDetector extends FunctionExecutor {
private final static Logger LOG = LoggerFactory.getLogger(AnomalyDetector
.class);
#Override
protected void init(ExpressionExecutor[] expressionExecutors, ExecutionPlanContext executionPlanContext) {
LOG.info("In AD:init()");
}
#Override
protected Object execute(Object[] objects) {
return null;
}
#Override
protected Object execute(Object o) {
LOG.info("In AD:process(" + o.toString() + ")");
String eventData = (String) o;
LOG.info("Event data : " + eventData);
if (eventData != null) {
return eventData.toUpperCase();
} else {
return "Null event data";
}
}
#Override
public void start() {
LOG.info("In AD:start()");
}
#Override
public void stop() {
}
#Override
public Map<String, Object> currentState() {
return null;
}
#Override
public void restoreState(Map<String, Object> map) {
}
#Override
public Attribute.Type getReturnType() {
return Attribute.Type.STRING;
}
}
I then put the jar in the /repository/components/lib/ since /repository/components/dropins/ did not pick it up.
I have 2 issues that are blocking me currently.
I wanted to write a simple execution plan that takes a value from an input stream (String), invoke my custom function and write the output to an export stream.
#Plan:name('AMSExecutionPlan')
#Import('AMSStream:1.0.0')
define stream amsStream (metrics_json string);
#Export('AnomalyStream:1.0.0')
define stream anomalyStream (anomaly string);
from amsStream
select ams:findAnomaly(metrics_json) as anomaly
insert into anomalyStream
I get the following validation error.
What could be wrong with my execution plan?
Whenever I change my custom function class, rebuild the jar and replace it in the wso2 classpath, and then restart ws02, I dont see the changes reflected in ws02. The log lines that I print out in my custom function class reflect an older version of the code. What should I do to make changes to my Custom function class on a live ws02 instance?
Thanks in advance!
Can you bundle the jar as an OSGI bundle and try? There can be a issue when converting your jar to an OSGI bundle.
Validation error you have pointed suggest that your extension is not returning the return type properly. But I can see you have implemented getReturnType() correctly. So may be your source and actual running code might not be synced up due to issue 2. So let's address that first.
In WSO2 servers lib folder is used to add non-OSGi dependencies and dropins for OSGi dependencies. Fact that it works in lib and not in dropins suggest that your jar is not packed as a bundle. To achieve that please follow below pom file from String extension. There are two things to note.
[1] Usage of bundle packaging
[2] Usage of bundle plugin
Update your pom referencing this and then you will be able to add your bundle to dropins directly. Also this is the reason why your changes are not reflected. When you add your jar to lib server will internally convert it to an OSGi bundle and add to dropins. Now when you update the jar in lib again the one in dropins will not get updated. It will be the old bundle. Hence changes are not reflected. This issue will also go away when you update the pom and build the bundle correctly.
[1] https://github.com/wso2/siddhi/blob/v3.1.0/modules/siddhi-extensions/string/pom.xml#L29
[2] https://github.com/wso2/siddhi/blob/v3.1.0/modules/siddhi-extensions/string/pom.xml#L57
Hope this helps!!

MVC instrumentation & WebApi attribute routing for Sitecore 7.5

I have been trying to get WebApi working with Sitecore 7.5 (I was able to get the same code working with 7.2)
I have left in the config the reference to MVC 5.1
and
I am getting the following exception when I try to access a route mapped with an attribute:
[RoutePrefix("test/api/Other")]
[Route("{action=Get}")]
public class OtherController : ApiController
{
[HttpGet]
public string GetId()
{
return "test";
}
}
Message: "An error has occurred.", ExceptionMessage: "Value cannot be
null. Parameter name: key", ExceptionType:
"System.ArgumentNullException", StackTrace: " at
System.Collections.Generic.Dictionary2.FindEntry(TKey key) at
System.Collections.Generic.Dictionary2.TryGetValue(TKey key, TValue&
value) at
Sitecore.Services.Infrastructure.Web.Http.Dispatcher.NamespaceHttpControllerSelector.SelectController(HttpRequestMessage
request) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage
request, CancellationToken cancellationToken) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()"
The code that I have in the application start is the following:
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configure(ConfigureRoutes);
}
public static void ConfigureRoutes(HttpConfiguration config)
{
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
}
any help would be appreciated....
Starting with Sitecore 7.5 they are replacing the default IHttpControllerSelector with their own NamespaceHttpControllerSelector which doesn't support Attribute Routing.
However, it is possible to workaround this. You have to create your own version of NamespaceHttpControllerSelector and patch it into the initialize pipeline after this one:
Sitecore.Services.Infrastructure.Sitecore.Pipelines.ServicesWebApiInitializer, Sitecore.Services.Infrastructure.Sitecore
I have created both a Sitecore package and a NuGet package to do this depending on what you prefer and what your needs are.
Sitecore package
NuGet package
NuGet package (Custom)
The "Custom" package creates the code in your solution, so you can edit it yourself if you have special needs. The Sitecore package and the standard NuGet package just drops my assembly in the bin folder and creates a config file in App_Config\Include which patches the initialize pipeline.
If you want to look at the code, or read a bit more about the issue, have a look at my GitHub repository.

JAVA JAX-WS NullPointerException at javax.xml.ws.Service.getPort(Service.java:188)

I have simple "HelloWorld" web service deployed on jboss under ubuntu.
I have created simple client, but I can't get it to work. I'm getting NullPointerException each time I run the client.
Note that I'm running on Oracle Java 7 under Ubuntu.
Here is the code:
HelloWorldClient.java
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class HelloWorldClient {
public static void main(String[] args){
URL url;
try {
url = new URL("http://localhost:8080/WebServiceProject/helloWorld?wsdl");
QName qname = new QName("http:///", "HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
System.out.println(hello.sayHello("mkyong"));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
HelloWorld.java
import javax.jws.WebMethod;
import javax.jws.WebService;
#WebService
public interface HelloWorld {
#WebMethod
public String sayHello(String name);
}
Stacktrace:
Exception in thread "main" java.lang.NullPointerException
at com.sun.xml.internal.ws.model.RuntimeModeler.getPortTypeName(RuntimeModeler.java:1407)
at com.sun.xml.internal.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:334)
at com.sun.xml.internal.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:354)
at javax.xml.ws.Service.getPort(Service.java:188)
at HelloWorldClient.main(HelloWorldClient.java:18)
The exception is thrown at this line:
HelloWorld hello = service.getPort(HelloWorld.class);
I have had the same problem myself for a few days now, because the WSDL-file (and service) I was using was moved to a new URL. I finally found the solution here:
http://techtracer.com/2007/08/15/jax-ws-jaxp-tutorial-building-a-stockquote-web-service-client/
In short, everything (should have) started working after I re-generated all the auto-generated java and class files with the following command (on Windows/CygWin)
"C:/Program Files/Java/jdk1.8.0_31/bin/wsimport.exe" -keep https://domain.com/path_to_wsdl
I had some extra trouble because some old files were left around and clashing with the newly generated ones, but everything slowly started working after I moved all the old files to the recycle bin.
It can also happen if your web-service's implementation is different than the interface from your project.
If in your project you have HelloWorld.class declaring some methods that are not present on the web-service side, the getPort(HelloWorld.class) call will raise a null pointer exception.
You can double check the HelloWorld.class interface on your application and the one on the web-service itself to make sure they match.