Monday, November 15, 2010

jQuery trim example

[sourcecode language="html"]
<html>
<head>
<title>
jQuery trim example
</title>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<button>Click on me to see the effect</button>
<script>
$("button").click(function () {
var exampleStr = " jQuery trim example ";
alert("'" + exampleStr + "'");
exampleStr = jQuery.trim(exampleStr);
alert("'" + exampleStr + "'");
});
</script>
</body>
</html>
[/sourcecode]

Email Sender using Apache commons mail

[sourcecode language="css"]
/*
Amobile - The Enterprise Open Source Mobile Billing System
Copyright (C) 2009-2010 Amobile Inc.

This file is part of aOneMobileVAS.

aOneMobileVAS is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

aOneMobileVAS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Amobile. If not, see <http://www.gnu.org/licenses/>.

File Name : EmailSender.java
Date : 20-Feb-2010:3:22:31 AM
User : Rahul Jain

*/
package com.thinkideas.client.emailengine;

/**
* @author Rahul Jain
*
*/

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

/**
* This Class Sends a Email.This class don't have any dependency.
*
* @author rahul.jain
* @version :1.0.0
* @HowToUse :
*/
public class EMailSender {

/** Instance of Logger : LOG. */
private static final Logger LOG = Logger.getLogger(EMailSender.class);
/** String: CONFIG_LOC location of email config file. */
/** Getting the Config Properties file Location. */
/*
* public static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
* .getBundle(CONFIG_LOC);
*/
/** Email Host Name server. */
public static String hostName;
/** Getting the Sender Name. */
public static String senderName;
/** Getting the Sender Email Id. */
public static String senderEmail;
/** Getting the Sender Email user name. */
public static String fromEmailUserName;
/** Getting the Sender email password. */
public static String fromEmailPassword;
/** Getting the email subject. */
public static String emailSubject;
/**
*
*/
public static String emailContent;
public static String adminEmailId;

private static void getEmailConfig() {
Properties emailProps = new Properties();
try {
emailProps.load(new FileInputStream("emailconfig.properties"));
hostName = emailProps.getProperty("HostName");
senderName = emailProps.getProperty("SenderName");
senderEmail = emailProps.getProperty("SenderEmail");
fromEmailUserName = emailProps.getProperty("SenderEmailUserName");
fromEmailPassword = emailProps.getProperty("SenderEmailPassword");
emailSubject = emailProps.getProperty("EMailSubject");
emailContent = emailProps.getProperty("EmailContent");
adminEmailId = emailProps.getProperty("AdminEmail");

} catch (FileNotFoundException fnfExe) {
LOG.error(fnfExe.getMessage());
} catch (IOException ioe) {
LOG.error(ioe.getMessage());
}
}

/**
* This Method is a internal method for sending email to a email recipient
* with some html content that includes the message to be send. This can be
* also extends for sending attachements.
*
* @param userName
* : user name of the user.
* @param newPassword
* : new password to be sent.
* @param recipientName
* : Recipient name like "Abc".
* @param recipientEmail
* : Recipient email id like "abc@abc.com".
* @param message
* : Message content to be sent like :
* "Dear User, Your password is reseted"
* @param attachementLocation
* : Attachment location if any.
* @param fileName
* : file name if any.
* @return boolean : True if sent successfully.
* @throws EmailException
* : email exception is thrown if any error occurs.
*/
private boolean sendMail(String userName, String newPassword, String recipientName, String recipientEmail,
String message, String attachementLocation, String[] fileName) throws EmailException {

getEmailConfig();
// Creating the email message
HtmlEmail email = new HtmlEmail();
System.out.println("hostName:" + hostName + " fromEmailUserName:" + fromEmailUserName + " fromEmailPassword:"
+ fromEmailPassword + " recipientEmail:" + recipientEmail + " senderEmail:" + senderEmail);

email.setHostName(hostName);
email.setAuthentication(fromEmailUserName, fromEmailPassword);
email.addTo(recipientEmail, recipientName);
email.setFrom(senderEmail, senderName);
email.setSubject(emailSubject);
email.setHtmlMsg(message);
email.setTLS(true);
String msg = null;
try {
msg = email.send();
} catch (Exception e) {
LOG.error("Error occurred while emailing:" + e.getMessage() + "cause?" + e.getCause());
return false;
}
LOG.debug("Returning Message Email Sending Program:" + msg);
return true;
}
/**
* This Method sends the email and it get some information from caller and
* add some information from its own. This method formats the received
* message and make appropriate changes in that.
*
* @param userName
* : user name of the user.
* @param newPassword
* @param userFirstName
* : first name of the user.
* @param recipientEmail
* : Recipient email id like "abc@abc.com".
* @param remoteIpAddr
* : Ip address of the User from where request has been made.
* @return
* @throws EmailException
* : email exception is thrown if any error occurs.
*/
public boolean sendEmailToUser(String userName, String newPassword, String userFirstName, String recipientEmail,
String remoteIpAddr) throws EmailException {
getEmailConfig();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:MM:SS");
Date toDayDate = new java.util.Date();
String currentTime = sdf.format(toDayDate);

LOG.debug("Cuurent time is :" + currentTime);

StringBuffer sb = new StringBuffer();
/*
* String emailContent = RESOURCE_BUNDLE.getProperty("EmailContent");
* String adminEmailId = RESOURCE_BUNDLE.getString("AdminEmail");
*/

LOG.debug("User:" + userName + " newPassword:" + newPassword + " userFirstName:" + userFirstName
+ " recipientEmail:" + recipientEmail + " remoteIpAddr:" + remoteIpAddr);

// If due to any reason user first name is coming as null then it will
// make default User. so in email it will become "Dear User" rather than
// "Dear null"
if (userFirstName == null || userFirstName.length() == 0) {
userFirstName = "User";
}

StringBuffer sb1 = new StringBuffer();
sb1.append(userFirstName.substring(0, 1).toUpperCase());
sb1.append(userFirstName.substring(1, userFirstName.length()));
userFirstName = sb1.toString();
sb1 = null;// Making null so can be collected by Java GarbageCollector.

emailContent = emailContent.replaceAll("%userName%", userName);
emailContent = emailContent.replaceAll("%newPassword%", newPassword);
emailContent = emailContent.replaceAll("%userFirstName%", userFirstName);
emailContent = emailContent.replaceAll("%requestIpAddress%", remoteIpAddr.toString());
emailContent = emailContent.replaceAll("%toDayDate%", toDayDate.toString());
emailContent = emailContent.replaceAll("%requestTime%", currentTime.toString());
emailContent = emailContent.replaceAll("%adminEmailId%", adminEmailId);

emailContent = sb.append(emailContent).toString();

sb = null;// Making null so can be collected by Java GarbageCollector.

// attachementLocation is null and fileName array is null;
// can be used if adding more functionalities in this program.
boolean emailSentStatus =
sendMail(userName, newPassword, userFirstName, recipientEmail, emailContent, null, null);
System.out.println("email content:" + emailContent);
if (emailSentStatus) {
LOG.info("Email Sent Sucsessfully");
} else {
LOG.info("Email Couldn't Sent Sucsessfully");
}
return emailSentStatus;

}

public static void main(String[] args) {
EMailSender emailSender = new EMailSender();
try {
emailSender.sendEmailToUser("", "", "testuser", "testuser@gmail.com", "");
} catch (EmailException e) {
System.out.println("Exception message:" + e.getMessage() + "cause?" + e.getCause());
e.printStackTrace();
}
}
}
[/sourcecode]

