Compiling a Maven plugin using the help-mojo phase with maven-plugin-plugin - java

I'm working on an extension of a MojoHaus plugin for Maven.
My project is at this GitHub repository.
When I try to run mvn clean install, the compilation fails with the following error message:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-plugin-plugin:3.4:helpmojo
(help-mojo) on project yaml-properties-maven-plugin: Execution help-mojo of goal
org.apache.maven.plugins:maven-plugin-plugin:3.4:helpmojo failed: syntax error #[11,22] in
file:/home/user/workspace/yaml-properties-maven-plugin/src/main/java/org/codehaus/mojo/properties/ResourceType.java -> [Help 1]
The class ResourceType looks like:
package org.codehaus.mojo.properties;
import java.util.HashSet;
import java.util.Set;
public enum ResourceType {
PROPERTIES(".properties"),
YAML(new String[]{".yml", ".yaml"});
private final Set<String> fileExtensions;
ResourceType(final String... fileExtensions) {
this.fileExtensions = new HashSet<String>();
for(final String fileExtension: fileExtensions){
this.fileExtensions.add(fileExtension);
}
}
public static Set<String> allFileExtensions(final ResourceType... resourceTypes) {
final Set<String> extensions = new HashSet<String>();
for (final ResourceType resourceType : resourceTypes) {
extensions.addAll(resourceType.fileExtensions());
}
return extensions;
}
public static ResourceType getByFileName(final String fileName) {
for (final ResourceType resourceType : ResourceType.values()) {
for (final String extension : resourceType.fileExtensions()) {
if (fileName.endsWith(extension)) {
return resourceType;
}
}
}
return null;
}
public Set<String> fileExtensions() {
return new HashSet<String>(fileExtensions);
}
}
What could be the issue?

I think you're hitting an issue with QDox, which probably has an issue with parsing the line YAML(new String[]{".yml", ".yaml"});. The stacktrace can confirm that.
The solution is actually quite simple since you're using varArgs: change the line to YAML(".yml", ".yaml");

Related

