Java Simple Email Program in Eclipse - java

I want to make a simple program where you can send email from the Command Line. I found this tutorial, ' http://www.tutorialspoint.com/java/java_sending_email.htm ', however the downloads don't. So where can I get JavaMail API and Java Activation Framework (JAF) and how would i put it in my class path.
Basically Im looking for someone to break it down and show me how I could make an email program.
Im using Eclipse luna.

Do have a look at this example. This example, simply sends one attachment as a mail. The contents of attachment quiz.txt are as follows:
What is the Capital of India?/New Delhi
Where is the Taj Mahal?/Agra
Here is the SendMailExample.java file:
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class SendMailExample {
private String from;
private String to;
private String subject;
private String messageBody;
private String fileName;
private String host;
private Properties properties;
private MimeMessage message;
private BodyPart messageBodyPart;
private Multipart multipart;
private Authenticator authenticator;
public SendMailExample () {
from = "sender#gmail.com";
to = "recipient#gmail.com";
subject = "Subject Testing";
messageBody = "<html><body><h1>HAVE FAITH, AND STAY" +
" CALM :-) I AM WITH YOU, OKAY :-)</h1></body></html>";
fileName = "quiz.txt";
host = "smtp.gmail.com";
authenticator = new SMTPAuthenticator ();
properties = System.getProperties ();
properties.put ( "mail.smtp.host", host );
properties.put ( "mail.smtp.starttls.enable", "true" );
properties.put ( "mail.smtp.port", "587" );
properties.put ( "mail.smtp.auth", "true" );
}
private void sendMail ( String from, String to,
String subject, String messageBody, String fileName ) {
try {
Session session = Session.getDefaultInstance ( properties, authenticator );
message = new MimeMessage ( session );
message.setFrom ( new InternetAddress ( from ) );
message.addRecipient ( Message.RecipientType.TO,
new InternetAddress ( to ) );
message.setSubject ( subject );
multipart = new MimeMultipart ();
messageBodyPart = new MimeBodyPart ();
messageBodyPart.setContent ( messageBody, "text/html" );
multipart.addBodyPart ( messageBodyPart );
messageBodyPart = new MimeBodyPart ();
DataSource source = new FileDataSource ( fileName );
messageBodyPart.setDataHandler ( new DataHandler ( source ) );
messageBodyPart.setFileName ( fileName );
multipart.addBodyPart ( messageBodyPart );
message.setContent ( multipart );
Transport.send ( message );
System.out.println ( "Message send successfully...." );
} catch ( Exception me ) {
me.printStackTrace ();
}
}
private void performTask () {
sendMail ( from, to, subject, messageBody, fileName );
}
public static void main ( String[] args ) {
new SendMailExample ().performTask ();
}
}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
class SMTPAuthenticator extends Authenticator {
private static final String SMTP_AUTH_USER = "example#gmail.com";
private static final String SMTP_AUTH_PASSWORD = "somepassword";
public PasswordAuthentication getPasswordAuthentication () {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PASSWORD;
return new PasswordAuthentication( username, password );
}
}
You simply needed this mail.jar file.
To compile, simply write ( mail.jar is present at C:\install\java\mail\mail.jar` location ):
javac -classpath .;C:\install\java\mail\mail.jar SendMailExample.java
To run, write:
java -classpath .;C:\install\java\mail\mail.jar SendMailExample
THis will do :-)

Take a look at this library Commons Email it will simplify your task

Related

Can't populate components field in JIRA using ComponentRestClient in Java

I've been trying different ways to populate components field while creating JIRA using JiraRestClient in java and somehow not able to do that.
Following is one of the approaches I tried -
public String createIssue(String projectKey, Long issueType, String issueSummary, String description) throws URISyntaxException {
IssueRestClient issueClient = restClient.getIssueClient();
ComponentRestClient componentClient = restClient.getComponentClient();
String componentUrl = "https://jira.abc.com/issues/?jql=project+%3D+PROJECTKEY+AND+component+%3D+%22Comp+Name%22";
Component component = componentClient.getComponent(new URI(componentUrl.trim())).claim();
//BasicComponent bc = new BasicComponent();
IssueInput newIssue = new IssueInputBuilder(projectKey, issueType, issueSummary)
.setDescription(description).setComponents(component).build();
return issueClient.createIssue(newIssue).claim().getKey();
}
With this I get error while JSON parsing step -
at org.codehaus.jettison.json.JSONTokener.syntaxError(JSONTokener.java:439) ~[jettison-1.1.jar:1.1]
at org.codehaus.jettison.json.JSONObject.<init>(JSONObject.java:169) ~[jettison-1.1.jar:1.1]
at org.codehaus.jettison.json.JSONObject.<init>(JSONObject.java:266) ~[jettison-1.1.jar:1.1]
at com.atlassian.jira.rest.client.internal.async.AbstractAsynchronousRestClient$1.handle(AbstractAsynchronousRestClient.java:147) ~[jira-rest-java-client-core-4.0.0.jar:?]
at com.atlassian.jira.rest.client.internal.async.AbstractAsynchronousRestClient$3.apply(AbstractAsynchronousRestClient.java:189) ~[jira-rest-java-client-core-4.0.0.jar:?]
at com.atlassian.jira.rest.client.internal.async.AbstractAsynchronousRestClient$3.apply(AbstractAsynchronousRestClient.java:185) ~[jira-rest-java-client-core-4.0.0.jar:?]
at com.atlassian.httpclient.api.ResponsePromiseMapFunction.apply(ResponsePromiseMapFunction.java:81) ~[atlassian-httpclient-api-0.23.0.jar:?]
at com.atlassian.httpclient.api.ResponsePromiseMapFunction.apply(ResponsePromiseMapFunction.java:11) ~[atlassian-httpclient-api-0.23.0.jar:?]
at com.atlassian.util.concurrent.Promises$Of$3.apply(Promises.java:268) ~[atlassian-util-concurrent-2.4.2.jar:?]
at com.atlassian.util.concurrent.Promises$2.onSuccess(Promises.java:158) ~[atlassian-util-concurrent-2.4.2.jar:?]
at com.google.common.util.concurrent.Futures$4.run(Futures.java:1132) ~[guava-20.0.jar:?]
at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:435) ~[guava-20.0.jar:?]
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:900) ~[guava-20.0.jar:?]
Any help or suggestions will be highly appreciated!
This should work:
IssueInputBuilder builder = new IssueInputBuilder( projectKey, issueType, issueSummary );
Iterable<BasicComponent> components = restClient
.getProject( projectKey )
.getComponents( );
for ( BasicComponent c : components ) {
if ( c.getName().equals( "your component name" ) ) {
builder.setComponents( c ); // assuming you want only one component
}
}
IssueInput newIssue = builder.setDescription(description).build(); // etc...

Neo4j - java Authentication failure

I'm a beginner for Java and neo4j.
Trying my first connection to neo4j using Java Application. I'm unable to understand why I am getting Error:
Exception in thread "main" org.neo4j.driver.v1.exceptions.AuthenticationException: The client is unauthorized due to authentication failure.
Bolt : bolt://localhost:7687 (neo4j Desktop on my macbook)
GraphName : PrakashTest1
Password : 12345678
Java Application:
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
public class HelloWorldExample implements AutoCloseable {
private final Driver driver;
public HelloWorldExample( String uri, String user, String password )
{
driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
}
#Override
public void close() throws Exception
{
driver.close();
}
public void printGreeting( final String message ) {
try ( Session session = driver.session() )
{
String greeting = session.writeTransaction( new TransactionWork<String>()
{
#Override
public String execute( Transaction tx )
{
StatementResult result = tx.run( "CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
parameters( "message", message ) );
return result.single().get( 0 ).asString();
}
} );
System.out.println( greeting );
}
}
public static void main( String... args ) throws Exception
{
try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "PrakashTest1", "12345678" ) )
{
greeter.printGreeting( "hello, world" );
}
}
}

How to run dql search query in java?

I want to check whether a file is present in a particular folder in documentum using Java.
Following is my code,
import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.DfQuery;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfFolder;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.IDfLoginInfo;
import com.documentum.operations.IDfDeleteOperation;
public class CountFiles {
// Documentum target repository where the files will be imported
private static final String REPO_NAME = "rep";
public static void main( String[] args ) throws Exception {
try {
String username = "user";
String password = "pwd";
System.out.println( "Starting to connect ..." );
IDfSessionManager sessMgr = createSessionManager( );
addIdentity( sessMgr, username, password);
IDfSession sess = sessMgr.getSession(REPO_NAME );
System.out.println( "Successfully connected to the server.");
queryDocumentum(sess);
} catch( Exception ex ) {
System.out.println( ex );
ex.printStackTrace( );
}
}
private static void queryDocumentum(IDfSession sess) throws DfException {
IDfQuery query = new DfQuery();
String queryStr= "select count(*) from dm_document WHERE FOLDER ('/XXX/YYY',DESCEND) search document contains 'abc.pdf' ";
query.setDQL(queryStr);
IDfCollection coll = query.execute(sess,IDfQuery.DF_EXEC_QUERY);
while(coll.next())
{
System.out.println("Result of method: " + coll.getValueAt(0));
}
coll.close();
}
/**
* Creates a new session manager instance. The session manager does not have
* any identities associated with it.
*
* #return a new session manager object.
* #throws DfException
*/
private static IDfSessionManager createSessionManager( )
throws Exception {
IDfClientX clientX = new DfClientX( );
IDfClient localClient = clientX.getLocalClient( );
IDfSessionManager sessMgr = localClient.newSessionManager( );
System.out.println( "Created session manager." );
return sessMgr;
}
/**
* Adds a new identity to the session manager.
*
*/
private static void addIdentity( final IDfSessionManager sm,
final String username, final String password )
throws Exception {
IDfClientX clientX = new DfClientX( );
IDfLoginInfo li = clientX.getLoginInfo( );
li.setUser( username );
li.setPassword( password );
// check if session manager already has an identity.
// if yes, remove it.
if( sm.hasIdentity( REPO_NAME ) ) {
sm.clearIdentity( REPO_NAME );
System.out.println( "Cleared identity on :" + REPO_NAME );
}
sm.setIdentity( REPO_NAME, li );
System.out.println( "Set up identity for the user." );
}
}
I am getting the following exception - [DM_QUERY_E_SYNTAX]error: "A Parser Error (syntax error) has occurred in the vicinity of "select count(*) from dm_document WHERE FOLDER ('/XXX/YYY',DESCEND) search document contains 'abc.pdf'". what is the issue in the query/code?
Well, obviously your DQL query is wrong:
select count(*) from dm_document WHERE FOLDER ('/XXX/YYY',DESCEND) search document contains 'abc.pdf'
if you just want to check if some document named 'abc.pdf' is present in path /XXX/YYY and all folders below (keyword 'descend') then the DQL should be more like this, you don't need Full Text search capabilities for that:
select count(*) from dm_document where folder('/XXX/YYY', DESCEND) and object_name = 'abc.pdf'
If you don't know exact file name you can use "LIKE", for example:
select count(*) from dm_document where folder('/XXX/YYY', DESCEND) and object_name LIKE '%abc.pdf'

How to multithread in Grizzly

I'm implementing a Java RESTful webservice on Heroku. Currently my entry point looks like
public class Main
{
public static final String BASE_URI = getBaseURI();
public static void main( String[] args ) throws Exception
{
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put( "com.sun.jersey.config.property.packages", "services.contracts" );
initParams.put( "com.sun.jersey.api.json.POJOMappingFeature", "true" );
System.out.println( "Starting grizzly..." );
SelectorThread threadSelector =
GrizzlyWebContainerFactory.create( BASE_URI, initParams );
System.out.println( String.format( "Jersey started with WADL available at %sapplication.wadl.", BASE_URI,
BASE_URI ) );
}
private static String getBaseURI()
{
return "http://localhost:" + ( System.getenv( "PORT" ) != null ? System.getenv( "PORT" ) : "9998" ) + "/";
}
}
where the initParms contains RESTful services being hosted. I understand that GrizzlyWebContainerFactory.create() returns an instance of ServletContainer (SelectorThread), but how would I multithread the returned threadSelector such that multiple SelectorThread's can handle the incoming requests under one process (aka web dyno)? The reason is to increase performance of a single dyno in handling requests.
Any suggestions appreciated! Thanks!
You can call:
SelectorThread.setSelectorReadThreadsCount(int)

How do I determine whether a path is a local file or not

Given just a location as a string, is there a reliable way to determine if this is a local file (such as /mnt/sdcard/test.jpg) or a remote resource (such as http://www.xyz.com/test.jpg)?
Converting it to a Uri with Uri.parse doesn't seem to give me anything to indicate where the file is.
I don't really want to have to look for // in the string!
You can also check with the android.webkit.URLUtil class
URLUtil.isFileUrl(file) || URLUtil.isContentUrl(file)
or any other member function of the aforementioned class. Preceding it with validation is advised:
URLUtil.isValidUrl(file)
uri format is
<protocol>://<server:port>/<path>
local files have:
file:///mnt/...
or just
/mnt
so if string starts with
\w+?://
and this is not file:// then this is url
I also had the same problem and tried to use Penkov Vladimir solution but it didn't work because the Uri had the schema of 'content' which is also not a remote resource.
I used the following code and it worked great.
List<Uri> urls = new ArrayList<>();
List<Uri> locals = new ArrayList<>();
for (Uri uri : uris) {
if (uri.getScheme() != null && (uri.getScheme().equals("content") || uri.getScheme().equals("file"))) {
locals.add(uri);
} else {
urls.add(uri);
}
}
To avoid hard-coding:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main( String args[] ) throws Exception {
final String[] inputs = {
"/tmp/file.txt",
"http://www.stackoverflow.com",
"file:///~/calendar",
"mailto:java-net#java.sun.com",
"urn:isbn:096139210x",
"gopher://host.com:70/path",
"wais://host.com:210/path",
"news:newsgroup",
"nntp://host.com:119/newsgroup",
"finger://user#host.com/",
"ftp://user:password#host.com:2121/",
"telnet://user:password#host.com",
"//localhost/index.html"
};
for( final String input : inputs ) {
System.out.println( "---------------------------------------------" );
final String protocol = getProtocol( input );
System.out.println( "protocol: " + protocol );
if( "file".equalsIgnoreCase( protocol ) ) {
System.out.println( "file : " + input );
}
else {
System.out.println( "not file: " + input );
}
}
}
/**
* Returns the protocol for a given URI or filename.
*
* #param source Determine the protocol for this URI or filename.
*
* #return The protocol for the given source.
*/
private static String getProtocol( final String source ) {
assert source != null;
String protocol = null;
try {
final URI uri = new URI( source );
if( uri.isAbsolute() ) {
protocol = uri.getScheme();
}
else {
final URL url = new URL( source );
protocol = url.getProtocol();
}
} catch( final Exception e ) {
// Could be HTTP, HTTPS?
if( source.startsWith( "//" ) ) {
throw new IllegalArgumentException( "Relative context: " + source );
}
else {
final File file = new File( source );
protocol = getProtocol( file );
}
}
return protocol;
}
/**
* Returns the protocol for a given file.
*
* #param file Determine the protocol for this file.
*
* #return The protocol for the given file.
*/
private static String getProtocol( final File file ) {
String result;
try {
result = file.toURI().toURL().getProtocol();
} catch( Exception e ) {
result = "unknown";
}
return result;
}
}
Output:
---------------------------------------------
protocol: file
file : /tmp/file.txt
---------------------------------------------
protocol: http
not file: http://www.stackoverflow.com
---------------------------------------------
protocol: file
file : file:///~/calendar
---------------------------------------------
protocol: mailto
not file: mailto:java-net#java.sun.com
---------------------------------------------
protocol: urn
not file: urn:isbn:096139210x
---------------------------------------------
protocol: gopher
not file: gopher://host.com:70/path
---------------------------------------------
protocol: wais
not file: wais://host.com:210/path
---------------------------------------------
protocol: news
not file: news:newsgroup
---------------------------------------------
protocol: nntp
not file: nntp://host.com:119/newsgroup
---------------------------------------------
protocol: finger
not file: finger://user#host.com/
---------------------------------------------
protocol: ftp
not file: ftp://user:password#host.com:2121/
---------------------------------------------
protocol: telnet
not file: telnet://user:password#host.com
---------------------------------------------
Exception in thread "main" java.lang.IllegalArgumentException: Relative context: //localhost/index.html
at Test.getProtocol(Test.java:67)
at Test.main(Test.java:30)
Fo checking if it's a local file you can simply do this:
public static boolean isLocalFile(String path) {
return new File(path).exists();
}
To check if it's a url Cameron Ketcham's answer is the best one.
Based on the answer by Penkov Vladimir, this is the exact Java code I used:
String path = "http://example.com/something.pdf";
if (path.matches("(?!file\\b)\\w+?:\\/\\/.*")) {
// Not a local file
}
See it live with RegExr

Categories