Apache Velocity - Resource not found exception - servlets

I have a requirement to generate some automated mails and so I wanted to use velocity for this task.I have copied all velocity jars to the lib folder and created a hello.vm template and placed in WEB-INF/templates folder.Below is exception I am getting,
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'hello.vm'
userCount incremented to :1
at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1514)
at org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:373)
at indian.test.handleRequest(test.java:34)
at org.apache.velocity.tools.view.VelocityViewServlet.doRequest(VelocityViewServlet.java:217)
at org.apache.velocity.tools.view.VelocityViewServlet.doGet(VelocityViewServlet.java:182)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at listener.trimresponse.doFilter(trimresponse.java:46)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
I tried all the other ways to load resource using classloader/webapps and still the error remains the same.I am using netbeans 7.2.x with tomcat 7.27. Appreciate if someone can suggest something for this.
Below is my velocity properties file,
resource.loader = file
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = C:\Users\kiran\Desktop\Netbeans Projects\ourstory\web\WEB-INF\templates
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 2
runtime.log=/WEB-INF/logs/velocity.log
runtime.log.logsystem.class=org.apache.velocity.runtime.log.Log4JLogSystem
runtime.log.logsystem.log4j.pattern=%d - %m%n
runtime.log.logsystem.log4j.file.size=10000
runtime.log.logsystem.log4j.file.backups=1
and below is servlet I am using
import java.util.Properties;
import javax.servlet.http.*;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;
public class test extends VelocityViewServlet {
private String htmlTemplate = "hello.vm";
VelocityContext context = new VelocityContext();
#Override
public Template handleRequest(HttpServletRequest request,
HttpServletResponse response,
Context context) {
// Properties props = new Properties();
// props.setProperty("resource.loader", "class");
// props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
// props.setProperty("webapp.resource.loader.path", "/WEB-INF/templates/");
VelocityEngine engine = new VelocityEngine();
engine.init();
Template template = null;
try {
context.put("name", "Velocity Test");
template = engine.getTemplate(htmlTemplate);
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception caught: " + e.getMessage());
}
return template;
}
}
its simple servlet but for some reason I am unable to get it working.

