to extract image and meta data from DICOM image using java - dcm4che

i am trying to extract image and metadata from dicom image using java on windows platform. i am new in dcm4che.
my code is
i am getting error
Exception in thread "main" java.lang.NoClassDefFoundError: org/dcm4che2/image/PartialComponentSampleModel
at org.dcm4che2.imageioimpl.plugins.dcm.DicomImageReaderSpi.createReaderInstance(DicomImageReaderSpi.java:146)
at javax.imageio.spi.ImageReaderSpi.createReaderInstance(ImageReaderSpi.java:320)
at javax.imageio.ImageIO$ImageReaderIterator.next(ImageIO.java:529)
at javax.imageio.ImageIO$ImageReaderIterator.next(ImageIO.java:513)
at miec.extraction.extraction.extractionD(extraction.java:32)
at miec.MIEC.main(MIEC.java:46)
Caused by: java.lang.ClassNotFoundException: org.dcm4che2.image.PartialComponentSampleModel
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)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 6 more
please help me... which all jar files should i include..

Use PixelMed Here the example
import com.pixelmed.dicom.Attribute;
import com.pixelmed.dicom.AttributeList;
import com.pixelmed.dicom.AttributeTag;
import com.pixelmed.dicom.TagFromName;
import com.pixelmed.display.SourceImage;
public class DisplayImageTagsToConsole {
private static AttributeList list = new AttributeList();
public static void readDcmFile() {
String dicomFile = "E:\\eye\\demo12.dcm";
try {
list.read(dicomFile);
System.out.println("Patient Name:" + getTagInformation(TagFromName.PatientName));
System.out.println("Patient ID:" + getTagInformation(TagFromName.PatientID));
System.out.println("Transfer Syntax:" + getTagInformation(TagFromName.TransferSyntaxUID));
System.out.println("SOP Class:" + getTagInformation(TagFromName.SOPClassUID));
System.out.println("Modality:" + getTagInformation(TagFromName.Modality));
System.out.println("Samples Per Pixel:" + getTagInformation(TagFromName.SamplesPerPixel));
System.out.println("Photometric Interpretation:" + getTagInformation(TagFromName.PhotometricInterpretation));
System.out.println("Pixel Spacing:" + getTagInformation(TagFromName.PixelSpacing));
System.out.println("Bits Allocated:" + getTagInformation(TagFromName.BitsAllocated));
System.out.println("Bits Stored:" + getTagInformation(TagFromName.BitsStored));
System.out.println("High Bit:" + getTagInformation(TagFromName.HighBit));
SourceImage img = new com.pixelmed.display.SourceImage(list);
System.out.println("Number of frames " + img.getNumberOfFrames());
System.out.println("Width " + img.getWidth());//all frames will have same width
System.out.println("Height " + img.getHeight());//all frames will have same height
System.out.println("Is Grayscale? " + img.isGrayscale());
System.out.println("Pixel Data present:" + (list.get(TagFromName.PixelData) != null));
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getTagInformation(AttributeTag attrTag) {
return Attribute.getDelimitedStringValuesOrEmptyString(list, attrTag);
}
}

Related

CAMEL HTTP4 post request was rejected because no multipart boundary was found

I'm using Camel-http4 because I simply need a producer, not expose a webservice. I simply need to push files up to an HTTP server, so this is a client implementation. the problem I am facing is the attempt to post returns an error.
CamelHttpResponseCode=403, CamelHttpResponseText=Forbidden
{"timestamp":"2018-05-03T20:36:20.571","traceId":"","path":"[POST] https://apm-query-svc-prod.apm-api.com/v2/t_series/upload%2520?throwExceptionOnFailure=false","errors":[{"httpStatusCode":"FORBIDDEN","code":"FORBIDDEN","message":"Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found","detail":null,"requestId":null}]}
Question, is there a way to do this with Camel-HTTP4 ? how is / can this be done? and thank you !!!
here is the route
<route
id="core.pr.upload.route"
autoStartup="false" >
<from uri="{{uploadEntranceEndpoint}}" />
<process ref="customerEntitesProcessor" />
<process ref="customerTokenProcessor" />
<process ref="uploadProcessor" />
<setHeader headerName="CamelHttpUri">
<simple>${header.UPLOADURL}?throwExceptionOnFailure=false</simple>
</setHeader>
<setHeader headerName="CamelHttpMethod">
<constant>POST</constant>
</setHeader>
<to uri="http4://apm-query-svc-prod.app-api.aws-usw02-pr.io:443/v2/t_series/upload?throwExceptionOnFailure=false" />
<log message="After POSTING FILE: ${body}" loggingLevel="INFO"/>
<to uri="{{afteruploadLocation}}" />
</route>
here is the class, I simply set the headers up and the URI is overridden with the one provided by Exchange.HTTP_URI.
public class UploadProcessor implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(UploadProcessor.class);
#Override
public void process(Exchange exchange) throws Exception {
LOG.info("Entering Upload Processor ..." );
final String tenant = (String)exchange.getIn().getHeader("TENANT");
final String token = (String)exchange.getIn().getHeader("TOKEN");
final String uploadUrl = (String)exchange.getIn().getHeader("UPLOADURL");
final String custKey = (String)exchange.getIn().getHeader("CUSTKEY");
LOG.info("TENANT: " + tenant);
LOG.info("TOKEN: " + token);
LOG.info("UPLOADURL: " + uploadUrl);
LOG.info("CUSTKEY: " + custKey);
LOG.info("Uploading File for CustKey: " + custKey + " and Tenant: " + tenant);
StringBuilder authHeader = new StringBuilder("Bearer ");
authHeader.append(token);
LOG.info("Authorization: " + authHeader.toString());
exchange.setProperty("CamelCharsetName", "UTF-8"); //"CamelCharsetName" Exchange.CHARSET_NAME
exchange.getIn().setHeader("CamelHttpCharacterEncoding", "UTF-8"); //"CamelHttpCharacterEncoding" Exchange.HTTP_CHARACTER_ENCODING
exchange.getIn().setHeader("CamelAcceptContentType", "application/json"); //"CamelAcceptContentType" Exchange.ACCEPT_CONTENT_TYPE
exchange.getIn().setHeader("CamelHttpUri", uploadUrl); //"CamelHttpUri" Exchange.HTTP_URI
exchange.getIn().setHeader("CamelHttpMethod", "POST"); //"CamelHttpMethod" Exchange.HTTP_METHOD
exchange.getIn().setHeader("x-ge-csvformat", "ODB");
exchange.getIn().setHeader("Tenant", tenant);
exchange.getIn().setHeader("Content-Type", "multipart/form-data"); //"Content-Type" ; boundary=
exchange.getIn().setHeader("Authorization", authHeader.toString());
LOG.info("Exiting Upload Processor: Finish " );
}
}
this is my first HTTP introduction, not familiar with the multipart boundary, I'm hoping there is a kind a simple solution to this. :) thank you !!!
The solution wasn't that difficult at all, here is the final based on Ralf's answer. thanks all! the hard part was finding the import packages and that it has a dependency.
add to POM
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1</version>
</dependency>
import java.lang.StringBuilder;
import java.net.URLEncoder;
import java.util.Base64;
import java.io.File;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.camel.LoggingLevel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
public class UploadProcessor implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(UploadProcessor.class);
#Override
public void process(Exchange exchange) throws Exception {
LOG.info("Entering Upload Processor ..." );
final String tenant = (String)exchange.getIn().getHeader("TENANT");
final String token = (String)exchange.getIn().getHeader("TOKEN");
final String uploadUrl = (String)exchange.getIn().getHeader("UPLOADURL");
final String custKey = (String)exchange.getIn().getHeader("CUSTKEY");
LOG.info("TENANT: " + tenant);
LOG.info("TOKEN: " + token);
LOG.info("UPLOADURL: " + uploadUrl);
LOG.info("CUSTKEY: " + custKey);
LOG.info("Uploading File for CustKey: " + custKey + " and Tenant: " + tenant);
StringBuilder authHeader = new StringBuilder("Bearer ");
authHeader.append(token);
LOG.info("Authorization: " + authHeader.toString());
exchange.setProperty("CamelCharsetName", "UTF-8"); //"CamelCharsetName" Exchange.CHARSET_NAME
exchange.getIn().setHeader("CamelHttpCharacterEncoding", "UTF-8"); //"CamelHttpCharacterEncoding" Exchange.HTTP_CHARACTER_ENCODING
exchange.getIn().setHeader("CamelAcceptContentType", "application/json"); //"CamelAcceptContentType" Exchange.ACCEPT_CONTENT_TYPE
exchange.getIn().setHeader("CamelHttpUri", uploadUrl); //"CamelHttpUri" Exchange.HTTP_URI
exchange.getIn().setHeader("CamelHttpMethod", "POST"); //"CamelHttpMethod" Exchange.HTTP_METHOD
exchange.getIn().setHeader("x-ge-csvformat", "ODB");
exchange.getIn().setHeader("Tenant", tenant);
exchange.getIn().setHeader("Authorization", authHeader.toString());
// Process the file in the exchange body
File file = exchange.getIn().getBody(File.class);
String fileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME);
LOG.info("fileName: " + fileName);
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addBinaryBody("file", file);
entity.addTextBody("name", fileName);
exchange.getIn().setBody(entity.build());
LOG.info("Exiting Upload Processor: Finish " );
}
}

