Type Date return content - return

Please see content below, confused on what to put for return that has type Date
#Override
public int maxCapacity() {
return 3;
}
#Override
public String area() {
return "10";
}
#Override
public Date whenBuilt() {
return ***[What should I return here?]***
}

Date methods must to return Date instance or null..
You can just return new Date();, but it will always fresh date.
Method whenBuilt looks like some date in the past, so you should to make some date, in constructor for example.
class A {
private final Date createdAt;
A() {
createdAt = new Date();
}
public Date whenBuilt() {
return createdAt;
}
}
#Override annotation points to your class is extension from some base class.
Try to check base class, may be built date is already in there.

Related

Save a list in a property in an entity in xodus

I have not found how to save a general list of primitive types, e.g. ints, or strings, in a property of an entity. I might have missed something obvious...
https://github.com/JetBrains/xodus/wiki/Entity-Stores described that "only Java primitive types, Strings, and ComparableSet values can be used by default".
It seems not hard to convert an Iterable into a ComparableSet. However it is a Set.
I will take a look into PersistentEntityStore.registerCustomPropertyType() to see if that helps. I just feel wrong to do that to just save a list of integers.
Links seemed to be able to serve as a way of saving a list of Entitys. But it seems there is no addProperty() counterpart to addLink().
Appreciated if some one can share a way or a workaround for this, or maybe why this is not supported.
Thanks
As mentioned in the comments, one workaround I came up with was to create a ComparableList, by adopting code from ComparableSet.
The idea was to make a list that is able to convert to and from an ArrayByteIterable, and register it with .registerCustomPropertyType(). To do that, 2 classes are needed, ComparableList and ComparableListBinding. I'm sharing one iteration I used at the bottom. By the way, I made them immutable, comparing to the mutable ComparableSet. The newly implemented types should be registered once in a transaction of the store before using them.
That should allow you to store and retrieve a list. However the items in ComparableList would not get indexed as they would when saved in a ComparableSet -- there are some special treatment for ComparableSet in the entity store implementation. So without modifying the library, indexing would work only with hacks like creating another property to just index the values.
I was considering to implement a different entity store that could better support lists, on top of the xodus key-value store, bypassing the xodus entity store entirely. That might be a better solution to the list issue we are talking about here.
ComparableList:
#SuppressWarnings("unchecked")
public class ComparableList<T extends Comparable<T>> implements Comparable<ComparableList<T>>,
Iterable<T> {
#Nonnull
private final ImmutableList<T> list;
public ComparableList(#Nonnull final Iterable<T> iterable) {
list = ImmutableList.copyOf(iterable);
}
#Override
public int compareTo(#Nonnull final ComparableList<T> other) {
final Iterator<T> thisIt = list.iterator();
final Iterator<T> otherIt = other.list.iterator();
while (thisIt.hasNext() && otherIt.hasNext()) {
final int cmp = thisIt.next().compareTo(otherIt.next());
if (cmp != 0) {
return cmp;
}
}
if (thisIt.hasNext()) {
return 1;
}
if (otherIt.hasNext()) {
return -1;
}
return 0;
}
#NotNull
#Override
public Iterator<T> iterator() {
return list.iterator();
}
#Nullable
public Class<T> getItemClass() {
final Iterator<T> it = list.iterator();
return it.hasNext() ? (Class<T>) it.next().getClass() : null;
}
#Override
public String toString() {
return list.toString();
}
}
ComparableListBinding:
#SuppressWarnings({"unchecked", "rawtypes"})
public class ComparableListBinding extends ComparableBinding {
public static final ComparableListBinding INSTANCE = new ComparableListBinding();
private ComparableListBinding() {}
#Override
public ComparableList readObject(#NotNull final ByteArrayInputStream stream) {
final int valueTypeId = stream.read() ^ 0x80;
final ComparableBinding itemBinding = ComparableValueType.getPredefinedBinding(valueTypeId);
final ImmutableList.Builder<Comparable> builder = ImmutableList.builder();
while (stream.available() > 0) {
builder.add(itemBinding.readObject(stream));
}
return new ComparableList(builder.build());
}
#Override
public void writeObject(#NotNull final LightOutputStream output,
#NotNull final Comparable object) {
final ComparableList<? extends Comparable> list = (ComparableList) object;
final Class itemClass = list.getItemClass();
if (itemClass == null) {
throw new ExodusException("Attempt to write empty ComparableList");
}
final ComparableValueType type = ComparableValueType.getPredefinedType(itemClass);
output.writeByte(type.getTypeId());
final ComparableBinding itemBinding = type.getBinding();
list.forEach(o -> itemBinding.writeObject(output, o));
}
/**
* De-serializes {#linkplain ByteIterable} entry to a {#code ComparableList} value.
*
* #param entry {#linkplain ByteIterable} instance
* #return de-serialized value
*/
public static ComparableList entryToComparableList(#NotNull final ByteIterable entry) {
return (ComparableList) INSTANCE.entryToObject(entry);
}
/**
* Serializes {#code ComparableList} value to the {#linkplain ArrayByteIterable} entry.
*
* #param object value to serialize
* #return {#linkplain ArrayByteIterable} entry
*/
public static ArrayByteIterable comparableSetToEntry(#NotNull final ComparableList object) {
return INSTANCE.objectToEntry(object);
}
}

