Intellij not recognizing javax.mail imports but project is building fine - intellij-idea

I am using javax.mail library in my project. My project is building fine using - mvn clean install, but when i try to debug my Intellij IDE shows error and it is not able to recognize the javax.mail imports. I have restarted my IDE from FILE -> Invalidate Caches and restart,still no luck.
These are not getting recognized by intellij IDEA,stating unused imports. I am using below the depeendency versions as:- javax.activation - 1.1.1 and javax.mail - 1.4.
Because the project is building fine,i believe the problem lies in some IDE setting.Kindly let me know if this can be resolved.

Try this maven dependency:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
<scope>provided</scope> <!-- add this only if code will run in a java container (i.e. tomcat, etc)-->
</dependency>
And you should also see the mail classes under External Libraries -> Maven:javax.mail:mail:1.4 -> mail-1.4.jar -> javax.mail
There are also newer versions of the java mail dependency you can use, like 1.4.7 or 1.5.0-b01
The latest version (as pointed out by #Mark Rotteveel) is 1.6.3 and the maven coordinates have changed to jakarta:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>1.6.3</version>
</dependency>
Based on your code I have created a simplified project version with only two files; pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>message-test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>
</project>
and SendMail.java
package com.test;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;
public class SendMail {
public static void main(String[] args) {
sendMail(new Exception("Problem with cable"));
}
public static void sendMail(Exception exception) {
String to = "destination#test.com";
String from = "sender#test.com";
String host = "smtp.test.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Trade-processor instance shutdown!");
message.setText(getExceptionMessage(exception));
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
private static String getExceptionMessage(Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
}
Make sure your 'java' source folder is marked as source (right click on it and select 'Mark directory as -> sources root' if it is not already light blue)
Make sure the class package (com.test) names match i.e. 'src/main/java/com/test/SendMail' on the project pane and 'package com.test' in SendMail.java

Related

gRPC UnsupportedAddressTypeException, but only when packaged with shadowJar

I have a simple gRPC client packaged in a jar by Gradle with shadowJar. When I run the main() with IntelliJ, the RPC is sent successfully. When I run it with java -jar, I get an exception:
Update: I think I've determined that the same set of classes is provided by both IntelliJ and ./gradlew shadowJar, but the order is different. I suspect this causes the divergent behavior but I don't really understand why, or how to control the order of the classpath in either case. It would be a big help if I could figure out which classes are actually relevant here. The full expansion include 19k class files.
Exception in thread "main" io.grpc.StatusException: UNKNOWN
at io.grpc.Status.asException(Status.java:550)
at io.grpc.kotlin.ClientCalls$rpcImpl$1$1$1.onClose(ClientCalls.kt:296)
at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:562)
at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:70)
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:743)
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:722)
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.nio.channels.UnsupportedAddressTypeException
at java.base/sun.nio.ch.Net.checkAddress(Net.java:146)
at java.base/sun.nio.ch.Net.checkAddress(Net.java:157)
at java.base/sun.nio.ch.SocketChannelImpl.checkRemote(SocketChannelImpl.java:816)
at java.base/sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:839)
at io.netty.util.internal.SocketUtils$3.run(SocketUtils.java:91)
at io.netty.util.internal.SocketUtils$3.run(SocketUtils.java:88)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:569)
at io.netty.util.internal.SocketUtils.connect(SocketUtils.java:88)
at io.netty.channel.socket.nio.NioSocketChannel.doConnect(NioSocketChannel.java:322)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.connect(AbstractNioChannel.java:248)
at io.netty.channel.DefaultChannelPipeline$HeadContext.connect(DefaultChannelPipeline.java:1342)
at io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:548)
at io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChannelHandlerContext.java:533)
at io.netty.channel.ChannelDuplexHandler.connect(ChannelDuplexHandler.java:54)
at io.grpc.netty.WriteBufferingAndExceptionHandler.connect(WriteBufferingAndExceptionHandler.java:157)
at io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:548)
at io.netty.channel.AbstractChannelHandlerContext.access$1000(AbstractChannelHandlerContext.java:61)
at io.netty.channel.AbstractChannelHandlerContext$9.run(AbstractChannelHandlerContext.java:538)
at io.netty.util.concurrent.AbstractEventExecutor.runTask(AbstractEventExecutor.java:174)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:167)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:470)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:503)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:995)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
... 1 more
my client (which does not appear to be the issue):
fun main() {
runBlocking {
SampleClient().hello("hello")
}
}
class SampleClient() : Closeable {
private val channel = ManagedChannelBuilder.forAddress("localhost", StationController.PORT).usePlaintext().build()
private val stub = StationServiceGrpcKt.StationServiceCoroutineStub(channel)
suspend fun hello(msg: String) {
val request = helloRequest { message = msg }
stub.hello(request)
}
override fun close() {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS)
}
}
Running with java -jar build/libs/test-0.1-all.jar fails with the above exception. Running with java -classpath <very long classpath> com.test.MainKt succeeds.
I tried to minimize my gradle.build.kts that still shows this behavior:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.google.protobuf.gradle.*
plugins {
kotlin("jvm") version "1.7.10"
id("com.github.johnrengelman.shadow") version "6.0.0"
id("com.google.protobuf") version "0.8.19"
}
// These address this error:
// 'compileJava' task (current target is 17) and 'compileKotlin' task (current target is 1.8) jvm target compatibility
// should be set to the same Java version.
java { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
tasks.withType<KotlinCompile> { kotlinOptions { jvmTarget = "17" } }
group = "com.test"
version = "0.1"
repositories { mavenCentral() }
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.3")
implementation("io.grpc:grpc-protobuf:1.48.1")
implementation("io.grpc:grpc-kotlin-stub:1.3.0")
// The rpc fails only when I run it from the fat jar. running from intellij works. the stacktrace is all in netty,
// but when I compile without netty there is no netty in the jar, making me think there is no transitive dependency
// on netty. it fails with both netty and netty-shaded, but with different stack traces.
// with netty-shaded, it says Caused by: io.grpc.netty.shaded.io.netty.channel.AbstractChannel$AnnotatedConnectException: connect(..) failed: Address family not supported by protocol: /localhost:8980
// with netty, it just says Caused by: java.nio.channels.UnsupportedAddressTypeException
implementation("io.grpc:grpc-netty:1.48.1")
implementation("com.google.protobuf:protobuf-kotlin:3.21.4")
}
// for gRPC
protobuf {
protoc { artifact = "com.google.protobuf:protoc:3.21.4" }
plugins {
// We only need this for Kotlin, but it doesn't fully link without the java sources.
id("grpc") { artifact = "io.grpc:protoc-gen-grpc-java:1.48.1" }
id("grpckt") { artifact = "io.grpc:protoc-gen-grpc-kotlin:1.3.0:jdk8#jar" }
}
generateProtoTasks {
all().forEach {
it.plugins { id("grpc"); id("grpckt") }
// The plugins above (I think) generate the Java proto code, but not the extra Kotlin stuff like DSLs.
// Including this adds a /kotlin folder to the generated code which contains all the extra stuff.
it.builtins { id("kotlin") }
}
}
}
sourceSets {
main {
java {
// These are the default generated source dirs, but they have to be added manually currently:
// https://github.com/google/protobuf-gradle-plugin/issues/109
// The plugin generates both a grpc dir with Java files, and grpckt with Kotlin files. I believe the grpckt
// contents includes all the functionality of the grpc (java) contents, but I'm not positive. The kotlin
// files might just be stubs for the java version? so maybe this compiles but doesn't run?
srcDirs("build/generated/source/proto/main/grpc")
srcDirs("build/generated/source/proto/main/grpckt")
// This contains the Java classes like the request and response messages.
srcDirs("build/generated/source/proto/main/java")
// This contains the Kotlin extensions to those java classes, like DSLs.
srcDirs("build/generated/source/proto/main/kotlin")
}
}
}
tasks.jar { manifest.attributes["Main-Class"] = "com.test.MainKt" }
I'm at a loss for how to proceed with debugging this.
A friend found the answer. This addition to build.gradle.kts ended up being all it took to make it work:
tasks.named("shadowJar", ShadowJar::class) {
mergeServiceFiles()
}
See shadowJar's documentation about what's happening here. Summary: "Java libraries often contain service descriptor files in the META-INF/services directory of the JAR. A service descriptor typically contains a line delimited list of classes that are supported for a particular service. At runtime, this file is read and used to configure library or application behavior.
Multiple dependencies may use the same service descriptor file name. In this case, it is generally desired to merge the content of each instance of the file into a single output file." mergeServiceFiles() does this.
I ran into the same problem with grpc and using maven-assembly-plugin.
I solved it by changing the assembly plugin to maven-shade-plugin and including both ServicesResourceTransformer and ManifestResourceTransformer transformers to contain meta-inf files into the final Jar
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer">
</transformer>
<transformer implementation=
"org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.PaxosServer</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
This issue is caused by broken name resolution when using certain maven plugins with grpc-java v1.47.0 and newer.
When using maven-assembly-plugin it can be resolved with a container descriptor handlers. File assembly.xml should include:
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.1.1 http://maven.apache.org/xsd/assembly-2.1.1.xsd">
....
<containerDescriptorHandlers>
<containerDescriptorHandler>
<handlerName>metaInf-services</handlerName>
</containerDescriptorHandler>
</containerDescriptorHandlers>
</assembly>
Here is the example of assembly.xml to build a JAR with dependencies.
For maven-shade-plugin resource transformers do the trick:
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
<configuration>

