How to send outlook mail from java program , without using SMTP - java

Thanks in advance for your help and support.
Using the below code i am able to open my outlook and specifying TO, CC Subject and Mail Body, but i am unable to send the email automatically, Kindly help on this.
package com.emailtrigger;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class sendMail
{
public static void main(String[] args) throws URISyntaxException
{
String subject="Email Testing through Code";
String body="This is testing purpose";
String cc="AAA#abc.com";
try {
Desktop.getDesktop().mail( new URI( "mailto:abc#ddd.com?subject="+subject+"&cc="+cc+"&body="+body) );
}
catch ( IOException ex )
{
}
}
}

If you will print error then it is : Illegal character in opaque part.
You should not provide space between values.Ref
All values should be URL-encoded (e.g. space becomes %20)
How to URL encode
Your code in above scenario -
public static void main(String[] args) throws URISyntaxException {
String subject="Email%20Testing%20through%20Code";
String body="This%20is%20testing%20purpose";
String cc="AAA#abc.com";
try {
Desktop.getDesktop().mail( new URI( "mailto:abc#ddd.com?subject="+subject+"&cc="+cc+"&body="+body) );
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}

Related

Can't parse an HTML element from web page by loop in, after some time parsing in java

I receive different exceptions after some iteration in runtime when I try to parse page and get the same element every 10 seconds.
javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake
Or EOFexception, SocketException, UnknownExceptiin.
In addition I am using maven for project and Jsoup for parsing, and I have last version of JDK (however I don't think it'll help). Here is my code.
package com.download;
import java.io.IOException;
import java.net.URL;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.Jsoup;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Download
{
public static void download() throws IOException,InterruptedException
{
for(int i=0;i<120;i++)
{
System.out.println(Parser.parse());
Thread.sleep(10000);
}
}
}
public class Parser
{
public static String parse( ) throws IOException
{
String data=parseElement();
String time=getDate();
return data+" "+time;
}
private static String parseElement() throws IOException
{
String url = "https://www.example.com/domain-has-changed-here";
Document page = Jsoup.connect(url).timeout(0).get();
return page.getElementById("last_last").text();
}
private static String getDate() throws IOException
{
LocalTime myDateObj = LocalTime.now();
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("HH:mm:ss");
String time = myDateObj.format(myFormatObj);
return time;
}
}
Have any Ideas? Thanks in advance.
This is probably due to the site that detected you as spam, to reduce this risk I recommend you customize your connection depending on the site, here is an example of customization:
Connection connection = Jsoup.connect("https://www.example.com/domain-has-changed-here");
connection.userAgent("Mozilla");
connection.timeout(5000);
connection.cookie("cookiename", "val234");
connection.cookie("cookiename", "val234");
connection.referrer("http://google.com");
connection.header("headersecurity", "xyz123");
Document docCustomConn = connection.get();

How to get a specific Value or Data using the API in Java

Sorry if the question is a bit simple. I am new to this and i am currently trying to fetch some values using a websites API. I will drop a link below. Here is the issue. The code i have is the exact code the website provided. I want to take the "quote" values only from the result sent from them. Here is the code:
import java.net.URI;
import java.io.IOException;
import java.lang.InterruptedException;
import javax.websocket.*;
#ClientEndpoint
public class WSClient {
#OnOpen
public void onOpen(Session session) throws java.io.IOException
{
session.getBasicRemote().sendText("{\"ticks\": \"R_100\"}");
}
#OnMessage
public void onMessage(String message)
{
System.out.println("ticks update: " + message);
}
public static void main(String[] args)
throws IOException, DeploymentException, InterruptedException
{
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
URI apiUri = URI.create("wss://ws.binaryws.com/websockets/v3");
Session session = container.connectToServer(WSClient.class, apiUri);
Thread.sleep(3000);
}
}
And here is the result on my Console in eclipse:
ticks update: {"echo_req":{"ticks":"R_100"},"tick":{"epoch":"1461413058","symbol":"R_100","quote":"37673.45","id":"810945BC-094B-11E6-B438-8E7300DB46A6"},"msg_type":"tick"}
The results works fine but i want to take just the "quote" Value which is a numeric value.
Here is the link to their API Website / Dev Website: https://developers.binary.com/
Thank you in Advance :)
Your response looks like a JSON string you should just do this
#OnMessage
public void onMessage(String message)
JSONObject response = new JSONObject(message);
int quote = Integer.parseInt(response.getString("quote"));
}

Array Index Out of Bounds Exception - RMI DynamicClient