(Answered in comments and edits. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Update Solved.
Finally After wasting good 2 days and pulling out lot of hairs,and banging the head many times, its resolved.here is what I did to resolve this, added couple of logging statements to ensure that it points correct to the templates folders and then pasing the absolute path to the template file. Watch out for backslashes and forward slashes. Need to log the folder paths and see where exactly its looking for and then keep dubugging. Its pain in the ass to fix such a simple stuff.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author kiran
*/
import java.io.File;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.http.*;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;
public class Hellotest extends VelocityViewServlet {
#Override
public Template handleRequest(HttpServletRequest request,
HttpServletResponse response,
Context context) {
Properties prop = new Properties();
// prop.put("resource.loader", "class");
// prop.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
String absolutePath = new File(Thread.currentThread().getContextClassLoader().getResource("").getFile()).getParentFile().getParentFile().getPath();
prop.put("file.resource.loader.path", absolutePath + "\\templates\\");
System.out.println("absolute path is : " + absolutePath);
System.out.println("keyset is : " + prop.keySet());
Enumeration em = prop.keys();
while (em.hasMoreElements()) {
String str = (String) em.nextElement();
System.out.println(str + ": " + prop.get(str));
}
VelocityEngine Velocity = new VelocityEngine();
Velocity.init(prop);
Template template = null;
context.put("name", "Velocity Test");
try {
System.out.println("absolute path inside is : " + context);
template = Velocity.getTemplate("hello.vm","UTF-8");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception caught: " + e.getMessage());
}
return template;
}
}
and here is updated velocity properties file,
resource.loader = file
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 2
and finally I put the templates under webpages folder. Maybe I will try to push this in web-inf and see how it goes. Its not good thing to keep templates under webpages given that we are exposing it.

Related

How to add Microsoft Word content in Email Body from Java Code

I am trying to put content of Microsoft Word Document in Email body from Java Code but getting following error:
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
at co.kush.DemoEmail.main(DemoEmail.java:134)
Caused by: javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)
at co.kush.DemoEmail.main(DemoEmail.java:128)
Caused by: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:896)
at javax.activation.DataHandler.writeTo(DataHandler.java:317)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
Refer my code :
package co.kush;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.CharacterRun;
/**
* #author Kush
*
*/
public class DemoEmail {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties prop = new Properties();
String Filepath = "Email.Properties";
FileInputStream propFile = new FileInputStream(Filepath);
prop.load(propFile);
String timeStamp = new SimpleDateFormat("M/dd # HH:mm:ss").format(Calendar.getInstance().getTime());
// Fetching values from property file
String sender = prop.getProperty("sender");
String recevier = prop.getProperty("recevier");
String password = prop.getProperty("password");
String proxyHost = prop.getProperty("proxyHost");
String proxyPort = prop.getProperty("proxyPort");
String smtpHost = prop.getProperty("smtpHost");
String smtpPort = prop.getProperty("smtpPort");
String attachFilePath = prop.getProperty("attachFilePath");
String mailSubject=prop.getProperty("mailSubject")+" on " + timeStamp;
String mailBody = prop.getProperty("mailBody");
Properties sys_prop = System.getProperties();
// Setting values for sending Email
sys_prop.put("mail.smtp.starttls.enable", "true");
sys_prop.put("mail.transport.protocol", "SMTP");
sys_prop.put("mail.smtp.host", smtpHost);
sys_prop.put("mail.smtp.auth", "true");
sys_prop.put("mail.smtp.port", smtpPort);
sys_prop.put("mail.smtp.debug", "true");
sys_prop.put("mail.smtp.socketFactory.port", smtpPort);
sys_prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
sys_prop.put("mail.smtp.socketFactory.fallback", "false");
sys_prop.put("proxySet", "true");
sys_prop.put("proxyPort", proxyPort);
sys_prop.put("socksProxyHost", proxyHost);
sys_prop.put("proxyHost", proxyHost);
Session session = Session.getDefaultInstance(sys_prop, null);
try {
//Adding Sender/Receiver address and Subject Line
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(sender));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recevier));
msg.setSubject(mailSubject);
MimeBodyPart messageBodyPart=new MimeBodyPart();
Multipart multipart = new MimeMultipart();
//Reading Word Document
HWPFDocument doc = new HWPFDocument(new FileInputStream("<AbsolutePathWordDoc\\<WordDocFile>.doc"));
WordExtractor we = new WordExtractor(doc);
String[] paragraphs = we.getParagraphText();
for (String para : paragraphs) {
//Putting word document to email Body
messageBodyPart.setContent(paragraphs, "application/msword");
multipart.addBodyPart(messageBodyPart);
}
//Adding attachment and Body content to MIME msg object
msg.setContent(multipart);
//Sending the message
Transport transport = session.getTransport("smtp");
transport.connect(smtpHost, sender, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("Mail sent succesfully!");
} catch (MessagingException e) {
throw new RuntimeException(e);
} finally {
//Removing System properties
sys_prop.remove("proxySet");
sys_prop.remove("proxyHost");
sys_prop.remove("proxyPort");
sys_prop.remove("socksProxyHost");
sys_prop.remove("mail.smtp.socketFactory.class");
sys_prop.remove("mail.smtp.socketFactory.fallback");
sys_prop.remove("mail.smtp.socketFactory.port");
}
}
}
Property file 'Email.Properties':
sender=helloqa86#gmail.com
recevier=k.b#xx.com
password=*****
proxyHost=web-proxy.**.**.com
proxyPort= 8080
smtpHost=smtp.gmail.com
smtpPort=465
From the error I can understand that problem is in this part
messageBodyPart.setContent(paragraphs, "application/msword"); where I am adding word document content to MIME message body part.
I have tried several other ways to achieve this but not able to do so. Please suggest a way to achieve this?
I got a resolution to this problem.Actually , I have to put different font face and font sizes in email body which I am trying to read from word document.To achieve this I have changed my approach,so instead of word document I have embedded my content into html tags which is quite simple :) , refer the below line of code which will replace word document part
String htmltext = "+
Different Font Size+
Different Font Size+
";
messageBodyPart.setContent(htmltext, "text/html");
During my research one of my friend suggested me following third party API's , it might be helpful to anyone
http://www.oracle.com/technetwork/java/javamail/third-party-136965.html
https://github.com/bbottema/simple-java-mail/

Why am I getting random errors in my Minecraft 1.7.10 mod using eclipse?

