Oct 16, 2008

how to use ACEGI filter






CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/javascript/**=#NONE#
/css/**=#NONE#
/images/**=#NONE#
/sounds.*=#NONE#
/secureimg=#NONE#
/**/tmplt.*=#NONE#
/**/.*popup.xhtml=securityFilter
/**/*.jsp=securityFilter
/**/*.xhtml=channelProcessingFilter,httpSessionContextIntegrationFilter,logoutFilter,casProcessingFilter,basicProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor,securityFilter
/**=httpSessionContextIntegrationFilter,logoutFilter,casProcessingFilter,basicProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor,securityFilter


Jul 12, 2008

Force authentication with Java Mail API

package com;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.MimeMessageHelper;

public class EmailTest {

/**
* @param args
*/
public static void main(String[] args) {
try {
String[] strarr = { "recipient@email.addresses" };
postMail(strarr, "Test u", "Test Mesage", "from@email.address", false);
System.out.println("Mail sent!...");
} catch (MessagingException e) {
e.printStackTrace();
}

}
public static void postMail(String recipients[], String subject, String message, String from, boolean isHtml) throws MessagingException {
boolean debug = false;

// Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host","hostipaddr");
String hostEmail = "admin@mail.com";
String pwd = "password";
// create some properties and get the default Session
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props, new ForcedAuthenticator(hostEmail,pwd));
session.setDebug(debug);

// create a message
MimeMessage msg = new MimeMessage(session);

MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(msg);

mimeMessageHelper.setTo(recipients);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setReplyTo(from);
mimeMessageHelper.setText(message, isHtml);

Transport.send(mimeMessageHelper.getMimeMessage());
}
}
class ForcedAuthenticator extends Authenticator {
String username;
String password;
public ForcedAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.username, this.password);
}
}

Jun 9, 2008

Wildcard To Regex in Java

This code works like wild card expression in java. there is no in-built methods to identify which are using wild card chars '?', and '*'.
Every programmer know about these('?','*') chars how there are working.
Here the code snippet to work like their behavior

public static String wildcardToRegex(String wildcard){
StringBuffer s = new StringBuffer(wildcard.length());
s.append('^');
for (int i = 0, is = wildcard.length(); i < is; i++) {
char c = wildcard.charAt(i);
switch(c) {
case '*':
s.append(".*");
break;
case '?':
s.append(".");
break;
// escape special regexp-characters
case '(': case ')': case '[': case ']': case '$':
case '^': case '.': case '{': case '}': case '|':
case '\\':
s.append("\\");
s.append(c);
break;
default:
s.append(c);
break;
}
}
s.append('$');
return(s.toString());
}

May 14, 2008

Loading Spring ApplicationContext in Class Path

Write a Startup Servlet and initialize it to 0 to load on application startup. Reading all ApplicationContext files from classpath to load them. The following example will explain how to load spring AppicationContext files while application startup. Following code write in Starup servlet.

private static final String[] CONTEXT_PATHS = {"/spring/applicationContext-*.xml" };
public void init(ServletConfig config) throws ServletException {
loadSpringResources(config);
}
private void loadSpringResources() {
ApplicationContext appContext = null;

// Set up the service locator factory...
BeanLocatorFactory.setApplicationContext(appContext);
// Start the different services.
}

Here Write the BeanLocatorFactory is as follows to set ApplicationContext and whenever your required.

public class BeanLocatorFactory {
private static ApplicationContext applicationContext = null;
private static final Map nameMap = Collections.synchronizedMap(new HashMap());

public static Object getService(Class interfaceClass) {
String cachedServiceName = (String) nameMap.get(interfaceClass);
if (cachedServiceName == null) {
int servicePackageLength = interfaceClass.getPackage().getName().length() + 1;
StringBuffer serviceName = new StringBuffer(interfaceClass.getName().substring(servicePackageLength));
cachedServiceName = serviceName.toString();
nameMap.put(interfaceClass, cachedServiceName);
}
return getService(cachedServiceName);
}
public static synchronized void setApplicationContext(ApplicationContext context) {
BeanLocatorFactory.applicationContext = context;
}
public static Object getService(String serviceName) {
try {
Object o = applicationContext.getBean(serviceName);
return o;
} catch (NoSuchBeanDefinitionException e) {
return null;
}
}
}

May 8, 2008

Image Cropping in java

//This is logic to crop image in java , here the code for how to crop image in java only. not this code runs completely
public void cropImage() {
byte[] bytesOut = null;
try {
int x1 = 0, y1 = 0, cw = 0, ch = 0;
HttpServletRequest request = getRequest();
String params = request.getParameter("dimensions");
String str[] = params.split(",");
HttpSession session = request.getSession();
String fname = (String) session.getAttribute("fileupload_name");
if (StringUtils.isNotBlank(str[0])) {
x1 = str[0].equals("") ? 50 : Integer.parseInt(str[0]);
y1 = str[1].equals("") ? 50 : Integer.parseInt(str[1]);
cw = str[2].equals("") ? 50 : Integer.parseInt(str[2]);
ch = str[3].equals("") ? 50 : Integer.parseInt(str[3]);
}
byte[] bytes = (byte[]) session .getAttribute("fileupload_bytes");
File tfile = new File(fname);
FileOutputStream fout = new FileOutputStream(tfile);
fout.write(bytes);
fout.close();
try{
BufferedImage bimage = ImageIO.read(tfile);
BufferedImage bi = null;
bi = bimage.getSubimage(x1, y1, cw, ch);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String format = fname.substring(fname.lastIndexOf(".") + 1);
if (bi != null) {
ImageIO.write(bi, format, baos);
}
bytesOut = baos.toByteArray();
}catch(Exception exp){
log.info("Invalid image Width or Height");
}
} catch (Throwable th) {
ExceptionTrapSender.sendException(th);
}

}

May 6, 2008

Calling Url using java servlet

This is the java code servlet block, to ping a servlet on URL.
Here we are using URLConnection class to open a connection.

System.err.println("@@W@Calling Test Servlet:: Called");
URLConnection uc = new URL("http://www.example.com/Test").openConnection();
uc.setDoInput(false);
uc.setDoOutput(true);
uc.setUseCaches(false);
uc.setDefaultUseCaches(false);
uc.setRequestProperty("Content-Type", "application/octet-stream");
ObjectOutputStream out = new ObjectOutputStream(uc.getOutputStream());
HashMap hm = new HashMap();
hm.put("Key1", "Val1");

out.writeObject(hm);
out.flush();
out.close();