My code connects to a gmail account and reads each email received. I retrieve the content of the email message. I use javamail api for that.
When I run the code from eclipse, it works absolutely fine. But if I export everything into a jar file and then run from command prompt, then I get the following error :
java.lang.ClassCastException: com.sun.mail.imap.IMAPInputStream cannot be cast to javax.mail.Multipart
in the following line :
Multipart mp = (Multipart) msg.getContent();
I tried using this but it doesn't help :
public static void main(String[] args) throws Exception {
System.out.println("Begin");
Thread.currentThread().setContextClassLoader(getOldIds.class.getClassLoader());
//read emails
}
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", -1, "username", "password");
//fetch the message from the inbox
Please suggest me what should be done.
Thanks
Add this line to your code :-
MimeMessage mimemsg = new MimeMessage(msg);
Multipart mp = (Multipart) mimemsg.getContent();
instead of :-
Multipart mp = (Multipart) msg.getContent();
Here I am safely assuming that msg if of type com.sun.mail.imap.IMAPMessage
How are you exporting everything into a jar file?
If you're combining all your application classes and all the JavaMail classes from the mail.jar file into a single new jar file, you're missing the resource files from the mail.jar file that configure the mapping from MIME type to Java class.
Your application classes should be in one jar file and that jar file should reference or use the JavaMail jar file, e.g., on the CLASSPATH when the application runs.
Thanks everyone for help...... the approach below worked for me :
BufferedReader br = new BufferedReader( new InputStreamReader(msg.getInputStream()));
content="";
String line;
while((line=br.readLine())!=null){
content = content + line;
}
System.out.println("\n\n" + content);
br.close();
Related
I try to parse PNG file containing scanned text using Apache Tika and Tesseract for Windows.
Though running Tesseract from command line does recognise the text correctly, the content returned by Tika contains line breaks ("\n") only.
This is my code:
ByteArrayInputStream inputstream = new ByteArrayInputStream(document.getFileContent());
byte[] content = document.getFileContent();
Parser parser = new AutoDetectParser();
BodyContentHandler handler = new BodyContentHandler(Integer.MAX_VALUE); //to process long files
Metadata metadata = new Metadata();
ParseContext parseContext = new ParseContext();
TesseractOCRConfig config = new TesseractOCRConfig();
config.setTesseractPath("C:\\Program Files (x86)\\Tesseract-OCR");
config.setTessdataPath("C:\\Program Files (x86)\\Tesseract-OCR\\tessdata");
config.setMaxFileSizeToOcr(Integer.MAX_VALUE);
parseContext.set(TesseractOCRConfig.class, config);
parseContext.set(Parser.class, parser);
parser.parse(inputstream, handler, metadata, parseContext);
String contentString = handler.toString();
System.out.println(contentString);
I tried to debug and found that TesseractOCRParser.doOcr() should run a process executing command like that:
tesseract C:\Users\admin\AppData\Local\Temp\apache-tika-6655676641285964446.tmp C:\Users\admin\AppData\Local\Temp\apache-tika-2151149415666715558.tmp -l eng -psm 1 txt
However, it looks like the process does not run. If I run the same command from another session, the recognised content comes.
I have found that the problem was in this line:
config.setTessdataPath("C:\\Program Files (x86)\\Tesseract-OCR\\tessdata");
This line should be omitted and the parser will find the right path.
I am writing a application that will run inside JBoss EAP 6.3.1 on a CentOS 6.5
During this application i have to save a file to the disk and when restarting the application i have to read it back into the application.
All this is working.
The problem is that i want to save to file in the working directory of the application.
What is happening right now is that the file: foo.bar will be saved at the location where i run the standalone.sh (or .bat on Windows).
public void saveToFile() throws IOException {
String foo = "bar";
Writer out = new OutputStreamWriter(new FileOutputStream("/foo.bar"), "UTF-8");
try {
out.write(foo);
} finally {
out.close();
}
}
You could try to use an absolute path to save your file:
String yourSystemPath = System.getProperty("jboss.home.url") /*OPTIONAL*/ + "/want/to/save/here";
File fileToSave = new File(yourSystemPath,"foo.bar");
Writer out = new OutputStreamWriter(new FileOutputStream(fileToSave), "UTF-8");
Basically here, I'm creating a File object using a yourSystemPath variable where I stored the path to save the file in, then I'm creating the new FileOutputStream(fileToSave) using the previously created object File
Please ensure that your JBoss server has write permissions for yourSystemPath
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));
}
I've created a JKS file with public and private RSA keys. When I load this file using external path (like c:/file.jks), the program executes like a charm. However, if I try load this same file from classpath, I got this exception:
java.io.IOException: Invalid keystore format
This is the code used to load the jks:
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream stream=this.getClass().getResourceAsStream("/lutum.jks") ;
keyStore.load(stream,passe);
the only difference is that I use FileInputStream with full path when loading externally.
What I'm doing wrong?
In general your solution should work, provisionally.
What are those provisions? Make sure that your resource folder is in your classpath. If you aren't sure, add it to the -cp flag passed to java when executing your program, or if you are using Eclipse or some other IDE, make sure it is listed as a member of the classpath for that project.
Next, check out this stackoverflow that relates to your question. While the way you are using the class's getResourceAsStream() method is valid (including the / at the start of the filename causes the class resource loader to defer to the ClassLoader's method) it is perhaps less confusing to use the ClassLoader directly. Another good example is found here.
So, first, check that your resources folder is explicitly part of the classpath. Second, prefer the following construction for finding the resource:
InputStream stream= this.class.getClassLoader().getResourceAsStream("lutum.jks");
Note the missing / from the filename. This is because the ClassLoader will automatically start searching at "project root", and the slash will likely just cause issues (if you deploy to JBoss or Tomcat, for instance, that will probably get interpreted by the classloader as an absolute file system path instead of a relative path).
I hope this helps. If not, comment me with more details on your project and I'll alter my answer accordingly.
I suspect that the two keystores are in fact not the same, and that the keystore on the classpath are somehow corrupt.
Try comparing the two keystores. Just read the files into a byte array with something like this:
public static byte[] streamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
int b = is.read();
while (b > -1) {
tmp.write(b);
b = is.read();
}
tmp.flush();
return tmp.toByteArray();
}
And then compare them like this:
InputStream cpStream = this.getClass().getResourceAsStream("/lutum.jks");
InputStream fileStream = new FileInputStream("c:/file.jks");
byte[] cpBytes = streamToByteArray(cpStream);
byte[] fileBytes = streamToByteArray(fileStream);
if (Arrays.equals(cpBytes, fileBytes)) {
System.out.println("They are the same.");
} else {
System.out.println("They are NOT the same.");
// print the file content ...
}
I'm using this code to return a FileContentResult with an MSI file for the user to download in my ASP.NET MVC controller:
using (StreamReader reader = new StreamReader(#"c:\WixTest.msi"))
{
Byte[] bytes = Encoding.ASCII.GetBytes(reader.ReadToEnd());
return File(bytes, "text/plain", "download.msi");
}
I can download the file, but when I try to run the installer I get an error message saying:
This installation package could not be
opened. Contact the application vendor
to verify that this is a valid Windows
Installer package.
I know the problem isn't C:\WixTest.msi, because it runs just fine if I use the local copy. I don't think I'm using the wrong MIME type, because I can get something similar with just using File.Copy and returning the copied file via a FilePathResult (without using a StreamReader) that does run properly after download.
I need to use the FileContentResult, however, so that I can delete the copy of the file that I'm making (which I can do once I've loaded it into memory).
I'm thinking I'm invalidating the install package by copying or encoding the file. Is there a way to read an MSI file into memory, and to return it via a FileContentResult without corrupting the install package?
Solution:
using (FileStream stream = new FileStream(#"c:\WixTest.msi", FileMode.Open))
{
BinaryReader reader = new BinaryReader(stream);
Byte[] bytes = reader.ReadBytes(Convert.ToInt32(stream.Length));
return File(bytes, "application/msi", "download.msi");
}
Try using binary encoding and content-type application/msi instead of text/plain - it's not ASCII or text content so you're mangling the file.