Boolean Method for ArrayList - methods

I have created an ArrayList and I am looking to use a boolean method to add an element to the ArrayList.
private static Arraylist <Bicycle> bikelist = new Arraylist<Bicycle>();
public boolean add(Bicycle bicycle)
{
if( bikelist.size() != -1)
return true;
bikelist.add(bicycle);
}
return false;
Would this be plausible? I'm not quite sure how boolean methods work? Do they have to contain an if statement to return true or false?

Using: public boolean add(Object obj): Adds an element obj to the Arraylist. If the element is added successfully, this method returns true

Depends on what you want to return the boolean value for.
For whether the add operation succeeded: the only reason why adding an Object to an ArrayList would fail is due to an OutOfMemoryException AFAIK. Then you would do:
public boolean add(Object obj) {
try {
list.add(obj);
} catch (OutOfMemoryException e) {
return false;
}
return true;
}
If you want to return false if the list already contains the object, then:
public boolean add(Object obj) {
if (list.contains(obj)) {
return false;
}
list.add(obj);
return true;
}
Note that ArrayList<T>.contains(T) checks for object equality using Object.equals(Object). Thus you need to override equals() for your custom class.
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Bicycle other = (Bicycle) obj;
if (other.owner != this.owner) {
return false;
}
if (this.model != other.model) {
return false;
}
return true;
}

Related

spring mvc checking checkbox does not set object

Hi I am new to spring MVC and am trying to implement a form:checkboxes tag and have run into a few issues. All the examples I have googled work with Strings and i want to work with objects so am hoping someone can advise.
I have a List of objects set in my DTO as follows:
TestDTO
private List<Barrier> barriers;
public List<Barrier> getBarriers() {
return barriers;
}
public void setBarriers(List<Barrier> barriers) {
this.barriers = barriers;
}
in my controller class I fetch the barrier objects from the database and add them to my DTO which will be passed to the jsp
savedRecord.setBarriers(dataService.getBarriers());
mav.addObject("testDto", savedRecord);
in my JSP I use the form:checkboxes tag as follows:
<form:checkboxes path="barriers" items="${testDto.barriers}" element="label class='block-label'"
itemLabel="barrier"/>
I also tried with adding
itemValue="id"
but that did not work either
this is wraped in a from element
<form:form method="post" accept-charset="UTF-8" action="${action}"
onsubmit="return checkAndSend()" id="create"
novalidate="" modelAttribute="testDto">
So the issues I am having are as follows:
The checkboxes when displayed all seem to be checked. I have implemented a hashcode and equals method on the barrier object but they still all seem to be checked when I want them unchecked.
Barrier.java
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((barrier == null) ? 0 : barrier.hashCode());
result = prime * result + ((display == null) ? 0 : display.hashCode());
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Barrier other = (Barrier) obj;
if (barrier == null) {
if (other.barrier != null)
return false;
} else if (!barrier.equals(other.barrier))
return false;
if (display == null) {
if (other.display != null)
return false;
} else if (!display.equals(other.display))
return false;
if (id != other.id)
return false;
return true;
}
When I click submit and i look at the testDto my barriers object list is null. How do I get the checked boxes that represent objects to be set on my testDto.
Any pointers and advice is appreciated
Thanks
UPDATE:
Thanks for the pointers. I went with the following. your suggestion helped.
I created the folloiwng in my controller
#InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Barrier.class, new BarrierPropertyEditor(barrierService));
}
and then added a class to do the conversion
public class BarrierPropertyEditor extends PropertyEditorSupport {
private BarrierService barrierService;
public BarrierPropertyEditor(BarrierService barrierService) {
this.barrierService = barrierService;
}
#Override
public void setAsText(String text) {
Barrier b = barrierService.findById(Integer.valueOf(text));
setValue(b);
}
}
This sets the barrier objects on my DTO.
(Sorry for the caps) IT DOES NOT SOLVE WHY THE CHECKBOXES ARE CHECKED ON INITIAL LOAD.
Any ideas how to set the checkboxes unchecked on intitial load?
You can use #ModelAttribute in your Controller to provide the list of values in checkboxes.
#ModelAttribute("barrierList")
public List<Barrier> populateBarrierList() {
List<Barrier> barrierList = dataService.getBarriers();
for(Barrier barrier: barrierList )
{
barrierList.add(barrier);
}
return barrierList ;
}
In JSP, use following :
<form:checkboxes path="barriers" items="${barrierList}" element="label class='block-label'" itemLabel="barrier"/>

Spring Cache Key Using Arguments

