A few of my classes aren't passing automated tests. Unfortunately, said tests do not provide any useful information about why they failed. Here is my code for a couple of the classes. I'd really appreciate it if you could tell me where I went wrong. The comments should explain what each method is supposed to do.
public class CellPhone {
protected String ownerName;
public CellPhone(String owner) {
ownerName = owner;
}
public String receiveCall(CellPhone sender) {
// returns a String of the form:
// owner's name " is receiving a call from " sender's name
String receivingCall = ownerName + " is receiving a call from " + sender;
return receivingCall;
}
public String call(CellPhone receiver) {
// returns a String by using the receiver to invoke receiveCall
// while passing in the current phone
String invokingReceiveCall = receiver.receiveCall(receiver);
return invokingReceiveCall;
}
}
public class TextMessagingPhone extends CellPhone {
private int availMessages;
public TextMessagingPhone(String owner, int messageLimit) {
// invokes the superclass constructor
super(owner);
// sets the new instance variable
availMessages = messageLimit;
}
public TextMessagingPhone(String owner) {
// invokes the other constructor of this class with 15 as the message limit
this(owner, 15);
}
public String receiveText(TextMessagingPhone sender, String message) {
// decreases the number of messages available to send
availMessages--;
// returns a String of the form:
// owner's name " has received TEXT from " sender's name ":" message
String receivedText = ownerName + " has received TEXT from " + sender + ":" + message;
return receivedText;
}
public String sendText(TextMessagingPhone receiver, String message) {
// decreases the number of messages available to send
availMessages--;
// returns a String by using the receiver to invoke receiveText
// while passing in the current phone and the message
String invokingReceiveText = receiver.receiveText(receiver, message);
return invokingReceiveText;
}
}
When a phone makes a call, it passes the receiver as a parameter, so the receiver thinks it is receiving from itself. Also it never gets the name from the passed sender. Try:
public String receiveCall(CellPhone sender) {
// returns a String of the form:
// owner's name " is receiving a call from " sender's name
String receivingCall = ownerName + " is receiving a call from " + sender.getName();
return receivingCall;
}
public String call(CellPhone receiver) {
// returns a String by using the receiver to invoke receiveCall
// while passing in the current phone
String invokingReceiveCall = receiver.receiveCall(this);
return invokingReceiveCall;
}
public String getName() {
return ownerName;
}
public CellPhone(String owner) {
}
You don't assign anything to ownerName...
public CellPhone(String owner) {
ownerName = owner;
}
Check this
String receivingCall = ownerName + " is receiving a call from " + sender;
You are using "sender" which is an object in the string expression. Using sender.ownerName after making it public or defining getOwnerName and using it should work. This same mistake is repeated couple more times!
Related
I'm creating an eAuction system and I have a method for browsing auctions. Each auction has a status (OPEN or CLOSED) and I want the browseAuctions method to only print out auctions that are opened.
I've tried a number of if statements and it always keeps printing out every single auction.
The following code is a few things I've hardcoded to test the system
public List<Auction> auctionSystem() throws Exception {
List<Auction> auctions = new LinkedList<Auction>();
auctions.add(new Auction (35.50, 75.50, 40.00, users.get(3), LocalDateTime.now().minusSeconds(60), "Xbox", users.get(1), Status.OPEN));
auctions.add(new Auction (27.00, 42.00, 32.00, users.get(2), LocalDateTime.now().plusSeconds(10), "PS3", users.get(1), Status.OPEN));
auctions.add(new Auction (19.00, 21.00, 50.00, users.get(2), LocalDateTime.now().minusSeconds(1), "iPhone", users.get(1), Status.CLOSED));
return auctions;
}
This is the Auction class constructor:
public Auction (double startPrice, double reservePrice, double currentBid, User highestBidder, LocalDateTime closeDate, String item, User seller, Status status) throws Exception {
if (closeDate.isBefore(LocalDateTime.now().plusDays(7))) {
this.startPrice = startPrice;
this.reservePrice = reservePrice;
this.closeDate = closeDate;
this.item = item;
this.highestBidder = highestBidder;
this.currentBid = currentBid;
this.seller = seller;
UP = currentBid * 0.20;
LOW = currentBid * 0.10;
} else {
throw new Exception ("CloseDate error: " + closeDate.format(formatter));
}
}
This is the Status class:
public enum Status {
OPEN, CLOSED
}
This is the method inside the Auction class to browse auctions:
public void browseAuctions () {
System.out.println("-----All Auctions-----");
for (Auction a : auctions) {
if (a.status.equals(Status.OPEN)){
System.out.println("Item: " + a.getItem());
System.out.println("Current Bid: " + "£" + a.getCurrentBid());
System.out.println("Close Date: " + a.getCloseDate());
}
}
}
}
The status is ignored in the constructor, therefore all the Auction instances shall be not be qualified according to the condition in the loop. I wonder all pass and the only explanation is that the Status.OPEN is set by default, it means you have the following declaration in the code:
private Status status = Status.OPEN;
Since it is missing in the constructor, it is not set to a new passed value. These are problems with mutable fields, so I suggest you declare them final and resolve a default value with a secondary constructor:
private final Status status;
// the rest
public Auction (double sPrice, double rPrice, double currentBid,
User highestBidder, LocalDateTime closeDate, String item, User seller)
{
this(sPrice, rPrice, currentBid, highestBidder, closeDate, item, seller, Status.OPEN)
}
Anyway, to fix your issue, complete the constructor with:
this.status = status;
I'm attempting to convert the JSON output from my session and map it to a class that I've created using JAVA's ObjectMapper. When I run my tests on Lambda I get a Deserialisation error:
Deserialization error: com.amazon.ask.exception.AskSdkException
com.amazon.ask.exception.AskSdkException: Deserialization error
at com.amazon.ask.util.impl.JacksonJsonUnmarshaller.unmarshall(JacksonJsonUnmarshaller.java:50)
at com.amazon.ask.impl.AbstractSkill.execute(AbstractSkill.java:44)
at com.amazon.ask.AlexaSkill.execute(AlexaSkill.java:22)
at com.amazon.ask.SkillStreamHandler.handleRequest(SkillStreamHandler.java:71)
Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'AnswerIntent' as a subtype of [simple type, class com.amazon.ask.model.Request]: known type ids = [Alexa.Presentation.APL.UserEvent, AlexaHouseholdListEvent.ItemsCreated, AlexaHouseholdListEvent.ItemsDeleted, AlexaHouseholdListEvent.ItemsUpdated, AlexaHouseholdListEvent.ListCreated, AlexaHouseholdListEvent.ListDeleted, AlexaHouseholdListEvent.ListUpdated, AlexaSkillEvent.SkillAccountLinked, AlexaSkillEvent.SkillDisabled, AlexaSkillEvent.SkillEnabled, AlexaSkillEvent.SkillPermissionAccepted, AlexaSkillEvent.SkillPermissionChanged, AudioPlayer.PlaybackFailed, AudioPlayer.PlaybackFinished, AudioPlayer.PlaybackNearlyFinished, AudioPlayer.PlaybackStarted, AudioPlayer.PlaybackStopped, Connections.Request, Connections.Response, Display.ElementSelected, GameEngine.InputHandlerEvent, IntentRequest, LaunchRequest, Messaging.MessageReceived, PlaybackController.NextCommandIssued, PlaybackController.PauseCommandIssued, PlaybackController.PlayCommandIssued, PlaybackController.PreviousCommandIssued, SessionEndedRequest, System.ExceptionEncountered] (for POJO property 'request')
at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.amazon.ask.model.RequestEnvelope$Builder["request"])
at com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43)
at com.fasterxml.jackson.databind.DeserializationContext.invalidTypeIdException(DeserializationContext.java:1628)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownTypeId(DeserializationContext.java:1186)
at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._handleUnknownTypeId(TypeDeserializerBase.java:291)
at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._findDeserializer(TypeDeserializerBase.java:162)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedForId(AsPropertyTypeDeserializer.java:113)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:97)
at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserializeWithType(AbstractDeserializer.java:254)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeSetAndReturn(MethodProperty.java:151)
at com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer.vanillaDeserialize(BuilderBasedDeserializer.java:269)
at com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer.deserialize(BuilderBasedDeserializer.java:193)
at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3972)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2264)
at com.fasterxml.jackson.databind.ObjectMapper.treeToValue(ObjectMapper.java:2746)
at com.amazon.ask.util.impl.JacksonJsonUnmarshaller.unmarshall(JacksonJsonUnmarshaller.java:48)
... 3 more
I did checks to ensure that my "riddleItem" variable is not null. The JSON values are being mapped to the Person class which just returns properties of a person. The code is shown below and I've highlighted the line which the error occurs on:
public Optional<Response> handle(HandlerInput input) {
Map<String, Object> sessionAttributes = input.getAttributesManager().getSessionAttributes();
System.out.println("This a FIRST debug");
LOG.debug("This a FIRST debug");
boolean correctAnswer;
String speechText = null, response;
System.out.println("This a SECOND debug");
Map<String, String> riddleItem = (LinkedHashMap<String, String>)sessionAttributes.get(Attributes.RIDDLE_ITEM_KEY);
Person person;
// System.out.println("riddleItem " + riddleItem);
if(riddleItem != null)
{
person = MAPPER.convertValue(riddleItem, Person.class); // ERROR OCCURS ON THIS LINE
}
System.out.println("This a THIRD debug");
PersonProperty personProperty = PersonProperty.valueOf((String) sessionAttributes.get(Attributes.RIDDLE_PROPERTY_KEY));
int counter = (int) sessionAttributes.get(Attributes.COUNTER_KEY);
int riddleGameScore = (int) sessionAttributes.get(Attributes.RIDDLE_SCORE_KEY);
System.out.println("This a FOURTH debug");
IntentRequest intentRequest = (IntentRequest) input.getRequestEnvelope().getRequest();
correctAnswer = compareSlots(intentRequest.getIntent().getSlots(), getPropertyOfPerson(personProperty, person));
System.out.println("This a FIFTH debug " + correctAnswer);
if(correctAnswer)
{
riddleGameScore++;
response = getSpeechExpressionCon(true);
System.out.println("This a SIXTH debug " + response);
sessionAttributes.put(Attributes.RIDDLE_SCORE_KEY, riddleGameScore);
}
else
{
response = getSpeechExpressionCon(false);
System.out.println("This a SEVENTH debug " + response);
}
AnswerIntentHandler setup = new AnswerIntentHandler();
//
if(riddle.getAnswer() != null)
{
speechText = "Hello " + riddle.getAnswer();
}
return input.getResponseBuilder()
.withSimpleCard("RiddleSession", speechText)
.withSpeech(speechText)
.withShouldEndSession(true)
.build();
}
[Json Output of properties under "riddleItem" during Session]1
I know my the values being mapped aren't empty thus I'm at a complete loss of ideas as to what's going on as I've come up short with possible ideas as to what the problem might be.
I solved the problem as I came to realise that when mapping from JSON to a class, methods ('set' methods) for assigning the JSON values to the variables in the class must be created. A sample structure for example:
public class State {
public State() {}
public State(String name, String abbreviation, String capital, String statehoodYear, String statehoodOrder) {
this.name = name;
this.abbreviation = abbreviation;
this.capital = capital;
this.statehoodYear = statehoodYear;
this.statehoodOrder = statehoodOrder;
}
public String getName() {
return name;
}
public String getAbbreviation() {
return abbreviation;
}
public String getCapital() {
return capital;
}
public String getStatehoodYear() { return statehoodYear; }
public String getStatehoodOrder() {
return statehoodOrder;
}
public void setName(String name) {
this.name = name;
}
public void setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
}
public void setCapital(String capital) {
this.capital = capital;
}
public void setStatehoodYear(String statehoodYear) {
this.statehoodYear = statehoodYear;
}
public void setStatehoodOrder(String statehoodOrder) {
this.statehoodOrder = statehoodOrder;
}
}
The declaration of an empty constructor is necessary when making use of multiple constructors where, one is parametric. In some cases without the inclusion of such constructor an error may be thrown so, to avoid the possibility of said error, adding the constructor as a "Dummy" so to say, is essential.
As the title says, I need a way(no matter if its complicated or not) to create a getData() method that would send request packet to the server > receive the message I already have the system setup but I have a problem with it that I only get the result in PluginMessageReceiveEvent Here's my code with explanations:
public String requestData(String path) {
SocketUtils.sendData("REQUEST|" + p.getPlayer().getUniqueId() + "|" + path, "playerconfig", "BUNGEE");
return /*Need to get data from the plugin message to here*/;
}
#EventHandler
public void onPluginMessageReceive(PluginMessageReceiveEvent e) {
if (e.getChannel().equalsIgnoreCase("playerconfig")) {
String[] args = e.getMessage().split("\\|");
String uuid = args[0];
String path = args[1];//Maybe a HashMap<Path, Data> but that would make the requestData() result return null because you don't get the data instantly.
String data = args[2].replace("_", " ");
if (uuid.equals(p.getPlayer().getUniqueId() + "")) {
return data; //I need to get this result on request data method.
}
}
}
A simple solution is to wait on a lock in the requestData and notify that lock in onPluginMessageReceive. Something like this:
synchronized(this) {
wait();
}
And in your receive method:
synchronized(this) {
notifyAll();
}
Make the data a member field of the class.
Look out for exception handling and syntax errors.
I have uploaded a test html page and servlet following this article exactly. This works and will send me an email. However, when I copy this code almost exactly into my SendEmail method in the code shown below it does not send an email. I know when I run this locally that it gets to the SendEmail method just fine (but you cannot send emails using the development server in GAE). When I deploy it there are no errors on the page or in the logs so it plain old seems like it is just not sending the email. Anyone see a reason why?
public class EmailService {
private static SimpleDateFormat dateFormatter = new SimpleDateFormat ("MM/dd/yyyy");
public static void SendDeadlineEmails() {
PersistenceManager pm = getPersistenceManager();
try {
List<DeadlineEmailObject> studentsWithDeadlineToday = populateEmailList(pm);
sendEmails(studentsWithDeadlineToday);
} finally {
pm.close();
}
}
private static List<DeadlineEmailObject> populateEmailList(PersistenceManager pm) {
List<Student> students = getStudents(pm);
List<DeadlineEmailObject> studentsWithDeadlineToday = new ArrayList<DeadlineEmailObject>();
String today = dateFormatter.format(System.currentTimeMillis());
for(Student student : students) {
Set<Charge> charges = student.getCharges();
if(charges != null) {
for(Charge charge : charges) {
String deadline = dateFormatter.format(charge.getDeadline());
if(deadline.equals(today)) {
studentsWithDeadlineToday.add(new DeadlineEmailObject(student, charge));
}
}
}
}
return studentsWithDeadlineToday;
}
#SuppressWarnings("unchecked")
private static List<Student> getStudents(PersistenceManager pm) {
return (List<Student>) pm.newQuery(Student.class).execute();
}
private static void sendEmails(List<DeadlineEmailObject> studentsWithDeadlineToday) {
for(DeadlineEmailObject emailObj : studentsWithDeadlineToday) {
sendEmail(emailObj);
System.out.println("Student: " + emailObj.getStudent().getFullName() + "\nAmount: " + emailObj.getCharge().getAmount() +
"\nDeadline: " + dateFormatter.format(emailObj.getCharge().getDeadline()));
}
}
private static void sendEmail(DeadlineEmailObject emailObj) {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("njbuwm#gmail.com", "Admin"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailObj.getStudent().getEmail(), emailObj.getStudent().getFullName()));
msg.setSubject("Deadline Reached");
msg.setText(buildMessage(emailObj));
Transport.send(msg);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String buildMessage(DeadlineEmailObject emailObj) {
String email = "";
email += "Dear " + emailObj.getStudent().getFullName() + " ,\n";
email += "You owe us money. This much: $" + emailObj.getCharge().getAmount() + ".\n";
email += "For this reason: " + emailObj.getCharge().getReason() + ".\n";
email += "The deadline is today and I advise you to pay it or you will be deported to Idontpaymybills Island forever.\n";
email += "Thank you,\n Automated Emailer";
return email;
}
private static PersistenceManager getPersistenceManager() {
return JDOHelper.getPersistenceManagerFactory("transactions-optional").getPersistenceManager();
}
}
Change your call to setFrom() to use an email address permitted in the Developers Guide:
To set the sender address, the app calls the setFrom() method on the
MimeMessage object. The sender address must be one of the following
types:
The address of a registered administrator for the application
The address of the user for the current request signed in with a Google Account. You can determine the current user's email address with the Users API. The user's account must be a Gmail account, or be on a domain managed by Google Apps.
Any valid email receiving address for the app (such as xxx#APP-ID.appspotmail.com).
I am new to FIX. I have a FIX message:
8=FIX.4.4|9=122|35=D|34=215|49=CLIENT12|52=20100225-19:41:57.316|56=B|1=Marcel|11=13346|21=1|40=2|44=5|54=1|59=0|60=20100225-19:39:52.020|10=072|
and I am using quickfixJ.
Here is my class code:
public String getYear(Message aMessage, SessionID aSessionID){
try {
crack(aMessage, aSessionID);
} catch (Exception e) {
e.printStackTrace();
}
String year = String.valueOf(mUTCCal.get(Calendar.YEAR));
String begin = String.valueOf(BeginString);
return year + " " + begin;
}
and when I call this method I 2012 null
I tried all sorts of methods for different fields and I get null. I am confused about why I do not get null for the date and how do I make it interpret correctly the other fields?
quickfix.fix44.NewOrderSingle message;
message = new quickfix.fix44.NewOrderSingle();
SessionID session = new SessionID("beginString", "senderCompID", "targetCompID");
MyApp app = new MyApp("", "", "");
String result = app.myMessage(message, session);
System.out.println(result);
I do not understand where to input the string I have (up top) into message
public void onMessage(Message message, SessionID sessionID) throws FieldNotFound {
Header header = message.getHeader();
String FIX = header.getString(8);
System.out.println(FIX);
}
public void onMessage(quickfix.fix44.NewOrderSingle message, SessionID sessionID) throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue {
Header header = message.getHeader();
String FIX = header.getString(8);
String a = message.getString(1);
System.out.println(a);
System.out.println(FIX);}
In order to correctly get and parse FIX messages via QuickFIX, you must:
Create your Application: http://www.quickfixengine.org/quickfix/doc/html/application.html
Implement FromApp(Message message, SessionID sessionID) method
Implement the cracked method for ALL your message types you will receive from your counterparty
The FromApp method can be very simple:
public void fromApp(Message message, SessionID sessionID)
{
crack(message, sessionID);
}
Now, in your example you have a message FIX 4.4 of type 35=D [NewOrderSingle]
Therefore, you MUST implement a method as follows:
public override void onMessage(QuickFix44.NewOrderSingle message, SessionID session)
{
base.onMessage(message, session);
}
Now into your method you can easily work with all the fields you need:
public override void onMessage(QuickFix44.NewOrderSingle message, SessionID session)
{
base.onMessage(message, session);
ClOrdID ordid = new ClOrdID();
message.get(ordid);
}
Please also take a look here: http://www.quickfixengine.org/quickfix/doc/html/receiving_messages.html