I am using JavaMail and smtp (gmail), here's my code :
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email {
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public static void main(String args[]) throws AddressException,
MessagingException {
Email javaEmail = new Email();
javaEmail.setMailServerProperties();
javaEmail.createEmailMessage();
javaEmail.sendEmail();
}
public void setMailServerProperties() {
String emailPort = "587";//gmail's smtp port
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", "true");
emailProperties.put("mail.smtp.starttls.enable", "true");
}
public void createEmailMessage() throws AddressException,
MessagingException {
String[] toEmails = { "to#gmail.com" };
String emailSubject = "Java Email";
String emailBody = "This is an email sent by JavaMail api.";
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
for (int i = 0; i < toEmails.length; i++) {
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");//for a html email
//emailMessage.setText(emailBody);// for a text email
}
public void sendEmail() throws AddressException, MessagingException {
String emailHost = "smtp.gmail.com";
String fromUser = "yourusername";//just the id alone without #gmail.com
String fromUserEmailPassword = "your_password";
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserEmailPassword);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
System.out.println("Email sent successfully.");
}
}
Error Message :
Exception in thread "main" javax.mail.MessagingException: 530 5.7.0
Must issue a STARTTLS command first. n80sm23847952pfi.25 - gsmtp
at
com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1020)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:716)
at
com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:388)
at com.mail.Email.sendEmail(Email.java:68) at
com.mail.Email.main(Email.java:26)
Could you try changing this line:
Transport t = session.getTransport("smtps");
You'll have to supply the appropriate username and password needed by
your mail server. Note that you can change the protocol to "smtps" to
make a secure connection over SSL.
The complete information here: http://www.oracle.com/technetwork/java/javamail/faq/index.html#gmail
In my case, the above issue occured when I use ibm-was-*.jar. And it got resolve when I switch the jar to Javax.mail-version.jar (version is a number like 1.5.5).
Related
We have aes-256 encryption for some data in one of the tables and we are migrating this to sql server. The problem is that we cannot decrypt the data in sql server due to incompatibility. Is there any way we can encrypt data in MYSQL in a way which is compatible with sql server aswell. Any advise ?
if you know the secretkey then you can decrypt the data see following code for encryption and decryption of AES-256 . the code is written in JAVA
check this link AES-256 Password Based Encryption/Decryption in Java
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes;
private static SecretKey secretKey;
public static void main(String []args) throws Exception {
salt = getSalt();
char[] message = "PasswordToEncrypt".toCharArray();
System.out.println("Message: " + String.valueOf(message));
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
System.out.println(encryptedText);
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return new String(salt);
}
}
I have to start Jenkins parameterized build programmatically using Jersey REST API and the values for the parameters must be provided as a JSON object. Any hint or example is welcome.
So, seems like you have not tried it yourself. I can give you a fast 5 minute solution, that should be reworked to be clear and not so ugly, but it works :)
import java.util.ArrayList;
import java.util.List;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JenkinsJob {
public static void main(String[] args) {
runParamJob("http://jenkins.host/", "SOME_JOB", "{\"object\":\"test\"}");
}
public static String runParamJob(String url, String jobName, String paramsJSON) {
String USERNAME = "user";
String PASSWORD = "pass";
Client client = Client.create();
client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(USERNAME, PASSWORD));
WebResource webResource = client.resource(url + jobName + "/buildWithParameters?PARAMETER=" + paramsJSON);
ClientResponse response = webResource.type("application/json").get(ClientResponse.class, paramsJSON);
String jsonResponse = response.getEntity(String.class);
client.destroy();
System.out.println("Server response:" + jsonResponse);
return jsonResponse;
}
}
In order to use rest API for parameterized build you should use POST and not get according to Jenkins wiki. Here is an example. Make sure that the json you send is as instructed at the documentation.
take this json for example:
{"parameter": [{"name":"id", "value":"123"}, {"name":"verbosity", "value":"high"}]}
You have two parameters with name and value for each. If I will use what was written at the former answer by #stanjer the json should look like that:
{"parameter": [{"name":"object", "value":"test"}]}
In addition there is a good discussion about it here
I would not recommend to use USER:PASSWORD but use token that could be configured in Jenkins job UI. Here is a class that implements builder pattern for with/without parameters.
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class JenkinsTrigger {
private String host;
private String jenkinsToken;
private String jobParams;
private MultivaluedMap<String,String> queryParams = new MultivaluedMapImpl();
private Client client = Client.create();
private WebResource webResource;
private JenkinsTrigger(JenkinsTriggerBuilder jenkinsTriggerBuilder){
this.host = jenkinsTriggerBuilder.host;
this.jenkinsToken = jenkinsTriggerBuilder.jenkinsToken;
this.jobParams = getJobParams(jenkinsTriggerBuilder.jobParams);
webResource = client.resource(this.host);
queryParams.add("token", jenkinsToken);
}
public void trigger(){
ClientResponse response = webResource.path(this.host).queryParams(queryParams)
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.header("Content-type", "application/x-www-form-urlencoded")
.post(ClientResponse.class, jobParams);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.toString());
} else {
System.out.println("Job Trigger: " + host);
}
}
private String getJobParams(Map<String,String> jobParams){
StringBuilder sb = new StringBuilder();
sb.append("json={\"parameter\":[");
jobParams.keySet().forEach(param -> {
sb.append("{\"name\":\""+param+"\",");
sb.append("\"value\":\""+ jobParams.get(param) + "\"},");
});
sb.setLength(sb.length() - 1);
sb.append("]}");
System.out.println("Job Parameters:" + sb.toString());
return sb.toString();
}
public static class JenkinsTriggerBuilder {
private String host;
private String jenkinsToken;
private Map<String,String> jobParams = null;
public JenkinsTriggerBuilder(String host, String jenkinsToken){
this.host = host;
this.jenkinsToken = jenkinsToken;
}
public JenkinsTriggerBuilder jobParams(Map<String,String> jobParams){
this.jobParams = jobParams;
return this;
}
public JenkinsTrigger build(){
return new JenkinsTrigger(this);
}
}
}
And here is usage sample:
Map<String, String> params = new HashMap<>();
params.put("ENV", "DEV103");
JenkinsTrigger trigger = new JenkinsTriggerBuilder("https://JENKINS_HOST/job/JOB_NAME/buildWithParameters","JOB_TOKEN").jobParams(params).build();
trigger.trigger();
best of luck
this is my code mention in that box.so please check this code and give me right answer.this code is totally run in my system and run successfully and show build successful but message does not send in mail ids.so please help me.
Thanks in advance
this is my code.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Main1
{
String d_email = "xyz#ibm.com",
d_password = "*******",
d_host = "blr-outlook.ibm.com",
d_port = "25",
m_to = "xyz#ibm.com",
m_subject = "Testing",
m_text = "Hey, this is the testing email using blr-outlook.ibm.com";
public static void main(String[] args)
{
String[] to={"xyz#ibm.com"};
String[] cc={"xyz#ibm.com"};
String[] bcc={"xyz#ibm.com"};
//This is for google
Main1.sendMail("xyz#ibm.com", "password", "blr-outlook.ibm.com",
"25", "true", "true",
true, "javax.net.ssl.SSLSocketFactory", "false",
to, cc, bcc,
"hi baba don't send virus mails..",
"This is my style...of reply..If u send virus mails..");
}
public synchronized static boolean sendMail(
String userName, String passWord, String host,
String port, String starttls, String auth,
boolean debug, String socketFactoryClass, String fallback,
String[] to, String[] cc, String[] bcc,
String subject, String text)
{
Properties props = new Properties();
//Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port)) {
props.put("mail.smtp.port", port);
}
if(!"".equals(starttls)) {
props.put("mail.smtp.starttls.enable",starttls);
}
props.put("mail.smtp.auth", auth);
if(debug) {
props.put("mail.smtp.debug", "true");
} else {
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port)) {
props.put("mail.smtp.socketFactory.port", port);
}
if(!"".equals(socketFactoryClass)) {
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
}
if(!"".equals(fallback)) {
props.put("mail.smtp.socketFactory.fallback", fallback);
}
try
{
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress("blr-outlook.ibm.com"));
for(int i=0;i<to.length;i++) {
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++) {
msg.addRecipient(Message.RecipientType.CC,
new InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++) {
msg.addRecipient(Message.RecipientType.BCC,
new InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
return false;
}
}
}
There are so many examples available in the net...even tutorialspoint have well explained examples....check it out here.....
http://www.tutorialspoint.com/javamail_api/javamail_api_overview.htm
i have used java mail api for mailing purposes and it works good enough.....i am away from home so i can't share the code with you now....
Edit:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailTLS {
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
try this....authentication is not mandatory....and if you are using any kinda app you need to change your gmail account setting to allow access for less secured apps....
Basically I have 2 bits of code one will do a ping sweep of a network range and then one will retrieve a MAC address from a given IP.
What I would like to do is incorporate these two pieces of code so when the ping sweep is performed it shows the MAC address in the output next to the IP addresses.
The MAC address retrieval code is as follows...
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test118;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Test118 {
public static String command;
public String ip = "192.168.0.4";
Test118() {
command = "arp -a " + ip;
}
public void viewMac() {
String process = null;
String mac[] = new String[5];
String rmac[] = new String[10];
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
int i = 0;
while ((line = bufferedreader.readLine()) != null) {
mac[i] = line;
i++;
}
rmac = mac[3].split(" ");
System.out.println(rmac[2]);
} catch (Exception e) {
System.out.println("mac cant find");
}
}
public static void main(String[] args) throws Exception {
Test118 r = new Test118();
r.viewMac();
}
}
The ping sweep is as follows...
package pingstestnew;
import java.io.IOException;
import java.net.InetAddress;
public class NetworkPing {
public static void main(String[] args) throws IOException {
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 142; i <= 145; i++)
{
ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(1000))
{
System.out.println(address + " Host is reachable");
}
else if (!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " Hostname Resolved, Host is reachable");
}
else
{
System.out.println(address + " Host Unreachable");
}
}
}
}
I am creating a SSL Server and Client in Java. The point of the program is to mimic a movie theater program. I can establish the connection but when I attempt to "reserve" a seat the program crashes. I get the following error:
Server aborted: javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
This is my Server Code
// SSL Server
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
public class SSL_Server {
public static void main(String[] args) {
int port = 2018;
System.setProperty("javax.net.ssl.keyStore","mySrvKeystore");
System.setProperty("javax.net.ssl.keyStorePassword","123456");
ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
ServerSocket ssocket = null;
System.out.println("SSL_Server started");
final ExecutorService threadPool = Executors.newCachedThreadPool();
try {
ssocket = ssocketFactory.createServerSocket(port);
InetAddress myIP =InetAddress.getLocalHost();
System.out.println(myIP.getHostAddress());
while(true){
Socket aClient = ssocket.accept();
//create a new thread for every client
threadPool.submit(new SSL_ClientHandler(aClient));
}
}
catch(Exception e) {
System.err.println("Server aborted:" + e);
} finally {
try{
ssocket.close();
} catch (Exception e){
System.err.println("could not close connection properly" + e);
}
}
System.out.println("connection was closed successfully");
}
}
The following is my client code
//SSL Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
public class TCP_Client {
public static void main(String[] args) throws IOException{
// SSL_Client newClient = new SSL_Client();
// Lock lock = new ReentrantLock();
boolean validInput = false;
BufferedReader din;
PrintStream pout;
int port = 2018;
BufferedReader stdinp = new BufferedReader(new InputStreamReader(System.in));
String line = "done";
StringTokenizer st;
String hostname;
String task = "done";
if(args.length>0)
hostname = args[0];
else
hostname = "localhost";
SocketFactory socketFactory = SSLSocketFactory.getDefault();
//Socket socket = socketFactory.createSocket(hostname, port);
while(true)
{
try{
//read input
while(!validInput)
{
System.out.println("Please enter a valid command or 'done' to finish.");
line = stdinp.readLine();
st = new StringTokenizer(line);
task = st.nextToken();
if(task.equals("reserve") || task.equals("search") || task.equals("delete") || task.equals("getinfo") || task.equals("done"))
{
validInput =true;
break;
}
System.out.println("Invalid command. Please enter another command or 'done' to escape.");
}
if(task.equals("done"))
{
break;
}
validInput = false;//reset for next line read in
//create a new socket every time
//Socket socket = new Socket(hostname, port);
Socket socket = socketFactory.createSocket(hostname, port);
din = new BufferedReader (new InputStreamReader (socket.getInputStream()));
pout = new PrintStream (socket.getOutputStream());
pout.println(line);
pout.flush();
//print out response from server
System.out.println(din.readLine());
} catch (Exception e){
System.err.println("Server aborted: " + e);
}
}
}
}
"Unable to find valid certification path to requested target" means that your truststore doesn't trust the server certificate. Import it into your truststore, or have it signed by a recognized CA.