SonarQube Runner throws NullPointerException during analysis

UPDATE:
I am running it on Fedora 21.
SonarQube - 5.0.
SonarQube Runner - 2.4
UPDATE2: Findbugs v3.1, Java Plugin v2.8
UPDATE3:
Analyzer fails on the following file:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MyManager extends ParentManager {
public MyManager(int id, int var1, int var2, int var3) {
super(id, var1, var2, var3);
}
public void load() {
Connection con = null;
Statement st;
ResultSet res;
try {
con = DatabaseManager.getDataSource().getConnection();
st = con.createStatement();
int currentId = 0;
CurrentData currentData= null;
res = st.executeQuery("SELECT subjects.subjectname" + " AS name, " +
" subjects.subjectcode AS code, " +
" groups.groupname AS gname, " +
" groups.groupID AS gID , " +
" subjects.sID AS sID, " +
" groups.isMain AS ismain " +
" FROM joinGroup LEFT JOIN groups ON joinGroup.groupID=groups.groupID " +
" LEFT JOIN subjects ON subjects.sID=groups.sID " +
" WHERE joinGroup.sID=" + id + " " +
" AND groups.var1" + var1 + " AND groups.var2=" + var2 + " " +
" ORDER BY name, subjects.subjectcode, subjects.sID ");
while (res.next()) {
if (currentId != res.getInt("sID")) {
currentData = new CurrentData();
data.subjects.add(currentData);
currentData.subjectName = res.getString("name");
currentData.subjectID = res.getInt("sID");
}
CurrentGroupData groupData = new CurrentGroupData();
groupData.name = res.getString("gname");
groupData.id = res.getInt("gID");
currentId = res.getInt("sID");
if (res.getBoolean("ismain")) {
assert currentData != null;
currentData.groupID = res.getInt("gID");
}
if (currentData != null) {
currentData.groups.add(groupData);
}
}
loadSubjectsData(st, res);
} catch (Exception exc) {
Log.writeLog(ex);
} finally {
try {
con.close();
} catch (SQLException e) {
Log.writeLog(e);
}
}
}
}
I have installed SonarQube following the tutorials on sonar website.
I am able to browse to localhost:9000 and it shows start page.
Then I try to analyze the project via command: sonar-runner.
It fails.
Running sonar-runner -X displays the following:
>
ERROR: Error during Sonar runner execution
org.sonar.runner.impl.RunnerException: Unable to execute Sonar
at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:91)
at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
at java.security.AccessController.doPrivileged(Native Method)
at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102)
at org.sonar.runner.api.Runner.execute(Runner.java:100)
at org.sonar.runner.Main.executeTask(Main.java:70)
at org.sonar.runner.Main.execute(Main.java:59)
at org.sonar.runner.Main.main(Main.java:53)
Caused by: org.sonar.squidbridge.api.AnalysisException: SonarQube is unable to analyze file : '/path/to/my/file/MyFile.java'
at org.sonar.java.ast.AstScanner.simpleScan(AstScanner.java:114)
at org.sonar.java.ast.AstScanner.scan(AstScanner.java:75)
at org.sonar.java.JavaSquid.scanSources(JavaSquid.java:122)
at org.sonar.java.JavaSquid.scan(JavaSquid.java:115)
at org.sonar.plugins.java.JavaSquidSensor.analyse(JavaSquidSensor.java:91)
at org.sonar.batch.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:79)
at org.sonar.batch.phases.SensorsExecutor.execute(SensorsExecutor.java:70)
at org.sonar.batch.phases.PhaseExecutor.execute(PhaseExecutor.java:122)
at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:222)
at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:93)
at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:78)
at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:235)
at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:230)
at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:223)
at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:93)
at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:78)
at org.sonar.batch.scan.ScanTask.scan(ScanTask.java:65)
at org.sonar.batch.scan.ScanTask.execute(ScanTask.java:52)
at org.sonar.batch.bootstrap.TaskContainer.doAfterStart(TaskContainer.java:128)
at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:93)
at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:78)
at org.sonar.batch.bootstrap.BootstrapContainer.executeTask(BootstrapContainer.java:171)
at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:95)
at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:67)
at org.sonar.runner.batch.IsolatedLauncher.execute(IsolatedLauncher.java:48)
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.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:87)
... 9 more
Caused by: java.lang.NullPointerException
at org.sonar.java.checks.AbstractInjectionChecker.isIdentifierDynamicString(AbstractInjectionChecker.java:67)
at org.sonar.java.checks.AbstractInjectionChecker.isDynamicString(AbstractInjectionChecker.java:54)
at org.sonar.java.checks.AbstractInjectionChecker.isDynamicString(AbstractInjectionChecker.java:49)
at org.sonar.java.checks.AbstractInjectionChecker.isDynamicString(AbstractInjectionChecker.java:57)
at org.sonar.java.checks.AbstractInjectionChecker.isDynamicString(AbstractInjectionChecker.java:49)
at org.sonar.java.checks.AbstractInjectionChecker.isDynamicString(AbstractInjectionChecker.java:57)
at org.sonar.java.checks.AbstractInjectionChecker.isDynamicString(AbstractInjectionChecker.java:49)
at org.sonar.java.checks.AbstractInjectionChecker.isDynamicString(AbstractInjectionChecker.java:57)
at org.sonar.java.checks.SQLInjectionCheck.visitNode(SQLInjectionCheck.java:48)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visit(SubscriptionVisitor.java:95)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visitChildren(SubscriptionVisitor.java:113)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visit(SubscriptionVisitor.java:97)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visitChildren(SubscriptionVisitor.java:113)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visit(SubscriptionVisitor.java:97)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visitChildren(SubscriptionVisitor.java:113)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visit(SubscriptionVisitor.java:97)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visitChildren(SubscriptionVisitor.java:113)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visit(SubscriptionVisitor.java:97)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visitChildren(SubscriptionVisitor.java:113)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visit(SubscriptionVisitor.java:97)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visitChildren(SubscriptionVisitor.java:113)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visit(SubscriptionVisitor.java:97)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visitChildren(SubscriptionVisitor.java:113)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visit(SubscriptionVisitor.java:97)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visitChildren(SubscriptionVisitor.java:113)
at org.sonar.java.ast.visitors.SubscriptionVisitor.visit(SubscriptionVisitor.java:97)
at org.sonar.java.ast.visitors.SubscriptionVisitor.scanTree(SubscriptionVisitor.java:73)
at org.sonar.java.ast.visitors.SubscriptionVisitor.scanFile(SubscriptionVisitor.java:67)
at org.sonar.java.model.VisitorsBridge.visitFile(VisitorsBridge.java:122)
at com.sonar.sslr.impl.ast.AstWalker.walkAndVisit(AstWalker.java:67)
at org.sonar.java.ast.AstScanner.simpleScan(AstScanner.java:107)
... 38 more
>
Didn't do anything "exotic", just followed the official tutorials like this one:
http://docs.sonarqube.org/display/SONAR/Analyzing+with+SonarQube+Runner
I am running it locally.
Any ideas?
Thanks
I got similar problem with ReturnEmptyArrayyNotNullCheck. As a workaround I disabled that rule in sonarqube web gui.
Log in as an admin. Click Rules in the top menu. Search for SQL or Inject or whatever other word to find the rule you think is causing analysis failures. Then select the rule and disable it in the quality profile attached to your project. Of course this rule will be ignored totally in all attached projects.
I got no solution, but ran into the same problem and and found this reference on sonar website, could it be the same problem you have?
http://sonarqube.15.x6.nabble.com/NullPointerException-analysing-file-with-SQLInjectionCheck-td5032155.html (Scroll to the end)