Binding between an Object and a SimpleIntegerProperty

I have a combo box over my GUI in JavaFX.
This Combo Box is composed of a complex type elements :
public class DureeChoiceBoxElement extends ObservableValueBase<DureeChoiceBoxElement> {
private IntegerProperty duree;
#Override
public String toString() {
return duree.get() + " an";
}
}
I want to map (or bind) the selected complex element with my model which contains the simple type :
public class Pel {
private IntegerProperty duree = new SimpleIntegerProperty(1);
public Property<Number> dureeProperty() {
return duree;
}
public void setDuree(Integer duree) {
this.duree.setValue(duree);
}
public Integer getDuree() {
return duree.getValue();
}
}
How to do it ?
I tried in the controller with :
public class PelController {
#FXML
private ChoiceBox<DureeChoiceBoxElement> duree;
//etc..
pel.dureeProperty().bind(createElapsedBindingByBindingsAPI2(duree.getValue()));
/*
* #return an ObjectBinding of immutable TimeElapsed objects for the player
*/
private ObjectBinding<Property<Number>> createElapsedBindingByBindingsAPI2(
final DureeChoiceBoxElement dureeChoiceBoxElement) {
return Bindings.createObjectBinding(new Callable<Property<Number>>() {
#Override
public IntegerProperty call() throws Exception {
return dureeChoiceBoxElement.dureeProperty();
}
}, dureeChoiceBoxElement.dureeProperty());
}
}
But it doesn't work (even not compile). I want to say that "Bind this simple property to this complex Object calling the method I give you through the method named "createElapsedBindingByBindingsAPI2(..)".
It is logical read but I didn't managed to make it works anyway.
That's poor ....
Any help please :).
Example that (obviously) works with legacy code style (Swing coding) :
duree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<DureeChoiceBoxElement>() {
#Override
public void changed(ObservableValue<? extends DureeChoiceBoxElement> observable,
DureeChoiceBoxElement oldValue, DureeChoiceBoxElement newValue) {
// changement durée
log.debug("Durée sélectionnée : {}", duree.getSelectionModel().getSelectedItem().getDuree());
log.debug("Durée bindée ? : {}", pel.getDuree());
pel.setDuree(duree.getSelectionModel().getSelectedItem().getDuree());
}
});
Like this my model is set to selected item. But it implies some boilerplate code. Any better idea based on high level bindings of JavaFX ?

JavaFX textfield binding