import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RMISecurityManager;
import java.rmi.server.RMIClassLoader;
import java.util.*;
import java.lang.reflect.Constructor;
public class DynamicClient {
public DynamicClient (String[] args) throws Exception {
Properties p = System.getProperties();
String url = p.getProperty("java.rmi.server.codebase");
Class ClasseClient = RMIClassLoader.loadClass(url,"ClientDistant");
Constructor [] C = ClasseClient.getConstructors();
C[0].newInstance( new Object[] {args} );
}
public static void main (String[] args) {
System.setSecurityManager( new RMISecurityManager() );
try {
DynamicClient cli = new DynamicClient(args);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
This code is supposed to dynamically charge the class ClientDistant from a web server and execute the treatment, however it displays an error message:
C:\Users\DELL\Desktop>java -Djava.security.policy=client.policy -Djava.rmi.serv
er.useCodebaseOnly=false -Djava.rmi.server.codebase=http://localhost:8080/RMI/
DynamicClient
java.lang.ArrayIndexOutOfBoundsException: 0
where RMI is a directory's in the java web application named RMI ( I m using GlassFish server).
Any solutions to load ClientDistant and execute its treatment?

MalformedURLException in java application

i wrote a simple program which is in my book.
but i'm getting the MalformedURLException exception.This is my code
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args){
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
but my friend said he got it right with the same code.
what's wr9ong with my code? Is it because of the internet connection(I'm using a dial-up connection)
I
Java uses the concept of checked Exceptions. You need to put this code inside a try/catch block, since it is bound to throw a MalformedURLException. Something like
URL imageLocation = null;
try {
imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
} catch (MalformedURLException mue) {
mue.printStackTrace();
}
Or let the main method throws the Exception like :
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args) throws MalformedURLException {
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
catch the MalformedURLException using try and catch block
try {
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",
JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
Your internet connection would not cause that Exception. (If your URL did not exist, Java would throw an IOException, probably a FileNotFoundException, per URLConnection documentation.) In fact, your code isn't throwing an Exception at all! What you're seeing is a compile error:
$ javac ImageGreet.java
ImageGreet.java:7: error: unreported exception MalformedURLException; must be caught or declared to be thrown
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
^
1 error
When Java tries to turn your program from source code into machine code, it finds a problem, so it stops and asks you to fix it. Your code hasn't run yet -- Java's warning you that there's a problem with your program's source code. (If you're running an IDE, this will show up in a "problems" pane, as opposed to an error message from javac.)
The issue is that you need to catch the MalformedURLException in your code, or declare that main throws MalformedURLException. For example:
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args) throws MalformedURLException {
URL imageLocation=new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
Note that I've added throws MalformedURLException to the end of your main method, which is the latter of the solutions I suggested above. That tells Java that your main method may propagate an Exception of type MalformedURLException.
Since Java has checked exception you have to add throws MalformedURLException to your methods header or you have to write the method logic inside try/catch blocks.

Oozie Java API Kerberos Authentication

I am trying to get an oozie job status using oozie java API. Currently it is failing with the message
Exception in thread "main" HTTP error code: 401 : Unauthorized
We are using a kerberos authentication in our cluster with a keytab file.
Please guide as how to proceed to implement the authentication.
My current program is:
import org.apache.oozie.client.OozieClient;
public class oozieCheck
{
public static void main(String[] args)
{
// get a OozieClient for local Oozie
OozieClient wc = new OozieClient(
"http://myserver:11000/oozie");
System.out.println(wc.getJobInfo(args[1]));
}
}
I figured a way to use kerberos in my java api.
First obtain kerberos tgt.
Then the below code works:
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.oozie.client.AuthOozieClient;
import org.apache.oozie.client.WorkflowJob.Status;
public class Wrapper
{
public static AuthOozieClient wc = null;
public static String OOZIE_SERVER_URL="http://localhost:11000/oozie";
public Wrapper ( String oozieUrlStr ) throws MalformedURLException
{
URL oozieUrl = new URL(oozieUrlStr);
// get a OozieClient for local Oozie
wc = new AuthOozieClient(oozieUrl.toString());
}
public static void main ( String [] args )
{
String lineCommon;
String jobId = args[0]; // The first argument is the oozie jobid
try
{
Wrapper client = new Wrapper(OOZIE_SERVER_URL);
Properties conf = wc.createConfiguration();
if(wc != null)
{
// get status of jobid from CLA
try
{
while (wc.getJobInfo(jobId).getStatus() == Status.RUNNING)
{
logger.info("Workflow job running ...");
logger.info("Workflow job ID:["+jobId+"]");
}
if(wc.getJobInfo(jobId).getStatus() == Status.SUCCEEDED)
{
// print the final status of the workflow job
logger.info("Workflow job completed ...");
logger.info(wc.getJobInfo(jobId));
}
else
{
// print the final status of the workflow job
logger.info("Workflow job Failed ...");
logger.info(wc.getJobInfo(jobId));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
System.exit(9999);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
You have to patch the oozie client if docs do not mention Kerberos.

Categories