In my GWT web application I have a textbox that holds a price.
How can one convert that String to a BigDecimal?
The easiest way is to create new text box widget that inherits ValueBox.
If you do it this way, you won't have to convert any string values manually. the ValueBox takes care of it all.
To get the BigDecimal value entered you can just go:
BigDecimal value = myTextBox.getValue();
Your BigDecimalBox.java:
public class BigDecimalBox extends ValueBox<BigDecimal> {
public BigDecimalBox() {
super(Document.get().createTextInputElement(), BigDecimalRenderer.instance(),
BigDecimalParser.instance());
}
}
Then your BigDecimalRenderer.java
public class BigDecimalRenderer extends AbstractRenderer<BigDecimal> {
private static BigDecimalRenderer INSTANCE;
public static Renderer<BigDecimal> instance() {
if (INSTANCE == null) {
INSTANCE = new BigDecimalRenderer();
}
return INSTANCE;
}
protected BigDecimalRenderer() {
}
public String render(BigDecimal object) {
if (null == object) {
return "";
}
return NumberFormat.getDecimalFormat().format(object);
}
}
And your BigDecimalParser.java
package com.google.gwt.text.client;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.text.shared.Parser;
import java.text.ParseException;
public class BigDecimalParser implements Parser<BigDecimal> {
private static BigDecimalParser INSTANCE;
public static Parser<BigDecimal> instance() {
if (INSTANCE == null) {
INSTANCE = new BigDecimalParser();
}
return INSTANCE;
}
protected BigDecimalParser() {
}
public BigDecimal parse(CharSequence object) throws ParseException {
if ("".equals(object.toString())) {
return null;
}
try {
return new BigDecimal(object.toString());
} catch (NumberFormatException e) {
throw new ParseException(e.getMessage(), 0);
}
}
}
Take a look at GWT-Math.
Related
in my project i am trying to use singleton class to store data in it. When im trying to access it from Service class, its creating new instance instead of using previous Singleton instance. I read a lot of post on github and couldn't find working answer
My Singleton class
import android.util.Log;
import com.softelnet.ksavi.android.model.AttachmentRequest;
import java.util.LinkedList;
public class AttachmentsUpdateQueue {
private static class Holder {
private static final AttachmentsUpdateQueue singleInstance = new AttachmentsUpdateQueue();
}
private AttachmentsUpdateQueue() {
Log.d("pox", "new instance");
}
private LinkedList<AttachmentRequest> attachmentsQueue = new LinkedList<>();
public static AttachmentsUpdateQueue getInstance() {
return Holder.singleInstance;
}
public AttachmentRequest getAttachmentForUpload() {
Log.d("pox", "get, size:" + attachmentsQueue.size());
if (attachmentsQueue.size() > 0) {
return attachmentsQueue.get(0);
} else {
return null;
}
}
public int getSize() {
return attachmentsQueue.size();
}
public void addAttachmentForUpload(AttachmentRequest attachment) {
attachmentsQueue.addLast(attachment);
Log.d("pox", "added, size:" + attachmentsQueue.size());
}
}
Adding data to Singleton
AttachmentsUpdateQueue.getInstance().addAttachmentForUpload(new AttachmentRequest(oprCtx.getUser(),task.getId(),attachment,isAttribute));
Getting data from Singleton
AttachmentRequest req = AttachmentsUpdateQueue.getInstance().getAttachmentForUpload();
may be you can write like this, which is named DCL(double check lock).
private volatile static AttachmentsUpdateQueue instance = null;
private AttachmentsUpdateQueue(){
System.out.println("Single: " + System.nanoTime());
}
public static AttachmentsUpdateQueue getInstance(){
if(instance == null){
synchronized (AttachmentsUpdateQueue.class) {
if(instance == null){
singleInstance = new AttachmentsUpdateQueue();
}
}
}
return instance;
}
This is my project structure. I'm trying to use a static factory function to check for an object and then perform some operations. I followed the this process.
Parent Class:
public abstract class Parent {
protected static Child1DTO ch1;
protected static Child2DTO ch2;
public Parent(Child1DTO ch1) {
this.ch1 = ch1;
}
public Parent(Child2DTO ch2) {
this.ch2 = ch2;
}
protected Parent() {
}
public static Child1DTO getCh1() {
return ch1;
}
public static Child2DTO getCh2() {
return ch2;
}
public static Class<?> childType(Object obj) {
if (obj instanceof Child1DTO) {
//do something
return Child1DTO.class;
} else if (obj instanceof Child2DTO) {
//do something
return Child2DTO.class;
}
return null;
}
}
Child1DTO Class:
public class Child1DTO extends Parent {
private String fName1;
private String lName1;
public String getfName1() {
return fName1;
}
public void setfName1(String fName1) {
this.fName1 = fName1;
}
public String getlName1() {
return lName1;
}
public void setlName1(String lName1) {
this.lName1 = lName1;
}
}
Child2DTO Class:
public class Child2DTO extends Parent{
private String fName2;
private String lName2;
public String getfName2() {
return fName2;
}
public void setfName2(String fName2) {
this.fName2 = fName2;
}
public String getlName2() {
return lName2;
}
public void setlName2(String lName2) {
this.lName2 = lName2;
}
}
Child Class:
public class Child extends Parent {
public Child(Child1DTO ch1) {
super(ch1);
}
public Child(Child2DTO ch2) {
super(ch2);
}
public static Child test(Object obj) {
if (obj instanceof Child1DTO) { //is this the correct way to check?
//do something
return new Child((Child1DTO) obj);
} else if (obj instanceof Child2DTO) {//is this the correct way to check?
//do something
return new Child((Child2DTO) obj);
}
return null;
}
public static void main(String args[]) {
if(childType(ch1).equals(ch1)){
//do something
}else if(childType(ch2).equals(ch2)){
//do something
}else{
System.out.println("Failed!");
}
}
}
EDIT:
Parent class has one Child class and two DTOs Child1DTO and Child2DTO.
Do I need to implement conditional check in Parent class or Child class?
How to achieve conditional check with constructors?
My singleton is called Resources. It should only be instantiated once by this Singleton standard I used:
package site.kevindhu.models;
import site.kevindhu.entity.Player;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class Resources {
public static Resources resources;
public Map<String, Object> data;
static {
resources = new Resources();
}
private Resources() {
data = new HashMap<>();
data.put("players", new HashSet<Player>());
data.put("newPlayers", new HashSet<Player>());
}
public static Resources getInstance() {
return resources;
}
}
However, it is not working correctly!
When I deploy a .ear to run my glassfish server, it goes into this block twice:
static {
resources = new Resources();
}
As a result, the "singleton" actually creates two different Resources each time I run the server.
I know I do twice because I debug it calls two different Resources objects whenever I attempt to call Resources.resources.
Is this possibly because I am deploying a .ear file? How do the specifics of this double instantiation work?
The best way to go is to let the compiler handle it for you:
/** Singleton. */
public enum Resources {
RESOURCES;
private final Map<String, Team> teams = new HashMap<>();
public boolean add(Team team) {
return team != null
&& teams.put(team.getName(), team) == null;
}
public Team find(String name) {
return name == null ? null : teams.get(name);
}
public Team find(Team team) {
return team == null ? null : get(team.getName());
}
public Map<String, Team> getTeams() {
return Collections.unmodifiableMap(teams);
}
// remove, iterators, etc.
}
public class TeamImpl implements Team {
private final String name;
private final Map<String, Player> roster = new HashMap<>();
public TeamImpl(String name) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
this.name = name;
assert this.name != null;
}
#Override
public boolean equals(Object other) {
// base comparison on team name
}
#Override
public int hashCode() {
assert this.name != null;
return name.hashCode();
}
// methods from interface Team:
#Override
public String getName() {
return name;
}
#Override
public Set<Player> getRoster() {
return Collections.unmodifiableSet(new HashSet<>(roster.values()));
}
#Override
public boolean add(Player player) {
return player != null
&& roster.put(player.getName(), player) == null;
}
#Override
public Player find(String name) {
return name == null ? null : roster.get(name);
}
// remove, iterators, etc.
}
I am trying to serialise some POJOs to XML. Some of them use #Transient annotations to indicate that some properties should not be serialised.
I have made a small test case to demonstrate the problem. I have also tried using #XStreamOmit but the result is the same. I do NOT expect to see the HiddenTop property in the output.
The POJO:
package test;
import java.beans.Transient;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
public class DerivedObject
{
private String xVisible = "GOODTOP";
private String xHidden = "BADTOP";
public DerivedObject() {
}
public String getVisibleTop() {
return xVisible;
}
public void setVisibleTop(String xVisible) {
this.xVisible = xVisible;
}
#Transient
public String getHiddenTop() {
return xHidden;
}
#Transient
public void setHiddenTop(String xHidden) {
this.xHidden = xHidden;
}
}
The Main:
package test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.javabean.JavaBeanConverter;
public class TestAnnotation
{
public static void main(String[] args) {
DerivedObject o = new DerivedObject();
o.setVisibleTop(":-)");
o.setHiddenTop(":-(");
try {
XStream xs = new XStream();
xs.autodetectAnnotations(true);
xs.registerConverter(new JavaBeanConverter(xs.getMapper()),
XStream.PRIORITY_LOW);
System.out.println(xs.toXML(o));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
The output
<test.DerivedObject>
<hiddenTop>:-(</hiddenTop>
<visibleTop>:-)</visibleTop>
</test.DerivedObject>
Becouse JavaBeanProvider doesn't respect the #Transient annotation a solution is to implement you own JavaBeanProvider that respect this annotation:
public class TransientRespectingBeanProvider extends BeanProvider {
#Override
protected boolean canStreamProperty(PropertyDescriptor descriptor) {
final boolean canStream = super.canStreamProperty(descriptor);
if (!canStream) {
return false;
}
final boolean readMethodIsTransient = descriptor.getReadMethod() == null
|| descriptor.getReadMethod().getAnnotation(Transient.class) != null;
final boolean writeMethodIsTransient = descriptor.getWriteMethod() == null
|| descriptor.getWriteMethod().getAnnotation(Transient.class) != null;
final boolean isTransient = readMethodIsTransient
|| writeMethodIsTransient;
return !isTransient;
}
}
You can use it as follows:
final JavaBeanProvider beanProvider = new TransientRespectingBeanProvider();
final Converter converter = new JavaBeanConverter(xstream.getMapper(), beanProvider);
xstream.registerConverter(converter);
I have a lot of classes UNO,HAV,MAS,KOS
I want to create a factory pattern.
validator.load("UNO").validate();
I need dynamically load classes into validator class and return an instance.
(dynamically set name of the class and return an instance)
My problem is: how can I return the instance of a class, if I have incompatible types?
I don't know what to write in return type of method.
The main problem in the Validator CLASS.
public SegmentAbstract load(String str) {
AND
return SegmentAbsClass.forName(identify);
Main class
try{
validator.load("UNO").validate();
}catch(Exception e){
System.out.print("No class ");
}
Abstract Class (SegmentAbstract)
public abstract class SegmentAbstract {
public abstract Boolean validate();
}
Class UNO
public class UNA extends SegmentAbstract{
public Boolean validate() {
System.out.print("UNO!!");
return true;
}
}
Class Validator
public class Validator {
public SegmentAbstract load(String str) {
String identify = str.substring(0, 3);
try {
return SegmentAbsClass.forName(identify);
}
catch(Exception e) {
return this;
}
}
}
Try this :
public interface Validator {
boolean validate(Object obj);
}
public final class ValidatorFactory {
private ValidatorFactory(){}
public static Validator load(String type){
try {
Class<?> clazz = Class.forName(type);
if (Arrays.asList(clazz.getInterfaces()).contains(Validator.class)){
return (Validator) clazz.newInstance();
}
throw new IllegalArgumentException("Provided class doesn't implement Validator interface");
} catch (Exception e) {
throw new IllegalArgumentException("Wrong class provided", e);
}
}
}
Maybe this will help???
I will do something like that:
// ISegment.java
public interface ISegment {
Boolean validate();
}
// Uno.java
public class Uno implements ISegment {
public Boolean validate() {
System.out.print("UNO!!");
return true;
}
}
// SegmentFactory.java
public final class SegmentFactory {
public static enum Supported {
UNO("uno", Uno.class), /* ... */, HAV("hav", Hav.class);
private final Class<?> clazz;
private final String name;
private Supported(final String name, final Class<?> clazz) {
this.name = name;
this.clazz = clazz;
}
public Class<?> getClazz() {
return clazz;
}
public static Supported for(final String name) {
for (final Supported s : values()) {
if (s.name.equals(name) {
return s;
}
}
return null; // a default one
}
}
public static ISegment create(final Supported supp) {
if (supp == null) {
return null;
}
return supp.getClazz.newInstance();
}
private SegmentFactory() {
// avoid instantiation
}
}
usage:
final ISegment sa = SegmentFactory.create(SegmentFactory.Supported.for("uno"));
sa.validate();
Not tested!!
Take a look here. Briefly, the idea is to create a map in your factory class (Map<String,String>, key is identifier, value is fully qualified class name), and add supported classes during initialization. Then you use reflection to instantiate an object in your factory method. Also, you can avoid reflection by using Map<String, SegmentAbstract> instead of Map<String,String> and adding public abstract getNewSegment() to your SegmentAbstract class.