Java crawler

package com.myjobalert.crawler;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public abstract class Crawler {

public String getURLContents(String urlStr, HttpParam[] httpParams) throws IOException {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
HttpURLConnection httpconn = (HttpURLConnection) conn;

if (httpParams != null) {
httpconn.setRequestMethod("POST");
for (HttpParam param : httpParams) {
httpconn.setRequestProperty(param.getName(), param.getValue());
}
conn = httpconn;
}
InputStreamReader bis = new InputStreamReader(conn.getInputStream());
System.out.println("page size:"+conn.getContentLength());
final int char_per_page = 5000;
char[] buff = new char[char_per_page];
StringBuilder sb = new StringBuilder(char_per_page);
int read = 0;
while (read != -1) {
read = bis.read(buff);
if (read != -1)
sb.append(buff, 0, read);
}
System.out.println("page size:"+(sb.length()/1000)+"KB");
System.out.println("page is downloaded");
return sb.toString();
}
}

class HttpParam {

private String name;
private String value;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}
}

http://ws.amazon.com/widgets/q?rt=qf_br_asin_ssw&ServiceVersion=20070822&MarketPlace=US&ID=V20070822%2FUS%2Fmyknowledgebo-20%2F8003%2F13de8fda-f06a-4d41-9041-b4aeab627f25&Operation=GetDisplayTemplate Amazon.com Widgets