I'm trying to figure out how to implement Apache Pool 2 (I'm using 2.5). As an initial POC I created an Employee Object with firstName, lastName, employeeId and age (Observer Pattern). I created an EmployeeObjectFactory which implements PooledObjectFactory and in the main class I was trying to add objects of Employee class. But I'm getting a class cast exception(EmployeeObjects cannot be cast to PooledObjects). So what changes do I need to make to my EmployeeObjects?
Employee Class
public class Employee{
private String firstName;
// omitting the getters and setters for other fields
public static class Builder {
private String firstName = "Unsub";
// declared and initialized lastName, emailId and age
public Builder firstName(String val) {
firstName = val;
return this;
}
// Similarly for other values
public EmployeeObject build() {
return new EmployeeObject(this);
}
}
private EmployeeObject(Builder builder) {
firstName = builder.firstName;
// omitting rest of the code
}
}
In the EmployeeObjectFactory
public class EmployeeObjectFactory implements PooledObjectFactory<EmployeeObject> {
#Override
public PooledObject<EmployeeObject> makeObject() {
return (PooledObject<EmployeeObject>) new EmployeeObject.Builder().build(); // This is where I'm getting the class cast
}
// Omitting rest of the code
}
Main Class
public static void main(String arg[]) throws Exception {
GenericObjectPool employeeObjectPool = new GenericObjectPool(new EmployeeObjectFactory());
employeeObjectPool.addObject();
I have tried to add as much little code as possible, because even I hate going through loads of code. Any help would be appreciated.
Finally got the answer after reading through the Apache Docs. DefaultPooledObject is what I need to use. DefaultPooledObject - "Create a new instance that wraps the provided object so that the pool can track the state of the pooled object." In the makeObject() function, I returned a DefaultPooledObject. So my code would look like
#Override
public PooledObject<EmployeeObject> makeObject() {
return new DefaultPooledObject<>(new EmployeeObject.Builder().build());
}
Related
I have created a simple class:
public class Example
{
private String name;
private int age;
// With getters and setters.
}
that I would like "put" into a chronicle map:
ChronicleMap<String,Example> map = ChronicleMapBuilder
.of(String.class, Example.class)
.name("example-map")
.entries(5_000)
.averageValue(new Example())
.valueMarshaller(ExampleSerializer.getInstance())
.averageKey("Horatio")
.createPersistedTo(new File("../logs/example.txt"));
However, I do not fully understand how to implement the ExampleSerializer class because I am not sure how the string member variables should be handled. How do I size strings? In the read and write methods, how do I read the string member variable, and how do I write the string member variable respectively. Pls note that on average, the name member string length will be between 7-10 characters. I have created the serializer below:
public class ExampleSerializer implements SizedReader<Example>,SizedWriter<Example>
{
private static ExampleSerializer INSTANCE = new ExampleSerializer();
public static ExampleSerializer getInstance() { return INSTANCE; }
private ExampleSerializer() {}
#NotNull
#Override
public Example read(Bytes in, long size, #Nullable Example using)
{
if (using == null)
using = new Example();
using.setAge(in.readInt());
using.setName(in.readUtf8()); // NOT SURE IF THIS IS CORRECT FOR A STRING
return using;
}
#Override
public long size(#NotNull Example toWrite)
{
return Integer.BYTES + ???; // NOT SURE WHAT THE SIZE SHOULD BE FOR STRING MEMBER?
}
#Override
public void write(Bytes out, long size, #NotNull Example toWrite)
{
out.writeInt(toWrite.getAge());
out.writeUtf8(toWrite.getName()); // NOT SURE IF THIS IS CORRECT FOR A STRING
}
}
Scenario 1 :
I am generating a report for more department's performance and participation in a institute. When I am display the report in GUI, it can be sort by department performance and participation(No.of student participated).
For this scenario, should i use Prototype Design pattern?
Ex :
public abstract class Report implements Cloneable {
private String id;
protected String type;
public void setId(String id){
id=id;
}
public String getId(){
return id;
}
public String getType(){
return type;
}
abstract void getReportData();
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
public class PerformanceReport extends Report {
public PerformanceReport(){
type = "Performance";
}
#Override
public void getReportData() {
/* Get report data from database and sort based on performance*/
}
}
public class ParticipationReport extends Report {
public ParticipationReport(){
type = "Participation";
}
#Override
public void getReportData() {
/* Get report data from database and sort based on participation*/
}
}
public class ReportCache {
private static Hashtable<String, Report> reportMap = new Hashtable<String, Report>();
public static Report getReport(String reportid) {
Report cachedReport = reportMap.get(reportid);
return (Report) cachedReport.clone();
}
public static void loadCache() {
ParticipationReport participationReport = new ParticipationReport();
participationReport.setId("1");
reportMap.put(report.getId(),report);
PerformanceReport performanceReport = new PerformanceReport();
performancenReport.setId("2");
reportMap.put(report.getId(),report);
}
}
public class PrototypePatternReport {
public static void main(String[] args) {
ReportCache.loadCache();
Report clonedReport = (Report) ReportCache.getReport("1");
System.out.println("Report : " + clonedReport.getType());
Report clonedReport2 = (Report) ReportCache.getReport("2");
System.out.println("Report : " + clonedReport2.getType());
}
}
Is my above concept is correct ? and this concept is relevant to Prototype-pattern?
Scenario 2 :
I am storing quiz detail (questions and options, answers) in a object, while student request for quiz, I should encrypt the answer and give. For encrypted answer i should keep another object to give. I this scenario can i use prototype? After response come from student I should compare the student answer with existing object.
Prototype pattern is often useful when object initialization is expensive or when you explicitly need an object that is a copy of another.
Scenario 1:
In your case, getting report data from database and sorting it is much more expensive than instantiating an object, and each report will consist on its own data (you will not benefit from copying from another object) so I would not consider using a prototype.
Scenario 2:
In this scenario, the key is
For encrypted answer i should keep another object to give
In this case, as you need another object and you need to ensure that the second object is an exact copy of the first, you could use a prototype to create the second object, and then change its properties to ensure that the answers are hidden.
maybe anybody could help me out. i'm working with Data access object.
i have a database:
table Receiverz
num name
1 Walmart
2 Target
3 McDonalds
i've created a class for this table
public class Receiverz {
private int num;
private String name;
public void setNum(int num) {
this.num = num;
}
public void setName(String name) {
this.name = name;
}
}
then i created Dao interface and passed a method to it:
public interface Dao {
Receiverz getReceiverz(int num);}
Then i created a class ExpensesDao that implements Dao and created a singleton in it(i aslo set up the connection with database but i will skip that part) and overrode getReceivers(int num) method by making it possible to work with database:
public class ExpensesDao implements Dao {
private static Dao thisdao;
public static synchronized Dao getDao() {
if (thisdao==null) {
thisdao = new ExpensesDao();
}
return thisdao;
}
#Override
public Receiverz getReceiverz(int num) {
Receiverz receiver = new Receiverz();
try {
Statement stmt = myConnection.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM receiverz");
while(result.next()){
receiver.setNum(num);
receiver.setName(result.getString(2));
}
}
catch (SQLException e){
System.out.println(e.getMessage());
}
return receiver;
}
when i try to run it in main class:
public class TryDatabase {
public static void main(String[] args) {
Dao ex = ExpensesDao.getDao();
System.out.println(ex.getReceiverz(2));
all i get is:
listexpenses.Receiverz#193499fd
but i have to get
2 Target
(since i passed 2 in the parameters and it refers to Target in my database.
does anyone know what's going wrong and what i should change in my code. P.S. i hope i made it clear enough.
ex.getReceiverz(2) is returning a Receiverz object. Thus the System.out.println(ex.getReceiverz(2)); is using the toString() method inherited from java.lang.Object. Create a toString() method in the Receiverz class that will output it the way you want.
add a getName to your recieverz and change to this ex.getReceiverz(2).getName()
A bit offtopic, but I recommend the double checked locking singleton code to avoid all concurrency issues in initalization.
Ps.: ex.getReceiverz(2).getName() breaks Law of Demeter, might be better to avoid it.
I have encountered a weird problem in my app (java).
I have an enum. Something like that
public enum myEnum implement myIntrface{
valueA(1),valueb(2),valuec(3),valued(4)
private int i;
// and then - a constructor
public MyEnum(int number){
i = number;
}
private MyObj obj = new MyObj;
// getter and setter for obj
}
and in another class I have this
MyEnum.valueA.setObj(new Obj(...))
in briefe - I have an enum with a private instance member that has a set and a get.
So far so good -
The only thing that amazes me is that later on I look at the value of the MyEnum.valueA().obj is null.
there is nothing that updates the value to null, I have even gave it a default value in the constructor and I still see it null later.
any suggestions?
Enums should be un-modifiable classes so you shouldn't really be doing this. If your looking to modify the state of a type based object like an enum you should use an final class approach with embedded constants. Below is an example of a class based approach with a modifiable name an a un-modifiable name...
public final class Connection {
public static final Connection EMAIL = new Connection("email");
public static final Connection PHONE = new Connection("phone");
public static final Connection FAX = new Connection("fax");
/**/
private final String unmodifiableName; //<-- it's final
private String modifiableName;
/*
* The constructor is private so no new connections can be created outside.
*/
private Connection(String name) {
this.unmodifiableName = name;
}
public String getUnmodifiableName() {
return unmodifiableName;
}
public String getModifiableName() {
return modifiableName;
}
public void setModifiableName(String modifiableName) {
this.modifiableName = modifiableName;
}
}
The purpose of enums is to represent constant values. It does not make any sense to set the fields of a constant value.
You should declare your fields as final, and use the constructor to initialize all of them.
For reference, the following code works as expected:
public class Test {
public static enum MyEnum {
valueA(1),valueb(2),valuec(3),valued(4);
private int i;
private Object o;
private MyEnum(int number) {
i = number;
}
public void set(Object o) {
this.o = o;
}
public Object get() {
return o;
}
}
public static void main(String[] args) {
System.out.println(MyEnum.valueA.get()); // prints "null"
MyEnum.valueA.set(new Integer(42));
System.out.println(MyEnum.valueA.get()); // prints "42"
}
}
the cause of this problem is the db40 framework . It loads an enum from the db using reflection. This is well documented .
http://developer.db4o.com/Forums/tabid/98/aft/5439/Default.aspx
I am trying to use SOJO to serialize a Java object to CSV. The example looks pretty straight forward:
Car car = new Car("My Car");
car.setDescription("This is my car.");
Serializer csvSerializer = new CsvSerializer();
String csvStr = (String) csvSerializer.serialize(car);
System.out.println(csvStr);
// print:
// description,build,properties,name,~unique-id~,class
// This is my car.,,,My Car,0,test.net.sf.sojo.model.Car
I tried implementing my own version of the example. I made a really simple Car class with two String fields (build and description) which implements a setDescription(..) method.
This is what I implemented:
import net.sf.sojo.interchange.csv.CsvSerializer;
public class Main {
private class Car
{
private String build;
private String description;
public Car(String build) {
this.build = build;
this.description = null;
}
public void setDescription(String description) {
this.description = description;
}
}
public static void main(String[] args) {
Main m = new Main();
Car car = m.new Car("My Car");
car.setDescription("This is my car.");
CsvSerializer csvSerializer = new CsvSerializer();
String csvStr = (String) csvSerializer.serialize(car);
System.out.println(csvStr);
}
}
However, when I run my implementation I get the following output:
~unique-id~,class,description
0,Main$Car,
I don't understand why in my implementation neither the build or description fields are serialized, can you help?
Cheers,
Pete
From the SOJO home page: "The intention for this project is a Java framework, that convert JavaBeans in a simplified representation"
The Car object in your example does not qualify. You must have a getter (and, probabaly, a setter as well) for every property that you wish SOJO to write to (or read from) your file. Add getBuild() and getDescription()
I haven't used SOJO, but for private fields you probably need getter methods; or you could try declaring the fields public.