Odd Java bug I can't seem to resolve - java

I'm scratching my head as to why some code within my try statement isn't being executed. Below is the culprit code in question.
try {
Long idSociety = UtilAction.<Long>getSessionAttribute(session, idSocietyAttrName);
ContactAddressForm caf = (ContactAddressForm) form;
java.lang.System.out.println("invoiceAddresss: " + caf.getInvoiceAddress()); //This doesn't show in Console
Address address = new Address(caf.getStreet(), caf.getPostalCode(), caf.getCity(), caf.getBoitePostale());
ContactAddress ca = new ContactAddress();
ca.setInvoiceAddress(caf.getInvoiceAddress()); //Not set despite the Debugger showing the correct value for caf.
ca.setAddress(address); //But this is set 0_o?
synchronized (session) {
SocietyPeer.storeAddress(idSociety, ca);
}
addAddressesInSession(session, idSociety);
form.reset(mapping, request);
}
ContactAddress class
package fr.model.society;
import fr.model.component.Address;
public class ContactAddress {
private Long idContactAddress;
private Address address;
private Boolean invoiceAddress = false;
private Society society;
public Long getIdContactAddress() {
return idContactAddress;
}
public void setIdContactAddress(Long id) {
this.idContactAddress = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public void setInvoiceAddress(Boolean invoiceAddress) {
this.invoiceAddress = invoiceAddress;
}
public Boolean getInvoiceAddress() {
return invoiceAddress;
}
/**
* **************** METHODES MAPPING *****************
*/
public Society getSociety() {
return society;
}
public void setSociety(Society society) {
this.society = society;
}
public String toString() {
return getAddress().toString();
}
public boolean equals(Object o) {
if (!(o instanceof ContactAddress)) {
return false;
}
ContactAddress ca = (ContactAddress) o;
return address.equals(ca.getAddress()) && (getSociety().equals(ca.getSociety()));
}
public int hashCode() {
return ((getIdContactAddress() == null) ? 0 : getIdContactAddress().hashCode())
^ address.hashCode()
^ ((getSociety() == null) ? 0 : getSociety().hashCode());
}
}
Edit:
Essentially I'm trying to set the invoiceAddress boolean variable and for all intents and purposes I can't at the moment. Nothing is printed in the console for java.lang.System.out.println("invoiceAddresss: " + caf.getInvoiceAddress()); I also tried passing it through a temp boolean variable and that variable isn't picked up in the debugger at all.

I loaded the project in Netbeans and this issue seems to be with eclipse and the Tomcat server. Must not be updating the Warfile despite re-building.

Related

my deterministic turing machine won't work, because my equals and indexof method throw no source error

I have the problem, that my equals method doesnt work as i want it to. I want to implement a deterministic turing machine, so I want to add the method findCommand(), which searchs through a arraylist of commands. So I decided to create a searchDummy to find all Transitions that are available for the Configuration I have.
Class States:
public class States {
private int stateId;
private boolean rejState;
private boolean accState;
private boolean stopState;
private List<Commands> commands = new ArrayList<Commands>();
equals in class States:
#Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof States) {
States otherState = (States) other;
return (stateId == otherState.stateId);
} else {
return false;
}
}
hashCode:
#Override public int hashCode() {
StringBuilder b = new StringBuilder(stateId);
return b.toString().hashCode();
}
this is the findCommand method in States:
public Commands findCommand(States state, char inputTapeChar,
char[] tapeChars) {
Commands searchDummy = new Commands(state, inputTapeChar, tapeChars,
null, null, null, null);
int pos = commands.indexOf(searchDummy);
return pos >= 0 ? commands.get(pos) : null;
}
commands is my arraylist, so I want to find the searchDummy with indexOf().
I have the class Commands, which holds the attribute Configuration configuration, the class Configuration, which holds the attributes of a Configuration and the attribute Transition transition and the class transition that holds the attributes for itself.
Class Commands:
public class Commands implements Comparable<Commands> {
private Configuration configuration;
Class Configuration:
public class Configuration {
private Transition transition;
private States state;
private char inputTapeChar;
private char[] tapeChars;
Class Transition:
public class Transition {
private States targetState;
private Direction inputTapeHeadMove;
private char[] newTapeChars;
private Direction[] tapeHeadMoves;
i have this equals method in Commands:
#Override public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Commands) {
Commands otherCmd = (Commands) other;
return (configuration.equals(otherCmd.configuration));
} else {
return false;
}
}
and this hashcode
#Override
public int hashCode() {
StringBuilder b = new StringBuilder(configuration.getState() + ","
+ configuration.getInputTapeChar());
for (char c : configuration.getTapeChars()) {
b.append("," + c);
}
return b.toString().hashCode();
}
then almost the same in Configuration:
#Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Configuration) {
Configuration otherConfi = (Configuration) other;
return (state.equals(otherConfi.state))
&& (inputTapeChar == otherConfi.inputTapeChar)
&& (Arrays.equals(tapeChars, otherConfi.tapeChars));
} else {
return false;
}
}
hashcode:
#Override
public int hashCode() {
StringBuilder b = new StringBuilder(state + "," + inputTapeChar);
for (char c : tapeChars) {
b.append("," + c);
}
return b.toString().hashCode();
}
equales in class State:
#Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof States) {
States otherState = (States) other;
return (stateId == otherState.stateId);
} else {
return false;
}
}
so my question:
when I debug this it goes through until it's finished with the checks but when it should return the value it stucks at Configuration.equals(...) and shows the error no source found!
what is the problem? Are the hashcodes wrong? Or are the equals wrong?
I never used equals before so I dont know when i need to use it or how i need to fix this. thanks for your help.
Your hashCode implementation looks suspect - all that String stuff is not standard.
For example for your Transition class should be something like this:
#Override
public int hashCode() {
int result = 17;
result = 31 * result + targetState.hashCode();
result = 31 * result + inputTapeHeadMove.hashCode();
result = 31 * result + newTapeChars.hashCode();
result = 31 * tapeHeadMoves.hashCode();
return result;
}
Most IDEs will offer autogen of hashCode and equals methods.

