Talend - The import org.apache cannot be resolved - talend

I've created a custom Talend component, which at certain step connects to an external Http service. For that, I'm using org.apache.commons.httpclient through javajet imports. I've seen the modules already exist in the Modules view. Nevertheless, when running a job the console outputs:
Execution failed : Failed to generate code.
[----------
1. ERROR in /Users/frb/Downloads/TOS_DI-20160510_1709-V6.2.0/workspace/.JETEmitters/src/org/talend/designer/codegen/translators/ngsi/orion/TOrionAppendBeginJava.java (at line 14)
import org.apache.commons.httpclient.*;
^^^^^^^^^^
The import org.apache cannot be resolved
----------
2. ERROR in /Users/frb/Downloads/TOS_DI-20160510_1709-V6.2.0/workspace/.JETEmitters/src/org/talend/designer/codegen/translators/ngsi/orion/TOrionAppendBeginJava.java (at line 15)
import org.apache.commons.httpclient.methods.*;
^^^^^^^^^^
The import org.apache cannot be resolved
----------
3. ERROR in /Users/frb/Downloads/TOS_DI-20160510_1709-V6.2.0/workspace/.JETEmitters/src/org/talend/designer/codegen/translators/ngsi/orion/TOrionAppendBeginJava.java (at line 16)
import org.apache.commons.httpclient.params.HttpMethodParams;;
^^^^^^^^^^
The import org.apache cannot be resolved
----------
3 problems (3 errors)
]
Any hints about how to fix this issue? My Talend version is 6.2.0.
EDIT 1
This is my begin code:
<%# jet
imports="
org.talend.core.model.process.INode
org.talend.core.model.process.ElementParameterParser
org.talend.core.model.metadata.IMetadataTable
org.talend.core.model.metadata.IMetadataColumn
org.talend.core.model.process.IConnection
org.talend.core.model.process.IConnectionCategory
org.talend.designer.codegen.config.CodeGeneratorArgument
org.talend.core.model.metadata.types.JavaTypesManager
org.talend.core.model.metadata.types.JavaType
java.util.List
java.util.Map
org.apache.commons.httpclient.*
org.apache.commons.httpclient.methods.*
org.apache.commons.httpclient.params.HttpMethodParams
"
%>
<%
// Get the CID
CodeGeneratorArgument codeGenArgument = (CodeGeneratorArgument) argument;
INode node = (INode)codeGenArgument.getArgument();
String cid = node.getUniqueName();
// Get the component parameters
String orionEndpoint = ElementParameterParser.getValue(node, "__ORION_ENDPOINT__");
String authEndpoint = ElementParameterParser.getValue(node, "__AUTH_ENDPOINT__");
String authUsername = ElementParameterParser.getValue(node, "__AUTH_USERNAME__");
String authPassword = ElementParameterParser.getValue(node, "__AUTH_PASSWORD__");
String entityIdField = ElementParameterParser.getValue(node, "__ENTITY_ID_FIELD__");
String entityTypeField = ElementParameterParser.getValue(node, "__ENTITY_TYPE_FIELD__");
String defaultEntityType = ElementParameterParser.getValue(node, "__DEFAULT_ENTITY_TYPE__");
String ignoredFilds = ElementParameterParser.getValue(node, "__IGNORED_FIELDS__");
%>
System.out.println("I am the begin section");
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(<%=authEndpoint%>);
method.setRequestHeader(new Header("Content-Type", "application/json"));
method.setRequestBody("{\"username\":\"" + <%=authUsername%> + "\",\"password\":\"" + <%=authPassword%> + "\"}");
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
} // if
byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
method.releaseConnection();
} // try
EDIT 2
I've added the following to my Component Descriptor file:
<IMPORTS>
<IMPORT
NAME="commons-httpclient"
MODULE="commons-httpclient-3.1.jar"
REQUIRED="true"
/>
</IMPORTS>
Now, in the modules view I'm able to see the following:
Sadly, the component outputs the same errors.
EDIT 3
After removing the imports and using fully qualified names, as suggested by #Balazs Gunics, the code seems to be generated. Nevertheless, some other errors related to commons-httpclient arise at running time:
Starting job job_tOrionAppend at 08:20 21/06/2016.
[statistics] connecting to socket on port 3916
[statistics] connected
I am the begin section
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.apache.commons.httpclient.HttpClient.<clinit>(HttpClient.java:66)
at iotp_talend_connectors.job_torionappend_0_1.job_tOrionAppend.tMysqlInput_1Process(job_tOrionAppend.java:854)
at iotp_talend_connectors.job_torionappend_0_1.job_tOrionAppend.tMysqlConnection_1Process(job_tOrionAppend.java:422)
at iotp_talend_connectors.job_torionappend_0_1.job_tOrionAppend.runJobInTOS(job_tOrionAppend.java:1355)
at iotp_talend_connectors.job_torionappend_0_1.job_tOrionAppend.main(job_tOrionAppend.java:1212)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
[statistics] disconnected
[statistics] disconnected
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 5 more
Job job_tOrionAppend ended at 08:20 21/06/2016. [exit code=1]

