dimanche 29 mars 2015

Binary Search Tree searching in java



I'm attempting to make a BST program that is capable of inserting a given number and then telling the user if the number is in the BST by saying either true or false. However, even if the number is inserted, it always registers as false. Would anyone be able to tell me where I am going wrong here? I can supply the rest of my class files if they are needed.



public class BinarySearchTree implements BST
{
private int n;
private Node r;
private Node l;

public void enter(int num)
{
Node node = new Node(num);

if (num < node.getData())
{
if (node.getL() != null)
{
insert(num);
}

else
{
node.setL(new Node(num));
}
}

else if (num > node.getData())
{
if (node.getR() != null)
{
insert(num);
}

else
{
node.setR(new Node(num));
}
}
}

public boolean search (int num)
{
if (num == this.n)
{
return true;
}

else if (num > this.n)
{
if (r == null)
{
return false;
}

else
{
return true;
}
}
else if (num < this.n)
{
if (l == null)
{
return false;
}
else
{
return true;
}
}
return false;
}
}



Using write method to save a picture file in Java



I need to save a picture object into the working directory with a specific file name using the write method. Here's my code:


public void storePhotos(String directory){



for(int i = 0; i < labelledPhotos.length; i++){
Picture currentPhoto = new Picture(labelledPhotos[i].getLabelledPhoto());

String fileName = directory + "/" + labelledPhotos[i].getYear() + "_" + labelledPhotos[i].getCategory() + "_" + labelledPhotos[i].getId() + ".jpg";
currentPhoto.write(fileName);

}


The user is suppose to input the director as the parameter and I need to save the image to the directory. For some reason the write method isn't saving it. If I hard code in the directory into the write parameter like:


currentPhoto.write("pic.jpg");


then the photo gets saved into directory. So I know its something wrong with the String fileName and how it gets passed into the write method, but I'm not sure what. Any help would be greatly appreciated.




Java vs JavaScript increment operator



In Java, if I do this



int value = 3;
int incr = value++;


incr is 4


but in JavaScript,



int value = 3;
int incr = value++;


incr is 3


in order for incr to be 4 in JS I have to do



int incr = ++value;


why is this?




Program loops where it shouldnt [duplicate]




This question already has an answer here:




I want the interface to go back to 'Enter a command' menu after it has completed a command (unless the user inputs "exit")but it keeps repeating the same interface for that command over and over again. e.g when the user inputs "register" the system should ask for name then phone number then email address and then says the staff member has been created (given the user input the correct type of input). The system should then ask for another command but instead it will ask for name, phone number and email address and will register another staff member. Please help?



public static void main(String args[]){
RoomBookSystem rbs = new RoomBookSystem();

//add rooms to the system
Room room1=new Room();
Room room2=new Room();
Room room3=new Room();
Room room4=new Room();

room1.setName("1");
room1.setCapacity(247);
room1.setEquipment("Projector");;
room1.setID(2);

room2.setName("2");
room2.setCapacity(18);
room2.setEquipment("Waffle maker, television");
room2.setID(2);

room3.setName("3");
room3.setCapacity(10);
room3.setEquipment("Television");
room3.setID(3);

room4.setName("4");
room4.setCapacity(12);
room4.setEquipment("Piano");
room1.setID(4);

rbs.addRoom(room1);
rbs.addRoom(room2);
rbs.addRoom(room3);
rbs.addRoom(room4);

//adds staff to the system
Staff kai = new Staff();
Staff sehun = new Staff();
Staff xiumin = new Staff();
Staff chen = new Staff();

kai.setName("Kai");
kai.setPhoneNumber("123456789");
kai.setEmailAddress("kai@exo.com");

sehun.setName("Sehun");
sehun.setPhoneNumber("6758302");
sehun.setEmailAddress("yehet@exo.com");

xiumin.setName("Xiumin");
xiumin.setPhoneNumber("90");
xiumin.setEmailAddress("xiurista@exo.com");


chen.setName("Chen");
chen.setPhoneNumber("609090900");
chen.setEmailAddress("chensingmachine@exo.com");

rbs.registerStaff(kai);
rbs.registerStaff(xiumin);
rbs.registerStaff(sehun);
rbs.registerStaff(chen);


//Starts the room booking interface
System.out.println("*************************************************");
System.out.println("Welcome to the room booking system!");
System.out.println("*************************************************");
System.out.println("The following rooms are available: ");
rbs.printRooms();
System.out.println("-------------------------------------------------");
System.out.println("Enter a command: (register, book, rooms, print, cancel, exit)");


Scanner scan = new Scanner(System.in);
String userCommand = scan.nextLine();
//while(userCommand!="exit"){
while(userCommand=="register"){

System.out.println("enter your name: ");
Staff newStaff = new Staff();
String name = scan.nextLine();
newStaff.setName(name);

System.out.println("Enter your email address: ");
String emailAddress = scan.nextLine();
newStaff.setEmailAddress(emailAddress);

System.out.println("Enter your phone number");
String phoneNumber=scan.nextLine();
newStaff.setPhoneNumber(phoneNumber);

rbs.registerStaff(newStaff);

System.out.println("Staff member: "+name+", "+emailAddress+", "+phoneNumber+" has been registered");


} if(userCommand=="book"){
System.out.println("Booking a new meeting: ");
System.out.println("Enter staff name");

String staffName = scan.nextLine();

if(rbs.isRegistered(staffName)){
Staff staffBooker = new Staff();
for(int i =0; i<rbs.currentStaff.length;i++){
if(rbs.currentStaff[i].getName()==staffName){
staffBooker=rbs.currentStaff[i];
}

Room newRoom = new Room();
System.out.println("Enter a room ID: ");
int roomID = scan.nextInt();

System.out.println("Enter a month: ");
int month= scan.nextInt();

System.out.println("Enter day: ");
int day = scan.nextInt();

System.out.println("Enter starting hour: ");
int startingHour=scan.nextInt();

System.out.println("Enter duration: ");
int duration = scan.nextInt();

newRoom.setID(roomID);

TimeInterval newTimeInterval = new TimeInterval(startingHour,day,month,duration);

Meeting newMeeting = new Meeting(staffBooker, newTimeInterval, newRoom);

rbs.bookMeeting(newMeeting);

}
}

} else if(userCommand=="rooms"){
Room newRoom = new Room();
System.out.println("Add a new room");
System.out.println("Enter room ID: ");
int roomID = scan.nextInt();

System.out.println("Enter room capacity: ");
int roomCapacity = scan.nextInt();

System.out.println("Enter equipment available in room: ");
String equipment = scan.nextLine();

newRoom.setID(roomID);
newRoom.setCapacity(roomCapacity);
newRoom.setEquipment(equipment);

rbs.addRoom(newRoom);

} else if(userCommand=="print"){
rbs.printRooms();
rbs.printMeeting();
rbs.printStaff();

scan.close();
System.out.println("Goodbye");
System.exit(0);


}


}




How to consume a Jax-RS 2.0 Response from Mule Apikit



I am trying to consume a JAX-RS 2 Response with Jersey client 2.17.



Response response = ClientBuilder.newClient()
.target("http://localhost:8080/api")
.path("organisations")
.request(MediaType.APPLICATION_JSON)
.get(); //[1] .get(GetOrganisationsResponse.class);
//[2] System.out.println("headers=" + response.getHeaders());
//[3] String json = response.readEntity(String.class);
//[4] System.out.println("json=" + json);
Organisations orgs = response.readEntity(Organisations.class);


The response is served by Mule apikit.



<flow name="get:/organisations:my-api-config" >
<set-payload value="#[app.registry['organisations'].getOrganisations(message.inboundProperties['start'], message.inboundProperties['pages'])]" doc:name="Set Payload" />
</flow>


POJOs are generated from a RAML description. Here is the generated POJO for the above service:



/**
* A collection of organisations
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"size",
"organisations"
})
public class Organisations {

/**
*
* (Required)
*
*/
@JsonProperty("size")
private Integer size;
@JsonProperty("organisations")
private List<Organisation> organisations = new ArrayList<Organisation>();
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

/**
*
* (Required)
*
* @return
* The size
*/
@JsonProperty("size")
public Integer getSize() {
return size;
}

/**
*
* (Required)
*
* @param size
* The size
*/
@JsonProperty("size")
public void setSize(Integer size) {
this.size = size;
}

public Organisations withSize(Integer size) {
this.size = size;
return this;
}

/**
*
* @return
* The organisations
*/
@JsonProperty("organisations")
public List<Organisation> getOrganisations() {
return organisations;
}

/**
*
* @param organisations
* The organisations
*/
@JsonProperty("organisations")
public void setOrganisations(List<Organisation> organisations) {
this.organisations = organisations;
}

public Organisations withOrganisations(List<Organisation> organisations) {
this.organisations = organisations;
return this;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

public Organisations withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
}


... and here is the generated GetOrganisationsResponse for the same service:



public class GetOrganisationsResponse
extends support.ResponseWrapper
{


private GetOrganisationsResponse(Response delegate) {
super(delegate);
}

/**
* OK
*
* @param entity
*
*/
public static Organisations.GetOrganisationsResponse withJsonOK(model.Organisations entity) {
Response.ResponseBuilder responseBuilder = Response.status(200).header("Content-Type", "application/json");
responseBuilder.entity(entity);
return new Organisations.GetOrganisationsResponse(responseBuilder.build());
}

}


In trying to GET an instance of Organisations on the client side, I observed the following:



  • All the properties from Organisations end up populated in the additionalProperties member suggesting none were recognized by the parser,

  • If I comment out the additionalProperties member and getter/setter, the parser's error is this:



com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "date" (class model.Organisations), not marked as ignorable (2 known properties: "size", "organisations"])




  • ... this makes sense if the date, headers (and others) fields were not mapped to the Response, but to the Organisations instead but why?

  • when uncommenting the lines marked 2, 3 and 4, the Response converted to String looks as follows. Shouldn't the GetOrganisationsResponse headers have been parsed and returned as a result of response.getHeaders() ?



