How to read a file from WEB-INF/resources folder? - jasper-reports

I am using Icefaces for webapplication development. I wish to read a file from the resources folder and use it in the sessionbean.
Actually I wish to setup Jasper Reports. I have already setup the libraries in the classpath. The problem I get is while fetching the file from /WEB-INF/resources/ folder. Everytime I run the code from SessionBean, I get the exception:
net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: /resources/reports/myreport.jrxml (No such file or directory)
The Code I use is:
public void generateReport() {
try {
JasperCompileManager.compileReportToFile(
"/resources/reports/myreport.jrxml",
"/resources/reports/myreport.jasper");
} catch (Exception e) {
e.printStackTrace();
}
}
The above code is in the SessionBean.
Plz help

You are passing relative
URLs to method JasperCompileManager.compileReportToFile.
This method expects filenames as parameters, not URLs.
The solution suggested in other internet forums is:
JasperCompileManager.compileReportToFile(
getServletContext().getRealPath(xmlFile),
getServletContext().getRealPath(compiledFile));

Related

Downloading file from storage folder not working

I'm trying to download pdf file from public folder in my lumen 8 application. The exact file path is public/assets/attachments/resume.pdf. My code is
public function downloadResume()
{
return response()->download('public/assets/attachments/resume.pdf');
}
as per suggested here.
However the code is throwing following error:
What's the proper way to downloding the file ?

Tesseract couldn't load any languages! java.lang.Error: Invalid memory access

I have upgraded the tess4j libraries from 3.4.8 to 4.3.0. Since then I am getting the below error :
"Error opening data file .src/img/tessdata/eng.traineddata
Please make sure the TESSDATA_PREFIX environment variable is set to your "tessdata" directory.
Failed loading language 'eng'
Tesseract couldn't load any languages!
java.lang.Error: Invalid memory access
I have already set the environment variable and provided the path to the tessdata directory.
String processImage(String imageFileName){
File imageFile = new File(getImagePath()+imageFileName)
Tesseract process = new Tesseract()
process.setDatapath(".src/img/tessdata");
//process and extract
try {
String outputText = process.doOCR(imageFile)
//System.out.println("\n"+outputText)
return outputText
} catch (TesseractException e) {
return imageFile.toString()+" Unable to process image file"
}
}
How can this error be resolved. I have followed many solutions already in Stackoverflow, none seem to work. Any help on this would be highly appreciated

The driver executable does not exist: C:\geckodriver.exe issue in Eclipse IDE

Please help me with this issue that is recurring every time I run my code.
I have extracted Geckodriver files in C Drive but when I run my code, the error that comes up is 'Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: C:\geckodriver.exe'.
My code is given below:
package Basics;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Browserinvocation {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();//FirefoxDriver class is used to implement methods present in Webdriver-Invocation of browser
driver.get("https://www.amazon.in/");// Get method to hit the url in browser
}
}
Error in console :
Exception in thread "main" java.lang.IllegalStateException: The driver
executable does not exist: C:\geckodriver.exe at
com.google.common.base.Preconditions.checkState(Preconditions.java:534)
at
org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:136)
at
org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:131)
at
org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
at
org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:141)
at
org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
at
org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:158)
at
org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:120)
at
org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:98)
at Basics.Browserinvocation.main(Browserinvocation.java:13)
Above exception occurs whenever Precondition does not find path of relevant driver mentioned in System.setProperty() method by any reason like below:
if path mentioned have different/wrong/single slashes.
Driver file itself is not present at mentioned location.
If path is mentioned in properties file or config file with double quotes.
Just check once before execution.
You should add the path to geckodriver.exe using / rather than \\. Change your line
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
to the following
System.setProperty("webdriver.gecko.driver","C:/geckodriver.exe");
Your code is running at my side, might be you are not extracting the gecko driver.
Change the path and try it once, it should worked
Please let me know selenium jars version and your firefox browser version
System.setProperty("webdriver.gecko.driver", "C:/Users/sankalp.gupta/Desktop/JAVASEL/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://www.amazon.in");
System.out.println(driver.getCurrentUrl());
driver.close();
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
Here remove . in between gecko and driver
Just download geckodriver.exe and move it to drive C:

Share properties file among slaves in domain mode Wildfly10

