factory method pattern with class registration produces a nullpointer exception - java

well, i searched the internet to this problem but didn't find any proper solution
in http://www.oodesign.com/factory-pattern.html
the author described away to register classes using reflection or object creation
i tried the object creation approach by the following code:
the factory class
package com.mf.egyptse;
import java.util.HashMap;
public abstract class ParserFactory {
private static HashMap parsers;
static
{
parsers= new HashMap();
System.out.println("This is first static block");
}
static void putParser(Object key,Object parser)
{
parsers.put(key, parser);
}
static Object getParser(Object key)
{
return parsers.get(key);
}
}
each parser register itself in the factory:
public class NormalParser extends ParserFactory implements ParsingBehavior{
/**
* Define the number of nested columns or tags to be parsed
*/
final static int NO_OF_COLOUMNS = 13;
static String input = null;
static String[] elements= {"name","sector", "p.c", "open", "close", "chgpercent", "lastprice", "high", "low","value","volume","trades","marketcap"};
static
{
ParserFactory.putParser("normal", new NormalParser());
}
and the main is :
public class Main {
/**
* #param args
* #throws IOException
* #throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
// NileParser.parseNile();
// OTCParser.parseOTC();
// NormalParser.parseNormal();
ParsingBehavior parser = (ParsingBehavior) ParserFactory.getParser("normal");
parser.parseToXML(null, null);
}
}
the interface is:
package com.mf.egyptse;
import java.io.File;
import java.io.IOException;
public interface ParsingBehavior {
void parseToXML(CharSequence input,File file) throws IOException;
}
this code return always nullpointer exception while executing. the porblem is that the static block don't executed. so what is the solution ?

As answered by "Snicolas", your problem is that the HashMap is not populated by the time its being used. Your static block in main should load all the necessary parser classes such that these classes register themselves first.
public class Main {
static {
// Load necessary parser classes
Class.forName("normal");
}
/**
* #param args
* #throws IOException
* #throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
ParsingBehavior parser = (ParsingBehavior) ParserFactory.getParser("normal");
parser.parseToXML(null, null);
}
}

Getparser should return a ParsingBehavior.
Cast inside it.
But your problem comes from the fact that your parser class is not loaded by the jvm, as it is not used by your main. So static code is not executed.
Your are mixing your factory with a bus. Let the main register your parser in the factory.

Related

Java - Avoid create empty sub Class & Interface or generate Java source code template

I am developing a java web project using Spring and Mybatis.
In the dao level, I defined a super class and a super interface which implemented all common methods.
Thus when create sub class or interface for a specific model in dao level, I only need to implement the super dao class & interface, and left the class body and interface body empty.
Over half of the sub dao level class & interface is empty through all the time.
(Example of the empty dao class & interface:)
RoleDao.java
package core.dao;
import core.dao.base.BaseDao;
import core.model.Role;
public interface RoleDao extends BaseDao<Role> {
}
RoleDaoImpl.java
package core.dao.impl;
import org.springframework.stereotype.Repository;
import core.dao.RoleDao;
import core.dao.base.BaseDaoImpl;
import core.model.Role;
#Repository
public class RoleDaoImpl extends BaseDaoImpl<Role> implements RoleDao {
}
My question is:
Is there a good way to avoid writing these empty class & interface, while still could use them?
I am thinking of using Code generator to generate these class file, or use Java reflection to create such class & interface at runtime as need, but didn't get into detail yet.
#Update
It seems not flexible to achieve the target without creating source code, so I decided to write some simple java source code generator for java web project.
And a tool called codemodel is very suitable to do that, it is developed by Sun, and now owned by Oracle I guess.
And, I gave an answer by myself with code that I wrote to generate java source code.
The Repository classes for the classes in our projects that use QueryDSL and JPA only have an interface, but not an implementation. However, it does not answer the question whether it is possible to directly generate these repositories based on the entity classes, although it would be similar to what the Apt Maven Plugin does to create the QEntity classes for use with QueryDSL.
#NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, QueryDslPredicateExecutor<T> {
}
#Repository
public interface DummyDataRepository extends BaseRepository<DummyData, Long> {
}
About a month ago I was asking myself the same thing :)
So, seems that we have a kind of solution, since you are using Spring library. As I read on docs:
Rather than code data access objects (DAOs) manually using
SqlSessionDaoSupport or SqlSessionTemplate, Mybatis-Spring provides a
proxy factory: MapperFactoryBean. This class lets you inject data
mapper interfaces directly into your service beans. When using mappers
you simply call them as you have always called your DAOs, but you
won't need to code any DAO implementation because MyBatis-Spring will
create a proxy for you.
There's an example on GitHub and also on this MyBatis' page.
I hope that it gives you some insights, because maybe it isn't feasible refactoring your whole system to be benefited of such nice feature.
I just wrote a simple code generator for my project.
It's just a single class, and could generate model/dao/service/action level code template for 1 or more models in a single execution.
Dependence:
It use codemodel and apache commons-io lib, and it's a spring + springMVC project.
How to use it:
It import some base class/interface in my project, from which the generated class extends/implements from, so you might can't run it directly. But you can create them as empty class/interface, or remove them from the genSourceXxx() function.
CodeGenerator.java:
package my.project.util;
import my.project.dao.base.BaseDao;
import my.project.dao.base.BaseDaoImpl;
import my.project.model.base.BaseIdModel;
import my.project.service.base.BaseService;
import my.project.service.base.BaseServiceImpl;
import my.project.web.action.base.BaseAction;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import com.sun.codemodel.ClassType;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JClassAlreadyExistsException;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
/**
* code generator
*
* #author eric
* #date Apr 10, 2015 3:32:57 PM
*/
public class CodeGenerator {
// location of source folder
public static final String tmpSourceFolderBaseLocation = "/tmp/java_code/"; // tmp location for generated code,
public static final String actualSourceFolderBaseLocation = "/mnt/star/workplace/eclipse_j2ee_workplace/project-name/source/java/"; // actual source folder,
// package
public static final String packageSeparator = ".";
public static final String basePackage = "my.project";
public static final String modelPackage = "model";
public static final String daoPackage = "dao";
public static final String daoImplPackage = "dao.impl";
public static final String servicePackage = "service";
public static final String serviceImplPackage = "service.impl";
public static final String actionPackage = "web.action";
// source file path
public static final String pkgPathSeparator = File.separator;
public static final String sourceSuffix = ".java";
public static final String basePkgPath = "my/project";
public static final String modelPkgPath = "model";
public static final String daoPkgPath = "dao";
public static final String daoImplPkgPath = "dao" + pkgPathSeparator + "impl";
public static final String servicePkgPath = "service";
public static final String serviceImplPkgPath = "service" + pkgPathSeparator + "impl";
public static final String actionPkgPath = "web" + pkgPathSeparator + "action";
// naming
public static final String daoSuffix = "Dao";
public static final String daoImplSuffix = "DaoImpl";
public static final String serviceSuffix = "Service";
public static final String serviceImplSuffix = "ServiceImpl";
public static final String actionSuffix = "Action";
// compiler for generated source code,
public static final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// classloader for compiled class,
public static final ClassLoader cl = genCl(tmpSourceFolderBaseLocation);
/**
* compile a source file,
*
* #param sourcePath
* #throws MalformedURLException
*/
public static void compileSource(String sourcePath) throws MalformedURLException {
// set this so that won't get compile error,
System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + tmpSourceFolderBaseLocation);
compiler.run(null, null, null, sourcePath);
}
/**
* generate a classloader,
*
* #param path
* #return
* #throws MalformedURLException
*/
public static ClassLoader genCl(String path) {
ClassLoader cl = null;
try {
cl = new URLClassLoader(new URL[] { new File(path).toURI().toURL() });
} catch (MalformedURLException e) {
e.printStackTrace();
}
return cl;
}
/**
* <p>
* Generate source for model.
* </p>
*
* #param modelName
* #throws IOException
* #throws JClassAlreadyExistsException
*/
public static void genSourceModel(String modelName) throws IOException, JClassAlreadyExistsException {
String modelFullName = genFullName(modelPackage, modelName);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(modelFullName, ClassType.CLASS);
// extends
dc._extends(BaseIdModel.class);
// id
JFieldVar idField = dc.field(JMod.PRIVATE, Integer.class, "id"); // field
// id - getter method
JMethod getIdMethod = dc.method(JMod.PUBLIC, Integer.class, "getId");
getIdMethod.body()._return(idField);
getIdMethod.annotate(cm.ref(Override.class)); // annotation - override
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(modelPkgPath, modelName));
}
public static void genSourceDao(String modelName) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
String daoFullName = genFullName(daoPackage, modelName, daoSuffix);
String modelFullName = genFullName(modelPackage, modelName);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(daoFullName, ClassType.INTERFACE);
// extends
JClass superClazz = cm.ref(BaseDao.class).narrow(cl.loadClass(modelFullName));
dc._extends(superClazz);
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(daoPkgPath, modelName, daoSuffix));
}
public static void genSourceDaoImpl(String modelName) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
String daoImplFullName = genFullName(daoImplPackage, modelName, daoImplSuffix);
String daoFullName = genFullName(daoPackage, modelName, daoSuffix);
String modelFullName = genFullName(modelPackage, modelName);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(daoImplFullName, ClassType.CLASS);
dc.annotate(Repository.class);
// extends
JClass superClazz = cm.ref(BaseDaoImpl.class).narrow(cl.loadClass(modelFullName));
dc._extends(superClazz);
// implements
dc._implements(cl.loadClass(daoFullName));
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(daoImplPkgPath, modelName, daoImplSuffix));
}
public static void genSourceService(String modelName) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
String serviceFullName = genFullName(servicePackage, modelName, serviceSuffix);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(serviceFullName, ClassType.INTERFACE);
// extends
dc._extends(BaseService.class);
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(servicePkgPath, modelName, serviceSuffix));
}
public static void genSourceServiceImpl(String modelName, boolean serviceTransaction) throws JClassAlreadyExistsException, ClassNotFoundException,
IOException {
String serviceImplFullName = genFullName(serviceImplPackage, modelName, serviceImplSuffix);
String serviceFullName = genFullName(servicePackage, modelName, serviceSuffix);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(serviceImplFullName, ClassType.CLASS);
// annotation
dc.annotate(Service.class);
if (serviceTransaction) {
dc.annotate(Transactional.class);
}
// extends
dc._extends(BaseServiceImpl.class);
// implements
dc._implements(cl.loadClass(serviceFullName));
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(serviceImplPkgPath, modelName, serviceImplSuffix));
}
public static void genSourceAction(String modelName) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
genSourceAction(modelName, null);
}
/**
* generate action,
*
* #param modelName
* #param rootMappingPath
* root mapping path, if null or empty then don't have this annotation,
* #throws JClassAlreadyExistsException
* #throws ClassNotFoundException
* #throws IOException
*/
public static void genSourceAction(String modelName, String rootMappingPath) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
String actionFullName = genFullName(actionPackage, modelName, actionSuffix);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(actionFullName, ClassType.CLASS);
// annotation
dc.annotate(Controller.class);
if (StringUtils.isNotBlank(rootMappingPath)) {
dc.annotate(cm.ref(RequestMapping.class)).param("value", rootMappingPath);
}
// extends
dc._extends(BaseAction.class);
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(actionPkgPath, modelName, actionSuffix));
}
/**
* <p>
* generate a serial java source code base on a single model, don't include service level,
* </p>
* <p>
* Warning: this will override existing code, so, be careful!
* </p>
*
* #param modelName
*/
public static void genStack(String modelName) {
genStack(modelName, false, false, null);
}
/**
* <p>
* generate a serial java source code base on a single model.
* </p>
* <p>
* Warning: this will override existing code, so, be careful!
* </p>
*
* #param modelName
* #param includeService
* specify whether include service level,
* #param serviceTransaction
* whether add transaction annotation to service impl class,
* #param actionRootMappingPath
* root mapping path, if null or empty then don't have this annotation,
*/
public static void genStack(String modelName, boolean includeService, boolean serviceTransaction, String actionRootMappingPath) {
try {
initTmp(); // clean or create folder,
// generate code - start
genSourceModel(modelName);
genSourceDao(modelName);
genSourceDaoImpl(modelName);
if (includeService) {
genSourceService(modelName);
genSourceServiceImpl(modelName, serviceTransaction);
}
genSourceAction(modelName, actionRootMappingPath);
// generate code - end
merge(); // copy,
initTmp(); // clean, so that won't have duplicated class,
} catch (IOException | JClassAlreadyExistsException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* <p>
* batch generate.
* </p>
* <p>
* Warning: this will override existing code, so, be careful!
* </p>
*
* #param models
* map of "modelName : actionRootMappingPath"
* #param includeService
* specify whether include service level,
* #param serviceTransaction
* whether add transaction annotation to service impl class,
*/
public static void genStackBatch(Map<String, String> models, boolean includeService, boolean serviceTransaction) {
for (String modelName : models.keySet()) {
genStack(modelName, includeService, serviceTransaction, models.get(modelName));
}
}
/**
* generate class fullname,
*
* #param subPackage
* #param modelName
* #return
*/
public static String genFullName(String subPackage, String modelName) {
return genFullName(subPackage, modelName, "");
}
/**
* generate class fullname,
*
* #param subPackage
* #param modelName
* #param suffix
* #return
*/
public static String genFullName(String subPackage, String modelName, String suffix) {
return new StringBuilder().append(basePackage).append(packageSeparator).append(subPackage).append(packageSeparator).append(modelName).append(suffix)
.toString();
}
/**
* generate source file path,
*
* #param subPkgPath
* #param modelName
* #return
*/
public static String genFullPath(String subPkgPath, String modelName) {
return genFullPath(subPkgPath, modelName, "");
}
/**
* generate source file path,
*
* #param subPkgPath
* #param modelName
* #param suffix
* #return
*/
public static String genFullPath(String subPkgPath, String modelName, String suffix) {
return new StringBuilder().append(tmpSourceFolderBaseLocation).append(basePkgPath).append(pkgPathSeparator).append(subPkgPath).append(pkgPathSeparator)
.append(modelName).append(suffix).append(sourceSuffix).toString();
}
/**
* clean tmp location,
*
* #throws IOException
*/
public static void initTmp() throws IOException {
File tmp = new File(tmpSourceFolderBaseLocation);
if (!tmp.exists()) { // create if not exists,
tmp.mkdirs();
} else { // clean if exists,
FileUtils.cleanDirectory(tmp);
}
}
/**
* <p>
* move generated code into source folder,
* </p>
* <p>
* Warning: this will override existing code, so, be careful!
* </p>
*/
public static void merge() {
File originalFile = new File(tmpSourceFolderBaseLocation + basePkgPath);
File targetFile = new File(actualSourceFolderBaseLocation + basePkgPath);
try {
// filter - java file,
IOFileFilter javaSuffixFilter = FileFilterUtils.suffixFileFilter(".java");
IOFileFilter javaFiles = FileFilterUtils.and(FileFileFilter.FILE, javaSuffixFilter);
// filter - dir or java file,
FileFilter filter = FileFilterUtils.or(DirectoryFileFilter.DIRECTORY, javaFiles);
FileUtils.copyDirectory(originalFile, targetFile, filter);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// String modelName = "LoginHistory";
// String actionRootMappingPath = "/loginHistory";
// genStack(modelName, true, false, actionRootMappingPath);
Map<String, String> models = new HashMap<String, String>();
models.put("AdminAccount", "/adminAccount");
models.put("CustomerAccount", "/customerAccount");
models.put("Role", "/role");
genStackBatch(models, true, true);
}
}

run excel using com interface

am trying to run excel using jacob , but it keeps throwing an exception , been searching for awhile for a cause of such exception , but no good
package com.se.jaexcel;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class JExcel {
/**
* #param args
*/
public static void main(String[] args) {
ActiveXComponent xl = new ActiveXComponent("Excel.Application");
}
}
the exception is
Exception in thread "main" com.jacob.com.ComFailException: Can't QI object for IDispatch
at com.jacob.com.Dispatch.createInstanceNative(Native Method)
at com.jacob.com.Dispatch.<init>(Dispatch.java:99)
at com.jacob.activeX.ActiveXComponent.<init>(ActiveXComponent.java:58)
at com.se.jaexcel.JExcel.main(JExcel.java:14)
you are not loading any native dll. In the example below c:\myapp\lib contains jacob-1.18-M2-x64.dll and jacob-1.18-M2-x86.dll. If you do not want to load them from a static location, see http://www.javaquery.com/2013/12/getting-started-with-jacob-example-with.html to see how you can load the DLL's from a resource.
private static void loadLibrary(final String appDir) throws IOException {
final String libFile = "amd64".equals(System.getProperty("os.arch")) ?
"/jacob-1.18-M2-x64.dll" : "/jacob-1.18-M2-x86.dll";
System.setProperty(LibraryLoader.JACOB_DLL_PATH,
Paths.get(appDir, "lib", libFile).toString());
LibraryLoader.loadJacobLibrary();
}
public static void main(String[] args) {
loadLibrary("c:\\myapp");
ActiveXComponent xl = new ActiveXComponent("Excel.Application");
}

Exception Exception is not compatible with throws clause in Server.main(String[]) [duplicate]

This question already has answers here:
What are reasons for Exceptions not to be compatible with throws clauses?
(4 answers)
Closed 4 years ago.
I'm running the Lip reading code on Eclipse Indigo from the following link :
https://github.com/sagioto/LipReading/blob/master/lipreading-core/src/main/java/edu/lipreading/WebFeatureExtractor.java
package main.java.edu.lipreading;
import com.googlecode.javacpp.BytePointer;
import com.googlecode.javacv.cpp.opencv_core;
import main.java.edu.lipreading.vision.AbstractFeatureExtractor;
import main.java.edu.lipreading.vision.NoMoreStickersFeatureExtractor;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketHandler;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.logging.Logger;
import static com.googlecode.javacv.cpp.opencv_core.CV_8UC1;
import static com.googlecode.javacv.cpp.opencv_core.cvMat;
import static com.googlecode.javacv.cpp.opencv_highgui.cvDecodeImage;
/**
* Created with IntelliJ IDEA.
* User: Sagi
* Date: 25/04/13
* Time: 21:47
*/
public class WebFeatureExtractor extends Server {
private final static Logger LOG = Logger.getLogger(WebFeatureExtractor.class.getSimpleName());
private final static AbstractFeatureExtractor fe = new NoMoreStickersFeatureExtractor();
public WebFeatureExtractor(int port) {
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(port);
addConnector(connector);
WebSocketHandler wsHandler = new WebSocketHandler() {
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new FeatureExtractorWebSocket();
}
};
setHandler(wsHandler);
}
/**
* Simple innerclass that is used to handle websocket connections.
*
* #author jos
*/
private static class FeatureExtractorWebSocket implements WebSocket, WebSocket.OnBinaryMessage, WebSocket.OnTextMessage {
private Connection connection;
public FeatureExtractorWebSocket() {
super();
}
/**
* On open we set the connection locally, and enable
* binary support
*/
#Override
public void onOpen(Connection connection) {
LOG.info("got connection open");
this.connection = connection;
this.connection.setMaxBinaryMessageSize(1024 * 512);
}
/**
* Cleanup if needed. Not used for this example
*/
#Override
public void onClose(int code, String message) {
LOG.info("got connection closed");
}
/**
* When we receive a binary message we assume it is an image. We then run this
* image through our face detection algorithm and send back the response.
*/
#Override
public void onMessage(byte[] data, int offset, int length) {
//LOG.info("got data message");
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
bOut.write(data, offset, length);
try {
String result = convert(bOut.toByteArray());
this.connection.sendMessage(result);
} catch (Exception e) {
LOG.severe("Error in facedetection, ignoring message:" + e.getMessage());
}
}
#Override
public void onMessage(String data) {
LOG.info("got string message");
}
}
public static String convert(byte[] imageData) throws Exception {
opencv_core.IplImage originalImage = cvDecodeImage(cvMat(1, imageData.length, CV_8UC1, new BytePointer(imageData)));
List<Integer> points = fe.getPoints(originalImage);
if(points == null)
return "null";
String ans = "";
for (Integer point : points) {
ans += point + ",";
}
return ans;
}
/**
* Start the server on port 999
*/
public static void main(String[] args) throws Exception {
WebFeatureExtractor server = new WebFeatureExtractor(9999);
server.start();
server.join();
}
}
In the following line :
public static void main(String[] args) throws Exception {
I'm getting the following error :
Exception Exception is not compatible with throws clause in Server.main(String[])
Please help me solve this.
There are two condition you need to check.
1) when declaring a method in interface you need to add throws exception for that method and similarly with the interface implementation class where the method is implemented.
for example
service.java
#Component
public interface UserService {
User getUser(Login login) throws Exception;
}
serviceimpl.java
public User getUser(Login login)throws Exception
{
}
2) by doing the above statement the error still doesn't vanish. make sure to save both the files.
Doest the server API handle all exceptions for itself. Why not try removing the throws in your code. I know its not good programming practice but might solve the problem.
The problem is that the Server class you are extending already contains a public static void main(String[]) method that does not have the same throws declaration. I didn't take a look at it, but I'd bet that method doesn't throw anything at all.
A solution would be to remove your throws clause in your main method and rely on try-catches instead.
EDIT: Why you cannot add a different throws clause in your case.
Let's assume the following scenario:
class A {
public static void foo() throws SomeException { ... }
}
class B extends A {
public static void foo() throws DifferentException { ... }
}
The Java standard says you are hiding the A.foo() method (or at least trying to). Thing is, you're only allowed to do that if the throws clause in B.foo() is already contained in the clause of A.foo(). So for the above scenario, you're perfectly legal only if DifferentException is a subclass of SomeException. Otherwise the compiler will yell.
I had the same issue, in my case I have implemented a method from an interface that did not declared to throw an exception.
In your case, I would guess that Server class also has a main method that didn't throw an exception. To quickly solve it. I would declare Server.main to throw an exception.
This link helped me
What are reasons for Exceptions not to be compatible with throws clauses?