Sonar-qube 4.5.1 custom rules plugin is not working

I have created a custom rule plugin using custom rule code snippet. Now I have added another rule which will show error when a anonymous class has more than 30 lines.
I have build the custom rule plugin jar using mvn package command and put in in sonar server extension/plugin and restarted the server.
my corresponding rule can be viewed from sonar server but rule cannot analyze the the code though there is a class with anonymous class with loc >30 lines. my custom rule is given below.
#Rule(
key = AnonymousClassesTooBigCheck.KEY,
name = "Avoid too big classes",
description = "avoid too bid classes",
tags = {"brain-overload"},
priority = Priority.MAJOR)
#BelongsToProfile(title = "Sonar way", priority = Priority.MAJOR)
public class AnonymousClassesTooBigCheck extends BaseTreeVisitor implements JavaFileScanner {
public static final String KEY = "AD0001";
private static final RuleKey RULE_KEY = RuleKey.of(MyJavaRulesDefinition.REPOSITORY_KEY, KEY);
private static final int DEFAULT_MAX = 30;
#RuleProperty(defaultValue = "" + DEFAULT_MAX)
public int max = DEFAULT_MAX;
private JavaFileScannerContext context;
/**
* Flag to skip check for class bodies of EnumConstants.
*/
private boolean isEnumConstantBody;
#Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
isEnumConstantBody = false;
scan(context.getTree());
}
#Override
public void visitNewClass(NewClassTree tree) {
if (tree.classBody() != null && !isEnumConstantBody) {
int lines = getNumberOfLines(tree.classBody());
if (lines > max) {
context.addIssue(tree, RULE_KEY, "Reduce this anonymous class number of lines from " + lines + " to at most " + max + ", or make it a named class.");
}
}
isEnumConstantBody = false;
super.visitNewClass(tree);
}
#Override
public void visitEnumConstant(EnumConstantTree tree) {
isEnumConstantBody = true;
super.visitEnumConstant(tree);
}
#Override
public void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree) {
int lines = getNumberOfLines(((JavaTree) lambdaExpressionTree.body()).getAstNode());
if (lines > max) {
context.addIssue(lambdaExpressionTree, RULE_KEY, "Reduce this lambda expression number of lines from " + lines + " to at most " + max + ".");
}
super.visitLambdaExpression(lambdaExpressionTree);
}
private int getNumberOfLines(ClassTree classTree) {
int startLine = ((InternalSyntaxToken) classTree.openBraceToken()).getLine();
int endline = ((InternalSyntaxToken) classTree.closeBraceToken()).getLine();
return endline - startLine + 1;
}
private int getNumberOfLines(AstNode node) {
return node.getLastToken().getLine() - node.getTokenLine() + 1;
}
}
Now do I need to do any thing more to get the rule hit?
One more thing
after putting the plugin jar in plugin folder if i run the analyzer using mvn sonar:sonar a error occures
Embedded error: org/sonar/java/model/InternalSyntaxToken
org.sonar.java.model.InternalSyntaxToken
[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.lifecycle.LifecycleExecutionException: Can not execute Sonar
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:719)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:569)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:539)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:284)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
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.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.MojoExecutionException: Can not execute Sonar
at org.codehaus.mojo.sonar.Bootstraper.executeMojo(Bootstraper.java:103)
at org.codehaus.mojo.sonar.Bootstraper.start(Bootstraper.java:79)
at org.codehaus.mojo.sonar.SonarMojo.execute(SonarMojo.java:88)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694)
... 17 more
Caused by: org.apache.maven.plugin.MojoExecutionException: org/sonar/java/model/InternalSyntaxToken
at org.sonar.maven.ExceptionHandling.handle(ExceptionHandling.java:37)
at org.sonar.maven.SonarMojo.execute(SonarMojo.java:175)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490)
at org.codehaus.mojo.sonar.Bootstraper.executeMojo(Bootstraper.java:98)
... 21 more
Caused by: java.lang.NoClassDefFoundError: org/sonar/java/model/InternalSyntaxToken
at org.sonar.samples.java.AnonymousClassesTooBigCheck.getNumberOfLines(AnonymousClassesTooBigCheck.java:78)
at org.sonar.samples.java.AnonymousClassesTooBigCheck.visitNewClass(AnonymousClassesTooBigCheck.java:53)
at org.sonar.java.model.expression.NewClassTreeImpl.accept(NewClassTreeImpl.java:126)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:42)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.visitVariable(BaseTreeVisitor.java:291)
at org.sonar.java.model.declaration.VariableTreeImpl.accept(VariableTreeImpl.java:180)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:42)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:36)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.visitClass(BaseTreeVisitor.java:69)
at org.sonar.java.model.declaration.ClassTreeImpl.accept(ClassTreeImpl.java:201)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:42)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:36)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.visitClass(BaseTreeVisitor.java:69)
at org.sonar.java.model.declaration.ClassTreeImpl.accept(ClassTreeImpl.java:201)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:42)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:36)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.visitCompilationUnit(BaseTreeVisitor.java:55)
at org.sonar.java.model.JavaTree$CompilationUnitTreeImpl.accept(JavaTree.java:202)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:42)
at org.sonar.samples.java.AnonymousClassesTooBigCheck.scanFile(AnonymousClassesTooBigCheck.java:47)
at org.sonar.java.model.VisitorsBridge.visitFile(VisitorsBridge.java:123)
at com.sonar.sslr.impl.ast.AstWalker.walkAndVisit(AstWalker.java:67)
at org.sonar.java.ast.AstScanner.simpleScan(AstScanner.java:107)
at org.sonar.java.ast.AstScanner.scan(AstScanner.java:75)
at org.sonar.java.JavaSquid.scanSources(JavaSquid.java:122)
at org.sonar.java.JavaSquid.scan(JavaSquid.java:115)
at org.sonar.plugins.java.JavaSquidSensor.analyse(JavaSquidSensor.java:91)
at org.sonar.batch.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:79)
at org.sonar.batch.phases.SensorsExecutor.execute(SensorsExecutor.java:70)
at org.sonar.batch.phases.PhaseExecutor.execute(PhaseExecutor.java:119)
at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:194)
at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:92)
at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:77)
at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:233)
at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:228)
at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:221)
at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:92)
at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:77)
at org.sonar.batch.scan.ScanTask.scan(ScanTask.java:64)
at org.sonar.batch.scan.ScanTask.execute(ScanTask.java:51)
at org.sonar.batch.bootstrap.TaskContainer.doAfterStart(TaskContainer.java:125)
at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:92)
at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:77)
at org.sonar.batch.bootstrap.BootstrapContainer.executeTask(BootstrapContainer.java:173)
at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:95)
at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:67)
at org.sonar.runner.batch.IsolatedLauncher.execute(IsolatedLauncher.java:48)
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.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:87)
at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
at java.security.AccessController.doPrivileged(Native Method)
at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102)
at org.sonar.runner.api.Runner.execute(Runner.java:100)
at org.sonar.maven.SonarMojo.execute(SonarMojo.java:173)
... 23 more
Caused by: java.lang.ClassNotFoundException: org.sonar.java.model.InternalSyntaxToken
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:259)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:235)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:227)
... 82 more
The reason you encounter this error is that the code of the AnonymousClassesTooBigCheck is using internal APIs, here InternalSyntaxToken is not supposed to be used directly and thus fails at runtime (you might notice that none of the example in the custom rule code snippet is using this class).

