Lucene - Highlighter throwing exception when using * on search - lucene

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

Related

Convert pdf to pdf/a using iText library

I want to export document to PdfAConformanceLevel.PDF_A_1B conformance, but when I do document.close, I get error below, resulting pdf is not usable.
I use following itext versions:
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
<artifactId>itext-pdfa</artifactId>
<version>5.5.9</version>
stack trace:
com.itextpdf.text.pdf.PdfAConformanceException: Real number is out of range.
at com.itextpdf.text.pdf.internal.PdfA1Checker.checkPdfObject(PdfA1Checker.java:259)
at com.itextpdf.text.pdf.internal.PdfAChecker.checkPdfAConformance(PdfAChecker.java:208)
at com.itextpdf.text.pdf.internal.PdfAConformanceImp.checkPdfIsoConformance(PdfAConformanceImp.java:71)
at com.itextpdf.text.pdf.PdfWriter.checkPdfIsoConformance(PdfWriter.java:3480)
at com.itextpdf.text.pdf.PdfWriter.checkPdfIsoConformance(PdfWriter.java:3476)
at com.itextpdf.text.pdf.PdfObject.toPdf(PdfObject.java:174)
at com.itextpdf.text.pdf.PdfArray.toPdf(PdfArray.java:175)
at com.itextpdf.text.pdf.PdfDictionary.toPdf(PdfDictionary.java:149)
at com.itextpdf.text.pdf.PdfStream.superToPdf(PdfStream.java:278)
at com.itextpdf.text.pdf.PRStream.toPdf(PRStream.java:239)
at com.itextpdf.text.pdf.PdfIndirectObject.writeTo(PdfIndirectObject.java:158)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.write(PdfWriter.java:420)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:398)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:377)
at com.itextpdf.text.pdf.PdfWriter.addToBody(PdfWriter.java:872)
at com.itextpdf.text.pdf.PdfReaderInstance.writeAllVisited(PdfReaderInstance.java:161)
at com.itextpdf.text.pdf.PdfReaderInstance.writeAllPages(PdfReaderInstance.java:177)
at com.itextpdf.text.pdf.PdfWriter.addSharedObjectsToBody(PdfWriter.java:1380)
at com.itextpdf.text.pdf.PdfWriter.close(PdfWriter.java:1264)
at com.itextpdf.text.pdf.PdfAWriter.close(PdfAWriter.java:337)
at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:889)
at com.itextpdf.text.Document.close(Document.java:416)
at si.telekom.erender.ERenderImpl.mergeContentOfItems(ERenderImpl.java:2911)
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 sun.reflect.misc.Trampoline.invoke(MethodUtil.java:75)
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 sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:279)
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 com.sun.xml.ws.api.server.MethodUtil.invoke(MethodUtil.java:83)
at com.sun.xml.ws.api.server.InstanceResolver$1.invoke(InstanceResolver.java:250)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149)
at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:419)
at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:868)
at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:422)
at com.sun.xml.ws.transport.http.servlet.ServletAdapter.invokeAsync(ServletAdapter.java:225)
at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doGet(WSServletDelegate.java:161)
at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doPost(WSServletDelegate.java:197)
at com.sun.xml.ws.transport.http.servlet.WSServlet.doPost(WSServlet.java:81)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I am producing PDF with following code:
public byte[] mergeContentOfItems(List<MergeItem> items) throws ErenderException {
MessageContext mc = wsCtx.getMessageContext();
HttpServletRequest req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
getLogger().info("Webservice method 'mergeContentOfItems' called from IP:" + req.getRemoteAddr());
if (items.size() < 1) {
String errDescription = "No barcodes specified!";
throw new ErenderException(errDescription, new ErenderExceptionBean("201", errDescription),
new Throwable(errDescription));
}
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
ByteArrayOutputStream baOs = new ByteArrayOutputStream();
PdfWriter writer = null;
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
try {
// Create a writer for the outputstream
writer = PdfAWriter.getInstance(document, baOs, PdfAConformanceLevel.PDF_A_1B);
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
writer.createXmpMetadata();
//writer = PdfWriter.getInstance(document, baOs);
document.open();
ICC_Profile icc = ICC_Profile
.getInstance(Thread.currentThread().getContextClassLoader().getResourceAsStream("srgb.profile"));
writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
for (int i = 0; i < items.size(); i++) {
String pdfFileName = null;
File urlTempFile = null;
if (items.get(i).getBarcode() != null) {
Template tmpl = TemplatesSynchronizer.getTemplateByBarcode(items.get(i).getBarcode());
String fileName = tmpl.getName();
pdfFileName = fileName.substring(0, fileName.indexOf(".")) + ".pdf";
getLogger().info("\tworking on:" + items.get(i) + " fileName:" + pdfFileName);
if (!new File(pdfFileName).exists()) {
String msg = String.format("Datoteka %s ne obstaja", pdfFileName);
throw new ErenderException("Error", new ErenderExceptionBean("109", msg, new Exception(msg)));
}
} else if (items.get(i).getUrl() != null) {
urlTempFile = File.createTempFile("myTemp", "pdf");
FileUtils.copyURLToFile(new URL(items.get(i).getUrl()), urlTempFile);
}
if (pdfFileName != null || urlTempFile != null) {
PdfReader pdfReader = null;
if (pdfFileName != null)
pdfReader = new PdfReader(pdfFileName);
else if (urlTempFile != null)
pdfReader = new PdfReader(urlTempFile.getAbsolutePath());
if (pdfReader != null) {
// Create Readers for the pdfs.
readers.add(pdfReader);
totalPages += pdfReader.getNumberOfPages();
int pageOfCurrentReaderPDF = 0;
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
document.newPage();
pageOfCurrentReaderPDF++;
PdfImportedPage page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
document.setPageSize(pdfReader.getPageSizeWithRotation(pageOfCurrentReaderPDF));
document.newPage();
cb.addTemplate(page, 0, 0);
}
}
if (urlTempFile != null)
urlTempFile.delete();
}
}
} catch (Throwable ex) {
StringWriter errorStringWriter = new StringWriter();
PrintWriter pw = new PrintWriter(errorStringWriter);
ex.printStackTrace(pw);
Logger.getLogger(this.getClass()).error(errorStringWriter.getBuffer().toString());
throw new ErenderException("Error", new ErenderExceptionBean("109", "Napaka v merge metodi.",ex), ex);
} finally {
if (document != null && document.isOpen())
try {
document.close();
} catch (Exception ex) {
StringWriter errorStringWriter = new StringWriter();
PrintWriter pw = new PrintWriter(errorStringWriter);
ex.printStackTrace(pw);
Logger.getLogger(this.getClass()).error(errorStringWriter.getBuffer().toString());
getLogger().error("Unable to close document.\n" + errorStringWriter);
}
if (writer != null && writer.isCloseStream()) {
try {
writer.flush();
writer.close();
} catch (Exception ex) {
getLogger().error("Unable to flush or close writer");
}
}
try {
baOs.flush();
baOs.close();
} catch (Exception ex) {
getLogger().error("Unable to close baOs in mergeContent method.");
}
}
getLogger().info("Webservice method 'mergeContent' called from IP:" + req.getRemoteAddr() + " ended. " + totalPages
+ " merged.");
return baOs.toByteArray();
}
Since I don't get error on other files this seems to be input files specific - here is one file to reproduce error:
I am trying to convert this input pdf file:
http://filebin.ca/2hR2xO1SNlzh/09062009073008005.pdf
First this: iText doesn't convert ordinary PDF documents to PDF/A documents. We have customers who use iText to do this, but their code is much more elaborate than yours.
The reason why iText doesn't convert ordinary PDF documents to PDF/A should be evident: an ordinary PDF might not have all the necessary features that are needed in a PDF/A. You might have a PDF of which the fonts aren't embedded. In that case, someone needs to provide the appropriate font program. iText doesn't ship with any font program, hence the software using iText has to provide this.
In your code, you just copy content streams without checking any possible issues that make the end result non-compliant with PDF/A. You should be very careful with the resulting PDFs. They will show the blue bar that the file claims to be PDF/A, but that doesn't mean that the file will validate as a PDF when you pass it through a validator.
Now for your problem. You want to convert an ordinary PDF to PDF/A-1. PDF/A-1 is based on PDF 1.4 dating from 2001. This means that you can't use any of the new features that were introduced after 2001. In PDF 1.4, there was a limitation with respect to object number. Object numbers in PDF couldn't exceed 32,767. This limitation was removed from PDF in PDF 1.5.
My guess is that the problem you describe is caused by your attempt to create a PDF 1.4 with more objects than is allowed in PDF 1.4. There could be two reasons:
Your original PDF is PDF 1.5 or later,
Your manipulations of the PDF require more than the maximum available number of objects.
This could be fixed by generating PDF/A-2 instead of PDF/A-1, but I'm pretty sure that you'll soon hit other limitations (e.g. missing fonts and other issues that are caused by creating a file that claims to be a PDF but that isn't). PdfAWriter will throw exceptions when you try doing things that are blatantly wrong, but there's no guarantee that some more subtle PDF/A requirements are being missed.

to extract image and meta data from DICOM image using java

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);
}
}

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)