Error invoking bsh method: eval Sourced file: inline evaluation of: `import org.skyscreamer.jsonassert.Customization; Constructor error: Can't find

I use jmeter to comapre json data.use org.skyscreamer.jsonassert.
suceess in idea with jdk8, but failed in jmeter
this is error info.
i have imported jsonassert-1.5.1.jar and android-json-0.0.20131108.vaadin1.jar into %Jmeter%lib,jackson use 2.13.3 version.jmeter version is 5.5 .
Response code:500
Response message:org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.skyscreamer.jsonassert.Customization; import org.skyscreamer.jsonasse . . . '' : Constructor error: Can't find constructor: org.skyscreamer.jsonassert.comparator.CustomComparator( org.skyscreamer.jsonassert.JSONCompareMode, org.skyscreamer.jsonassert.Customization ) in class: org.skyscreamer.jsonassert.comparator.CustomComparator
this is beanshell sampler ,the code i write in the jmeter
import org.skyscreamer.jsonassert.Customization;
import org.skyscreamer.jsonassert.JSONCompare;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.JSONCompareResult;
import org.skyscreamer.jsonassert.ValueMatcher;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.json.JSONException;
String newResponseMessage = vars.get("new_S{custNo}");
String oldResponseMessage = vars.get("old_S{custNo}");
log.info("oldRes"+oldResponseMessage);
log.info("newRes"+newResponseMessage);
ValueMatcher matcher = new ValueMatcher() {
public boolean equal(Object o1, Object o2) {
return true;
}
};
Customization customization = new Customization("orgSeqNo", matcher);
JSONCompareResult result;
try {
result = JSONCompare.compareJSON(newResponseMessage, oldResponseMessage, new CustomComparator(JSONCompareMode.NON_EXTENSIBLE,customization));
if (result.passed()) {
System.out.println("no different");
} else {
System.out.println(result.getMessage());
log.error(result.getMessage());
// ctx.getEngine().stopTest();
}
}catch (JSONException e){
log.error("Beanshell failure: ", e);
throw ex;
}
code in jmeter beanshell sampler
error info picture
i have imported jsonassert-1.5.1.jar and android-json-0.0.20131108.vaadin1.jar into %Jmeter%lib and %Jmeter%/lib/ext both,jackson use 2.13.3 version.jmeter version is 5.5 .
enter image description here
I use jmeter to comapre json data.use org.skyscreamer.jsonassert.
suceess in idea with jdk8, but failed in jmeter
these are codes i write with jdk8,success run,but failed in jmeter
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.5.1</version>
</dependency>
public class Main {
static String jsonStr1 = "{\"orgSeqNo\":\"123123\",\"code\":200,\"person\":{\"partyId\":\"10000000001\",\"partyName\":\"john\",\"partyCertType\":\"10100\",\"partyCertNo\":\"320925199612122314\",\"partyStatus\":\"1\",\"addresses\":[{\"addrId\":\"1\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":103,\"phone\":\"13213137625\"},{\"addrId\":\"2\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"101\",\"phone\":\"13213137625\"},{\"addrId\":\"3\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"102\",\"phone\":\"13213137625\"}]},\"message\":\"ok\"}";
static String jsonStr2 = "{\"orgSeqNo\":\"12e9fc45c09b4a69b7aa2bbcb1313cba\",\"code\":200,\"person\":{\"partyId\":\"10000000001\",\"partyName\":\"john\",\"partyCertType\":\"10100\",\"partyCertNo\":\"320925199612122314\",\"partyStatus\":\"1\",\"addresses\":[{\"addrId\":\"1\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"103\",\"phone\":\"13213137625\"},{\"addrId\":\"2\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"101\",\"phone\":\"13213137625\"},{\"addrId\":\"3\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"102\",\"phone\":\"13213137625\"}]},\"message\":\"ok\"}";
static String jsonStr3 = "{\"orgSeqNo\":\"12e9fc45c09b4a69b7aa2bbcb1313cba\",\"code\":200,\"person\":{\"partyId\":\"10000000001\",\"partyName\":\"john\",\"partyCertType\":\"10100\",\"partyCertNo\":\"320925199612122314\",\"partyStatus\":\"1\",\"addresses\":[{\"addrId\":\"2\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"101\",\"phone\":\"13213137625\"},{\"addrId\":\"1\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"103\",\"phone\":\"13213137625\"},{\"addrId\":\"3\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"102\",\"phone\":\"13213137625\"}]},\"message\":\"ok\"}";
static String jsonStr4 = "{\"orgSeqNo\":\"12e9fc45c09b4a69b7aa2bbcb1313cba\",\"code\":200,\"person\":{\"partyId\":\"10000000001\",\"partyName\":\"john\",\"partyCertType\":\"10100\",\"partyCertNo\":\"320925199612122314\",\"partyStatus\":\"1\",\"addresses\":[{\"addrId\":\"1\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":103,\"phone\":\"13213137625\"},{\"addrId\":\"2\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"101\",\"phone\":\"13213137625\"},{\"addrId\":\"3\",\"partyId\":\"10000000001\",\"city\":\"suchou\",\"detailAddr\":\"asdfghqwe\",\"addrType\":\"102\",\"phone\":\"13213137625\"}]},\"message\":\"ok\"}";
public static void main(String[] args) {
// Customization customization = new Customization("orgSeqNo", (o1, o2) -> true);
ValueMatcher matcher = new ValueMatcher() {
#Override
public boolean equal(Object o1, Object o2) {
return true;
}
};
Customization customization = new Customization("orgSeqNo", matcher);
JSONCompareResult result = null;
try {
result = JSONCompare.compareJSON(jsonStr1, jsonStr3, new CustomComparator(JSONCompareMode.NON_EXTENSIBLE,customization));
if (result1.passed()) {
System.out.println("no different");
} else {
System.out.println(result.getMessage());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
next is result,i want jmeter also like this result
person.addresses[addrId=1].addrType
Expected: 103
got: 103
Program execution result picture
i have imported jsonassert-1.5.1.jar and android-json-0.0.20131108.vaadin1.jar into %Jmeter%lib,jackson use 2.13.3 version.jmeter version is 5.5 .
run success in jvm , but error info in jmeter...
Beanshell != Java so even given your code "suceess in idea with jdk8" it doesn't necessarily mean that it will "suceess" in JMeter's Beanshell components.
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting so my expectation is that if you switch to the JSR223 Sampler and use groovy your code will "suceess" as well.
More information on Groovy scripting in JMeter: Apache Groovy: What Is Groovy Used For?

Custom Gradle Java plugin crashes in v5.2.1, but worked in v4.7?

My plugin worked in Gradle v4.7, but is now crashing v5.2.1. I know that's a HUGE version jump.
I wrote a custom Gradle java plugin, and this the plugin implementation class. I put a breakpoint in the task.setProject(project) call, but it never gets there.
package com.zift.utilities;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
public class ZiftVersionPlugin implements Plugin<Project> {
public void apply(Project project) {
project.getTasks().create("manageVersion", ZiftVersion.class, (task) -> {
// Added breakpoint here, but it's never reached!
task.setProject(project);
});
}
}
Edit: (added simplified plugin code below)
Here's the simplified class that implements the manageVersion task. All the import statements will probably be unnecessary with this code.
package com.zift.utilities;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.options.Option;
import org.gradle.api.Project;
public class ZiftVersion extends DefaultTask {
#Input private Project project;
private String projectDir=null;
private String propFileFullPath=null;
private String sourceBranch=null;
private String destinationBranch="staging";
String getPropFile() { return propFileFullPath; }
void setPropFile(String fn) { this.propFileFullPath = fn; }
public Project getProject() { return project; }
public void setProject(Project project) {
this.project = project;
this.projectDir = this.project.getRootDir().toString();
}
// The void set*() functions have to immediately follow their corresponding
// #Option() so they can take arguments in the command line, e.g.,
// $ ./gradlew manageVersion \
// --srcBranch=bugfix/devops-507-semver --dstBranch=master
#Option(option = "srcBranch", description = "Source branch of the pull request")
public void setSrcBranch(String s) { this.sourceBranch = s; }
public String getSrcBranch() { return sourceBranch; }
#Option(option = "dstBranch", description = "Destination branch of the pull request")
public void setDstBranch(String d) { this.destinationBranch = d; }
public String getDstBranch() { return destinationBranch; }
#TaskAction
void manageProjectVersion() {
System.out.println("Hello world!");
}
}
Here's my project's build.gradle file to build the plugin
plugins {
id 'idea'
id 'java'
id 'maven'
id 'maven-publish'
id 'java-gradle-plugin'
}
group=project.groupId
version = '666.666.666'
dependencies {
compile gradleApi()
}
jar {
manifest {
attributes 'artifactId': 'zift-version-plugin',
'groupId': 'com.zift.utilities',
'version': project.version
}
baseName artifactId
doLast {
println "artifactId: $project.artifactId\ngroupId: $project.groupId\nversion: $version"
}
}
gradlePlugin {
plugins {
simplePlugin {
id = 'com.zift.utilities.zift-version-plugin'
implementationClass = 'com.zift.utilities.ZiftVersionPlugin'
}
}
}
Here's how I use it, from another Gradle project that uses the plugin
$ ./gradlew manageVersion --srcBranch=feature/devops-507-semver-support --dstBranch=master
> Task :manageVersion
Hello world!
Here's the exception, which looks like it occurred during the create() function call.
Caused by org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreationException: Could not create task ':manageVersion'
Caused by java.lang.NullPointerException: (No message provided)
at org.gradle.api.internal.tasks.TaskPropertyUtils.visitProperties(TaskPropertyUtils.java:38)
at org.gradle.api.internal.project.taskfactory.PropertyAssociationTaskFactory.create(PropertyAssociationTaskFactory.java:49)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory.create(AnnotationProcessingTaskFactory.java:46)
...
at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:359)
at com.zift.utilities.ZiftVersionPlugin.apply(ZiftVersionPlugin.java:8)
Any clues?
Idiocy is the cause, my idiocy particularly.
I compiled my plugin with Gradle wrapper from v4.x, so when a project built with v5.x or above uses it, the plugin crashes.
Solution is to upgrade my plugin's wrapper to Gradle v6.0, build and publish a new version, and have projects use the new version. No more crashes.

Scanning classpath/modulepath in runtime in Java 9

I can't seem to find any info on whether scanning all available classes (for interfaces, annotations etc) is still possible in runtime, the way Spring, Reflections and many other frameworks and libraries currently do, in the face of Jigsaw related changes to the way classes are loaded.
EDIT:
This question is about scanning the real physical file paths looking for classes. The other question is about dynamically loading classes and resources. It's related but very much not a duplicate.
UPDATE: Jetty project has made a JEP proposal for a standardized API for this. If you have a way to help make this reality, please do. Otherwise, wait and hope.
UPDATE 2: Found this relevant sounding post. Quoting the code snippet for posterity:
If you are really just looking to get at the contents of the modules in
the boot layer (the modules that are resolved at startup) then you'll do
something like this:
ModuleLayer.boot().configuration().modules().stream()
.map(ResolvedModule::reference)
.forEach(mref -> {
System.out.println(mref.descriptor().name());
try (ModuleReader reader = mref.open()) {
reader.list().forEach(System.out::println);
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
});
The following code achieves module path scanning in Java 9+ (Jigsaw / JPMS). It finds all classes on the callstack, then for each class reference, calls classRef.getModule().getLayer().getConfiguration().modules(), which returns a a List<ResolvedModule>, rather than just a List<Module>. (ResolvedModule gives you access to the module resources, whereas Module does not.) Given a ResolvedModule reference for each module, you can call the .reference() method to get the ModuleReference for a module. ModuleReference#open() gives you a ModuleReader, which allows you to list the resources in a module, using ModuleReader#list(), or to open a resource using Optional<InputStream> ModuleReader#open(resourcePath) or Optional<ByteBuffer> ModuleReader#read(resourcePath). You then close the ModuleReader when you're done with the module. This is not documented anywhere that I have seen. It was very difficult to figure all this out. But here is the code, in the hope that someone else will benefit from this.
Note that even in JDK9+, you can still utilize traditional classpath elements along with module path elements, so for a complete module path + classpath scan, you should probably use a proper classpath scanning solution, such as ClassGraph, which supports module scanning using the below mechanism (disclaimer, I am the author). You can find a reflection-based version of the following code here.
Also note that there was a bug in StackWalker in several JDK releases after JDK 9 that has to be worked around, see the above reflection-based code for details.
package main;
import java.lang.StackWalker;
import java.lang.StackWalker.Option;
import java.lang.StackWalker.StackFrame;
import java.lang.module.ModuleReader;
import java.lang.module.ModuleReference;
import java.lang.module.ResolvedModule;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
public class Java9Scanner {
/** Recursively find the topological sort order of ancestral layers. */
private static void findLayerOrder(ModuleLayer layer,
Set<ModuleLayer> visited, Deque<ModuleLayer> layersOut) {
if (visited.add(layer)) {
List<ModuleLayer> parents = layer.parents();
for (int i = 0; i < parents.size(); i++) {
findLayerOrder(parents.get(i), visited, layersOut);
}
layersOut.push(layer);
}
}
/** Get ModuleReferences from a Class reference. */
private static List<Entry<ModuleReference, ModuleLayer>> findModuleRefs(
Class<?>[] callStack) {
Deque<ModuleLayer> layerOrder = new ArrayDeque<>();
Set<ModuleLayer> visited = new HashSet<>();
for (int i = 0; i < callStack.length; i++) {
ModuleLayer layer = callStack[i].getModule().getLayer();
findLayerOrder(layer, visited, layerOrder);
}
Set<ModuleReference> addedModules = new HashSet<>();
List<Entry<ModuleReference, ModuleLayer>> moduleRefs = new ArrayList<>();
for (ModuleLayer layer : layerOrder) {
Set<ResolvedModule> modulesInLayerSet = layer.configuration()
.modules();
final List<Entry<ModuleReference, ModuleLayer>> modulesInLayer =
new ArrayList<>();
for (ResolvedModule module : modulesInLayerSet) {
modulesInLayer
.add(new SimpleEntry<>(module.reference(), layer));
}
// Sort modules in layer by name for consistency
Collections.sort(modulesInLayer,
(e1, e2) -> e1.getKey().descriptor().name()
.compareTo(e2.getKey().descriptor().name()));
// To be safe, dedup ModuleReferences, in case a module occurs in multiple
// layers and reuses its ModuleReference (no idea if this can happen)
for (Entry<ModuleReference, ModuleLayer> m : modulesInLayer) {
if (addedModules.add(m.getKey())) {
moduleRefs.add(m);
}
}
}
return moduleRefs;
}
/** Get the classes in the call stack. */
private static Class<?>[] getCallStack() {
// Try StackWalker (JDK 9+)
PrivilegedAction<Class<?>[]> stackWalkerAction =
(PrivilegedAction<Class<?>[]>) () ->
StackWalker.getInstance(
Option.RETAIN_CLASS_REFERENCE)
.walk(s -> s.map(
StackFrame::getDeclaringClass)
.toArray(Class[]::new));
try {
// Try with doPrivileged()
return AccessController
.doPrivileged(stackWalkerAction);
} catch (Exception e) {
}
try {
// Try without doPrivileged()
return stackWalkerAction.run();
} catch (Exception e) {
}
// Try SecurityManager
PrivilegedAction<Class<?>[]> callerResolverAction =
(PrivilegedAction<Class<?>[]>) () ->
new SecurityManager() {
#Override
public Class<?>[] getClassContext() {
return super.getClassContext();
}
}.getClassContext();
try {
// Try with doPrivileged()
return AccessController
.doPrivileged(callerResolverAction);
} catch (Exception e) {
}
try {
// Try without doPrivileged()
return callerResolverAction.run();
} catch (Exception e) {
}
// As a fallback, use getStackTrace() to try to get the call stack
try {
throw new Exception();
} catch (final Exception e) {
final List<Class<?>> classes = new ArrayList<>();
for (final StackTraceElement elt : e.getStackTrace()) {
try {
classes.add(Class.forName(elt.getClassName()));
} catch (final Throwable e2) {
// Ignore
}
}
if (classes.size() > 0) {
return classes.toArray(new Class<?>[0]);
} else {
// Last-ditch effort -- include just this class
return new Class<?>[] { Java9Scanner.class };
}
}
}
/**
* Return true if the given module name is a system module.
* There can be system modules in layers above the boot layer.
*/
private static boolean isSystemModule(
final ModuleReference moduleReference) {
String name = moduleReference.descriptor().name();
if (name == null) {
return false;
}
return name.startsWith("java.") || name.startsWith("jdk.")
|| name.startsWith("javafx.") || name.startsWith("oracle.");
}
public static void main(String[] args) throws Exception {
// Get ModuleReferences for modules of all classes in call stack,
List<Entry<ModuleReference, ModuleLayer>> systemModuleRefs = new ArrayList<>();
List<Entry<ModuleReference, ModuleLayer>> nonSystemModuleRefs = new ArrayList<>();
Class<?>[] callStack = getCallStack();
List<Entry<ModuleReference, ModuleLayer>> moduleRefs = findModuleRefs(
callStack);
// Split module refs into system and non-system modules based on module name
for (Entry<ModuleReference, ModuleLayer> m : moduleRefs) {
(isSystemModule(m.getKey()) ? systemModuleRefs
: nonSystemModuleRefs).add(m);
}
// List system modules
System.out.println("\nSYSTEM MODULES:\n");
for (Entry<ModuleReference, ModuleLayer> e : systemModuleRefs) {
ModuleReference ref = e.getKey();
System.out.println(" " + ref.descriptor().name());
}
// Show info for non-system modules
System.out.println("\nNON-SYSTEM MODULES:");
for (Entry<ModuleReference, ModuleLayer> e : nonSystemModuleRefs) {
ModuleReference ref = e.getKey();
ModuleLayer layer = e.getValue();
System.out.println("\n " + ref.descriptor().name());
System.out.println(
" Version: " + ref.descriptor().toNameAndVersion());
System.out.println(
" Packages: " + ref.descriptor().packages());
System.out.println(" ClassLoader: "
+ layer.findLoader(ref.descriptor().name()));
Optional<URI> location = ref.location();
if (location.isPresent()) {
System.out.println(" Location: " + location.get());
}
try (ModuleReader moduleReader = ref.open()) {
Stream<String> stream = moduleReader.list();
stream.forEach(s -> System.out.println(" File: " + s));
}
}
}
}
The actual issue here is to find the paths to all jars and folders on the classpath. Once when you have them, you can scan.
What I did is the following:
get the current module descriptor for current class
get all requires modules
for each such module open resource of MANIFEST.MF
remove the MANIFEST.MF path from the resource url
what remains is the classpath of the module, i.e. to it's jar or folder.
I do the same for current module, to get the classpath for current code.
This way I collect classpath of a currently working module and all its required modules (1 step away). That was working for me - and my Java8 scanner was still being able to do the job. This approach does not require any additional VM flag etc.
I could extend this approach to get all required modules easily (not only the first level), but for now, I don't need that.
Code.

java.lang.IllegalAccessError: tried to access method net.sourceforge.tess4j.Tesseract.<init>()V from class Tess4jTest.TestTess

I did a Java OCR project with Tesseract in the Mirth.When I run the jar file from the Mirth,I get this error.When I search it,I found that there is a init() method and also it is a protected void in Tesseract.java.I think that maybe it is the reason for that error.
What should I do?Thank you so much for your helps.
package Tess4jTest;
import java.io.File;
import java.io.IOException;
import net.sourceforge.tess4j.*;
public class TestTess {
public static String Tc;
public static String phone;
public static String date;
public static void main(String[] args) {
//System.out.println(returnText("C:\\Users\\Nevzat\\Desktop\\deneme.pdf"));
}
public static String returnText(String fileName){
File imageFile = new File(fileName);
if(imageFile.exists()){
Tesseract instance = new Tesseract();
instance.setDatapath("C:\\imageRAD\\Onam\\tessdata");
String result = null;
try {
result = instance.doOCR(imageFile);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
if(result!=null){
int i=result.indexOf("Numarasn: ");
int j=result.indexOf("Tel No:");
int k=result.indexOf("Bilgllendirme Tarihl:");
Tc = result.substring(i+10, i+21);
phone = result.substring(j+8,j+23);
date = result.substring(k+22,k+32);
//System.out.println(result);
}else{
return "Null Error!";
}
}else{
return "Does not found a file!";
}
return Tc+","+phone+","+date;
}
public static String returnTC() throws IOException{
return Tc;
}
public static String returnPhone() throws IOException{
return phone;
}
public static String returnDate() throws IOException{
return date;
}
}
The error you got occurs when you try to create an object with a private constructor. (<init>() is the name of a constructor with no parameters)
Looking at the tess4j source I found a method with the following documentation:
#deprecated As of Release 2.0, use default constructor instead.
Looking at the source before 2.0 reveals the default constructor was private.
This means your problem is most likely that you are compiling against a version newer than 2.0, but your environment is running one older than 2.0.
Either update your environment or downgrade the library you build against to fix it.
I solved the error and have finished the project.I mention step by step
1.You have to use right jar files for tess4j.
2.Add java project all of in the tess4j-3.2.1.zip except tess4j-3.2.1.jar via Build Path.
3.Add tess4j-1.5.jar from this
4.Add tessdata folder,ghost4j-0.5.1.jar,jna-4.1.jar,tess4j.jar and jar file of your java project.

How can a Maven plugin discover its own version during execution?

I'd like to be able to discover the version of my plugin during its execution; 0.0.1-SNAPSHOT, 0.0.1, 1.0-SNAPSHOT, etc.
Can this be done? The AbstractMojo class doesn't really give you much information about the plugin itself.
EDIT - I am using the following code as a workaround. It assumes that the MANIFEST for the plugin can be loaded from a resource URL built using the resource URL of the plugin itself. It's not nice but seems to work for MANIFEST located in either file or jar class loader:
String getPluginVersion() throws IOException {
Manifest mf = loadManifest(getClass().getClassLoader(), getClass());
return mf.getMainAttributes().getValue("Implementation-Version");
}
Manifest loadManifest(final ClassLoader cl, final Class c) throws IOException {
String resourceName = "/" + c.getName().replaceAll("\\.", "/") + ".class";
URL classResource = cl.getResource(resourceName);
String path = classResource.toString();
int idx = path.indexOf(resourceName);
if (idx < 0) {
return null;
}
String urlStr = classResource.toString().substring(0, idx) + "/META-INF/MANIFEST.MF";
URL url = new URL(urlStr);
InputStream in = null;
Manifest mf = null;
try {
in = url.openStream();
mf = new Manifest(in);
} finally {
if (null != in) {
in.close();
}
in = null;
}
return mf;
}
I don't think your "workaround" with the manifest file is such a bad idea. Since it's packed inside the .jar of your plugin you should always have access to it.
For this post to be an answer, here is another idea: Let maven do the dirty work for you during the build of your plugin: have a placeholder in your plugin source:
private final String myVersion = "[CURRENT-VERSION]";
use ant-plugin or something else to replace that placeholder with the current version before compilation.
First, add the following dependency to your plugin's POM:
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>2.0</version>
</dependency>
Then you can just do the following:
public class MyMojo extends AbstractMojo {
private static final String GROUP_ID = "your-group-id";
private static final String ARTIFACT_ID = "your-artifact-id";
/**
* #parameter default-value="${project}"
*/
MavenProject project;
public void execute() throws MojoExecutionException {
Set pluginArtifacts = project.getPluginArtifacts();
for (Iterator iterator = pluginArtifacts.iterator(); iterator.hasNext();) {
Artifact artifact = (Artifact) iterator.next();
String groupId = artifact.getGroupId();
String artifactId = artifact.getArtifactId();
if (groupId.equals(GROUP_ID) && artifactId.equals(ARTIFACT_ID)) {
System.out.println(artifact.getVersion());
break;
}
}
}

Categories

Resources