Lucene - Highlighter throwing exception when using * on search

I'm using Lucene 4.6.1 and Highlighter 4.6.0. Since indexing is working properly, I'm just gonna show my search code:
... code to get all the fields' name/values, numDocs, etc.
...
// Create Query and search
try {
TopScoreDocCollector collector = TopScoreDocCollector.create(numDocs, true);
Query q = MultiFieldQueryParser.parse(Version.LUCENE_40, searchTerms, fields, analyzer);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
Highlighter highlighter = new Highlighter(new QueryScorer(q));
highlighter.setTextFragmenter(new SimpleFragmenter(40));
int maxNumFragmentsRequired = 2;
System.out.println("Found " + hits.length + " hits.");
for(int i=0;i<hits.length;++i) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
for(int j=0; j<fields.length; j++) {
if(d.get(fields[j]) != null) {
String fieldText = d.get(fields[j]).trim();
TokenStream tokenStream = analyzer.tokenStream(fields[j], new StringReader(fieldText));
// Create String without the highlighted term
String unhighlighted = (i + 1) + ". "+fields[j]+ " "+ d.get(fields[j]).trim() + "<br>";
// Create the highlighted term
String highlighted = highlighter.getBestFragments(tokenStream, fieldText, maxNumFragmentsRequired, "...");
// If the highlighted term really exists
if(!highlighted.equals(""))
unhighlighted = (i + 1) + ". "+fields[j]+ " "+ highlighted + "<br>";
response += unhighlighted;
}
}
}
} catch (Exception e) {
System.out.println("Error searching " + searchTerm + " : " + e.getMessage());
}
System.out.println(response);
}
For example: into my index I got many Documents named "Process 001", "Process 002", "Process 003" and so on. If I try to search by: Process, I can retrieve all the Process (this is working perfect!). The problem happens when I try to search by: proc*, or: pr*, or something like that... The errors are here:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/lucene/queries/CommonTermsQuery
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.extract(WeightedSpanTermExtractor.java:149)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.extract(WeightedSpanTermExtractor.java:99)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.getWeightedSpanTerms(WeightedSpanTermExtractor.java:474)
at org.apache.lucene.search.highlight.QueryScorer.initExtractor(QueryScorer.java:217)
at org.apache.lucene.search.highlight.QueryScorer.init(QueryScorer.java:186)
at org.apache.lucene.search.highlight.Highlighter.getBestTextFragments(Highlighter.java:197)
at org.apache.lucene.search.highlight.Highlighter.getBestFragments(Highlighter.java:156)
at org.apache.lucene.search.highlight.Highlighter.getBestFragments(Highlighter.java:460)
at freedom.lucene.service.LuceneTestApplication.search(LuceneTestApplication.java:406)
at freedom.lucene.service.LuceneTestApplication.main(LuceneTestApplication.java:75)
Caused by: java.lang.ClassNotFoundException: org.apache.lucene.queries.CommonTermsQuery
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 10 more
The exception occurs on this line:
String highlighted = highlighter.getBestFragments(tokenStream, fieldText, maxNumFragmentsRequired, "...");
If I remove the Highlighter code, the search works properly with *
Add lucene-queries-4.6.1.jar to your classpath.
CommonTermsQuery is not included in the lucene-core jar.
Add lucene-memory-XX.jar to your External Libraries