I have a textfield with a binding to a timestring like this:
timeStringProperty.bind(clock.getTimeString());
timeTextField.textProperty().bind(timeStringProperty);
In Clock.java I have:
public StringBinding getTimeString() {
return Bindings.createStringBinding(() -> DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM).format(time.get()), time);
}
where time comes from a TimeLine.
This works well and the current time is displayed and updated in the timeTextfield.
Now I want to add the ability for the user of my program to determine the format of the time e.g. "hh:mm" or "hh:mm:ss".
How can I bind to a formatString, such that the time display updates with the new format as soon as the formatString value is changed?
Introduce an ObjectProperty<DateTimeFormatter> to Clock:
public class Clock {
private final ObjectProperty<DateTimeFormatter> formatter =
new SimpleObjectProperty<>(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
public ObjectProperty<DateTimeFormatter> formatterProperty() {
return formatter ;
}
public final DateTimeFormatter getFormatter() {
return formatterProperty().get();
}
public final void setFormatter(DateTimeFormatter formatter) {
formatterProperty().set(formatter);
}
// ... other code as before
}
And now update the StringBinding so that it uses the formatter and binds to it:
public StringBinding getTimeString() {
return Bindings.createStringBinding(() -> getFormatter().format(time.get()), time, formatter);
}

How to sort Vectors in blackberry using SimpleSortingVector?

I am having trouble to sort Vector for my blackberry app using SimpleSortingVector. My stuff does not sort it remains the same.
here is what i have so far...
MyComparator class
private Vector vector = new Vector(); //Assume that this vector is populated with elements already
SimpleSortingVector ssv = new SimpleSortingVector();
ssv.setSortComparator(new Comparator() {
public int compare(Object o1, Object o2) {
Record o1C = (Record)o1;
Record o2C = (Record)o2;
return o1C.getName().compareTo(o2C.getName());
}
public boolean equals(Object obj) {
return compare(this, obj) == 0;
}
});
for(int i=0;i<vector.size();i++){
Record record = new Record();
record=(Record) vector.elementAt(i);
//when you add elements to this vector, it is to post to be automatically sorted
ssv.addElement(record);
}
class Record
public class Record {
String name;
int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
SimpleSortingVector does not sort by default. This was unexpected for me the first time I ran into it, too, given the name of the class.
You can do one of two things. Call SimpleSortingVector.setSort(true) to make sure the vector is always sorted after each change. This is surprisingly not turned on by default.
Or, you can call SimpleSortingVector.reSort() after adding all the elements to the vector, to do the sort in one batch operation.

how to convert date from yyyy-MM-dd to dd-MMM-yyyy without using Date function

I have "2011-12-05" and I want to convert this to "Monday 05-Dec-2011".
My date conversion code depends on the device timezone. If my timezone is India, then I get date Monday 05-Dec-2011 and if my timezone is Kingston, Jamaica, I get Sunday 04-Dec-2011.
For this reason my application does not display the correct date for different timezones.
Is there any solution to convert date without Blackberry Date class or using current Date and Time Zone?
I want to only convert this date to String
I am converting this date using below function
public static String reformatMonthDate(String source)
{
SimpleDateFormat write = new SimpleDateFormat("dd MMM yyyy"); //YYYY-MMM-dd
Date date = new Date(HttpDateParser.parse(source));
return write.format(date);
}
You can specify a specific locale, instead of relying on the system's default.
Locale locale = Locale.get(Locale.LOCALE_fr);
// Parse with HttpDateParser
Date date = new Date(HttpDateParser.parse("2002-01-29"));
// Format with a custom format and locale
DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
StringBuffer buf = new StringBuffer(30);
String s = formatter.format(date, buf, null).toString(); // mar., 29 janv. 2002
DateTimePicker gives the current date according to the location or device configuration settings.
Try this code:
You should get your requirement.
public class LoadingScreen extends MainScreen implements FieldChangeListener
{
private String select_Date[]={"Select Date"};
private String month_ar[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
private ObjectChoiceField choiceField;
private ButtonField show;
public LoadingScreen()
{
createGUI();
}
private void createGUI()
{
choiceField=new ObjectChoiceField("Select Date: ", select_Date, 0)
{
protected boolean navigationClick(int status, int time)
{
DateTimePicker datePicker = DateTimePicker.createInstance( Calendar.getInstance(), "dd/MM/yyyy",null);
datePicker.doModal();
Calendar cal1=datePicker.getDateTime();
String day="";
String mon="";
if(String.valueOf(cal1.get(Calendar.DAY_OF_MONTH)).length()==1)
{
day="0"+String.valueOf(cal1.get(Calendar.DAY_OF_MONTH));
}
else
{
day=String.valueOf(cal1.get(Calendar.DAY_OF_MONTH));
}
mon=String.valueOf(cal1.get(Calendar.MONTH));
String month=""+month_ar[cal1.get(Calendar.MONTH)];
select_Date[0]=day+"-"+month+"-"+cal1.get(Calendar.YEAR);
choiceField.setChoices(select_Date);
return true;
}
};
add(choiceField);
show=new ButtonField("Show",FIELD_HCENTER);
show.setChangeListener(this);
add(show);
}
public void fieldChanged(Field field, int context)
{
if(field==show)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(select_Date[choiceField.getSelectedIndex()]);
}
});
}
}
public boolean onMenu(int instance)
{
return true;
}
protected boolean onSavePrompt()
{
return true;
}
}

Resources