Sorry, I'm not sure if I'm in the right forum or if I'm wording it right. People may call this vague or something. I won't care.
Anyway, I've started to get random errors after trying something. It didn't turn out well. Here's the code + errors of my main mod file.
package com.harry.MoStuff;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
#Mod(modid = "ms", name = "Mo' Stuff", version = "a-1.0")
public class MoStuff {
public static Item itemRuby;
public static Item itemChain;
public static Item itemRubyEssence;
public static Item itemRubyShard;
public static Item itemRedBull;
public static Block blockRubyOre;
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
//Item/block init and registering
//Config handling
itemRuby = new ItemRuby().setUnlocalizedName("ruby").setTextureName("ms:ruby");
itemChain = new ItemChain().setUnlocalizedName("chain");
blockRubyOre = new BlockRubyOre(Material.rock).setBlockName("ruby_ore").setBlockTextureName("ms:ruby_ore");
itemRubyShard = new ItemRubyShard().setUnlocalizedName("ruby_shard");
itemRubyEssence = new ItemRubyEssence().setUnlocalizedName("ruby_essence");
itemRedBull = new ItemFood(8, 1.0F, true).setUnlocalizedName("red_bull").setTextureName("ms:red_bull");
}
GameRegistry.registerItem(itemRuby, itemRuby.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemChain, itemChain.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemRubyShard, itemRubyShard.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemRubyEssence, itemRubyEssence.getUnlocalizedName().substring(5));
GameRegistry.registerBlock(blockRubyOre, blockRubyOre.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemRedBull, itemRedBull.getUnlocalizedName().substring(5));
#EventHandler
public void init(FMLInitializationEvent event) {
//Proxy, tile entity, entity, GUI, packet reg.
GameRegistry.addRecipe(new ItemStack(itemRuby), new Object[]{"RRR","RRR","RRR", 'R', itemRubyShard});
GameRegistry.addRecipe(new ItemStack(itemChain), new Object[] {"III","I I","III", 'I', Items.iron_ingot});
GameRegistry.addRecipe(new ItemStack(itemRubyEssence, 5), new Object[]{" "," R "," ", 'R', itemRuby});
}
#EventHandler
public void postInit(FMLPostInitializationEvent event) {
}
}
The errors are:
Multiple markers at this line (38, where GameRegistry.registerItem(itemRuby) and so on):
Syntax error on token ".", > expected.
Syntax error on token "(", < expected.
Syntax error on token ".", { expected.
Syntax error on token ")", delete this token.
Multiple markers at this line (46, where public void init(params) is.)
Syntax error on token "(", ; expected.
Syntax error on token ")", ; expected.
Multiple markers at this line (54, where public void postInit(params) is.)
Syntax error on token "(", ; expected.
Syntax error on token ")", ; expected.
That's all I can say. Thanks in advance.
On line 37, you closed the brace. Close it after all your GameRegistry.register

Getting started with XMLPullParser

I am trying to use XMLPullParser but I cannot find any useful tutorials. Based off of the instructions on http://xmlpull.org/ I need to download an implementation of XMLPullParser as a jar file and then add it to my class path. However I cannot find any link to any jar file that works. Does anyone know where I might be able to find a jar file I can download.
Thanks
Ok, here it is for you.
From the official doc :
XmlPull API Implementations:
XNI 2 XmlPull
XPP3/MXP1
KXML2
Here i use KXML2.
Steps :
Download KXML2 jar file from here.
Create a new java project
Create a new class
Right click the java project -> Properties -> Java Build path -> Libraries -> Add external jar's -> Add downloaded kxml2 jar file.
Java code
import java.io.IOException;
import java.io.StringReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class XmlPullparserBasic {
public static void main (String args[]) throws XmlPullParserException, IOException
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}
}
Output :
Hope it helps!

AspectJ - Is is possible to extend an enum's value?

