How could i inherit a class using github.parser without deprication warrings - javaparser

I am using Com.GitHub.java parser for generating java code. i am facing a problem for generating extends keywords
This line "extendsList.add(new ClassOrInterfaceType("CustomEndpointResource"));".
This statement is showing deprecated .that means it gives a warning.
How can i avoid this warning ? So, i can not use this statement. any alternative
way other than this deprecated statement (extendsList.add(new ClassOrInterfaceType).
My Source code:
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
​
public class ProductCreate2 {
​
public static void main(String[] args) {
CompilationUnit compilationUnit = new CompilationUnit();
compilationUnit.setPackageDeclaration("org.meveo.mymodule.resource");
compilationUnit.addImport("java.util", false, true);
ClassOrInterfaceDeclaration restEndpointClass = compilationUnit.addClass("ProductCreate",Modifier.Keyword.PUBLIC);
restEndpointClass.addSingleMemberAnnotation("Path",new StringLiteralExpr("myproduct"));
restEndpointClass.addMarkerAnnotation("RequestScoped");
var injectedfield=restEndpointClass.addField("CreateMyProduct", "CreateMyProduct", Modifier.Keyword.PRIVATE);
injectedfield.addMarkerAnnotation("Inject");
NodeList<ClassOrInterfaceType> extendsList = new NodeList<>();
extendsList.add(new ClassOrInterfaceType("CustomEndpointResource"));
restEndpointClass.setExtendedTypes(extendsList);
​
System.out.println(compilationUnit);
​
}
}
Expected output of my code:
class productCreate extends ABC
{
}

There can be multiple ways to avoid using the deprecated constructor. E.g. you can use the following instead:
ClassOrInterfaceType extendClass = new ClassOrInterfaceType();
extendClass.setName(new SimpleName("CustomEndpointResource"));
extendsList.add(extendClass);

i am facing another problem for generating this annotation line : #Path("/{uuid}").
Expected output of my code:
class productGet {
#Path("/{uuid}")
public Response getProduct() throws ServletException {
}
}

Related

Apache Pig : UDF : ERROR 1003: Unable to find an operator for alias fileterd

Wrote a custom UDF in pig by name vaidateUser which validates usernames.
public class ValidateUser extends FilterFunc {
public Boolean exec(Tuple tuple) throws IOException {
// custom validation code
}
}
The class is a part of default package and is part of pig_udfs.jar.
This JAR is used in the pig script : validateUsers.pig
REGISTER 'pig_udfs.jar';
users = load 'users.txt' using PigStorage(',') as (user:chararray);
validUsers = filter users by ValidateUser(user);
dump validUsers;
Tried executing the script using :
pig -x local validateusers.pig
Getting error as below, any inputs/ thoughts on resolving this would be appreciated !
Pig Stack Trace:
ERROR 1003: Unable to find an operator for alias fileterd
org.apache.pig.impl.logicalLayer.FrontendException: ERROR 1003: Unable to find an operator for alias fileterd
at org.apache.pig.PigServer.openIterator(PigServer.java:732)
at org.apache.pig.tools.grunt.GruntParser.processDump(GruntParser.java:615)
at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:303)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:168)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:144)
at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:90)
at org.apache.pig.Main.run(Main.java:500)
at org.apache.pig.Main.main(Main.java:107)
I didn't face any issue the custom filter UDF and its working fine, Can you try this?.
In the below example, i will filter out all the names which is not equal to "test".
users.txt
test
mike
test
john
PigScript:
REGISTER 'pig_udfs.jar';
users = load 'users.txt' using PigStorage(',') as (user:chararray);
validUsers = filter users by ValidateUser(user);
dump validUsers;
ValidateUser.java
import java.io.IOException;
import org.apache.pig.FilterFunc;
import org.apache.pig.data.Tuple;
public class ValidateUser extends FilterFunc {
#Override
public Boolean exec(Tuple input) throws IOException {
try {
String str = (String)input.get(0);
return (!str.equals("test"));
}
catch (IOException ee) {
throw ee;
}
}
}
Output:
(john)
(mike)
Makesure that you have set piggybank.jar in the classpath
> javac ValidateUser.java
> jar -cvf pig_udfs.jar ValidateUser.class
> pig -x local validateusers.pig