Why am i getting this error java.lang.ClassNotFoundException?

Why am i getting this error message?
Testcase: createIndexBatch_usingTheTestArchive(src.LireHandlerTest): Caused an ERROR
at/lux/imageanalysis/ColorLayoutImpl
java.lang.NoClassDefFoundError: at/lux/imageanalysis/ColorLayoutImpl
at net.semanticmetadata.lire.impl.SimpleDocumentBuilder.createDocument(Unknown Source)
at net.semanticmetadata.lire.AbstractDocumentBuilder.createDocument(Unknown Source)
at backend.storage.LireHandler.createIndexBatch(LireHandler.java:49)
at backend.storage.LireHandler.createIndexBatch(LireHandler.java:57)
at src.LireHandlerTest.createIndexBatch_usingTheTestArchive(LireHandlerTest.java:56)
Caused by: java.lang.ClassNotFoundException: at.lux.imageanalysis.ColorLayoutImpl
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
I am trying to create a Lucene index using documents that are created using Lire. When i am getting to the point where it tries to create a document using the document builder it gives me this error message.
input paramaters first run:
filepath: "test_archive" (this is a image archive)
whereToStoreIndex: "test_index" (Where i am going to store the index)
createNewIndex: true
Since the method is recursive (see the if statement where it checks if is a directory) it will call itself multiple times but all the recursive calls uses createNewIndex = false.
Here is the code:
public static boolean createIndexBatch(String filepath, String whereToStoreIndex, boolean createNewIndex){
DocumentBuilder docBldr = DocumentBuilderFactory.getDefaultDocumentBuilder();
try{
IndexWriter indexWriter = new IndexWriter(
FSDirectory.open(new File(whereToStoreIndex)),
new SimpleAnalyzer(),
createNewIndex,
IndexWriter.MaxFieldLength.UNLIMITED
);
File[] files = FileHandler.getFilesFromDirectory(filepath);
for(File f:files){
if(f.isFile()){
//Hopper over Thumbs.db filene...
if(!f.getName().equals("Thumbs.db")){
//Creating the document that is going to be stored in the index
String name = f.getName();
String path = f.getPath();
FileInputStream stream = new FileInputStream(f);
Document doc = docBldr.createDocument(stream, f.getName());
//Add document to the index
indexWriter.addDocument(doc);
}
}else if(f.isDirectory()){
indexWriter.optimize();
indexWriter.close();
LireHandler.createIndexBatch(f.getPath(), whereToStoreIndex, false);
}
}
indexWriter.close();
}catch(IOException e){
System.out.print("IOException in createIndexBatch:\n"+e.getMessage()+"\n");
return false;
}
return true;
}
It sounds like you are missing a java library.
I think you need to download Caliph & Emir, that may be used indirectly by Lire.
http://www.semanticmetadata.net/download/

