All Things Techie With Huge, Unstructured, Intuitive Leaps
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Javamail Won't Work: AuthenticationFailedException



Everyone knows how to use JavaMail API and the javamail.jar.  I wrote a class to send emails:  The code looked like this:

public synchronized static boolean sendMail() {
Properties props = new Properties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", smtp_host);
props.put("mail.smtp.port", use_port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.auth.mechanisms", "PLAIN");
props.put("mail.smtp.debug", "false");
props.put("mail.smtp.socketFactory.port", use_port);
props.put("mail.smtp.socketFactory.class", socketFactoryClass);
props.put("mail.smtp.socketFactory.fallback", "false");

try {
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
MimeMessage msg = new MimeMessage(session);
msg.setText(msg_text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
to_addr));
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(smtp_host, userName, acct_pwd);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
return false;
}
}

Easy, peasy piece of cake - right? Nope!

It kept throwing an exception: java - javax.mail.AuthenticationFailedException: 535 5.0.0 Authentication Failed

I tore my hair out over this one.  I couldn't figure it out. And weirdly enough, the code worked on a Windoze server but not on a Linux server.  What do to? Go back to first principles.

The fix was a simple line.  I added this line to the properties:

props.put("mail.smtp.auth", "true");

and the thing worked on Linux. And it still worked on Windoze.

Hope this helps someone.

Java java.io.NotSerializableException


I decided to get fancy with my multilayer perceptron, Artificial Intelligence machine that I build over the Christmas season. It was a classical design of artificial neurons, arranged in a layered perceptron pattern with weights and firing thresholds.  Instead of loading a bunch of arrays that were the nodes in the perceptron, I created objects. There were the neurons themselves, and the axons feeding the neurons.  I had the problem of saving the weights, and instead of writing all of it to a file, and having a massive IO operation, I decided to serialize the whole machine.  That way, I could resurrect the whole machine by de-serializing it.

I also thought that I was being smart by having a property change listener on the last input of each layer.  When the final input changed state, I would use the property change listener to fire the neuron.  It all worked like a charm, except when it came time to save the machine.  I kept getting a

java.io.NotSerializableException

It turned out that the PropertyChangeListener is not serializable.  I marked it transient, which means that it wasn't serialized, but I wasn't crazy about the whole machine not being serialized.

So, I coded out the property change listener.  All this to say, is that if you get this exception, you can mark the field transient, to not serialize it, or you can code out the parts that won't serialize.

Hope this helps someone.

Java - determine an image or file exists

One of our programmers asked me how to determine if an image or a file exists last week, so I thought that I would post this code snippet for anyone else that needs a reminder.

String thumbnail = <put the name of image or file here>
try{
   File iFile = new File(config.getServletContext().getRealPath("/")
    + "albums/" + thumbnail);  //we keep all of our images in a directory called albums
   
   if (iFile.exists()) {
    String thisImage = "albums/"+ thumbnail;
     }  else {
        String thisImage = "albums/"+ "noImage.jgp";
     }
}
catch (Exception e)
{
  System.out.println("Can't find image.");
}


Hope this helps someone.

Java - How to calculate and find out how many seconds to an event in the future

Java lesson.  Let's suppose that you have an event happening in the future.  The date and time of that event is stored in a database and you want to calculate how many seconds there are to that event. Once you get seconds, you can divide by 60 to get minutes, and again by 60 to get hours and then by 24 to get days etc.

Here is a code snippet that lets you do that:

Date now = new Date();
Timestamp eventStart = rs.getTimestamp("eventStart");
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(eventStart);
Date endInterval = gc.getTime();
long difference = Math.abs(endInterval.getTime() - now.getTime());
long secondsToEvent = difference / (1000);

Date is java.util.Date. Timestamp is java.sql.Timestamp.

Hope this helps someone.

Code Snippet for Creating Secure Token in Java



Tokens can be used for many things.  Among them are Single Sign On, or saving an identification number without exposing it to the web.  Here is a quick code snippet to create a 16 character token

First you need an import:

import java.security.SecureRandom;

here is the code snippet:

String token1 = null;
SecureRandom secureRandom = new SecureRandom();
String secString = new BigInteger(130, secureRandom).toString(32);
token1 = secString.substring(0, 15);  //creates a 16 character token

Alter the substring end value to change the size of the token.

Hope this helps someone.

Getting Freshdesk.com SSO to work



We recently decided to use Freshdesk.com for our help desk, knowledge base etc.  Since we want our knowledge base to be private for clients only, Freshdesk requires a login.  We don't want to make our clients log in twice, so Freshdesk has this SSO or Single Sign On token system.