Any got Spring Boot working with cucumber-jvm?

I'm using spring boot as it removes all the boring stuff and let's me focus on my code, but all the test examples use junit and I want to use cucumber?
Can someone point me in the right direction to get cucumber and spring to start things up, do all the auto config and wiring and let my step definitions use auto wired beans to do stuff?
Try to use the following on your step definition class:
#ContextConfiguration(classes = YourBootApplication.class,
loader = SpringApplicationContextLoader.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class MySteps {
//...
}
Also make sure you have the cucumber-spring module on your classpath.
Jake - my final code had the following annotations in a superclass that each cucumber step definition class extended, This gives access to web based mocks, adds in various scopes for testing, and bootstraps Spring boot only once.
#ContextConfiguration(classes = {MySpringConfiguration.class}, loader = SpringApplicationContextLoader.class)
#WebAppConfiguration
#TestExecutionListeners({WebContextTestExecutionListener.class,ServletTestExecutionListener.class})
where WebContextTestExecutionListener is:
public class WebContextTestExecutionListener extends
AbstractTestExecutionListener {
#Override
public void prepareTestInstance(TestContext testContext) throws Exception {
if (testContext.getApplicationContext() instanceof GenericApplicationContext) {
GenericApplicationContext context = (GenericApplicationContext) testContext.getApplicationContext();
ConfigurableListableBeanFactory beanFactory = context
.getBeanFactory();
Scope requestScope = new RequestScope();
beanFactory.registerScope("request", requestScope);
Scope sessionScope = new SessionScope();
beanFactory.registerScope("session", sessionScope);
}
}
}
My approach is quite simple. In a Before hook (in env.groovy as I am using Cucumber-JVM for Groovy), do the following.
package com.example.hooks
import static cucumber.api.groovy.Hooks.Before
import static org.springframework.boot.SpringApplication.exit
import static org.springframework.boot.SpringApplication.run
def context
Before {
if (!context) {
context = run Application
context.addShutdownHook {
exit context
}
}
}
Thanks to #PaulNUK, I found a set of annotations that will work.
I posted the answer in my question here
My StepDefs class required the annotations:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = DemoApplication.class, loader = SpringApplicationContextLoader.class)
#WebAppConfiguration
#IntegrationTest
There is also a repository with source code in answer I linked.

Dynamic Method Invocation and JAXBElement Type on CXF

I wrote the small application below to list all the methods and of a soap service using Apache CXF library. This application lists all the methods of the service, but as it is seen on the output when you run this application, input parameters and return types of the service methods are JAXBElement for the complex types. I want cxf not to generate JAXBElement, instead I want the complex types in their original classes generated on runtime. As it is said on http://s141.codeinspot.com/q/1455881 , it can be done by setting generateElementProperty property's value to false for wsdl2java utility of cxf library, but I couldn't find the same parameter for dynamic method invocation with cxf library. I want to obtain input parameters and return types in their original types.
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import org.apache.cxf.binding.Binding;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingMessageInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.service.model.MessagePartInfo;
import org.apache.cxf.service.model.OperationInfo;
import org.apache.cxf.service.model.ServiceModelUtil;
public class Main {
public static void main(String[] args) {
URL wsdlURL = null;
try {
wsdlURL = new URL("http://path_to_wsdl?wsdl");
} catch (MalformedURLException e) {
e.printStackTrace();
}
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient(wsdlURL, classLoader);
Binding binding = client.getEndpoint().getBinding();
BindingInfo bindingInfo = binding.getBindingInfo();
Collection<BindingOperationInfo> operations = bindingInfo.getOperations();
for(BindingOperationInfo boi:operations){
OperationInfo oi = boi.getOperationInfo();
BindingMessageInfo inputMessageInfo = boi.getInput();
List<MessagePartInfo> parts = inputMessageInfo.getMessageParts();
System.out.println("function name: "+oi.getName().getLocalPart());
List<String> inputParams = ServiceModelUtil.getOperationInputPartNames(oi);
System.out.println("input parameters: "+inputParams);
for(MessagePartInfo partInfo:parts){
Class<?> partClass = partInfo.getTypeClass(); //here we have input parameter object on each iteration
Method[] methods = partClass.getMethods();
for(Method method:methods){
System.out.println("method: "+method);
Class<?>[] paramTypes = method.getParameterTypes();
for(Class paramType:paramTypes){
System.out.println("param: "+paramType.getCanonicalName());
}
Class returnType = method.getReturnType();
System.out.println("returns: "+returnType.getCanonicalName());
}
System.out.println("partclass: "+partClass.getCanonicalName());
}
}
System.out.println("binding: " + binding);
}
}
Create a binding file that looks like:
<jaxb:bindings
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.0"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" jaxb:extensionBindingPrefixes="xjc">
<jaxb:globalBindings generateElementProperty="false">
<xjc:simple />
</jaxb:globalBindings>
</jaxb:bindings>
and pass that into the JaxWsDynamicClientFactory via the createClient method that takes the List of binding files.