Detail Hudson test reports

Is there any way to force Hudson to give me more detailed test results - e.g. I'm comparing two strings and I want to know where they differ.
Is there any way to do this?
Thank you for help.
You should not hope Hudson give the detail information, it just shows the testing messages generated by junit.
You could show the expected string and actual string when failing asserting equals between those two strings.
For example,
protected void compareFiles(File newFile, String referenceLocation, boolean lineNumberMatters) {
BufferedReader reader = null;
BufferedReader referenceReader = null;
List<String> expectedLines = new ArrayList<String>();
try {
referenceReader = new BufferedReader(new InputStreamReader(FileLocator.openStream(Activator.getDefault().getBundle(), new Path("data/regression/" + referenceLocation), false))); //$NON-NLS-1$
expectedLines = getLinesFromReader(referenceReader);
} catch (Exception e) {
assertFalse("Exception occured during reading reference data: " + e, true); //$NON-NLS-1$
}
List<String>foundLines = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(newFile));
foundLines = getLinesFromReader(reader);
} catch (Exception e) {
assertFalse("Exception occured during reading file: " + e, true); //$NON-NLS-1$
}
boolean throwException = expectedLines.size() != foundLines.size();
if (throwException) {
StringBuffer buffer = new StringBuffer("\n" + newFile.toString()); //$NON-NLS-1$
for (String line: foundLines)
buffer.append(line + "\n"); //$NON-NLS-1$
assertEquals("The number of lines in the reference(" + referenceLocation + ") and new output(" + newFile.getAbsolutePath()+ ") did not match!" + buffer, expectedLines.size(), foundLines.size()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
if (!lineNumberMatters) {
Collections.sort(expectedLines);
Collections.sort(foundLines);
}
/** Either the line matches character by character or it matches regex-wise, in that order */
for (int i=0;i<expectedLines.size(); i++)
assertTrue("Found errors in file (" + newFile + ")! " + foundLines.get(i) + " vs. " + expectedLines.get(i), foundLines.get(i).equals(expectedLines.get(i)) || foundLines.get(i).matches(expectedLines.get(i))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
Hudson supports JUnit directly. On your job configuration page, near the end, should be an option to "Publish JUnit test results report".
I'm not too familiar with JUnit itself, but I guess it produces (or has the ability to produce) and put results in an xml file. You just need to put the path of to the xml file (relative to the workspace) in the text box.
Once you do that, and create a build, you'll have a detailed report on your project page. You should then be able to click your way through the results for each test.