We use Java, and there was a java servlet showing how to sign on with a token.  However the online java in a repository didn't quite work.

Here is a working Java servlet for the Freshdesk SSO token system:

import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.application.User; (replace with your own user bean)

public class FreshDeskSSOServlet extends HttpServlet {

private static final long serialVersionUID = 7027717204177362374L;
private final String BASE_URL = "baseUrl including trailing slash" + "login/sso";
private final String sharedSecret = "put in shared secret";



@Override

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

try {
String url = this.getSSOURL();
response.sendRedirect(url);
} catch (Exception e) {
    System.out.println(e.getLocalizedMessage());
    System.out.println(e.getMessage());
}
}

private static String getHash(String text) throws Exception {
    MessageDigest m=MessageDigest.getInstance("MD5");
        m.update(text.getBytes(),0,text.length());
    return ""+new BigInteger(1,m.digest()).toString(16);
}



private String getSSOURL() {

String hash = null;
String url = null;
User user; //Get the user details using your current authentication system
String name = "First & Last Name";// Full name of the user
String email = "email@youraddress.com";// Email of the user
try {
hash = getHash(name + email + sharedSecret);
} catch (Exception e1) {
System.out.println(e1.getMessage());
e1.printStackTrace();
}

try {
name = URLEncoder.encode(name);
email = URLEncoder.encode(email);
url = BASE_URL + "?name="+name+"&email="+email+"&hash=" + hash; 


}catch (Exception e) {
//Handle appropriate code
System.out.println("There is an exception while constructing the URL");
e.printStackTrace();
}

return url;

}
}

Hope this helps.

Java Networking

I have this issue where I need to know the IP address or some identifying part of a computer.  Using Java, I came across the class of java.net.NetworkInterface.  Since there may be several LAN adapters on a computer, I wanted to find a single identifying feature that could be used to positively identify who sent something.

I implemented the following code to see what comes out of it:

String ip;
   try {
       Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
       while (interfaces.hasMoreElements()) {
           NetworkInterface iface = interfaces.nextElement();
           // filters out 127.0.0.1 and inactive interfaces
           if (iface.isLoopback() || !iface.isUp())
               continue;
           System.out.println("HW" + iface.getHardwareAddress());

           Enumeration<InetAddress> addresses = iface.getInetAddresses();
           while(addresses.hasMoreElements()) {
               InetAddress addr = addresses.nextElement();
               
               ip = addr.getHostAddress();
               System.out.println(iface.getDisplayName() + " " + ip);
           }
       }
   } catch (SocketException e) {
       throw new RuntimeException(e);
   }

The very first thing that comes back out of this piece of code is very, very interesting.  It returns the name of the LAN network adapter that was actively used.  Concatenated to that was the byte fe80: which identifies the IPV6 and the unique MAC Address of that computer.  Here's the interesting bit -- immediately preceding the fe80 is the name of the SSID that is being used.  This not only reveals the computer MAC address but also the network (and the place of the network) that is connected to.

Hope this helps someone.

Eclipse Java -- Classes Will Not Build


We had an interesting problem.  After checking out the latest project out of our repository (Subversion), we couldn't get a build.  After a clean, the WEB-INF/classes directory was empty.  We checked the build path stuff under the project properties.  All was in order.  We rebuilt several times.  Nothing.

It turns out that somehow a corrupted .classpath file was checked into the main trunk.  This is the .classpath file automagically generated by Eclipse.  When we reverted to the previous version of the .classpath file, everything worked and we got a build.

Hope this helps someone.

Data source rejected establishment of connection

It was frustrating. I set up a Java JDBC connection pool to MySQL, and the app ran for awhile, then it would not connect. Obviously I had leaking connections somewhere.

The message in the transcript log was:
Data source rejected establishment of connection, message from server: "Too many connections"

  I went and tried closing all of the connections, but the app is a fairly large one. What to do? I Googled around and there was no obvious way of seeing where the connection leak was, so I opted for brute force. The pseudo code for establishing a connection with at connection pool looks like this:

 DataSource ds=getDataSource();
 Connection conn=ds.getConnection();

and to close the connection, it was:

conn.close();

 So the way that I solved it and found the connection leak, was that I added a couple of lines to the above code.

In the open connection method, I added