Allure is not generating report on cucumber 7

After updating the cucumber version to 7.2.3, Allure not generating reports. (unknown report and NaN%). It still uses the config file in the directory. I think it's not about the folder path. If I decrease the version to 5.6.0 it is working.
The related part of the pom.xml is like below.
Does anyone have a solution for this??
Thanks,
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.2.3</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>7.2.3</version>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-cucumber7-jvm</artifactId>
<version>2.17.3</version>
</dependency>
<dependencies>
<argLine>
-Dcucumber.options="--plugin io.qameta.allure.cucumber7jvm.AllureCucumber7Jvm
</argLine>
I know that it doesn't answer the exact question but hope it can help somebody.
I had the same issue with Gradle - build/allure-results folder had only one small json file that generated empty allure report.
It seems like not all the Cucumber and Allure versions are compatible with each other. So I have found a compatible versions pair of Cucumber and Allure. Surprisingly they are the same as author has:
cucumberVersion = '7.2.3'
allureVersion = '2.17.3'
related part of my build.gradle:
plugins {
id 'java'
id 'io.qameta.allure' version '2.9.1'
}
apply plugin: 'io.qameta.allure'
dependencies {
implementation group: 'io.cucumber', name: 'cucumber-java', version: '7.2.3'
testImplementation group: 'io.cucumber', name: 'cucumber-java', version: '7.2.3'
implementation group: 'io.qameta.allure', name: 'allure-cucumber7-jvm', version: '2.17.3'
}
configurations {
cucumberRuntime {
extendsFrom testImplementation
}
}
task cucumber() {
dependsOn assemble, testClasses
doLast {
javaexec {
main = "io.cucumber.core.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--plugin', 'html:results.html',
'--plugin', 'pretty',
'--plugin', 'io.qameta.allure.cucumber7jvm.AllureCucumber7Jvm',
'--glue', 'step_definitions',
'src/test/resources']
}
}
}
No, no this problem is not depend any cucumber version. Allure report have to write allure-result to any folder on test executing so you can use this commandline under <argLine> raw your pom.xml.
<systemPropertyVariables>
<allure.results.directory>
${project.build.directory}/allure-results
</allure.results.directory>
</systemPropertyVariables>