headers={X-MULE_ENCODING=[UTF-8], Date=[Mon, 30 Mar 2015 02:16:57 +0000], Content-Length=[746], X-MULE_SESSION=[...], Connection=[close], http.status=[200], Content-Type=[application/json], Server=[Mule Core/3.6.1]} json={"date":null,"lastModified":null,"headers":{"Content-Type":["application/json"]},"entity":{"size":3,"organisations":[{"oid":"54df33936d725e370b000004","name":"org1","additionalProperties":{}},{"oid":"54df34406d725e370b000006","name":"org2","additionalProperties":{}},{"oid":"54df33c96d725e370b000005","name":"org3","additionalProperties":{}}],"additionalProperties":{}},"status":200,"mediaType":{"type":"application","subtype":"json","parameters":{},"wildcardType":false,"wildcardSubtype":false},"allowedMethods":[],"links":[],"cookies":{},"entityTag":null,"statusInfo":"OK","metadata":{"Content-Type":["application/json"]},"stringHeaders":{"Content-Type":["application/json"]},"length":-1,"language":null,"location":null}




  • Finally when trying to force the Response as generated on the server side with .get(GetOrganisationsResponse.class) (uncommenting 1), the outcome is:



Can not find a deserializer for non-concrete Map type [map type; class javax.ws.rs.core.MultivaluedMap, [simple type, class java.lang.String] -> [collection type; class java.util.List, contains [simple type, class java.lang.String]]]





  • The culprit is the following code in the parent class of GetOrganisationResponse called ResponseWrapper:


    @Override public MultivaluedMap getHeaders() { return delegate.getHeaders(); }


    @Override public MultivaluedMap getStringHeaders() { return delegate.getStringHeaders(); }