Say I have an enum
public enum E {A,B,C}
Is it possible to add another value, say D, by AspectJ?
After googling around, it seems that there used to be a way to hack the private static field $VALUES, then call the constructor(String, int) by reflection, but seems not working with 1.7 anymore.
Here are several links:
http://www.javaspecialists.eu/archive/Issue161.html (provided by #WimDeblauwe )
and this: http://www.jroller.com/VelkaVrana/entry/modify_enum_with_reflection
Actually, I recommend you to refactor the source code, maybe adding a collection of valid region IDs to each enumeration value. This should be straightforward enough for subsequent merging if you use Git and not some old-school SCM tool like SVN.
Maybe it would even make sense to use a dynamic data structure altogether instead of an enum if it is clear that in the future the list of commands is dynamic. But that should go into the upstream code base. I am sure the devs will accept a good patch or pull request if prepared cleanly.
Remember: Trying to avoid refactoring is usually a bad smell, a symptom of an illness, not a solution. I prefer solutions to symptomatic workarounds. Clean code rules and software craftsmanship attitude demand that.
Having said the above, now here is what you can do. It should work under JDK 7/8 and I found it on Jérôme Kehrli's blog (please be sure to add the bugfix mentioned in one of the comments below the article).
Enum extender utility:
package de.scrum_master.util;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;
public class DynamicEnumExtender {
private static ReflectionFactory reflectionFactory =
ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target, Object value)
throws NoSuchFieldException, IllegalAccessException
{
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName)
throws NoSuchFieldException, IllegalAccessException
{
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass)
throws NoSuchFieldException, IllegalAccessException
{
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
throws NoSuchMethodException
{
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass .getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues)
throws Exception
{
Object[] parms = new Object[additionalValues.length + 2];
parms[0] = value;
parms[1] = Integer.valueOf(ordinal);
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
}
/**
* Add an enum instance to the enum class given as argument
*
* #param <T> the type of the enum (implicit)
* #param enumType the class of the enum to be modified
* #param enumName the name of the new enum instance to be added to the class
*/
#SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType))
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
// 1. Lookup "$VALUES" holder in enum class and get previous enum
// instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(
enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(), new Class<?>[] {}, // could be used to pass values to the enum constuctor if needed
new Object[] {} // could be used to pass values to the enum constuctor if needed
);
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
}
Sample application & enum:
package de.scrum_master.app;
/** In honour of "The Secret of Monkey Island"... ;-) */
public enum Command {
OPEN, CLOSE, PUSH, PULL, WALK_TO, PICK_UP, TALK_TO, GIVE, USE, LOOK_AT, TURN_ON, TURN_OFF
}
package de.scrum_master.app;
public class Server {
public void executeCommand(Command command) {
System.out.println("Executing command " + command);
}
}
package de.scrum_master.app;
public class Client {
private Server server;
public Client(Server server) {
this.server = server;
}
public void issueCommand(String command) {
server.executeCommand(
Command.valueOf(
command.toUpperCase().replace(' ', '_')
)
);
}
public static void main(String[] args) {
Client client = new Client(new Server());
client.issueCommand("use");
client.issueCommand("walk to");
client.issueCommand("undress");
client.issueCommand("sleep");
}
}
Console output with original enum:
Executing command USE
Executing command WALK_TO
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant de.scrum_master.app.Command.UNDRESS
at java.lang.Enum.valueOf(Enum.java:236)
at de.scrum_master.app.Command.valueOf(Command.java:1)
at de.scrum_master.app.Client.issueCommand(Client.java:12)
at de.scrum_master.app.Client.main(Client.java:22)
Now you can either add an aspect with an advice executed after the enum class was loaded or just call this manually in your application before extended enum values are to be used for the first time. Here I am showing how it can be done in an aspect.
Enum extender aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.Command;
import de.scrum_master.util.DynamicEnumExtender;
public aspect CommandExtender {
after() : staticinitialization(Command) {
System.out.println(thisJoinPoint);
DynamicEnumExtender.addEnum(Command.class, "UNDRESS");
DynamicEnumExtender.addEnum(Command.class, "SLEEP");
DynamicEnumExtender.addEnum(Command.class, "WAKE_UP");
DynamicEnumExtender.addEnum(Command.class, "DRESS");
}
}
Console output with extended enum:
staticinitialization(de.scrum_master.app.Command.<clinit>)
Executing command USE
Executing command WALK_TO
Executing command UNDRESS
Executing command SLEEP
Et voilà! ;-)

eventhough i change the environmental variables and classpath, while running sqlite jdbc program i get the error stating no class definition doun

im running a jdbc program on Sqlite. though i change the environmental variables or define the classpath of the jar file sqlite-jdbc-3.7.2.jar, i get an error stating ClassNotFoundException: org.sqlite.JDBC... how to rectify it?
my code is`
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args)throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}`
my jar file is sqlite-jdbc-3.7.2.jar
my class path is D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar
my environmental variable is also the same
what should i do?
help pls
i found the solution to my problem...
the class path should be like
`javac Sample.java
java -classpath "D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar";. Sample`
the problem is solved:)

Resources