Initializaton error in com.cucumber.listener.ExtentCucumberFormatter

I am running the script using Cucumber in BDD Framework and I am using Extent Reports plugin to create the execution report.
I've created the test runner class as below:
package com.ctl.it.qa;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features = { "src/test/resources/Feature/ABC.feature"
},
plugin = {"com.cucumber.listener.ExtentCucumberFormatter:BDDControlCenterTools/target/Reports/cucumber-report.html"}
)
public class RunCukes {
}
I have included the below dependency for the Extent report in the POM.xml file:
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.2</version>
</dependency>
I am running the script with Junit and have the cucumber dependency for Junit too.
But when I execute the above runner class, its showing an Initialization error:
cucumber.runtime.CucumberException: Couldn't load plugin class: com.cucumber.listener.ExtentCucumberFormatter
Can anyone please help in this error and help to resolve it.
You need to also add the Maven dependency for this formatter. Refer to this -- https://github.com/email2vimalraj/CucumberExtentReporter documents.
<dependency>
<groupId>com.vimalselvam</groupId>
<artifactId>cucumber-extentsreport</artifactId>
<version>2.0.5</version>
</dependency>
But i think this only works with ExtentReport version 3 and above.
I was having com.cucumber.listener.ExtentCucumberFormatter initialization error but after few tweaks. I can generate the report now.
I added these two to my POM file. The version can be tricky as I used 3.1.1 for cucumber-extentreport but it didn't work for me. After trying a few 3.0.2 worked.
<dependency>
<groupId>com.vimalselvam</groupId>
<artifactId>cucumber-extentsreport</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.1.1</version>
</dependency>
My runner class looked like this:
package cucumber;
import java.io.File;
import org.junit.AfterClass;
import org.junit.runner.RunWith;
import com.cucumber.listener.Reporter;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src/test/resources/features",
glue = {"stepDefinitions"},
plugin = {"com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report.html"},
monochrome = true
)
public class CucumberRunner {
#AfterClass
public static void writeExtentReport() {
Reporter.loadXMLConfig(new File("config/report.xml"));
}
}
I hope this helps.
Try using a different version of cucumber-extentsreport. For me, the latest version (3.1.1) did not work, but 3.0.2 did.
To resolve this.
Remove below code "com.cucumber.listener.ExtentCucumberFormatter:target/report.html" from the runner class and then run the runner class.
It will run successfuly. Then put this back into the runer class and execute, it will work.