Missing return statement method ReturnCopy

I've created this method and I'm unsure why it says there's a missing return statement. do I need to change the print to a return? (it's the method at the very bottom) I'm a bit of a Java beginner so any help will be appreciated!
public class Book {
private String title;
private String author;
private int copies;
private boolean borrowed;
public Book( String inAuthor, String inTitle, int inNumberOfCopies ) {
this.author = inAuthor;
this.title = inAuthor;
this.copies = inNumberOfCopies;
}
public void borrowed() {
borrowed = true;
}
public void rented() {
borrowed = true;
}
public void returned() {
borrowed = false;
}
public boolean isBorrowed() {
return borrowed;
}
public String getAuthor() {
return this.author;
}
public static String getTitle() {
return getTitle();
}
public int getTotalCopies() {
return this.copies;
}
public int getAvailableCopies() {
}
public void withdrawCopy() {
int found = 0;
for (Book b : Library.getListOfBooks()) {
if (b.getTitle().equals(title)) {
if (found == 0) {
found = 1;
}
if (!b.isBorrowed()) {
b.borrowed=true;
found = 2;
break;
}
if (found == 0) {
System.out.println("Sorry, this book is not in our catalog.");
} else if (found == 1) {
System.out.println("Sorry, this book is already borrowed.");
} else if (found == 2) {
System.out.println("You successfully borrowed " + title);
}
}
}
}
public String returnCopy() {
boolean found = false;
for (Book book : Library.getListOfBooks()) {
if (getTitle().equals(title) && book.isBorrowed()) {
book.returned();
found = true;
}
if (found) {
System.out.println("you successfully returned " + title);
}
}
}
}
public String returnCopy()
String after public means that this method will return a String.
Your public String returnCopy() is currently not returning anything.
If you don't want to return anything, you can use void like this:
public void returnCopy(){
// code
}
Same issue with public int getAvailableCopies(), this is supposed to return an int but you are not returning anything.
Be careful:
this method:
public static String getTitle() {
return getTitle();
}
is a recursive method without a base condition. This will cause an error and force your application to crash.
You've defined the method as returning a String but you don't return a value anywhere in the method body. Simplest fix is probably to change the return type to void...
public void returnCopy() {...
}
All the above answer are pointing to the same issue, you have defined methods that are breaking the contract about what they return..
In you code you have as well something like this:
public int getAvailableCopies() {
}
so you are telling the compiler, you have a method with the name getAvailableCopies, it takes no params and return an integer.
BUT if you don't return anything, then you are contradicting your own method, your own contract, this is an enough reason for a compiler to complain...
Conclusion:
keep in mind the information that defines the method.