Thanks for pointing me in the right direction:



  1. Is client.get() or client.get(GetOrganisationsResponse.class) the recommended aproach to parse a Mule Apikit response on the client? (I could not find answers in Mule docs)

  2. Considering I get errors for either option: Thanks for your help&ideas on how to fix them.




Issue in checkstyle configuaration in IntelliJ Idea



My objective is to implement Google's Java Style Checkstyle as stated in http://ift.tt/1ET0LMG .


In IntelliJ I have enabled Checkstyle plugin and try to point checkstyle xml ( downloaded from http://ift.tt/1EuY6wf).


I got following exception stated Property 'fileExtensions' in module Checker does not exist though this property is defined in the xml as "property name="fileExtensions" value="java, properties, xml"


Exception details:


org.infernus.idea.checkstyle.exception.CheckStylePluginException: The CheckStyle rules file could not be loaded.

Property 'fileExtensions' in module Checker does not exist, please check the documentation at org.infernus.idea.checkstyle.checker.CheckerFactory.blacklistAndShowMessage(CheckerFactory.java:248) at org.infernus.idea.checkstyle.checker.CheckerFactory.createChecker(CheckerFactory.java:202)




where is a sample JAX-RS client sample?



I'm aware of the Java API for Yahoo Finance. I'm looking for a sample "hello world" client which uses, for example, Yahoo Finance, or, perhaps, some other publicly available RESTful API to test against.


see also:


http://ift.tt/1a8TSiN


http://ift.tt/1sXQ3j6


The Jersey example above seems ok. Just adapt it to Yahoo Finance?


(Not a well researched question, admittedly. Only trying to avoid going down a rabbit hole.)