Publish kotlin library (Not Android) to jCenter

I have Intellij Idea 2016.1 gradle-application(Not Android) written in Kotlin. I need to place it in jCenter and add to the Android-application as a dependency. I can not find any information about it. All references refer to the Android project. I have no concept of how this can be done. Looking for detailed instructions
Publishing Kotlin libraries to jCenter is absolutely the same as for JAva libraries.
buildscript {
ext.kotlinVersion = '1.0.2'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
}
}
plugins {
id "com.jfrog.bintray" version "1.6"
}
apply plugin: 'kotlin'
apply plugin: 'maven-publish'
group '<groupId>'
version '<version>'
sourceCompatibility = 1.6
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
}
bintray {
user = '<bintray user name>'
key = '<bintray API key>'
publications = ['mavenJava']
pkg {
repo = '<repository name on bintray>'
name = '<artifactId>'
version {
name = project.version
released = new Date()
vcsTag = "v${project.version}"
}
}
}
task sourcesJar(type: Jar, dependsOn: project.classes) {
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: project.javadoc) {
from javadoc.destinationDir
}
artifacts {
archives sourcesJar, javadocJar
}
publishing {
publications {
mavenJava(MavenPublication) {
artifactId project.bintray.pkg.name
from components.java
artifact sourcesJar {
classifier = 'sources'
}
artifact javadocJar {
classifier = 'javadoc'
}
}
}
}
Create a repository on bintray and then just call ./gradlew bintrayUpload. If you don't ask the bintray plugin to publish an uploaded dependency then you have to publish it manually from your bintray account.
When the dependency is published you can link it to jCenter from your account. After it's published on jCenter you can use it as a regular dependency from an Android project.
Michael's answer is correct. But if you execute bintrayUpload, the kotlin dependency will be included to the .pom file. This lead to adding kotlin libs twice when you include your lib in gradle-project. This lead to DuplicateFileException. I don't know what's wrong. Maybe I did some stupid mistake. But if this is your case to, you can execute gradlew build with Michael's build.gradle for generating .jar and source.jar. Then you can create your own .pom file with no dependencies and deploy 3 files(jar, source.jar and .pom) to bintray manually. Then link library to jCenter.
For example:
Generated .pom with ./gradlew bintrayUpload:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.livemaster</groupId>
<artifactId>LongToWords</artifactId>
<version>0.1</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>1.0.2</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
Your own .pom for deploying without kotlin-dependencies:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.livemaster</groupId>
<artifactId>LongToWords</artifactId>
<version>0.1</version>
</project>