Java3D and Behaviours : KeyNavigatorBehaviour works fine, but not MouseRotate

I don't manage to give user mouse interaction to a ColorCube by using a MouseRotate. However, when i use a KeyNavigatorBehaviour, i can control the cube with keyboard as needed.
Here the code i used to test MouseRotate :
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.GraphicsConfigTemplate3D;
import javax.media.j3d.TransformGroup;
import javax.swing.JFrame;
import javax.vecmath.Point3d;
import com.sun.j3d.exp.swing.JCanvas3D;
import com.sun.j3d.utils.behaviors.mouse.MouseRotate;
import com.sun.j3d.utils.geometry.ColorCube;
import com.sun.j3d.utils.universe.SimpleUniverse;
public class MovingAroundCube extends JFrame {
private static final long serialVersionUID = 1L;
public MovingAroundCube(){
setTitle("Moving around cube");
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JCanvas3D jCanvas3D = new JCanvas3D(new GraphicsConfigTemplate3D());
jCanvas3D.setSize(300, 300);
add(jCanvas3D);
SimpleUniverse universe = new SimpleUniverse(jCanvas3D.getOffscreenCanvas3D());
universe.getViewingPlatform().setNominalViewingTransform();
universe.addBranchGraph(createSceneGraph());
}
public BranchGroup createSceneGraph() {
BranchGroup objRoot = new BranchGroup();
TransformGroup listenerGroup = new TransformGroup();
listenerGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
listenerGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
objRoot.addChild(listenerGroup);
//KeyNavigatorBehavior behaviour = new KeyNavigatorBehavior(listenerGroup);
MouseRotate behaviour = new MouseRotate(listenerGroup);
behaviour.setSchedulingBounds(new BoundingSphere(new Point3d(), 100));
listenerGroup.addChild(behaviour);
listenerGroup.addChild(new ColorCube(0.4));
return objRoot;
}
public static void main(String[] args) {
new MovingAroundCube().setVisible(true);
}
}
If I uncomment the line creating the KeyNavigatorBehaviour and comment the line creating the MouseRotate, user interaction this time is possible .
So, why can't the cube react to the mouse (when i use MouseRotate behaviour instance) ?
Any help will be appreciated.
System : Xubuntu 11.04
Java3D version : 1.5.2
There are two ways to solve this dilemma:
Use this constructor:
MouseRotate behaviour = new MouseRotate(jCanvas3D, listenerGroup);
or
Enable mouse events as long as no MouseListeners are added:
import java.awt.AWTEvent;
JCanvas3D jCanvas3D = new JCanvas3D(new GraphicsConfigTemplate3D()) {
{
this.enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK |
AWTEvent.MOUSE_WHEEL_EVENT_MASK);
}
};
Key events are enabled because 'setFocusable(true)' is set in JCanvas3D.
August, InteractiveMesh

How do I create a custom directive for Apache Velocity