In domain mode , I am able to use properties file as a module but the problem is if there is any modification in the file then i'l need to do it for all slaves in the domain.
I want to centralize the file so that at one point I can change and it will be reflected on all slaves.
I know in domain.xml we can configure global level system properties but I have around 25 properties files.
So is there a way to centralized the files??
myjar.jar
-->package
--> class
-->properties
-->xml files
myjar.jar is an archived jar file
To fetch the xml files
URL url = Thread.currentThread().getContextClassLoader().getResource("./properties");
File queryFolder = new File(url.getFile());
for (File fileName : queryFolder.listFiles()) // null pointer exception
{
if (fileName.getName().toUpperCase().endsWith("XML"))
{
saxParser.parse(fileName, this);
}
}
This is not working.
Tried this
How do I list the files inside a JAR file?
And facing the same problem given in below link
JBoss wildfly 8.x Provider "vfs" not installed when using java nio Paths
URL w_url = mmyClass.class.getProtectionDomain().getCodeSource().getLocation();
JarEntry w_ze = null;
LOGGER.info("Jar******************" + w_url.toString());
if (w_url.toString().endsWith(".jar"))
{
try (JarInputStream jar = new JarInputStream(w_url.openStream()))
{
while ((w_ze = jar.getNextJarEntry()) != null)
{
LOGGER.info("Name *******" + w_ze.getName());
}
}
catch(Exception e)
{
}
}
Added properties folder inside a war file and fetched the exploded folder path using below code in the servlet of the war file.
config.getServletContext().getRealPath("/");
This gives the vfs path of the folder.
and configured the same in
System.setProperty("REALPATH", config.getServletContext().getRealPath("/"));
and used the same in the jar file.

How to execute JMeter test case from Java code

How do I run a JMeter test case from Java code?
I have followed the example Here from Blazemeter.com
My code is as follows:
public class BasicSampler {
public static void main(String[] argv) throws Exception {
// JMeter Engine
StandardJMeterEngine jmeter = new StandardJMeterEngine();
// Initialize Properties, logging, locale, etc.
JMeterUtils.loadJMeterProperties("/home/stone/Workbench/automated-testing/apache-jmeter-2.11/bin/jmeter.properties");
JMeterUtils.setJMeterHome("/home/stone/Workbench/automated-testing/apache-jmeter-2.11");
JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
JMeterUtils.initLocale();
// Initialize JMeter SaveService
SaveService.loadProperties();
// Load existing .jmx Test Plan
FileInputStream in = new FileInputStream("/home/stone/Workbench/automated-testing/apache-jmeter-2.11/bin/examples/CSVSample.jmx");
HashTree testPlanTree = SaveService.loadTree(in);
in.close();
// Run JMeter Test
jmeter.configure(testPlanTree);
jmeter.run();
}
}
but I keep getting the following messages in the console and my test never executes.
INFO 2014-09-23 12:04:40.492 [jmeter.e] (): Listeners will be started after enabling running version
INFO 2014-09-23 12:04:40.511 [jmeter.e] (): To revert to the earlier behaviour, define jmeterengine.startlistenerslater=false
I have also tried uncommented jmeterengine.startlistenerslater=false from jmeter.properties file
How do you know that your "test never executes"?
What is in jmeter.log file (it should be in the root of your project). Or alternatively comment JMeterUtils.initLogging() line to see the full output in STDOUT
Have you changed relative path CSVSample_user.csv in "Get user details" CSV Data Set Config as it may resolve into a different location as it recommended in Using CSV DATA SET CONFIG
Is CSVSample.jtl file generated anywhere (again it should be in the root of your project by default)? What is in it?
The code looks good and I'm pretty sure that the problem is with the path to CSVSample_user.csv file and you have something like java.io.FileNotFoundException in your log. Please double check that CSVSample.jmx file contains valid full path to CSVSample_user.csv.
UPDATE TO ANSWER QUESTIONS IN COMMENTS
jmeter.log file should be under your Eclipse workspace folder by default
Looking into CSVSample.jmx there is a View Resulst in Table listener which is configured to store results under ~/CSVSample.jtl
If you want to see summarizer messages and "classic" .jtl reporting add next few lines before jmeter.configure(testPlanTree); stanza
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
String logFile = "/path/to/jtl/results/file.jtl";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(logFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);
Try using library - https://github.com/abstracta/jmeter-java-dsl.
It supports implementing JMeter test as java code.
Below example shows how to implement and execute test for REST API. Same approach could be applied to other type of tests as well.
#Test
public void testPerformance() throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
.post("{\"name\": \"test\"}", Type.APPLICATION_JSON)
),
//this is just to log details of each request stats
jtlWriter("test" + Instant.now().toString().replace(":", "-") + ".jtl")
).run();
assertThat(stats.overall().elapsedTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}