What's the difference between jython-standalone-2.7.0.jar and jython-2.7.0.jar

I wrote a Java example, the code is:
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.List;
class JythonExample {
public static void main(String args[]) throws ScriptException {
listEngines();
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine pyEngine = mgr.getEngineByName("python");
try {
pyEngine.eval("print \"Python - Hello, world!\"");
} catch (Exception ex) {
ex.printStackTrace();
}
final PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print \"Python - Hello, world!\"");
PyObject result = interpreter.eval("2 + 3");
System.out.println(result.toString());
}
public static void listEngines(){
ScriptEngineManager mgr = new ScriptEngineManager();
List<ScriptEngineFactory> factories =
mgr.getEngineFactories();
for (ScriptEngineFactory factory: factories) {
System.out.println("ScriptEngineFactory Info");
String engName = factory.getEngineName();
String engVersion = factory.getEngineVersion();
String langName = factory.getLanguageName();
String langVersion = factory.getLanguageVersion();
System.out.printf("\tScript Engine: %s (%s)\n",
engName, engVersion);
List<String> engNames = factory.getNames();
for(String name: engNames) {
System.out.printf("\tEngine Alias: %s\n", name);
}
System.out.printf("\tLanguage: %s (%s)\n",
langName, langVersion);
}
}
}
In my pom.xml, if I use:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
then I can run java -jar target/jython-example-1.0-SNAPSHOT.jar successfuly, by the way, I used maven-assembly-plugin to build a runnable jar.
if I use:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.7.0</version>
</dependency>
then when I run java -jar target/jython-example-1.0-SNAPSHOT.jar, I'll always get the following error:
ScriptEngineFactory Info
Script Engine: jython (2.7.0)
Engine Alias: python
Engine Alias: jython
Language: python (2.7)
ScriptEngineFactory Info
Script Engine: Oracle Nashorn (1.8.0_31)
Engine Alias: nashorn
Engine Alias: Nashorn
Engine Alias: js
Engine Alias: JS
Engine Alias: JavaScript
Engine Alias: javascript
Engine Alias: ECMAScript
Engine Alias: ecmascript
Language: ECMAScript (ECMA - 262 Edition 5.1)
java.lang.NullPointerException
at me.soulmachine.JythonExample.main(JythonExample.java:21)
Exception in thread "main" ImportError: Cannot import site module and its dependencies: No module named site
Determine if the following attributes are correct:
* sys.path: ['/home/programmer/src/github/JythonExample/JythonExample/target/Lib', '__classpath__', '__pyclasspath__/']
This attribute might be including the wrong directories, such as from CPython
* sys.prefix: /home/programmer/src/github/JythonExample/JythonExample/target
This attribute is set by the system property python.home, although it can
be often automatically determined by the location of the Jython jar file
You can use the -S option or python.import.site=false to not import the site module
It seems the pyEngine is null.
So I wonder what's the difference between jython-standalone-2.7.0.jar and jython-2.7.0.jar
One problem I've just discovered with the same error is that the maven build 2.7.0 does not include the lib folder. This is probably a build error for the release build. I had to move up the b2 build which does properly include the lib folder in the supplied jar.
Problem maven 2.7.0 jar:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
Working maven 2.7.1b2 that includes the lib folder:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.1b2</version>
</dependency>
NOTE: If you download the jar directly from the Jython site it does correctly include the lib folder. It's just the maven repository version.
I believe the main difference causing your issue is that the jython-standalone jar provides Lib/ (which contains site.py) while the jython jar does not.
https://github.com/scijava/jython-shaded gives a more in-depth description of the issue, as well as other issues, and provides an alternative jar to get around some issues noted in the description.
I don't have experience with scijava:jython-shaded, but I substituted it into your pom (for my setup I also had to change jdk.version to 1.7 and to JythonExample) and your example runs.