I am using Apache's Velocity templating engine, and I would like to create a custom Directive. That is, I want to be able to write "#doMyThing()" and have it invoke some java code I wrote in order to generate the text.
I know that I can register a custom directive by adding a line
userdirective=my.package.here.MyDirectiveName
to my velocity.properties file. And I know that I can write such a class by extending the Directive class. What I don't know is how to extend the Directive class -- some sort of documentation for the author of a new Directive. For instance I'd like to know if my getType() method return "BLOCK" or "LINE" and I'd like to know what should my setLocation() method should do?
Is there any documentation out there that is better than just "Use the source, Luke"?
On the Velocity wiki, there's a presentation and sample code from a talk I gave called "Hacking Velocity". It includes an example of a custom directive.
Also was trying to come up with a custom directive. Couldn't find any documentation at all, so I looked at some user created directives: IfNullDirective (nice and easy one), MergeDirective as well as velocity build-in directives.
Here is my simple block directive that returns compressed content (complete project with some directive installation instructions is located here):
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.TemplateInitException;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.log.Log;
import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
/**
* Velocity directive that compresses an HTML content within #compressHtml ... #end block.
*/
public class HtmlCompressorDirective extends Directive {
private static final HtmlCompressor htmlCompressor = new HtmlCompressor();
private Log log;
public String getName() {
return "compressHtml";
}
public int getType() {
return BLOCK;
}
#Override
public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {
super.init(rs, context, node);
log = rs.getLog();
//set compressor properties
htmlCompressor.setEnabled(rs.getBoolean("userdirective.compressHtml.enabled", true));
htmlCompressor.setRemoveComments(rs.getBoolean("userdirective.compressHtml.removeComments", true));
}
public boolean render(InternalContextAdapter context, Writer writer, Node node)
throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
//render content to a variable
StringWriter content = new StringWriter();
node.jjtGetChild(0).render(context, content);
//compress
try {
writer.write(htmlCompressor.compress(content.toString()));
} catch (Exception e) {
writer.write(content.toString());
String msg = "Failed to compress content: "+content.toString();
log.error(msg, e);
throw new RuntimeException(msg, e);
}
return true;
}
}
Block directives always accept a body and must end with #end when used in a template. e.g. #foreach( $i in $foo ) this has a body! #end
Line directives do not have a body or an #end. e.g. #parse( 'foo.vtl' )
You don't need to both with setLocation() at all. The parser uses that.
Any other specifics i can help with?
Also, have you considered using a "tool" approach? Even if you don't use VelocityTools to automatically make your tool available and whatnot, you can just create a tool class that does what you want, put it in the context and either have a method you call to generate content or else just have its toString() method generate the content. e.g. $tool.doMyThing() or just $myThing
Directives are best for when you need to mess with Velocity internals (access to InternalContextAdapter or actual Nodes).
Prior to velocity v1.6 I had a #blockset($v)#end directive to be able to deal with a multiline #set($v) but this function is now handled by the #define directive.
Custom block directives are a pain with modern IDEs because they don't parse the structure correctly, assuming your #end associated with #userBlockDirective is an extra and paints the whole file RED. They should be avoided if possible.
I copied something similar from the velocity source code and created a "blockset" (multiline) directive.
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.TemplateInitException;
import java.io.Writer;
import java.io.IOException;
import java.io.StringWriter;
public class BlockSetDirective extends Directive {
private String blockKey;
/**
* Return name of this directive.
*/
public String getName() {
return "blockset";
}
/**
* Return type of this directive.
*/
public int getType() {
return BLOCK;
}
/**
* simple init - get the blockKey
*/
public void init( RuntimeServices rs, InternalContextAdapter context,
Node node )
throws TemplateInitException {
super.init( rs, context, node );
/*
* first token is the name of the block. I don't even check the format,
* just assume it looks like this: $block_name. Should check if it has
* a '$' or not like macros.
*/
blockKey = node.jjtGetChild( 0 ).getFirstToken().image.substring( 1 );
}
/**
* Renders node to internal string writer and stores in the context at the
* specified context variable
*/
public boolean render( InternalContextAdapter context, Writer writer,
Node node )
throws IOException, MethodInvocationException,
ResourceNotFoundException, ParseErrorException {
StringWriter sw = new StringWriter(256);
boolean b = node.jjtGetChild( 1 ).render( context, sw );
context.put( blockKey, sw.toString() );
return b;
}
}