System.out.println("Open Connection " + conn.toString();

and in the close method, before the close statement, I added:

System.out.println("Close Connection " + conn.toString();

It prints out stuff in the console like this:


Open  Connection ProxyConnection[PooledConnection[com.mysql.jdbc.JDBC4Connection@e78c1b]]
Close Connection ProxyConnection[PooledConnection[com.mysql.jdbc.JDBC4Connection@e78c1b]]

I then match up the open and closes as I do stuff, and find my unclosed connections leaks.

Hope this helps.


MySQL Connection Pooling with Java & Tomcat Tip

It is time we got serious with a webapp of my to quit setting up and tearing down connections to the mysql database.  I decided to implement a connection pool.  There are examples all over the web on how to do this.  Luckily, I am using Apache Tomcat 7 and it has the connection pooling built in.

So I was implementing the java code:


 import java.sql.Connection;
  import java.sql.ResultSet;
  import java.sql.Statement;

  import org.apache.tomcat.jdbc.pool.DataSource;
  import org.apache.tomcat.jdbc.pool.PoolProperties;

and the import was throwing the class not found error.  I thought "WTH -- I am using Apache 7".  As it turns out, I had to go to the properties, and add the Apache Tomcat Library (not the jars but the libraries) in the Project Build Path.  Problem solved.  Hope this helps someone.

Giving a user an anonymous ID programatically

We have a web application written in Java whereby when the users sign in, we want them to be anonymous to each other.  So what we do, is give them a number.  I needed an algorithm to generate the number from their database user id, and I wanted the algorithm to vary such that it wasn't that easy to figure out.

So what I do, is on even days of the month, the user id is added to the day of the month, and on odd month days, I take the absolute value of the day of month - the user id.


//get day of month

int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
//cast it to a double so that I can get a modulus 2 which indicates whether it is even or odd
double amem = (double) dayOfMonth;
if ((amem % 2) == 0) {       // it's an even day with no remainder
dayOfMonth = dayOfMonth + userId;
} else {
//its an odd day
dayOfMonth = Math.abs(dayOfMonth - userId);
}


Hope this helps someone.

Linux Sendmail Not Working

It's real easy to send email using a linux server.  We have an app where we need to send notification details to our users so we send it via the linux server that is already running Apache Tomcat.

Since the details and notifications go beyond the simple, we use java to write the details to a temp file, get the email address from the database, invoke a bash shell to send the mail and then delete the temp file.

Here is how its done.



String messbody = (new StringBuilder(String.valueOf(messbody)))
.append("Please log into www.mydomain.com to see the latest things on your account.").toString();

Then I generate a random file name by assembling a bunch of random characters:

int rancharacter = 65 + (int) (Math.random() * 90);

char ck = (char) rancharacter; 
String fnum = String.valueOf(ck); 

I did the rancharacter many times to generate a random string.  I created a linux directory where this would be written to.  It is in /home/messages.



String longfileName = "/home/messages/" + fnum; 
 File f = new File(longfileName); 
 try {
 BufferedWriter bout = new BufferedWriter( new FileWriter(longfileName)); 
 bout.write(messbody);
 bout.close(); 
 } catch (IOException e)
 { System.out
 .println("Writing email file exception");
 System.out.println("Exception " + e.getMessage()); }

Now that I have a file, I wrote a very little bash script called mailer, put it in the /bin directory and did a chmod so that it could be executed.  The bash script looks like this:


#!/bin/bash
IFS=":-;"
#FILE= "/home/messages/$3"
#echo $(basename "$2")
mail -s $(basename "$2") $(basename "$1") < /home/messages/$(basename "$3")


The only thing life to do, is to create a subject, get the email, get the runtime so that one can execute a linux command, and send the email.

Here's some code:

String emailAddress = email;   //previous declared variable that went to the database
 String subject = "Account_Notification";  //I had to put the underscore to eliminate space problems
 String messBody = fileName; 
 String cmd = "mailer" + " " + emailAddress
 + "  " + subject + " " + longfileName; 
  // get the linux runtime to execute the command
 try { Runtime run
 = Runtime.getRuntime(); Process pr = run.exec(cmd);
 pr.waitFor(); BufferedReader buf = new
 BufferedReader( new InputStreamReader(
 pr.getInputStream()));
 
 } catch (Exception fu) {
 
 System.out.print(fu.getMessage()); } 
 boolean success = f.delete();

OK - all of this was working.  Then I changed the message body and it stopped working.  What caused it to stop working.  In the body of the message, I put java.util.Date.toString();

That would stop Centos linux from mailing.  Weird.  I hope that this helps someone.



Java - How to make an arraylist of arraylists

I had to make an arraylist of arraylists.  The reason that I was doing this, was that I had to eliminate duplicates from a resultset.  The easiest way to do this was to put the resultset into an arraylist so that I could operate on it, because you can't iterate or use a resultset twice in Java.

Here are a few examples of the constructors to make an arraylist of arraylists:

   ArrayList<ArrayList<Object>> allData = new ArrayList<ArrayList<Object>>();

 ArrayList<ArrayList<String>> allString = new ArrayList<ArrayList<String>>();

 ArrayList<ArrayList<int>> allInts = new ArrayList<ArrayList<int>>();


Easy once you know how.

Java String MySQL Error

I just spent an hour banging my head against a wall.  I constructed a mysql query string from variables.  So my string construct would look like this:
String quality = "Very Good";

String queryString = "Select  * from products where consumer_rating=" + quality;

The thing kept bombing.  It said that I had an sql error near where consumer_rating=Very Good.

It all looked kosher.  I had forgotten that a string value needs single quotes.

In other words, I should have declared quality =" 'Very Good' ";

Notice the single quotes after the double quotes.  Necessary for an sql statement for string injection.

Hope this helps someone save some time.

Java: How to schedule an event for a specific time

In a previous blog entry, I showed a snippet of code on how to determine the amount of minutes from now to a specific time.

The code was quite simple:

Date now = new Date();
GregorianCalendar expiryDate = myevent.getExpiryDate();
Date end = expiryDate.getTime();
long difference = Math.abs(end.getTime() - now.getTime());
long minutesLeft = difference / (1000 * 60);



Starting from that point, it is quite simple to schedule a Java runnable thread at a specific time. Here is how I did it:

private ScheduledExecutorService scheduler;
.....
scheduler = Executors.newSingleThreadScheduledExecutor();

.....
Date now = new Date();
GregorianCalendar expiryDate = myevent.getExpiryDate();
Date end = expiryDate.getTime();
long difference = Math.abs(end.getTime() - now.getTime());
long minutesLeft = difference / (1000 * 60);
long secondsLeft = difference / 1000;
// task to run is embedded in a class implementing Runnable
RunnableNow runnableNow = new RunnableNow()
scheduler.schedule(uhuraNow, secondsLeft, TimeUnit.SECONDS);


Hope this snippet save someone some time

Java ~ How to get the remaining minutes between two dates


I had to look this up, so I am posting this snippet in the hope that it helps someone else.

I monitor events in real time. The program has to know when the event ends, and send SMS messages. The event, including the expiry date/time is a database entry. How do you determine the remaining time in minutes?

First I fetch the expiry date/time into a bean. It is stored as a GregorianCalendar entity in the database, because I have to extensively manipulate it before the event starts. Then I get a time for NOW. Then I have to subtract the two. This is how I do it:

Date now = new Date();
GregorianCalendar expiryDate = myevent.getExpiryDate();
Date end = expiryDate.getTime();
long difference = Math.abs(end.getTime() - now.getTime());
long minutesLeft = difference / (1000 * 60);

Hope this helps.

Java MySQL SQL Tip Comparing Timestamp in Column to Current DateTime

There are many ways to skin a cat. I have a database table where I have to compare a column timestamp with the current date/time as well as adding hours and minutes. I realize that there is an SQL NOW function, but I also need the now time converted to calendar to be able to add and subtract calendar units, and I construct the SQL statement in Java.

Here is the syntax of the snippet in Java for comparison to the current datetime:

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sqlDate = new java.sql.Timestamp(utilDate.getTime());
try {
stmt = conn.createStatement();
String myQueryString = "SELECT * FROM sale_table where saleStart < {ts '" + sqlDate.toString() + "' }";

Fuzzy Logic, "Ish" values, Java

I previously wrote about an "ish" function ( which can be read HERE ) , that describes the need for a fuzzificator that identifies things from incomplete or incorrect knowledge. Humans are excellent at doing this in some sort of neural pattern recognition. In my "ish" function article, I made the case that it was needed to crack a code that the FBI was working on and asking for the public's help.

Little did I realize that I would need an "ish" function or a fuzzy value function shortly in my work. I am writing software that processes health surveys sent by smart phone to identify persons that need immediate care in a Third World country. The way this is done, is by sending people out using a survey tool that asks questions which identifies risk signs. There are many different types of surveys, and the only way to classify what comes in over GPRS or HTTP, is the XML document with the survey answers. I parse the document, and identify the type of survey by the number of answers.

However this method is not foolproof, because the tool lets the interviewer skip an answer. At this point, my survey classifier throws an exception because it cannot determine the type of survey. However each type of survey has a significant difference in the number of answers, so a fuzzificator would work well here. For example, one particular survey has 12 answers, the next has 25 and the next has 64, so making a fuzzy logic class to determine the type of survey is quite easy. I just give the exact answer a range, and if it falls into that range, then I know what type of survey it is.

Right now, my fuzzy value function works only on integers. It works on an actual difference or a percentage difference. The values are hard coded but the code could be modified to get the values from a config file or a database.

I see this function extended to strings, doubles, floats and indeed anything you want. In addition, once you have the fuzzificator, one can make the same thing for logic types, for example Boolean algebra. One could have a fuzzy AND gate where there are many inputs, and if one or two is out, a decision still could be made. And if one combines the decision making with Bayesian inference, or probabilities, then one has a truly useful tool for complex fuzzy logic.

Here is the prototype source code in Java:


package org.FuzzyLogic;



public class FuzzyValues {
static final int PLUS_MINUS_VALUE_INT = 1;
static final double PLUS_MINUS_VALUE_INT_PERCENT = 0.09;
static final int expectedInput = 12;

public static boolean fuzzyInt(int actualInput) {
boolean fuzzy = ((expectedInput-PLUS_MINUS_VALUE_INT) <= actualInput) && (actualInput <= (expectedInput+PLUS_MINUS_VALUE_INT ));
return fuzzy;
}



public static boolean intPercentMatch(int input) {
double minus_percent_value = expectedInput * (1 + PLUS_MINUS_VALUE_INT_PERCENT);
double plus_percent_value = expectedInput * (1 - PLUS_MINUS_VALUE_INT_PERCENT);
boolean fuzzy = (minus_percent_value <= input)&& (plus_percent_value >= input);
return fuzzy;
}




public static boolean isFuzzyIntValue(int input)
{
boolean success = fuzzyInt(input);
return success;
}
public static boolean isFuzzyIntPercent(int input)
{
boolean success = intPercentMatch(input);
return success;
}

}

Java Virus ???

I am a firm believer in Avira. I use it on all of my machines for anti-virus. The way that I became a believer was in Nassau, the Bahamas. We need a cheap machine to act as a modem answer gateway. We walked over to the local Radio Shack store and bought the cheapest Pentium-knock-off that they had. It came loaded with all sorts of stuff, like Microsoft Office, Adobe Photoshop and all of the expensive programs.

This being the Caribbean, and the land of the Pirates of the Caribbean, of course it was all cracked stuff, loaded with viruses. I did my best to clean the machine with every available package, including Norton, McAfee and such -- all to no avail. Avira (free personal download) was the only one that did it.

So, today, Avira began its scan, and this showed up in the transcript pad:

Begin scan in 'C:\'
C:\Documents and Settings\Administrator\Application Data\Sun\Java\Deployment\cache\6.0\19\33c334d3-7247e552
[0] Archive type: ZIP
--> main.class
[DETECTION] Contains recognition pattern of the EXP/CVE-2012-0507 exploit

Beginning disinfection:
C:\Documents and Settings\Administrator\Application Data\Sun\Java\Deployment\cache\6.0\19\33c334d3-7247e552
[DETECTION] Contains recognition pattern of the EXP/CVE-2012-0507 exploit
[NOTE] The file was moved to the quarantine directory under the name '4af8d44b.qua'.

Holy crap, it was a Java virus. Here is more information:


Virus:EXP/CVE-2012-0507.A
Date discovered:19/03/2012
Type:Exploit
In the wild:No
Reported Infections:Low
Distribution Potential:Low
Damage Potential:Medium
VDF version:7.11.25.166
IVDF version:7.11.25.166

General Method of propagation:
• No own spreading routine


Aliases:
• Mcafee: Generic
• Kaspersky: Exploit.Java.CVE-2011-3544.lt
• Microsoft: Exploit:Java/CVE-2012-0507.A
• GData: Java:CVE-2011-3544-ET


Platforms / OS:
• Windows 2000
• Windows XP
• Windows 2003
• Windows Vista
• Windows Server 2008
• Windows 7


Side effects:
• Can be used to execute malicious code
• Makes use of software vulnerability
CVE-2012-0507

File details Programming language:
• Java

comm3.0_u1_linux and comm3.0_u1_linux.zip

[img]http://www.fileden.com/files/2011/6/23/3156918/comm3.0_u1_linux.zip[/img]
[url=http://www.fileden.com]Free file hosting from File Den![/url]


I was writing java code to use on a linux platform and I needed the linux comm.jar and the drivers. I had a hell of a time finding them.

I am posting them here from a fileden account to help others.

Good Luck.