I have a class Person with properties id, name and age.
I would like to cache Person object using id and name.
my method is
#Cacheable(value = "person", key = "#p.id + p.name")
getPerson(Person p).
Question is, how do i use cache annotation on getPerson()... something like this.
Using the annotation you could concatenate the values to create a key (I read but have not tested tha the debug symbols may be removed and so the parameter should be referenced as "p0").
#Cacheable(value="person", key="#p0.id.concat(‘:’).concat(#p0.name)")
Otherwise, it will be cached based on Person class equals() and hashCode() just the same way as if you were using the Person object as a key in a Map.
So, for example:
public class Person {
String id;
String name;
Number age;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Person))
return false;
Person other = (Person) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

Silverlight 5 validation issue

i'm trying to validate the data entry of my project using the validation in silverlight
this is the result
http://imageshack.us/photo/my-images/842/immagineleb.png/
as you can see the borders of almost all the textboxes are red, actually, in this case, no one of them should be red! And in all of the tooltips there's the same message.
there are the properties of the object that i use in the data context of the form
private int matricola;
public int Matricola
{
get { return matricola; }
set
{
ValidateRequiredInt("Matricola", value, "Inserire un numero");
matricola = value;
OnNotifyPropertyChanged("Matricola");
}
}
private String cognome;
public String Cognome
{
get { return cognome; }
set
{
ValidateRequiredString("Cognome", value, "Inserire cognome");
cognome = value;
OnNotifyPropertyChanged("Cognome");
}
}
private String nome;
public String Nome
{
get { return nome; }
set
{
ValidateRequiredString("Nome", value, "Inserire nome");
nome = value;
OnNotifyPropertyChanged("Nome");
}
}
private String codiceUtente;
public String CodiceUtente
{
get { return codiceUtente; }
set
{
ValidateRequiredString("CodiceUtente", value, "Inserire codice utente");
codiceUtente = value;
OnNotifyPropertyChanged("CodiceUtente");
}
}
private String password;
public String Password
{
get { return password; }
set
{
ValidateRequiredString("Password", value, "Inserire password");
password = value;
OnNotifyPropertyChanged("Password");
}
}
private int? idOrario;
public int? IdOrario
{
get { return idOrario; }
set { idOrario = value; }
}
private DateTime? dataAssunzione;
public DateTime? DataAssunzione
{
get { return dataAssunzione; }
set
{
if (value != null)
{
ValidateDateTime("DataAssunzione", (DateTime)value, "Immettere una data corretta");
if (((DateTime)value).Year == 1 && ((DateTime)value).Month == 1 && ((DateTime)value).Day == 1)
{
dataAssunzione = null;
}
else
{
dataAssunzione = value;
}
OnNotifyPropertyChanged("DataAssunzione");
}
else
{
dataAssunzione = null;
}
}
}
private DateTime? dataLicenziamento;
public DateTime? DataLicenziamento
{
get { return dataLicenziamento; }
set
{
if (value != null)
{
ValidateDateTime("DataLicenziamento", (DateTime)value, "Immettere una data corretta");
if (((DateTime)value).Year == 1 && ((DateTime)value).Month == 1 && ((DateTime)value).Day == 1)
{
dataLicenziamento = null;
}
else
{
dataLicenziamento = value;
}
OnNotifyPropertyChanged("DataLicenziamento");
}
else
{
dataLicenziamento = null;
}
}
}
private int idGruppoAnag;
public int IdGruppoAnag
{
get { return idGruppoAnag; }
set { idGruppoAnag = value; }
}
private int? costoOrario;
public int? CostoOrario
{
get { return costoOrario; }
set
{
if (value != null)
{
ValidateInt("CostoOrario", (int)value, "Immettere un numero o lasciare il campo vuoto");
if (value == 0 || value == -1)
{
costoOrario = null;
}
else
{
costoOrario = value;
}
OnNotifyPropertyChanged("CostoOrario");
}
else
{
costoOrario = null;
}
}
}
and these are the methods used for the validation
protected bool ValidateRequiredInt(string propName, int value, string errorText)
{
if (DataErrors.ContainsKey(propName))
{
DataErrors[propName].Remove(errorText);
}
if (value == 0 || value == -1)
{
AddError(propName, errorText);
return false;
}
OnErrorsChanged(propName);
return true;
}
//validazione dei campi che richiedono numeri interi nullable
protected bool ValidateInt(string propName, int value, string errorText)
{
if (DataErrors.ContainsKey(propName))
{
DataErrors[propName].Remove(errorText);
}
if (value == 0)
{
AddError(propName, errorText);
return false;
}
OnErrorsChanged(propName);
return true;
}
//validazione dei campi che richiedono stringhe
protected bool ValidateRequiredString(string propName, string value, string errorText)
{
//Clear any existing errors since we're revalidating now
if (DataErrors.ContainsKey(propName))
{
DataErrors[propName].Remove(errorText);
}
if (string.IsNullOrEmpty(value))
{
AddError(propName, errorText);
return false;
}
OnErrorsChanged(propName);
return true;
}
protected bool ValidateDateTime(string propName, DateTime value, string errorText)
{
//Clear any existing errors since we're revalidating now
if (DataErrors.ContainsKey(propName))
{
DataErrors[propName].Remove(errorText);
}
if (value.Year == 9999 && value.Month == 12 && value.Day == 31)
{
AddError(propName, errorText);
return false;
}
OnErrorsChanged(propName);
return true;
}
i'm also using using a dataconverter, in the two "Data" textboxes, and numberconverter, in the matricola and costo textboxes, as locals resources and i can say that they work fine.
i'm missing something?
How about implementing INotifyDataErrorInfo?
In a view-model base class:
public abstract class BaseViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region INotifyDataErrorInfo Members
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public System.Collections.IEnumerable GetErrors(string propertyName)
{
....
}
public System.Collections.IEnumerable GetErrors()
{
...
}
//Plus methods to push errors into an underlying error dictionary used by the above error get methods
}
Expand on this and you will have reusable base class for all view-models.
Validate properties in the appropriate setters. If they fail validation then push an error into the error dictionary keyed by property name. If validation succeeds then remove the validation error (if any) from the the dictionary for the property.
You will need to fire the ErrorsChanged event when you change the dictionary, but this can be achieved by having a protected
SetErrorForProperty(string propName, object error)
method whcih wraps this up.
Clearing an error can be done by passing null to this method and/or by having a separate
ClearErrorsFroProperty(string propName)
method.