So in the begin.javajet code of yours the following code will only import these libraries for the code generation itself. But you need them to the generated code.
Generating java using java makes it hard to oversee this.
<%# jet
imports="
org.apache.commons.httpclient.*
org.apache.commons.httpclient.methods.*
org.apache.commons.httpclient.params.HttpMethodParams
So what you need is to have these imports added to the generated code. Well that is not really possible :( https://www.talendforge.org/forum/viewtopic.php?id=3670 To do that you need to modify the xml descriptor for your component.
So your imports are right. All you have to do is make sure you use the fully qualified names. I.e.: This piece of code:
System.out.println("I am the begin section");
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(<%=authEndpoint%>);
Have to be rewritten to look like this:
System.out.println("I am the begin section");
org.apache.commons.httpclient.HttpClient client =
new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.methods.PostMethod method =
new org.apache.commons.httpclient.methods.PostMethod(<%=authEndpoint%>);
Yes, it would be way more elegant if we could import the classes and use them.

Related

How do I use jGrasp's libraries?

I have a folder full of classes from a class I took. With a fresh install of jGrasp old projects that used to run fine are now full of "symbol not found" errors.
I still have the libraries, but I don't know how to import them. The way our class was set up, you didn't need import statements for anything that was in the library.
/* Turtle Drawing Program Lab 6, Part B */
/* Started by Celine Latulipe , modified by Bruce Long*/
public class Lab6PartB {
public static void main(String [] args)
{
/* Create the world */
World w = new World();
/* Create the turtle, call him Tom */
Turtle tom = new Turtle(w);
/* test the getDistance2() method */
int dist = tom.getDistance2();
System.out.println("This should print out the value 400. Value is: " + dist);
tom.moveTo(500, 400);
dist = tom.getDistance2();
System.out.println("This should print out the value 640. Value is: " + dist);
// TODO: Add a third test case that you make up
}
}
Error:
----jGRASP exec: java Lab6PartB
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: ModelDisplay
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: ModelDisplay
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
You can add the directory containing the class files to the classpath, either at the OS level, or using "Settings" > "PATH / CLASSPATH" > "Workspace" in jGRASP.
Also, you could copy all the class files/directories to the folder containing your new project classes.

Issue with application where EJB connection is left open and subsequent connections are opened and closed

Is it common or acceptable to keep and ejb connection opened while opening and closing other ejb connections or should connections be closed as soon as the client is done with it and a new one opened for subsequent tasks?
I'm currently working on a Swing application that uses EJBs (JBoss AS 7.1.1.final). The application opens an ejb connection (i.e. creates an InitialContext instance) and then uses that InitialContext for common tasks for the as long as the application is left running. There are a number of long running operations where an additional ejb connection (and InitialContext) is created. This connection is used for the single long running process and is then closed.
On JBoss, after about the 40th connection is opened and closed I get the exception shown below.
2017 May 15, 16:29:03 INFO - (JBossEJBClient.java:121) initialize - JNDI context initialized.
java.lang.IllegalStateException: No EJB receiver available for handling [appName:dtsjboss,modulename:dtsserverejb,distinctname:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#4e692639
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:584)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:119)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:136)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:121)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:104)
at com.sun.proxy.$Proxy4.getAuthorities(Unknown Source)
at com.apelon.dts.examples.errors.ejb.EjbConnectionNotClosedErrorExample.doTest(EjbConnectionNotClosedErrorExample.java:53)
at com.apelon.dts.examples.errors.ejb.EjbConnectionNotClosedErrorExample.bothCasesShouldSucceed(EjbConnectionNotClosedErrorExample.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
If I run the code below, the case where the ejb connections are used and closed works but the case where a single connection is left open fails with the above stack trace.
package com.myCompany.myApp.examples.errors.ejb;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.myCompany.myApp.client.jboss.JBossEJBClient;
import com.myCompany.myApp.dao.client.myAppServiceClient;
import com.myCompany.myApp.dao.client.myAppServiceClientParams;
import com.myCompany.myApp.testing.util.logging.LoggerForIntegrationTests;
import com.myCompany.myAppserver.dao.remote.AuthorityDao;
import com.myCompany.myAppserver.types.TAuthority;
import com.myCompany.install.util.ejb.ejbclient.myAppServiceClientFactory;
public class EjbConnectionNotClosedErrorExample {
private static Logger logger = LoggerForIntegrationTests.get();
private static final int COUNT = 100;
#Test
public void bothCasesShouldSucceed() {
try {
logger.debug("Doing case that works");
doTest(true);
logger.debug("Done with case that works.");
logger.debug("\n\n\n");
logger.debug("********************* DOING CASE THAT FAILS *********************");
doTest(false);
logger.debug("Done with use case that didn't work.");
} catch (Exception exp) {
exp.printStackTrace();
throw new RuntimeException(exp);
}
}
private void doTest(boolean closeConnection) {
myAppServiceClientParams params = myAppServiceClientFactory.getDefaultClientParams();
JBossEJBClient blocker = new JBossEJBClient();
blocker.initialize(params);
if (closeConnection == true) {
blocker.close();
}
int max = COUNT;
for (int i = 0; i < max; i++) {
myAppServiceClient client = myAppServiceClientFactory.getDefaultClient();
AuthorityDao dao = client.createAuthorityDao();
List<TAuthority> list = dao.getAuthorities();
logger.debug("CONNECTION " + (i + 1) + " ------------------------------------------------");
logger.debug("Got " + list.size() + " authorities.");
client.close();
}
System.out.println("");
}
public void initialize(myAppServiceClientParams params) {
this.initialize(params.getHost(), params.getPort(), params.getInstance(), params.getUid(), params.getPwd());
}
public void initialize(String host, int port, String instance, String user, String password) {
final Properties jndiProperties = new Properties();
String providerURL = "remote://" + host + ":" + port;
jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
jndiProperties.put(Context.PROVIDER_URL, providerURL);
jndiProperties.put("jboss.naming.client.ejb.context", true);
jndiProperties.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
// Explicitly specify STARTTLS = false for connecting to Wildfly v10
jndiProperties.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "false");
jndiProperties.put(Context.SECURITY_PRINCIPAL, user);
jndiProperties.put(Context.SECURITY_CREDENTIALS, password);
try {
InitialContext ctx = new InitialContext(jndiProperties);
ctx.getEnvironment();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Is this a bug that is specific to JBoss AS 7.1.1.final?
The problem here was that a single connection was being left open and used as a resource by the main thread of the application and this (for some reason) caused JBoss not to completely de-allocate the other connections. The solution was to get a reference to this connection when it was opened and then close this connection before creating any other new connection and then re-open the connection being used by the main thread as soon as the new connection was created.

Solution to NullPointerException in my TestNG test case

I am trying to login Facebook by using multiple sets of login cridential from external excel sheet using TestNG but in between the code what i have written throws:
FAILED: f
java.lang.NullPointerException
at DataDriven.loginRetesting.f(loginRetesting.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Code:
#Test
public void f() throws Exception{
FileInputStream fi=new FileInputStream("E:\\workspace99\\SeleniumAutomations\\testdata\\LoginData.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
for (int i = 1; i < 8; i++) {
driver.findElement(By.id("email")).sendKeys(s.getCell(0,i).getContents());
driver.findElement(By.id("pass")).sendKeys(s.getCell(1,i).getContents());
driver.findElement(By.id("u_0_1")).click();
Thread.sleep(1000);
if (selenium.isElementPresent("id=userNavigationLabel")) {
//driver.findElement(By.cssSelector("span.gb_V.gbii")).click();
driver.findElement(By.id("userNavigationLabel")).click();
driver.findElement(By.cssSelector("input.uiLinkButtonInput")).click();
Thread.sleep(1000);
}
else{
System.out.println("invalid cridential");
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("pass")).clear();
}
}
}
I am not able to find out where the problem is? so how to solve it.
For one thing, don't use "throws Exception" in the method declaration. Instead, have a try block inside the method with a "not null assertion".
Keep in mind that you never want to throw typical exceptions in a test method because it will drop you out of the test lifecycle too early and skip your #After phases. An exception thrown in a #Before annotated method will probably cause a SkipAssertion.
So, what you want to do instead is fail assertions. So, if you have a exception condition that occurs sometimes, swallow the exception (don't throw it) and use an assertion to handle it.
For example:
try {
} catch ( NullPointerException e ) {
Assert.assertTrue( "There was an error in blah.", false );
}
Null pointer means, exepected value of variable is null.
Please check the file exists at the specified path "E:\workspace99\SeleniumAutomations\testdata\LoginData.xls" and you get the value correctly from the file.
The stack trace says the issue is line 31 in your code but your snippet does not allow us to work out where line 31 is .
you are calling "selenium.isElementPresent". Could "selenium" be nil?

StringTemplate : how to import from a jar?

I have a case where I am loading a string template group from a file contained in a jar.
This works fine using the following mechanism:
final String urlName = new StringBuilder()
.append("jar:file:").append(templateJar.getAbsolutePath()).append("!")
.append(templateFileName).toString();
final URL url;
try {
url = new URL(urlName);
} catch (MalformedURLException ex) {
throw new GeneratorException("bad manifest url", ex);
}
final STGroup stg = new STGroupFile(url, "US-ASCII", '<', '>');
The difficulty comes in when the template file contains an
...
import "../../dataTypeMaps.stg"
...
String template fails with the following:
can't load group file jar:file:/home/phreed/.m2/repository/edu/vanderbilt/isis/druid/druid-template/2.0.0/druid-template-2.0.0.jar!/template/src/main/java/sponsor/orm/ContractCreator.stg
Caused by: java.lang.IllegalArgumentException: No such group file: ../../dataTypeMaps.stg
at org.stringtemplate.v4.STGroupFile.<init>(STGroupFile.java:69)
at org.stringtemplate.v4.STGroup.importTemplates(STGroup.java:570)
at org.stringtemplate.v4.compiler.GroupParser.group(GroupParser.java:199)
at org.stringtemplate.v4.STGroup.loadGroupFile(STGroup.java:619)
at org.stringtemplate.v4.STGroupFile.load(STGroupFile.java:139)
at org.stringtemplate.v4.STGroupFile.load(STGroupFile.java:128)
at org.stringtemplate.v4.STGroup.lookupTemplate(STGroup.java:237)
at org.stringtemplate.v4.STGroup.getInstanceOf(STGroup.java:172)
at edu.vanderbilt.isis.druid.generator.Generator.build(Generator.java:215)
at edu.vanderbilt.isis.druid.generator.DruidMojo.execute(DruidMojo.java:193)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Is it possible to set things up with the jar so that the import will work?
The above approach works fine when there is no jar involved.
The simple answer is that the path to the imported file is wrong
...
import "dataTypeMaps.stg"
...
The import will cause the file to be looked for starting at the root of the jar.
The above import would amount to the file being placed at...
final String urlName = new StringBuilder()
.append("jar:file:").append(templateJar.getAbsolutePath()).append("!")
.append("dataTypeMaps.stg").toString();
Why the behavior is different than when the template group file is on the native file system I do not know.
In order to get this to work I changed the classpath to include the jar file.
As this was done in the context of a Maven plugin, the plugin needs to change the classpath dynamically. This was done with the following code...
public void setTemplateJarName(String templateJarName) throws GeneratorException {
this.templateJarName = templateJarName;
final Thread ct = Thread.currentThread();
final ClassLoader pcl = ct.getContextClassLoader();
URL[] nurl;
try {
nurl = new URL[]{ new URL("file://"+templateJarName) };
} catch (MalformedURLException ex) {
throw new GeneratorException("could not load template jar", ex);
}
final URLClassLoader ucl = new URLClassLoader(nurl, pcl);
ct.setContextClassLoader(ucl);
}
Double check your templates are really in your jar.
Use the following code :
If the templates are dispatched in a tree like this:
/-->resources
+--> c/ (many .st and .stg files)
+--> cpp/ (many .st and .stg files)
+--> java/ (many .st and .stg files)
+--> c.stg
+--> cpp.stg
+--> java.stg
The content of java.stg is:
group Java;
import "java"
doNothing() ::= <<>>
To load all the files in one call :
URL url = getClass().getResource( "/resources/" + templateName );
STGroup group = new STGroupFile( url, "utf-8", '<', '>' );
In my case templateName equals c.stg, cpp.stg or java.stg.
The relative path only works on the file system. If you want to import a template from the classpath, use the fully qualified name. This is the same, as when you would load the file from the classpath yourself, using Class::getResource(). Using the fully qualified name, also works for the filesystem.
So, assuming there are two template files:
src/main/resources/util/date.stg
src/main/resources/generator/class.stg
Then in class.stg you use the fully qualified name:
import "util/date.stg"

Java dynamic class loading fails on windows, but working fine on linux

I am trying to load a class dynamically from a jar file. It worked fine on a Ubuntu linux box ( Sun Java Version 1.6.0_24 (b07).
When I tried to run the same thing on Windows (Windows 7, Java version "1.6.0_14") it fails with Class Not Found exception.
Following is code :
try {
String jarFile = "/sqljdbc4.jar";
File newf = new File(jarFile);
System.out.println(newf.getAbsolutePath());
System.out.println("File exists ? :" + newf.exists());
String urlPath = "jar:file://" + newf.getAbsolutePath() + "!/";
System.out.println(urlPath);
ClassLoader cur = Thread.currentThread().getContextClassLoader();
URL[] jarUrlArray = { new URL(urlPath) };
URLClassLoader cl = URLClassLoader.newInstance(jarUrlArray, cur);
Class c = Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver", true, cl);
Method m[] = c.getMethods();
for (Method mm : m) {
System.out.println(mm.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
While running on Linux, jar is placed at root and for Windows its at c:\ (source and binaries are in some folder on C:\ so "/sqljdbc4.jar" resolves to c:\sqljdbc4.jar on windows, I have made sure that correct jar location in passed to classloader for both the platforms.
Following is the stack trace i get on windows
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:594)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at DemoClass.loadAClass(DemoClass.java:31)
at DemoClass.main(DemoClass.java:14)
NOTE : You can use any jar that u have to try this out. I was playing with MS SQL Server JDBC Driver jar.
Thanks !
-Abhijeet.
Try using this to create the URL rather than manually building the string:
URL[] jarUrlArray = { newf.toURI().toURL() };