Use property file in a JAR

After a lot of property file articles and comments I am really lost.
All I want is to retrieve values and to overwrite them - and I want to use that with a jar-file.
If I compile in eclipse it works perfectly but the moment I compile I got the famous "property file not found"-exception.
FileInputStream in = new FileInputStream(ClassLoader.getSystemResource("client.properties").getPath());
Properties props = new Properties();
props.load(in);
in.close();
The exception I got is the following:
C:\Users\thomas\Desktop>java -jar erp_auer_client_v0_1.jar
java.io.FileNotFoundException: file:\C:\Users\thomas\Desktop\erp_auer_client_v0_
1.jar!\client.properties (Die Syntax f³r den Dateinamen, Verzeichnisnamen oder d
ie Datentrõgerbezeichnung ist falsch)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at global_functions.helperFunctions.getPathBARTENDEREXE(helperFunctions.
java:361)
at client.programmeinstellungen.ProgrammEinstellungenManagement.<init>(P
rogrammEinstellungenManagement.java:59)
at client.main.MainOverview$11.mousePressed(MainOverview.java:275)
The german part (Die Syntax f³r den Dateinamen, Verzeichnisnamen oder d
ie Datentrõgerbezeichnung ist falsch) means "The syntax for the filename, directory name or disk name is wrong".
Do you have an idea what that could be?
Alright, I tried it myself and realized that it is a little more trickier than I thought initially. However, I think that in your scenario you can just use something like bellow. I tested in windows and linux and worked fine for me:
package mypackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Properties;
public class MyMainClass {
public static void main(String[] args) throws URISyntaxException {
/*
*
* MyMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
* In Linux it returns null
*
* ClassLoader.getSystemClassLoader().getResource(".").getPath() + "MyProperty.properties";
* In Linux it returns {JRE_PATH}/lib/ext/pulse-java.jar
* In Windows it returns {JAR_FILE_PATH}
*/
String propertyFilePath = "MyProperty.properties";
Properties props = new Properties();
try {
FileInputStream in = new FileInputStream(propertyFilePath);
props.load(in);
in.close();
} catch (Exception e) {
File f = new File(propertyFilePath);
System.err.println("Could not read file: " + f.getAbsolutePath());
}
System.out.println("Fetching property value of [now]: " + props.get("now"));
String now = new Date().toString();
System.out.println("Storing property [now]: " + now);
props.setProperty("now", now);
try {
OutputStream out = new FileOutputStream(propertyFilePath);
props.store(out, "Saving value of [now]");
} catch (Exception e) {
File f = new File(propertyFilePath);
System.err.println("Could not write file: " + f.getAbsolutePath());
}
}
}