CacheLoader loading the same keys in multiple times

I am getting duplicate keys in my cacheIterator.
I'm calling a web service using SOAP to rate policies for an insurance company. I am attempting to use a Cachebuilder / loader to store the DTO's as a key and the response from the service as a value. From what I've researched, the .get and .getUnchecked methods will get a value from the cache and if it's not there, it will load that value into the cache.
here is some code:
public class CacheLoaderImpl
{
private static CacheLoaderImpl instance = null;
private static LoadingCache<PolicyDTO, RatingServiceObjectsResponse> responses;
protected CacheLoaderImpl()
{
responses = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
new CacheLoader<PolicyDTO, RatingServiceObjectsResponse>() {
public RatingServiceObjectsResponse load(PolicyDTO key)
throws Exception
{
return getResponse(key);
}
});
}
public static CacheLoaderImpl getIntance()
{
if(instance == null)
{
instance = new CacheLoaderImpl();
}
return instance;
}
public LoadingCache<PolicyDTO, RatingServiceObjectsResponse> getResponses()
{
return responses;
}
public RatingServiceObjectsResponse getResponse(PolicyDTO key) throws ExecutionException
{
RatingServiceObjectsResponse response = new RatingServiceObjectsResponse();
try
{
response = new CGIRatabaseServiceImpl().getCoverages(key);
}
catch (RemoteException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
return response;
}
}
And this is where I call the get method:
RatingServiceObjectsResponse response = CacheLoaderImpl.getIntance().getResponses().get(policy.toCoveragesCallDTO());
I was under the assumption that maybe it was comparing memory addresses which would be different so I overwrote the toString method to convert the DTO object to JSON. Upon inspecting the cache I can see that the keys are exactly the same with a compare tool. Yet, they're still being stored and calling the service every single time. I tried overwriting the equals method on PolicyDTO but it is never hit when I debug.
How can I make the cacheloader only load values of different keys and pull existing values out as it is originally intended?
I think I just don't have a solid idea how the cacheLoader actually works. I appreciate any help or suggestions.
PolicyDTO class:
public class PolicyDTO extends AbstractDto implements IPolicyDTO
{
private ArrayList<ILineOfBusinessDTO> lobDTOs = new ArrayList<ILineOfBusinessDTO>();
private String pcInd;
private String ratingEffectiveDate;
private String companyName;
public String getPcInd()
{
return pcInd;
}
public void setPcInd(String pcInd)
{
this.pcInd = pcInd;
}
public String getRatingEffectiveDate()
{
return ratingEffectiveDate;
}
public void setRatingEffectiveDate(AdvancedDate ratingEffectiveDate)
{
if(ratingEffectiveDate != null)
{
this.ratingEffectiveDate = ratingEffectiveDate.toFormattedStringMMDDYYYY();
}
else
{
this.ratingEffectiveDate = new AdvancedDate().toFormattedStringMMDDYYYY();
}
}
public String getCompanyName()
{
return companyName;
}
public void setCompanyName(String companyName)
{
this.companyName = companyName;
}
public DtoType getType()
{
return hasGetCoveragesCoverageDTO() ? DtoType.GET_COVERAGE_POLICY : DtoType.RATE_POLICY;
}
public boolean hasGetCoveragesCoverageDTO()
{
if(lobDTOs != null)
{
for(ILineOfBusinessDTO lineDTO : lobDTOs)
{
if(lineDTO.hasGetCoveragesCoverageDTO())
{
return true;
}
}
}
return false;
}
#Override
public void addLob(ILineOfBusinessDTO lob) {
lobDTOs.add(lob);
}
#Override
public Iterator<ILineOfBusinessDTO> getLobIterator() {
return lobDTOs.iterator();
}
public ICoverageDTO findCoverage(String coverageID)
{
ICoverageDTO coverageDTO = null;
for(ILineOfBusinessDTO lineDTO : lobDTOs)
{
coverageDTO = lineDTO.findCoverage(coverageID);
if(coverageDTO != null)
{
return coverageDTO;
}
}
return null;
}
#Override
public String toString()
{
return JSONConversionUtility.convertPolicyDTO(this);
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result
+ ((companyName == null) ? 0 : companyName.hashCode());
result = prime * result + ((lobDTOs == null) ? 0 : lobDTOs.hashCode());
result = prime * result + ((pcInd == null) ? 0 : pcInd.hashCode());
result = prime
* result
+ ((ratingEffectiveDate == null) ? 0 : ratingEffectiveDate
.hashCode());
return result;
}
#Override
public boolean equals(Object object)
{
if(object instanceof PolicyDTO)
{
return object.toString().equals(this.toString());
}
return false;
}
}
Your PolicyDTO class has hashCode inconsistent with equals - it violates the following rule:
If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce
the same integer result.
Cache uses hashCode (much like HashMap class does), so when it sees two keys with different hashcodes, it assumes they are not equal.