Accessing Roles from Custom Authorize Attribute

I am creating my own custom authorize attribute, overriding the AuthorizeCore method and wanted to know if it is possible to access the Roles which have been passed into the authorize attribute tag.
So for instance if I have this:
[CustomAuthorize(Roles = "Administrator, Sales, Entry")]
Is it possible to access these from inside here:
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
I could then split the string and create an array.
You can this this.Roles which is a string that you need to split.
The source code is freely available.
The default AuthorizeCore implementation:
protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null) {
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated) {
return false;
}
if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
return false;
}
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {
return false;
}
return true;
}
And they have an internal split function which looks like this:
internal static string[] SplitString(string original) {
if (String.IsNullOrEmpty(original)) {
return new string[0];
}
var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}

SingleOrDefault: How to change the default values?

SingleOrDefault returns null, but what if I want to assign values to represent the object that wasn't found?
you can do something like
myStrings.DefaultIfEmpty("myDefaultString").Single()
check out here
?? operator. If the left argument is null, evaluate and return the second argument.
myCollection.SingleOrDefault() ?? new[]{new Item(...)}
This will only work with reference types (or nullables), but it would do what you're looking for very simply.
You could roll your own.
public static T SingleOrDefault<T>(this IEnumerable<T> enumerable, T defaultValue) {
if ( 1 != enumerable.Count() ) {
return defaultValue;
}
return enumerable.Single();
}
This can be a bit expensive though because Count() requires you to process the entire collection and can be fairly expensive to run. It would be better to either call Single, catch the InvalidOperationException or roll a IsSingle method
public static bool IsSingle<T>(this IEnumerable<T> enumerable) {
using ( var e = enumerable.GetEnumerator() ) {
return e.MoveNext() && !e.MoveNext();
}
}
public static T SingleOrDefault<T>(this IEnumerable<T> enumerable, T defaultValue) {
if ( !enumerable.IsSingle() ) {
if( enumerable.IsEmpty() ) {
return defaultValue;
}
throw new InvalidOperationException("More than one element");
}
return enumerable.Single();
}
You could create your own extension methods -- SingleOrNew.
public static class IEnumerableExtensions
{
public static T SingleOrNew<T>( this IEnumerable<T> enumeration, T newValue )
{
T elem = enumeration.SingleOrDefault();
if (elem == null)
{
return newValue;
}
return elem;
}
public static T SingleOrNew<T>( this IEnumerable<T> enumeration, Func<T,bool> predicate, T newValue )
{
T elem = enumeration.SingleOrDefault( predicate );
if (elem == null)
{
return newValue;
}
return elem;
}
}

Resources