JUnit Testing - What am I doing Wrong

I am very new to JUnit testing, I am trying to test the following very simple class
public interface IItemsService extends IService {
public final String NAME = "IItemsService";
/** Places items into the database
* #return
* #throws ItemNotStoredException
*/
public boolean storeItem(Items items) throws ItemNotStoredException;
/** Retrieves items from the database
*
* #param category
* #param amount
* #param color
* #param type
* #return
* #throws ItemNotFoundException
*/
public Items getItems (String category, float amount, String color, String type) throws ItemNotFoundException;
}
This is what I have for the test but I keep getting null pointer, and another error about it not being applicable for the argument... obviously I am doing something stupid but I am not seeing it. Could someone point me in the right direction?
public class ItemsServiceTest extends TestCase {
/**
* #throws java.lang.Exception
*/
private Items items;
private IItemsService itemSrvc;
protected void setUp() throws Exception {
super.setUp();
items = new Items ("red", 15, "pens", "gel");
}
IItemsService itemsService;
#Test
public void testStore() throws ItemNotStoredException {
try {
Assert.assertTrue(itemSrvc.storeItem(items));
} catch (ItemNotStoredException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println ("Item not stored");
}
}
#Test
public void testGet() throws ItemNotStoredException {
try {
Assert.assertFalse(itemSrvc.getItems(getName(), 0, getName(), getName()));
} catch (ItemNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You're not creating an instance of the class under test, you're only declaring it as the interface. In each of your tests you should create an instance of the class under test and test it's implementation of the method. Note also, your tests should not be dependent on one another. You shouldn't rely on them running in particular order; any set up for a test should be done in the test set up method, not by another test.
Generally you want to use the AAA (Arrange, Act, Assert) pattern in your tests. The setUp (arrange) and tearDown (assert) can be part of this, but the pattern should also be reflected in each test method.
#Test
public void testStore() throws ItemNotStoredException {
// Arrange
ISomeDependency serviceDependency = // create a mock dependency
IItemsService itemSvc = new ItemsService(someDependency);
// Act
bool result = itemSrvc.storeItem(items);
// Assert
Assert.assertTrue(result);
// assert that your dependency was used properly if appropriate
}

How can I create a static final java.net.URL?

My question is simple. I'm trying to make a set of java.net.URLs that are public static final, so that any class can access them from any context, as these URLs won't change during runtime. However, when I try to create them, I get a compiler error telling me that I must catch or declare thrown a java.net.MalformedURLException, but that is impossible outside a method. Is there any way to circumvent such a constructor that throws a non-java.lang Throwable?
Some dummy code below to visualize my problem:
public class Main
{
public static final java.net.URL STATIC_URL = new java.net.URL("http://example.com/");
public static void main(String[] args)
{
GUI gui = new GUI();
gui.setVisible(true);
}
}
public class GUI extends java.awt.Window
{
public GUI()
{
add(new java.awt.Label(Main.STATIC_URL.toString()));
}
}
If you try to compile this, it will tell you that you can't because of line 3. Hence my question.
An "alternative" which I'd prefer to #HosamAly method:
private static final java.net.URL STATIC_URL = makeUrl("http://www.example.com");
public static java.net.URL makeUrl(String urlString) {
try {
return new java.net.URL(urlString);
} catch (java.net.MalformedURLException e) {
return null; //Or rethrow an unchecked exception
}
}
Use a static initializer:
public class Main {
private static final java.net.URL STATIC_URL;
static {
java.net.URL temp;
try {
temp = new java.net.URL("http://www.example.com");
} catch (java.net.MalformedURLException e) {
temp = null;
}
STATIC_URL = temp;
}
}
Note: The usage of a temporary variable is required to avoid a compilation error about assigning to the final static field twice. If the field is not final, the assignment could be done directly.
If you're sure you want to hardwire a URL. Are you sure? java.net.URL is one of the most comprehensively broken classes in the JDK. In regards to use as a "constant", there is DNS lookup involved and it uses a mutable static (albeit one guarded by a security check, if you have a SecurityManager installed).
If it's just one, a static initialiser should be fine.
private static final java.net.URL STATIC_URL;
static {
try {
STATIC_URL = new java.net.URL("http://example.com/");
} catch (java.net.MalformedException exc) {
throw new Error(exc);
}
}
(Note, you can't qualify the static field name with the class name.)
Note: You really do not want a null - throw an error of some sort and stop the class loading. I've made the constant private as it really isn't the sort of thing you want dependencies on.
If you have lots, then a method for the common code and assignment at the site of the definition is appropriate.
private static final java.net.URL STATIC_URL = constantURL("http://example.com/");
private static URL constantURL(String str) {
try {
return new java.net.URL("http://example.com/");
} catch (java.net.MalformedException exc) {
throw new Error(exc);
}
}
Again, no nulls!
The only way I got this to compile is by removing final and using the static initializer block.
/**
*
*/
package com.neurologic.example;
import java.net.MalformedURLException;
import java.net.URL;
/**
* #author The Elite Gentleman
* #since 06 December 2011
*
*/
public class StaticUrlTest {
public static URL url = null;
static {
try {
url = new URL("http://www.google.com");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}

Categories