How would you add a delete and edit function to the Address book program?

So i am practicing TableView through this example:
http://docs.oracle.com/javase/8/javafx/fxml-tutorial/fxml_tutorial_intermediate.htm
I understand everything in it, except I wanted to extend it further and include a delete and edit function as well. Could somebody please help me!? I've been trying for a while now but nothing seems to be working.
This is my add function (which works):
#FXML
protected void addMusic(ActionEvent actionEvent) {
ObservableList<Music> data = tableView.getItems();
data.add(new Music(albumField.getText(),
songField.getText(),
genreField.getText()
));
albumField.setText("");
songField.setText("");
genreField.setText("");
}
my Delete function which doesn't work:
#FXML
protected void deleteMusic(ActionEvent actionEvent) {
ObservableList<Music> data = tableView.getItems();
data.remove(new Music(albumField.deleteText(),
songField.deleteText(),
genreField.deleteText()
));
}
}
Thanks
Changed deleteMusic:
#Override
protected void deleteMusic(ActionEvent actionEvent) {
ObservableList<Music> data = tableView.getItems();
data.remove(equals(Music(albumField.deleteText(), songField.deleteText(), genreField.deleteText());
albumField.setText("");
songField.setText("");
genreField.setText("");
}
Music class:
package sample;
import javafx.beans.property.SimpleStringProperty;
public class Music {
private final SimpleStringProperty album = new SimpleStringProperty("");
private final SimpleStringProperty song = new SimpleStringProperty("");
private final SimpleStringProperty genre = new SimpleStringProperty("");
public Music() {
this("", "", "");
}
public Music(String album, String song, String genre) { //Constructor utilised
setAlbum(album);
setSong(song);
setGenre(genre);
}
public String getAlbum() {
return album.get();
}
public void setAlbum(String sAlbum) {
album.set(sAlbum);
}
public String getSong() {
return song.get();
}
public void setSong(String sAlbum) {
song.set(sAlbum);
}
public String getGenre() {
return genre.get();
}
public void setGenre(String sAlbum) {
genre.set(sAlbum);
}
}
http://i.stack.imgur.com/2SoWs.png
Most java Collections use the equals method to check, if 2 objects are considered to be the same. If the elements of a collection don't override equals, no 2 different objects are considered to be equal, even if they contain equal values in their fields.
You could override equals like this:
...
import java.util.Objects;
public class Music {
...
#Override
public boolean equals(Object obj) {
// make sure equals is symetric
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Music other = (Music) obj;
// compare strings for equality
return Objects.equals(this.getAlbum(), other.getAlbum())
&& Objects.equals(this.getSong(), other.getSong())
&& Objects.equals(this.getGenre(), other.getGenre());
}
}
You could then use
data.remove(new Music(albumField.getText(), songField.getText(), genreField.getText()));
to remove a Music object from the list.

How to subclass BasicPermission to add actions

I want to create a subclass of BasicPermission to add actions, which according to the the java docs should be possible:
Subclasses may implement actions on top of BasicPermission, if desired.
Here is my initial attempt:
public class BasicPermissionWithActions extends BasicPermission {
String actions;
String[] actionList;
String name;
public BasicPermissionWithActions(String name, String actions) {
super(name, actions);
this.actions = actions;
this.actionList = actions.split("\\,");
this.name = name;
}
private static final long serialVersionUID = 7608854273379948062L;
#Override
public boolean implies(Permission p) {
// name and class check can be done by super
if (!super.implies(p))
return false;
// now check actions
String requestedActions = p.getActions();
String[] requestedActionList = requestedActions.split("\\,");
for (String requestedAction : requestedActionList) {
if (!hasRequestedAction(requestedAction))
return false;
}
return true;
}
private boolean hasRequestedAction(String requestedAction) {
for (String action : actionList) {
if (action.equals(requestedAction))
return true;
}
return false;
}
#Override
public String getActions() {
return actions;
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((actions == null) ? 0 : actions.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
BasicPermissionWithActions other = (BasicPermissionWithActions) obj;
if (actions == null) {
if (other.actions != null)
return false;
} else if (!actions.equals(other.actions))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
#Override
public String toString() {
return "(\"" + this.getClass().getName() + "\" \"" + name + "\" \"" + actions + "\")";
}
And an entry in the policy file to grant access using this permission (in this case I'm specify a permission which should be insufficient to allow the desired action):
grant principal sample.principal.SampleGroup "TestGroup" {
permission BasicPermissionWithActions "*", "read";
};
And the code to check the permission:
rep.getAccessControlContext().checkPermission(new BasicPermissionWithActions(getName(), "write"));
I expect this check to fail since the policy has only specified a read action. However the check passes quietly.
The problem is that whenever the permission in the policy file has name "*", the actions are never checked. Running in debug mode shows that the method BasicPermissionWithActions.implies method is never called.
If I omit the permission from the policy file I get a security exception as expected but I cannot make actions work.
The problem is related to PermissionCollection. BasicPermission implements its own PermissionCollection for better performance. Unfortunately, this implementation makes some simplifying assumptions which break the semantics for subclasses. Specifically it implements a shortcut for "*" which bypasses the Permission.implies method and always returns true.
The solution is to implement a custom PermissionCollection which simply calls the Permission.implies methods of its members:
private class CustomPermissionCollection extends PermissionCollection {
private static final long serialVersionUID = 5654758059940546018L;
Collection<Permission> perms = new ArrayList<Permission>();
#Override
public void add(Permission permission) {
perms.add(permission);
}
#Override
public boolean implies(Permission permission) {
for (Permission p : perms) {
if (p.implies(permission))
return true;
}
return false;
}
#Override
public Enumeration<Permission> elements() {
return Collections.enumeration(perms);
}
}
and return this in the newPermissionCollection method of BasicPermissionWithActions
#Override
public PermissionCollection newPermissionCollection() {
return new CustomPermissionCollection();
}

Categories