repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/BookingImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.entities; import java.io.Serializable; import java.util.*; import com.acmeair.entities.Booking; import com.acmeair.entities.Customer; import com.acmeair.entities.Flight; public class BookingImpl implements Booking, Serializable{ private static final long serialVersionUID = 1L; private BookingPKImpl pkey; private FlightPKImpl flightKey; private Date dateOfBooking; private Customer customer; private Flight flight; public BookingImpl() { } public BookingImpl(String id, Date dateOfFlight, Customer customer, Flight flight) { this(id, dateOfFlight, customer, (FlightImpl)flight); } public BookingImpl(String id, Date dateOfFlight, Customer customer, FlightImpl flight) { this.pkey = new BookingPKImpl(customer.getUsername(),id); this.flightKey = flight.getPkey(); this.dateOfBooking = dateOfFlight; this.customer = customer; this.flight = flight; } public BookingPKImpl getPkey() { return pkey; } // adding the method for index calculation public String getCustomerId() { return pkey.getCustomerId(); } public void setPkey(BookingPKImpl pkey) { this.pkey = pkey; } public FlightPKImpl getFlightKey() { return flightKey; } public void setFlightKey(FlightPKImpl flightKey) { this.flightKey = flightKey; } public void setFlight(Flight flight) { this.flight = flight; } public Date getDateOfBooking() { return dateOfBooking; } public void setDateOfBooking(Date dateOfBooking) { this.dateOfBooking = dateOfBooking; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Flight getFlight() { return flight; } @Override public String toString() { return "Booking [key=" + pkey + ", flightKey=" + flightKey + ", dateOfBooking=" + dateOfBooking + ", customer=" + customer + ", flight=" + flight + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BookingImpl other = (BookingImpl) obj; if (customer == null) { if (other.customer != null) return false; } else if (!customer.equals(other.customer)) return false; if (dateOfBooking == null) { if (other.dateOfBooking != null) return false; } else if (!dateOfBooking.equals(other.dateOfBooking)) return false; if (flight == null) { if (other.flight != null) return false; } else if (!flight.equals(other.flight)) return false; if (flightKey == null) { if (other.flightKey != null) return false; } else if (!flightKey.equals(other.flightKey)) return false; if (pkey == null) { if (other.pkey != null) return false; } else if (!pkey.equals(other.pkey)) return false; return true; } @Override public String getBookingId() { return pkey.getId(); } @Override public String getFlightId() { return flight.getFlightId(); } }
3,736
23.266234
89
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/BookingPKImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.entities; import java.io.Serializable; import com.acmeair.entities.BookingPK; import com.ibm.websphere.objectgrid.plugins.PartitionableKey; public class BookingPKImpl implements BookingPK, Serializable, PartitionableKey { private static final long serialVersionUID = 1L; private String id; private String customerId; public BookingPKImpl() { super(); } public BookingPKImpl(String customerId,String id) { super(); this.id = id; this.customerId = customerId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } @Override public Object ibmGetPartition() { return this.customerId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((customerId == null) ? 0 : customerId.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BookingPKImpl other = (BookingPKImpl) obj; if (customerId == null) { if (other.customerId != null) return false; } else if (!customerId.equals(other.customerId)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "BookingPK [customerId=" + customerId + ",id=" + id + "]"; } }
2,424
23.25
81
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/CustomerAddressImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.entities; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.CustomerAddress; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement public class CustomerAddressImpl implements CustomerAddress, Serializable{ private static final long serialVersionUID = 1L; private String streetAddress1; private String streetAddress2; private String city; private String stateProvince; private String country; private String postalCode; public CustomerAddressImpl() { } public CustomerAddressImpl(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode) { super(); this.streetAddress1 = streetAddress1; this.streetAddress2 = streetAddress2; this.city = city; this.stateProvince = stateProvince; this.country = country; this.postalCode = postalCode; } public String getStreetAddress1() { return streetAddress1; } public void setStreetAddress1(String streetAddress1) { this.streetAddress1 = streetAddress1; } public String getStreetAddress2() { return streetAddress2; } public void setStreetAddress2(String streetAddress2) { this.streetAddress2 = streetAddress2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStateProvince() { return stateProvince; } public void setStateProvince(String stateProvince) { this.stateProvince = stateProvince; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } @Override public String toString() { return "CustomerAddress [streetAddress1=" + streetAddress1 + ", streetAddress2=" + streetAddress2 + ", city=" + city + ", stateProvince=" + stateProvince + ", country=" + country + ", postalCode=" + postalCode + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CustomerAddressImpl other = (CustomerAddressImpl) obj; if (city == null) { if (other.city != null) return false; } else if (!city.equals(other.city)) return false; if (country == null) { if (other.country != null) return false; } else if (!country.equals(other.country)) return false; if (postalCode == null) { if (other.postalCode != null) return false; } else if (!postalCode.equals(other.postalCode)) return false; if (stateProvince == null) { if (other.stateProvince != null) return false; } else if (!stateProvince.equals(other.stateProvince)) return false; if (streetAddress1 == null) { if (other.streetAddress1 != null) return false; } else if (!streetAddress1.equals(other.streetAddress1)) return false; if (streetAddress2 == null) { if (other.streetAddress2 != null) return false; } else if (!streetAddress2.equals(other.streetAddress2)) return false; return true; } }
4,029
27.785714
80
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/CustomerImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.entities; import java.io.Serializable; import com.acmeair.entities.Customer; import com.acmeair.entities.CustomerAddress; public class CustomerImpl implements Customer, Serializable{ private static final long serialVersionUID = 1L; private String _id; private String password; private MemberShipStatus status; private int total_miles; private int miles_ytd; private CustomerAddress address; private String phoneNumber; private PhoneType phoneNumberType; public CustomerImpl() { } public CustomerImpl(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, CustomerAddress address, String phoneNumber, PhoneType phoneNumberType) { this._id = username; this.password = password; this.status = status; this.total_miles = total_miles; this.miles_ytd = miles_ytd; this.address = address; this.phoneNumber = phoneNumber; this.phoneNumberType = phoneNumberType; } @Override public String getCustomerId() { return _id; } public String getUsername() { return _id; } public void setUsername(String username) { this._id = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public MemberShipStatus getStatus() { return status; } public void setStatus(MemberShipStatus status) { this.status = status; } public int getTotal_miles() { return total_miles; } public void setTotal_miles(int total_miles) { this.total_miles = total_miles; } public int getMiles_ytd() { return miles_ytd; } public void setMiles_ytd(int miles_ytd) { this.miles_ytd = miles_ytd; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public PhoneType getPhoneNumberType() { return phoneNumberType; } public void setPhoneNumberType(PhoneType phoneNumberType) { this.phoneNumberType = phoneNumberType; } public CustomerAddress getAddress() { return address; } public void setAddress(CustomerAddress address) { this.address = address; } @Override public String toString() { return "Customer [id=" + _id + ", password=" + password + ", status=" + status + ", total_miles=" + total_miles + ", miles_ytd=" + miles_ytd + ", address=" + address + ", phoneNumber=" + phoneNumber + ", phoneNumberType=" + phoneNumberType + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CustomerImpl other = (CustomerImpl) obj; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; if (_id == null) { if (other._id != null) return false; } else if (!_id.equals(other._id)) return false; if (miles_ytd != other.miles_ytd) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (phoneNumber == null) { if (other.phoneNumber != null) return false; } else if (!phoneNumber.equals(other.phoneNumber)) return false; if (phoneNumberType != other.phoneNumberType) return false; if (status != other.status) return false; if (total_miles != other.total_miles) return false; return true; } }
4,208
23.758824
185
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/CustomerSessionImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.entities; import java.io.Serializable; import java.util.Date; import com.acmeair.entities.CustomerSession; public class CustomerSessionImpl implements CustomerSession, Serializable { private static final long serialVersionUID = 1L; private String _id; private String customerid; private Date lastAccessedTime; private Date timeoutTime; public CustomerSessionImpl() { } public CustomerSessionImpl(String id, String customerid, Date lastAccessedTime, Date timeoutTime) { this._id= id; this.customerid = customerid; this.lastAccessedTime = lastAccessedTime; this.timeoutTime = timeoutTime; } public String getId() { return _id; } public void setId(String id) { this._id = id; } public String getCustomerid() { return customerid; } public void setCustomerid(String customerid) { this.customerid = customerid; } public Date getLastAccessedTime() { return lastAccessedTime; } public void setLastAccessedTime(Date lastAccessedTime) { this.lastAccessedTime = lastAccessedTime; } public Date getTimeoutTime() { return timeoutTime; } public void setTimeoutTime(Date timeoutTime) { this.timeoutTime = timeoutTime; } @Override public String toString() { return "CustomerSession [id=" + _id + ", customerid=" + customerid + ", lastAccessedTime=" + lastAccessedTime + ", timeoutTime=" + timeoutTime + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CustomerSessionImpl other = (CustomerSessionImpl) obj; if (customerid == null) { if (other.customerid != null) return false; } else if (!customerid.equals(other.customerid)) return false; if (_id == null) { if (other._id != null) return false; } else if (!_id.equals(other._id)) return false; if (lastAccessedTime == null) { if (other.lastAccessedTime != null) return false; } else if (!lastAccessedTime.equals(other.lastAccessedTime)) return false; if (timeoutTime == null) { if (other.timeoutTime != null) return false; } else if (!timeoutTime.equals(other.timeoutTime)) return false; return true; } }
2,985
24.305085
100
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/FlightImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.entities; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import com.acmeair.entities.Flight; import com.acmeair.entities.FlightSegment; public class FlightImpl implements Flight, Serializable{ private static final long serialVersionUID = 1L; private FlightPKImpl pkey; private Date scheduledDepartureTime; private Date scheduledArrivalTime; private BigDecimal firstClassBaseCost; private BigDecimal economyClassBaseCost; private int numFirstClassSeats; private int numEconomyClassSeats; private String airplaneTypeId; private FlightSegment flightSegment; public FlightImpl() { } public FlightImpl(String id, String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId) { this.pkey = new FlightPKImpl(flightSegmentId,id); this.scheduledDepartureTime = scheduledDepartureTime; this.scheduledArrivalTime = scheduledArrivalTime; this.firstClassBaseCost = firstClassBaseCost; this.economyClassBaseCost = economyClassBaseCost; this.numFirstClassSeats = numFirstClassSeats; this.numEconomyClassSeats = numEconomyClassSeats; this.airplaneTypeId = airplaneTypeId; } public FlightPKImpl getPkey() { return pkey; } public void setPkey(FlightPKImpl pkey) { this.pkey = pkey; } @Override public String getFlightId() { return pkey.getId(); } @Override public void setFlightId(String id) { pkey.setId(id); } // The method is needed for index calculation public String getFlightSegmentId() { return pkey.getFlightSegmentId(); } public Date getScheduledDepartureTime() { return scheduledDepartureTime; } public void setScheduledDepartureTime(Date scheduledDepartureTime) { this.scheduledDepartureTime = scheduledDepartureTime; } public Date getScheduledArrivalTime() { return scheduledArrivalTime; } public void setScheduledArrivalTime(Date scheduledArrivalTime) { this.scheduledArrivalTime = scheduledArrivalTime; } public BigDecimal getFirstClassBaseCost() { return firstClassBaseCost; } public void setFirstClassBaseCost(BigDecimal firstClassBaseCost) { this.firstClassBaseCost = firstClassBaseCost; } public BigDecimal getEconomyClassBaseCost() { return economyClassBaseCost; } public void setEconomyClassBaseCost(BigDecimal economyClassBaseCost) { this.economyClassBaseCost = economyClassBaseCost; } public int getNumFirstClassSeats() { return numFirstClassSeats; } public void setNumFirstClassSeats(int numFirstClassSeats) { this.numFirstClassSeats = numFirstClassSeats; } public int getNumEconomyClassSeats() { return numEconomyClassSeats; } public void setNumEconomyClassSeats(int numEconomyClassSeats) { this.numEconomyClassSeats = numEconomyClassSeats; } public String getAirplaneTypeId() { return airplaneTypeId; } public void setAirplaneTypeId(String airplaneTypeId) { this.airplaneTypeId = airplaneTypeId; } public FlightSegment getFlightSegment() { return flightSegment; } public void setFlightSegment(FlightSegment flightSegment) { this.flightSegment = flightSegment; } @Override public String toString() { return "Flight key="+pkey + ", scheduledDepartureTime=" + scheduledDepartureTime + ", scheduledArrivalTime=" + scheduledArrivalTime + ", firstClassBaseCost=" + firstClassBaseCost + ", economyClassBaseCost=" + economyClassBaseCost + ", numFirstClassSeats=" + numFirstClassSeats + ", numEconomyClassSeats=" + numEconomyClassSeats + ", airplaneTypeId=" + airplaneTypeId + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FlightImpl other = (FlightImpl) obj; if (airplaneTypeId == null) { if (other.airplaneTypeId != null) return false; } else if (!airplaneTypeId.equals(other.airplaneTypeId)) return false; if (economyClassBaseCost == null) { if (other.economyClassBaseCost != null) return false; } else if (!economyClassBaseCost.equals(other.economyClassBaseCost)) return false; if (firstClassBaseCost == null) { if (other.firstClassBaseCost != null) return false; } else if (!firstClassBaseCost.equals(other.firstClassBaseCost)) return false; if (flightSegment == null) { if (other.flightSegment != null) return false; } else if (!flightSegment.equals(other.flightSegment)) return false; if (pkey == null) { if (other.pkey != null) return false; } else if (!pkey.equals(other.pkey)) return false; if (numEconomyClassSeats != other.numEconomyClassSeats) return false; if (numFirstClassSeats != other.numFirstClassSeats) return false; if (scheduledArrivalTime == null) { if (other.scheduledArrivalTime != null) return false; } else if (!scheduledArrivalTime.equals(other.scheduledArrivalTime)) return false; if (scheduledDepartureTime == null) { if (other.scheduledDepartureTime != null) return false; } else if (!scheduledDepartureTime.equals(other.scheduledDepartureTime)) return false; return true; } /* public void setFlightSegmentId(String segmentId) { pkey.setFlightSegmentId(segmentId); } */ }
6,141
25.13617
80
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/FlightPKImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.entities; import java.io.Serializable; import com.acmeair.entities.FlightPK; import com.ibm.websphere.objectgrid.plugins.PartitionableKey; public class FlightPKImpl implements FlightPK, Serializable, PartitionableKey { private static final long serialVersionUID = 1L; private String id; private String flightSegmentId; public FlightPKImpl() { super(); } public FlightPKImpl(String flightSegmentId,String id) { super(); this.id = id; this.flightSegmentId = flightSegmentId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFlightSegmentId() { return flightSegmentId; } public void setFlightSegmentId(String flightSegmentId) { this.flightSegmentId = flightSegmentId; } @Override public Object ibmGetPartition() { return this.flightSegmentId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((flightSegmentId == null) ? 0 : flightSegmentId.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FlightPKImpl other = (FlightPKImpl) obj; if (flightSegmentId == null) { if (other.flightSegmentId != null) return false; } else if (!flightSegmentId.equals(other.flightSegmentId)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "FlightPK [flightSegmentId=" + flightSegmentId +",id=" + id+ "]"; } }
2,506
25.670213
80
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/FlightSegmentImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.entities; import java.io.Serializable; import com.acmeair.entities.FlightSegment; public class FlightSegmentImpl implements FlightSegment, Serializable{ private static final long serialVersionUID = 1L; private String _id; private String originPort; private String destPort; private int miles; public FlightSegmentImpl() { } public FlightSegmentImpl(String flightName, String origPort, String destPort, int miles) { this._id = flightName; this.originPort = origPort; this.destPort = destPort; this.miles = miles; } public String getFlightName() { return _id; } public void setFlightName(String flightName) { this._id = flightName; } public String getOriginPort() { return originPort; } public void setOriginPort(String originPort) { this.originPort = originPort; } public String getDestPort() { return destPort; } public void setDestPort(String destPort) { this.destPort = destPort; } public int getMiles() { return miles; } public void setMiles(int miles) { this.miles = miles; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("FlightSegment ").append(_id).append(" originating from:\"").append(originPort).append("\" arriving at:\"").append(destPort).append("\""); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FlightSegmentImpl other = (FlightSegmentImpl) obj; if (destPort == null) { if (other.destPort != null) return false; } else if (!destPort.equals(other.destPort)) return false; if (_id == null) { if (other._id != null) return false; } else if (!_id.equals(other._id)) return false; if (miles != other.miles) return false; if (originPort == null) { if (other.originPort != null) return false; } else if (!originPort.equals(other.originPort)) return false; return true; } }
2,770
24.190909
150
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/service/BookingServiceImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.service; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.inject.Inject; import com.acmeair.entities.Booking; import com.acmeair.entities.Customer; import com.acmeair.entities.Flight; import com.acmeair.service.BookingService; import com.acmeair.service.CustomerService; import com.acmeair.service.DataService; import com.acmeair.service.FlightService; import com.acmeair.service.KeyGenerator; import com.acmeair.service.ServiceLocator; import com.acmeair.wxs.WXSConstants; import com.acmeair.wxs.entities.BookingImpl; import com.acmeair.wxs.entities.BookingPKImpl; import com.acmeair.wxs.entities.FlightPKImpl; import com.acmeair.wxs.utils.WXSSessionManager; import com.ibm.websphere.objectgrid.ObjectGrid; import com.ibm.websphere.objectgrid.ObjectGridException; import com.ibm.websphere.objectgrid.ObjectMap; import com.ibm.websphere.objectgrid.Session; import com.ibm.websphere.objectgrid.UndefinedMapException; import com.ibm.websphere.objectgrid.plugins.TransactionCallbackException; import com.ibm.websphere.objectgrid.plugins.index.MapIndex; @DataService(name=WXSConstants.KEY,description=WXSConstants.KEY_DESCRIPTION) public class BookingServiceImpl implements BookingService, WXSConstants { private final static Logger logger = Logger.getLogger(BookingService.class.getName()); private static String BOOKING_MAP_NAME="Booking"; private static String BASE_BOOKING_MAP_NAME="Booking"; private ObjectGrid og; @Inject private KeyGenerator keyGenerator; private FlightService flightService = ServiceLocator.instance().getService(FlightService.class); private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); @PostConstruct private void initialization() { try { og = WXSSessionManager.getSessionManager().getObjectGrid(); BOOKING_MAP_NAME = BASE_BOOKING_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix(); } catch (ObjectGridException e) { logger.severe("Unable to retreive the ObjectGrid reference " + e.getMessage()); } } public BookingPKImpl bookFlight(String customerId, FlightPKImpl flightId) { try{ // We still delegate to the flight and customer service for the map access than getting the map instance directly Flight f = flightService.getFlightByFlightId(flightId.getId(), flightId.getFlightSegmentId()); Customer c = customerService.getCustomerByUsername(customerId); BookingImpl newBooking = new BookingImpl(keyGenerator.generate().toString(), new Date(), c, f); BookingPKImpl key = newBooking.getPkey(); //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap bookingMap = session.getMap(BOOKING_MAP_NAME); @SuppressWarnings("unchecked") HashSet<Booking> bookingsByUser = (HashSet<Booking>)bookingMap.get(customerId); if (bookingsByUser == null) { bookingsByUser = new HashSet<Booking>(); } if (bookingsByUser.contains(newBooking)) { throw new Exception("trying to book a duplicate booking"); } bookingsByUser.add(newBooking); bookingMap.upsert(customerId, bookingsByUser); return key; }catch (Exception e) { throw new RuntimeException(e); } } @Override public String bookFlight(String customerId, String flightSegmentId, String id) { if(logger.isLoggable(Level.FINER)) logger.finer("WXS booking service, bookFlight with customerId = '"+ customerId+"', flightSegmentId = '"+ flightSegmentId + "', and id = '" + id + "'"); return bookFlight(customerId, new FlightPKImpl(flightSegmentId, id)).getId(); } @Override public Booking getBooking(String user, String id) { try{ //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap bookingMap = session.getMap(BOOKING_MAP_NAME); // return (Booking)bookingMap.get(new BookingPK(user, id)); @SuppressWarnings("unchecked") HashSet<BookingImpl> bookingsByUser = (HashSet<BookingImpl>)bookingMap.get(user); if (bookingsByUser == null) { return null; } for (BookingImpl b : bookingsByUser) { if (b.getPkey().getId().equals(id)) { return b; } } return null; }catch (Exception e) { throw new RuntimeException(e); } } @Override public void cancelBooking(String user, String id) { try{ Session session = og.getSession(); //Session session = sessionManager.getObjectGridSession(); ObjectMap bookingMap = session.getMap(BOOKING_MAP_NAME); @SuppressWarnings("unchecked") HashSet<BookingImpl> bookingsByUser = (HashSet<BookingImpl>)bookingMap.get(user); if (bookingsByUser == null) { return; } boolean found = false; HashSet<Booking> newBookings = new HashSet<Booking>(); for (BookingImpl b : bookingsByUser) { if (b.getPkey().getId().equals(id)) { found = true; } else { newBookings.add(b); } } if (found) { bookingMap.upsert(user, newBookings); } }catch (Exception e) { throw new RuntimeException(e); } } @Override public List<Booking> getBookingsByUser(String user) { try{ Session session = og.getSession(); //Session session = sessionManager.getObjectGridSession(); boolean startedTran = false; if (!session.isTransactionActive()) { startedTran = true; session.begin(); } ObjectMap bookingMap = session.getMap(BOOKING_MAP_NAME); @SuppressWarnings("unchecked") HashSet<Booking> bookingsByUser = (HashSet<Booking>)bookingMap.get(user); if (bookingsByUser == null) { bookingsByUser = new HashSet<Booking>(); } ArrayList<Booking> bookingsList = new ArrayList<Booking>(); for (Booking b : bookingsByUser) { bookingsList.add(b); } if (startedTran) session.commit(); return bookingsList; }catch (Exception e) { throw new RuntimeException(e); } } @Override public Long count () { try { Session session = og.getSession(); ObjectMap objectMap = session.getMap(BOOKING_MAP_NAME); MapIndex mapIndex = (MapIndex)objectMap.getIndex("com.ibm.ws.objectgrid.builtin.map.KeyIndex"); Iterator<?> keyIterator = mapIndex.findAll(); Long result = 0L; while(keyIterator.hasNext()) { keyIterator.next(); result++; } /* int partitions = og.getMap(BOOKING_MAP_NAME).getPartitionManager().getNumOfPartitions(); Long result = 0L; ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + BOOKING_MAP_NAME + " o "); for(int i = 0; i<partitions;i++){ query.setPartition(i); result += (Long) query.getSingleResult(); } */ return result; } catch (UndefinedMapException e) { e.printStackTrace(); } catch (TransactionCallbackException e) { e.printStackTrace(); } catch (ObjectGridException e) { e.printStackTrace(); } return -1L; } }
7,806
31.260331
156
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/service/CustomerServiceImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.service; import java.util.Date; import java.util.Iterator; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.enterprise.inject.Default; import javax.inject.Inject; import com.acmeair.entities.Customer; import com.acmeair.entities.Customer.MemberShipStatus; import com.acmeair.entities.Customer.PhoneType; import com.acmeair.entities.CustomerAddress; import com.acmeair.entities.CustomerSession; import com.acmeair.service.BookingService; import com.acmeair.service.CustomerService; import com.acmeair.service.DataService; import com.acmeair.service.KeyGenerator; import com.acmeair.wxs.WXSConstants; import com.acmeair.wxs.entities.CustomerAddressImpl; import com.acmeair.wxs.entities.CustomerImpl; import com.acmeair.wxs.entities.CustomerSessionImpl; import com.acmeair.wxs.utils.WXSSessionManager; import com.ibm.websphere.objectgrid.ObjectGrid; import com.ibm.websphere.objectgrid.ObjectGridException; import com.ibm.websphere.objectgrid.ObjectMap; import com.ibm.websphere.objectgrid.Session; import com.ibm.websphere.objectgrid.UndefinedMapException; import com.ibm.websphere.objectgrid.plugins.TransactionCallbackException; import com.ibm.websphere.objectgrid.plugins.index.MapIndex; import com.ibm.websphere.objectgrid.plugins.index.MapIndexPlugin; @Default @DataService(name=WXSConstants.KEY,description=WXSConstants.KEY_DESCRIPTION) public class CustomerServiceImpl extends CustomerService implements WXSConstants{ private static String BASE_CUSTOMER_MAP_NAME="Customer"; private static String BASE_CUSTOMER_SESSION_MAP_NAME="CustomerSession"; private static String CUSTOMER_MAP_NAME="Customer"; private static String CUSTOMER_SESSION_MAP_NAME="CustomerSession"; private final static Logger logger = Logger.getLogger(BookingService.class.getName()); private ObjectGrid og; @Inject KeyGenerator keyGenerator; @PostConstruct private void initialization() { try { og = WXSSessionManager.getSessionManager().getObjectGrid(); CUSTOMER_MAP_NAME = BASE_CUSTOMER_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix(); CUSTOMER_SESSION_MAP_NAME = BASE_CUSTOMER_SESSION_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix(); } catch (ObjectGridException e) { logger.severe("Unable to retreive the ObjectGrid reference " + e.getMessage()); } } @Override public Long count () { try { Session session = og.getSession(); ObjectMap objectMap = session.getMap(CUSTOMER_MAP_NAME); MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME); Iterator<?> keyIterator = mapIndex.findAll(); Long result = 0L; while(keyIterator.hasNext()) { keyIterator.next(); result++; } /* int partitions = og.getMap(CUSTOMER_MAP_NAME).getPartitionManager().getNumOfPartitions(); ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + CUSTOMER_MAP_NAME + " o "); for(int i = 0; i<partitions;i++){ query.setPartition(i); result += (Long) query.getSingleResult(); } */ return result; } catch (UndefinedMapException e) { e.printStackTrace(); } catch (TransactionCallbackException e) { e.printStackTrace(); } catch (ObjectGridException e) { e.printStackTrace(); } return -1L; } @Override public Long countSessions () { try { Session session = og.getSession(); ObjectMap objectMap = session.getMap(CUSTOMER_SESSION_MAP_NAME); MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME); Iterator<?> keyIterator = mapIndex.findAll(); Long result = 0L; while(keyIterator.hasNext()) { keyIterator.next(); result++; } /* int partitions = og.getMap(CUSTOMER_SESSION_MAP_NAME).getPartitionManager().getNumOfPartitions(); Long result = 0L; ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + CUSTOMER_SESSION_MAP_NAME + " o "); for(int i = 0; i<partitions;i++){ query.setPartition(i); result += (Long) query.getSingleResult(); } */ return result; } catch (UndefinedMapException e) { e.printStackTrace(); } catch (TransactionCallbackException e) { e.printStackTrace(); } catch (ObjectGridException e) { e.printStackTrace(); } return -1L; } @Override public Customer createCustomer(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber, PhoneType phoneNumberType, CustomerAddress address) { try{ Customer customer = new CustomerImpl(username, password, status, total_miles, miles_ytd, address, phoneNumber, phoneNumberType); // Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap customerMap = session.getMap(CUSTOMER_MAP_NAME); customerMap.insert(customer.getUsername(), customer); return customer; }catch (Exception e) { throw new RuntimeException(e); } } @Override public CustomerAddress createAddress (String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode){ CustomerAddress address = new CustomerAddressImpl(streetAddress1, streetAddress2, city, stateProvince, country, postalCode); return address; } @Override public Customer updateCustomer(Customer customer) { try{ //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap customerMap = session.getMap(CUSTOMER_MAP_NAME); customerMap.update(customer.getUsername(), customer); return customer; }catch (Exception e) { throw new RuntimeException(e); } } @Override protected Customer getCustomer(String username) { try{ //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap customerMap = session.getMap(CUSTOMER_MAP_NAME); Customer c = (Customer) customerMap.get(username); return c; }catch (Exception e) { throw new RuntimeException(e); } } @Override protected CustomerSession getSession(String sessionid){ try { Session session = og.getSession(); ObjectMap customerSessionMap = session.getMap(CUSTOMER_SESSION_MAP_NAME); return (CustomerSession)customerSessionMap.get(sessionid); }catch (Exception e) { throw new RuntimeException(e); } } @Override protected void removeSession(CustomerSession session){ try { Session ogSession = og.getSession(); ObjectMap customerSessionMap = ogSession.getMap(CUSTOMER_SESSION_MAP_NAME); customerSessionMap.remove(session.getId()); }catch (Exception e) { throw new RuntimeException(e); } } @Override protected CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration) { try{ CustomerSession cSession = new CustomerSessionImpl(sessionId, customerId, creation, expiration); // Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap customerSessionMap = session.getMap(CUSTOMER_SESSION_MAP_NAME); customerSessionMap.insert(cSession.getId(), cSession); return cSession; }catch (Exception e) { throw new RuntimeException(e); } } @Override public void invalidateSession(String sessionid) { try{ //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap customerSessionMap = session.getMap(CUSTOMER_SESSION_MAP_NAME); customerSessionMap.remove(sessionid); }catch (Exception e) { throw new RuntimeException(e); } } }
8,363
33.138776
131
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/service/FlightServiceImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.inject.Inject; import com.acmeair.entities.AirportCodeMapping; import com.acmeair.entities.Flight; import com.acmeair.entities.FlightSegment; import com.acmeair.service.BookingService; import com.acmeair.service.DataService; import com.acmeair.service.FlightService; import com.acmeair.service.KeyGenerator; import com.acmeair.wxs.WXSConstants; import com.acmeair.wxs.entities.AirportCodeMappingImpl; import com.acmeair.wxs.entities.FlightImpl; import com.acmeair.wxs.entities.FlightSegmentImpl; import com.acmeair.wxs.utils.WXSSessionManager; import com.ibm.websphere.objectgrid.ObjectGrid; import com.ibm.websphere.objectgrid.ObjectGridException; import com.ibm.websphere.objectgrid.ObjectMap; import com.ibm.websphere.objectgrid.Session; import com.ibm.websphere.objectgrid.UndefinedMapException; import com.ibm.websphere.objectgrid.plugins.TransactionCallbackException; import com.ibm.websphere.objectgrid.plugins.index.MapIndex; import com.ibm.websphere.objectgrid.plugins.index.MapIndexPlugin; @DataService(name=WXSConstants.KEY,description=WXSConstants.KEY_DESCRIPTION) public class FlightServiceImpl extends FlightService implements WXSConstants { private static String FLIGHT_MAP_NAME="Flight"; private static String FLIGHT_SEGMENT_MAP_NAME="FlightSegment"; private static String AIRPORT_CODE_MAPPING_MAP_NAME="AirportCodeMapping"; private static String BASE_FLIGHT_MAP_NAME="Flight"; private static String BASE_FLIGHT_SEGMENT_MAP_NAME="FlightSegment"; private static String BASE_AIRPORT_CODE_MAPPING_MAP_NAME="AirportCodeMapping"; private final static Logger logger = Logger.getLogger(BookingService.class.getName()); private ObjectGrid og; @Inject KeyGenerator keyGenerator; @PostConstruct private void initialization() { try { og = WXSSessionManager.getSessionManager().getObjectGrid(); FLIGHT_MAP_NAME = BASE_FLIGHT_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix(); FLIGHT_SEGMENT_MAP_NAME = BASE_FLIGHT_SEGMENT_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix(); AIRPORT_CODE_MAPPING_MAP_NAME = BASE_AIRPORT_CODE_MAPPING_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix(); } catch (ObjectGridException e) { logger.severe("Unable to retreive the ObjectGrid reference " + e.getMessage()); } } @Override public Long countFlights() { try { Session session = og.getSession(); ObjectMap objectMap = session.getMap(FLIGHT_MAP_NAME); MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME); Iterator<?> keyIterator = mapIndex.findAll(); Long result = 0L; while(keyIterator.hasNext()) { keyIterator.next(); result++; } /* int partitions = og.getMap(FLIGHT_MAP_NAME).getPartitionManager().getNumOfPartitions(); Long result = 0L; ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + FLIGHT_MAP_NAME + " o "); for(int i = 0; i<partitions;i++){ query.setPartition(i); result += (Long) query.getSingleResult(); } */ return result; } catch (UndefinedMapException e) { e.printStackTrace(); } catch (TransactionCallbackException e) { e.printStackTrace(); } catch (ObjectGridException e) { e.printStackTrace(); } return -1L; } @Override public Long countAirports() { try { Session session = og.getSession(); ObjectMap objectMap = session.getMap(AIRPORT_CODE_MAPPING_MAP_NAME); MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME); Iterator<?> keyIterator = mapIndex.findAll(); Long result = 0L; while(keyIterator.hasNext()) { keyIterator.next(); result++; } return result; } catch (UndefinedMapException e) { e.printStackTrace(); } catch (TransactionCallbackException e) { e.printStackTrace(); } catch (ObjectGridException e) { e.printStackTrace(); } return -1L; } @Override public Long countFlightSegments() { try { Session session = og.getSession(); ObjectMap objectMap = session.getMap(FLIGHT_SEGMENT_MAP_NAME); MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME); Iterator<?> keyIterator = mapIndex.findAll(); Long result = 0L; while(keyIterator.hasNext()) { keyIterator.next(); result++; } /* int partitions = og.getMap(FLIGHT_SEGMENT_MAP_NAME).getPartitionManager().getNumOfPartitions(); Long result = 0L; ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + FLIGHT_SEGMENT_MAP_NAME + " o "); for(int i = 0; i<partitions;i++){ query.setPartition(i); result += (Long) query.getSingleResult(); } */ return result; } catch (UndefinedMapException e) { e.printStackTrace(); } catch (TransactionCallbackException e) { e.printStackTrace(); } catch (ObjectGridException e) { e.printStackTrace(); } return -1L; } /* public Flight getFlightByFlightKey(FlightPK key) { try { Flight flight; flight = flightPKtoFlightCache.get(key); if (flight == null) { //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap flightMap = session.getMap(FLIGHT_MAP_NAME); @SuppressWarnings("unchecked") HashSet<Flight> flightsBySegment = (HashSet<Flight>)flightMap.get(key.getFlightSegmentId()); for (Flight f : flightsBySegment) { if (f.getPkey().getId().equals(key.getId())) { flightPKtoFlightCache.putIfAbsent(key, f); flight = f; break; } } } return flight; } catch (Exception e) { throw new RuntimeException(e); } } */ @Override protected Flight getFlight(String flightId, String flightSegmentId) { try { if(logger.isLoggable(Level.FINER)) logger.finer("in WXS getFlight. search for flightId = '" + flightId + "' and flightSegmentId = '"+flightSegmentId+"'"); //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap flightMap = session.getMap(FLIGHT_MAP_NAME); @SuppressWarnings("unchecked") HashSet<FlightImpl> flightsBySegment = (HashSet<FlightImpl>)flightMap.get(flightSegmentId); for (FlightImpl flight : flightsBySegment) { if (flight.getFlightId().equals(flightId)) { return flight; } } logger.warning("No matching flights found for flightId =" + flightId + " and flightSegment " + flightSegmentId); return null; } catch (Exception e) { throw new RuntimeException(e); } } @Override protected FlightSegment getFlightSegment(String fromAirport, String toAirport) { try { Session session = null; // boolean startedTran = false; //session = sessionManager.getObjectGridSession(); session = og.getSession(); FlightSegment segment = null; /* if (!session.isTransactionActive()) { startedTran = true; session.begin(); } */ ObjectMap flightSegmentMap = session.getMap(FLIGHT_SEGMENT_MAP_NAME); @SuppressWarnings("unchecked") HashSet<FlightSegment> segmentsByOrigPort = (HashSet<FlightSegment>)flightSegmentMap.get(fromAirport); if (segmentsByOrigPort!=null) { for (FlightSegment fs : segmentsByOrigPort) { if (fs.getDestPort().equals(toAirport)) { segment = fs; return segment; } } } if (segment == null) { segment = new FlightSegmentImpl(); // put a sentinel value of a non-populated flightsegment } // if (startedTran) // session.commit(); return segment; } catch (Exception e) { throw new RuntimeException(e); } } @Override protected List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate){ try { List<Flight> flights = new ArrayList<Flight>(); Session session = null; boolean startedTran = false; if (session == null) { //session = sessionManager.getObjectGridSession(); session = og.getSession(); if (!session.isTransactionActive()) { startedTran = true; session.begin(); } } ObjectMap flightMap = session.getMap(FLIGHT_MAP_NAME); @SuppressWarnings("unchecked") HashSet<Flight> flightsBySegment = (HashSet<Flight>)flightMap.get(segment.getFlightName()); if(deptDate != null){ for (Flight f : flightsBySegment) { if (areDatesSameWithNoTime(f.getScheduledDepartureTime(), deptDate)) { f.setFlightSegment(segment); flights.add(f); } } } else { for (Flight f : flightsBySegment) { f.setFlightSegment(segment); flights.add(f); } } if (startedTran) session.commit(); return flights; } catch (Exception e) { throw new RuntimeException(e); } } private static boolean areDatesSameWithNoTime(Date d1, Date d2) { return getDateWithNoTime(d1).equals(getDateWithNoTime(d2)); } private static Date getDateWithNoTime(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); return c.getTime(); } @Override public void storeAirportMapping(AirportCodeMapping mapping) { try{ //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap airportCodeMappingMap = session.getMap(AIRPORT_CODE_MAPPING_MAP_NAME); airportCodeMappingMap.upsert(mapping.getAirportCode(), mapping); }catch (Exception e) { throw new RuntimeException(e); } } @Override public AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName){ AirportCodeMapping acm = new AirportCodeMappingImpl(airportCode, airportName); return acm; } @Override public Flight createNewFlight(String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId) { try{ String id = keyGenerator.generate().toString(); Flight flight = new FlightImpl(id, flightSegmentId, scheduledDepartureTime, scheduledArrivalTime, firstClassBaseCost, economyClassBaseCost, numFirstClassSeats, numEconomyClassSeats, airplaneTypeId); //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap flightMap = session.getMap(FLIGHT_MAP_NAME); //flightMap.insert(flight.getPkey(), flight); //return flight; @SuppressWarnings("unchecked") HashSet<Flight> flightsBySegment = (HashSet<Flight>)flightMap.get(flightSegmentId); if (flightsBySegment == null) { flightsBySegment = new HashSet<Flight>(); } if (!flightsBySegment.contains(flight)) { flightsBySegment.add(flight); flightMap.upsert(flightSegmentId, flightsBySegment); } return flight; }catch (Exception e) { throw new RuntimeException(e); } } @Override public void storeFlightSegment(FlightSegment flightSeg) { try { //Session session = sessionManager.getObjectGridSession(); Session session = og.getSession(); ObjectMap flightSegmentMap = session.getMap(FLIGHT_SEGMENT_MAP_NAME); // TODO: Consider moving this to a ArrayList - List ?? @SuppressWarnings("unchecked") HashSet<FlightSegment> segmentsByOrigPort = (HashSet<FlightSegment>)flightSegmentMap.get(flightSeg.getOriginPort()); if (segmentsByOrigPort == null) { segmentsByOrigPort = new HashSet<FlightSegment>(); } if (!segmentsByOrigPort.contains(flightSeg)) { segmentsByOrigPort.add(flightSeg); flightSegmentMap.upsert(flightSeg.getOriginPort(), segmentsByOrigPort); } } catch (Exception e) { throw new RuntimeException(e); } } @Override public void storeFlightSegment(String flightName, String origPort, String destPort, int miles) { FlightSegment flightSeg = new FlightSegmentImpl(flightName, origPort, destPort, miles); storeFlightSegment(flightSeg); } }
12,920
31.794416
125
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/utils/MapPutAllAgent.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.utils; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import com.ibm.websphere.objectgrid.ObjectGridException; import com.ibm.websphere.objectgrid.ObjectMap; import com.ibm.websphere.objectgrid.Session; import com.ibm.websphere.objectgrid.datagrid.MapGridAgent; import com.ibm.websphere.objectgrid.plugins.io.dataobject.SerializedKey; public class MapPutAllAgent implements MapGridAgent { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(MapPutAllAgent.class.getName()); private HashMap<Object, HashMap<Object,Object>>objectsToSave = null ; public HashMap<Object, HashMap<Object,Object>> getObjectsToSave() { return objectsToSave; } public void setObjectsToSave(HashMap<Object,HashMap<Object,Object>> objectsToSave) { this.objectsToSave = objectsToSave; } //@Override public Object process(Session arg0, ObjectMap arg1, Object arg2) { // The key is the partition key, can be either the PK or when partition field is defined the partition field value try{ Object key; // I need to find the real key as the hashmap is using the real key... if( arg2 instanceof SerializedKey ) key = ((SerializedKey)arg2).getObject(); else key = arg2; HashMap<Object, Object> objectsForThePartition = this.objectsToSave.get(key); if (objectsForThePartition==null) logger.info("ERROR!!! Can not get the objects for partiton key:"+arg2); else { Entry<Object, Object> entry; Object value; for (Iterator<Map.Entry<Object, Object>> itr = objectsForThePartition.entrySet().iterator(); itr.hasNext();) { entry = itr.next(); key = entry.getKey(); value = entry.getValue(); logger.finer("Save using agent:"+key+",value:"+value); arg1.upsert(key, value); } } }catch (ObjectGridException e) { logger.info("Getting exception:"+e); } return arg2; } //@Override public Map<Object, Object> processAllEntries(Session arg0, ObjectMap arg1) { return null; } }
2,905
32.402299
116
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/utils/WXSSessionManager.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.utils; import java.util.HashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; import javax.naming.InitialContext; import javax.naming.NamingException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import com.acmeair.service.DataService; import com.acmeair.service.TransactionService; import com.acmeair.wxs.WXSConstants; import com.ibm.websphere.objectgrid.BackingMap; import com.ibm.websphere.objectgrid.ClientClusterContext; import com.ibm.websphere.objectgrid.ObjectGrid; import com.ibm.websphere.objectgrid.ObjectGridException; import com.ibm.websphere.objectgrid.ObjectGridManager; import com.ibm.websphere.objectgrid.ObjectGridManagerFactory; import com.ibm.websphere.objectgrid.ObjectGridRuntimeException; import com.ibm.websphere.objectgrid.Session; import com.ibm.websphere.objectgrid.config.BackingMapConfiguration; import com.ibm.websphere.objectgrid.config.ObjectGridConfigFactory; import com.ibm.websphere.objectgrid.config.ObjectGridConfiguration; import com.ibm.websphere.objectgrid.config.Plugin; import com.ibm.websphere.objectgrid.config.PluginType; import com.ibm.websphere.objectgrid.security.config.ClientSecurityConfiguration; import com.ibm.websphere.objectgrid.security.config.ClientSecurityConfigurationFactory; import com.ibm.websphere.objectgrid.security.plugins.CredentialGenerator; import com.ibm.websphere.objectgrid.security.plugins.builtins.UserPasswordCredentialGenerator; import com.ibm.websphere.objectgrid.spring.SpringLocalTxManager; @DataService(name=WXSConstants.KEY,description=WXSConstants.KEY_DESCRIPTION) public class WXSSessionManager implements TransactionService, WXSConstants{ private static final String GRID_CONNECT_LOOKUP_KEY = "com.acmeair.service.wxs.gridConnect"; private static final String GRID_NAME_LOOKUP_KEY = "com.acmeair.service.wxs.gridName"; private static final String GRID_DISABLE_NEAR_CACHE_NAME_LOOKUP_KEY = "com.acmeair.service.wxs.disableNearCacheName"; private static final String GRID_PARTITION_FIELD_NAME_LOOKUP_KEY = "com.acmeair.service.wxs.partitionFieldName"; private static final Logger logger = Logger.getLogger(WXSSessionManager.class.getName()); private static final String SPLIT_COMMA = "\\s*,\\s*"; private static final String SPLIT_COLON = "\\s*:\\s*"; private String gridConnectString; private String gridUsername = null; private String gridPassword = null; private String gridName = "Grid"; private boolean integrateWithWASTransactions = false; private String disableNearCacheNameString; private String[] disableNearCacheNames = null; private String partitionFieldNameString; private HashMap<String, String> partitionFieldNames = null; // For now to make it simple to only support one partition field private SpringLocalTxManager txManager; private String mapSuffix = ""; private AtomicReference<ObjectGrid> sharedGrid = new AtomicReference<ObjectGrid>(); private static AtomicReference<WXSSessionManager> connectionManager = new AtomicReference<WXSSessionManager>(); public static WXSSessionManager getSessionManager() { if (connectionManager.get() == null) { synchronized (connectionManager) { if (connectionManager.get() == null) { connectionManager.set(new WXSSessionManager()); } } } return connectionManager.get(); } private WXSSessionManager(){ ObjectGrid og = null; try { InitialContext ic = new InitialContext(); og = (ObjectGrid) ic.lookup(JNDI_NAME); } catch (NamingException e) { logger.warning("Unable to look up the ObjectGrid reference " + e.getMessage()); } if(og != null) { sharedGrid.set(og); } else { initialization(); } } private void initialization() { String vcapJSONString = System.getenv("VCAP_SERVICES"); if (vcapJSONString != null) { logger.info("Reading VCAP_SERVICES"); Object jsonObject = JSONValue.parse(vcapJSONString); logger.info("jsonObject = " + ((JSONObject)jsonObject).toJSONString()); JSONObject json = (JSONObject)jsonObject; String key; for (Object k: json.keySet()) { key = (String ) k; if (key.startsWith("ElasticCaching")||key.startsWith("DataCache")) { JSONArray elasticCachingServiceArray = (JSONArray)json.get(key); JSONObject elasticCachingService = (JSONObject)elasticCachingServiceArray.get(0); JSONObject credentials = (JSONObject)elasticCachingService.get("credentials"); String username = (String)credentials.get("username"); setGridUsername(username); String password = (String)credentials.get("password"); setGridPassword(password); String gridName = (String)credentials.get("gridName"); String catalogEndPoint = (String)credentials.get("catalogEndPoint"); logger.info("username = " + username + "; password = " + password + "; gridName = " + gridName + "; catalogEndpoint = " + catalogEndPoint); setGridConnectString(catalogEndPoint); setGridName(gridName); break; } } setMapSuffix(".NONE.O"); } else { logger.info("Creating the WXS Client connection. Looking up host and port information" ); gridName = lookup(GRID_NAME_LOOKUP_KEY); if(gridName == null){ gridName = "AcmeGrid"; } gridConnectString = lookup(GRID_CONNECT_LOOKUP_KEY); if(gridConnectString == null){ gridConnectString = "127.0.0.1:2809"; logger.info("Using default grid connection setting of " + gridConnectString); } setDisableNearCacheNameString(lookup(GRID_DISABLE_NEAR_CACHE_NAME_LOOKUP_KEY)); setPartitionFieldNameString(lookup(GRID_PARTITION_FIELD_NAME_LOOKUP_KEY)); } if(getDisableNearCacheNameString() == null){ setDisableNearCacheNameString("Flight,FlightSegment,AirportCodeMapping,CustomerSession,Booking,Customer"); logger.info("Using default disableNearCacheNameString value of " + disableNearCacheNameString); } if(getPartitionFieldNameString() == null){ setPartitionFieldNameString("Flight:pk.flightSegmentId,FlightSegment:originPort,Booking:pk.customerId"); logger.info("Using default partitionFieldNameString value of " + partitionFieldNameString); } if (!integrateWithWASTransactions && txManager!=null) // Using Spring TX if WAS TX is not enabled { logger.info("Session will be created from SpringLocalTxManager w/ tx support."); }else { txManager=null; logger.info("Session will be created from ObjectGrid directly w/o tx support."); } try { prepareForTransaction(); } catch (ObjectGridException e) { e.printStackTrace(); } } private String lookup (String key){ String value = null; String lookup = key.replace('.', '/'); javax.naming.Context context = null; javax.naming.Context envContext = null; try { context = new javax.naming.InitialContext(); envContext = (javax.naming.Context) context.lookup("java:comp/env"); if (envContext != null) value = (String) envContext.lookup(lookup); } catch (NamingException e) { } if (value != null) { logger.info("JNDI Found " + lookup + " : " + value); } else if (context != null) { try { value = (String) context.lookup(lookup); if (value != null) logger.info("JNDI Found " +lookup + " : " + value); } catch (NamingException e) { } } if (value == null) { value = System.getProperty(key); if (value != null) logger.info("Found " + key + " in jvm property : " + value); else { value = System.getenv(key); if (value != null) logger.info("Found "+key+" in environment property : " + value); } } return value; } /** * Connect to a remote ObjectGrid * @param cep the catalog server end points in the form: <host>:<port> * @param gridName the name of the ObjectGrid to connect to that is managed by the Catalog Service * @return a client ObjectGrid connection. */ private ObjectGrid connectClient(String cep, String gridName, boolean integrateWithWASTransactions,String[] disableNearCacheNames) { try { ObjectGrid gridToReturn = sharedGrid.get(); if (gridToReturn == null) { synchronized(sharedGrid) { if (sharedGrid.get() == null) { ObjectGridManager ogm = ObjectGridManagerFactory.getObjectGridManager(); ObjectGridConfiguration ogConfig = ObjectGridConfigFactory.createObjectGridConfiguration(gridName); if (integrateWithWASTransactions) // Using WAS Transactions as Highest Priority { Plugin trans = ObjectGridConfigFactory.createPlugin(PluginType.TRANSACTION_CALLBACK, "com.ibm.websphere.objectgrid.plugins.builtins.WebSphereTransactionCallback"); ogConfig.addPlugin(trans); } if (disableNearCacheNames!=null) { String mapNames[] = disableNearCacheNames; for (String mName : mapNames) { BackingMapConfiguration bmc = ObjectGridConfigFactory.createBackingMapConfiguration(mName); bmc.setNearCacheEnabled(false); ogConfig.addBackingMapConfiguration(bmc); } } ClientClusterContext ccc = null; if (gridUsername != null) { ClientSecurityConfiguration clientSC = ClientSecurityConfigurationFactory.getClientSecurityConfiguration(); clientSC.setSecurityEnabled(true); CredentialGenerator credGen = new UserPasswordCredentialGenerator(gridUsername, gridPassword); clientSC.setCredentialGenerator(credGen); ccc = ogm.connect(cep, clientSC, null); } else { ccc = ogm.connect(cep, null, null); } ObjectGrid grid = ObjectGridManagerFactory.getObjectGridManager().getObjectGrid(ccc, gridName, ogConfig); sharedGrid.compareAndSet(null, grid); gridToReturn = grid; logger.info("Create instance of Grid: " + gridToReturn); }else{ gridToReturn = sharedGrid.get(); } } } return gridToReturn; } catch (Exception e) { throw new ObjectGridRuntimeException("Unable to connect to catalog server at endpoints:" + cep, e); } } public String getMapSuffix(){ return mapSuffix; } public void setMapSuffix(String suffix){ this.mapSuffix = suffix; } public String getGridConnectString() { return gridConnectString; } public void setGridConnectString(String gridConnectString) { this.gridConnectString = gridConnectString; } public String getGridName() { return gridName; } public void setGridName(String gridName) { this.gridName = gridName; } public String getGridUsername() { return gridUsername; } public void setGridUsername(String gridUsername) { this.gridUsername = gridUsername; } public String getGridPassword() { return gridPassword; } public void setGridPassword(String gridPassword) { this.gridPassword = gridPassword; } public boolean isIntegrateWithWASTransactions() { return integrateWithWASTransactions; } public void setIntegrateWithWASTransactions(boolean integrateWithWASTransactions) { this.integrateWithWASTransactions = integrateWithWASTransactions; } public String getDisableNearCacheNameString() { return disableNearCacheNameString; } public void setDisableNearCacheNameString(String disableNearCacheNameString) { this.disableNearCacheNameString = disableNearCacheNameString; if (disableNearCacheNameString ==null || disableNearCacheNameString.length()==0) disableNearCacheNames =null; else disableNearCacheNames = disableNearCacheNameString.split(SPLIT_COMMA); } public String getPartitionFieldNameString() { return partitionFieldNameString; } public void setPartitionFieldNameString(String partitionFieldNameString) { this.partitionFieldNameString = partitionFieldNameString; // In the form of <MapName>:<PartitionFieldName>,<MapName>:<PartitionFieldName> if (partitionFieldNameString ==null || partitionFieldNameString.length()==0) partitionFieldNames =null; else { String[] maps = partitionFieldNameString.split(SPLIT_COMMA); partitionFieldNames = new HashMap<String, String>(); String[] mapDef; for (int i=0; i<maps.length; i++) { mapDef = maps[i].split(SPLIT_COLON); partitionFieldNames.put(mapDef[0], mapDef[1]); } } } public String getPartitionFieldName(String mapName) { if (partitionFieldNames == null) return null; return partitionFieldNames.get(mapName); } public SpringLocalTxManager getTxManager() { return txManager; } public void setTxManager(SpringLocalTxManager txManager) { logger.finer("txManager:"+txManager); this.txManager = txManager; } // This method needs to be called by the client from its thread before triggering a service with @Transactional annotation public void prepareForTransaction() throws ObjectGridException { ObjectGrid grid = this.getObjectGrid(); if (txManager!=null) txManager.setObjectGridForThread(grid); } // Helper function public ObjectGrid getObjectGrid() throws ObjectGridException { ObjectGrid grid = connectClient(this.gridConnectString, this.gridName, this.integrateWithWASTransactions, this.disableNearCacheNames); return grid; } public Session getObjectGridSession() throws ObjectGridException { Session result; ObjectGrid grid = getObjectGrid(); if (txManager!=null) result= txManager.getSession(); else result = grid.getSession(); // this.log.debug("Got session:"+ result); return result; } public BackingMap getBackingMap(String mapName)throws ObjectGridException { return this.getObjectGrid().getMap(mapName); } }
14,628
35.390547
146
java
acmeair
acmeair-master/acmeair-services/src/main/java/com/acmeair/service/BookingService.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; import java.util.List; import com.acmeair.entities.Booking; public interface BookingService { //String bookFlight(String customerId, FlightPK flightId); // String bookFlight(String customerId, String flightId); String bookFlight(String customerId, String flightSegmentId, String FlightId); Booking getBooking(String user, String id); List<Booking> getBookingsByUser(String user); void cancelBooking(String user, String id); Long count(); }
1,226
32.162162
80
java
acmeair
acmeair-master/acmeair-services/src/main/java/com/acmeair/service/CustomerService.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; import java.util.Calendar; import java.util.Date; import javax.inject.Inject; import com.acmeair.entities.Customer; import com.acmeair.entities.CustomerAddress; import com.acmeair.entities.Customer.MemberShipStatus; import com.acmeair.entities.Customer.PhoneType; import com.acmeair.entities.CustomerSession; public abstract class CustomerService { protected static final int DAYS_TO_ALLOW_SESSION = 1; @Inject protected KeyGenerator keyGenerator; public abstract Customer createCustomer( String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber, PhoneType phoneNumberType, CustomerAddress address); public abstract CustomerAddress createAddress (String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode); public abstract Customer updateCustomer(Customer customer); protected abstract Customer getCustomer(String username); public Customer getCustomerByUsername(String username) { Customer c = getCustomer(username); if (c != null) { c.setPassword(null); } return c; } public boolean validateCustomer(String username, String password) { boolean validatedCustomer = false; Customer customerToValidate = getCustomer(username); if (customerToValidate != null) { validatedCustomer = password.equals(customerToValidate.getPassword()); } return validatedCustomer; } public Customer getCustomerByUsernameAndPassword(String username, String password) { Customer c = getCustomer(username); if (!c.getPassword().equals(password)) { return null; } // Should we also set the password to null? return c; } public CustomerSession validateSession(String sessionid) { CustomerSession cSession = getSession(sessionid); if (cSession == null) { return null; } Date now = new Date(); if (cSession.getTimeoutTime().before(now)) { removeSession(cSession); return null; } return cSession; } protected abstract CustomerSession getSession(String sessionid); protected abstract void removeSession(CustomerSession session); public CustomerSession createSession(String customerId) { String sessionId = keyGenerator.generate().toString(); Date now = new Date(); Calendar c = Calendar.getInstance(); c.setTime(now); c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION); Date expiration = c.getTime(); return createSession(sessionId, customerId, now, expiration); } protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration); public abstract void invalidateSession(String sessionid); public abstract Long count(); public abstract Long countSessions(); }
3,520
30.159292
119
java
acmeair
acmeair-master/acmeair-services/src/main/java/com/acmeair/service/DataService.java
package com.acmeair.service; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Qualifier; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface DataService { String name() default "none"; String description() default "none"; }
596
28.85
72
java
acmeair
acmeair-master/acmeair-services/src/main/java/com/acmeair/service/FlightService.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import com.acmeair.entities.Flight; import com.acmeair.entities.FlightSegment; import com.acmeair.entities.AirportCodeMapping; public abstract class FlightService { protected Logger logger = Logger.getLogger(FlightService.class.getName()); //TODO:need to find a way to invalidate these maps protected static ConcurrentHashMap<String, FlightSegment> originAndDestPortToSegmentCache = new ConcurrentHashMap<String,FlightSegment>(); protected static ConcurrentHashMap<String, List<Flight>> flightSegmentAndDataToFlightCache = new ConcurrentHashMap<String,List<Flight>>(); protected static ConcurrentHashMap<String, Flight> flightPKtoFlightCache = new ConcurrentHashMap<String, Flight>(); public Flight getFlightByFlightId(String flightId, String flightSegment) { try { Flight flight = flightPKtoFlightCache.get(flightId); if (flight == null) { flight = getFlight(flightId, flightSegment); if (flightId != null && flight != null) { flightPKtoFlightCache.putIfAbsent(flightId, flight); } } return flight; } catch (Exception e) { throw new RuntimeException(e); } } protected abstract Flight getFlight(String flightId, String flightSegment); public List<Flight> getFlightByAirportsAndDepartureDate(String fromAirport, String toAirport, Date deptDate) { if(logger.isLoggable(Level.FINE)) logger.fine("Search for flights from "+ fromAirport + " to " + toAirport + " on " + deptDate.toString()); String originPortAndDestPortQueryString= fromAirport+toAirport; FlightSegment segment = originAndDestPortToSegmentCache.get(originPortAndDestPortQueryString); if (segment == null) { segment = getFlightSegment(fromAirport, toAirport); originAndDestPortToSegmentCache.putIfAbsent(originPortAndDestPortQueryString, segment); } // cache flights that not available (checks against sentinel value above indirectly) if (segment.getFlightName() == null) { return new ArrayList<Flight>(); } String segId = segment.getFlightName(); String flightSegmentIdAndScheduledDepartureTimeQueryString = segId + deptDate.toString(); List<Flight> flights = flightSegmentAndDataToFlightCache.get(flightSegmentIdAndScheduledDepartureTimeQueryString); if (flights == null) { flights = getFlightBySegment(segment, deptDate); flightSegmentAndDataToFlightCache.putIfAbsent(flightSegmentIdAndScheduledDepartureTimeQueryString, flights); } if(logger.isLoggable(Level.FINEST)) logger.finest("Returning "+ flights); return flights; } // NOTE: This is not cached public List<Flight> getFlightByAirports(String fromAirport, String toAirport) { FlightSegment segment = getFlightSegment(fromAirport, toAirport); if (segment == null) { return new ArrayList<Flight>(); } return getFlightBySegment(segment, null); } protected abstract FlightSegment getFlightSegment(String fromAirport, String toAirport); protected abstract List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate); public abstract void storeAirportMapping(AirportCodeMapping mapping); public abstract AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName); public abstract Flight createNewFlight(String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId); public abstract void storeFlightSegment(FlightSegment flightSeg); public abstract void storeFlightSegment(String flightName, String origPort, String destPort, int miles); public abstract Long countFlightSegments(); public abstract Long countFlights(); public abstract Long countAirports(); }
4,749
38.256198
139
java
acmeair
acmeair-master/acmeair-services/src/main/java/com/acmeair/service/KeyGenerator.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; public class KeyGenerator { public Object generate() { return java.util.UUID.randomUUID().toString(); } }
885
35.916667
80
java
acmeair
acmeair-master/acmeair-services/src/main/java/com/acmeair/service/ServiceLocator.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; import java.lang.annotation.Annotation; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.PostConstruct; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.Any; import javax.enterprise.inject.Default; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.util.AnnotationLiteral; import javax.inject.Inject; import javax.naming.InitialContext; import javax.naming.NamingException; import java.util.logging.Logger; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class ServiceLocator { public static String REPOSITORY_LOOKUP_KEY = "com.acmeair.repository.type"; private static String serviceType; private static Logger logger = Logger.getLogger(ServiceLocator.class.getName()); private static AtomicReference<ServiceLocator> singletonServiceLocator = new AtomicReference<ServiceLocator>(); @Inject BeanManager beanManager; public static ServiceLocator instance() { if (singletonServiceLocator.get() == null) { synchronized (singletonServiceLocator) { if (singletonServiceLocator.get() == null) { singletonServiceLocator.set(new ServiceLocator()); } } } return singletonServiceLocator.get(); } @PostConstruct private void initialization() { if(beanManager == null){ logger.info("Attempting to look up BeanManager through JNDI at java:comp/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/BeanManager"); } } if(beanManager == null){ logger.info("Attempting to look up BeanManager through JNDI at java:comp/env/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/env/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/env/BeanManager "); } } } public static void updateService(String serviceName){ logger.info("Service Locator updating service to : " + serviceName); serviceType = serviceName; } private ServiceLocator() { String type = null; String lookup = REPOSITORY_LOOKUP_KEY.replace('.', '/'); javax.naming.Context context = null; javax.naming.Context envContext = null; try { context = new javax.naming.InitialContext(); envContext = (javax.naming.Context) context.lookup("java:comp/env"); if (envContext != null) type = (String) envContext.lookup(lookup); } catch (NamingException e) { // e.printStackTrace(); } if (type != null) { logger.info("Found repository in web.xml:" + type); } else if (context != null) { try { type = (String) context.lookup(lookup); if (type != null) logger.info("Found repository in server.xml:" + type); } catch (NamingException e) { // e.printStackTrace(); } } if (type == null) { type = System.getProperty(REPOSITORY_LOOKUP_KEY); if (type != null) logger.info("Found repository in jvm property:" + type); else { type = System.getenv(REPOSITORY_LOOKUP_KEY); if (type != null) logger.info("Found repository in environment property:" + type); } } if(beanManager == null) { logger.info("Attempting to look up BeanManager through JNDI at java:comp/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/BeanManager"); } } if(beanManager == null){ logger.info("Attempting to look up BeanManager through JNDI at java:comp/env/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/env/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/env/BeanManager "); } } if (type==null) { String vcapJSONString = System.getenv("VCAP_SERVICES"); if (vcapJSONString != null) { logger.info("Reading VCAP_SERVICES"); Object jsonObject = JSONValue.parse(vcapJSONString); logger.fine("jsonObject = " + ((JSONObject)jsonObject).toJSONString()); JSONObject json = (JSONObject)jsonObject; String key; for (Object k: json.keySet()) { key = (String ) k; if (key.startsWith("ElasticCaching")||key.startsWith("DataCache")) { logger.info("VCAP_SERVICES existed with service:"+key); type ="wxs"; break; } if (key.startsWith("mongo")) { logger.info("VCAP_SERVICES existed with service:"+key); type ="morphia"; break; } if (key.startsWith("redis")) { logger.info("VCAP_SERVICES existed with service:"+key); type ="redis"; break; } if (key.startsWith("mysql")|| key.startsWith("cleardb")) { logger.info("VCAP_SERVICES existed with service:"+key); type ="mysql"; break; } if (key.startsWith("postgresql")) { logger.info("VCAP_SERVICES existed with service:"+key); type ="postgresql"; break; } if (key.startsWith("db2")) { logger.info("VCAP_SERVICES existed with service:"+key); type ="db2"; break; } } } } serviceType = type; logger.info("ServiceType is now : " + serviceType); if (type ==null) { logger.warning("Can not determine type. Use default service implementation."); } } @SuppressWarnings("unchecked") public <T> T getService (Class<T> clazz) { logger.fine("Looking up service: "+clazz.getName() + " with service type: " + serviceType); if(beanManager == null) { logger.severe("BeanManager is null!!!"); } Set<Bean<?>> beans = beanManager.getBeans(clazz,new AnnotationLiteral<Any>() { private static final long serialVersionUID = 1L;}); for (Bean<?> bean : beans) { logger.fine(" Bean = "+bean.getBeanClass().getName()); for (Annotation qualifer: bean.getQualifiers()) { if(null == serviceType) { logger.warning("Service type is not set, searching for the default implementation."); if(Default.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){ CreationalContext<?> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, clazz, ctx); } } else { if(DataService.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){ DataService service = (DataService) qualifer; logger.fine(" name="+service.name()+" description="+service.description()); if(serviceType.equalsIgnoreCase(service.name())) { CreationalContext<?> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, clazz, ctx); } } } } } logger.warning("No Service of type: " + serviceType + " found for "+clazz.getName()+" "); return null; } /** * Retrieves the services that are available for use with the description for each service. * The Services are determined by looking up all of the implementations of the * Customer Service interface that are using the DataService qualifier annotation. * The DataService annotation contains the service name and description information. * @return Map containing a list of services available and a description of each one. */ public Map<String,String> getServices (){ TreeMap<String,String> services = new TreeMap<String,String>(); logger.fine("Getting CustomerService Impls"); Set<Bean<?>> beans = beanManager.getBeans(CustomerService.class,new AnnotationLiteral<Any>() { private static final long serialVersionUID = 1L;}); for (Bean<?> bean : beans) { for (Annotation qualifer: bean.getQualifiers()){ if(DataService.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){ DataService service = (DataService) qualifer; logger.fine(" name="+service.name()+" description="+service.description()); services.put(service.name(), service.description()); } } } return services; } /** * The type of service implementation that the application is * currently configured to use. * * @return The type of service in use, or "default" if no service has been set. */ public String getServiceType (){ if(serviceType == null){ return "default"; } return serviceType; } }
9,389
33.145455
112
java
acmeair
acmeair-master/acmeair-services/src/main/java/com/acmeair/service/TransactionService.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; public interface TransactionService { void prepareForTransaction() throws Exception; }
859
36.391304
80
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
package com.acmeair.config; import java.util.ArrayList; import java.util.Map; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import com.acmeair.service.BookingService; import com.acmeair.service.CustomerService; import com.acmeair.service.FlightService; import com.acmeair.service.ServiceLocator; @Path("/config") public class AcmeAirConfiguration { @Inject BeanManager beanManager; Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName()); private BookingService bs = ServiceLocator.instance().getService(BookingService.class); private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); private FlightService flightService = ServiceLocator.instance().getService(FlightService.class); public AcmeAirConfiguration() { super(); } @PostConstruct private void initialization() { if(beanManager == null){ logger.info("Attempting to look up BeanManager through JNDI at java:comp/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/BeanManager"); } } if(beanManager == null){ logger.info("Attempting to look up BeanManager through JNDI at java:comp/env/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/env/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/env/BeanManager "); } } } @GET @Path("/dataServices") @Produces("application/json") public ArrayList<ServiceData> getDataServiceInfo() { try { ArrayList<ServiceData> list = new ArrayList<ServiceData>(); Map<String, String> services = ServiceLocator.instance().getServices(); logger.fine("Get data service configuration info"); for (Map.Entry<String, String> entry : services.entrySet()){ ServiceData data = new ServiceData(); data.name = entry.getKey(); data.description = entry.getValue(); list.add(data); } return list; } catch (Exception e) { e.printStackTrace(); return null; } } @GET @Path("/activeDataService") @Produces("application/json") public Response getActiveDataServiceInfo() { try { logger.fine("Get active Data Service info"); return Response.ok(ServiceLocator.instance().getServiceType()).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok("Unknown").build(); } } @GET @Path("/runtime") @Produces("application/json") public ArrayList<ServiceData> getRuntimeInfo() { try { logger.fine("Getting Runtime info"); ArrayList<ServiceData> list = new ArrayList<ServiceData>(); ServiceData data = new ServiceData(); data.name = "Runtime"; data.description = "Java"; list.add(data); data = new ServiceData(); data.name = "Version"; data.description = System.getProperty("java.version"); list.add(data); data = new ServiceData(); data.name = "Vendor"; data.description = System.getProperty("java.vendor"); list.add(data); return list; } catch (Exception e) { e.printStackTrace(); return null; } } class ServiceData { public String name = ""; public String description = ""; } @GET @Path("/countBookings") @Produces("application/json") public Response countBookings() { try { Long count = bs.count(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countCustomers") @Produces("application/json") public Response countCustomer() { try { Long customerCount = customerService.count(); return Response.ok(customerCount).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countSessions") @Produces("application/json") public Response countCustomerSessions() { try { Long customerCount = customerService.countSessions(); return Response.ok(customerCount).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countFlights") @Produces("application/json") public Response countFlights() { try { Long count = flightService.countFlights(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countFlightSegments") @Produces("application/json") public Response countFlightSegments() { try { Long count = flightService.countFlightSegments(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countAirports") @Produces("application/json") public Response countAirports() { try { Long count = flightService.countAirports(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } }
5,380
23.022321
103
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/config/LoaderREST.java
package com.acmeair.config; import javax.inject.Inject; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import com.acmeair.loader.Loader; @Path("/loader") public class LoaderREST { // private static Logger logger = Logger.getLogger(LoaderREST.class.getName()); @Inject private Loader loader; @GET @Path("/query") @Produces("text/plain") public Response queryLoader() { String response = loader.queryLoader(); return Response.ok(response).build(); } @GET @Path("/load") @Produces("text/plain") public Response loadDB(@DefaultValue("-1") @QueryParam("numCustomers") long numCustomers) { String response = loader.loadDB(numCustomers); return Response.ok(response).build(); } }
842
20.615385
93
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/AcmeAirApp.java
package com.acmeair.web; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import javax.ws.rs.ApplicationPath; @ApplicationPath("/rest/api") public class AcmeAirApp extends Application { public Set<Class<?>> getClasses() { return new HashSet<Class<?>>(Arrays.asList(BookingsREST.class, CustomerREST.class, FlightsREST.class, LoginREST.class)); } }
427
25.75
128
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/AppConfig.java
package com.acmeair.web; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import javax.ws.rs.ApplicationPath; import com.acmeair.config.AcmeAirConfiguration; import com.acmeair.config.LoaderREST; @ApplicationPath("/rest/info") public class AppConfig extends Application { public Set<Class<?>> getClasses() { return new HashSet<Class<?>>(Arrays.asList(LoaderREST.class, AcmeAirConfiguration.class)); } }
484
24.526316
98
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/BookingsREST.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import java.util.*; import javax.ws.rs.*; import javax.ws.rs.core.*; import javax.ws.rs.core.Response.Status; import com.acmeair.entities.Booking; import com.acmeair.service.BookingService; import com.acmeair.service.ServiceLocator; import com.acmeair.web.dto.BookingInfo; import com.acmeair.web.dto.BookingReceiptInfo; @Path("/bookings") public class BookingsREST { private BookingService bs = ServiceLocator.instance().getService(BookingService.class); @POST @Consumes({"application/x-www-form-urlencoded"}) @Path("/bookflights") @Produces("application/json") public /*BookingInfo*/ Response bookFlights( @FormParam("userid") String userid, @FormParam("toFlightId") String toFlightId, @FormParam("toFlightSegId") String toFlightSegId, @FormParam("retFlightId") String retFlightId, @FormParam("retFlightSegId") String retFlightSegId, @FormParam("oneWayFlight") boolean oneWay) { try { String bookingIdTo = bs.bookFlight(userid, toFlightSegId, toFlightId); String bookingIdReturn = null; if (!oneWay) { bookingIdReturn = bs.bookFlight(userid, retFlightSegId, retFlightId); } // YL. BookingInfo will only contains the booking generated keys as customer info is always available from the session BookingReceiptInfo bi; if (!oneWay) bi = new BookingReceiptInfo(bookingIdTo, bookingIdReturn, oneWay); else bi = new BookingReceiptInfo(bookingIdTo, null, oneWay); return Response.ok(bi).build(); } catch (Exception e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } @GET @Path("/bybookingnumber/{userid}/{number}") @Produces("application/json") public BookingInfo getBookingByNumber( @PathParam("number") String number, @PathParam("userid") String userid) { try { Booking b = bs.getBooking(userid, number); BookingInfo bi = null; if(b != null){ bi = new BookingInfo(b); } return bi; } catch (Exception e) { e.printStackTrace(); return null; } } @GET @Path("/byuser/{user}") @Produces("application/json") public List<BookingInfo> getBookingsByUser(@PathParam("user") String user) { try { List<Booking> list = bs.getBookingsByUser(user); List<BookingInfo> newList = new ArrayList<BookingInfo>(); for(Booking b : list){ newList.add(new BookingInfo(b)); } return newList; } catch (Exception e) { e.printStackTrace(); return null; } } @POST @Consumes({"application/x-www-form-urlencoded"}) @Path("/cancelbooking") @Produces("application/json") public Response cancelBookingsByNumber( @FormParam("number") String number, @FormParam("userid") String userid) { try { bs.cancelBooking(userid, number); return Response.ok("booking " + number + " deleted.").build(); } catch (Exception e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } }
3,686
28.733871
121
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/CustomerREST.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.*; import com.acmeair.entities.Customer; import com.acmeair.entities.CustomerAddress; import com.acmeair.service.*; import com.acmeair.web.dto.*; import javax.ws.rs.core.Context; @Path("/customer") public class CustomerREST { private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); @Context private HttpServletRequest request; private boolean validate(String customerid) { String loginUser = (String) request.getAttribute(RESTCookieSessionFilter.LOGIN_USER); return customerid.equals(loginUser); } @GET @Path("/byid/{custid}") @Produces("application/json") public Response getCustomer(@CookieParam("sessionid") String sessionid, @PathParam("custid") String customerid) { try { // make sure the user isn't trying to update a customer other than the one currently logged in if (!validate(customerid)) { return Response.status(Response.Status.FORBIDDEN).build(); } Customer customer = customerService.getCustomerByUsername(customerid); CustomerInfo customerDTO = new CustomerInfo(customer); return Response.ok(customerDTO).build(); } catch (Exception e) { e.printStackTrace(); return null; } } @POST @Path("/byid/{custid}") @Produces("application/json") public /* Customer */ Response putCustomer(@CookieParam("sessionid") String sessionid, CustomerInfo customer) { if (!validate(customer.getUsername())) { return Response.status(Response.Status.FORBIDDEN).build(); } Customer customerFromDB = customerService.getCustomerByUsernameAndPassword(customer.getUsername(), customer.getPassword()); if (customerFromDB == null) { // either the customer doesn't exist or the password is wrong return Response.status(Response.Status.FORBIDDEN).build(); } CustomerAddress addressFromDB = customerFromDB.getAddress(); addressFromDB.setStreetAddress1(customer.getAddress().getStreetAddress1()); if (customer.getAddress().getStreetAddress2() != null) { addressFromDB.setStreetAddress2(customer.getAddress().getStreetAddress2()); } addressFromDB.setCity(customer.getAddress().getCity()); addressFromDB.setStateProvince(customer.getAddress().getStateProvince()); addressFromDB.setCountry(customer.getAddress().getCountry()); addressFromDB.setPostalCode(customer.getAddress().getPostalCode()); customerFromDB.setPhoneNumber(customer.getPhoneNumber()); customerFromDB.setPhoneNumberType(Customer.PhoneType.valueOf(customer.getPhoneNumberType())); customerService.updateCustomer(customerFromDB); customerFromDB.setPassword(null); return Response.ok(customerFromDB).build(); } }
3,502
34.744898
125
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/FlightsREST.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import java.util.ArrayList; import java.util.List; import java.util.Date; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import com.acmeair.entities.Flight; import com.acmeair.service.FlightService; import com.acmeair.service.ServiceLocator; import com.acmeair.web.dto.TripFlightOptions; import com.acmeair.web.dto.TripLegInfo; @Path("/flights") public class FlightsREST { private FlightService flightService = ServiceLocator.instance().getService(FlightService.class); // TODO: Consider a pure GET implementation of this service, but maybe not much value due to infrequent similar searches @POST @Path("/queryflights") @Consumes({"application/x-www-form-urlencoded"}) @Produces("application/json") public TripFlightOptions getTripFlights( @FormParam("fromAirport") String fromAirport, @FormParam("toAirport") String toAirport, @FormParam("fromDate") Date fromDate, @FormParam("returnDate") Date returnDate, @FormParam("oneWay") boolean oneWay ) { TripFlightOptions options = new TripFlightOptions(); ArrayList<TripLegInfo> legs = new ArrayList<TripLegInfo>(); TripLegInfo toInfo = new TripLegInfo(); List<Flight> toFlights = flightService.getFlightByAirportsAndDepartureDate(fromAirport, toAirport, fromDate); toInfo.setFlightsOptions(toFlights); legs.add(toInfo); toInfo.setCurrentPage(0); toInfo.setHasMoreOptions(false); toInfo.setNumPages(1); toInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); if (!oneWay) { TripLegInfo retInfo = new TripLegInfo(); List<Flight> retFlights = flightService.getFlightByAirportsAndDepartureDate(toAirport, fromAirport, returnDate); retInfo.setFlightsOptions(retFlights); legs.add(retInfo); retInfo.setCurrentPage(0); retInfo.setHasMoreOptions(false); retInfo.setNumPages(1); retInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); options.setTripLegs(2); } else { options.setTripLegs(1); } options.setTripFlights(legs); return options; } @POST @Path("/browseflights") @Consumes({"application/x-www-form-urlencoded"}) @Produces("application/json") public TripFlightOptions browseFlights( @FormParam("fromAirport") String fromAirport, @FormParam("toAirport") String toAirport, @FormParam("oneWay") boolean oneWay ) { TripFlightOptions options = new TripFlightOptions(); ArrayList<TripLegInfo> legs = new ArrayList<TripLegInfo>(); TripLegInfo toInfo = new TripLegInfo(); List<Flight> toFlights = flightService.getFlightByAirports(fromAirport, toAirport); toInfo.setFlightsOptions(toFlights); legs.add(toInfo); toInfo.setCurrentPage(0); toInfo.setHasMoreOptions(false); toInfo.setNumPages(1); toInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); if (!oneWay) { TripLegInfo retInfo = new TripLegInfo(); List<Flight> retFlights = flightService.getFlightByAirports(toAirport, fromAirport); retInfo.setFlightsOptions(retFlights); legs.add(retInfo); retInfo.setCurrentPage(0); retInfo.setHasMoreOptions(false); retInfo.setNumPages(1); retInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); options.setTripLegs(2); } else { options.setTripLegs(1); } options.setTripFlights(legs); return options; } }
4,076
31.879032
122
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/LoginREST.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import javax.ws.rs.*; import javax.ws.rs.core.*; import com.acmeair.entities.CustomerSession; import com.acmeair.service.*; @Path("/login") public class LoginREST { public static String SESSIONID_COOKIE_NAME = "sessionid"; private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); @POST @Consumes({"application/x-www-form-urlencoded"}) @Produces("text/plain") public Response login(@FormParam("login") String login, @FormParam("password") String password) { try { boolean validCustomer = customerService.validateCustomer(login, password); if (!validCustomer) { return Response.status(Response.Status.FORBIDDEN).build(); } CustomerSession session = customerService.createSession(login); // TODO: Need to fix the security issues here - they are pretty gross likely NewCookie sessCookie = new NewCookie(SESSIONID_COOKIE_NAME, session.getId()); // TODO: The mobile client app requires JSON in the response. // To support the mobile client app, choose one of the following designs: // - Change this method to return JSON, and change the web app javascript to handle a JSON response. // example: return Response.ok("{\"status\":\"logged-in\"}").cookie(sessCookie).build(); // - Or create another method which is identical to this one, except returns JSON response. // Have the web app use the original method, and the mobile client app use the new one. return Response.ok("logged in").cookie(sessCookie).build(); } catch (Exception e) { e.printStackTrace(); return null; } } @GET @Path("/logout") @Produces("text/plain") public Response logout(@QueryParam("login") String login, @CookieParam("sessionid") String sessionid) { try { customerService.invalidateSession(sessionid); // The following call will trigger query against all partitions, disable for now // customerService.invalidateAllUserSessions(login); // TODO: Want to do this with setMaxAge to zero, but to do that I need to have the same path/domain as cookie // created in login. Unfortunately, until we have a elastic ip and domain name its hard to do that for "localhost". // doing this will set the cookie to the empty string, but the browser will still send the cookie to future requests // and the server will need to detect the value is invalid vs actually forcing the browser to time out the cookie and // not send it to begin with NewCookie sessCookie = new NewCookie(SESSIONID_COOKIE_NAME, ""); return Response.ok("logged out").cookie(sessCookie).build(); } catch (Exception e) { e.printStackTrace(); return null; } } }
3,440
39.964286
120
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/RESTCookieSessionFilter.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import java.io.IOException; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.acmeair.entities.CustomerSession; import com.acmeair.service.CustomerService; import com.acmeair.service.ServiceLocator; import com.acmeair.service.TransactionService; public class RESTCookieSessionFilter implements Filter { static final String LOGIN_USER = "acmeair.login_user"; private static final String LOGIN_PATH = "/rest/api/login"; private static final String LOGOUT_PATH = "/rest/api/login/logout"; private static final String LOADDB_PATH = "/rest/api/loaddb"; private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); private TransactionService transactionService = ServiceLocator.instance().getService(TransactionService.class);; @Inject BeanManager beanManager; @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)resp; String path = request.getContextPath() + request.getServletPath() + request.getPathInfo(); // The following code is to ensure that OG is always set on the thread try{ if (transactionService!=null) transactionService.prepareForTransaction(); }catch( Exception e) { e.printStackTrace(); } if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH) || path.endsWith(LOADDB_PATH)) { // if logging in, logging out, or loading the database, let the request flow chain.doFilter(req, resp); return; } Cookie cookies[] = request.getCookies(); Cookie sessionCookie = null; if (cookies != null) { for (Cookie c : cookies) { if (c.getName().equals(LoginREST.SESSIONID_COOKIE_NAME)) { sessionCookie = c; } if (sessionCookie!=null) break; } String sessionId = ""; if (sessionCookie!=null) // We need both cookie to work sessionId= sessionCookie.getValue().trim(); // did this check as the logout currently sets the cookie value to "" instead of aging it out // see comment in LogingREST.java if (sessionId.equals("")) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Need the URLDecoder so that I can get @ not %40 CustomerSession cs = customerService.validateSession(sessionId); if (cs != null) { request.setAttribute(LOGIN_USER, cs.getCustomerid()); chain.doFilter(req, resp); return; } else { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } // if we got here, we didn't detect the session cookie, so we need to return 404 response.sendError(HttpServletResponse.SC_FORBIDDEN); } @Override public void init(FilterConfig config) throws ServletException { } }
3,998
33.179487
121
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/AddressInfo.java
/******************************************************************************* * Copyright (c) 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.CustomerAddress; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement(name="CustomerAddress") public class AddressInfo implements Serializable{ private static final long serialVersionUID = 1L; private String streetAddress1; private String streetAddress2; private String city; private String stateProvince; private String country; private String postalCode; public AddressInfo() { } public AddressInfo(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode) { super(); this.streetAddress1 = streetAddress1; this.streetAddress2 = streetAddress2; this.city = city; this.stateProvince = stateProvince; this.country = country; this.postalCode = postalCode; } public AddressInfo(CustomerAddress address) { super(); this.streetAddress1 = address.getStreetAddress1(); this.streetAddress2 = address.getStreetAddress2(); this.city = address.getCity(); this.stateProvince = address.getStateProvince(); this.country = address.getCountry(); this.postalCode = address.getPostalCode(); } public String getStreetAddress1() { return streetAddress1; } public void setStreetAddress1(String streetAddress1) { this.streetAddress1 = streetAddress1; } public String getStreetAddress2() { return streetAddress2; } public void setStreetAddress2(String streetAddress2) { this.streetAddress2 = streetAddress2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStateProvince() { return stateProvince; } public void setStateProvince(String stateProvince) { this.stateProvince = stateProvince; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } @Override public String toString() { return "CustomerAddress [streetAddress1=" + streetAddress1 + ", streetAddress2=" + streetAddress2 + ", city=" + city + ", stateProvince=" + stateProvince + ", country=" + country + ", postalCode=" + postalCode + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AddressInfo other = (AddressInfo) obj; if (city == null) { if (other.city != null) return false; } else if (!city.equals(other.city)) return false; if (country == null) { if (other.country != null) return false; } else if (!country.equals(other.country)) return false; if (postalCode == null) { if (other.postalCode != null) return false; } else if (!postalCode.equals(other.postalCode)) return false; if (stateProvince == null) { if (other.stateProvince != null) return false; } else if (!stateProvince.equals(other.stateProvince)) return false; if (streetAddress1 == null) { if (other.streetAddress1 != null) return false; } else if (!streetAddress1.equals(other.streetAddress1)) return false; if (streetAddress2 == null) { if (other.streetAddress2 != null) return false; } else if (!streetAddress2.equals(other.streetAddress2)) return false; return true; } }
4,325
27.460526
80
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/BookingInfo.java
package com.acmeair.web.dto; import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.Booking; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement(name="Booking") public class BookingInfo { @XmlElement(name="bookingId") private String bookingId; @XmlElement(name="flightId") private String flightId; @XmlElement(name="customerId") private String customerId; @XmlElement(name="dateOfBooking") private Date dateOfBooking; @XmlElement(name="pkey") private BookingPKInfo pkey; public BookingInfo() { } public BookingInfo(Booking booking){ this.bookingId = booking.getBookingId(); this.flightId = booking.getFlightId(); this.customerId = booking.getCustomerId(); this.dateOfBooking = booking.getDateOfBooking(); this.pkey = new BookingPKInfo(this.customerId, this.bookingId); } public String getBookingId() { return bookingId; } public void setBookingId(String bookingId) { this.bookingId = bookingId; } public String getFlightId() { return flightId; } public void setFlightId(String flightId) { this.flightId = flightId; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public Date getDateOfBooking() { return dateOfBooking; } public void setDateOfBooking(Date dateOfBooking) { this.dateOfBooking = dateOfBooking; } public BookingPKInfo getPkey(){ return pkey; } }
1,629
21.328767
65
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/BookingPKInfo.java
package com.acmeair.web.dto; import javax.xml.bind.annotation.XmlElement; public class BookingPKInfo { @XmlElement(name="id") private String id; @XmlElement(name="customerId") private String customerId; public BookingPKInfo() { } public BookingPKInfo(String customerId,String id) { this.id = id; this.customerId = customerId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } }
595
13.190476
52
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/BookingReceiptInfo.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; public class BookingReceiptInfo { private String departBookingId; private String returnBookingId; private boolean oneWay; public BookingReceiptInfo(String departBookingId, String returnBookingId, boolean oneWay) { this.departBookingId = departBookingId; this.returnBookingId = returnBookingId; this.oneWay = oneWay; } public BookingReceiptInfo() { } public String getDepartBookingId() { return departBookingId; } public void setDepartBookingId(String departBookingId) { this.departBookingId = departBookingId; } public String getReturnBookingId() { return returnBookingId; } public void setReturnBookingId(String returnBookingId) { this.returnBookingId = returnBookingId; } public boolean isOneWay() { return oneWay; } public void setOneWay(boolean oneWay) { this.oneWay = oneWay; } @Override public String toString() { return "BookingInfo [departBookingId=" + departBookingId + ", returnBookingId=" + returnBookingId + ", oneWay=" + oneWay + "]"; } }
1,780
29.186441
92
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/CustomerInfo.java
/******************************************************************************* * Copyright (c) 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.Customer; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement(name="Customer") public class CustomerInfo implements Serializable{ private static final long serialVersionUID = 1L; @XmlElement(name="_id") private String _id; @XmlElement(name="password") private String password; @XmlElement(name="status") private String status; @XmlElement(name="total_miles") private int total_miles; @XmlElement(name="miles_ytd") private int miles_ytd; @XmlElement(name="address") private AddressInfo address; @XmlElement(name="phoneNumber") private String phoneNumber; @XmlElement(name="phoneNumberType") private String phoneNumberType; public CustomerInfo() { } public CustomerInfo(String username, String password, String status, int total_miles, int miles_ytd, AddressInfo address, String phoneNumber, String phoneNumberType) { this._id = username; this.password = password; this.status = status; this.total_miles = total_miles; this.miles_ytd = miles_ytd; this.address = address; this.phoneNumber = phoneNumber; this.phoneNumberType = phoneNumberType; } public CustomerInfo(Customer c) { this._id = c.getUsername(); this.password = c.getPassword(); this.status = c.getStatus().toString(); this.total_miles = c.getTotal_miles(); this.miles_ytd = c.getMiles_ytd(); this.address = new AddressInfo(c.getAddress()); this.phoneNumber = c.getPhoneNumber(); this.phoneNumberType = c.getPhoneNumberType().toString(); } public String getUsername() { return _id; } public void setUsername(String username) { this._id = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getTotal_miles() { return total_miles; } public void setTotal_miles(int total_miles) { this.total_miles = total_miles; } public int getMiles_ytd() { return miles_ytd; } public void setMiles_ytd(int miles_ytd) { this.miles_ytd = miles_ytd; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPhoneNumberType() { return phoneNumberType; } public void setPhoneNumberType(String phoneNumberType) { this.phoneNumberType = phoneNumberType; } public AddressInfo getAddress() { return address; } public void setAddress(AddressInfo address) { this.address = address; } @Override public String toString() { return "Customer [id=" + _id + ", password=" + password + ", status=" + status + ", total_miles=" + total_miles + ", miles_ytd=" + miles_ytd + ", address=" + address + ", phoneNumber=" + phoneNumber + ", phoneNumberType=" + phoneNumberType + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CustomerInfo other = (CustomerInfo) obj; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; if (_id == null) { if (other._id != null) return false; } else if (!_id.equals(other._id)) return false; if (miles_ytd != other.miles_ytd) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (phoneNumber == null) { if (other.phoneNumber != null) return false; } else if (!phoneNumber.equals(other.phoneNumber)) return false; if (phoneNumberType != other.phoneNumberType) return false; if (status != other.status) return false; if (total_miles != other.total_miles) return false; return true; } }
4,918
24.096939
168
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/FlightInfo.java
package com.acmeair.web.dto; import java.math.BigDecimal; import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.Flight; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement(name="Flight") public class FlightInfo { @XmlElement(name="_id") private String _id; private String flightSegmentId; private Date scheduledDepartureTime; private Date scheduledArrivalTime; private BigDecimal firstClassBaseCost; private BigDecimal economyClassBaseCost; private int numFirstClassSeats; private int numEconomyClassSeats; private String airplaneTypeId; private FlightSegmentInfo flightSegment; @XmlElement(name="pkey") private FlightPKInfo pkey; public FlightInfo(){ } public FlightInfo(Flight flight){ this._id = flight.getFlightId(); this.flightSegmentId = flight.getFlightSegmentId(); this.scheduledDepartureTime = flight.getScheduledDepartureTime(); this.scheduledArrivalTime = flight.getScheduledArrivalTime(); this.firstClassBaseCost = flight.getFirstClassBaseCost(); this.economyClassBaseCost = flight.getEconomyClassBaseCost(); this.numFirstClassSeats = flight.getNumFirstClassSeats(); this.numEconomyClassSeats = flight.getNumEconomyClassSeats(); this.airplaneTypeId = flight.getAirplaneTypeId(); if(flight.getFlightSegment() != null){ this.flightSegment = new FlightSegmentInfo(flight.getFlightSegment()); } else { this.flightSegment = null; } this.pkey = new FlightPKInfo(this.flightSegmentId, this._id); } public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getFlightSegmentId() { return flightSegmentId; } public void setFlightSegmentId(String flightSegmentId) { this.flightSegmentId = flightSegmentId; } public Date getScheduledDepartureTime() { return scheduledDepartureTime; } public void setScheduledDepartureTime(Date scheduledDepartureTime) { this.scheduledDepartureTime = scheduledDepartureTime; } public Date getScheduledArrivalTime() { return scheduledArrivalTime; } public void setScheduledArrivalTime(Date scheduledArrivalTime) { this.scheduledArrivalTime = scheduledArrivalTime; } public BigDecimal getFirstClassBaseCost() { return firstClassBaseCost; } public void setFirstClassBaseCost(BigDecimal firstClassBaseCost) { this.firstClassBaseCost = firstClassBaseCost; } public BigDecimal getEconomyClassBaseCost() { return economyClassBaseCost; } public void setEconomyClassBaseCost(BigDecimal economyClassBaseCost) { this.economyClassBaseCost = economyClassBaseCost; } public int getNumFirstClassSeats() { return numFirstClassSeats; } public void setNumFirstClassSeats(int numFirstClassSeats) { this.numFirstClassSeats = numFirstClassSeats; } public int getNumEconomyClassSeats() { return numEconomyClassSeats; } public void setNumEconomyClassSeats(int numEconomyClassSeats) { this.numEconomyClassSeats = numEconomyClassSeats; } public String getAirplaneTypeId() { return airplaneTypeId; } public void setAirplaneTypeId(String airplaneTypeId) { this.airplaneTypeId = airplaneTypeId; } public FlightSegmentInfo getFlightSegment() { return flightSegment; } public void setFlightSegment(FlightSegmentInfo flightSegment) { this.flightSegment = flightSegment; } public FlightPKInfo getPkey(){ return pkey; } }
3,519
28.830508
73
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/FlightPKInfo.java
package com.acmeair.web.dto; public class FlightPKInfo { private String id; private String flightSegmentId; FlightPKInfo(){} FlightPKInfo(String flightSegmentId,String id){ this.id = id; this.flightSegmentId = flightSegmentId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFlightSegmentId() { return flightSegmentId; } public void setFlightSegmentId(String flightSegmentId) { this.flightSegmentId = flightSegmentId; } }
508
17.851852
57
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/FlightSegmentInfo.java
package com.acmeair.web.dto; import com.acmeair.entities.FlightSegment; public class FlightSegmentInfo { private String _id; private String originPort; private String destPort; private int miles; public FlightSegmentInfo() { } public FlightSegmentInfo(FlightSegment flightSegment) { this._id = flightSegment.getFlightName(); this.originPort = flightSegment.getOriginPort(); this.destPort = flightSegment.getDestPort(); this.miles = flightSegment.getMiles(); } public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getOriginPort() { return originPort; } public void setOriginPort(String originPort) { this.originPort = originPort; } public String getDestPort() { return destPort; } public void setDestPort(String destPort) { this.destPort = destPort; } public int getMiles() { return miles; } public void setMiles(int miles) { this.miles = miles; } }
958
19.847826
56
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/TripFlightOptions.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; /** * TripFlightOptions is the main return type when searching for flights. * * The object will return as many tripLeg's worth of Flight options as requested. So if the user * requests a one way flight they will get a List that has only one TripLegInfo and it will have * a list of flights that are options for that flight. If a user selects round trip, they will * have a List of two TripLegInfo objects. If a user does a multi-leg flight then the list will * be whatever size they requested. For now, only supporting one way and return flights so the * list should always be of size one or two. * * * @author aspyker * */ @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement public class TripFlightOptions { private int tripLegs; private List<TripLegInfo> tripFlights; public int getTripLegs() { return tripLegs; } public void setTripLegs(int tripLegs) { this.tripLegs = tripLegs; } public List<TripLegInfo> getTripFlights() { return tripFlights; } public void setTripFlights(List<TripLegInfo> tripFlights) { this.tripFlights = tripFlights; } }
2,039
33
97
java
acmeair
acmeair-master/acmeair-webapp/src/main/java/com/acmeair/web/dto/TripLegInfo.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; import java.util.ArrayList; import java.util.List; import com.acmeair.entities.Flight; /** * The TripLegInfo object contains a list of flights that satisfy the query request for any one * leg of a trip. Also, it supports paging so a query can't return too many requests. * @author aspyker * */ public class TripLegInfo { public static int DEFAULT_PAGE_SIZE = 10; private boolean hasMoreOptions; private int numPages; private int pageSize; private int currentPage; private List<FlightInfo> flightsOptions; public boolean isHasMoreOptions() { return hasMoreOptions; } public void setHasMoreOptions(boolean hasMoreOptions) { this.hasMoreOptions = hasMoreOptions; } public int getNumPages() { return numPages; } public void setNumPages(int numPages) { this.numPages = numPages; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public List<FlightInfo> getFlightsOptions() { return flightsOptions; } public void setFlightsOptions(List<Flight> flightsOptions) { List<FlightInfo> flightInfoOptions = new ArrayList<FlightInfo>(); for(Flight info : flightsOptions){ flightInfoOptions.add(new FlightInfo(info)); } this.flightsOptions = flightInfoOptions; } }
2,196
24.847059
95
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/BackOrderMgr.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; import java.io.Serializable; import java.util.Collection; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.Dependent; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.ibm.websphere.samples.pbw.jpa.BackOrder; import com.ibm.websphere.samples.pbw.jpa.Inventory; import com.ibm.websphere.samples.pbw.utils.Util; /** * The BackOrderMgr provides a transactional and secured facade to access back order information. * This bean no longer requires an interface as there is one and only one implementation. */ @Dependent @RolesAllowed("SampAdmin") public class BackOrderMgr implements Serializable { @PersistenceContext(unitName = "PBW") private EntityManager em; /** * Method createBackOrder. * * @param inventoryID * @param amountToOrder * @param maximumItems */ public void createBackOrder(String inventoryID, int amountToOrder, int maximumItems) { try { Util.debug("BackOrderMgr.createBackOrder() - Entered"); BackOrder backOrder = null; try { // See if there is already an existing backorder and increase // the order quantity // but only if it has not been sent to the supplier. Query q = em.createNamedQuery("findByInventoryID"); q.setParameter("id", inventoryID); backOrder = (BackOrder) q.getSingleResult(); if (!(backOrder.getStatus().equals(Util.STATUS_ORDERSTOCK))) { Util.debug("BackOrderMgr.createBackOrder() - Backorders found but have already been ordered from the supplier"); // throw new FinderException(); } // Increase the BackOrder quantity for an existing Back Order. backOrder.setQuantity(backOrder.getQuantity() + amountToOrder); } catch (NoResultException e) { Util.debug("BackOrderMgr.createBackOrder() - BackOrder doesn't exist." + e); Util.debug("BackOrderMgr.createBackOrder() - Creating BackOrder for InventoryID: " + inventoryID); // Order enough stock from the supplier to reach the maximum // threshold and to // satisfy the back order. amountToOrder = maximumItems + amountToOrder; Inventory inv = em.find(Inventory.class, inventoryID); BackOrder b = new BackOrder(inv, amountToOrder); em.persist(b); } } catch (Exception e) { Util.debug("BackOrderMgr.createBackOrder() - Exception: " + e); } } /** * Method findBackOrderItems. * * @return Collection */ @SuppressWarnings("unchecked") public Collection<BackOrder> findBackOrders() { Query q = em.createNamedQuery("findAllBackOrders"); return q.getResultList(); } /** * Method deleteBackOrder. * * @param backOrderID */ public void deleteBackOrder(String backOrderID) { Util.debug("BackOrderMgr.deleteBackOrder() - Entered"); // BackOrderLocal backOrder = // getBackOrderLocalHome().findByPrimaryKeyUpdate(backOrderID); BackOrder backOrder = em.find(BackOrder.class, backOrderID); em.remove(backOrder); } /** * Method receiveConfirmation. * * @param backOrderID * / public int receiveConfirmation(String backOrderID) { int rc = 0; BackOrder * backOrder; Util.debug( * "BackOrderMgr.receiveConfirmation() - Finding Back Order for backOrderID=" + * backOrderID); backOrder = em.find(BackOrder.class, backOrderID); * backOrder.setStatus(Util.STATUS_RECEIVEDSTOCK); Util.debug( * "BackOrderMgr.receiveConfirmation() - Updating status(" + * Util.STATUS_RECEIVEDSTOCK + ") of backOrderID(" + backOrderID + ")"); return (rc); * } */ /** * Method orderStock. * * @param backOrderID * @param quantity * / public void orderStock(String backOrderID, int quantity) { * this.setBackOrderStatus(backOrderID, Util.STATUS_ORDEREDSTOCK); * this.setBackOrderQuantity(backOrderID, quantity); * this.setBackOrderOrderDate(backOrderID); } */ /** * Method updateStock. * * @param backOrderID * @param quantity */ public void updateStock(String backOrderID, int quantity) { this.setBackOrderStatus(backOrderID, Util.STATUS_ADDEDSTOCK); } /** * @param backOrderID * / public void abortorderStock(String backOrderID) { Util.debug( * "backOrderStockBean.abortorderStock() - Aborting orderStock transation for backorderID: " * + backOrderID); // Reset the back order status since the order failed. * this.setBackOrderStatus(backOrderID, Util.STATUS_ORDERSTOCK); } */ /** * Method getBackOrderID. * * @param backOrderID * @return String / public String getBackOrderID(String backOrderID) { String retbackOrderID = * ""; Util.debug( "BackOrderMgr.getBackOrderID() - Entered"); // BackOrderLocal * backOrder = getBackOrderLocalHome().findByPrimaryKey(new BackOrderKey(backOrderID)); * BackOrder backOrder = em.find(BackOrder.class, backOrderID); retbackOrderID = * backOrder.getBackOrderID(); return retbackOrderID; } */ /** * Method getBackOrderInventoryID. * * @param backOrderID * @return String */ public String getBackOrderInventoryID(String backOrderID) { String retinventoryID = ""; Util.debug("BackOrderMgr.getBackOrderID() - Entered"); // BackOrderLocal backOrder = // getBackOrderLocalHome().findByPrimaryKey(new // BackOrderKey(backOrderID)); BackOrder backOrder = em.find(BackOrder.class, backOrderID); retinventoryID = backOrder.getInventory().getInventoryId(); return retinventoryID; } /** * Method getBackOrderQuantity. * * @param backOrderID * @return int */ public int getBackOrderQuantity(String backOrderID) { int backOrderQuantity = -1; Util.debug("BackOrderMgr.getBackOrderQuantity() - Entered"); // BackOrderLocal backOrder = // getBackOrderLocalHome().findByPrimaryKey(new // BackOrderKey(backOrderID)); BackOrder backOrder = em.find(BackOrder.class, backOrderID); backOrderQuantity = backOrder.getQuantity(); return backOrderQuantity; } /** * Method setBackOrderQuantity. * * @param backOrderID * @param quantity */ public void setBackOrderQuantity(String backOrderID, int quantity) { Util.debug("BackOrderMgr.setBackOrderQuantity() - Entered"); // BackOrderLocal backOrder = // getBackOrderLocalHome().findByPrimaryKeyUpdate(backOrderID); BackOrder backOrder = em.find(BackOrder.class, backOrderID); backOrder.setQuantity(quantity); } /** * Method setBackOrderStatus. * * @param backOrderID * @param Status */ public void setBackOrderStatus(String backOrderID, String Status) { Util.debug("BackOrderMgr.setBackOrderStatus() - Entered"); // BackOrderLocal backOrder = // getBackOrderLocalHome().findByPrimaryKeyUpdate(backOrderID); BackOrder backOrder = em.find(BackOrder.class, backOrderID); backOrder.setStatus(Status); } /** * Method setBackOrderOrderDate. * * @param backOrderID */ public void setBackOrderOrderDate(String backOrderID) { Util.debug("BackOrderMgr.setBackOrderQuantity() - Entered"); // BackOrderLocal backOrder = // getBackOrderLocalHome().findByPrimaryKeyUpdate(backOrderID); BackOrder backOrder = em.find(BackOrder.class, backOrderID); backOrder.setOrderDate(System.currentTimeMillis()); } }
8,602
34.995816
117
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/CatalogMgr.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; import java.io.Serializable; import java.util.Vector; import javax.enterprise.context.Dependent; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.ibm.websphere.samples.pbw.jpa.Inventory; import com.ibm.websphere.samples.pbw.utils.Util; /** * The CatalogMgr provides transactional access to the catalog of items the store is willing to sell * to customers. * * @see com.ibm.websphere.samples.pbw.jpa.Inventory */ @Dependent @SuppressWarnings("unchecked") public class CatalogMgr implements Serializable { @PersistenceContext(unitName = "PBW") EntityManager em; /** * Get all inventory items. * * @return Vector of Inventorys. / public Vector<Inventory> getItems() { Vector<Inventory> items * = new Vector<Inventory>(); int count = Util.getCategoryStrings().length; for (int i = * 0; i < count; i++) { items.addAll(getItemsByCategory(i)); } return items; } */ /** * Get all inventory items for the given category. * * @param category * of items desired. * @return Vector of Inventory. */ public Vector<Inventory> getItemsByCategory(int category) { Query q = em.createNamedQuery("getItemsByCategory"); q.setParameter("category", category); // The return type must be Vector because the PBW client ActiveX sample requires Vector return new Vector<Inventory>(q.getResultList()); } /** * Get inventory items that contain a given String within their names. * * @param name * String to search names for. * @return A Vector of Inventorys that match. / public Vector<Inventory> getItemsLikeName(String * name) { Query q = em.createNamedQuery("getItemsLikeName"); q.setParameter("name", '%' * + name + '%'); //The return type must be Vector because the PBW client ActiveX sample * requires Vector return new Vector<Inventory>(q.getResultList()); } */ /** * Get the StoreItem for the given ID. * * @param inventoryID * - ID of the Inventory item desired. * @return StoreItem / public StoreItem getItem(String inventoryID) { return new * StoreItem(getItemInventory(inventoryID)); } */ /** * Get the Inventory item for the given ID. * * @param inventoryID * - ID of the Inventory item desired. * @return Inventory */ public Inventory getItemInventory(String inventoryID) { Inventory si = null; Util.debug("getItemInventory id=" + inventoryID); si = em.find(Inventory.class, inventoryID); return si; } /** * Add an inventory item. * * @param item * The Inventory to add. * @return True, if item added. */ public boolean addItem(Inventory item) { boolean retval = true; Util.debug("addItem " + item.getInventoryId()); em.persist(item); em.flush(); return retval; } /** * Add an StoreItem item (same as Inventory item). * * @param item * The StoreItem to add. * @return True, if item added. / public boolean addItem(StoreItem item) { return addItem(new * Inventory(item)); } */ /** * Delete an inventory item. * * @param inventoryID * The ID of the inventory item to delete. * @return True, if item deleted. / public boolean deleteItem(String inventoryID) { boolean * retval = true; em.remove(em.find(Inventory.class, inventoryID)); return retval; } */ /** * Get the image for the inventory item. * * @param inventoryID * The id of the inventory item wanted. * @return Buffer containing the image. */ public byte[] getItemImageBytes(String inventoryID) { byte[] retval = null; Inventory inv = getInv(inventoryID); if (inv != null) { retval = inv.getImgbytes(); } return retval; } /** * Set the image for the inventory item. * * @param inventoryID * The id of the inventory item wanted. * @param imgbytes * Buffer containing the image. */ public void setItemImageBytes(String inventoryID, byte[] imgbytes) { Inventory inv = getInvUpdate(inventoryID); if (inv != null) { inv.setImgbytes(imgbytes); } } /** * Set the inventory item's quantity. * * @param inventoryID * The inventory item's ID. * @param quantity * The inventory item's new quantity. */ public void setItemQuantity(String inventoryID, int quantity) { Inventory inv = getInvUpdate(inventoryID); if (inv != null) { inv.setQuantity(quantity); } } /** * Get a remote Inventory object. * * @param inventoryID * The id of the inventory item wanted. * @return Reference to the remote Inventory object. */ private Inventory getInv(String inventoryID) { return em.find(Inventory.class, inventoryID); } /** * Get a remote Inventory object to Update. * * @param inventoryID * The id of the inventory item wanted. * @return Reference to the remote Inventory object. */ private Inventory getInvUpdate(String inventoryID) { Inventory inv = null; inv = em.find(Inventory.class, inventoryID); em.lock(inv, LockModeType.OPTIMISTIC_FORCE_INCREMENT); em.refresh(inv); return inv; } }
6,488
30.5
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/CustomerMgr.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; import java.io.Serializable; import javax.enterprise.context.Dependent; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import com.ibm.websphere.samples.pbw.jpa.Customer; import com.ibm.websphere.samples.pbw.utils.Util; /** * The CustomerMgr provides a transactional facade for access to a user DB as well as simple * authentication support for those users. * */ @Transactional @Dependent public class CustomerMgr implements Serializable { @PersistenceContext(unitName = "PBW") EntityManager em; /** * Create a new user. * * @param customerID * The new customer ID. * @param password * The password for the customer ID. * @param firstName * First name. * @param lastName * Last name. * @param addr1 * Address line 1. * @param addr2 * Address line 2. * @param addrCity * City address information. * @param addrState * State address information. * @param addrZip * Zip code address information. * @param phone * User's phone number. * @return Customer */ public Customer createCustomer(String customerID, String password, String firstName, String lastName, String addr1, String addr2, String addrCity, String addrState, String addrZip, String phone) { Customer c = new Customer(customerID, password, firstName, lastName, addr1, addr2, addrCity, addrState, addrZip, phone); em.persist(c); em.flush(); return c; } /** * Retrieve an existing user. * * @param customerID * The customer ID. * @return Customer */ public Customer getCustomer(String customerID) { Customer c = em.find(Customer.class, customerID); return c; } /** * Update an existing user. * * @param customerID * The customer ID. * @param firstName * First name. * @param lastName * Last name. * @param addr1 * Address line 1. * @param addr2 * Address line 2. * @param addrCity * City address information. * @param addrState * State address information. * @param addrZip * Zip code address information. * @param phone * User's phone number. * @return Customer */ public Customer updateUser(String customerID, String firstName, String lastName, String addr1, String addr2, String addrCity, String addrState, String addrZip, String phone) { Customer c = em.find(Customer.class, customerID); em.lock(c, LockModeType.WRITE); em.refresh(c); c.setFirstName(firstName); c.setLastName(lastName); c.setAddr1(addr1); c.setAddr2(addr2); c.setAddrCity(addrCity); c.setAddrState(addrState); c.setAddrZip(addrZip); c.setPhone(phone); return c; } /** * Verify that the user exists and the password is value. * * @param customerID * The customer ID * @param password * The password for the customer ID * @return String with a results message. */ public String verifyUserAndPassword(String customerID, String password) { // Try to get customer. String results = null; Customer customer = null; customer = em.find(Customer.class, customerID); // Does customer exist? if (customer != null) { if (!customer.verifyPassword(password)) // Is password correct? { results = "\nPassword does not match for : " + customerID; Util.debug("Password given does not match for userid=" + customerID); } } else // Customer was not found. { results = "\nCould not find account for : " + customerID; Util.debug("customer " + customerID + " NOT found"); } return results; } }
5,089
27.757062
114
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/EMailMessage.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; /** * This class encapsulates the info needed to send an email message. This object is passed to the * Mailer EJB sendMail() method. */ public class EMailMessage implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; private String subject; private String htmlContents; private String emailReceiver; public EMailMessage(String subject, String htmlContents, String emailReceiver) { this.subject = subject; this.htmlContents = htmlContents; this.emailReceiver = emailReceiver; } // subject field of email message public String getSubject() { return subject; } // Email address of recipient of email message public String getEmailReceiver() { return emailReceiver; } // contents of email message public String getHtmlContents() { return htmlContents; } public String toString() { return " subject=" + subject + " " + emailReceiver + " " + htmlContents; } }
2,181
36.62069
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/MailerAppException.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; /** * MailerAppException extends the standard Exception. This is thrown by the mailer component when * there is some failure sending the mail. */ public class MailerAppException extends Exception { /** * */ private static final long serialVersionUID = 1L; public MailerAppException() { } public MailerAppException(String str) { super(str); } }
1,608
41.342105
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/MailerBean.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; import java.io.Serializable; import java.util.Date; import javax.annotation.Resource; import javax.enterprise.context.Dependent; import javax.inject.Named; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import com.ibm.websphere.samples.pbw.jpa.Customer; import com.ibm.websphere.samples.pbw.jpa.Order; import com.ibm.websphere.samples.pbw.utils.Util; /** * MailerBean provides a transactional facade for access to Order information and notification of * the buyer of order state. * */ @Named(value = "mailerbean") @Dependent public class MailerBean implements Serializable { private static final long serialVersionUID = 1L; // public static final String MAIL_SESSION = "java:comp/env/mail/PlantsByWebSphere"; @Resource(name = "mail/PlantsByWebSphere") Session mailSession; @PersistenceContext(unitName = "PBW") EntityManager em; /** * Create the email message. * * @param orderKey * The order number. * @return The email message. */ private String createMessage(String orderKey) { Util.debug("creating email message for order:" + orderKey); StringBuffer msg = new StringBuffer(); Order order = em.find(Order.class, orderKey); msg.append("Thank you for your order " + orderKey + ".\n"); msg.append("Your Plants By WebSphere order will be shipped to:\n"); msg.append(" " + order.getShipName() + "\n"); msg.append(" " + order.getShipAddr1() + " " + order.getShipAddr2() + "\n"); msg.append(" " + order.getShipCity() + ", " + order.getShipState() + " " + order.getShipZip() + "\n\n"); msg.append("Please save it for your records.\n"); return msg.toString(); } /** * Create the Subject line. * * @param orderKey * The order number. * @return The Order number string. */ private String createSubjectLine(String orderKey) { StringBuffer msg = new StringBuffer(); msg.append("Your order number " + orderKey); return msg.toString(); } /** * Create a mail message and send it. * * @param customerInfo * Customer information. * @param orderKey * @throws MailerAppException */ public void createAndSendMail(Customer customerInfo, String orderKey) throws MailerAppException { try { EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey), customerInfo.getCustomerID()); Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: " + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents()); Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: " + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents()); MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false)); msg.setSubject(eMessage.getSubject()); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(eMessage.getHtmlContents(), "us-ascii"); msg.setHeader("X-Mailer", "JavaMailer"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp); msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); Util.debug("Mail sent successfully."); } catch (Exception e) { Util.debug("Error sending mail. Have mail resources been configured correctly?"); Util.debug("createAndSendMail exception : " + e); e.printStackTrace(); throw new MailerAppException("Failure while sending mail"); } } }
5,049
35.594203
110
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/NoSupplierException.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; public class NoSupplierException extends Exception { /** * */ private static final long serialVersionUID = 1L; /** * Method NoSupplierException * * @param message */ public NoSupplierException(String message) { super(message); return; } }
1,508
40.916667
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/PopulateDBBean.java
package com.ibm.websphere.samples.pbw.bean; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.inject.Inject; import com.ibm.websphere.samples.pbw.utils.Util; @Singleton @Startup public class PopulateDBBean { @Inject ResetDBBean dbBean; @PostConstruct public void initDB() { Util.debug("Initializing database..."); dbBean.populateDB(); } }
445
17.583333
48
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/ResetDBBean.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2004,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Serializable; import java.net.URL; import java.util.Vector; import javax.annotation.Resource; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; import javax.persistence.Query; import javax.persistence.SynchronizationType; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.Transactional; import javax.transaction.UserTransaction; import com.ibm.websphere.samples.pbw.jpa.Inventory; import com.ibm.websphere.samples.pbw.utils.Util; /** * ResetDBBean provides a transactional and secure facade to reset all the database information for * the PlantsByWebSphere application. */ @Named(value = "resetbean") @Dependent @RolesAllowed("SampAdmin") public class ResetDBBean implements Serializable { @Inject private CatalogMgr catalog; @Inject private CustomerMgr customer; @Inject private ShoppingCartBean cart; @Inject private BackOrderMgr backOrderStock; @Inject private SuppliersBean suppliers; @PersistenceContext(unitName = "PBW") EntityManager em; @Resource UserTransaction tx; public void resetDB() { deleteAll(); populateDB(); } /** * @param itemID * @param fileName * @param catalog * @throws FileNotFoundException * @throws IOException */ public static void addImage(String itemID, String fileName, CatalogMgr catalog) throws FileNotFoundException, IOException { URL url = Thread.currentThread().getContextClassLoader().getResource("resources/images/" + fileName); Util.debug("URL: " + url); fileName = url.getPath(); Util.debug("Fully-qualified Filename: " + fileName); File imgFile = new File(fileName); // Open the input file as a stream of bytes FileInputStream fis = new FileInputStream(imgFile); DataInputStream dis = new DataInputStream(fis); int dataSize = dis.available(); byte[] data = new byte[dataSize]; dis.readFully(data); catalog.setItemImageBytes(itemID, data); } public void populateDB() { /** * Populate INVENTORY table with text */ Util.debug("Populating INVENTORY table with text..."); try { String[] values = Util.getProperties("inventory"); for (int index = 0; index < values.length; index++) { Util.debug("Found INVENTORY property values: " + values[index]); String[] fields = Util.readTokens(values[index], "|"); String id = fields[0]; String name = fields[1]; String heading = fields[2]; String descr = fields[3]; String pkginfo = fields[4]; String image = fields[5]; float price = new Float(fields[6]).floatValue(); float cost = new Float(fields[7]).floatValue(); int quantity = new Integer(fields[8]).intValue(); int category = new Integer(fields[9]).intValue(); String notes = fields[10]; boolean isPublic = new Boolean(fields[11]).booleanValue(); Util.debug("Populating INVENTORY with following values: "); Util.debug(fields[0]); Util.debug(fields[1]); Util.debug(fields[2]); Util.debug(fields[3]); Util.debug(fields[4]); Util.debug(fields[5]); Util.debug(fields[6]); Util.debug(fields[7]); Util.debug(fields[8]); Util.debug(fields[9]); Util.debug(fields[10]); Util.debug(fields[11]); Inventory storeItem = new Inventory(id, name, heading, descr, pkginfo, image, price, cost, quantity, category, notes, isPublic); catalog.addItem(storeItem); addImage(id, image, catalog); } Util.debug("INVENTORY table populated with text..."); } catch (Exception e) { Util.debug("Unable to populate INVENTORY table with text data: " + e); e.printStackTrace(); } /** * Populate CUSTOMER table with text */ Util.debug("Populating CUSTOMER table with default values..."); try { String[] values = Util.getProperties("customer"); Util.debug("Found CUSTOMER properties: " + values[0]); for (int index = 0; index < values.length; index++) { String[] fields = Util.readTokens(values[index], "|"); String customerID = fields[0]; String password = fields[1]; String firstName = fields[2]; String lastName = fields[3]; String addr1 = fields[4]; String addr2 = fields[5]; String addrCity = fields[6]; String addrState = fields[7]; String addrZip = fields[8]; String phone = fields[9]; Util.debug("Populating CUSTOMER with following values: "); Util.debug(fields[0]); Util.debug(fields[1]); Util.debug(fields[2]); Util.debug(fields[3]); Util.debug(fields[4]); Util.debug(fields[5]); Util.debug(fields[6]); Util.debug(fields[7]); Util.debug(fields[8]); Util.debug(fields[9]); customer.createCustomer(customerID, password, firstName, lastName, addr1, addr2, addrCity, addrState, addrZip, phone); } } catch (Exception e) { Util.debug("Unable to populate CUSTOMER table with text data: " + e); e.printStackTrace(); } /** * Populate ORDER table with text */ Util.debug("Populating ORDER table with default values..."); try { String[] values = Util.getProperties("order"); Util.debug("Found ORDER properties: " + values[0]); if (values[0] != null && values.length > 0) { for (int index = 0; index < values.length; index++) { String[] fields = Util.readTokens(values[index], "|"); if (fields != null && fields.length >= 21) { String customerID = fields[0]; String billName = fields[1]; String billAddr1 = fields[2]; String billAddr2 = fields[3]; String billCity = fields[4]; String billState = fields[5]; String billZip = fields[6]; String billPhone = fields[7]; String shipName = fields[8]; String shipAddr1 = fields[9]; String shipAddr2 = fields[10]; String shipCity = fields[11]; String shipState = fields[12]; String shipZip = fields[13]; String shipPhone = fields[14]; int shippingMethod = Integer.parseInt(fields[15]); String creditCard = fields[16]; String ccNum = fields[17]; String ccExpireMonth = fields[18]; String ccExpireYear = fields[19]; String cardHolder = fields[20]; Vector<Inventory> items = new Vector<Inventory>(); Util.debug("Populating ORDER with following values: "); Util.debug(fields[0]); Util.debug(fields[1]); Util.debug(fields[2]); Util.debug(fields[3]); Util.debug(fields[4]); Util.debug(fields[5]); Util.debug(fields[6]); Util.debug(fields[7]); Util.debug(fields[8]); Util.debug(fields[9]); Util.debug(fields[10]); Util.debug(fields[11]); Util.debug(fields[12]); Util.debug(fields[13]); Util.debug(fields[14]); Util.debug(fields[15]); Util.debug(fields[16]); Util.debug(fields[17]); Util.debug(fields[18]); Util.debug(fields[19]); Util.debug(fields[20]); cart.createOrder(customerID, billName, billAddr1, billAddr2, billCity, billState, billZip, billPhone, shipName, shipAddr1, shipAddr2, shipCity, shipState, shipZip, shipPhone, creditCard, ccNum, ccExpireMonth, ccExpireYear, cardHolder, shippingMethod, items); } else { Util.debug("Property does not contain enough fields: " + values[index]); Util.debug("Fields found were: " + fields); } } } // stmt.executeUpdate(" INSERT INTO ORDERITEM(INVENTORYID, NAME, PKGINFO, PRICE, COST, // CATEGORY, QUANTITY, SELLDATE, ORDER_ORDERID) VALUES ('A0001', 'Bulb Digger', // 'Assembled', 12.0, 5.0, 3, 900, '01054835419625', '1')"); } catch (Exception e) { Util.debug("Unable to populate ORDERITEM table with text data: " + e); e.printStackTrace(); e.printStackTrace(); } /** * Populate BACKORDER table with text */ Util.debug("Populating BACKORDER table with default values..."); try { String[] values = Util.getProperties("backorder"); Util.debug("Found BACKORDER properties: " + values[0]); // Inserting backorders for (int index = 0; index < values.length; index++) { String[] fields = Util.readTokens(values[index], "|"); String inventoryID = fields[0]; int amountToOrder = new Integer(fields[1]).intValue(); int maximumItems = new Integer(fields[2]).intValue(); Util.debug("Populating BACKORDER with following values: "); Util.debug(inventoryID); Util.debug("amountToOrder -> " + amountToOrder); Util.debug("maximumItems -> " + maximumItems); backOrderStock.createBackOrder(inventoryID, amountToOrder, maximumItems); } } catch (Exception e) { Util.debug("Unable to populate BACKORDER table with text data: " + e); e.printStackTrace(); } /** * Populate SUPPLIER table with text */ Util.debug("Populating SUPPLIER table with default values..."); try { String[] values = Util.getProperties("supplier"); Util.debug("Found SUPPLIER properties: " + values[0]); // Inserting Suppliers for (int index = 0; index < values.length; index++) { String[] fields = Util.readTokens(values[index], "|"); String supplierID = fields[0]; String name = fields[1]; String address = fields[2]; String city = fields[3]; String state = fields[4]; String zip = fields[5]; String phone = fields[6]; String url = fields[7]; Util.debug("Populating SUPPLIER with following values: "); Util.debug(fields[0]); Util.debug(fields[1]); Util.debug(fields[2]); Util.debug(fields[3]); Util.debug(fields[4]); Util.debug(fields[5]); Util.debug(fields[6]); Util.debug(fields[7]); suppliers.createSupplier(supplierID, name, address, city, state, zip, phone, url); } } catch (Exception e) { Util.debug("Unable to populate SUPPLIER table with text data: " + e); e.printStackTrace(); } } @Transactional public void deleteAll() { try { Query q = em.createNamedQuery("removeAllOrders"); q.executeUpdate(); q = em.createNamedQuery("removeAllInventory"); q.executeUpdate(); // q=em.createNamedQuery("removeAllIdGenerator"); // q.executeUpdate(); q = em.createNamedQuery("removeAllCustomers"); q.executeUpdate(); q = em.createNamedQuery("removeAllOrderItem"); q.executeUpdate(); q = em.createNamedQuery("removeAllBackOrder"); q.executeUpdate(); q = em.createNamedQuery("removeAllSupplier"); q.executeUpdate(); em.flush(); Util.debug("Deleted all data from database"); } catch (Exception e) { Util.debug("ResetDB(deleteAll) -- Error deleting data from the database: " + e); e.printStackTrace(); try { tx.setRollbackOnly(); } catch (IllegalStateException | SystemException ignore) { } } } }
12,389
35.122449
264
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/ShoppingCartBean.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import javax.enterprise.context.SessionScoped; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import com.ibm.websphere.samples.pbw.jpa.BackOrder; import com.ibm.websphere.samples.pbw.jpa.Customer; import com.ibm.websphere.samples.pbw.jpa.Inventory; import com.ibm.websphere.samples.pbw.jpa.Order; import com.ibm.websphere.samples.pbw.jpa.OrderItem; import com.ibm.websphere.samples.pbw.utils.Util; /** * ShopingCartBean provides a transactional facade for order collection and processing. * */ @Transactional @SessionScoped public class ShoppingCartBean implements Serializable { @PersistenceContext(unitName = "PBW") EntityManager em; private ArrayList<Inventory> items = new ArrayList<Inventory>(); /** * Add an item to the cart. * * @param new_item * Item to add to the cart. */ public void addItem(Inventory new_item) { boolean added = false; // If the same item is already in the cart, just increase the quantity. for (Inventory old_item : items) { if (old_item.getID().equals(new_item.getID())) { old_item.setQuantity(old_item.getQuantity() + new_item.getQuantity()); added = true; break; } } // Add this item to shopping cart, if it is a brand new item. if (!added) items.add(new_item); } /** * Remove an item from the cart. * * @param item * Item to remove from cart. */ public void removeItem(Inventory item) { for (Inventory i : items) { if (item.equals(i)) { items.remove(i); break; } } } /** * Remove all items from the cart. */ public void removeAllItems() { items = new ArrayList<Inventory>(); } /** * Remove zero quantity items. */ public void removeZeroQuantityItems() { ArrayList<Inventory> newItems = new ArrayList<Inventory>(); for (Inventory i : items) { if (i.getQuantity() > 0) { newItems.add(i); } } items = newItems; } /** * Get the items in the shopping cart. * * @return A Collection of ShoppingCartItems. */ public ArrayList<Inventory> getItems() { return items; } /** * Set the items in the shopping cart. * * @param items * A Vector of ShoppingCartItem's. */ public void setItems(Collection<Inventory> items) { this.items = new ArrayList<Inventory>(items); } /** * Get the contents of the shopping cart. * * @return The contents of the shopping cart. / public ShoppingCartContents getCartContents() { * ShoppingCartContents cartContents = new ShoppingCartContents(); // Fill it with data. * for (int i = 0; i < items.size(); i++) { cartContents.addItem((ShoppingCartItem) * items.get(i)); } return cartContents; } */ /** * Create a shopping cart. * * @param cartContents * Contents to populate cart with. / public void setCartContents(ShoppingCartContents * cartContents) { items = new ArrayList<ShoppingCartItem>(); int qty; String * inventoryID; ShoppingCartItem si; Inventory inv; for (int i = 0; i < * cartContents.size(); i++) { inventoryID = cartContents.getInventoryID(i); qty = * cartContents.getQuantity(inventoryID); inv = em.find(Inventory.class, * inventoryID); // clone so we can use Qty as qty to purchase, not inventory in * stock si = new ShoppingCartItem(inv); si.setQuantity(qty); addItem(si); } } */ /** * Get the cost of all items in the shopping cart. * * @return The total cost of all items in the shopping cart. */ public float getSubtotalCost() { float f = 0.0F; for (Inventory item : items) { f += item.getPrice() * (float) item.getQuantity(); } return f; } /** * Method checkInventory. Check the inventory level of a store item. Order additional inventory * when necessary. * * @param si * - Store item */ public void checkInventory(Inventory si) { Util.debug("ShoppingCart.checkInventory() - checking Inventory quantity of item: " + si.getID()); Inventory inv = getInventoryItem(si.getID()); /** * Decrease the quantity of this inventory item. * * @param quantity * The number to decrease the inventory by. * @return The number of inventory items removed. */ int quantity = si.getQuantity(); int minimumItems = inv.getMinThreshold(); int amountToOrder = 0; Util.debug("ShoppingCartBean:checkInventory() - Decreasing inventory item " + inv.getInventoryId()); int quantityNotFilled = 0; if (inv.getQuantity() < 1) { quantityNotFilled = quantity; } else if (inv.getQuantity() < quantity) { quantityNotFilled = quantity - inv.getQuantity(); } // When quantity becomes < 0, this will be to determine the // quantity of unfilled orders due to insufficient stock. inv.setQuantity(inv.getQuantity() - quantity); // Check to see if more inventory needs to be ordered from the supplier // based on a set minimum Threshold if (inv.getQuantity() < minimumItems) { // Calculate the amount of stock to order from the supplier // to get the inventory up to the maximum. amountToOrder = quantityNotFilled; backOrder(inv, amountToOrder); } } /** * Create an order with contents of a shopping cart. * * @param customerID * customer's ID * @param billName * billing name * @param billAddr1 * billing address line 1 * @param billAddr2 * billing address line 2 * @param billCity * billing address city * @param billState * billing address state * @param billZip * billing address zip code * @param billPhone * billing phone * @param shipName * shippng name * @param shipAddr1 * shippng address line 1 * @param shipAddr2 * shippng address line 2 * @param shipCity * shippng address city * @param shipState * shippng address state * @param shipZip * shippng address zip code * @param shipPhone * shippng phone * @param creditCard * credit card * @param ccNum * credit card number * @param ccExpireMonth * credit card expiration month * @param ccExpireYear * credit card expiration year * @param cardHolder * credit card holder name * @param shippingMethod * int of shipping method used * @param items * vector of StoreItems ordered * @return OrderInfo */ public Order createOrder(String customerID, String billName, String billAddr1, String billAddr2, String billCity, String billState, String billZip, String billPhone, String shipName, String shipAddr1, String shipAddr2, String shipCity, String shipState, String shipZip, String shipPhone, String creditCard, String ccNum, String ccExpireMonth, String ccExpireYear, String cardHolder, int shippingMethod, Collection<Inventory> items) { Order order = null; Util.debug("ShoppingCartBean.createOrder: Creating Order"); Collection<OrderItem> orderitems = new ArrayList<OrderItem>(); for (Inventory si : items) { Inventory inv = em.find(Inventory.class, si.getID()); OrderItem oi = new OrderItem(inv); oi.setQuantity(si.getQuantity()); orderitems.add(oi); } Customer c = em.find(Customer.class, customerID); order = new Order(c, billName, billAddr1, billAddr2, billCity, billState, billZip, billPhone, shipName, shipAddr1, shipAddr2, shipCity, shipState, shipZip, shipPhone, creditCard, ccNum, ccExpireMonth, ccExpireYear, cardHolder, shippingMethod, orderitems); em.persist(order); em.flush(); // store the order items for (OrderItem o : orderitems) { o.setOrder(order); o.updatePK(); em.persist(o); } em.flush(); return order; } public int getSize() { return getItems().size(); } /* * Get the inventory item. * * @param id of inventory item. * * @return an inventory bean. */ private Inventory getInventoryItem(String inventoryID) { Inventory inv = null; inv = em.find(Inventory.class, inventoryID); return inv; } /* * Create a BackOrder of this inventory item. * * @param quantity The number of the inventory item to be backordered */ private void backOrder(Inventory inv, int amountToOrder) { BackOrder b = em.find(BackOrder.class, inv.getInventoryId()); if (b == null) { // create a new backorder if none exists BackOrder newBO = new BackOrder(inv, amountToOrder); em.persist(newBO); em.flush(); inv.setBackOrder(newBO); } else { // update the backorder with the new quantity int quantity = b.getQuantity(); quantity += amountToOrder; em.lock(b, LockModeType.WRITE); em.refresh(b); b.setQuantity(quantity); em.flush(); inv.setBackOrder(b); } } }
10,306
28.617816
105
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/ShoppingCartContent.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; import java.util.Enumeration; import java.util.Hashtable; import com.ibm.websphere.samples.pbw.jpa.Inventory; /** * A class to hold a shopping cart's contents. */ public class ShoppingCartContent implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; private Hashtable<String, Integer> table = null; public ShoppingCartContent() { table = new Hashtable<String, Integer>(); } /** Add the item to the shopping cart. */ public void addItem(Inventory si) { table.put(si.getID(), new Integer(si.getQuantity())); } /** Update the item in the shopping cart. */ public void updateItem(Inventory si) { table.put(si.getID(), new Integer(si.getQuantity())); } /** Remove the item from the shopping cart. */ public void removeItem(Inventory si) { table.remove(si.getID()); } /** * Return the number of items in the cart. * * @return The number of items in the cart. */ public int size() { return table.size(); } /** * Return the inventory ID at the index given. The first element is at index 0, the second at * index 1, and so on. * * @return The inventory ID at the index, or NULL if not present. */ public String getInventoryID(int index) { String retval = null; String inventoryID; int cnt = 0; for (Enumeration<String> myEnum = table.keys(); myEnum.hasMoreElements(); cnt++) { inventoryID = (String) myEnum.nextElement(); if (index == cnt) { retval = inventoryID; break; } } return retval; } /** * Return the quantity for the inventory ID given. * * @return The quantity for the inventory ID given.. * */ public int getQuantity(String inventoryID) { Integer quantity = (Integer) table.get(inventoryID); if (quantity == null) return 0; else return quantity.intValue(); } }
3,065
30.285714
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/bean/SuppliersBean.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2004,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.bean; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import javax.enterprise.context.Dependent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.ibm.websphere.samples.pbw.jpa.Supplier; import com.ibm.websphere.samples.pbw.utils.Util; /** * Bean implementation class for Enterprise Bean: Suppliers */ @Dependent public class SuppliersBean implements Serializable { @PersistenceContext(unitName = "PBW") EntityManager em; /** * @param supplierID * @param name * @param street * @param city * @param state * @param zip * @param phone * @param url */ public void createSupplier(String supplierID, String name, String street, String city, String state, String zip, String phone, String url) { try { Util.debug("SuppliersBean.createSupplier() - Entered"); Supplier supplier = null; supplier = em.find(Supplier.class, supplierID); if (supplier == null) { Util.debug("SuppliersBean.createSupplier() - supplier doesn't exist."); Util.debug("SuppliersBean.createSupplier() - Creating Supplier for SupplierID: " + supplierID); supplier = new Supplier(supplierID, name, street, city, state, zip, phone, url); em.persist(supplier); } } catch (Exception e) { Util.debug("SuppliersBean.createSupplier() - Exception: " + e); } } /** * @return Supplier */ public Supplier getSupplier() { // Retrieve the first Supplier Info try { Collection<Supplier> suppliers = this.findSuppliers(); if (suppliers != null) { Util.debug("AdminServlet.getSupplierInfo() - Supplier found!"); Iterator<Supplier> i = suppliers.iterator(); if (i.hasNext()) { return (Supplier) i.next(); } } } catch (Exception e) { Util.debug("AdminServlet.getSupplierInfo() - Exception:" + e); } return null; } /** * @param supplierID * @param name * @param street * @param city * @param state * @param zip * @param phone * @param url * @return supplierInfo */ public Supplier updateSupplier(String supplierID, String name, String street, String city, String state, String zip, String phone, String url) { Supplier supplier = null; try { Util.debug("SuppliersBean.updateSupplier() - Entered"); supplier = em.find(Supplier.class, supplierID); if (supplier != null) { // Create a new Supplier if there is NOT an existing Supplier. // supplier = getSupplierLocalHome().findByPrimaryKey(new SupplierKey(supplierID)); supplier.setName(name); supplier.setStreet(street); supplier.setCity(city); supplier.setUsstate(state); supplier.setZip(zip); supplier.setPhone(phone); supplier.setUrl(url); } else { Util.debug("SuppliersBean.updateSupplier() - supplier doesn't exist."); Util.debug("SuppliersBean.updateSupplier() - Couldn't update Supplier for SupplierID: " + supplierID); } } catch (Exception e) { Util.debug("SuppliersBean.createSupplier() - Exception: " + e); } return (supplier); } /** * @return suppliers */ @SuppressWarnings("unchecked") private Collection<Supplier> findSuppliers() { Query q = em.createNamedQuery("findAllSuppliers"); return q.getResultList(); } }
4,543
30.337931
106
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/jpa/BackOrder.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.jpa; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import com.ibm.websphere.samples.pbw.utils.Util; /** * Bean mapping for BACKORDER table. */ @Entity(name = "BackOrder") @Table(name = "BACKORDER", schema = "APP") @NamedQueries({ @NamedQuery(name = "findAllBackOrders", query = "select b from BackOrder b"), @NamedQuery(name = "findByInventoryID", query = "select b from BackOrder b where ((b.inventory.inventoryId = :id) and (b.status = 'Order Stock'))"), @NamedQuery(name = "removeAllBackOrder", query = "delete from BackOrder") }) public class BackOrder { @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "BackOrderSeq") @TableGenerator(name = "BackOrderSeq", table = "IDGENERATOR", pkColumnName = "IDNAME", pkColumnValue = "BACKORDER", valueColumnName = "IDVALUE") private String backOrderID; private int quantity; private String status; private long lowDate; private long orderDate; private String supplierOrderID; // missing table // relationships @OneToOne @JoinColumn(name = "INVENTORYID") private Inventory inventory; public BackOrder() { } public BackOrder(String backOrderID) { setBackOrderID(backOrderID); } public BackOrder(Inventory inventory, int quantity) { this.setInventory(inventory); this.setQuantity(quantity); this.setStatus(Util.STATUS_ORDERSTOCK); this.setLowDate(System.currentTimeMillis()); } public String getBackOrderID() { return backOrderID; } public void setBackOrderID(String backOrderID) { this.backOrderID = backOrderID; } public long getLowDate() { return lowDate; } public void setLowDate(long lowDate) { this.lowDate = lowDate; } public long getOrderDate() { return orderDate; } public void setOrderDate(long orderDate) { this.orderDate = orderDate; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public void increateQuantity(int delta) { if (!(status.equals(Util.STATUS_ORDERSTOCK))) { Util.debug("BackOrderMgr.createBackOrder() - Backorders found but have already been ordered from the supplier"); throw new RuntimeException("cannot increase order size for orders already in progress"); } // Increase the BackOrder quantity for an existing Back Order. quantity = quantity + delta; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getSupplierOrderID() { return supplierOrderID; } public void setSupplierOrderID(String supplierOrderID) { this.supplierOrderID = supplierOrderID; } public Inventory getInventory() { return inventory; } public void setInventory(Inventory inventory) { this.inventory = inventory; } }
4,301
30.632353
150
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/jpa/Customer.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.jpa; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; /** * Customer is the bean mapping for the CUSTOMER table. * * @see Customer */ @Entity(name = "Customer") @Table(name = "CUSTOMER", schema = "APP") @NamedQueries({ @NamedQuery(name = "removeAllCustomers", query = "delete from Customer") }) public class Customer { @Id private String customerID; private String password; @NotNull @Size(min = 1, message = "First name must include at least one letter.") private String firstName; @NotNull @Size(min = 1, message = "Last name must include at least one letter.") private String lastName; @NotNull @Size(min = 1, message = "Address must include at least one letter.") private String addr1; private String addr2; @NotNull @Size(min = 1, message = "City name must include at least one letter.") private String addrCity; @NotNull @Size(min = 2, message = "State must include at least two letters.") private String addrState; @Pattern(regexp = "\\d{5}", message = "Zip code does not have 5 digits.") private String addrZip; @NotNull @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}", message = "Phone number does not match xxx-xxx-xxxx.") private String phone; public Customer() { } /** * Create a new Customer. * * @param key * CustomerKey * @param password * Password used for this customer account. * @param firstName * First name of the customer. * @param lastName * Last name of the customer * @param addr1 * Street address of the customer * @param addr2 * Street address of the customer * @param addrCity * City * @param addrState * State * @param addrZip * Zip code * @param phone * Phone number */ public Customer(String key, String password, String firstName, String lastName, String addr1, String addr2, String addrCity, String addrState, String addrZip, String phone) { this.setCustomerID(key); this.setPassword(password); this.setFirstName(firstName); this.setLastName(lastName); this.setAddr1(addr1); this.setAddr2(addr2); this.setAddrCity(addrCity); this.setAddrState(addrState); this.setAddrZip(addrZip); this.setPhone(phone); } /** * Verify password. * * @param password * value to be checked. * @return True, if password matches one stored. */ public boolean verifyPassword(String password) { return this.getPassword().equals(password); } /** * Get the customer's full name. * * @return String of customer's full name. */ public String getFullName() { return this.getFirstName() + " " + this.getLastName(); } public String getAddr1() { return addr1; } public void setAddr1(String addr1) { this.addr1 = addr1; } public String getAddr2() { return addr2; } public void setAddr2(String addr2) { this.addr2 = addr2; } public String getAddrCity() { return addrCity; } public void setAddrCity(String addrCity) { this.addrCity = addrCity; } public String getAddrState() { return addrState; } public void setAddrState(String addrState) { this.addrState = addrState; } public String getAddrZip() { return addrZip; } public void setAddrZip(String addrZip) { this.addrZip = addrZip; } public String getCustomerID() { return customerID; } public void setCustomerID(String customerID) { this.customerID = customerID; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
5,432
25.502439
108
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/jpa/Inventory.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.jpa; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.Version; import com.ibm.websphere.samples.pbw.utils.Util; /** * Inventory is the bean mapping for the INVENTORY table. It provides information about products the * store has for sale. * * @see Inventory */ @Entity(name = "Inventory") @Table(name = "INVENTORY", schema = "APP") @NamedQueries({ @NamedQuery(name = "getItemsByCategory", query = "select i from Inventory i where i.category = :category ORDER BY i.inventoryId"), @NamedQuery(name = "getItemsLikeName", query = "select i from Inventory i where i.name like :name"), @NamedQuery(name = "removeAllInventory", query = "delete from Inventory") }) public class Inventory implements Cloneable, java.io.Serializable { private static final long serialVersionUID = 1L; private static final int DEFAULT_MINTHRESHOLD = 50; private static final int DEFAULT_MAXTHRESHOLD = 200; @Id private String inventoryId; private String name; private String heading; private String description; private String pkginfo; private String image; private byte[] imgbytes; private float price; private float cost; private int quantity; private int category; private String notes; private boolean isPublic; private int minThreshold; private int maxThreshold; @Version private long version; @Transient private BackOrder backOrder; public Inventory() { } /** * Create a new Inventory. * * @param key * Inventory Key * @param name * Name of inventory item. * @param heading * Description heading of inventory item. * @param desc * Description of inventory item. * @param pkginfo * Package info of inventory item. * @param image * Image of inventory item. * @param price * Price of inventory item. * @param cost * Cost of inventory item. * @param quantity * Quantity of inventory items in stock. * @param category * Category of inventory item. * @param notes * Notes of inventory item. * @param isPublic * Access permission of inventory item. */ public Inventory(String key, String name, String heading, String desc, String pkginfo, String image, float price, float cost, int quantity, int category, String notes, boolean isPublic) { this.setInventoryId(key); Util.debug("creating new Inventory, inventoryId=" + this.getInventoryId()); this.setName(name); this.setHeading(heading); this.setDescription(desc); this.setPkginfo(pkginfo); this.setImage(image); this.setPrice(price); this.setCost(cost); this.setQuantity(quantity); this.setCategory(category); this.setNotes(notes); this.setIsPublic(isPublic); this.setMinThreshold(DEFAULT_MINTHRESHOLD); this.setMaxThreshold(DEFAULT_MAXTHRESHOLD); } /** * Create a new Inventory. * * @param item * Inventory to use to make a new inventory item. */ public Inventory(Inventory item) { this.setInventoryId(item.getInventoryId()); this.setName(item.getName()); this.setHeading(item.getHeading()); this.setDescription(item.getDescription()); this.setPkginfo(item.getPkginfo()); this.setImage(item.getImage()); this.setPrice(item.getPrice()); this.setCost(item.getCost()); this.setQuantity(item.getQuantity()); this.setCategory(item.getCategory()); this.setNotes(item.getNotes()); this.setMinThreshold(DEFAULT_MINTHRESHOLD); this.setMaxThreshold(DEFAULT_MAXTHRESHOLD); setIsPublic(item.isPublic()); // does not clone BackOrder info } /** * Increase the quantity of this inventory item. * * @param quantity * The number to increase the inventory by. */ public void increaseInventory(int quantity) { this.setQuantity(this.getQuantity() + quantity); } public int getCategory() { return category; } public void setCategory(int category) { this.category = category; } public float getCost() { return cost; } public void setCost(float cost) { this.cost = cost; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getHeading() { return heading; } public void setHeading(String heading) { this.heading = heading; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public String getPkginfo() { return pkginfo; } public void setPkginfo(String pkginfo) { this.pkginfo = pkginfo; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getMaxThreshold() { return maxThreshold; } public void setMaxThreshold(int maxThreshold) { this.maxThreshold = maxThreshold; } public int getMinThreshold() { return minThreshold; } public void setMinThreshold(int minThreshold) { this.minThreshold = minThreshold; } public String getInventoryId() { return inventoryId; } public void setInventoryId(String id) { inventoryId = id; } /** * Same as getInventoryId. Added for compatability with ShoppingCartItem when used by the Client * XJB sample * * @return String ID of the inventory item */ public String getID() { return inventoryId; } /** * Same as setInventoryId. Added for compatability with ShoppingCartItem when used by the Client * XJB sample * */ public void setID(String id) { inventoryId = id; } public boolean isPublic() { return isPublic; } public void setIsPublic(boolean isPublic) { this.isPublic = isPublic; } /** Set the inventory item's public availability. */ public void setPrivacy(boolean isPublic) { setIsPublic(isPublic); } public byte[] getImgbytes() { return imgbytes; } public void setImgbytes(byte[] imgbytes) { this.imgbytes = imgbytes; } public BackOrder getBackOrder() { return backOrder; } public void setBackOrder(BackOrder backOrder) { this.backOrder = backOrder; } @Override public String toString() { return getClass().getSimpleName() + "{id=" + inventoryId + "}"; } }
7,896
24.230032
132
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/jpa/Order.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.jpa; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Transient; import com.ibm.websphere.samples.pbw.utils.Util; /** * Bean mapping for the ORDER1 table. */ @Entity(name = "Order") @Table(name = "ORDER1", schema = "APP") @NamedQueries({ @NamedQuery(name = "removeAllOrders", query = "delete from Order") }) public class Order { public static final String ORDER_INFO_TABLE_NAME = "java:comp/env/jdbc/OrderInfoTableName"; public static final String ORDER_ITEMS_TABLE_NAME = "java:comp/env/jdbc/OrderItemsTableName"; @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "OrderSeq") @TableGenerator(name = "OrderSeq", table = "IDGENERATOR", pkColumnName = "IDNAME", pkColumnValue = "ORDER", valueColumnName = "IDVALUE") private String orderID; private String sellDate; private String billName; private String billAddr1; private String billAddr2; private String billCity; private String billState; private String billZip; private String billPhone; private String shipName; private String shipAddr1; private String shipAddr2; private String shipCity; private String shipState; private String shipZip; private String shipPhone; private String creditCard; private String ccNum; private String ccExpireMonth; private String ccExpireYear; private String cardHolder; private int shippingMethod; private float profit; @ManyToOne @JoinColumn(name = "CUSTOMERID") private Customer customer; @Transient private Collection orderItems; @Transient private Collection<OrderItem> items = null; /** * Constructor to create an Order. * * @param customer * - customer who created the order * @param billName * - billing name * @param billAddr1 * - billing address line 1 * @param billAddr2 * - billing address line 2 * @param billCity * - billing address city * @param billState * - billing address state * @param billZip * - billing address zip code * @param billPhone * - billing phone * @param shipName * - shippng name * @param shipAddr1 * - shippng address line 1 * @param shipAddr2 * - shippng address line 2 * @param shipCity * - shippng address city * @param shipState * - shippng address state * @param shipZip * - shippng address zip code * @param shipPhone * - shippng phone * @param creditCard * - credit card * @param ccNum * - credit card number * @param ccExpireMonth * - credit card expiration month * @param ccExpireYear * - credit card expiration year * @param cardHolder * - credit card holder name * @param shippingMethod * int of shipping method used * @param items * vector of StoreItems ordered */ public Order(Customer customer, String billName, String billAddr1, String billAddr2, String billCity, String billState, String billZip, String billPhone, String shipName, String shipAddr1, String shipAddr2, String shipCity, String shipState, String shipZip, String shipPhone, String creditCard, String ccNum, String ccExpireMonth, String ccExpireYear, String cardHolder, int shippingMethod, Collection<OrderItem> items) { this.setSellDate(Long.toString(System.currentTimeMillis())); // Pad it to 14 digits so sorting works properly. if (this.getSellDate().length() < 14) { StringBuffer sb = new StringBuffer(Util.ZERO_14); sb.replace((14 - this.getSellDate().length()), 14, this.getSellDate()); this.setSellDate(sb.toString()); } this.setCustomer(customer); this.setBillName(billName); this.setBillAddr1(billAddr1); this.setBillAddr2(billAddr2); this.setBillCity(billCity); this.setBillState(billState); this.setBillZip(billZip); this.setBillPhone(billPhone); this.setShipName(shipName); this.setShipAddr1(shipAddr1); this.setShipAddr2(shipAddr2); this.setShipCity(shipCity); this.setShipState(shipState); this.setShipZip(shipZip); this.setShipPhone(shipPhone); this.setCreditCard(creditCard); this.setCcNum(ccNum); this.setCcExpireMonth(ccExpireMonth); this.setCcExpireYear(ccExpireYear); this.setCardHolder(cardHolder); this.setShippingMethod(shippingMethod); this.items = items; // Get profit for total order. OrderItem oi; float profit; profit = 0.0f; for (Object o : items) { oi = (OrderItem) o; profit = profit + (oi.getQuantity() * (oi.getPrice() - oi.getCost())); oi.setOrder(this); } this.setProfit(profit); } public Order(String orderID) { setOrderID(orderID); } public Order() { } public String getBillAddr1() { return billAddr1; } public void setBillAddr1(String billAddr1) { this.billAddr1 = billAddr1; } public String getBillAddr2() { return billAddr2; } public void setBillAddr2(String billAddr2) { this.billAddr2 = billAddr2; } public String getBillCity() { return billCity; } public void setBillCity(String billCity) { this.billCity = billCity; } public String getBillName() { return billName; } public void setBillName(String billName) { this.billName = billName; } public String getBillPhone() { return billPhone; } public void setBillPhone(String billPhone) { this.billPhone = billPhone; } public String getBillState() { return billState; } public void setBillState(String billState) { this.billState = billState; } public String getBillZip() { return billZip; } public void setBillZip(String billZip) { this.billZip = billZip; } public String getCardHolder() { return cardHolder; } public void setCardHolder(String cardHolder) { this.cardHolder = cardHolder; } public String getCcExpireMonth() { return ccExpireMonth; } public void setCcExpireMonth(String ccExpireMonth) { this.ccExpireMonth = ccExpireMonth; } public String getCcExpireYear() { return ccExpireYear; } public void setCcExpireYear(String ccExpireYear) { this.ccExpireYear = ccExpireYear; } public String getCcNum() { return ccNum; } public void setCcNum(String ccNum) { this.ccNum = ccNum; } public String getCreditCard() { return creditCard; } public void setCreditCard(String creditCard) { this.creditCard = creditCard; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Collection<OrderItem> getItems() { return items; } public void setItems(Collection<OrderItem> items) { this.items = items; } public String getOrderID() { return orderID; } public void setOrderID(String orderID) { this.orderID = orderID; } public Collection getOrderItems() { return orderItems; } public void setOrderItems(Collection orderItems) { this.orderItems = orderItems; } public float getProfit() { return profit; } public void setProfit(float profit) { this.profit = profit; } public String getSellDate() { return sellDate; } public void setSellDate(String sellDate) { this.sellDate = sellDate; } public String getShipAddr1() { return shipAddr1; } public void setShipAddr1(String shipAddr1) { this.shipAddr1 = shipAddr1; } public String getShipAddr2() { return shipAddr2; } public void setShipAddr2(String shipAddr2) { this.shipAddr2 = shipAddr2; } public String getShipCity() { return shipCity; } public void setShipCity(String shipCity) { this.shipCity = shipCity; } public String getShipName() { return shipName; } public void setShipName(String shipName) { this.shipName = shipName; } public String getShipPhone() { return shipPhone; } public void setShipPhone(String shipPhone) { this.shipPhone = shipPhone; } public int getShippingMethod() { return shippingMethod; } public void setShippingMethod(int shippingMethod) { this.shippingMethod = shippingMethod; } public String getShipZip() { return shipZip; } public void setShipZip(String shipZip) { this.shipZip = shipZip; } public String getShipState() { return shipState; } public void setShipState(String shipState) { this.shipState = shipState; } }
9,827
23.944162
137
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/jpa/OrderItem.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.jpa; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Transient; import com.ibm.websphere.samples.pbw.utils.Util; /** * Bean mapping for the ORDERITEM table. */ @Entity(name = "OrderItem") @Table(name = "ORDERITEM", schema = "APP") @NamedQueries({ @NamedQuery(name = "removeAllOrderItem", query = "delete from OrderItem") }) public class OrderItem { /** * Composite Key class for Entity Bean: OrderItem * * Key consists of essentially two foreign key relations, but is mapped as foreign keys. */ @Embeddable public static class PK implements java.io.Serializable { static final long serialVersionUID = 3206093459760846163L; @Column(name = "inventoryID") public String inventoryID; @Column(name = "ORDER_ORDERID") public String order_orderID; public PK() { Util.debug("OrderItem.PK()"); } public PK(String inventoryID, String argOrder) { Util.debug("OrderItem.PK() inventoryID=" + inventoryID + "="); Util.debug("OrderItem.PK() orderID=" + argOrder + "="); this.inventoryID = inventoryID; this.order_orderID = argOrder; } /** * Returns true if both keys are equal. */ public boolean equals(java.lang.Object otherKey) { if (otherKey instanceof PK) { PK o = (PK) otherKey; return ((this.inventoryID.equals(o.inventoryID)) && (this.order_orderID.equals(o.order_orderID))); } return false; } /** * Returns the hash code for the key. */ public int hashCode() { Util.debug("OrderItem.PK.hashCode() inventoryID=" + inventoryID + "="); Util.debug("OrderItem.PK.hashCode() orderID=" + order_orderID + "="); return (inventoryID.hashCode() + order_orderID.hashCode()); } } @SuppressWarnings("unused") @EmbeddedId private OrderItem.PK id; private String name; private String pkginfo; private float price; private float cost; private int category; private int quantity; private String sellDate; @Transient private String inventoryId; @ManyToOne @JoinColumn(name = "INVENTORYID", insertable = false, updatable = false) private Inventory inventory; @ManyToOne @JoinColumn(name = "ORDER_ORDERID", insertable = false, updatable = false) private Order order; public int getCategory() { return category; } public void setCategory(int category) { this.category = category; } public float getCost() { return cost; } public void setCost(float cost) { this.cost = cost; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPkginfo() { return pkginfo; } public void setPkginfo(String pkginfo) { this.pkginfo = pkginfo; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getSellDate() { return sellDate; } public void setSellDate(String sellDate) { this.sellDate = sellDate; } public OrderItem() { } public OrderItem(Inventory inv) { Util.debug("OrderItem(inv) - id = " + inv.getInventoryId()); setInventoryId(inv.getInventoryId()); inventory = inv; name = inv.getName(); pkginfo = inv.getPkginfo(); price = inv.getPrice(); cost = inv.getCost(); category = inv.getCategory(); } public OrderItem(Order order, String orderID, Inventory inv, java.lang.String name, java.lang.String pkginfo, float price, float cost, int quantity, int category, java.lang.String sellDate) { Util.debug("OrderItem(etc.)"); inventory = inv; setInventoryId(inv.getInventoryId()); setName(name); setPkginfo(pkginfo); setPrice(price); setCost(cost); setQuantity(quantity); setCategory(category); setSellDate(sellDate); setOrder(order); id = new OrderItem.PK(inv.getInventoryId(), order.getOrderID()); } /* * updates the primary key field with the composite orderId+inventoryId */ public void updatePK() { id = new OrderItem.PK(inventoryId, order.getOrderID()); } public Inventory getInventory() { return inventory; } public void setInventory(Inventory inv) { this.inventory = inv; } public Order getOrder() { return order; } /** * Sets the order for this item Also updates the sellDate * * @param order */ public void setOrder(Order order) { this.order = order; this.sellDate = order.getSellDate(); } public String getInventoryId() { return inventoryId; } public void setInventoryId(String inventoryId) { this.inventoryId = inventoryId; } }
6,064
25.600877
110
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/jpa/OrderKey.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.jpa; import java.io.Serializable; /** * The key class of the Order entity bean. **/ public class OrderKey implements Serializable { private static final long serialVersionUID = 7912030586849592135L; public String orderID; /** * Constructs an OrderKey object. */ public OrderKey() { } /** * Constructs a newly allocated OrderKey object that represents the primitive long argument. */ public OrderKey(String orderID) { this.orderID = orderID; } /** * Determines if the OrderKey object passed to the method matches this OrderKey object. * * @param obj * java.lang.Object The OrderKey object to compare to this OrderKey object. * @return boolean The pass object is either equal to this OrderKey object (true) or not. */ public boolean equals(Object obj) { if (obj instanceof OrderKey) { OrderKey otherKey = (OrderKey) obj; return (((orderID.equals(otherKey.orderID)))); } else return false; } /** * Generates a hash code for this OrderKey object. * * @return int The hash code. */ public int hashCode() { return (orderID.hashCode()); } /** * Get accessor for persistent attribute: orderID */ public java.lang.String getOrderID() { return orderID; } /** * Set accessor for persistent attribute: orderID */ public void setOrderID(java.lang.String newOrderID) { orderID = newOrderID; } }
2,621
30.97561
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/jpa/Supplier.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2004,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.jpa; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * Bean mapping for the SUPPLIER table. */ @Entity(name = "Supplier") @Table(name = "SUPPLIER", schema = "APP") @NamedQueries({ @NamedQuery(name = "findAllSuppliers", query = "select s from Supplier s"), @NamedQuery(name = "removeAllSupplier", query = "delete from Supplier") }) public class Supplier { @Id private String supplierID; private String name; private String city; private String usstate; private String zip; private String phone; private String url; private String street; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getSupplierID() { return supplierID; } public void setSupplierID(String supplierID) { this.supplierID = supplierID; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsstate() { return usstate; } public void setUsstate(String usstate) { this.usstate = usstate; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public Supplier() { } public Supplier(String supplierID) { setSupplierID(supplierID); } /** * @param supplierID * @param name * @param street * @param city * @param state * @param zip * @param phone * @param url */ public Supplier(String supplierID, String name, String street, String city, String state, String zip, String phone, String url) { this.setSupplierID(supplierID); this.setName(name); this.setStreet(street); this.setCity(city); this.setUsstate(state); this.setZip(zip); this.setPhone(phone); this.setUrl(url); } }
3,399
24
116
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/utils/ListProperties.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2004,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Hashtable; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; /** * @author aamortim * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ /** * Utility class. */ public class ListProperties extends Properties { /** * */ private static final long serialVersionUID = 1L; private Hashtable<String, Vector<String>> listProps = null; /* Method load * @param inStream */ public void load(InputStream inStream) throws IOException { try { Util.debug("ListProperties.load - loading from stream "+inStream); // Parse property file, remove comments, blank lines, and combine // continued lines. String propFile = ""; BufferedReader inputLine = new BufferedReader(new InputStreamReader(inStream)); String line = inputLine.readLine(); boolean lineContinue = false; while (line != null) { Util.debug("ListProperties.load - Line read: " + line); line = line.trim(); String currLine = ""; if (line.startsWith("#")) { // Skipping comment } else if (line.startsWith("!")) { // Skipping comment } else if (line.equals("")) { // Skipping blank lines } else { if (!lineContinue) { currLine = line; } else { // This is a continuation line. Add to previous line. currLine += line; } // Must be a property line if (line.endsWith("\\")) { // Next line is continued from the current one. lineContinue = true; } else { // The current line is completed. Parse the property. propFile += currLine + "\n"; currLine = ""; lineContinue = false; } } line = inputLine.readLine(); } // Load Properties listProps = new Hashtable<String, Vector<String>>(); // Now parse the Properties to create an array String[] props = readTokens(propFile, "\n"); for (int index = 0; index < props.length; index++) { Util.debug("ListProperties.load() - props[" + index + "] = " + props[index]); // Parse the line to get the key,value pair String[] val = readTokens(props[index], "="); Util.debug("ListProperties.load() - val[0]: " + val[0] + " val[1]: " + val[1]); if (!val[0].equals("")) { if (this.containsKey(val[0])) { // Previous key,value was already created. // Need an array Vector<String> currList = (Vector<String>) listProps.get(val[0]); if ((currList == null) || currList.isEmpty()) { currList = new Vector<String>(); String prevVal = this.getProperty(val[0]); currList.addElement(prevVal); } currList.addElement(val[1]); listProps.put(val[0], currList); } this.setProperty(val[0], val[1]); } } } catch (Exception e) { Util.debug("ListProperties.load(): Exception: " + e); e.printStackTrace(); } } /** * Method readTokens. * @param text * @param token * @return list */ public String[] readTokens(String text, String token) { StringTokenizer parser = new StringTokenizer(text, token); int numTokens = parser.countTokens(); String[] list = new String[numTokens]; for (int i = 0; i < numTokens; i++) { list[i] = parser.nextToken(); } return list; } /** * Method getProperties. * @param name * @return values */ public String[] getProperties(String name) { String[] values = { "" }; try { String value = this.getProperty(name); Util.debug("ListProperties.getProperties: property (" + name + ") -> " + value); if (listProps.containsKey(name)) { Vector<String> list = (Vector<String>) listProps.get(name); values = new String[list.size()]; for (int index = 0; index < list.size(); index++) { values[index] = (String) list.elementAt(index); } } else { values[0] = value; } } catch (Exception e) { Util.debug("ListProperties.getProperties(): Exception: " + e); } return (values); } }
6,525
40.833333
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/utils/Util.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.utils; import java.io.FileNotFoundException; import java.text.NumberFormat; import java.util.StringTokenizer; import javax.faces.application.Application; import javax.faces.application.ProjectStage; import javax.faces.context.FacesContext; import javax.naming.InitialContext; import javax.naming.NamingException; /** * Utility class. */ public class Util { /** Datasource name. */ public static final String DS_NAME = "java:comp/env/jdbc/PlantsByWebSphereDataSource"; // Constants for JSPs and HTMLs. public static final String PAGE_ACCOUNT = "account.jsp"; public static final String PAGE_CART = "cart.jsp"; public static final String PAGE_CHECKOUTFINAL = "checkout_final.jsp"; public static final String PAGE_HELP = "help.jsp"; public static final String PAGE_LOGIN = "login.jsp"; public static final String PAGE_ORDERDONE = "orderdone.jsp"; public static final String PAGE_ORDERINFO = "orderinfo.jsp"; public static final String PAGE_PRODUCT = "product.jsp"; public static final String PAGE_PROMO = "promo.html"; public static final String PAGE_REGISTER = "register.jsp"; public static final String PAGE_SHOPPING = "shopping.jsp"; public static final String PAGE_BACKADMIN = "backorderadmin.jsp"; public static final String PAGE_SUPPLIERCFG = "supplierconfig.jsp"; public static final String PAGE_ADMINHOME = "admin.html"; public static final String PAGE_ADMINACTIONS = "adminactions.html"; // Request and session attributes. public static final String ATTR_ACTION = "action"; public static final String ATTR_CART = "ShoppingCart"; // public static final String ATTR_CART_CONTENTS = "CartContents"; public static final String ATTR_CARTITEMS = "cartitems"; public static final String ATTR_CATEGORY = "Category"; public static final String ATTR_CHECKOUT = "CheckingOut"; public static final String ATTR_CUSTOMER = "CustomerInfo"; public static final String ATTR_EDITACCOUNTINFO = "EditAccountInfo"; public static final String ATTR_INVITEM = "invitem"; public static final String ATTR_INVITEMS = "invitems"; public static final String ATTR_ORDERID = "OrderID"; public static final String ATTR_ORDERINFO = "OrderInfo"; public static final String ATTR_ORDERKEY = "OrderKey"; public static final String ATTR_RESULTS = "results"; public static final String ATTR_UPDATING = "updating"; public static final int ATTR_SFTIMEOUT = 10; // if this is changed, updated session timeout // in the PlantsByWebSphere web.xml public static final String ATTR_SUPPLIER = "SupplierInfo"; // Admin type actions public static final String ATTR_ADMINTYPE = "admintype"; public static final String ADMIN_BACKORDER = "backorder"; public static final String ADMIN_SUPPLIERCFG = "supplierconfig"; public static final String ADMIN_POPULATE = "populate"; // Servlet action codes. // Supplier Config actions public static final String ACTION_GETSUPPLIER = "getsupplier"; public static final String ACTION_UPDATESUPPLIER = "updatesupplier"; // Backorder actions public static final String ACTION_ORDERSTOCK = "orderstock"; public static final String ACTION_UPDATESTOCK = "updatestock"; public static final String ACTION_GETBACKORDERS = "getbackorders"; public static final String ACTION_UPDATEQUANTITY = "updatequantity"; public static final String ACTION_ORDERSTATUS = "orderstatus"; public static final String ACTION_CANCEL = "cancel"; public static final String STATUS_ORDERSTOCK = "Order Stock"; public static final String STATUS_ORDEREDSTOCK = "Ordered Stock"; public static final String STATUS_RECEIVEDSTOCK = "Received Stock"; public static final String STATUS_ADDEDSTOCK = "Added Stock"; public static final String DEFAULT_SUPPLIERID = "Supplier"; private static InitialContext initCtx = null; private static final String[] CATEGORY_STRINGS = { "Flowers", "Fruits & Vegetables", "Trees", "Accessories" }; private static final String[] SHIPPING_METHOD_STRINGS = { "Standard Ground", "Second Day Air", "Next Day Air" }; private static final String[] SHIPPING_METHOD_TIMES = { "( 3 to 6 business days )", "( 2 to 3 business days )", "( 1 to 2 business days )" }; private static final float[] SHIPPING_METHOD_PRICES = { 4.99f, 8.99f, 12.99f }; public static final String ZERO_14 = "00000000000000"; /** * Return the cached Initial Context. * * @return InitialContext, or null if a naming exception. */ static public InitialContext getInitialContext() { try { // Get InitialContext if it has not been gotten yet. if (initCtx == null) { // properties are in the system properties initCtx = new InitialContext(); } } // Naming Exception will cause a null return. catch (NamingException e) {} return initCtx; } /** * Get the displayable name of a category. * @param index The int representation of a category. * @return The category as a String (null, if an invalid index given). */ static public String getCategoryString(int index) { if ((index >= 0) && (index < CATEGORY_STRINGS.length)) return CATEGORY_STRINGS[index]; else return null; } /** * Get the category strings in an array. * * @return The category strings in an array. */ static public String[] getCategoryStrings() { return CATEGORY_STRINGS; } /** * Get the shipping method. * @param index The int representation of a shipping method. * @return The shipping method (null, if an invalid index given). */ static public String getShippingMethod(int index) { if ((index >= 0) && (index < SHIPPING_METHOD_STRINGS.length)) return SHIPPING_METHOD_STRINGS[index]; else return null; } /** * Get the shipping method price. * @param index The int representation of a shipping method. * @return The shipping method price (-1, if an invalid index given). */ static public float getShippingMethodPrice(int index) { if ((index >= 0) && (index < SHIPPING_METHOD_PRICES.length)) return SHIPPING_METHOD_PRICES[index]; else return -1; } /** * Get the shipping method price. * @param index The int representation of a shipping method. * @return The shipping method time (null, if an invalid index given). */ static public String getShippingMethodTime(int index) { if ((index >= 0) && (index < SHIPPING_METHOD_TIMES.length)) return SHIPPING_METHOD_TIMES[index]; else return null; } /** * Get the shipping method strings in an array. * @return The shipping method strings in an array. */ static public String[] getShippingMethodStrings() { return SHIPPING_METHOD_STRINGS; } /** * Get the shipping method strings, including prices and times, in an array. * @return The shipping method strings, including prices and times, in an array. */ static public String[] getFullShippingMethodStrings() { String[] shippingMethods = new String[SHIPPING_METHOD_STRINGS.length]; for (int i = 0; i < shippingMethods.length; i++) { shippingMethods[i] = SHIPPING_METHOD_STRINGS[i] + " " + SHIPPING_METHOD_TIMES[i] + " " + NumberFormat.getCurrencyInstance(java.util.Locale.US).format(new Float(SHIPPING_METHOD_PRICES[i])); } return shippingMethods; } private static final String PBW_PROPERTIES = "pbw.properties"; private static ListProperties PBW_Properties = null; /** * Method readProperties. */ public static void readProperties() throws FileNotFoundException { if (PBW_Properties == null) { // Try to read the properties file. ListProperties prop = new ListProperties(); try { String PBW_Properties_File = PBW_PROPERTIES; debug("Util.readProperties(): Loading PBW Properties from file: " + PBW_Properties_File); prop.load(Util.class.getClassLoader().getResourceAsStream(PBW_Properties_File)); } catch (Exception e) { debug("Util.readProperties(): Exception: " + e); // Reset properties to retry loading next time. PBW_Properties = null; e.printStackTrace(); throw new FileNotFoundException(); } PBW_Properties = prop; } } /** * Method getProperty. * @param name * @return value */ public static String getProperty(String name) { String value = ""; try { if (PBW_Properties == null) { readProperties(); } value = PBW_Properties.getProperty(name); } catch (Exception e) { debug("Util.getProperty(): Exception: " + e); } return (value); } /** * Method readTokens. * @param text * @param token * @return list */ public static String[] readTokens(String text, String token) { StringTokenizer parser = new StringTokenizer(text, token); int numTokens = parser.countTokens(); String[] list = new String[numTokens]; for (int i = 0; i < numTokens; i++) { list[i] = parser.nextToken(); } return list; } /** * Method getProperties. * @param name * @return values */ public static String[] getProperties(String name) { String[] values = { "" }; try { if (PBW_Properties == null) { readProperties(); } values = PBW_Properties.getProperties(name); debug("Util.getProperties: property (" + name + ") -> " + values.toString()); //for (Enumeration e = PBW_Properties.propertyNames() ; e.hasMoreElements() ;) { // debug((String)e.nextElement()); //} } catch (Exception e) { debug("Util.getProperties(): Exception: " + e); } return (values); } static private boolean debug = false; /** Set debug setting to on or off. * @param val True or false. */ static final public void setDebug(boolean val) { debug = val; } /** Is debug turned on? */ static final public boolean debugOn() { return debug; } /** * Output RAS message. * @param msg Message to be output. */ static final public void debug(String msg) { FacesContext context = FacesContext.getCurrentInstance(); if (context != null) { Application app = context.getApplication(); if (app != null) { ProjectStage stage = app.getProjectStage(); if (stage == ProjectStage.Development || stage == ProjectStage.UnitTest) { setDebug(true); } } if (debug) { System.out.println(msg); } } } /** * Utilty functions for validating user input. * validateString will return false if any of the invalid characters appear in the input string. * * In general, we do not want to allow special characters in user input, * because this can open us to a XSS security vulnerability. * For example, a user should not be allowed to enter javascript in an input field. */ static final char[] invalidCharList={'|','&',';','$','%','\'','\"','\\','<','>',','}; public static boolean validateString(String input){ if (input==null) return true; for (int i=0;i<invalidCharList.length;i++){ if (input.indexOf(invalidCharList[i])!=-1){ return false; } } return true; } }
13,190
41.278846
200
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/AccountBean.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.faces.application.Application; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import com.ibm.websphere.samples.pbw.bean.CustomerMgr; import com.ibm.websphere.samples.pbw.bean.MailerAppException; import com.ibm.websphere.samples.pbw.bean.MailerBean; import com.ibm.websphere.samples.pbw.bean.ShoppingCartBean; import com.ibm.websphere.samples.pbw.jpa.Customer; import com.ibm.websphere.samples.pbw.utils.Util; /** * Provides a combination of JSF action and backing bean support for the account web page. * */ @Named(value = "account") @SessionScoped public class AccountBean implements Serializable { private static final long serialVersionUID = 1L; private static final String ACTION_ACCOUNT = "account"; private static final String ACTION_CHECKOUT_FINAL = "checkout_final"; private static final String ACTION_LOGIN = "login"; private static final String ACTION_ORDERDONE = "orderdone"; private static final String ACTION_ORDERINFO = "orderinfo"; private static final String ACTION_PROMO = "promo"; private static final String ACTION_REGISTER = "register"; @Inject private CustomerMgr login; @Inject private MailerBean mailer; @Inject private ShoppingCartBean shoppingCart; private boolean checkingOut; private Customer customer; private String lastOrderNum; private LoginInfo loginInfo; private Customer newCustomer; private OrderInfo orderInfo; private int orderNum = 1; private boolean register; private boolean updating; public String performAccount() { if (customer == null || loginInfo == null) { checkingOut = false; loginInfo = new LoginInfo(); register = false; updating = true; loginInfo.setMessage("You must log in first."); return AccountBean.ACTION_LOGIN; } else { return AccountBean.ACTION_ACCOUNT; } } public String performAccountUpdate() { if (register) { customer = login.createCustomer(loginInfo.getEmail(), loginInfo.getPassword(), newCustomer .getFirstName(), newCustomer.getLastName(), newCustomer.getAddr1(), newCustomer .getAddr2(), newCustomer.getAddrCity(), newCustomer .getAddrState(), newCustomer.getAddrZip(), newCustomer.getPhone()); register = false; } else { customer = login.updateUser(customer.getCustomerID(), customer.getFirstName(), customer .getLastName(), customer.getAddr1(), customer.getAddr2(), customer .getAddrCity(), customer.getAddrState(), customer.getAddrZip(), customer.getPhone()); } return AccountBean.ACTION_PROMO; } public String performCheckoutFinal() { FacesContext context = FacesContext.getCurrentInstance(); Application app = context.getApplication(); ShoppingBean shopping = (ShoppingBean) app.createValueBinding("#{shopping}").getValue(context); shopping.setShippingCost(Util.getShippingMethodPrice(orderInfo.getShippingMethod())); return AccountBean.ACTION_CHECKOUT_FINAL; } public String performCompleteCheckout() { FacesContext context = FacesContext.getCurrentInstance(); Application app = context.getApplication(); app.createValueBinding("#{shopping}").getValue(context); // persist the order OrderInfo oi = new OrderInfo(shoppingCart .createOrder(customer.getCustomerID(), orderInfo.getBillName(), orderInfo.getBillAddr1(), orderInfo .getBillAddr2(), orderInfo.getBillCity(), orderInfo.getBillState(), orderInfo .getBillZip(), orderInfo.getBillPhone(), orderInfo.getShipName(), orderInfo .getShipAddr1(), orderInfo.getShipAddr2(), orderInfo.getShipCity(), orderInfo .getShipState(), orderInfo.getShipZip(), orderInfo .getShipPhone(), orderInfo.getCardName(), orderInfo .getCardNum(), orderInfo.getCardExpMonth(), orderInfo .getCardExpYear(), orderInfo .getCardholderName(), orderInfo .getShippingMethod(), shoppingCart .getItems())); lastOrderNum = oi.getID(); Util.debug("Account.performCompleteCheckout: order id =" + orderInfo); /* * // Check the available inventory and backorder if necessary. if (shoppingCart != null) { * Inventory si; Collection<Inventory> items = shoppingCart.getItems(); for (Object o : * items) { si = (Inventory) o; shoppingCart.checkInventory(si); Util.debug( * "ShoppingCart.checkInventory() - checking Inventory quantity of item: " + si.getID()); } * } */ try { mailer.createAndSendMail(customer, oi.getID()); } catch (MailerAppException e) { System.out.println("MailerAppException:" + e); e.printStackTrace(); } catch (Exception e) { System.out.println("Exception during create and send mail :" + e); e.printStackTrace(); } orderInfo = null; // shoppingCart.setCartContents (new ShoppingCartContents()); shoppingCart.removeAllItems(); return AccountBean.ACTION_ORDERDONE; } public String performLogin() { checkingOut = false; loginInfo = new LoginInfo(); register = false; updating = false; loginInfo.setMessage(""); return AccountBean.ACTION_LOGIN; } public String performLoginComplete() { String message; // Attempt to log in the user. message = login.verifyUserAndPassword(loginInfo.getEmail(), loginInfo.getPassword()); if (message != null) { // Error, so go back to the login page. loginInfo.setMessage(message); return AccountBean.ACTION_LOGIN; } // Otherwise, no error, so continue to the correct page. customer = login.getCustomer(loginInfo.getEmail()); if (isCheckingOut()) { return performOrderInfo(); } if (isUpdating()) { return performAccount(); } return AccountBean.ACTION_PROMO; } public String performOrderInfo() { if (customer == null) { checkingOut = true; loginInfo = new LoginInfo(); register = false; updating = false; loginInfo.setMessage("You must log in first."); return AccountBean.ACTION_LOGIN; } else { if (orderInfo == null) { orderInfo = new OrderInfo(customer.getFirstName() + " " + customer.getLastName(), customer.getAddr1(), customer.getAddr2(), customer.getAddrCity(), customer.getAddrState(), customer.getAddrZip(), customer.getPhone(), "", "", "", "", "", "", "", 0, "" + (orderNum++)); } return AccountBean.ACTION_ORDERINFO; } } public String performRegister() { loginInfo = new LoginInfo(); newCustomer = new Customer("", "", "", "", "", "", "", "", "", ""); register = true; updating = false; return AccountBean.ACTION_REGISTER; } public Customer getCustomer() { return (isRegister() ? newCustomer : customer); } public String getLastOrderNum() { return lastOrderNum; } public LoginInfo getLoginInfo() { return loginInfo; } public OrderInfo getOrderInfo() { return orderInfo; } public boolean isCheckingOut() { return checkingOut; } public boolean isRegister() { return register; } public boolean isUpdating() { return updating; } }
8,293
30.777778
106
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/AccountServlet.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.io.IOException; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.pbw.bean.CatalogMgr; import com.ibm.websphere.samples.pbw.bean.CustomerMgr; import com.ibm.websphere.samples.pbw.jpa.Customer; import com.ibm.websphere.samples.pbw.utils.Util; /** * Servlet to handle customer account actions, such as login and register. */ @Named(value = "accountservlet") @WebServlet("/servlet/AccountServlet") public class AccountServlet extends HttpServlet { private static final long serialVersionUID = 1L; // Servlet action codes. public static final String ACTION_ACCOUNT = "account"; public static final String ACTION_ACCOUNTUPDATE = "accountUpdate"; public static final String ACTION_LOGIN = "login"; public static final String ACTION_REGISTER = "register"; public static final String ACTION_SETLOGGING = "SetLogging"; @Inject private CustomerMgr login; @Inject private CatalogMgr catalog; /** * Servlet initialization. */ public void init(ServletConfig config) throws ServletException { super.init(config); } /** * Process incoming HTTP GET requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Process incoming HTTP POST requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Main service method for AccountServlet * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ private void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = null; action = req.getParameter(Util.ATTR_ACTION); Util.debug("action=" + action); if (action.equals(ACTION_LOGIN)) { try { HttpSession session = req.getSession(true); String userid = req.getParameter("userid"); String passwd = req.getParameter("passwd"); String updating = req.getParameter(Util.ATTR_UPDATING); String results = null; if (Util.validateString(userid)) { results = login.verifyUserAndPassword(userid, passwd); } else { // user id was invalid, and may contain XSS attack results = "\nEmail address was invalid."; Util.debug("User id or email address was invalid. id=" + userid); } // If results have an error msg, return it, otherwise continue. if (results != null) { // Proliferate UPDATING flag if user is trying to update his account. if (updating.equals("true")) req.setAttribute(Util.ATTR_UPDATING, "true"); req.setAttribute(Util.ATTR_RESULTS, results); requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_LOGIN); } else { // If not logging in for the first time, then clear out the // session data for the old user. if (session.getAttribute(Util.ATTR_CUSTOMER) != null) { session.removeAttribute(Util.ATTR_CART); // session.removeAttribute(Util.ATTR_CART_CONTENTS); session.removeAttribute(Util.ATTR_CHECKOUT); session.removeAttribute(Util.ATTR_ORDERKEY); } // Store customer userid in HttpSession. Customer customer = login.getCustomer(userid); session.setAttribute(Util.ATTR_CUSTOMER, customer); Util.debug("updating=" + updating + "="); // Was customer trying to edit account information. if (updating.equals("true")) { req.setAttribute(Util.ATTR_EDITACCOUNTINFO, customer); requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ACCOUNT); } else { // See if user was in the middle of checking out. Boolean checkingOut = (Boolean) session.getAttribute(Util.ATTR_CHECKOUT); Util.debug("checkingOut=" + checkingOut + "="); if ((checkingOut != null) && (checkingOut.booleanValue())) { Util.debug("must be checking out"); requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ORDERINFO); } else { Util.debug("must NOT be checking out"); String url; String category = (String) session.getAttribute(Util.ATTR_CATEGORY); // Default to plants if ((category == null) || (category.equals("null"))) { url = Util.PAGE_PROMO; } else { url = Util.PAGE_SHOPPING; req.setAttribute(Util.ATTR_INVITEMS, catalog .getItemsByCategory(Integer.parseInt(category))); } requestDispatch(getServletConfig().getServletContext(), req, resp, url); } } } } catch (ServletException e) { req.setAttribute(Util.ATTR_RESULTS, "/nException occurred"); throw e; } catch (Exception e) { req.setAttribute(Util.ATTR_RESULTS, "/nException occurred"); throw new ServletException(e.getMessage()); } } else if (action.equals(ACTION_REGISTER)) { // Register a new user. // try // { String url; HttpSession session = req.getSession(true); String userid = req.getParameter("userid"); String password = req.getParameter("passwd"); String cpassword = req.getParameter("vpasswd"); String firstName = req.getParameter("fname"); String lastName = req.getParameter("lname"); String addr1 = req.getParameter("addr1"); String addr2 = req.getParameter("addr2"); String addrCity = req.getParameter("city"); String addrState = req.getParameter("state"); String addrZip = req.getParameter("zip"); String phone = req.getParameter("phone"); // validate all user input if (!Util.validateString(userid)) { req.setAttribute(Util.ATTR_RESULTS, "Email address contains invalid characters."); url = Util.PAGE_REGISTER; } else if (!Util.validateString(firstName)) { req.setAttribute(Util.ATTR_RESULTS, "First Name contains invalid characters."); url = Util.PAGE_REGISTER; } else if (!Util.validateString(lastName)) { req.setAttribute(Util.ATTR_RESULTS, "Last Name contains invalid characters."); url = Util.PAGE_REGISTER; } else if (!Util.validateString(addr1)) { req.setAttribute(Util.ATTR_RESULTS, "Address Line 1 contains invalid characters."); url = Util.PAGE_REGISTER; } else if (!Util.validateString(addr2)) { req.setAttribute(Util.ATTR_RESULTS, "Address Line 2 contains invalid characters."); url = Util.PAGE_REGISTER; } else if (!Util.validateString(addrCity)) { req.setAttribute(Util.ATTR_RESULTS, "City contains invalid characters."); url = Util.PAGE_REGISTER; } else if (!Util.validateString(addrState)) { req.setAttribute(Util.ATTR_RESULTS, "State contains invalid characters."); url = Util.PAGE_REGISTER; } else if (!Util.validateString(addrZip)) { req.setAttribute(Util.ATTR_RESULTS, "Zip contains invalid characters."); url = Util.PAGE_REGISTER; } else if (!Util.validateString(phone)) { req.setAttribute(Util.ATTR_RESULTS, "Phone Number contains invalid characters."); url = Util.PAGE_REGISTER; } // Make sure passwords match. else if (!password.equals(cpassword)) { req.setAttribute(Util.ATTR_RESULTS, "Passwords do not match."); url = Util.PAGE_REGISTER; } else { // Create the new user. Customer customer = login .createCustomer(userid, password, firstName, lastName, addr1, addr2, addrCity, addrState, addrZip, phone); if (customer != null) { // Store customer info in HttpSession. session.setAttribute(Util.ATTR_CUSTOMER, customer); // See if user was in the middle of checking out. Boolean checkingOut = (Boolean) session.getAttribute(Util.ATTR_CHECKOUT); if ((checkingOut != null) && (checkingOut.booleanValue())) { url = Util.PAGE_ORDERINFO; } else { String category = (String) session.getAttribute(Util.ATTR_CATEGORY); // Default to plants if (category == null) { url = Util.PAGE_PROMO; } else { url = Util.PAGE_SHOPPING; req.setAttribute(Util.ATTR_INVITEMS, catalog .getItemsByCategory(Integer.parseInt(category))); } } } else { url = Util.PAGE_REGISTER; req.setAttribute(Util.ATTR_RESULTS, "New user NOT created!"); } } requestDispatch(getServletConfig().getServletContext(), req, resp, url); // } // catch (CreateException e) { } } else if (action.equals(ACTION_ACCOUNT)) { String url; HttpSession session = req.getSession(true); Customer customer = (Customer) session.getAttribute(Util.ATTR_CUSTOMER); if (customer == null) { url = Util.PAGE_LOGIN; req.setAttribute(Util.ATTR_UPDATING, "true"); req.setAttribute(Util.ATTR_RESULTS, "\nYou must login first."); } else { url = Util.PAGE_ACCOUNT; req.setAttribute(Util.ATTR_EDITACCOUNTINFO, customer); } requestDispatch(getServletConfig().getServletContext(), req, resp, url); } else if (action.equals(ACTION_ACCOUNTUPDATE)) { // try // { String url; HttpSession session = req.getSession(true); Customer customer = (Customer) session.getAttribute(Util.ATTR_CUSTOMER); String userid = customer.getCustomerID(); String firstName = req.getParameter("fname"); String lastName = req.getParameter("lname"); String addr1 = req.getParameter("addr1"); String addr2 = req.getParameter("addr2"); String addrCity = req.getParameter("city"); String addrState = req.getParameter("state"); String addrZip = req.getParameter("zip"); String phone = req.getParameter("phone"); // Create the new user. customer = login.updateUser(userid, firstName, lastName, addr1, addr2, addrCity, addrState, addrZip, phone); // Store updated customer info in HttpSession. session.setAttribute(Util.ATTR_CUSTOMER, customer); // See if user was in the middle of checking out. Boolean checkingOut = (Boolean) session.getAttribute(Util.ATTR_CHECKOUT); if ((checkingOut != null) && (checkingOut.booleanValue())) { url = Util.PAGE_ORDERINFO; } else { String category = (String) session.getAttribute(Util.ATTR_CATEGORY); // Default to plants if (category == null) { url = Util.PAGE_PROMO; } else { url = Util.PAGE_SHOPPING; req.setAttribute(Util.ATTR_INVITEMS, catalog.getItemsByCategory(Integer.parseInt(category))); } } requestDispatch(getServletConfig().getServletContext(), req, resp, url); // } // catch (CreateException e) { } } else if (action.equals(ACTION_SETLOGGING)) { String debugSetting = req.getParameter("logging"); if ((debugSetting == null) || (!debugSetting.equals("debug"))) Util.setDebug(false); else Util.setDebug(true); requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_HELP); } } /** * Request dispatch. */ private void requestDispatch(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String page) throws ServletException, IOException { resp.setContentType("text/html"); ctx.getRequestDispatcher(page).include(req, resp); } }
13,135
37.749263
114
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/AdminServlet.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.pbw.bean.BackOrderMgr; import com.ibm.websphere.samples.pbw.bean.CatalogMgr; import com.ibm.websphere.samples.pbw.bean.CustomerMgr; import com.ibm.websphere.samples.pbw.bean.ResetDBBean; import com.ibm.websphere.samples.pbw.bean.SuppliersBean; import com.ibm.websphere.samples.pbw.jpa.BackOrder; import com.ibm.websphere.samples.pbw.jpa.Inventory; import com.ibm.websphere.samples.pbw.jpa.Supplier; import com.ibm.websphere.samples.pbw.utils.Util; /** * Servlet to handle Administration actions */ @Named(value = "admin") @WebServlet("/servlet/AdminServlet") public class AdminServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Inject private SuppliersBean suppliers = null; @Inject private CustomerMgr login; @Inject private BackOrderMgr backOrderStock = null; @Inject private CatalogMgr catalog = null; @Inject private ResetDBBean resetDB; /** * @see javax.servlet.Servlet#init(ServletConfig) */ /** * Servlet initialization. */ public void init(ServletConfig config) throws ServletException { super.init(config); // Uncomment the following to generated debug code. // Util.setDebug(true); } /** * Process incoming HTTP GET requests * * @param req * Object that encapsulates the request to the servlet * @param resp * Object that encapsulates the response from the servlet */ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { performTask(req, resp); } /** * Process incoming HTTP POST requests * * @param req * Object that encapsulates the request to the servlet * @param resp * Object that encapsulates the response from the servlet */ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { performTask(req, resp); } /** * Method performTask. * * @param req * @param resp * @throws ServletException * @throws IOException */ public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String admintype = null; admintype = req.getParameter(Util.ATTR_ADMINTYPE); Util.debug("inside AdminServlet:performTask. admintype=" + admintype); if ((admintype == null) || (admintype.equals(""))) { // Invalid Admin requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ADMINHOME); } if (admintype.equals(Util.ADMIN_BACKORDER)) { performBackOrder(req, resp); } else if (admintype.equals(Util.ADMIN_SUPPLIERCFG)) { performSupplierConfig(req, resp); } else if (admintype.equals(Util.ADMIN_POPULATE)) { performPopulate(req, resp); } } /** * @param supplierID * @param name * @param street * @param city * @param state * @param zip * @param phone * @param location_url * @return supplierInfo */ public Supplier updateSupplierInfo(String supplierID, String name, String street, String city, String state, String zip, String phone, String location_url) { // Only retrieving info for 1 supplier. Supplier supplier = null; try { supplier = suppliers.updateSupplier(supplierID, name, street, city, state, zip, phone, location_url); } catch (Exception e) { Util.debug("AdminServlet.updateSupplierInfo() - Exception: " + e); } return (supplier); } /** * @param req * @param resp * @throws ServletException * @throws IOException */ public void performSupplierConfig(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Supplier supplier = null; String action = null; action = req.getParameter(Util.ATTR_ACTION); if ((action == null) || (action.equals(""))) action = Util.ACTION_GETSUPPLIER; Util.debug("AdminServlet.performSupplierConfig() - action=" + action); HttpSession session = req.getSession(true); if (action.equals(Util.ACTION_GETSUPPLIER)) { // Get supplier info try { supplier = suppliers.getSupplier(); } catch (Exception e) { Util.debug("AdminServlet.performSupplierConfig() Exception: " + e); } } else if (action.equals(Util.ACTION_UPDATESUPPLIER)) { String supplierID = req.getParameter("supplierid"); Util.debug("AdminServlet.performSupplierConfig() - supplierid = " + supplierID); if ((supplierID != null) && (!supplierID.equals(""))) { String name = req.getParameter("name"); String street = req.getParameter("street"); String city = req.getParameter("city"); String state = req.getParameter("state"); String zip = req.getParameter("zip"); String phone = req.getParameter("phone"); String location_url = req.getParameter("location_url"); supplier = updateSupplierInfo(supplierID, name, street, city, state, zip, phone, location_url); } } else { // Unknown Supplier Config Admin Action so go back to the // Administration home page sendRedirect(resp, "/PlantsByWebSphere/" + Util.PAGE_ADMINHOME); } session.setAttribute(Util.ATTR_SUPPLIER, supplier); requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_SUPPLIERCFG); } /** * @param req * @param resp * @throws ServletException * @throws IOException */ public void performPopulate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Populate popDB = new Populate(resetDB, catalog, login, backOrderStock, suppliers); popDB.doPopulate(); sendRedirect(resp, "/PlantsByWebSphere/" + Util.PAGE_HELP); } /** * Method performBackOrder. * * @param req * @param resp * @throws ServletException * @throws IOException */ public void performBackOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = null; action = req.getParameter(Util.ATTR_ACTION); if ((action == null) || (action.equals(""))) action = Util.ACTION_GETBACKORDERS; Util.debug("AdminServlet.performBackOrder() - action=" + action); HttpSession session = req.getSession(true); if (action.equals(Util.ACTION_GETBACKORDERS)) { getBackOrders(session); requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_BACKADMIN); } else if (action.equals(Util.ACTION_UPDATESTOCK)) { Util.debug("AdminServlet.performBackOrder() - AdminServlet(performTask): Update Stock Action"); String[] backOrderIDs = (String[]) req.getParameterValues("selectedObjectIds"); if (backOrderIDs != null) { for (int i = 0; i < backOrderIDs.length; i++) { String backOrderID = backOrderIDs[i]; Util.debug("AdminServlet.performBackOrder() - Selected BackOrder backOrderID: " + backOrderID); try { String inventoryID = backOrderStock.getBackOrderInventoryID(backOrderID); Util.debug("AdminServlet.performBackOrder() - backOrderID = " + inventoryID); int quantity = backOrderStock.getBackOrderQuantity(backOrderID); catalog.setItemQuantity(inventoryID, quantity); // Update the BackOrder status Util.debug("AdminServlet.performBackOrder() - quantity: " + quantity); backOrderStock.updateStock(backOrderID, quantity); } catch (Exception e) { Util.debug("AdminServlet.performBackOrder() - Exception: " + e); e.printStackTrace(); } } } getBackOrders(session); requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_BACKADMIN); } else if (action.equals(Util.ACTION_CANCEL)) { Util.debug("AdminServlet.performBackOrder() - AdminServlet(performTask): Cancel Action"); String[] backOrderIDs = (String[]) req.getParameterValues("selectedObjectIds"); if (backOrderIDs != null) { for (int i = 0; i < backOrderIDs.length; i++) { String backOrderID = backOrderIDs[i]; Util.debug("AdminServlet.performBackOrder() - Selected BackOrder backOrderID: " + backOrderID); try { backOrderStock.deleteBackOrder(backOrderID); } catch (Exception e) { Util.debug("AdminServlet.performBackOrder() - Exception: " + e); e.printStackTrace(); } } } getBackOrders(session); requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_BACKADMIN); } else if (action.equals(Util.ACTION_UPDATEQUANTITY)) { Util.debug("AdminServlet.performBackOrder() - Update Quantity Action"); try { String backOrderID = req.getParameter("backOrderID"); if (backOrderID != null) { Util.debug("AdminServlet.performBackOrder() - backOrderID = " + backOrderID); String paramquantity = req.getParameter("itemqty"); if (paramquantity != null) { int quantity = new Integer(paramquantity).intValue(); Util.debug("AdminServlet.performBackOrder() - quantity: " + quantity); backOrderStock.setBackOrderQuantity(backOrderID, quantity); } } } catch (Exception e) { Util.debug("AdminServlet.performBackOrder() - Exception: " + e); e.printStackTrace(); } getBackOrders(session); requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_BACKADMIN); } else { // Unknown Backup Admin Action so go back to the Administration home // page sendRedirect(resp, "/PlantsByWebSphere/" + Util.PAGE_ADMINHOME); } } /** * Method getBackOrders. * * @param session */ public void getBackOrders(HttpSession session) { try { // Get the list of back order items. Util.debug("AdminServlet.getBackOrders() - Looking for BackOrders"); Collection<BackOrder> backOrders = backOrderStock.findBackOrders(); ArrayList<BackOrderItem> backOrderItems = new ArrayList<BackOrderItem>(); for (BackOrder bo : backOrders) { BackOrderItem boi = new BackOrderItem(bo); backOrderItems.add(boi); } Util.debug("AdminServlet.getBackOrders() - BackOrders found!"); Iterator<BackOrderItem> i = backOrderItems.iterator(); while (i.hasNext()) { BackOrderItem backOrderItem = (BackOrderItem) i.next(); String backOrderID = backOrderItem.getBackOrderID(); String inventoryID = backOrderItem.getInventory().getInventoryId(); // Get the inventory quantity and name for the back order item // information. Inventory item = catalog.getItemInventory(inventoryID); int quantity = item.getQuantity(); backOrderItem.setInventoryQuantity(quantity); String name = item.getName(); backOrderItem.setName(name); // Don't include backorders that have been completed. if (!(backOrderItem.getStatus().equals(Util.STATUS_ADDEDSTOCK))) { String invID = backOrderItem.getInventory().getInventoryId(); String supplierOrderID = backOrderItem.getSupplierOrderID(); String status = backOrderItem.getStatus(); String lowDate = new Long(backOrderItem.getLowDate()).toString(); String orderDate = new Long(backOrderItem.getOrderDate()).toString(); Util.debug("AdminServlet.getBackOrders() - backOrderID = " + backOrderID); Util.debug("AdminServlet.getBackOrders() - supplierOrderID = " + supplierOrderID); Util.debug("AdminServlet.getBackOrders() - invID = " + invID); Util.debug("AdminServlet.getBackOrders() - name = " + name); Util.debug("AdminServlet.getBackOrders() - quantity = " + quantity); Util.debug("AdminServlet.getBackOrders() - status = " + status); Util.debug("AdminServlet.getBackOrders() - lowDate = " + lowDate); Util.debug("AdminServlet.getBackOrders() - orderDate = " + orderDate); } } session.setAttribute("backorderitems", backOrderItems); } catch (Exception e) { e.printStackTrace(); Util.debug("AdminServlet.getBackOrders() - RemoteException: " + e); } } /** * Method sendRedirect. * * @param resp * @param page * @throws ServletException * @throws IOException */ private void sendRedirect(HttpServletResponse resp, String page) throws ServletException, IOException { resp.sendRedirect(resp.encodeRedirectURL(page)); } /** * Method requestDispatch. * * @param ctx * @param req * @param resp * @param page * @throws ServletException * @throws IOException */ /** * Request dispatch */ private void requestDispatch(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String page) throws ServletException, IOException { resp.setContentType("text/html"); ctx.getRequestDispatcher(page).forward(req, resp); } }
14,157
35.774026
117
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/BackOrderItem.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import com.ibm.websphere.samples.pbw.jpa.BackOrder; import com.ibm.websphere.samples.pbw.jpa.Inventory; import com.ibm.websphere.samples.pbw.utils.Util; /** * A class to hold a back order item's data. */ public class BackOrderItem implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; private String name; private int inventoryQuantity; private String backOrderID; // from BackOrder private int quantity; // from BackOrder private String status; // from BackOrder private long lowDate; // from BackOrder private long orderDate; // from BackOrder private String supplierOrderID; // from BackOrder private Inventory inventory; // from BackOrder /** * @see java.lang.Object#Object() */ /** Default constructor. */ public BackOrderItem() { } /** * Method BackOrderItem. * * @param backOrderID * @param inventoryID * @param name * @param quantity * @param status */ public BackOrderItem(String backOrderID, Inventory inventoryID, String name, int quantity, String status) { this.backOrderID = backOrderID; this.inventory = inventoryID; this.name = name; this.quantity = quantity; this.status = status; } /** * Method BackOrderItem. * * @param backOrder */ public BackOrderItem(BackOrder backOrder) { try { this.backOrderID = backOrder.getBackOrderID(); this.inventory = backOrder.getInventory(); this.quantity = backOrder.getQuantity(); this.status = backOrder.getStatus(); this.lowDate = backOrder.getLowDate(); this.orderDate = backOrder.getOrderDate(); this.supplierOrderID = backOrder.getSupplierOrderID(); } catch (Exception e) { Util.debug("BackOrderItem - Exception: " + e); } } /** * Method getBackOrderID. * * @return String */ public String getBackOrderID() { return backOrderID; } /** * Method setBackOrderID. * * @param backOrderID */ public void setBackOrderID(String backOrderID) { this.backOrderID = backOrderID; } /** * Method getSupplierOrderID. * * @return String */ public String getSupplierOrderID() { return supplierOrderID; } /** * Method setSupplierOrderID. * * @param supplierOrderID */ public void setSupplierOrderID(String supplierOrderID) { this.supplierOrderID = supplierOrderID; } /** * Method setQuantity. * * @param quantity */ public void setQuantity(int quantity) { this.quantity = quantity; } /** * Method getInventoryID. * * @return String */ public Inventory getInventory() { return inventory; } /** * Method getName. * * @return String */ public String getName() { return name; } /** * Method setName. * * @param name */ public void setName(String name) { this.name = name; } /** * Method getQuantity. * * @return int */ public int getQuantity() { return quantity; } /** * Method getInventoryQuantity. * * @return int */ public int getInventoryQuantity() { return inventoryQuantity; } /** * Method setInventoryQuantity. * * @param quantity */ public void setInventoryQuantity(int quantity) { this.inventoryQuantity = quantity; } /** * Method getStatus. * * @return String */ public String getStatus() { return status; } /** * Method getLowDate. * * @return long */ public long getLowDate() { return lowDate; } /** * Method getOrderDate. * * @return long */ public long getOrderDate() { return orderDate; } }
4,733
21.542857
108
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/HelpBean.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.io.Serializable; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import com.ibm.websphere.samples.pbw.bean.ResetDBBean; import com.ibm.websphere.samples.pbw.utils.Util; /** * JSF action bean for the help page. * */ @Named("help") public class HelpBean implements Serializable { @Inject private ResetDBBean rdb; private String dbDumpFile; private static final String ACTION_HELP = "help"; private static final String ACTION_HOME = "promo"; public String performHelp() { return ACTION_HELP; } public String performDBReset() { rdb.resetDB(); return ACTION_HOME; } /** * @return the dbDumpFile */ public String getDbDumpFile() { return dbDumpFile; } /** * @param dbDumpFile * the dbDumpFile to set */ public void setDbDumpFile(String dbDumpFile) { this.dbDumpFile = dbDumpFile; } /** * @return whether debug is on or not */ public boolean isDebug() { return Util.debugOn(); } /** * Debugging is currently tied to the JavaServer Faces project stage. Any change here is likely * to be automatically reset. * * @param debug * Sets whether debug is on or not. */ public void setDebug(boolean debug) { Util.setDebug(debug); } }
2,520
27.977011
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/ImageServlet.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.io.IOException; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.pbw.bean.CatalogMgr; import com.ibm.websphere.samples.pbw.utils.Util; /** * Servlet to handle image actions. */ @Named(value = "image") @WebServlet("/servlet/ImageServlet") public class ImageServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Inject private CatalogMgr catalog; /** * Servlet initialization. */ public void init(ServletConfig config) throws ServletException { super.init(config); } /** * Process incoming HTTP GET requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Process incoming HTTP POST requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Main service method for ImageServlet * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ private void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = null; action = req.getParameter("action"); Util.debug("action=" + action); if (action.equals("getimage")) { String inventoryID = req.getParameter("inventoryID"); byte[] buf = catalog.getItemImageBytes(inventoryID); if (buf != null) { resp.setContentType("image/jpeg"); resp.getOutputStream().write(buf); } } } }
3,628
33.894231
114
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/LoginInfo.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; /** * A JSF backing bean used to store information for the login web page. It is accessed via the * account bean. * */ public class LoginInfo { private String checkPassword; @Pattern(regexp = "[a-zA-Z0-9_-]+@[a-zA-Z0-9.-]+") private String email; private String message; @Size(min = 6, max = 10, message = "Password must be between 6 and 10 characters.") private String password; public LoginInfo() { } public String getCheckPassword() { return this.checkPassword; } public String getEmail() { return this.email; } public String getMessage() { return this.message; } public String getPassword() { return this.password; } public void setCheckPassword(String checkPassword) { this.checkPassword = checkPassword; } public void setEmail(String email) { this.email = email; } public void setMessage(String message) { this.message = message; } public void setPassword(String password) { this.password = password; } }
2,298
30.493151
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/MailAction.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import javax.inject.Inject; import javax.inject.Named; import com.ibm.websphere.samples.pbw.bean.MailerAppException; import com.ibm.websphere.samples.pbw.bean.MailerBean; import com.ibm.websphere.samples.pbw.jpa.Customer; import com.ibm.websphere.samples.pbw.utils.Util; /** * This class sends the email confirmation message. */ @Named("mailaction") public class MailAction implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; @Inject private MailerBean mailer; /** Public constructor */ public MailAction() { } /** * Send the email order confirmation message. * * @param customer * The customer information. * @param orderKey * The order number. */ public final void sendConfirmationMessage(Customer customer, String orderKey) { try { System.out.println("mailer=" + mailer); mailer.createAndSendMail(customer, orderKey); } // The MailerAppException will be ignored since mail may not be configured. catch (MailerAppException e) { Util.debug("Mailer threw exception, mail may not be configured. Exception:" + e); } } }
2,382
35.661538
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/OrderInfo.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.util.Calendar; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import com.ibm.websphere.samples.pbw.jpa.Order; import com.ibm.websphere.samples.pbw.utils.Util; /** * A class to hold an order's data. */ public class OrderInfo implements java.io.Serializable { private static final long serialVersionUID = 1L; private String orderID; @NotNull @Size(min = 1, message = "Name for billing must include at least one letter.") private String billName; @NotNull @Size(min = 1, message = "Billing address must include at least one letter.") private String billAddr1; private String billAddr2; @NotNull @Size(min = 1, message = "Billing city must include at least one letter.") private String billCity; @NotNull @Size(min = 1, message = "Billing state must include at least one letter.") private String billState; @Pattern(regexp = "\\d{5}", message = "Billing zip code does not have 5 digits.") private String billZip; @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}", message = "Billing phone number does not match xxx-xxx-xxxx.") private String billPhone; @NotNull @Size(min = 1, message = "Name for shipping must include at least one letter.") private String shipName; @NotNull @Size(min = 1, message = "Shipping address must include at least one letter.") private String shipAddr1; private String shipAddr2; @NotNull @Size(min = 1, message = "Shipping city must include at least one letter.") private String shipCity; @NotNull @Size(min = 1, message = "Shipping state must include at least one letter.") private String shipState; @Pattern(regexp = "[0-9][0-9][0-9][0-9][0-9]", message = "Shipping zip code does not have 5 digits.") private String shipZip; @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}", message = "Shipping phone number does not match xxx-xxx-xxxx.") private String shipPhone; private int shippingMethod; @NotNull @Size(min = 1, message = "Card holder name must include at least one letter.") private String cardholderName; private String cardName; @Pattern(regexp = "\\d{4} \\d{4} \\d{4} \\d{4}", message = "Credit card numbers must be entered as XXXX XXXX XXXX XXXX.") private String cardNum; private String cardExpMonth; private String cardExpYear; private String[] cardExpYears; private boolean shipisbill = false; /** * Constructor to create an OrderInfo by passing each field. */ public OrderInfo(String billName, String billAddr1, String billAddr2, String billCity, String billState, String billZip, String billPhone, String shipName, String shipAddr1, String shipAddr2, String shipCity, String shipState, String shipZip, String shipPhone, int shippingMethod, String orderID) { this.orderID = orderID; this.billName = billName; this.billAddr1 = billAddr1; this.billAddr2 = billAddr2; this.billCity = billCity; this.billState = billState; this.billZip = billZip; this.billPhone = billPhone; this.shipName = shipName; this.shipAddr1 = shipAddr1; this.shipAddr2 = shipAddr2; this.shipCity = shipCity; this.shipState = shipState; this.shipZip = shipZip; this.shipPhone = shipPhone; this.shippingMethod = shippingMethod; initLists(); cardholderName = ""; cardNum = ""; } /** * Constructor to create an OrderInfo using an Order. * * @param order */ public OrderInfo(Order order) { orderID = order.getOrderID(); billName = order.getBillName(); billAddr1 = order.getBillAddr1(); billAddr2 = order.getBillAddr2(); billCity = order.getBillCity(); billState = order.getBillState(); billZip = order.getBillZip(); billPhone = order.getBillPhone(); shipName = order.getShipName(); shipAddr1 = order.getShipAddr1(); shipAddr2 = order.getShipAddr2(); shipCity = order.getShipCity(); shipState = order.getShipState(); shipZip = order.getShipZip(); shipPhone = order.getShipPhone(); shippingMethod = order.getShippingMethod(); } /** * Get the shipping method name. */ public String getShippingMethodName() { return getShippingMethods()[shippingMethod]; } /** * Set the shipping method by name */ public void setShippingMethodName(String name) { String[] methodNames = Util.getShippingMethodStrings(); for (int i = 0; i < methodNames.length; i++) { if (methodNames[i].equals(name)) shippingMethod = i; } } /** * Get shipping methods that are possible. * * @return String[] of method names */ public String[] getShippingMethods() { return Util.getFullShippingMethodStrings(); } public int getShippingMethodCount() { return Util.getShippingMethodStrings().length; } private void initLists() { int i = Calendar.getInstance().get(1); cardExpYears = new String[5]; for (int j = 0; j < 5; j++) cardExpYears[j] = (new Integer(i + j)).toString(); } /** * @return the orderID */ public String getID() { return orderID; } /** * @param orderID * the orderID to set */ public void setID(String orderID) { this.orderID = orderID; } /** * @return the billName */ public String getBillName() { return billName; } /** * @param billName * the billName to set */ public void setBillName(String billName) { this.billName = billName; } /** * @return the billAddr1 */ public String getBillAddr1() { return billAddr1; } /** * @param billAddr1 * the billAddr1 to set */ public void setBillAddr1(String billAddr1) { this.billAddr1 = billAddr1; } /** * @return the billAddr2 */ public String getBillAddr2() { return billAddr2; } /** * @param billAddr2 * the billAddr2 to set */ public void setBillAddr2(String billAddr2) { this.billAddr2 = billAddr2; } /** * @return the billCity */ public String getBillCity() { return billCity; } /** * @param billCity * the billCity to set */ public void setBillCity(String billCity) { this.billCity = billCity; } /** * @return the billState */ public String getBillState() { return billState; } /** * @param billState * the billState to set */ public void setBillState(String billState) { this.billState = billState; } /** * @return the billZip */ public String getBillZip() { return billZip; } /** * @param billZip * the billZip to set */ public void setBillZip(String billZip) { this.billZip = billZip; } /** * @return the billPhone */ public String getBillPhone() { return billPhone; } /** * @param billPhone * the billPhone to set */ public void setBillPhone(String billPhone) { this.billPhone = billPhone; } /** * @return the shipName */ public String getShipName() { return shipName; } /** * @param shipName * the shipName to set */ public void setShipName(String shipName) { this.shipName = shipName; } /** * @return the shipAddr1 */ public String getShipAddr1() { return shipAddr1; } /** * @param shipAddr1 * the shipAddr1 to set */ public void setShipAddr1(String shipAddr1) { this.shipAddr1 = shipAddr1; } /** * @return the shipAddr2 */ public String getShipAddr2() { return shipAddr2; } /** * @param shipAddr2 * the shipAddr2 to set */ public void setShipAddr2(String shipAddr2) { this.shipAddr2 = shipAddr2; } /** * @return the shipCity */ public String getShipCity() { return shipCity; } /** * @param shipCity * the shipCity to set */ public void setShipCity(String shipCity) { this.shipCity = shipCity; } /** * @return the shipState */ public String getShipState() { return shipState; } /** * @param shipState * the shipState to set */ public void setShipState(String shipState) { this.shipState = shipState; } /** * @return the shipZip */ public String getShipZip() { return shipZip; } /** * @param shipZip * the shipZip to set */ public void setShipZip(String shipZip) { this.shipZip = shipZip; } /** * @return the shipPhone */ public String getShipPhone() { return shipPhone; } /** * @param shipPhone * the shipPhone to set */ public void setShipPhone(String shipPhone) { this.shipPhone = shipPhone; } /** * @return the shippingMethod */ public int getShippingMethod() { return shippingMethod; } /** * @param shippingMethod * the shippingMethod to set */ public void setShippingMethod(int shippingMethod) { this.shippingMethod = shippingMethod; } /** * @return the cardholderName */ public String getCardholderName() { return cardholderName; } /** * @param cardholderName * the cardholderName to set */ public void setCardholderName(String cardholderName) { this.cardholderName = cardholderName; } /** * @return the cardName */ public String getCardName() { return cardName; } /** * @param cardName * the cardName to set */ public void setCardName(String cardName) { this.cardName = cardName; } /** * @return the cardNum */ public String getCardNum() { return cardNum; } /** * @param cardNum * the cardNum to set */ public void setCardNum(String cardNum) { this.cardNum = cardNum; } /** * @return the cardExpMonth */ public String getCardExpMonth() { return cardExpMonth; } /** * @param cardExpMonth * the cardExpMonth to set */ public void setCardExpMonth(String cardExpMonth) { this.cardExpMonth = cardExpMonth; } /** * @return the cardExpYear */ public String getCardExpYear() { return cardExpYear; } /** * @param cardExpYear * the cardExpYear to set */ public void setCardExpYear(String cardExpYear) { this.cardExpYear = cardExpYear; } /** * @return the cardExpYears */ public String[] getCardExpYears() { return cardExpYears; } /** * @param cardExpYears * the cardExpYears to set */ public void setCardExpYears(String[] cardExpYears) { this.cardExpYears = cardExpYears; } /** * @return the shipisbill */ public boolean isShipisbill() { return shipisbill; } /** * @param shipisbill * the shipisbill to set */ public void setShipisbill(boolean shipisbill) { this.shipisbill = shipisbill; } }
11,626
21.359615
122
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/Populate.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2004,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.Vector; import com.ibm.websphere.samples.pbw.bean.BackOrderMgr; import com.ibm.websphere.samples.pbw.bean.CatalogMgr; import com.ibm.websphere.samples.pbw.bean.CustomerMgr; import com.ibm.websphere.samples.pbw.bean.ResetDBBean; import com.ibm.websphere.samples.pbw.bean.ShoppingCartBean; import com.ibm.websphere.samples.pbw.bean.SuppliersBean; import com.ibm.websphere.samples.pbw.jpa.Inventory; import com.ibm.websphere.samples.pbw.utils.Util; /** * A basic POJO class for resetting the database. */ public class Populate { private ResetDBBean resetDB; private CatalogMgr catalog; private CustomerMgr login; private ShoppingCartBean cart; private BackOrderMgr backOrderStock; private SuppliersBean suppliers; /** * */ public Populate() { } public Populate(ResetDBBean resetDB, CatalogMgr c, CustomerMgr l, BackOrderMgr b, SuppliersBean s) { this.resetDB = resetDB; this.catalog = c; this.login = l; this.backOrderStock = b; this.suppliers = s; } /** * @param itemID * @param fileName * @param catalog * @throws FileNotFoundException * @throws IOException */ public static void addImage(String itemID, String fileName, CatalogMgr catalog) throws FileNotFoundException, IOException { URL url = Thread.currentThread().getContextClassLoader().getResource("resources/images/" + fileName); Util.debug("URL: " + url); fileName = url.getPath(); Util.debug("Fully-qualified Filename: " + fileName); File imgFile = new File(fileName); // Open the input file as a stream of bytes FileInputStream fis = new FileInputStream(imgFile); DataInputStream dis = new DataInputStream(fis); int dataSize = dis.available(); byte[] data = new byte[dataSize]; dis.readFully(data); catalog.setItemImageBytes(itemID, data); } /** * */ public void doPopulate() { try { resetDB.deleteAll(); } catch (Exception e) { Util.debug("Populate:doPopulate() - Exception deleting data in database: " + e); e.printStackTrace(); } /** * Populate INVENTORY table with text */ Util.debug("Populating INVENTORY table with text..."); try { String[] values = Util.getProperties("inventory"); for (int index = 0; index < values.length; index++) { Util.debug("Found INVENTORY property values: " + values[index]); String[] fields = Util.readTokens(values[index], "|"); String id = fields[0]; String name = fields[1]; String heading = fields[2]; String descr = fields[3]; String pkginfo = fields[4]; String image = fields[5]; float price = new Float(fields[6]).floatValue(); float cost = new Float(fields[7]).floatValue(); int quantity = new Integer(fields[8]).intValue(); int category = new Integer(fields[9]).intValue(); String notes = fields[10]; boolean isPublic = new Boolean(fields[11]).booleanValue(); Util.debug("Populating INVENTORY with following values: "); Util.debug(fields[0]); Util.debug(fields[1]); Util.debug(fields[2]); Util.debug(fields[3]); Util.debug(fields[4]); Util.debug(fields[5]); Util.debug(fields[6]); Util.debug(fields[7]); Util.debug(fields[8]); Util.debug(fields[9]); Util.debug(fields[10]); Util.debug(fields[11]); Inventory storeItem = new Inventory(id, name, heading, descr, pkginfo, image, price, cost, quantity, category, notes, isPublic); catalog.addItem(storeItem); addImage(id, image, catalog); } Util.debug("INVENTORY table populated with text..."); } catch (Exception e) { Util.debug("Unable to populate INVENTORY table with text data: " + e); } /** * Populate CUSTOMER table with text */ Util.debug("Populating CUSTOMER table with default values..."); try { String[] values = Util.getProperties("customer"); Util.debug("Found CUSTOMER properties: " + values[0]); for (int index = 0; index < values.length; index++) { String[] fields = Util.readTokens(values[index], "|"); String customerID = fields[0]; String password = fields[1]; String firstName = fields[2]; String lastName = fields[3]; String addr1 = fields[4]; String addr2 = fields[5]; String addrCity = fields[6]; String addrState = fields[7]; String addrZip = fields[8]; String phone = fields[9]; Util.debug("Populating CUSTOMER with following values: "); Util.debug(fields[0]); Util.debug(fields[1]); Util.debug(fields[2]); Util.debug(fields[3]); Util.debug(fields[4]); Util.debug(fields[5]); Util.debug(fields[6]); Util.debug(fields[7]); Util.debug(fields[8]); Util.debug(fields[9]); login.createCustomer(customerID, password, firstName, lastName, addr1, addr2, addrCity, addrState, addrZip, phone); } } catch (Exception e) { Util.debug("Unable to populate CUSTOMER table with text data: " + e); } /** * Populate ORDER table with text */ Util.debug("Populating ORDER table with default values..."); try { String[] values = Util.getProperties("order"); Util.debug("Found ORDER properties: " + values[0]); if (values[0] != null && values.length > 0) { for (int index = 0; index < values.length; index++) { String[] fields = Util.readTokens(values[index], "|"); if (fields != null && fields.length >= 21) { String customerID = fields[0]; String billName = fields[1]; String billAddr1 = fields[2]; String billAddr2 = fields[3]; String billCity = fields[4]; String billState = fields[5]; String billZip = fields[6]; String billPhone = fields[7]; String shipName = fields[8]; String shipAddr1 = fields[9]; String shipAddr2 = fields[10]; String shipCity = fields[11]; String shipState = fields[12]; String shipZip = fields[13]; String shipPhone = fields[14]; int shippingMethod = Integer.parseInt(fields[15]); String creditCard = fields[16]; String ccNum = fields[17]; String ccExpireMonth = fields[18]; String ccExpireYear = fields[19]; String cardHolder = fields[20]; Vector<Inventory> items = new Vector<Inventory>(); Util.debug("Populating ORDER with following values: "); Util.debug(fields[0]); Util.debug(fields[1]); Util.debug(fields[2]); Util.debug(fields[3]); Util.debug(fields[4]); Util.debug(fields[5]); Util.debug(fields[6]); Util.debug(fields[7]); Util.debug(fields[8]); Util.debug(fields[9]); Util.debug(fields[10]); Util.debug(fields[11]); Util.debug(fields[12]); Util.debug(fields[13]); Util.debug(fields[14]); Util.debug(fields[15]); Util.debug(fields[16]); Util.debug(fields[17]); Util.debug(fields[18]); Util.debug(fields[19]); Util.debug(fields[20]); cart.createOrder(customerID, billName, billAddr1, billAddr2, billCity, billState, billZip, billPhone, shipName, shipAddr1, shipAddr2, shipCity, shipState, shipZip, shipPhone, creditCard, ccNum, ccExpireMonth, ccExpireYear, cardHolder, shippingMethod, items); } else { Util.debug("Property does not contain enough fields: " + values[index]); Util.debug("Fields found were: " + fields); } } } // stmt.executeUpdate(" INSERT INTO ORDERITEM(INVENTORYID, NAME, PKGINFO, PRICE, COST, // CATEGORY, QUANTITY, SELLDATE, ORDER_ORDERID) VALUES ('A0001', 'Bulb Digger', // 'Assembled', 12.0, 5.0, 3, 900, '01054835419625', '1')"); } catch (Exception e) { Util.debug("Unable to populate ORDERITEM table with text data: " + e); e.printStackTrace(); } /** * Populate BACKORDER table with text */ Util.debug("Populating BACKORDER table with default values..."); try { String[] values = Util.getProperties("backorder"); Util.debug("Found BACKORDER properties: " + values[0]); // Inserting backorders for (int index = 0; index < values.length; index++) { String[] fields = Util.readTokens(values[index], "|"); String inventoryID = fields[0]; int amountToOrder = new Integer(fields[1]).intValue(); int maximumItems = new Integer(fields[2]).intValue(); Util.debug("Populating BACKORDER with following values: "); Util.debug(inventoryID); Util.debug("amountToOrder -> " + amountToOrder); Util.debug("maximumItems -> " + maximumItems); backOrderStock.createBackOrder(inventoryID, amountToOrder, maximumItems); } } catch (Exception e) { Util.debug("Unable to populate BACKORDER table with text data: " + e); } /** * Populate SUPPLIER table with text */ Util.debug("Populating SUPPLIER table with default values..."); try { String[] values = Util.getProperties("supplier"); Util.debug("Found SUPPLIER properties: " + values[0]); // Inserting Suppliers for (int index = 0; index < values.length; index++) { String[] fields = Util.readTokens(values[index], "|"); String supplierID = fields[0]; String name = fields[1]; String address = fields[2]; String city = fields[3]; String state = fields[4]; String zip = fields[5]; String phone = fields[6]; String url = fields[7]; Util.debug("Populating SUPPLIER with following values: "); Util.debug(fields[0]); Util.debug(fields[1]); Util.debug(fields[2]); Util.debug(fields[3]); Util.debug(fields[4]); Util.debug(fields[5]); Util.debug(fields[6]); Util.debug(fields[7]); suppliers.createSupplier(supplierID, name, address, city, state, zip, phone, url); } } catch (Exception e) { Util.debug("Unable to populate SUPPLIER table with text data: " + e); } } }
11,056
35.371711
264
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/ProductBean.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.io.Serializable; import java.text.NumberFormat; import java.util.Locale; import java.util.Objects; import com.ibm.websphere.samples.pbw.jpa.Inventory; import com.ibm.websphere.samples.pbw.utils.Util; /** * Provides backing bean support for the product web page. Accessed via the shopping bean. * */ public class ProductBean implements Serializable { private static final long serialVersionUID = 1L; private Inventory inventory; private int quantity; protected ProductBean(Inventory inventory) { Objects.requireNonNull(inventory, "Inventory cannot be null"); this.inventory = inventory; this.quantity = 1; } public String getCategoryName() { return Util.getCategoryString(this.inventory.getCategory()); } public Inventory getInventory() { return this.inventory; } public String getMenuString() { String categoryString = getCategoryName(); if (categoryString.equals("Flowers")) { return "banner:menu1"; } else if (categoryString.equals("Fruits & Vegetables")) { return "banner:menu2"; } else if (categoryString.equals("Trees")) { return "banner:menu3"; } else { return "banner:menu4"; } } public String getPrice() { return NumberFormat.getCurrencyInstance(Locale.US).format(new Float(this.inventory.getPrice())); } public int getQuantity() { return this.quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } }
2,672
31.204819
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/ShoppingBean.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2001,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.io.Serializable; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.Locale; import java.util.Map; import java.util.Vector; import javax.enterprise.context.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import com.ibm.websphere.samples.pbw.bean.CatalogMgr; import com.ibm.websphere.samples.pbw.bean.ShoppingCartBean; import com.ibm.websphere.samples.pbw.jpa.Inventory; /** * A combination JSF action bean and backing bean for the shopping web page. * */ @Named(value = "shopping") @SessionScoped public class ShoppingBean implements Serializable { private static final long serialVersionUID = 1L; private static final String ACTION_CART = "cart"; private static final String ACTION_PRODUCT = "product"; private static final String ACTION_SHOPPING = "shopping"; // keep an independent list of items so we can add pricing methods private ArrayList<ShoppingItem> cartItems; @Inject private CatalogMgr catalog; private ProductBean product; private LinkedList<ProductBean> products; private float shippingCost; @Inject private ShoppingCartBean shoppingCart; public String performAddToCart() { Inventory item = new Inventory(this.product.getInventory()); item.setQuantity(this.product.getQuantity()); shoppingCart.addItem(item); return performCart(); } public String performCart() { cartItems = wrapInventoryItems(shoppingCart.getItems()); return ShoppingBean.ACTION_CART; } public String performProductDetail() { FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); Map<String, String> requestParams = externalContext.getRequestParameterMap(); this.product = new ProductBean(this.catalog.getItemInventory(requestParams.get("itemID"))); return ShoppingBean.ACTION_PRODUCT; } public String performRecalculate() { shoppingCart.removeZeroQuantityItems(); this.cartItems = wrapInventoryItems(shoppingCart.getItems()); return performCart(); } public String performShopping() { int category = 0; FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); Vector<Inventory> inventories; Map<String, String> requestParams = externalContext.getRequestParameterMap(); try { category = Integer.parseInt(requestParams.get("category")); } catch (Throwable e) { if (this.products != null) { // No category specified, so just use the last one. return ShoppingBean.ACTION_SHOPPING; } } inventories = this.catalog.getItemsByCategory(category); this.products = new LinkedList<ProductBean>(); // Have to convert all the inventory objects into product beans. for (Object obj : inventories) { Inventory inventory = (Inventory) obj; if (inventory.isPublic()) { this.products.add(new ProductBean(inventory)); } } return ShoppingBean.ACTION_SHOPPING; } public Collection<ShoppingItem> getCartItems() { return this.cartItems; } public ProductBean getProduct() { return this.product; } public Collection<ProductBean> getProducts() { return this.products; } public String getShippingCostString() { return NumberFormat.getCurrencyInstance(Locale.US).format(this.shippingCost); } /** * @return the shippingCost */ public float getShippingCost() { return shippingCost; } public void setShippingCost(float shippingCost) { this.shippingCost = shippingCost; } public float getTotalCost() { return shoppingCart.getSubtotalCost() + this.shippingCost; } public String getTotalCostString() { return NumberFormat.getCurrencyInstance(Locale.US).format(getTotalCost()); } public ShoppingCartBean getCart() { return shoppingCart; } private ArrayList<ShoppingItem> wrapInventoryItems(Collection<Inventory> invItems) { ArrayList<ShoppingItem> shoppingList = new ArrayList<ShoppingItem>(); for (Inventory i : invItems) { shoppingList.add(new ShoppingItem(i)); } return shoppingList; } }
5,443
28.912088
104
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/ShoppingItem.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import java.io.Serializable; import javax.validation.constraints.Min; import com.ibm.websphere.samples.pbw.jpa.BackOrder; import com.ibm.websphere.samples.pbw.jpa.Inventory; /** * ShoppingItem wraps the JPA Inventory entity class to provide additional methods needed by the web * app. */ public class ShoppingItem implements Cloneable, Serializable { private static final long serialVersionUID = 1L; private Inventory item; public ShoppingItem() { } public ShoppingItem(Inventory i) { item = i; } public ShoppingItem(String key, String name, String heading, String desc, String pkginfo, String image, float price, float cost, int quantity, int category, String notes, boolean isPublic) { item = new Inventory(key, name, heading, desc, pkginfo, image, price, cost, quantity, category, notes, isPublic); } /** * Subtotal price calculates a cost based on price and quantity. */ public float getSubtotalPrice() { return getPrice() * getQuantity(); } /** * @param o * @return boolean true if object equals this * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { return item.equals(o); } /** * @return int hashcode for this object * @see java.lang.Object#hashCode() */ public int hashCode() { return item.hashCode(); } /** * @return String String representation of this object * @see java.lang.Object#toString() */ public String toString() { return item.toString(); } /** * @param quantity * @see com.ibm.websphere.samples.pbw.jpa.Inventory#increaseInventory(int) */ public void increaseInventory(int quantity) { item.increaseInventory(quantity); } /** * @return int category enum int value * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getCategory() */ public int getCategory() { return item.getCategory(); } /** * @param category * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setCategory(int) */ public void setCategory(int category) { item.setCategory(category); } /** * @return float cost of the item * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getCost() */ public float getCost() { return item.getCost(); } /** * @param cost * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setCost(float) */ public void setCost(float cost) { item.setCost(cost); } /** * @return String description of the item * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getDescription() */ public String getDescription() { return item.getDescription(); } /** * @param description * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setDescription(java.lang.String) */ public void setDescription(String description) { item.setDescription(description); } /** * @return String item heading * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getHeading() */ public String getHeading() { return item.getHeading(); } /** * @param heading * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setHeading(java.lang.String) */ public void setHeading(String heading) { item.setHeading(heading); } /** * @return String image URI * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getImage() */ public String getImage() { return item.getImage(); } /** * @param image * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setImage(java.lang.String) */ public void setImage(String image) { item.setImage(image); } /** * @return String name of the item * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getName() */ public String getName() { return item.getName(); } /** * @param name * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setName(java.lang.String) */ public void setName(String name) { item.setName(name); } /** * @return String item notes * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getNotes() */ public String getNotes() { return item.getNotes(); } /** * @param notes * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setNotes(java.lang.String) */ public void setNotes(String notes) { item.setNotes(notes); } /** * @return String package information * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getPkginfo() */ public String getPkginfo() { return item.getPkginfo(); } /** * @param pkginfo * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setPkginfo(java.lang.String) */ public void setPkginfo(String pkginfo) { item.setPkginfo(pkginfo); } /** * @return float Price of the item * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getPrice() */ public float getPrice() { return item.getPrice(); } /** * @param price * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setPrice(float) */ public void setPrice(float price) { item.setPrice(price); } /** * Property accessor for quantity of items ordered. Quantity may not be less than zero. Bean * Validation will ensure this is true. * * @return int quantity of items * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getQuantity() */ @Min(value = 0, message = "Quantity must be a number greater than or equal to zero.") public int getQuantity() { return item.getQuantity(); } /** * @param quantity * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setQuantity(int) */ public void setQuantity(int quantity) { item.setQuantity(quantity); } /** * @return int maximum threshold * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getMaxThreshold() */ public int getMaxThreshold() { return item.getMaxThreshold(); } /** * @param maxThreshold * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setMaxThreshold(int) */ public void setMaxThreshold(int maxThreshold) { item.setMaxThreshold(maxThreshold); } /** * @return int minimum threshold * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getMinThreshold() */ public int getMinThreshold() { return item.getMinThreshold(); } /** * @param minThreshold * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setMinThreshold(int) */ public void setMinThreshold(int minThreshold) { item.setMinThreshold(minThreshold); } /** * @return String item ID in the inventory * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getInventoryId() */ public String getInventoryId() { return item.getInventoryId(); } /** * @param id * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setInventoryId(java.lang.String) */ public void setInventoryId(String id) { item.setInventoryId(id); } /** * @return String item ID * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getID() */ public String getID() { return item.getID(); } /** * @param id * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setID(java.lang.String) */ public void setID(String id) { item.setID(id); } /** * @return boolean true if this is a public item * @see com.ibm.websphere.samples.pbw.jpa.Inventory#isPublic() */ public boolean isPublic() { return item.isPublic(); } /** * @param isPublic * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setIsPublic(boolean) */ public void setIsPublic(boolean isPublic) { item.setIsPublic(isPublic); } /** * @param isPublic * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setPrivacy(boolean) */ public void setPrivacy(boolean isPublic) { item.setPrivacy(isPublic); } /** * @return byte[] item image as a byte array * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getImgbytes() */ public byte[] getImgbytes() { return item.getImgbytes(); } /** * @param imgbytes * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setImgbytes(byte[]) */ public void setImgbytes(byte[] imgbytes) { item.setImgbytes(imgbytes); } /** * @return BackOrder item is on back order * @see com.ibm.websphere.samples.pbw.jpa.Inventory#getBackOrder() */ public BackOrder getBackOrder() { return item.getBackOrder(); } /** * @param backOrder * @see com.ibm.websphere.samples.pbw.jpa.Inventory#setBackOrder(com.ibm.websphere.samples.pbw.jpa.BackOrder) */ public void setBackOrder(BackOrder backOrder) { item.setBackOrder(backOrder); } }
9,387
24.034667
117
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/ValidatePasswords.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import javax.faces.validator.FacesValidator; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; /** * A JSF validator class, not implemented in Bean Validation since validation is only required * during GUI interaction. */ @FacesValidator(value = "validatePasswords") public class ValidatePasswords implements Validator { @Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { UIInput otherComponent; String otherID = (String) component.getAttributes().get("otherPasswordID"); String otherStr; String str = (String) value; otherComponent = (UIInput) context.getViewRoot().findComponent(otherID); otherStr = (String) otherComponent.getValue(); if (!otherStr.equals(str)) { ValidatorUtils.addErrorMessage(context, "Passwords do not match."); } } }
2,242
43.86
108
java
null
sample.plantsbywebsphere-main/src/main/java/com/ibm/websphere/samples/pbw/war/ValidatorUtils.java
// // COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, // modify, and distribute these sample programs in any form without payment to IBM for the purposes of // developing, using, marketing or distributing application programs conforming to the application // programming interface for the operating platform for which the sample code is written. // Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS // AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED // WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE // SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS // OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. // // (C) COPYRIGHT International Business Machines Corp., 2003,2011 // All Rights Reserved * Licensed Materials - Property of IBM // package com.ibm.websphere.samples.pbw.war; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; /** * Simple helper class for JSF validators to handle error messages. * */ public class ValidatorUtils { protected static void addErrorMessage(FacesContext context, String message) { FacesMessage facesMessage = new FacesMessage(); facesMessage.setDetail(message); facesMessage.setSummary(message); facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(facesMessage); } protected static void addErrorMessage(FacesContext context, UIComponent component) { String errorMessage = (String) component.getAttributes().get("errorMessage"); addErrorMessage(context, errorMessage); } }
2,052
45.659091
104
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/TradeAction.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader; import java.io.InputStream; import java.math.BigDecimal; import java.util.Collection; //import java.util.Properties; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Element; import javax.naming.InitialContext; import com.ibm.websphere.samples.daytrader.beans.MarketSummaryDataBean; import com.ibm.websphere.samples.daytrader.beans.RunStatsDataBean; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBLocal; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBRemote; import com.ibm.websphere.samples.daytrader.entities.AccountDataBean; import com.ibm.websphere.samples.daytrader.entities.AccountProfileDataBean; import com.ibm.websphere.samples.daytrader.entities.HoldingDataBean; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * The TradeAction class provides the generic client side access to each of the * Trade brokerage user operations. These include login, logout, buy, sell, * getQuote, etc. The TradeAction class does not handle user interface * processing and should be used by a class that is UI specific. For example, * {trade_client.TradeServletAction}manages a web interface to Trade, making * calls to TradeAction methods to actually performance each operation. */ public class TradeAction implements TradeServices { // This lock is used to serialize market summary operations. private static final Integer marketSummaryLock = new Integer(0); private static long nextMarketSummary = System.currentTimeMillis(); private static MarketSummaryDataBean cachedMSDB = MarketSummaryDataBean.getRandomInstance(); // make this static so the trade impl can be cached // - ejb3 mode is the only thing that really uses this // - can go back and update other modes to take advantage (ie. TradeDirect) private static TradeServices trade = null; private static TradeServices tradeLocal = null; private static TradeServices tradeRemote = null; static { // Determine if JPA Shared L2 Class is enabled // Depends on the <shared-cache-mode> in the persistence.xml try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream is = loader.getResourceAsStream ("META-INF/persistence.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(is); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("shared-cache-mode"); if (nList.getLength() != 0 && ((Element)nList.item(0)).getTextContent().equals("NONE")) { Log.log("JPA Shared L2 Cache disabled."); } else { Log.log("JPA Shared L2 Cache enabled."); } } catch (Exception e) { Log.log("Unable to determine if JPA Shared L2 Cache is enabled or disabled."); e.printStackTrace(); } } public TradeAction() { if (Log.doTrace()) { Log.trace("TradeAction:TradeAction()"); } createTrade(); } public TradeAction(TradeServices trade) { if (Log.doActionTrace()) { Log.trace("TradeAction:TradeAction(trade)"); } TradeAction.trade = trade; } private void createTrade() { if (TradeConfig.runTimeMode == TradeConfig.EJB3) { try { if (tradeLocal == null && tradeRemote == null ) { InitialContext context = new InitialContext(); tradeLocal = (TradeSLSBLocal) context.lookup("java:comp/env/ejb/TradeSLSBBean"); tradeRemote = (TradeSLSBRemote) context.lookup("java:comp/env/ejb/TradeSLSBBeanRemote"); } // Determine local or remote interface. if (!TradeConfig.useRemoteEJBInterface()) { if (!(trade instanceof TradeSLSBLocal)) { trade = tradeLocal; } } else if (!(trade instanceof TradeSLSBRemote)) { /* TODO: For split tier this will need to be changed I have not tried this yet with DT7 */ trade = tradeRemote; } } catch (Exception e) { Log.error("TradeAction:TradeAction() Creation of Trade EJB 3 failed\n" + e); e.printStackTrace(); } } else if (TradeConfig.runTimeMode == TradeConfig.DIRECT) { try { trade = new TradeDirect(); } catch (Exception e) { Log.error("TradeAction:TradeAction() Creation of Trade Direct failed\n" + e); e.printStackTrace(); } } } /** * Market Summary is inherently a heavy database operation. For servers that * have a caching story this is a great place to cache data that is good for * a period of time. In order to provide a flexible framework for this we * allow the market summary operation to be invoked on every transaction, * time delayed or never. This is configurable in the configuration panel. * * @return An instance of the market summary */ @Override public MarketSummaryDataBean getMarketSummary() throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getMarketSummary()"); } // If EJB3 mode, then have the Singleton Bean handle this. if (TradeConfig.getRunTimeMode() == TradeConfig.EJB3) { if (Log.doActionTrace()) { Log.trace("TradeAction:getMarketSummary() -- EJB3 mode, using Singleton Bean"); } return trade.getMarketSummary(); } if (TradeConfig.getMarketSummaryInterval() == 0) { return getMarketSummaryInternal(); } if (TradeConfig.getMarketSummaryInterval() < 0) { return cachedMSDB; } /** * This is a little funky. If its time to fetch a new Market summary * then we'll synchronize access to make sure only one requester does * it. Others will merely return the old copy until the new * MarketSummary has been executed. */ long currentTime = System.currentTimeMillis(); if (currentTime > nextMarketSummary) { long oldNextMarketSummary = nextMarketSummary; boolean fetch = false; synchronized (marketSummaryLock) { /** * Is it still ahead or did we miss lose the race? If we lost * then let's get out of here as the work has already been done. */ if (oldNextMarketSummary == nextMarketSummary) { fetch = true; nextMarketSummary += TradeConfig.getMarketSummaryInterval() * 1000; /** * If the server has been idle for a while then its possible * that nextMarketSummary could be way off. Rather than try * and play catch up we'll simply get in sync with the * current time + the interval. */ if (nextMarketSummary < currentTime) { nextMarketSummary = currentTime + TradeConfig.getMarketSummaryInterval() * 1000; } } } /** * If we're the lucky one then let's update the MarketSummary */ if (fetch) { cachedMSDB = getMarketSummaryInternal(); } } return cachedMSDB; } /** * Compute and return a snapshot of the current market conditions This * includes the TSIA - an index of the price of the top 100 Trade stock * quotes The openTSIA ( the index at the open) The volume of shares traded, * Top Stocks gain and loss * * @return A snapshot of the current market summary */ public MarketSummaryDataBean getMarketSummaryInternal() throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getMarketSummaryInternal()"); } MarketSummaryDataBean marketSummaryData = null; marketSummaryData = trade.getMarketSummary(); return marketSummaryData; } /** * Purchase a stock and create a new holding for the given user. Given a * stock symbol and quantity to purchase, retrieve the current quote price, * debit the user's account balance, and add holdings to user's portfolio. * * @param userID * the customer requesting the stock purchase * @param symbol * the symbol of the stock being purchased * @param quantity * the quantity of shares to purchase * @return OrderDataBean providing the status of the newly created buy order */ @Override public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:buy", userID, symbol, new Double(quantity), new Integer(orderProcessingMode)); } OrderDataBean orderData = trade.buy(userID, symbol, quantity, orderProcessingMode); // after the purchase or sell of a stock, update the stocks volume and // price updateQuotePriceVolume(symbol, TradeConfig.getRandomPriceChangeFactor(), quantity); return orderData; } /** * Sell(SOAP 2.2 Wrapper converting int to Integer) a stock holding and * removed the holding for the given user. Given a Holding, retrieve current * quote, credit user's account, and reduce holdings in user's portfolio. * * @param userID * the customer requesting the sell * @param holdingID * the users holding to be sold * @return OrderDataBean providing the status of the newly created sell * order */ public OrderDataBean sell(String userID, int holdingID, int orderProcessingMode) throws Exception { return sell(userID, new Integer(holdingID), orderProcessingMode); } /** * Sell a stock holding and removed the holding for the given user. Given a * Holding, retrieve current quote, credit user's account, and reduce * holdings in user's portfolio. * * @param userID * the customer requesting the sell * @param holdingID * the users holding to be sold * @return OrderDataBean providing the status of the newly created sell * order */ @Override public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:sell", userID, holdingID, new Integer(orderProcessingMode)); } OrderDataBean orderData = trade.sell(userID, holdingID, orderProcessingMode); if (!orderData.getOrderStatus().equalsIgnoreCase("cancelled")) { updateQuotePriceVolume(orderData.getSymbol(), TradeConfig.getRandomPriceChangeFactor(), orderData.getQuantity()); } return orderData; } /** * Queue the Order identified by orderID to be processed * <p/> * Orders are submitted through JMS to a Trading Broker and completed * asynchronously. This method queues the order for processing * <p/> * The boolean twoPhase specifies to the server implementation whether or * not the method is to participate in a global transaction * * @param orderID * the Order being queued for processing */ @Override public void queueOrder(Integer orderID, boolean twoPhase) { throw new UnsupportedOperationException("TradeAction: queueOrder method not supported"); } /** * Complete the Order identefied by orderID Orders are submitted through JMS * to a Trading agent and completed asynchronously. This method completes * the order For a buy, the stock is purchased creating a holding and the * users account is debited For a sell, the stock holding is removed and the * users account is credited with the proceeds * <p/> * The boolean twoPhase specifies to the server implementation whether or * not the method is to participate in a global transaction * * @param orderID * the Order to complete * @return OrderDataBean providing the status of the completed order */ @Override public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) { throw new UnsupportedOperationException("TradeAction: completeOrder method not supported"); } /** * Cancel the Order identified by orderID * <p/> * Orders are submitted through JMS to a Trading Broker and completed * asynchronously. This method queues the order for processing * <p/> * The boolean twoPhase specifies to the server implementation whether or * not the method is to participate in a global transaction * * @param orderID * the Order being queued for processing */ @Override public void cancelOrder(Integer orderID, boolean twoPhase) { throw new UnsupportedOperationException("TradeAction: cancelOrder method not supported"); } @Override public void orderCompleted(String userID, Integer orderID) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:orderCompleted", userID, orderID); } if (Log.doTrace()) { Log.trace("OrderCompleted", userID, orderID); } } /** * Get the collection of all orders for a given account * * @param userID * the customer account to retrieve orders for * @return Collection OrderDataBeans providing detailed order information */ @Override public Collection<?> getOrders(String userID) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getOrders", userID); } Collection<?> orderDataBeans = trade.getOrders(userID); return orderDataBeans; } /** * Get the collection of completed orders for a given account that need to * be alerted to the user * * @param userID * the customer account to retrieve orders for * @return Collection OrderDataBeans providing detailed order information */ @Override public Collection<?> getClosedOrders(String userID) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getClosedOrders", userID); } Collection<?> orderDataBeans = trade.getClosedOrders(userID); return orderDataBeans; } /** * Given a market symbol, price, and details, create and return a new * {@link QuoteDataBean} * * @param symbol * the symbol of the stock * @param price * the current stock price * @return a new QuoteDataBean or null if Quote could not be created */ @Override public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:createQuote", symbol, companyName, price); } return trade.createQuote(symbol, companyName, price); } /** * Return a collection of {@link QuoteDataBean}describing all current quotes * * @return the collection of QuoteDataBean */ @Override public Collection<?> getAllQuotes() throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getAllQuotes"); } return trade.getAllQuotes(); } /** * Return a {@link QuoteDataBean}describing a current quote for the given * stock symbol * * @param symbol * the stock symbol to retrieve the current Quote * @return the QuoteDataBean */ @Override public QuoteDataBean getQuote(String symbol) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getQuote", symbol); } if ((symbol == null) || (symbol.length() == 0) || (symbol.length() > 10)) { if (Log.doActionTrace()) { Log.trace("TradeAction:getQuote --- primitive workload"); } return new QuoteDataBean("Invalid symbol", "", 0.0, FinancialUtils.ZERO, FinancialUtils.ZERO, FinancialUtils.ZERO, FinancialUtils.ZERO, 0.0); } QuoteDataBean quoteData = trade.getQuote(symbol); return quoteData; } /** * Update the stock quote price for the specified stock symbol * * @param symbol * for stock quote to update * @return the QuoteDataBean describing the stock */ /* avoid data collision with synch */ @Override public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:updateQuotePriceVolume", symbol, changeFactor, new Double(sharesTraded)); } QuoteDataBean quoteData = null; try { quoteData = trade.updateQuotePriceVolume(symbol, changeFactor, sharesTraded); } catch (Exception e) { Log.error("TradeAction:updateQuotePrice -- ", e); } return quoteData; } /** * Return the portfolio of stock holdings for the specified customer as a * collection of HoldingDataBeans * * @param userID * the customer requesting the portfolio * @return Collection of the users portfolio of stock holdings */ @Override public Collection<?> getHoldings(String userID) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getHoldings", userID); } Collection<?> holdingDataBeans = trade.getHoldings(userID); return holdingDataBeans; } /** * Return a specific user stock holding identifed by the holdingID * * @param holdingID * the holdingID to return * @return a HoldingDataBean describing the holding */ @Override public HoldingDataBean getHolding(Integer holdingID) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getHolding", holdingID); } return trade.getHolding(holdingID); } /** * Return an AccountDataBean object for userID describing the account * * @param userID * the account userID to lookup * @return User account data in AccountDataBean */ @Override public AccountDataBean getAccountData(String userID) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getAccountData", userID); } AccountDataBean accountData = trade.getAccountData(userID); return accountData; } /** * Return an AccountProfileDataBean for userID providing the users profile * * @param userID * the account userID to lookup */ @Override public AccountProfileDataBean getAccountProfileData(String userID) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:getAccountProfileData", userID); } AccountProfileDataBean accountProfileData = trade.getAccountProfileData(userID); return accountProfileData; } /** * Update userID's account profile information using the provided * AccountProfileDataBean object * * @param accountProfileData * account profile data in AccountProfileDataBean */ @Override public AccountProfileDataBean updateAccountProfile(AccountProfileDataBean accountProfileData) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:updateAccountProfile", accountProfileData); } accountProfileData = trade.updateAccountProfile(accountProfileData); return accountProfileData; } /** * Attempt to authenticate and login a user with the given password * * @param userID * the customer to login * @param password * the password entered by the customer for authentication * @return User account data in AccountDataBean */ @Override public AccountDataBean login(String userID, String password) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:login", userID, password); } AccountDataBean accountData = trade.login(userID, password); return accountData; } /** * Logout the given user * * @param userID * the customer to logout */ @Override public void logout(String userID) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:logout", userID); } trade.logout(userID); } /** * Register a new Trade customer. Create a new user profile, user registry * entry, account with initial balance, and empty portfolio. * * @param userID * the new customer to register * @param password * the customers password * @param fullname * the customers fullname * @param address * the customers street address * @param email * the customers email address * @param creditCard * the customers creditcard number * @param openBalance * the amount to charge to the customers credit to open the * account and set the initial balance * @return the userID if successful, null otherwise */ @Override public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditCard, BigDecimal openBalance) throws Exception { if (Log.doActionTrace()) { Log.trace("TradeAction:register", userID, password, fullname, address, email, creditCard, openBalance); } return trade.register(userID, password, fullname, address, email, creditCard, openBalance); } public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditCard, String openBalanceString) throws Exception { BigDecimal openBalance = new BigDecimal(openBalanceString); return register(userID, password, fullname, address, email, creditCard, openBalance); } /** * Reset the TradeData by - removing all newly registered users by scenario * servlet (i.e. users with userID's beginning with "ru:") * - removing all * buy/sell order pairs - setting logoutCount = loginCount * * return statistics for this benchmark run */ @Override public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception { RunStatsDataBean runStatsData = trade.resetTrade(deleteAll); return runStatsData; } }
24,760
36.234586
159
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/TradeServices.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader; import java.math.BigDecimal; import java.util.Collection; import com.ibm.websphere.samples.daytrader.beans.MarketSummaryDataBean; import com.ibm.websphere.samples.daytrader.beans.RunStatsDataBean; import com.ibm.websphere.samples.daytrader.entities.AccountDataBean; import com.ibm.websphere.samples.daytrader.entities.AccountProfileDataBean; import com.ibm.websphere.samples.daytrader.entities.HoldingDataBean; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; /** * TradeServices interface specifies the business methods provided by the Trade * online broker application. These business methods represent the features and * operations that can be performed by customers of the brokerage such as login, * logout, get a stock quote, buy or sell a stock, etc. This interface is * implemented by {@link Trade} providing an EJB implementation of these * business methods and also by {@link TradeDirect} providing a JDBC * implementation. * * @see Trade * @see TradeDirect * */ public interface TradeServices { /** * Compute and return a snapshot of the current market conditions This * includes the TSIA - an index of the price of the top 100 Trade stock * quotes The openTSIA ( the index at the open) The volume of shares traded, * Top Stocks gain and loss * * @return A snapshot of the current market summary */ MarketSummaryDataBean getMarketSummary() throws Exception; /** * Purchase a stock and create a new holding for the given user. Given a * stock symbol and quantity to purchase, retrieve the current quote price, * debit the user's account balance, and add holdings to user's portfolio. * buy/sell are asynchronous, using J2EE messaging, A new order is created * and submitted for processing to the TradeBroker * * @param userID * the customer requesting the stock purchase * @param symbol * the symbol of the stock being purchased * @param quantity * the quantity of shares to purchase * @return OrderDataBean providing the status of the newly created buy order */ OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception; /** * Sell a stock holding and removed the holding for the given user. Given a * Holding, retrieve current quote, credit user's account, and reduce * holdings in user's portfolio. * * @param userID * the customer requesting the sell * @param holdingID * the users holding to be sold * @return OrderDataBean providing the status of the newly created sell * order */ OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception; /** * Queue the Order identified by orderID to be processed * * Orders are submitted through JMS to a Trading Broker and completed * asynchronously. This method queues the order for processing * * The boolean twoPhase specifies to the server implementation whether or * not the method is to participate in a global transaction * * @param orderID * the Order being queued for processing * @return OrderDataBean providing the status of the completed order */ void queueOrder(Integer orderID, boolean twoPhase) throws Exception; /** * Complete the Order identefied by orderID Orders are submitted through JMS * to a Trading agent and completed asynchronously. This method completes * the order For a buy, the stock is purchased creating a holding and the * users account is debited For a sell, the stock holding is removed and the * users account is credited with the proceeds * * The boolean twoPhase specifies to the server implementation whether or * not the method is to participate in a global transaction * * @param orderID * the Order to complete * @return OrderDataBean providing the status of the completed order */ OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception; /** * Cancel the Order identefied by orderID * * The boolean twoPhase specifies to the server implementation whether or * not the method is to participate in a global transaction * * @param orderID * the Order to complete * @return OrderDataBean providing the status of the completed order */ void cancelOrder(Integer orderID, boolean twoPhase) throws Exception; /** * Signify an order has been completed for the given userID * * @param userID * the user for which an order has completed * @param orderID * the order which has completed * */ void orderCompleted(String userID, Integer orderID) throws Exception; /** * Get the collection of all orders for a given account * * @param userID * the customer account to retrieve orders for * @return Collection OrderDataBeans providing detailed order information */ Collection<?> getOrders(String userID) throws Exception; /** * Get the collection of completed orders for a given account that need to * be alerted to the user * * @param userID * the customer account to retrieve orders for * @return Collection OrderDataBeans providing detailed order information */ Collection<?> getClosedOrders(String userID) throws Exception; /** * Given a market symbol, price, and details, create and return a new * {@link QuoteDataBean} * * @param symbol * the symbol of the stock * @param price * the current stock price * @param details * a short description of the stock or company * @return a new QuoteDataBean or null if Quote could not be created */ QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) throws Exception; /** * Return a {@link QuoteDataBean} describing a current quote for the given * stock symbol * * @param symbol * the stock symbol to retrieve the current Quote * @return the QuoteDataBean */ QuoteDataBean getQuote(String symbol) throws Exception; /** * Return a {@link java.util.Collection} of {@link QuoteDataBean} describing * all current quotes * * @return A collection of QuoteDataBean */ Collection<?> getAllQuotes() throws Exception; /** * Update the stock quote price and volume for the specified stock symbol * * @param symbol * for stock quote to update * @param price * the updated quote price * @return the QuoteDataBean describing the stock */ QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal newPrice, double sharesTraded) throws Exception; /** * Return the portfolio of stock holdings for the specified customer as a * collection of HoldingDataBeans * * @param userID * the customer requesting the portfolio * @return Collection of the users portfolio of stock holdings */ Collection<?> getHoldings(String userID) throws Exception; /** * Return a specific user stock holding identifed by the holdingID * * @param holdingID * the holdingID to return * @return a HoldingDataBean describing the holding */ HoldingDataBean getHolding(Integer holdingID) throws Exception; /** * Return an AccountDataBean object for userID describing the account * * @param userID * the account userID to lookup * @return User account data in AccountDataBean */ AccountDataBean getAccountData(String userID) throws Exception; /** * Return an AccountProfileDataBean for userID providing the users profile * * @param userID * the account userID to lookup * @param User * account profile data in AccountProfileDataBean */ AccountProfileDataBean getAccountProfileData(String userID) throws Exception; /** * Update userID's account profile information using the provided * AccountProfileDataBean object * * @param userID * the account userID to lookup * @param User * account profile data in AccountProfileDataBean */ AccountProfileDataBean updateAccountProfile(AccountProfileDataBean profileData) throws Exception; /** * Attempt to authenticate and login a user with the given password * * @param userID * the customer to login * @param password * the password entered by the customer for authentication * @return User account data in AccountDataBean */ AccountDataBean login(String userID, String password) throws Exception; /** * Logout the given user * * @param userID * the customer to logout * @return the login status */ void logout(String userID) throws Exception; /** * Register a new Trade customer. Create a new user profile, user registry * entry, account with initial balance, and empty portfolio. * * @param userID * the new customer to register * @param password * the customers password * @param fullname * the customers fullname * @param address * the customers street address * @param email * the customers email address * @param creditcard * the customers creditcard number * @param initialBalance * the amount to charge to the customers credit to open the * account and set the initial balance * @return the userID if successful, null otherwise */ AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditcard, BigDecimal openBalance) throws Exception; /** * Reset the TradeData by - removing all newly registered users by scenario * servlet (i.e. users with userID's beginning with "ru:") * - removing all * buy/sell order pairs - setting logoutCount = loginCount * * return statistics for this benchmark run */ RunStatsDataBean resetTrade(boolean deleteAll) throws Exception; }
11,314
35.977124
150
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/beans/MarketSummaryDataBean.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.beans; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; public class MarketSummaryDataBean implements Serializable { private static final long serialVersionUID = 650652242288745600L; private BigDecimal TSIA; /* Trade Stock Index Average */ private BigDecimal openTSIA; /* Trade Stock Index Average at the open */ private double volume; /* volume of shares traded */ private Collection<QuoteDataBean> topGainers; /* * Collection of top gaining * stocks */ private Collection<QuoteDataBean> topLosers; /* * Collection of top losing * stocks */ // FUTURE private Collection topVolume; /* Collection of top stocks by // volume */ private Date summaryDate; /* Date this summary was taken */ // cache the gainPercent once computed for this bean private BigDecimal gainPercent = null; public MarketSummaryDataBean() { } public MarketSummaryDataBean(BigDecimal TSIA, BigDecimal openTSIA, double volume, Collection<QuoteDataBean> topGainers, Collection<QuoteDataBean> topLosers// , Collection topVolume ) { setTSIA(TSIA); setOpenTSIA(openTSIA); setVolume(volume); setTopGainers(topGainers); setTopLosers(topLosers); setSummaryDate(new java.sql.Date(System.currentTimeMillis())); gainPercent = FinancialUtils.computeGainPercent(getTSIA(), getOpenTSIA()); } public static MarketSummaryDataBean getRandomInstance() { Collection<QuoteDataBean> gain = new ArrayList<QuoteDataBean>(); Collection<QuoteDataBean> lose = new ArrayList<QuoteDataBean>(); for (int ii = 0; ii < 5; ii++) { QuoteDataBean quote1 = QuoteDataBean.getRandomInstance(); QuoteDataBean quote2 = QuoteDataBean.getRandomInstance(); gain.add(quote1); lose.add(quote2); } return new MarketSummaryDataBean(TradeConfig.rndBigDecimal(1000000.0f), TradeConfig.rndBigDecimal(1000000.0f), TradeConfig.rndQuantity(), gain, lose); } @Override public String toString() { String ret = "\n\tMarket Summary at: " + getSummaryDate() + "\n\t\t TSIA:" + getTSIA() + "\n\t\t openTSIA:" + getOpenTSIA() + "\n\t\t gain:" + getGainPercent() + "\n\t\t volume:" + getVolume(); if ((getTopGainers() == null) || (getTopLosers() == null)) { return ret; } ret += "\n\t\t Current Top Gainers:"; Iterator<QuoteDataBean> it = getTopGainers().iterator(); while (it.hasNext()) { QuoteDataBean quoteData = it.next(); ret += ("\n\t\t\t" + quoteData.toString()); } ret += "\n\t\t Current Top Losers:"; it = getTopLosers().iterator(); while (it.hasNext()) { QuoteDataBean quoteData = it.next(); ret += ("\n\t\t\t" + quoteData.toString()); } return ret; } public String toHTML() { String ret = "<BR>Market Summary at: " + getSummaryDate() + "<LI> TSIA:" + getTSIA() + "</LI>" + "<LI> openTSIA:" + getOpenTSIA() + "</LI>" + "<LI> volume:" + getVolume() + "</LI>"; if ((getTopGainers() == null) || (getTopLosers() == null)) { return ret; } ret += "<BR> Current Top Gainers:"; Iterator<QuoteDataBean> it = getTopGainers().iterator(); while (it.hasNext()) { QuoteDataBean quoteData = it.next(); ret += ("<LI>" + quoteData.toString() + "</LI>"); } ret += "<BR> Current Top Losers:"; it = getTopLosers().iterator(); while (it.hasNext()) { QuoteDataBean quoteData = it.next(); ret += ("<LI>" + quoteData.toString() + "</LI>"); } return ret; } public JsonObject toJSON() { JsonObjectBuilder jObjectBuilder = Json.createObjectBuilder(); int i = 1; for (Iterator<QuoteDataBean> iterator = topGainers.iterator(); iterator.hasNext();) { QuoteDataBean quote = iterator.next(); jObjectBuilder.add("gainer" + i + "_stock",quote.getSymbol()); jObjectBuilder.add("gainer" + i + "_price","$" + quote.getPrice()); jObjectBuilder.add("gainer" + i + "_change",quote.getChange()); i++; } i = 1; for (Iterator<QuoteDataBean> iterator = topLosers.iterator(); iterator.hasNext();) { QuoteDataBean quote = iterator.next(); jObjectBuilder.add("loser" + i + "_stock",quote.getSymbol()); jObjectBuilder.add("loser" + i + "_price","$" + quote.getPrice()); jObjectBuilder.add("loser" + i + "_change",quote.getChange()); i++; } jObjectBuilder.add("tsia", TSIA); jObjectBuilder.add("volume",volume); jObjectBuilder.add("date", summaryDate.toString()); return jObjectBuilder.build(); } public void print() { Log.log(this.toString()); } public BigDecimal getGainPercent() { if (gainPercent == null) { gainPercent = FinancialUtils.computeGainPercent(getTSIA(), getOpenTSIA()); } return gainPercent; } /** * Gets the tSIA * * @return Returns a BigDecimal */ public BigDecimal getTSIA() { return TSIA; } /** * Sets the tSIA * * @param tSIA * The tSIA to set */ public void setTSIA(BigDecimal tSIA) { TSIA = tSIA; } /** * Gets the openTSIA * * @return Returns a BigDecimal */ public BigDecimal getOpenTSIA() { return openTSIA; } /** * Sets the openTSIA * * @param openTSIA * The openTSIA to set */ public void setOpenTSIA(BigDecimal openTSIA) { this.openTSIA = openTSIA; } /** * Gets the volume * * @return Returns a BigDecimal */ public double getVolume() { return volume; } /** * Sets the volume * * @param volume * The volume to set */ public void setVolume(double volume) { this.volume = volume; } /** * Gets the topGainers * * @return Returns a Collection */ public Collection<QuoteDataBean> getTopGainers() { return topGainers; } /** * Sets the topGainers * * @param topGainers * The topGainers to set */ public void setTopGainers(Collection<QuoteDataBean> topGainers) { this.topGainers = topGainers; } /** * Gets the topLosers * * @return Returns a Collection */ public Collection<QuoteDataBean> getTopLosers() { return topLosers; } /** * Sets the topLosers * * @param topLosers * The topLosers to set */ public void setTopLosers(Collection<QuoteDataBean> topLosers) { this.topLosers = topLosers; } /** * Gets the summaryDate * * @return Returns a Date */ public Date getSummaryDate() { return summaryDate; } /** * Sets the summaryDate * * @param summaryDate * The summaryDate to set */ public void setSummaryDate(Date summaryDate) { this.summaryDate = summaryDate; } }
8,792
29.637631
184
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/beans/RunStatsDataBean.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.beans; import java.io.Serializable; public class RunStatsDataBean implements Serializable { private static final long serialVersionUID = 4017778674103242167L; // Constructors public RunStatsDataBean() { } // count of trade users in the database (users w/ userID like 'uid:%') private int tradeUserCount; // count of trade stocks in the database (stocks w/ symbol like 's:%') private int tradeStockCount; // count of new registered users in this run (users w/ userID like 'ru:%') // -- random user private int newUserCount; // sum of logins by trade users private int sumLoginCount; // sum of logouts by trade users private int sumLogoutCount; // count of holdings of trade users private int holdingCount; // count of orders of trade users private int orderCount; // count of buy orders of trade users private int buyOrderCount; // count of sell orders of trade users private int sellOrderCount; // count of cancelled orders of trade users private int cancelledOrderCount; // count of open orders of trade users private int openOrderCount; // count of orders deleted during this trade Reset private int deletedOrderCount; @Override public String toString() { return "\n\tRunStatsData for reset at " + new java.util.Date() + "\n\t\t tradeUserCount: " + getTradeUserCount() + "\n\t\t newUserCount: " + getNewUserCount() + "\n\t\t sumLoginCount: " + getSumLoginCount() + "\n\t\t sumLogoutCount: " + getSumLogoutCount() + "\n\t\t holdingCount: " + getHoldingCount() + "\n\t\t orderCount: " + getOrderCount() + "\n\t\t buyOrderCount: " + getBuyOrderCount() + "\n\t\t sellOrderCount: " + getSellOrderCount() + "\n\t\t cancelledOrderCount: " + getCancelledOrderCount() + "\n\t\t openOrderCount: " + getOpenOrderCount() + "\n\t\t deletedOrderCount: " + getDeletedOrderCount(); } /** * Gets the tradeUserCount * * @return Returns a int */ public int getTradeUserCount() { return tradeUserCount; } /** * Sets the tradeUserCount * * @param tradeUserCount * The tradeUserCount to set */ public void setTradeUserCount(int tradeUserCount) { this.tradeUserCount = tradeUserCount; } /** * Gets the newUserCount * * @return Returns a int */ public int getNewUserCount() { return newUserCount; } /** * Sets the newUserCount * * @param newUserCount * The newUserCount to set */ public void setNewUserCount(int newUserCount) { this.newUserCount = newUserCount; } /** * Gets the sumLoginCount * * @return Returns a int */ public int getSumLoginCount() { return sumLoginCount; } /** * Sets the sumLoginCount * * @param sumLoginCount * The sumLoginCount to set */ public void setSumLoginCount(int sumLoginCount) { this.sumLoginCount = sumLoginCount; } /** * Gets the sumLogoutCount * * @return Returns a int */ public int getSumLogoutCount() { return sumLogoutCount; } /** * Sets the sumLogoutCount * * @param sumLogoutCount * The sumLogoutCount to set */ public void setSumLogoutCount(int sumLogoutCount) { this.sumLogoutCount = sumLogoutCount; } /** * Gets the holdingCount * * @return Returns a int */ public int getHoldingCount() { return holdingCount; } /** * Sets the holdingCount * * @param holdingCount * The holdingCount to set */ public void setHoldingCount(int holdingCount) { this.holdingCount = holdingCount; } /** * Gets the buyOrderCount * * @return Returns a int */ public int getBuyOrderCount() { return buyOrderCount; } /** * Sets the buyOrderCount * * @param buyOrderCount * The buyOrderCount to set */ public void setBuyOrderCount(int buyOrderCount) { this.buyOrderCount = buyOrderCount; } /** * Gets the sellOrderCount * * @return Returns a int */ public int getSellOrderCount() { return sellOrderCount; } /** * Sets the sellOrderCount * * @param sellOrderCount * The sellOrderCount to set */ public void setSellOrderCount(int sellOrderCount) { this.sellOrderCount = sellOrderCount; } /** * Gets the cancelledOrderCount * * @return Returns a int */ public int getCancelledOrderCount() { return cancelledOrderCount; } /** * Sets the cancelledOrderCount * * @param cancelledOrderCount * The cancelledOrderCount to set */ public void setCancelledOrderCount(int cancelledOrderCount) { this.cancelledOrderCount = cancelledOrderCount; } /** * Gets the openOrderCount * * @return Returns a int */ public int getOpenOrderCount() { return openOrderCount; } /** * Sets the openOrderCount * * @param openOrderCount * The openOrderCount to set */ public void setOpenOrderCount(int openOrderCount) { this.openOrderCount = openOrderCount; } /** * Gets the deletedOrderCount * * @return Returns a int */ public int getDeletedOrderCount() { return deletedOrderCount; } /** * Sets the deletedOrderCount * * @param deletedOrderCount * The deletedOrderCount to set */ public void setDeletedOrderCount(int deletedOrderCount) { this.deletedOrderCount = deletedOrderCount; } /** * Gets the orderCount * * @return Returns a int */ public int getOrderCount() { return orderCount; } /** * Sets the orderCount * * @param orderCount * The orderCount to set */ public void setOrderCount(int orderCount) { this.orderCount = orderCount; } /** * Gets the tradeStockCount * * @return Returns a int */ public int getTradeStockCount() { return tradeStockCount; } /** * Sets the tradeStockCount * * @param tradeStockCount * The tradeStockCount to set */ public void setTradeStockCount(int tradeStockCount) { this.tradeStockCount = tradeStockCount; } }
7,402
24.094915
158
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/direct/KeySequenceDirect.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.direct; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import com.ibm.websphere.samples.daytrader.util.KeyBlock; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; public class KeySequenceDirect { private static HashMap<String, Collection<?>> keyMap = new HashMap<String, Collection<?>>(); public static synchronized Integer getNextID(Connection conn, String keyName, boolean inSession, boolean inGlobalTxn) throws Exception { Integer nextID = null; // First verify we have allocated a block of keys // for this key name // Then verify the allocated block has not been depleted // allocate a new block if necessary if (keyMap.containsKey(keyName) == false) { allocNewBlock(conn, keyName, inSession, inGlobalTxn); } Collection<?> block = keyMap.get(keyName); Iterator<?> ids = block.iterator(); if (ids.hasNext() == false) { ids = allocNewBlock(conn, keyName, inSession, inGlobalTxn).iterator(); } // get and return a new unique key nextID = (Integer) ids.next(); if (Log.doTrace()) { Log.trace("KeySequenceDirect:getNextID inSession(" + inSession + ") - return new PK ID for Entity type: " + keyName + " ID=" + nextID); } return nextID; } private static Collection<?> allocNewBlock(Connection conn, String keyName, boolean inSession, boolean inGlobalTxn) throws Exception { try { if (inGlobalTxn == false && !inSession) { conn.commit(); // commit any pending txns } PreparedStatement stmt = conn.prepareStatement(getKeyForUpdateSQL); stmt.setString(1, keyName); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { // No keys found for this name - create a new one PreparedStatement stmt2 = conn.prepareStatement(createKeySQL); int keyVal = 0; stmt2.setString(1, keyName); stmt2.setInt(2, keyVal); stmt2.executeUpdate(); stmt2.close(); stmt.close(); stmt = conn.prepareStatement(getKeyForUpdateSQL); stmt.setString(1, keyName); rs = stmt.executeQuery(); rs.next(); } int keyVal = rs.getInt("keyval"); stmt.close(); stmt = conn.prepareStatement(updateKeyValueSQL); stmt.setInt(1, keyVal + TradeConfig.KEYBLOCKSIZE); stmt.setString(2, keyName); stmt.executeUpdate(); stmt.close(); Collection<?> block = new KeyBlock(keyVal, keyVal + TradeConfig.KEYBLOCKSIZE - 1); keyMap.put(keyName, block); if (inGlobalTxn == false && !inSession) { conn.commit(); } return block; } catch (Exception e) { String error = "KeySequenceDirect:allocNewBlock - failure to allocate new block of keys for Entity type: " + keyName; Log.error(e, error); throw new Exception(error + e.toString()); } } private static final String getKeyForUpdateSQL = "select * from keygenejb kg where kg.keyname = ? for update"; private static final String createKeySQL = "insert into keygenejb " + "( keyname, keyval ) " + "VALUES ( ? , ? )"; private static final String updateKeyValueSQL = "update keygenejb set keyval = ? " + "where keyname = ?"; }
4,374
37.043478
147
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/direct/TradeDirect.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.direct; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import javax.enterprise.concurrent.ManagedThreadFactory; import javax.jms.ConnectionFactory; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.TextMessage; import javax.jms.Topic; import javax.naming.InitialContext; import javax.sql.DataSource; import javax.transaction.UserTransaction; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.TradeServices; import com.ibm.websphere.samples.daytrader.beans.MarketSummaryDataBean; import com.ibm.websphere.samples.daytrader.beans.RunStatsDataBean; import com.ibm.websphere.samples.daytrader.entities.AccountDataBean; import com.ibm.websphere.samples.daytrader.entities.AccountProfileDataBean; import com.ibm.websphere.samples.daytrader.entities.HoldingDataBean; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.CompleteOrderThread; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.MDBStats; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * TradeDirect uses direct JDBC and JMS access to a * <code>javax.sql.DataSource</code> to implement the business methods of the * Trade online broker application. These business methods represent the * features and operations that can be performed by customers of the brokerage * such as login, logout, get a stock quote, buy or sell a stock, etc. and are * specified in the {@link com.ibm.websphere.samples.daytrader.TradeServices} * interface * * Note: In order for this class to be thread-safe, a new TradeJDBC must be * created for each call to a method from the TradeInterface interface. * Otherwise, pooled connections may not be released. * * @see com.ibm.websphere.samples.daytrader.TradeServices * */ public class TradeDirect implements TradeServices { private static String dsName = TradeConfig.DATASOURCE; private static DataSource datasource = null; private static BigDecimal ZERO = new BigDecimal(0.0); private boolean inGlobalTxn = false; private boolean inSession = false; /** * Zero arg constructor for TradeDirect */ public TradeDirect() { if (initialized == false) { init(); } } public TradeDirect(boolean inSession) { if (initialized == false) { init(); } this.inSession = inSession; } /** * @see TradeServices#getMarketSummary() */ @Override public MarketSummaryDataBean getMarketSummary() throws Exception { MarketSummaryDataBean marketSummaryData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getMarketSummary - inSession(" + this.inSession + ")"); } conn = getConn(); PreparedStatement stmt = getStatement(conn, getTSIAQuotesOrderByChangeSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ArrayList<QuoteDataBean> topGainersData = new ArrayList<QuoteDataBean>(5); ArrayList<QuoteDataBean> topLosersData = new ArrayList<QuoteDataBean>(5); ResultSet rs = stmt.executeQuery(); int count = 0; while (rs.next() && (count++ < 5)) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topLosersData.add(quoteData); } stmt.close(); stmt = getStatement(conn, "select * from quoteejb q order by q.change1 DESC", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(); count = 0; while (rs.next() && (count++ < 5)) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topGainersData.add(quoteData); } /* * rs.last(); count = 0; while (rs.previous() && (count++ < 5) ) { * QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); * topGainersData.add(quoteData); } */ stmt.close(); BigDecimal TSIA = ZERO; BigDecimal openTSIA = ZERO; double volume = 0.0; if ((topGainersData.size() > 0) || (topLosersData.size() > 0)) { stmt = getStatement(conn, getTSIASQL); rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:getMarketSummary -- error w/ getTSIASQL -- no results"); } else { TSIA = rs.getBigDecimal("TSIA"); } stmt.close(); stmt = getStatement(conn, getOpenTSIASQL); rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:getMarketSummary -- error w/ getOpenTSIASQL -- no results"); } else { openTSIA = rs.getBigDecimal("openTSIA"); } stmt.close(); stmt = getStatement(conn, getTSIATotalVolumeSQL); rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:getMarketSummary -- error w/ getTSIATotalVolumeSQL -- no results"); } else { volume = rs.getDouble("totalVolume"); } stmt.close(); } commit(conn); marketSummaryData = new MarketSummaryDataBean(TSIA, openTSIA, volume, topGainersData, topLosersData); } catch (Exception e) { Log.error("TradeDirect:login -- error logging in user", e); rollBack(conn, e); } finally { releaseConn(conn); } return marketSummaryData; } /** * @see TradeServices#buy(String, String, double) */ @Override public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception { final Connection conn = getConn(); OrderDataBean orderData = null; UserTransaction txn = null; BigDecimal total; try { if (Log.doTrace()) { Log.trace("TradeDirect:buy - inSession(" + this.inSession + ")", userID, symbol, new Double(quantity)); } if (!inSession && orderProcessingMode == TradeConfig.ASYNCH_2PHASE) { if (Log.doTrace()) { Log.trace("TradeDirect:buy create/begin global transaction"); } // FUTURE the UserTransaction be looked up once txn = (javax.transaction.UserTransaction) context.lookup("java:comp/UserTransaction"); txn.begin(); setInGlobalTxn(true); } //conn = getConn(); AccountDataBean accountData = getAccountData(conn, userID); QuoteDataBean quoteData = getQuoteData(conn, symbol); HoldingDataBean holdingData = null; // the buy operation will create // the holding orderData = createOrder(conn, accountData, quoteData, holdingData, "buy", quantity); // Update -- account should be credited during completeOrder BigDecimal price = quoteData.getPrice(); BigDecimal orderFee = orderData.getOrderFee(); total = (new BigDecimal(quantity).multiply(price)).add(orderFee); // subtract total from account balance creditAccountBalance(conn, accountData, total.negate()); final Integer orderID = orderData.getOrderID(); try { if (orderProcessingMode == TradeConfig.SYNCH) { completeOrder(conn,orderID); } else { commit(conn); queueOrder(orderID, true); // 2-phase } } catch (JMSException je) { Log.error("TradeBean:buy(" + userID + "," + symbol + "," + quantity + ") --> failed to queueOrder", je); /* On exception - cancel the order */ cancelOrder(conn, orderData.getOrderID()); } orderData = getOrderData(conn, orderData.getOrderID().intValue()); if (txn != null) { if (Log.doTrace()) { Log.trace("TradeDirect:buy committing global transaction"); } txn.commit(); setInGlobalTxn(false); } else { commit(conn); } } catch (Exception e) { Log.error("TradeDirect:buy error - rolling back", e); if (getInGlobalTxn()) { txn.rollback(); } else { rollBack(conn, e); } } finally { releaseConn(conn); } return orderData; } /** * @see TradeServices#sell(String, Integer) */ @Override public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception { Connection conn = null; OrderDataBean orderData = null; UserTransaction txn = null; /* * total = (quantity * purchasePrice) + orderFee */ BigDecimal total; try { if (Log.doTrace()) { Log.trace("TradeDirect:sell - inSession(" + this.inSession + ")", userID, holdingID); } if (!inSession && orderProcessingMode == TradeConfig.ASYNCH_2PHASE) { if (Log.doTrace()) { Log.trace("TradeDirect:sell create/begin global transaction"); // FUTURE the UserTransaction be looked up once } txn = (javax.transaction.UserTransaction) context.lookup("java:comp/UserTransaction"); txn.begin(); setInGlobalTxn(true); } conn = getConn(); AccountDataBean accountData = getAccountData(conn, userID); HoldingDataBean holdingData = getHoldingData(conn, holdingID.intValue()); QuoteDataBean quoteData = null; if (holdingData != null) { quoteData = getQuoteData(conn, holdingData.getQuoteID()); } if ((accountData == null) || (holdingData == null) || (quoteData == null)) { String error = "TradeDirect:sell -- error selling stock -- unable to find: \n\taccount=" + accountData + "\n\tholding=" + holdingData + "\n\tquote=" + quoteData + "\nfor user: " + userID + " and holdingID: " + holdingID; Log.error(error); if (getInGlobalTxn()) { txn.rollback(); } else { rollBack(conn, new Exception(error)); } return orderData; } double quantity = holdingData.getQuantity(); orderData = createOrder(conn, accountData, quoteData, holdingData, "sell", quantity); // Set the holdingSymbol purchaseDate to selling to signify the sell // is "inflight" updateHoldingStatus(conn, holdingData.getHoldingID(), holdingData.getQuoteID()); // UPDATE -- account should be credited during completeOrder BigDecimal price = quoteData.getPrice(); BigDecimal orderFee = orderData.getOrderFee(); total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee); creditAccountBalance(conn, accountData, total); try { if (orderProcessingMode == TradeConfig.SYNCH) { completeOrder(conn, orderData.getOrderID()); } else { commit(conn); queueOrder(orderData.getOrderID(), true); } } catch (JMSException je) { Log.error("TradeBean:sell(" + userID + "," + holdingID + ") --> failed to queueOrder", je); /* On exception - cancel the order */ cancelOrder(conn, orderData.getOrderID()); } orderData = getOrderData(conn, orderData.getOrderID().intValue()); if (txn != null) { if (Log.doTrace()) { Log.trace("TradeDirect:sell committing global transaction"); } txn.commit(); setInGlobalTxn(false); } else { commit(conn); } } catch (Exception e) { Log.error("TradeDirect:sell error", e); if (getInGlobalTxn()) { txn.rollback(); } else { rollBack(conn, e); } } finally { releaseConn(conn); } return orderData; } /** * @see TradeServices#queueOrder(Integer) */ @Override public void queueOrder(Integer orderID, boolean twoPhase) throws Exception { if (Log.doTrace()) { Log.trace("TradeDirect:queueOrder - inSession(" + this.inSession + ")", orderID); } if (TradeConfig.getOrderProcessingMode() == TradeConfig.ASYNCH_MANAGEDTHREAD) { try { //TODO: Do I need this lookup every time? ManagedThreadFactory managedThreadFactory = (ManagedThreadFactory) context.lookup("java:comp/DefaultManagedThreadFactory"); Thread thread = managedThreadFactory.newThread(new CompleteOrderThread(orderID, twoPhase)); thread.start(); } catch (Exception e) { e.printStackTrace(); } } else { try (JMSContext context = qConnFactory.createContext();){ TextMessage message = context.createTextMessage(); message.setStringProperty("command", "neworder"); message.setIntProperty("orderID", orderID.intValue()); message.setBooleanProperty("twoPhase", twoPhase); message.setBooleanProperty("direct", true); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("neworder: orderID=" + orderID + " runtimeMode=Direct twoPhase=" + twoPhase); context.createProducer().send(brokerQueue, message); } catch (Exception e) { throw e; // pass the exception } } } /** * @see TradeServices#completeOrder(Integer) */ @Override public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception { OrderDataBean orderData = null; Connection conn = null; try { // twoPhase if (Log.doTrace()) { Log.trace("TradeDirect:completeOrder - inSession(" + this.inSession + ")", orderID); } setInGlobalTxn(!inSession && twoPhase); conn = getConn(); orderData = completeOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:completeOrder -- error completing order", e); rollBack(conn, e); cancelOrder(orderID, twoPhase); } finally { releaseConn(conn); } return orderData; } private OrderDataBean completeOrder(Connection conn, Integer orderID) throws Exception { //conn = getConn(); OrderDataBean orderData = null; if (Log.doTrace()) { Log.trace("TradeDirect:completeOrderInternal - inSession(" + this.inSession + ")", orderID); } PreparedStatement stmt = getStatement(conn, getOrderSQL); stmt.setInt(1, orderID.intValue()); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:completeOrder -- unable to find order: " + orderID); stmt.close(); return orderData; } orderData = getOrderDataFromResultSet(rs); String orderType = orderData.getOrderType(); String orderStatus = orderData.getOrderStatus(); // if (order.isCompleted()) if ((orderStatus.compareToIgnoreCase("completed") == 0) || (orderStatus.compareToIgnoreCase("alertcompleted") == 0) || (orderStatus.compareToIgnoreCase("cancelled") == 0)) { throw new Exception("TradeDirect:completeOrder -- attempt to complete Order that is already completed"); } int accountID = rs.getInt("account_accountID"); String quoteID = rs.getString("quote_symbol"); int holdingID = rs.getInt("holding_holdingID"); BigDecimal price = orderData.getPrice(); double quantity = orderData.getQuantity(); // get the data for the account and quote // the holding will be created for a buy or extracted for a sell /* * Use the AccountID and Quote Symbol from the Order AccountDataBean * accountData = getAccountData(accountID, conn); QuoteDataBean * quoteData = getQuoteData(conn, quoteID); */ String userID = getAccountProfileData(conn, new Integer(accountID)).getUserID(); HoldingDataBean holdingData = null; if (Log.doTrace()) { Log.trace("TradeDirect:completeOrder--> Completing Order " + orderData.getOrderID() + "\n\t Order info: " + orderData + "\n\t Account info: " + accountID + "\n\t Quote info: " + quoteID); } // if (order.isBuy()) if (orderType.compareToIgnoreCase("buy") == 0) { /* * Complete a Buy operation - create a new Holding for the Account - * deduct the Order cost from the Account balance */ holdingData = createHolding(conn, accountID, quoteID, quantity, price); updateOrderHolding(conn, orderID.intValue(), holdingData.getHoldingID().intValue()); } // if (order.isSell()) { if (orderType.compareToIgnoreCase("sell") == 0) { /* * Complete a Sell operation - remove the Holding from the Account - * deposit the Order proceeds to the Account balance */ holdingData = getHoldingData(conn, holdingID); if (holdingData == null) { Log.debug("TradeDirect:completeOrder:sell -- user: " + userID + " already sold holding: " + holdingID); } else { removeHolding(conn, holdingID, orderID.intValue()); } } updateOrderStatus(conn, orderData.getOrderID(), "closed"); if (Log.doTrace()) { Log.trace("TradeDirect:completeOrder--> Completed Order " + orderData.getOrderID() + "\n\t Order info: " + orderData + "\n\t Account info: " + accountID + "\n\t Quote info: " + quoteID + "\n\t Holding info: " + holdingData); } stmt.close(); commit(conn); // commented out following call // - orderCompleted doesn't really do anything (think it was a hook for // old Trade caching code) // signify this order for user userID is complete // This call does not work here for Sync if (TradeConfig.orderProcessingMode != TradeConfig.SYNCH) { TradeAction tradeAction = new TradeAction(this); tradeAction.orderCompleted(userID, orderID); } return orderData; } /** * @see TradeServices#cancelOrder(Integer, boolean) */ @Override public void cancelOrder(Integer orderID, boolean twoPhase) throws Exception { Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:cancelOrder - inSession(" + this.inSession + ")", orderID); } setInGlobalTxn(!inSession && twoPhase); conn = getConn(); cancelOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:cancelOrder -- error cancelling order: " + orderID, e); rollBack(conn, e); } finally { releaseConn(conn); } } private void cancelOrder(Connection conn, Integer orderID) throws Exception { updateOrderStatus(conn, orderID, "cancelled"); } @Override public void orderCompleted(String userID, Integer orderID) throws Exception { throw new UnsupportedOperationException("TradeDirect:orderCompleted method not supported"); } private HoldingDataBean createHolding(Connection conn, int accountID, String symbol, double quantity, BigDecimal purchasePrice) throws Exception { Timestamp purchaseDate = new Timestamp(System.currentTimeMillis()); PreparedStatement stmt = getStatement(conn, createHoldingSQL); Integer holdingID = KeySequenceDirect.getNextID(conn, "holding", inSession, getInGlobalTxn()); stmt.setInt(1, holdingID.intValue()); stmt.setTimestamp(2, purchaseDate); stmt.setBigDecimal(3, purchasePrice); stmt.setDouble(4, quantity); stmt.setString(5, symbol); stmt.setInt(6, accountID); stmt.executeUpdate(); stmt.close(); return getHoldingData(conn, holdingID.intValue()); } private void removeHolding(Connection conn, int holdingID, int orderID) throws Exception { PreparedStatement stmt = getStatement(conn, removeHoldingSQL); stmt.setInt(1, holdingID); stmt.executeUpdate(); stmt.close(); // set the HoldingID to NULL for the purchase and sell order now that // the holding as been removed stmt = getStatement(conn, removeHoldingFromOrderSQL); stmt.setInt(1, holdingID); stmt.executeUpdate(); stmt.close(); } private OrderDataBean createOrder(Connection conn, AccountDataBean accountData, QuoteDataBean quoteData, HoldingDataBean holdingData, String orderType, double quantity) throws Exception { Timestamp currentDate = new Timestamp(System.currentTimeMillis()); PreparedStatement stmt = getStatement(conn, createOrderSQL); Integer orderID = KeySequenceDirect.getNextID(conn, "order", inSession, getInGlobalTxn()); stmt.setInt(1, orderID.intValue()); stmt.setString(2, orderType); stmt.setString(3, "open"); stmt.setTimestamp(4, currentDate); stmt.setDouble(5, quantity); stmt.setBigDecimal(6, quoteData.getPrice().setScale(FinancialUtils.SCALE, FinancialUtils.ROUND)); stmt.setBigDecimal(7, TradeConfig.getOrderFee(orderType)); stmt.setInt(8, accountData.getAccountID().intValue()); if (holdingData == null) { stmt.setNull(9, java.sql.Types.INTEGER); } else { stmt.setInt(9, holdingData.getHoldingID().intValue()); } stmt.setString(10, quoteData.getSymbol()); stmt.executeUpdate(); stmt.close(); return getOrderData(conn, orderID.intValue()); } /** * @see TradeServices#getOrders(String) */ @Override public Collection<OrderDataBean> getOrders(String userID) throws Exception { Collection<OrderDataBean> orderDataBeans = new ArrayList<OrderDataBean>(); Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getOrders - inSession(" + this.inSession + ")", userID); } conn = getConn(); PreparedStatement stmt = getStatement(conn, getOrdersByUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); // TODO: return top 5 orders for now -- next version will add a // getAllOrders method // also need to get orders sorted by order id descending int i = 0; while ((rs.next()) && (i++ < 5)) { OrderDataBean orderData = getOrderDataFromResultSet(rs); orderDataBeans.add(orderData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getOrders -- error getting user orders", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderDataBeans; } /** * @see TradeServices#getClosedOrders(String) */ @Override public Collection<OrderDataBean> getClosedOrders(String userID) throws Exception { Collection<OrderDataBean> orderDataBeans = new ArrayList<OrderDataBean>(); Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getClosedOrders - inSession(" + this.inSession + ")", userID); } conn = getConn(); PreparedStatement stmt = getStatement(conn, getClosedOrdersSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { OrderDataBean orderData = getOrderDataFromResultSet(rs); orderData.setOrderStatus("completed"); updateOrderStatus(conn, orderData.getOrderID(), orderData.getOrderStatus()); orderDataBeans.add(orderData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getOrders -- error getting user orders", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderDataBeans; } /** * @see TradeServices#createQuote(String, String, BigDecimal) */ @Override public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) throws Exception { QuoteDataBean quoteData = null; Connection conn = null; try { if (Log.doTrace()) { Log.traceEnter("TradeDirect:createQuote - inSession(" + this.inSession + ")"); } price = price.setScale(FinancialUtils.SCALE, FinancialUtils.ROUND); double volume = 0.0, change = 0.0; conn = getConn(); PreparedStatement stmt = getStatement(conn, createQuoteSQL); stmt.setString(1, symbol); // symbol stmt.setString(2, companyName); // companyName stmt.setDouble(3, volume); // volume stmt.setBigDecimal(4, price); // price stmt.setBigDecimal(5, price); // open stmt.setBigDecimal(6, price); // low stmt.setBigDecimal(7, price); // high stmt.setDouble(8, change); // change stmt.executeUpdate(); stmt.close(); commit(conn); quoteData = new QuoteDataBean(symbol, companyName, volume, price, price, price, price, change); if (Log.doTrace()) { Log.traceExit("TradeDirect:createQuote"); } } catch (Exception e) { Log.error("TradeDirect:createQuote -- error creating quote", e); } finally { releaseConn(conn); } return quoteData; } /** * @see TradeServices#getQuote(String) */ @Override public QuoteDataBean getQuote(String symbol) throws Exception { QuoteDataBean quoteData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getQuote - inSession(" + this.inSession + ")", symbol); } conn = getConn(); quoteData = getQuote(conn, symbol); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getQuote -- error getting quote", e); rollBack(conn, e); } finally { releaseConn(conn); } return quoteData; } private QuoteDataBean getQuote(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteSQL); stmt.setString(1, symbol); // symbol ResultSet rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:getQuote -- failure no result.next() for symbol: " + symbol); } else { quoteData = getQuoteDataFromResultSet(rs); } stmt.close(); return quoteData; } private QuoteDataBean getQuoteForUpdate(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteForUpdateSQL); stmt.setString(1, symbol); // symbol ResultSet rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:getQuote -- failure no result.next()"); } else { quoteData = getQuoteDataFromResultSet(rs); } stmt.close(); return quoteData; } /** * @see TradeServices#getAllQuotes(String) */ @Override public Collection<QuoteDataBean> getAllQuotes() throws Exception { Collection<QuoteDataBean> quotes = new ArrayList<QuoteDataBean>(); QuoteDataBean quoteData = null; Connection conn = null; try { conn = getConn(); PreparedStatement stmt = getStatement(conn, getAllQuotesSQL); ResultSet rs = stmt.executeQuery(); while (!rs.next()) { quoteData = getQuoteDataFromResultSet(rs); quotes.add(quoteData); } stmt.close(); } catch (Exception e) { Log.error("TradeDirect:getAllQuotes", e); rollBack(conn, e); } finally { releaseConn(conn); } return quotes; } /** * @see TradeServices#getHoldings(String) */ @Override public Collection<HoldingDataBean> getHoldings(String userID) throws Exception { Collection<HoldingDataBean> holdingDataBeans = new ArrayList<HoldingDataBean>(); Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getHoldings - inSession(" + this.inSession + ")", userID); } conn = getConn(); PreparedStatement stmt = getStatement(conn, getHoldingsForUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { HoldingDataBean holdingData = getHoldingDataFromResultSet(rs); holdingDataBeans.add(holdingData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getHoldings -- error getting user holings", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingDataBeans; } /** * @see TradeServices#getHolding(Integer) */ @Override public HoldingDataBean getHolding(Integer holdingID) throws Exception { HoldingDataBean holdingData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getHolding - inSession(" + this.inSession + ")", holdingID); } conn = getConn(); holdingData = getHoldingData(holdingID.intValue()); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getHolding -- error getting holding " + holdingID + "", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingData; } /** * @see TradeServices#getAccountData(String) */ @Override public AccountDataBean getAccountData(String userID) throws Exception { try { AccountDataBean accountData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getAccountData - inSession(" + this.inSession + ")", userID); } conn = getConn(); accountData = getAccountData(conn, userID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountData -- error getting account data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; } catch (Exception e) { throw new Exception(e.getMessage(), e); } } private AccountDataBean getAccountData(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } /*private AccountDataBean getAccountDataForUpdate(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUserForUpdateSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; }*/ /** * @see TradeServices#getAccountData(String) */ public AccountDataBean getAccountData(int accountID) throws Exception { AccountDataBean accountData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getAccountData - inSession(" + this.inSession + ")", new Integer(accountID)); } conn = getConn(); accountData = getAccountData(accountID, conn); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountData -- error getting account data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; } private AccountDataBean getAccountData(int accountID, Connection conn) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountSQL); stmt.setInt(1, accountID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } /* private AccountDataBean getAccountDataForUpdate(int accountID, Connection conn) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUpdateSQL); stmt.setInt(1, accountID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } */ /* private QuoteDataBean getQuoteData(String symbol) throws Exception { QuoteDataBean quoteData = null; Connection conn = null; try { conn = getConn(); quoteData = getQuoteData(conn, symbol); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getQuoteData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return quoteData; } */ private QuoteDataBean getQuoteData(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteSQL); stmt.setString(1, symbol); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:getQuoteData -- could not find quote for symbol=" + symbol); } else { quoteData = getQuoteDataFromResultSet(rs); } stmt.close(); return quoteData; } private HoldingDataBean getHoldingData(int holdingID) throws Exception { HoldingDataBean holdingData = null; Connection conn = null; try { conn = getConn(); holdingData = getHoldingData(conn, holdingID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getHoldingData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingData; } private HoldingDataBean getHoldingData(Connection conn, int holdingID) throws Exception { HoldingDataBean holdingData = null; PreparedStatement stmt = getStatement(conn, getHoldingSQL); stmt.setInt(1, holdingID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:getHoldingData -- no results -- holdingID=" + holdingID); } else { holdingData = getHoldingDataFromResultSet(rs); } stmt.close(); return holdingData; } /* private OrderDataBean getOrderData(int orderID) throws Exception { OrderDataBean orderData = null; Connection conn = null; try { conn = getConn(); orderData = getOrderData(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getOrderData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderData; } */ private OrderDataBean getOrderData(Connection conn, int orderID) throws Exception { OrderDataBean orderData = null; if (Log.doTrace()) { Log.trace("TradeDirect:getOrderData(conn, " + orderID + ")"); } PreparedStatement stmt = getStatement(conn, getOrderSQL); stmt.setInt(1, orderID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:getOrderData -- no results for orderID:" + orderID); } else { orderData = getOrderDataFromResultSet(rs); } stmt.close(); return orderData; } /** * @see TradeServices#getAccountProfileData(String) */ @Override public AccountProfileDataBean getAccountProfileData(String userID) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getAccountProfileData - inSession(" + this.inSession + ")", userID); } conn = getConn(); accountProfileData = getAccountProfileData(conn, userID); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private AccountProfileDataBean getAccountProfileData(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountProfileSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountProfileDataBean accountProfileData = getAccountProfileDataFromResultSet(rs); stmt.close(); return accountProfileData; } /* private AccountProfileDataBean getAccountProfileData(Integer accountID) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:getAccountProfileData", accountID); } conn = getConn(); accountProfileData = getAccountProfileData(conn, accountID); commit(conn); } catch (Exception e) { Log.error( "TradeDirect:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } */ private AccountProfileDataBean getAccountProfileData(Connection conn, Integer accountID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountProfileForAccountSQL); stmt.setInt(1, accountID.intValue()); ResultSet rs = stmt.executeQuery(); AccountProfileDataBean accountProfileData = getAccountProfileDataFromResultSet(rs); stmt.close(); return accountProfileData; } /** * @see TradeServices#updateAccountProfile(AccountProfileDataBean) */ @Override public AccountProfileDataBean updateAccountProfile(AccountProfileDataBean profileData) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:updateAccountProfileData - inSession(" + this.inSession + ")", profileData.getUserID()); } conn = getConn(); updateAccountProfile(conn, profileData); accountProfileData = getAccountProfileData(conn, profileData.getUserID()); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private void creditAccountBalance(Connection conn, AccountDataBean accountData, BigDecimal credit) throws Exception { PreparedStatement stmt = getStatement(conn, creditAccountBalanceSQL); stmt.setBigDecimal(1, credit); stmt.setInt(2, accountData.getAccountID().intValue()); stmt.executeUpdate(); stmt.close(); } // Set Timestamp to zero to denote sell is inflight // UPDATE -- could add a "status" attribute to holding private void updateHoldingStatus(Connection conn, Integer holdingID, String symbol) throws Exception { Timestamp ts = new Timestamp(0); PreparedStatement stmt = getStatement(conn, "update holdingejb set purchasedate= ? where holdingid = ?"); stmt.setTimestamp(1, ts); stmt.setInt(2, holdingID.intValue()); stmt.executeUpdate(); stmt.close(); } private void updateOrderStatus(Connection conn, Integer orderID, String status) throws Exception { PreparedStatement stmt = getStatement(conn, updateOrderStatusSQL); stmt.setString(1, status); stmt.setTimestamp(2, new Timestamp(System.currentTimeMillis())); stmt.setInt(3, orderID.intValue()); stmt.executeUpdate(); stmt.close(); } private void updateOrderHolding(Connection conn, int orderID, int holdingID) throws Exception { PreparedStatement stmt = getStatement(conn, updateOrderHoldingSQL); stmt.setInt(1, holdingID); stmt.setInt(2, orderID); stmt.executeUpdate(); stmt.close(); } private void updateAccountProfile(Connection conn, AccountProfileDataBean profileData) throws Exception { PreparedStatement stmt = getStatement(conn, updateAccountProfileSQL); stmt.setString(1, profileData.getPassword()); stmt.setString(2, profileData.getFullName()); stmt.setString(3, profileData.getAddress()); stmt.setString(4, profileData.getEmail()); stmt.setString(5, profileData.getCreditCard()); stmt.setString(6, profileData.getUserID()); stmt.executeUpdate(); stmt.close(); } /* private void updateQuoteVolume(Connection conn, QuoteDataBean quoteData, double quantity) throws Exception { PreparedStatement stmt = getStatement(conn, updateQuoteVolumeSQL); stmt.setDouble(1, quantity); stmt.setString(2, quoteData.getSymbol()); stmt.executeUpdate(); stmt.close(); } */ @Override public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) throws Exception { return updateQuotePriceVolumeInt(symbol, changeFactor, sharesTraded, TradeConfig.getPublishQuotePriceChange()); } /** * Update a quote's price and volume * * @param symbol * The PK of the quote * @param changeFactor * the percent to change the old price by (between 50% and 150%) * @param sharedTraded * the ammount to add to the current volume * @param publishQuotePriceChange * used by the PingJDBCWrite Primitive to ensure no JMS is used, * should be true for all normal calls to this API */ public QuoteDataBean updateQuotePriceVolumeInt(String symbol, BigDecimal changeFactor, double sharesTraded, boolean publishQuotePriceChange) throws Exception { if (TradeConfig.getUpdateQuotePrices() == false) { return new QuoteDataBean(); } QuoteDataBean quoteData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:updateQuotePriceVolume - inSession(" + this.inSession + ")", symbol, changeFactor, new Double(sharesTraded)); } conn = getConn(); quoteData = getQuoteForUpdate(conn, symbol); BigDecimal oldPrice = quoteData.getPrice(); BigDecimal openPrice = quoteData.getOpen(); double newVolume = quoteData.getVolume() + sharesTraded; if (oldPrice.equals(TradeConfig.PENNY_STOCK_PRICE)) { changeFactor = TradeConfig.PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER; } else if (oldPrice.compareTo(TradeConfig.MAXIMUM_STOCK_PRICE) > 0) { changeFactor = TradeConfig.MAXIMUM_STOCK_SPLIT_MULTIPLIER; } BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP); double change = newPrice.subtract(openPrice).doubleValue(); updateQuotePriceVolume(conn, quoteData.getSymbol(), newPrice, newVolume, change); quoteData = getQuote(conn, symbol); commit(conn); if (publishQuotePriceChange) { publishQuotePriceChange(quoteData, oldPrice, changeFactor, sharesTraded); } } catch (Exception e) { Log.error("TradeDirect:updateQuotePriceVolume -- error updating quote price/volume for symbol:" + symbol); rollBack(conn, e); throw e; } finally { releaseConn(conn); } return quoteData; } private void updateQuotePriceVolume(Connection conn, String symbol, BigDecimal newPrice, double newVolume, double change) throws Exception { PreparedStatement stmt = getStatement(conn, updateQuotePriceVolumeSQL); stmt.setBigDecimal(1, newPrice); stmt.setDouble(2, change); stmt.setDouble(3, newVolume); stmt.setString(4, symbol); stmt.executeUpdate(); stmt.close(); } private void publishQuotePriceChange(QuoteDataBean quoteData, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded) throws Exception { if (Log.doTrace()) { Log.trace("TradeDirect:publishQuotePrice PUBLISHING to MDB quoteData = " + quoteData); } try (JMSContext context = tConnFactory.createContext();){ TextMessage message = context.createTextMessage(); message.setStringProperty("command", "updateQuote"); message.setStringProperty("symbol", quoteData.getSymbol()); message.setStringProperty("company", quoteData.getCompanyName()); message.setStringProperty("price", quoteData.getPrice().toString()); message.setStringProperty("oldPrice", oldPrice.toString()); message.setStringProperty("open", quoteData.getOpen().toString()); message.setStringProperty("low", quoteData.getLow().toString()); message.setStringProperty("high", quoteData.getHigh().toString()); message.setDoubleProperty("volume", quoteData.getVolume()); message.setStringProperty("changeFactor", changeFactor.toString()); message.setDoubleProperty("sharesTraded", sharesTraded); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("Update Stock price for " + quoteData.getSymbol() + " old price = " + oldPrice + " new price = " + quoteData.getPrice()); context.createProducer().send(streamerTopic, message); } catch (Exception e) { throw e; // pass exception back } } /** * @see TradeServices#login(String, String) */ @Override public AccountDataBean login(String userID, String password) throws Exception { AccountDataBean accountData = null; Connection conn = null; try { if (Log.doTrace()) { Log.trace("TradeDirect:login - inSession(" + this.inSession + ")", userID, password); } conn = getConn(); PreparedStatement stmt = getStatement(conn, getAccountProfileSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeDirect:login -- failure to find account for" + userID); throw new javax.ejb.FinderException("Cannot find account for" + userID); } String pw = rs.getString("passwd"); stmt.close(); if ((pw == null) || (pw.equals(password) == false)) { String error = "TradeDirect:Login failure for user: " + userID + "\n\tIncorrect password-->" + userID + ":" + password; Log.error(error); throw new Exception(error); } stmt = getStatement(conn, loginSQL); stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis())); stmt.setString(2, userID); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, getAccountForUserSQL); stmt.setString(1, userID); rs = stmt.executeQuery(); accountData = getAccountDataFromResultSet(rs); stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:login -- error logging in user", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; /* * setLastLogin( new Timestamp(System.currentTimeMillis()) ); * setLoginCount( getLoginCount() + 1 ); */ } /** * @see TradeServices#logout(String) */ @Override public void logout(String userID) throws Exception { if (Log.doTrace()) { Log.trace("TradeDirect:logout - inSession(" + this.inSession + ")", userID); } Connection conn = null; try { conn = getConn(); PreparedStatement stmt = getStatement(conn, logoutSQL); stmt.setString(1, userID); stmt.executeUpdate(); stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeDirect:logout -- error logging out user", e); rollBack(conn, e); } finally { releaseConn(conn); } } /** * @see TradeServices#register(String, String, String, String, String, * String, BigDecimal, boolean) */ @Override public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditcard, BigDecimal openBalance) throws Exception { AccountDataBean accountData = null; Connection conn = null; try { if (Log.doTrace()) { Log.traceEnter("TradeDirect:register - inSession(" + this.inSession + ")"); } conn = getConn(); PreparedStatement stmt = getStatement(conn, createAccountSQL); Integer accountID = KeySequenceDirect.getNextID(conn, "account", inSession, getInGlobalTxn()); BigDecimal balance = openBalance; Timestamp creationDate = new Timestamp(System.currentTimeMillis()); Timestamp lastLogin = creationDate; int loginCount = 0; int logoutCount = 0; stmt.setInt(1, accountID.intValue()); stmt.setTimestamp(2, creationDate); stmt.setBigDecimal(3, openBalance); stmt.setBigDecimal(4, balance); stmt.setTimestamp(5, lastLogin); stmt.setInt(6, loginCount); stmt.setInt(7, logoutCount); stmt.setString(8, userID); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, createAccountProfileSQL); stmt.setString(1, userID); stmt.setString(2, password); stmt.setString(3, fullname); stmt.setString(4, address); stmt.setString(5, email); stmt.setString(6, creditcard); stmt.executeUpdate(); stmt.close(); commit(conn); accountData = new AccountDataBean(accountID, loginCount, logoutCount, lastLogin, creationDate, balance, openBalance, userID); if (Log.doTrace()) { Log.traceExit("TradeDirect:register"); } } catch (Exception e) { Log.error("TradeDirect:register -- error registering new user", e); } finally { releaseConn(conn); } return accountData; } private AccountDataBean getAccountDataFromResultSet(ResultSet rs) throws Exception { AccountDataBean accountData = null; if (!rs.next()) { Log.error("TradeDirect:getAccountDataFromResultSet -- cannot find account data"); } else { accountData = new AccountDataBean(new Integer(rs.getInt("accountID")), rs.getInt("loginCount"), rs.getInt("logoutCount"), rs.getTimestamp("lastLogin"), rs.getTimestamp("creationDate"), rs.getBigDecimal("balance"), rs.getBigDecimal("openBalance"), rs.getString("profile_userID")); } return accountData; } private AccountProfileDataBean getAccountProfileDataFromResultSet(ResultSet rs) throws Exception { AccountProfileDataBean accountProfileData = null; if (!rs.next()) { Log.error("TradeDirect:getAccountProfileDataFromResultSet -- cannot find accountprofile data"); } else { accountProfileData = new AccountProfileDataBean(rs.getString("userID"), rs.getString("passwd"), rs.getString("fullName"), rs.getString("address"), rs.getString("email"), rs.getString("creditCard")); } return accountProfileData; } private HoldingDataBean getHoldingDataFromResultSet(ResultSet rs) throws Exception { HoldingDataBean holdingData = null; holdingData = new HoldingDataBean(new Integer(rs.getInt("holdingID")), rs.getDouble("quantity"), rs.getBigDecimal("purchasePrice"), rs.getTimestamp("purchaseDate"), rs.getString("quote_symbol")); return holdingData; } private QuoteDataBean getQuoteDataFromResultSet(ResultSet rs) throws Exception { QuoteDataBean quoteData = null; quoteData = new QuoteDataBean(rs.getString("symbol"), rs.getString("companyName"), rs.getDouble("volume"), rs.getBigDecimal("price"), rs.getBigDecimal("open1"), rs.getBigDecimal("low"), rs.getBigDecimal("high"), rs.getDouble("change1")); return quoteData; } private OrderDataBean getOrderDataFromResultSet(ResultSet rs) throws Exception { OrderDataBean orderData = null; orderData = new OrderDataBean(new Integer(rs.getInt("orderID")), rs.getString("orderType"), rs.getString("orderStatus"), rs.getTimestamp("openDate"), rs.getTimestamp("completionDate"), rs.getDouble("quantity"), rs.getBigDecimal("price"), rs.getBigDecimal("orderFee"), rs.getString("quote_symbol")); return orderData; } public String checkDBProductName() throws Exception { Connection conn = null; String dbProductName = null; try { if (Log.doTrace()) { Log.traceEnter("TradeDirect:checkDBProductName"); } conn = getConn(); DatabaseMetaData dbmd = conn.getMetaData(); dbProductName = dbmd.getDatabaseProductName(); } catch (SQLException e) { Log.error(e, "TradeDirect:checkDBProductName() -- Error checking the Daytrader Database Product Name"); } finally { releaseConn(conn); } return dbProductName; } public boolean recreateDBTables(Object[] sqlBuffer, java.io.PrintWriter out) throws Exception { // Clear MDB Statistics MDBStats.getInstance().reset(); Connection conn = null; boolean success = false; try { if (Log.doTrace()) { Log.traceEnter("TradeDirect:recreateDBTables"); } conn = getConn(); Statement stmt = conn.createStatement(); int bufferLength = sqlBuffer.length; for (int i = 0; i < bufferLength; i++) { try { stmt.executeUpdate((String) sqlBuffer[i]); // commit(conn); } catch (SQLException ex) { // Ignore DROP statements as tables won't always exist. if (((String) sqlBuffer[i]).indexOf("DROP ") < 0) { Log.error("TradeDirect:recreateDBTables SQL Exception thrown on executing the foll sql command: " + sqlBuffer[i], ex); out.println("<BR>SQL Exception thrown on executing the foll sql command: <I>" + sqlBuffer[i] + "</I> . Check log for details.</BR>"); } } } stmt.close(); commit(conn); success = true; } catch (Exception e) { Log.error(e, "TradeDirect:recreateDBTables() -- Error dropping and recreating the database tables"); } finally { releaseConn(conn); } return success; } @Override public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception { // Clear MDB Statistics MDBStats.getInstance().reset(); // Reset Trade RunStatsDataBean runStatsData = new RunStatsDataBean(); Connection conn = null; try { if (Log.doTrace()) { Log.traceEnter("TradeDirect:resetTrade deleteAll rows=" + deleteAll); } conn = getConn(); PreparedStatement stmt = null; ResultSet rs = null; if (deleteAll) { try { stmt = getStatement(conn, "delete from quoteejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from accountejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from accountprofileejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from holdingejb"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from orderejb"); stmt.executeUpdate(); stmt.close(); // FUTURE: - DuplicateKeyException - For now, don't start at // zero as KeySequenceDirect and KeySequenceBean will still // give out // the cached Block and then notice this change. Better // solution is // to signal both classes to drop their cached blocks // stmt = getStatement(conn, "delete from keygenejb"); // stmt.executeUpdate(); // stmt.close(); commit(conn); } catch (Exception e) { Log.error(e, "TradeDirect:resetTrade(deleteAll) -- Error deleting Trade users and stock from the Trade database"); } return runStatsData; } stmt = getStatement(conn, "delete from holdingejb where holdingejb.account_accountid is null"); stmt.executeUpdate(); stmt.close(); // Count and Delete newly registered users (users w/ id that start // "ru:%": stmt = getStatement(conn, "delete from accountprofileejb where userid like 'ru:%'"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from orderejb where account_accountid in (select accountid from accountejb a where a.profile_userid like 'ru:%')"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from holdingejb where account_accountid in (select accountid from accountejb a where a.profile_userid like 'ru:%')"); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, "delete from accountejb where profile_userid like 'ru:%'"); int newUserCount = stmt.executeUpdate(); runStatsData.setNewUserCount(newUserCount); stmt.close(); // Count of trade users stmt = getStatement(conn, "select count(accountid) as \"tradeUserCount\" from accountejb a where a.profile_userid like 'uid:%'"); rs = stmt.executeQuery(); rs.next(); int tradeUserCount = rs.getInt("tradeUserCount"); runStatsData.setTradeUserCount(tradeUserCount); stmt.close(); rs.close(); // Count of trade stocks stmt = getStatement(conn, "select count(symbol) as \"tradeStockCount\" from quoteejb a where a.symbol like 's:%'"); rs = stmt.executeQuery(); rs.next(); int tradeStockCount = rs.getInt("tradeStockCount"); runStatsData.setTradeStockCount(tradeStockCount); stmt.close(); // Count of trade users login, logout stmt = getStatement(conn, "select sum(loginCount) as \"sumLoginCount\", sum(logoutCount) as \"sumLogoutCount\" from accountejb a where a.profile_userID like 'uid:%'"); rs = stmt.executeQuery(); rs.next(); int sumLoginCount = rs.getInt("sumLoginCount"); int sumLogoutCount = rs.getInt("sumLogoutCount"); runStatsData.setSumLoginCount(sumLoginCount); runStatsData.setSumLogoutCount(sumLogoutCount); stmt.close(); rs.close(); // Update logoutcount and loginCount back to zero stmt = getStatement(conn, "update accountejb set logoutCount=0,loginCount=0 where profile_userID like 'uid:%'"); stmt.executeUpdate(); stmt.close(); // count holdings for trade users stmt = getStatement(conn, "select count(holdingid) as \"holdingCount\" from holdingejb h where h.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')"); rs = stmt.executeQuery(); rs.next(); int holdingCount = rs.getInt("holdingCount"); runStatsData.setHoldingCount(holdingCount); stmt.close(); rs.close(); // count orders for trade users stmt = getStatement(conn, "select count(orderid) as \"orderCount\" from orderejb o where o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')"); rs = stmt.executeQuery(); rs.next(); int orderCount = rs.getInt("orderCount"); runStatsData.setOrderCount(orderCount); stmt.close(); rs.close(); // count orders by type for trade users stmt = getStatement(conn, "select count(orderid) \"buyOrderCount\"from orderejb o where (o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND " + " (o.orderType='buy')"); rs = stmt.executeQuery(); rs.next(); int buyOrderCount = rs.getInt("buyOrderCount"); runStatsData.setBuyOrderCount(buyOrderCount); stmt.close(); rs.close(); // count orders by type for trade users stmt = getStatement(conn, "select count(orderid) \"sellOrderCount\"from orderejb o where (o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND " + " (o.orderType='sell')"); rs = stmt.executeQuery(); rs.next(); int sellOrderCount = rs.getInt("sellOrderCount"); runStatsData.setSellOrderCount(sellOrderCount); stmt.close(); rs.close(); // Delete cancelled orders stmt = getStatement(conn, "delete from orderejb where orderStatus='cancelled'"); int cancelledOrderCount = stmt.executeUpdate(); runStatsData.setCancelledOrderCount(cancelledOrderCount); stmt.close(); rs.close(); // count open orders by type for trade users stmt = getStatement(conn, "select count(orderid) \"openOrderCount\"from orderejb o where (o.account_accountid in " + "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND " + " (o.orderStatus='open')"); rs = stmt.executeQuery(); rs.next(); int openOrderCount = rs.getInt("openOrderCount"); runStatsData.setOpenOrderCount(openOrderCount); stmt.close(); rs.close(); // Delete orders for holding which have been purchased and sold stmt = getStatement(conn, "delete from orderejb where holding_holdingid is null"); int deletedOrderCount = stmt.executeUpdate(); runStatsData.setDeletedOrderCount(deletedOrderCount); stmt.close(); rs.close(); commit(conn); System.out.println("TradeDirect:reset Run stats data\n\n" + runStatsData); } catch (Exception e) { Log.error(e, "Failed to reset Trade"); rollBack(conn, e); throw e; } finally { releaseConn(conn); } return runStatsData; } private void releaseConn(Connection conn) throws Exception { try { if (conn != null) { conn.close(); if (Log.doTrace()) { synchronized (lock) { connCount--; } Log.trace("TradeDirect:releaseConn -- connection closed, connCount=" + connCount); } } } catch (Exception e) { Log.error("TradeDirect:releaseConnection -- failed to close connection", e); } } /* * Lookup the TradeData datasource */ private void getDataSource() throws Exception { datasource = (DataSource) context.lookup(dsName); } /* * Allocate a new connection to the datasource */ private static int connCount = 0; private static Integer lock = new Integer(0); private Connection getConn() throws Exception { Connection conn = null; if (datasource == null) { getDataSource(); } conn = datasource.getConnection(); if (!this.inGlobalTxn) { conn.setAutoCommit(false); } if (Log.doTrace()) { synchronized (lock) { connCount++; } Log.trace("TradeDirect:getConn -- new connection allocated, IsolationLevel=" + conn.getTransactionIsolation() + " connectionCount = " + connCount); } return conn; } public Connection getConnPublic() throws Exception { return getConn(); } /* * Commit the provided connection if not under Global Transaction scope - * conn.commit() is not allowed in a global transaction. the txn manager * will perform the commit */ private void commit(Connection conn) throws Exception { if (!inSession) { if ((getInGlobalTxn() == false) && (conn != null)) { conn.commit(); } } } /* * Rollback the statement for the given connection */ private void rollBack(Connection conn, Exception e) throws Exception { if (!inSession) { Log.log("TradeDirect:rollBack -- rolling back conn due to previously caught exception -- inGlobalTxn=" + getInGlobalTxn()); if ((getInGlobalTxn() == false) && (conn != null)) { conn.rollback(); } else { throw e; // Throw the exception // so the Global txn manager will rollBack } } } /* * Allocate a new prepared statment for this connection */ private PreparedStatement getStatement(Connection conn, String sql) throws Exception { return conn.prepareStatement(sql); } private PreparedStatement getStatement(Connection conn, String sql, int type, int concurrency) throws Exception { return conn.prepareStatement(sql, type, concurrency); } private static final String createQuoteSQL = "insert into quoteejb " + "( symbol, companyName, volume, price, open1, low, high, change1 ) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? )"; private static final String createAccountSQL = "insert into accountejb " + "( accountid, creationDate, openBalance, balance, lastLogin, loginCount, logoutCount, profile_userid) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? )"; private static final String createAccountProfileSQL = "insert into accountprofileejb " + "( userid, passwd, fullname, address, email, creditcard ) " + "VALUES ( ? , ? , ? , ? , ? , ? )"; private static final String createHoldingSQL = "insert into holdingejb " + "( holdingid, purchaseDate, purchasePrice, quantity, quote_symbol, account_accountid ) " + "VALUES ( ? , ? , ? , ? , ? , ? )"; private static final String createOrderSQL = "insert into orderejb " + "( orderid, ordertype, orderstatus, opendate, quantity, price, orderfee, account_accountid, holding_holdingid, quote_symbol) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; private static final String removeHoldingSQL = "delete from holdingejb where holdingid = ?"; private static final String removeHoldingFromOrderSQL = "update orderejb set holding_holdingid=null where holding_holdingid = ?"; private static final String updateAccountProfileSQL = "update accountprofileejb set " + "passwd = ?, fullname = ?, address = ?, email = ?, creditcard = ? " + "where userid = (select profile_userid from accountejb a " + "where a.profile_userid=?)"; private static final String loginSQL = "update accountejb set lastLogin=?, logincount=logincount+1 " + "where profile_userid=?"; private static final String logoutSQL = "update accountejb set logoutcount=logoutcount+1 " + "where profile_userid=?"; private static final String getAccountSQL = "select * from accountejb a where a.accountid = ?"; private static final String getAccountProfileSQL = "select * from accountprofileejb ap where ap.userid = " + "(select profile_userid from accountejb a where a.profile_userid=?)"; private static final String getAccountProfileForAccountSQL = "select * from accountprofileejb ap where ap.userid = " + "(select profile_userid from accountejb a where a.accountid=?)"; private static final String getAccountForUserSQL = "select * from accountejb a where a.profile_userid = " + "( select userid from accountprofileejb ap where ap.userid = ?)"; private static final String getHoldingSQL = "select * from holdingejb h where h.holdingid = ?"; private static final String getHoldingsForUserSQL = "select * from holdingejb h where h.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getOrderSQL = "select * from orderejb o where o.orderid = ?"; private static final String getOrdersByUserSQL = "select * from orderejb o where o.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getClosedOrdersSQL = "select * from orderejb o " + "where o.orderstatus = 'closed' AND o.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getQuoteSQL = "select * from quoteejb q where q.symbol=?"; private static final String getAllQuotesSQL = "select * from quoteejb q"; private static final String getQuoteForUpdateSQL = "select * from quoteejb q where q.symbol=? For Update"; private static final String getTSIAQuotesOrderByChangeSQL = "select * from quoteejb q order by q.change1"; private static final String getTSIASQL = "select SUM(price)/count(*) as TSIA from quoteejb q "; private static final String getOpenTSIASQL = "select SUM(open1)/count(*) as openTSIA from quoteejb q "; private static final String getTSIATotalVolumeSQL = "select SUM(volume) as totalVolume from quoteejb q "; private static final String creditAccountBalanceSQL = "update accountejb set " + "balance = balance + ? " + "where accountid = ?"; private static final String updateOrderStatusSQL = "update orderejb set " + "orderstatus = ?, completiondate = ? " + "where orderid = ?"; private static final String updateOrderHoldingSQL = "update orderejb set " + "holding_holdingID = ? " + "where orderid = ?"; private static final String updateQuotePriceVolumeSQL = "update quoteejb set " + "price = ?, change1 = ?, volume = ? " + "where symbol = ?"; private static boolean initialized = false; public static synchronized void init() { if (initialized) { return; } if (Log.doTrace()) { Log.trace("TradeDirect:init -- *** initializing"); } try { if (Log.doTrace()) { Log.trace("TradeDirect: init"); } context = new InitialContext(); datasource = (DataSource) context.lookup(dsName); } catch (Exception e) { Log.error("TradeDirect:init -- error on JNDI lookups of DataSource -- TradeDirect will not work", e); return; } try { qConnFactory = (ConnectionFactory) context.lookup("java:comp/env/jms/QueueConnectionFactory"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate QueueConnectionFactory.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); TradeConfig.setPublishQuotePriceChange(false); } try { brokerQueue = (Queue) context.lookup("java:comp/env/jms/TradeBrokerQueue"); } catch (Exception e) { try { brokerQueue = (Queue) context.lookup("jms/TradeBrokerQueue"); } catch (Exception e2) { Log.error("TradeDirect:init Unable to locate TradeBrokerQueue.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); TradeConfig.setPublishQuotePriceChange(false); } } try { tConnFactory = (ConnectionFactory) context.lookup("java:comp/env/jms/TopicConnectionFactory"); } catch (Exception e) { Log.error("TradeDirect:init Unable to locate TopicConnectionFactory.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); TradeConfig.setPublishQuotePriceChange(false); } try { streamerTopic = (Topic) context.lookup("java:comp/env/jms/TradeStreamerTopic"); } catch (Exception e) { try { streamerTopic = (Topic) context.lookup("jms/TradeStreamerTopic"); } catch (Exception e2) { Log.error("TradeDirect:init Unable to locate TradeStreamerTopic.\n\t -- Asynchronous mode will not work correctly and Quote Price change publishing will be disabled"); TradeConfig.setPublishQuotePriceChange(false); } } if (Log.doTrace()) { Log.trace("TradeDirect:init -- +++ initialized"); } initialized = true; } public static void destroy() { try { if (!initialized) { return; } Log.trace("TradeDirect:destroy"); } catch (Exception e) { Log.error("TradeDirect:destroy", e); } } private static InitialContext context; private static ConnectionFactory qConnFactory; private static Queue brokerQueue; private static ConnectionFactory tConnFactory; private static Topic streamerTopic; /** * Gets the inGlobalTxn * * @return Returns a boolean */ private boolean getInGlobalTxn() { return inGlobalTxn; } /** * Sets the inGlobalTxn * * @param inGlobalTxn * The inGlobalTxn to set */ private void setInGlobalTxn(boolean inGlobalTxn) { this.inGlobalTxn = inGlobalTxn; } }
79,883
36.663366
184
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/ejb3/DTBroker3MDB.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.ejb3; import javax.annotation.Resource; import javax.ejb.ActivationConfigProperty; import javax.ejb.EJB; import javax.ejb.MessageDriven; import javax.ejb.MessageDrivenContext; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import com.ibm.websphere.samples.daytrader.TradeServices; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.MDBStats; import com.ibm.websphere.samples.daytrader.util.TimerStat; @TransactionAttribute(TransactionAttributeType.REQUIRED) @TransactionManagement(TransactionManagementType.CONTAINER) @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "TradeBrokerQueue"), @ActivationConfigProperty(propertyName = "subscriptionDurability", propertyValue = "NonDurable") }) public class DTBroker3MDB implements MessageListener { private final MDBStats mdbStats; private int statInterval = 10000; // TODO: Using local interface, make it configurable to use remote? @EJB private TradeSLSBLocal tradeSLSB; @Resource public MessageDrivenContext mdc; public DTBroker3MDB() { if (Log.doTrace()) { Log.trace("DTBroker3MDB:DTBroker3MDB()"); } if (statInterval <= 0) { statInterval = 10000; } mdbStats = MDBStats.getInstance(); } @Override public void onMessage(Message message) { try { if (Log.doTrace()) { Log.trace("TradeBroker:onMessage -- received message -->" + ((TextMessage) message).getText() + "command-->" + message.getStringProperty("command") + "<--"); } if (message.getJMSRedelivered()) { Log.log("DTBroker3MDB: The following JMS message was redelivered due to a rollback:\n" + ((TextMessage) message).getText()); // Order has been cancelled -- ignore returned messages return; } String command = message.getStringProperty("command"); if (command == null) { Log.debug("DTBroker3MDB:onMessage -- received message with null command. Message-->" + message); return; } if (command.equalsIgnoreCase("neworder")) { /* Get the Order ID and complete the Order */ Integer orderID = new Integer(message.getIntProperty("orderID")); boolean twoPhase = message.getBooleanProperty("twoPhase"); boolean direct = message.getBooleanProperty("direct"); long publishTime = message.getLongProperty("publishTime"); long receiveTime = System.currentTimeMillis(); TradeServices trade = null; try { trade = getTrade(direct); if (Log.doTrace()) { Log.trace("DTBroker3MDB:onMessage - completing order " + orderID + " twoPhase=" + twoPhase + " direct=" + direct); } trade.completeOrder(orderID, twoPhase); TimerStat currentStats = mdbStats.addTiming("DTBroker3MDB:neworder", publishTime, receiveTime); if ((currentStats.getCount() % statInterval) == 0) { Log.log(" DTBroker3MDB: processed " + statInterval + " stock trading orders." + " Total NewOrders process = " + currentStats.getCount() + "Time (in seconds):" + " min: " +currentStats.getMinSecs()+ " max: " +currentStats.getMaxSecs()+ " avg: " +currentStats.getAvgSecs()); } } catch (Exception e) { Log.error("DTBroker3MDB:onMessage Exception completing order: " + orderID + "\n", e); mdc.setRollbackOnly(); /* * UPDATE - order is cancelled in trade if an error is * caught try { trade.cancelOrder(orderID, twoPhase); } * catch (Exception e2) { Log.error("order cancel failed", * e); } */ } } else if (command.equalsIgnoreCase("ping")) { if (Log.doTrace()) { Log.trace("DTBroker3MDB:onMessage received test command -- message: " + ((TextMessage) message).getText()); } long publishTime = message.getLongProperty("publishTime"); long receiveTime = System.currentTimeMillis(); TimerStat currentStats = mdbStats.addTiming("DTBroker3MDB:ping", publishTime, receiveTime); if ((currentStats.getCount() % statInterval) == 0) { Log.log(" DTBroker3MDB: received " + statInterval + " ping messages." + " Total ping message count = " + currentStats.getCount() + " Time (in seconds):" + " min: " +currentStats.getMinSecs()+ " max: " +currentStats.getMaxSecs()+ " avg: " +currentStats.getAvgSecs()); } } else { Log.error("DTBroker3MDB:onMessage - unknown message request command-->" + command + "<-- message=" + ((TextMessage) message).getText()); } } catch (Throwable t) { // JMS onMessage should handle all exceptions Log.error("DTBroker3MDB: Error rolling back transaction", t); mdc.setRollbackOnly(); } } private TradeServices getTrade(boolean direct) throws Exception { TradeServices trade; if (direct) { trade = new TradeDirect(); } else { trade = tradeSLSB; } return trade; } }
7,065
42.617284
152
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/ejb3/DTStreamer3MDB.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.ejb3; import javax.annotation.Resource; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.ejb.MessageDrivenContext; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.enterprise.event.Event; import javax.inject.Inject; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.MDBStats; import com.ibm.websphere.samples.daytrader.util.TimerStat; import com.ibm.websphere.samples.daytrader.util.TradeConfig; import com.ibm.websphere.samples.daytrader.util.WebSocketJMSMessage; @TransactionAttribute(TransactionAttributeType.REQUIRED) @TransactionManagement(TransactionManagementType.CONTAINER) @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "TradeStreamerTopic"), @ActivationConfigProperty(propertyName = "subscriptionDurability", propertyValue = "NonDurable") }) public class DTStreamer3MDB implements MessageListener { private final MDBStats mdbStats; private int statInterval = 10000; @Resource public MessageDrivenContext mdc; /** Creates a new instance of TradeSteamerMDB */ public DTStreamer3MDB() { if (Log.doTrace()) { Log.trace("DTStreamer3MDB:DTStreamer3MDB()"); } if (statInterval <= 0) { statInterval = 10000; } mdbStats = MDBStats.getInstance(); } @Inject @WebSocketJMSMessage Event<Message> jmsEvent; @Override public void onMessage(Message message) { try { if (Log.doTrace()) { Log.trace("DTStreamer3MDB:onMessage -- received message -->" + ((TextMessage) message).getText() + "command-->" + message.getStringProperty("command") + "<--"); } String command = message.getStringProperty("command"); if (command == null) { Log.debug("DTStreamer3MDB:onMessage -- received message with null command. Message-->" + message); return; } if (command.equalsIgnoreCase("updateQuote")) { if (Log.doTrace()) { Log.trace("DTStreamer3MDB:onMessage -- received message -->" + ((TextMessage) message).getText() + "\n\t symbol = " + message.getStringProperty("symbol") + "\n\t current price =" + message.getStringProperty("price") + "\n\t old price =" + message.getStringProperty("oldPrice")); } long publishTime = message.getLongProperty("publishTime"); long receiveTime = System.currentTimeMillis(); TimerStat currentStats = mdbStats.addTiming("DTStreamer3MDB:udpateQuote", publishTime, receiveTime); if ((currentStats.getCount() % statInterval) == 0) { Log.log(" DTStreamer3MDB: " + statInterval + " prices updated:" + " Total message count = " + currentStats.getCount() + " Time (in seconds):" + " min: " +currentStats.getMinSecs()+ " max: " +currentStats.getMaxSecs()+ " avg: " +currentStats.getAvgSecs() ); } // Fire message to Websocket Endpoint // Limit Symbols that get sent with percentageToWebSocket (default 5%). int symbolNumber = new Integer(message.getStringProperty("symbol").substring(2)); if ( symbolNumber < TradeConfig.getMAX_QUOTES() * TradeConfig.getPercentSentToWebsocket() * 0.01) { jmsEvent.fire(message); } } else if (command.equalsIgnoreCase("ping")) { if (Log.doTrace()) { Log.trace("DTStreamer3MDB:onMessage received ping command -- message: " + ((TextMessage) message).getText()); } long publishTime = message.getLongProperty("publishTime"); long receiveTime = System.currentTimeMillis(); TimerStat currentStats = mdbStats.addTiming("DTStreamer3MDB:ping", publishTime, receiveTime); if ((currentStats.getCount() % statInterval) == 0) { Log.log(" DTStreamer3MDB: received " + statInterval + " ping messages." + " Total message count = " + currentStats.getCount() + " Time (in seconds):" + " min: " +currentStats.getMinSecs()+ " max: " +currentStats.getMaxSecs()+ " avg: " +currentStats.getAvgSecs()); } } else { Log.error("DTStreamer3MDB:onMessage - unknown message request command-->" + command + "<-- message=" + ((TextMessage) message).getText()); } } catch (Throwable t) { // JMS onMessage should handle all exceptions Log.error("DTStreamer3MDB: Exception", t); //UPDATE - Not rolling back for now -- so error messages are not redelivered mdc.setRollbackOnly(); } } }
6,308
44.717391
154
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/ejb3/MarketSummarySingleton.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.ejb3; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.Lock; import javax.ejb.LockType; import javax.ejb.Schedule; import javax.ejb.Singleton; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import com.ibm.websphere.samples.daytrader.beans.MarketSummaryDataBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Singleton public class MarketSummarySingleton { private MarketSummaryDataBean marketSummaryDataBean; @PersistenceContext private EntityManager entityManager; @PostConstruct private void setup () { updateMarketSummary(); } /* Update Market Summary every 20 seconds */ @Schedule(second = "*/20",minute = "*", hour = "*", persistent = false) private void updateMarketSummary() { if (Log.doTrace()) { Log.trace("MarketSummarySingleton:updateMarketSummary -- updating market summary"); } if (TradeConfig.getRunTimeMode() != TradeConfig.EJB3) { if (Log.doTrace()) { Log.trace("MarketSummarySingleton:updateMarketSummary -- Not EJB3 Mode, so not updating"); } return; // Only do the actual work if in EJB3 Mode } List<QuoteDataBean> quotes; try { // Find Trade Stock Index Quotes (Top 100 quotes) ordered by their change in value CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<QuoteDataBean> criteriaQuery = criteriaBuilder.createQuery(QuoteDataBean.class); Root<QuoteDataBean> quoteRoot = criteriaQuery.from(QuoteDataBean.class); criteriaQuery.orderBy(criteriaBuilder.desc(quoteRoot.get("change1"))); criteriaQuery.select(quoteRoot); TypedQuery<QuoteDataBean> q = entityManager.createQuery(criteriaQuery); quotes = q.getResultList(); } catch (Exception e) { Log.debug("Warning: The database has not been configured. If this is the first time the application has been started, please create and populate the database tables. Then restart the server."); return; } /* TODO: Make this cleaner? */ QuoteDataBean[] quoteArray = quotes.toArray(new QuoteDataBean[quotes.size()]); ArrayList<QuoteDataBean> topGainers = new ArrayList<QuoteDataBean>(5); ArrayList<QuoteDataBean> topLosers = new ArrayList<QuoteDataBean>(5); BigDecimal TSIA = FinancialUtils.ZERO; BigDecimal openTSIA = FinancialUtils.ZERO; double totalVolume = 0.0; if (quoteArray.length > 5) { for (int i = 0; i < 5; i++) { topGainers.add(quoteArray[i]); } for (int i = quoteArray.length - 1; i >= quoteArray.length - 5; i--) { topLosers.add(quoteArray[i]); } for (QuoteDataBean quote : quoteArray) { BigDecimal price = quote.getPrice(); BigDecimal open = quote.getOpen(); double volume = quote.getVolume(); TSIA = TSIA.add(price); openTSIA = openTSIA.add(open); totalVolume += volume; } TSIA = TSIA.divide(new BigDecimal(quoteArray.length), FinancialUtils.ROUND); openTSIA = openTSIA.divide(new BigDecimal(quoteArray.length), FinancialUtils.ROUND); } setMarketSummaryDataBean(new MarketSummaryDataBean(TSIA, openTSIA, totalVolume, topGainers, topLosers)); } @Lock(LockType.READ) public MarketSummaryDataBean getMarketSummaryDataBean() { return marketSummaryDataBean; } @Lock(LockType.WRITE) public void setMarketSummaryDataBean(MarketSummaryDataBean marketSummaryDataBean) { this.marketSummaryDataBean = marketSummaryDataBean; } }
5,017
38.511811
202
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/ejb3/TradeSLSBBean.java
/** * (C) Copyright IBM Corporation 2015, 2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.ejb3; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.ejb.SessionContext; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.enterprise.concurrent.ManagedThreadFactory; import javax.jms.JMSContext; import javax.jms.Queue; import javax.jms.QueueConnectionFactory; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnectionFactory; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.transaction.RollbackException; import com.ibm.websphere.samples.daytrader.TradeAction; //import com.ibm.websphere.samples.daytrader.TradeServices; import com.ibm.websphere.samples.daytrader.beans.MarketSummaryDataBean; import com.ibm.websphere.samples.daytrader.beans.RunStatsDataBean; import com.ibm.websphere.samples.daytrader.entities.AccountDataBean; import com.ibm.websphere.samples.daytrader.entities.AccountProfileDataBean; import com.ibm.websphere.samples.daytrader.entities.HoldingDataBean; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.CompleteOrderThread; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Stateless @TransactionAttribute(TransactionAttributeType.REQUIRED) @TransactionManagement(TransactionManagementType.CONTAINER) public class TradeSLSBBean implements TradeSLSBRemote, TradeSLSBLocal { @Resource(name = "jms/QueueConnectionFactory", authenticationType = javax.annotation.Resource.AuthenticationType.APPLICATION) private QueueConnectionFactory queueConnectionFactory; @Resource(name = "jms/TopicConnectionFactory", authenticationType = javax.annotation.Resource.AuthenticationType.APPLICATION) private TopicConnectionFactory topicConnectionFactory; @Resource(lookup = "jms/TradeStreamerTopic") private Topic tradeStreamerTopic; @Resource(lookup = "jms/TradeBrokerQueue") private Queue tradeBrokerQueue; @Resource private ManagedThreadFactory managedThreadFactory; /* JBoss @Resource(name = "java:/jms/QueueConnectionFactory", authenticationType = javax.annotation.Resource.AuthenticationType.APPLICATION) private QueueConnectionFactory queueConnectionFactory; @Resource(name = "java:/jms/TopicConnectionFactory", authenticationType = javax.annotation.Resource.AuthenticationType.APPLICATION) private TopicConnectionFactory topicConnectionFactory; @Resource(lookup = "java:/jms/TradeStreamerTopic") private Topic tradeStreamerTopic; @Resource(lookup = "java:/jms/TradeBrokerQueue") private Queue tradeBrokerQueue; */ @PersistenceContext private EntityManager entityManager; @Resource private SessionContext context; @EJB MarketSummarySingleton marketSummarySingleton; /** Creates a new instance of TradeSLSBBean */ public TradeSLSBBean() { if (Log.doTrace()) { Log.trace("TradeSLSBBean:ejbCreate -- JNDI lookups of EJB and JMS resources"); } } @Override public MarketSummaryDataBean getMarketSummary() { if (Log.doTrace()) { Log.trace("TradeSLSBBean:getMarketSummary -- getting market summary"); } return marketSummarySingleton.getMarketSummaryDataBean(); } @Override public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) { OrderDataBean order; BigDecimal total; try { if (Log.doTrace()) { Log.trace("TradeSLSBBean:buy", userID, symbol, quantity, orderProcessingMode); } AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID); AccountDataBean account = profile.getAccount(); QuoteDataBean quote = entityManager.find(QuoteDataBean.class, symbol); HoldingDataBean holding = null; // The holding will be created by // this buy order order = createOrder(account, quote, holding, "buy", quantity); // UPDATE - account should be credited during completeOrder BigDecimal price = quote.getPrice(); BigDecimal orderFee = order.getOrderFee(); BigDecimal balance = account.getBalance(); total = (new BigDecimal(quantity).multiply(price)).add(orderFee); account.setBalance(balance.subtract(total)); final Integer orderID=order.getOrderID(); if (orderProcessingMode == TradeConfig.SYNCH) { completeOrder(orderID, false); } else { entityManager.flush(); queueOrder(orderID, true); } } catch (Exception e) { Log.error("TradeSLSBBean:buy(" + userID + "," + symbol + "," + quantity + ") --> failed", e); /* On exception - cancel the order */ // TODO figure out how to do this with JPA // if (order != null) order.cancel(); throw new EJBException(e); } return order; } @Override public OrderDataBean sell(final String userID, final Integer holdingID, int orderProcessingMode) { OrderDataBean order; BigDecimal total; try { if (Log.doTrace()) { Log.trace("TradeSLSBBean:sell", userID, holdingID, orderProcessingMode); } AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID); AccountDataBean account = profile.getAccount(); HoldingDataBean holding = entityManager.find(HoldingDataBean.class, holdingID); if (holding == null) { Log.error("TradeSLSBBean:sell User " + userID + " attempted to sell holding " + holdingID + " which has already been sold"); OrderDataBean orderData = new OrderDataBean(); orderData.setOrderStatus("cancelled"); entityManager.persist(orderData); return orderData; } QuoteDataBean quote = holding.getQuote(); double quantity = holding.getQuantity(); order = createOrder(account, quote, holding, "sell", quantity); // UPDATE the holding purchase data to signify this holding is // "inflight" to be sold // -- could add a new holdingStatus attribute to holdingEJB holding.setPurchaseDate(new java.sql.Timestamp(0)); // UPDATE - account should be credited during completeOrder BigDecimal price = quote.getPrice(); BigDecimal orderFee = order.getOrderFee(); BigDecimal balance = account.getBalance(); total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee); account.setBalance(balance.add(total)); final Integer orderID=order.getOrderID(); if (orderProcessingMode == TradeConfig.SYNCH) { completeOrder(orderID, false); } else { entityManager.flush(); queueOrder(orderID, true); } } catch (Exception e) { Log.error("TradeSLSBBean:sell(" + userID + "," + holdingID + ") --> failed", e); // if (order != null) order.cancel(); // UPDATE - handle all exceptions like: throw new EJBException("TradeSLSBBean:sell(" + userID + "," + holdingID + ")", e); } return order; } @Override public void queueOrder(Integer orderID, boolean twoPhase) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:queueOrder", orderID); } if (TradeConfig.getOrderProcessingMode() == TradeConfig.ASYNCH_MANAGEDTHREAD) { Thread thread = managedThreadFactory.newThread(new CompleteOrderThread(orderID, twoPhase)); thread.start(); } else { try (JMSContext queueContext = queueConnectionFactory.createContext();) { TextMessage message = queueContext.createTextMessage(); message.setStringProperty("command", "neworder"); message.setIntProperty("orderID", orderID); message.setBooleanProperty("twoPhase", twoPhase); message.setText("neworder: orderID=" + orderID + " runtimeMode=EJB twoPhase=" + twoPhase); message.setLongProperty("publishTime", System.currentTimeMillis()); queueContext.createProducer().send(tradeBrokerQueue, message); } catch (Exception e) { throw new EJBException(e.getMessage(), e); // pass the exception } } } @Override public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception { if (Log.doTrace()) { Log.trace("TradeSLSBBean:completeOrder", orderID + " twoPhase=" + twoPhase); } OrderDataBean order = entityManager.find(OrderDataBean.class, orderID); if (order == null) { throw new EJBException("Error: attempt to complete Order that is null\n" + order); } order.getQuote(); if (order.isCompleted()) { throw new EJBException("Error: attempt to complete Order that is already completed\n" + order); } AccountDataBean account = order.getAccount(); QuoteDataBean quote = order.getQuote(); HoldingDataBean holding = order.getHolding(); BigDecimal price = order.getPrice(); double quantity = order.getQuantity(); String userID = account.getProfile().getUserID(); if (Log.doTrace()) { Log.trace("TradeSLSBBeanInternal:completeOrder--> Completing Order " + order.getOrderID() + "\n\t Order info: " + order + "\n\t Account info: " + account + "\n\t Quote info: " + quote + "\n\t Holding info: " + holding); } if (order.isBuy()) { /* * Complete a Buy operation - create a new Holding for the Account - * deduct the Order cost from the Account balance */ HoldingDataBean newHolding = createHolding(account, quote, quantity, price); order.setHolding(newHolding); } if (order.isSell()) { /* * Complete a Sell operation - remove the Holding from the Account - * deposit the Order proceeds to the Account balance */ if (holding == null) { //Log.error("TradeSLSBBean:completeOrder -- Unable to sell order " + order.getOrderID() + " holding already sold"); order.cancel(); throw new EJBException("TradeSLSBBean:completeOrder -- Unable to sell order " + order.getOrderID() + " holding already sold"); } else { entityManager.remove(holding); order.setHolding(null); } } order.setOrderStatus("closed"); order.setCompletionDate(new java.sql.Timestamp(System.currentTimeMillis())); if (Log.doTrace()) { Log.trace("TradeSLSBBean:completeOrder--> Completed Order " + order.getOrderID() + "\n\t Order info: " + order + "\n\t Account info: " + account + "\n\t Quote info: " + quote + "\n\t Holding info: " + holding); } // if (Log.doTrace()) // Log.trace("Calling TradeAction:orderCompleted from Session EJB using Session Object"); // FUTURE All getEJBObjects could be local -- need to add local I/F TradeAction tradeAction = new TradeAction(); tradeAction.orderCompleted(userID, orderID); return order; } @Override public void cancelOrder(Integer orderID, boolean twoPhase) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:cancelOrder", orderID + " twoPhase=" + twoPhase); } OrderDataBean order = entityManager.find(OrderDataBean.class, orderID); order.cancel(); } @Override public void orderCompleted(String userID, Integer orderID) { throw new UnsupportedOperationException("TradeSLSBBean:orderCompleted method not supported"); } @Override public Collection<OrderDataBean> getOrders(String userID) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:getOrders", userID); } AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID); AccountDataBean account = profile.getAccount(); return account.getOrders(); } @Override public Collection<OrderDataBean> getClosedOrders(String userID) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:getClosedOrders", userID); } try { /* I want to do a CriteriaUpdate here, but there are issues with JBoss/Hibernate */ CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<OrderDataBean> criteriaQuery = criteriaBuilder.createQuery(OrderDataBean.class); Root<OrderDataBean> orders = criteriaQuery.from(OrderDataBean.class); criteriaQuery.select(orders); criteriaQuery.where( criteriaBuilder.equal(orders.get("orderStatus"), criteriaBuilder.parameter(String.class, "p_status")), criteriaBuilder.equal(orders.get("account").get("profile").get("userID"), criteriaBuilder.parameter(String.class, "p_userid"))); TypedQuery<OrderDataBean> q = entityManager.createQuery(criteriaQuery); q.setParameter("p_status", "closed"); q.setParameter("p_userid", userID); List<OrderDataBean> results = q.getResultList(); Iterator<OrderDataBean> itr = results.iterator(); // Spin through the orders to remove or mark completed while (itr.hasNext()) { OrderDataBean order = itr.next(); // TODO: Investigate ConncurrentModification Exceptions if (TradeConfig.getLongRun()) { //Added this for Longruns (to prevent orderejb growth) entityManager.remove(order); } else { order.setOrderStatus("completed"); } } return results; } catch (Exception e) { Log.error("TradeSLSBBean.getClosedOrders", e); throw new EJBException("TradeSLSBBean.getClosedOrders - error", e); } } @Override public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) { try { QuoteDataBean quote = new QuoteDataBean(symbol, companyName, 0, price, price, price, price, 0); entityManager.persist(quote); if (Log.doTrace()) { Log.trace("TradeSLSBBean:createQuote-->" + quote); } return quote; } catch (Exception e) { Log.error("TradeSLSBBean:createQuote -- exception creating Quote", e); throw new EJBException(e); } } @Override public QuoteDataBean getQuote(String symbol) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:getQuote", symbol); } return entityManager.find(QuoteDataBean.class, symbol); } @Override public Collection<QuoteDataBean> getAllQuotes() { if (Log.doTrace()) { Log.trace("TradeSLSBBean:getAllQuotes"); } TypedQuery<QuoteDataBean> query = entityManager.createNamedQuery("quoteejb.allQuotes",QuoteDataBean.class); return query.getResultList(); } @Override public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) { if (!TradeConfig.getUpdateQuotePrices()) { return new QuoteDataBean(); } if (Log.doTrace()) { Log.trace("TradeSLSBBean:updateQuote", symbol, changeFactor); } TypedQuery<QuoteDataBean> q = entityManager.createNamedQuery("quoteejb.quoteForUpdate",QuoteDataBean.class); q.setParameter(1, symbol); QuoteDataBean quote = q.getSingleResult(); BigDecimal oldPrice = quote.getPrice(); BigDecimal openPrice = quote.getOpen(); if (oldPrice.equals(TradeConfig.PENNY_STOCK_PRICE)) { changeFactor = TradeConfig.PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER; } else if (oldPrice.compareTo(TradeConfig.MAXIMUM_STOCK_PRICE) > 0) { changeFactor = TradeConfig.MAXIMUM_STOCK_SPLIT_MULTIPLIER; } BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP); quote.setPrice(newPrice); quote.setChange(newPrice.subtract(openPrice).doubleValue()); quote.setVolume(quote.getVolume() + sharesTraded); entityManager.merge(quote); context.getBusinessObject(TradeSLSBLocal.class).publishQuotePriceChange(quote, oldPrice, changeFactor, sharesTraded); return quote; } @Override public Collection<HoldingDataBean> getHoldings(String userID) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:getHoldings", userID); } CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<HoldingDataBean> criteriaQuery = criteriaBuilder.createQuery(HoldingDataBean.class); Root<HoldingDataBean> holdings = criteriaQuery.from(HoldingDataBean.class); criteriaQuery.where( criteriaBuilder.equal(holdings.get("account").get("profile").get("userID"), criteriaBuilder.parameter(String.class, "p_userid"))); criteriaQuery.select(holdings); TypedQuery<HoldingDataBean> typedQuery = entityManager.createQuery(criteriaQuery); typedQuery.setParameter("p_userid", userID); return typedQuery.getResultList(); } @Override public HoldingDataBean getHolding(Integer holdingID) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:getHolding", holdingID); } return entityManager.find(HoldingDataBean.class, holdingID); } @Override public AccountDataBean getAccountData(String userID) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:getAccountData", userID); } AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID); AccountDataBean account = profile.getAccount(); // Added to populate transient field for account account.setProfileID(profile.getUserID()); return account; } @Override public AccountProfileDataBean getAccountProfileData(String userID) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:getProfileData", userID); } return entityManager.find(AccountProfileDataBean.class, userID); } @Override public AccountProfileDataBean updateAccountProfile(AccountProfileDataBean profileData) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:updateAccountProfileData", profileData); } AccountProfileDataBean temp = entityManager.find(AccountProfileDataBean.class, profileData.getUserID()); temp.setAddress(profileData.getAddress()); temp.setPassword(profileData.getPassword()); temp.setFullName(profileData.getFullName()); temp.setCreditCard(profileData.getCreditCard()); temp.setEmail(profileData.getEmail()); entityManager.merge(temp); return temp; } @Override public AccountDataBean login(String userID, String password) throws RollbackException { AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID); if (profile == null) { throw new EJBException("No such user: " + userID); } AccountDataBean account = profile.getAccount(); if (Log.doTrace()) { Log.trace("TradeSLSBBean:login", userID, password); } account.login(password); if (Log.doTrace()) { Log.trace("TradeSLSBBean:login(" + userID + "," + password + ") success" + account); } return account; } @Override public void logout(String userID) { if (Log.doTrace()) { Log.trace("TradeSLSBBean:logout", userID); } AccountProfileDataBean profile = entityManager.find(AccountProfileDataBean.class, userID); AccountDataBean account = profile.getAccount(); account.logout(); if (Log.doTrace()) { Log.trace("TradeSLSBBean:logout(" + userID + ") success"); } } @Override public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditcard, BigDecimal openBalance) { AccountDataBean account = null; AccountProfileDataBean profile = null; if (Log.doTrace()) { Log.trace("TradeSLSBBean:register", userID, password, fullname, address, email, creditcard, openBalance); } // Check to see if a profile with the desired userID already exists profile = entityManager.find(AccountProfileDataBean.class, userID); if (profile != null) { Log.error("Failed to register new Account - AccountProfile with userID(" + userID + ") already exists"); return null; } else { profile = new AccountProfileDataBean(userID, password, fullname, address, email, creditcard); account = new AccountDataBean(0, 0, null, new Timestamp(System.currentTimeMillis()), openBalance, openBalance, userID); profile.setAccount(account); account.setProfile(profile); entityManager.persist(profile); entityManager.persist(account); } return account; } @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception { if (Log.doTrace()) { Log.trace("TradeSLSBBean:resetTrade", deleteAll); } return new com.ibm.websphere.samples.daytrader.direct.TradeDirect(false).resetTrade(deleteAll); } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void publishQuotePriceChange(QuoteDataBean quote, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded) { if (!TradeConfig.getPublishQuotePriceChange()) { return; } if (Log.doTrace()) { Log.trace("TradeSLSBBean:publishQuotePricePublishing -- quoteData = " + quote); } try (JMSContext topicContext = topicConnectionFactory.createContext();) { TextMessage message = topicContext.createTextMessage(); message.setStringProperty("command", "updateQuote"); message.setStringProperty("symbol", quote.getSymbol()); message.setStringProperty("company", quote.getCompanyName()); message.setStringProperty("price", quote.getPrice().toString()); message.setStringProperty("oldPrice", oldPrice.toString()); message.setStringProperty("open", quote.getOpen().toString()); message.setStringProperty("low", quote.getLow().toString()); message.setStringProperty("high", quote.getHigh().toString()); message.setDoubleProperty("volume", quote.getVolume()); message.setStringProperty("changeFactor", changeFactor.toString()); message.setDoubleProperty("sharesTraded", sharesTraded); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("Update Stock price for " + quote.getSymbol() + " old price = " + oldPrice + " new price = " + quote.getPrice()); topicContext.createProducer().send(tradeStreamerTopic, message); } catch (Exception e) { throw new EJBException(e.getMessage(), e); // pass the exception } } private OrderDataBean createOrder(AccountDataBean account, QuoteDataBean quote, HoldingDataBean holding, String orderType, double quantity) { OrderDataBean order; if (Log.doTrace()) { Log.trace("TradeSLSBBean:createOrder(orderID=" + " account=" + ((account == null) ? null : account.getAccountID()) + " quote=" + ((quote == null) ? null : quote.getSymbol()) + " orderType=" + orderType + " quantity=" + quantity); } try { order = new OrderDataBean(orderType, "open", new Timestamp(System.currentTimeMillis()), null, quantity, quote.getPrice().setScale( FinancialUtils.SCALE, FinancialUtils.ROUND), TradeConfig.getOrderFee(orderType), account, quote, holding); entityManager.persist(order); } catch (Exception e) { Log.error("TradeSLSBBean:createOrder -- failed to create Order. The stock/quote may not exist in the database.", e); throw new EJBException("TradeSLSBBean:createOrder -- failed to create Order. Check that the symbol exists in the database.", e); } return order; } private HoldingDataBean createHolding(AccountDataBean account, QuoteDataBean quote, double quantity, BigDecimal purchasePrice) throws Exception { HoldingDataBean newHolding = new HoldingDataBean(quantity, purchasePrice, new Timestamp(System.currentTimeMillis()), account, quote); entityManager.persist(newHolding); return newHolding; } public double investmentReturn(double investment, double NetValue) throws Exception { if (Log.doTrace()) { Log.trace("TradeSLSBBean:investmentReturn"); } double diff = NetValue - investment; double ir = diff / investment; return ir; } public QuoteDataBean pingTwoPhase(String symbol) throws Exception { if (Log.doTrace()) { Log.trace("TradeSLSBBean:pingTwoPhase", symbol); } QuoteDataBean quoteData = null; try (JMSContext queueContext = queueConnectionFactory.createContext();) { // Get a Quote and send a JMS message in a 2-phase commit quoteData = entityManager.find(QuoteDataBean.class, symbol); TextMessage message = queueContext.createTextMessage(); message.setStringProperty("command", "ping"); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("Ping message for queue java:comp/env/jms/TradeBrokerQueue sent from TradeSLSBBean:pingTwoPhase at " + new java.util.Date()); queueContext.createProducer().send(tradeBrokerQueue, message); } catch (Exception e) { Log.error("TradeSLSBBean:pingTwoPhase -- exception caught", e); } return quoteData; } class quotePriceComparator implements Comparator<Object> { @Override public int compare(Object quote1, Object quote2) { double change1 = ((QuoteDataBean) quote1).getChange(); double change2 = ((QuoteDataBean) quote2).getChange(); return new Double(change2).compareTo(change1); } } @PostConstruct public void postConstruct() { if (Log.doTrace()) { Log.trace("updateQuotePrices: " + TradeConfig.getUpdateQuotePrices()); Log.trace("publishQuotePriceChange: " + TradeConfig.getPublishQuotePriceChange()); } } }
29,347
39.257888
159
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/ejb3/TradeSLSBLocal.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.ejb3; import java.math.BigDecimal; import javax.ejb.Local; import com.ibm.websphere.samples.daytrader.TradeServices; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; @Local public interface TradeSLSBLocal extends TradeServices { public double investmentReturn(double investment, double NetValue) throws Exception; public QuoteDataBean pingTwoPhase(String symbol) throws Exception; public void publishQuotePriceChange(QuoteDataBean quote, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded); }
1,197
35.30303
128
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/ejb3/TradeSLSBRemote.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.ejb3; import javax.ejb.Remote; import com.ibm.websphere.samples.daytrader.TradeServices; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import java.math.BigDecimal; @Remote public interface TradeSLSBRemote extends TradeServices { public double investmentReturn(double investment, double NetValue) throws Exception; public QuoteDataBean pingTwoPhase(String symbol) throws Exception; public void publishQuotePriceChange(QuoteDataBean quote, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded); }
1,196
35.272727
128
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/entities/AccountDataBean.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.entities; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Collection; import java.util.Date; import javax.ejb.EJBException; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Entity(name = "accountejb") @Table(name = "accountejb") public class AccountDataBean implements Serializable { private static final long serialVersionUID = 8437841265136840545L; /* Accessor methods for persistent fields */ @TableGenerator(name = "accountIdGen", table = "KEYGENEJB", pkColumnName = "KEYNAME", valueColumnName = "KEYVAL", pkColumnValue = "account", allocationSize = 1000) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "accountIdGen") @Column(name = "ACCOUNTID", nullable = false) private Integer accountID; /* accountID */ @NotNull @Column(name = "LOGINCOUNT", nullable = false) private int loginCount; /* loginCount */ @NotNull @Column(name = "LOGOUTCOUNT", nullable = false) private int logoutCount; /* logoutCount */ @Column(name = "LASTLOGIN") @Temporal(TemporalType.TIMESTAMP) private Date lastLogin; /* lastLogin Date */ @Column(name = "CREATIONDATE") @Temporal(TemporalType.TIMESTAMP) private Date creationDate; /* creationDate */ @Column(name = "BALANCE") private BigDecimal balance; /* balance */ @Column(name = "OPENBALANCE") private BigDecimal openBalance; /* open balance */ @OneToMany(mappedBy = "account", fetch = FetchType.LAZY) private Collection<OrderDataBean> orders; @OneToMany(mappedBy = "account", fetch = FetchType.LAZY) private Collection<HoldingDataBean> holdings; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "PROFILE_USERID") private AccountProfileDataBean profile; /* * Accessor methods for relationship fields are only included for the * AccountProfile profileID */ @Transient private String profileID; public AccountDataBean() { } public AccountDataBean(Integer accountID, int loginCount, int logoutCount, Date lastLogin, Date creationDate, BigDecimal balance, BigDecimal openBalance, String profileID) { setAccountID(accountID); setLoginCount(loginCount); setLogoutCount(logoutCount); setLastLogin(lastLogin); setCreationDate(creationDate); setBalance(balance); setOpenBalance(openBalance); setProfileID(profileID); } public AccountDataBean(int loginCount, int logoutCount, Date lastLogin, Date creationDate, BigDecimal balance, BigDecimal openBalance, String profileID) { setLoginCount(loginCount); setLogoutCount(logoutCount); setLastLogin(lastLogin); setCreationDate(creationDate); setBalance(balance); setOpenBalance(openBalance); setProfileID(profileID); } public static AccountDataBean getRandomInstance() { return new AccountDataBean(new Integer(TradeConfig.rndInt(100000)), // accountID TradeConfig.rndInt(10000), // loginCount TradeConfig.rndInt(10000), // logoutCount new java.util.Date(), // lastLogin new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)), // creationDate TradeConfig.rndBigDecimal(1000000.0f), // balance TradeConfig.rndBigDecimal(1000000.0f), // openBalance TradeConfig.rndUserID() // profileID ); } @Override public String toString() { return "\n\tAccount Data for account: " + getAccountID() + "\n\t\t loginCount:" + getLoginCount() + "\n\t\t logoutCount:" + getLogoutCount() + "\n\t\t lastLogin:" + getLastLogin() + "\n\t\t creationDate:" + getCreationDate() + "\n\t\t balance:" + getBalance() + "\n\t\t openBalance:" + getOpenBalance() + "\n\t\t profileID:" + getProfileID(); } public String toHTML() { return "<BR>Account Data for account: <B>" + getAccountID() + "</B>" + "<LI> loginCount:" + getLoginCount() + "</LI>" + "<LI> logoutCount:" + getLogoutCount() + "</LI>" + "<LI> lastLogin:" + getLastLogin() + "</LI>" + "<LI> creationDate:" + getCreationDate() + "</LI>" + "<LI> balance:" + getBalance() + "</LI>" + "<LI> openBalance:" + getOpenBalance() + "</LI>" + "<LI> profileID:" + getProfileID() + "</LI>"; } public void print() { Log.log(this.toString()); } public Integer getAccountID() { return accountID; } public void setAccountID(Integer accountID) { this.accountID = accountID; } public int getLoginCount() { return loginCount; } public void setLoginCount(int loginCount) { this.loginCount = loginCount; } public int getLogoutCount() { return logoutCount; } public void setLogoutCount(int logoutCount) { this.logoutCount = logoutCount; } public Date getLastLogin() { return lastLogin; } public void setLastLogin(Date lastLogin) { this.lastLogin = lastLogin; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } public BigDecimal getOpenBalance() { return openBalance; } public void setOpenBalance(BigDecimal openBalance) { this.openBalance = openBalance; } public String getProfileID() { return profileID; } public void setProfileID(String profileID) { this.profileID = profileID; } /* * Disabled for D185273 public String getUserID() { return getProfileID(); } */ public Collection<OrderDataBean> getOrders() { return orders; } public void setOrders(Collection<OrderDataBean> orders) { this.orders = orders; } public Collection<HoldingDataBean> getHoldings() { return holdings; } public void setHoldings(Collection<HoldingDataBean> holdings) { this.holdings = holdings; } public AccountProfileDataBean getProfile() { return profile; } public void setProfile(AccountProfileDataBean profile) { this.profile = profile; } public void login(String password) { AccountProfileDataBean profile = getProfile(); if ((profile == null) || (profile.getPassword().equals(password) == false)) { String error = "AccountBean:Login failure for account: " + getAccountID() + ((profile == null) ? "null AccountProfile" : "\n\tIncorrect password-->" + profile.getUserID() + ":" + profile.getPassword()); throw new EJBException(error); } setLastLogin(new Timestamp(System.currentTimeMillis())); setLoginCount(getLoginCount() + 1); } public void logout() { setLogoutCount(getLogoutCount() + 1); } @Override public int hashCode() { int hash = 0; hash += (this.accountID != null ? this.accountID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof AccountDataBean)) { return false; } AccountDataBean other = (AccountDataBean) object; if (this.accountID != other.accountID && (this.accountID == null || !this.accountID.equals(other.accountID))) { return false; } return true; } }
8,986
31.096429
167
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/entities/AccountProfileDataBean.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.entities; //import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Entity(name = "accountprofileejb") @Table(name = "accountprofileejb") public class AccountProfileDataBean implements java.io.Serializable { /* Accessor methods for persistent fields */ private static final long serialVersionUID = 2794584136675420624L; @Id @NotNull @Column(name = "USERID", nullable = false) private String userID; /* userID */ @Column(name = "PASSWD") private String passwd; /* password */ @Column(name = "FULLNAME") private String fullName; /* fullName */ @Column(name = "ADDRESS") private String address; /* address */ @Column(name = "EMAIL") private String email; /* email */ @Column(name = "CREDITCARD") private String creditCard; /* creditCard */ @OneToOne(mappedBy = "profile", fetch = FetchType.LAZY) private AccountDataBean account; public AccountProfileDataBean() { } public AccountProfileDataBean(String userID, String password, String fullName, String address, String email, String creditCard) { setUserID(userID); setPassword(password); setFullName(fullName); setAddress(address); setEmail(email); setCreditCard(creditCard); } public static AccountProfileDataBean getRandomInstance() { return new AccountProfileDataBean(TradeConfig.rndUserID(), // userID TradeConfig.rndUserID(), // passwd TradeConfig.rndFullName(), // fullname TradeConfig.rndAddress(), // address TradeConfig.rndEmail(TradeConfig.rndUserID()), // email TradeConfig.rndCreditCard() // creditCard ); } @Override public String toString() { return "\n\tAccount Profile Data for userID:" + getUserID() + "\n\t\t passwd:" + getPassword() + "\n\t\t fullName:" + getFullName() + "\n\t\t address:" + getAddress() + "\n\t\t email:" + getEmail() + "\n\t\t creditCard:" + getCreditCard(); } public String toHTML() { return "<BR>Account Profile Data for userID: <B>" + getUserID() + "</B>" + "<LI> passwd:" + getPassword() + "</LI>" + "<LI> fullName:" + getFullName() + "</LI>" + "<LI> address:" + getAddress() + "</LI>" + "<LI> email:" + getEmail() + "</LI>" + "<LI> creditCard:" + getCreditCard() + "</LI>"; } public void print() { Log.log(this.toString()); } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getPassword() { return passwd; } public void setPassword(String password) { this.passwd = password; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCreditCard() { return creditCard; } public void setCreditCard(String creditCard) { this.creditCard = creditCard; } public AccountDataBean getAccount() { return account; } public void setAccount(AccountDataBean account) { this.account = account; } @Override public int hashCode() { int hash = 0; hash += (this.userID != null ? this.userID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof AccountProfileDataBean)) { return false; } AccountProfileDataBean other = (AccountProfileDataBean) object; if (this.userID != other.userID && (this.userID == null || !this.userID.equals(other.userID))) { return false; } return true; } }
5,099
27.651685
152
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/entities/HoldingDataBean.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.entities; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Entity(name = "holdingejb") @Table(name = "holdingejb") public class HoldingDataBean implements Serializable { /* persistent/relationship fields */ private static final long serialVersionUID = -2338411656251935480L; @Id @TableGenerator(name = "holdingIdGen", table = "KEYGENEJB", pkColumnName = "KEYNAME", valueColumnName = "KEYVAL", pkColumnValue = "holding", allocationSize = 1000) @GeneratedValue(strategy = GenerationType.TABLE, generator = "holdingIdGen") @Column(name = "HOLDINGID", nullable = false) private Integer holdingID; /* holdingID */ @NotNull @Column(name = "QUANTITY", nullable = false) private double quantity; /* quantity */ @Column(name = "PURCHASEPRICE") private BigDecimal purchasePrice; /* purchasePrice */ @Column(name = "PURCHASEDATE") @Temporal(TemporalType.TIMESTAMP) private Date purchaseDate; /* purchaseDate */ @Transient private String quoteID; /* Holding(*) ---> Quote(1) */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ACCOUNT_ACCOUNTID") private AccountDataBean account; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "QUOTE_SYMBOL") private QuoteDataBean quote; public HoldingDataBean() { } public HoldingDataBean(Integer holdingID, double quantity, BigDecimal purchasePrice, Date purchaseDate, String quoteID) { setHoldingID(holdingID); setQuantity(quantity); setPurchasePrice(purchasePrice); setPurchaseDate(purchaseDate); setQuoteID(quoteID); } public HoldingDataBean(double quantity, BigDecimal purchasePrice, Date purchaseDate, AccountDataBean account, QuoteDataBean quote) { setQuantity(quantity); setPurchasePrice(purchasePrice); setPurchaseDate(purchaseDate); setAccount(account); setQuote(quote); } public static HoldingDataBean getRandomInstance() { return new HoldingDataBean(new Integer(TradeConfig.rndInt(100000)), // holdingID TradeConfig.rndQuantity(), // quantity TradeConfig.rndBigDecimal(1000.0f), // purchasePrice new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)), // purchaseDate TradeConfig.rndSymbol() // symbol ); } @Override public String toString() { return "\n\tHolding Data for holding: " + getHoldingID() + "\n\t\t quantity:" + getQuantity() + "\n\t\t purchasePrice:" + getPurchasePrice() + "\n\t\t purchaseDate:" + getPurchaseDate() + "\n\t\t quoteID:" + getQuoteID(); } public String toHTML() { return "<BR>Holding Data for holding: " + getHoldingID() + "</B>" + "<LI> quantity:" + getQuantity() + "</LI>" + "<LI> purchasePrice:" + getPurchasePrice() + "</LI>" + "<LI> purchaseDate:" + getPurchaseDate() + "</LI>" + "<LI> quoteID:" + getQuoteID() + "</LI>"; } public void print() { Log.log(this.toString()); } public Integer getHoldingID() { return holdingID; } public void setHoldingID(Integer holdingID) { this.holdingID = holdingID; } public double getQuantity() { return quantity; } public void setQuantity(double quantity) { this.quantity = quantity; } public BigDecimal getPurchasePrice() { return purchasePrice; } public void setPurchasePrice(BigDecimal purchasePrice) { this.purchasePrice = purchasePrice; } public Date getPurchaseDate() { return purchaseDate; } public void setPurchaseDate(Date purchaseDate) { this.purchaseDate = purchaseDate; } public String getQuoteID() { if (quote != null) { return quote.getSymbol(); } return quoteID; } public void setQuoteID(String quoteID) { this.quoteID = quoteID; } public AccountDataBean getAccount() { return account; } public void setAccount(AccountDataBean account) { this.account = account; } public QuoteDataBean getQuote() { return quote; } public void setQuote(QuoteDataBean quote) { this.quote = quote; } @Override public int hashCode() { int hash = 0; hash += (this.holdingID != null ? this.holdingID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof HoldingDataBean)) { return false; } HoldingDataBean other = (HoldingDataBean) object; if (this.holdingID != other.holdingID && (this.holdingID == null || !this.holdingID.equals(other.holdingID))) { return false; } return true; } }
6,167
29.84
167
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/entities/OrderDataBean.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.entities; import java.io.Serializable; import java.math.BigDecimal; //import java.sql.Timestamp; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Entity(name = "orderejb") @Table(name = "orderejb") @NamedQueries({ @NamedQuery(name = "orderejb.findByOrderfee", query = "SELECT o FROM orderejb o WHERE o.orderFee = :orderfee"), @NamedQuery(name = "orderejb.findByCompletiondate", query = "SELECT o FROM orderejb o WHERE o.completionDate = :completiondate"), @NamedQuery(name = "orderejb.findByOrdertype", query = "SELECT o FROM orderejb o WHERE o.orderType = :ordertype"), @NamedQuery(name = "orderejb.findByOrderstatus", query = "SELECT o FROM orderejb o WHERE o.orderStatus = :orderstatus"), @NamedQuery(name = "orderejb.findByPrice", query = "SELECT o FROM orderejb o WHERE o.price = :price"), @NamedQuery(name = "orderejb.findByQuantity", query = "SELECT o FROM orderejb o WHERE o.quantity = :quantity"), @NamedQuery(name = "orderejb.findByOpendate", query = "SELECT o FROM orderejb o WHERE o.openDate = :opendate"), @NamedQuery(name = "orderejb.findByOrderid", query = "SELECT o FROM orderejb o WHERE o.orderID = :orderid"), @NamedQuery(name = "orderejb.findByAccountAccountid", query = "SELECT o FROM orderejb o WHERE o.account.accountID = :accountAccountid"), @NamedQuery(name = "orderejb.findByQuoteSymbol", query = "SELECT o FROM orderejb o WHERE o.quote.symbol = :quoteSymbol"), @NamedQuery(name = "orderejb.findByHoldingHoldingid", query = "SELECT o FROM orderejb o WHERE o.holding.holdingID = :holdingHoldingid"), @NamedQuery(name = "orderejb.closedOrders", query = "SELECT o FROM orderejb o WHERE o.orderStatus = 'closed' AND o.account.profile.userID = :userID"), @NamedQuery(name = "orderejb.completeClosedOrders", query = "UPDATE orderejb o SET o.orderStatus = 'completed' WHERE o.orderStatus = 'closed' AND o.account.profile.userID = :userID") }) public class OrderDataBean implements Serializable { private static final long serialVersionUID = 120650490200739057L; @Id @TableGenerator(name = "orderIdGen", table = "KEYGENEJB", pkColumnName = "KEYNAME", valueColumnName = "KEYVAL", pkColumnValue = "order", allocationSize = 1000) @GeneratedValue(strategy = GenerationType.TABLE, generator = "orderIdGen") @Column(name = "ORDERID", nullable = false) private Integer orderID; /* orderID */ @Column(name = "ORDERTYPE") private String orderType; /* orderType (buy, sell, etc.) */ @Column(name = "ORDERSTATUS") private String orderStatus; /* * orderStatus (open, processing, completed, * closed, cancelled) */ @Column(name = "OPENDATE") @Temporal(TemporalType.TIMESTAMP) private Date openDate; /* openDate (when the order was entered) */ @Column(name = "COMPLETIONDATE") @Temporal(TemporalType.TIMESTAMP) private Date completionDate; /* completionDate */ @NotNull @Column(name = "QUANTITY", nullable = false) private double quantity; /* quantity */ @Column(name = "PRICE") private BigDecimal price; /* price */ @Column(name = "ORDERFEE") private BigDecimal orderFee; /* price */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ACCOUNT_ACCOUNTID") private AccountDataBean account; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "QUOTE_SYMBOL") private QuoteDataBean quote; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "HOLDING_HOLDINGID") private HoldingDataBean holding; /* Fields for relationship fields are not kept in the Data Bean */ @Transient private String symbol; public OrderDataBean() { } public OrderDataBean(Integer orderID, String orderType, String orderStatus, Date openDate, Date completionDate, double quantity, BigDecimal price, BigDecimal orderFee, String symbol) { setOrderID(orderID); setOrderType(orderType); setOrderStatus(orderStatus); setOpenDate(openDate); setCompletionDate(completionDate); setQuantity(quantity); setPrice(price); setOrderFee(orderFee); setSymbol(symbol); } public OrderDataBean(String orderType, String orderStatus, Date openDate, Date completionDate, double quantity, BigDecimal price, BigDecimal orderFee, AccountDataBean account, QuoteDataBean quote, HoldingDataBean holding) { setOrderType(orderType); setOrderStatus(orderStatus); setOpenDate(openDate); setCompletionDate(completionDate); setQuantity(quantity); setPrice(price); setOrderFee(orderFee); setAccount(account); setQuote(quote); setHolding(holding); } public static OrderDataBean getRandomInstance() { return new OrderDataBean(new Integer(TradeConfig.rndInt(100000)), TradeConfig.rndBoolean() ? "buy" : "sell", "open", new java.util.Date( TradeConfig.rndInt(Integer.MAX_VALUE)), new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)), TradeConfig.rndQuantity(), TradeConfig.rndBigDecimal(1000.0f), TradeConfig.rndBigDecimal(1000.0f), TradeConfig.rndSymbol()); } @Override public String toString() { return "Order " + getOrderID() + "\n\t orderType: " + getOrderType() + "\n\t orderStatus: " + getOrderStatus() + "\n\t openDate: " + getOpenDate() + "\n\t completionDate: " + getCompletionDate() + "\n\t quantity: " + getQuantity() + "\n\t price: " + getPrice() + "\n\t orderFee: " + getOrderFee() + "\n\t symbol: " + getSymbol(); } public String toHTML() { return "<BR>Order <B>" + getOrderID() + "</B>" + "<LI> orderType: " + getOrderType() + "</LI>" + "<LI> orderStatus: " + getOrderStatus() + "</LI>" + "<LI> openDate: " + getOpenDate() + "</LI>" + "<LI> completionDate: " + getCompletionDate() + "</LI>" + "<LI> quantity: " + getQuantity() + "</LI>" + "<LI> price: " + getPrice() + "</LI>" + "<LI> orderFee: " + getOrderFee() + "</LI>" + "<LI> symbol: " + getSymbol() + "</LI>"; } public void print() { Log.log(this.toString()); } public Integer getOrderID() { return orderID; } public void setOrderID(Integer orderID) { this.orderID = orderID; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getOrderStatus() { return orderStatus; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } public Date getOpenDate() { return openDate; } public void setOpenDate(Date openDate) { this.openDate = openDate; } public Date getCompletionDate() { return completionDate; } public void setCompletionDate(Date completionDate) { this.completionDate = completionDate; } public double getQuantity() { return quantity; } public void setQuantity(double quantity) { this.quantity = quantity; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getOrderFee() { return orderFee; } public void setOrderFee(BigDecimal orderFee) { this.orderFee = orderFee; } public String getSymbol() { if (quote != null) { return quote.getSymbol(); } return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public AccountDataBean getAccount() { return account; } public void setAccount(AccountDataBean account) { this.account = account; } public QuoteDataBean getQuote() { return quote; } public void setQuote(QuoteDataBean quote) { this.quote = quote; } public HoldingDataBean getHolding() { return holding; } public void setHolding(HoldingDataBean holding) { this.holding = holding; } public boolean isBuy() { String orderType = getOrderType(); if (orderType.compareToIgnoreCase("buy") == 0) { return true; } return false; } public boolean isSell() { String orderType = getOrderType(); if (orderType.compareToIgnoreCase("sell") == 0) { return true; } return false; } public boolean isOpen() { String orderStatus = getOrderStatus(); if ((orderStatus.compareToIgnoreCase("open") == 0) || (orderStatus.compareToIgnoreCase("processing") == 0)) { return true; } return false; } public boolean isCompleted() { String orderStatus = getOrderStatus(); if ((orderStatus.compareToIgnoreCase("completed") == 0) || (orderStatus.compareToIgnoreCase("alertcompleted") == 0) || (orderStatus.compareToIgnoreCase("cancelled") == 0)) { return true; } return false; } public boolean isCancelled() { String orderStatus = getOrderStatus(); if (orderStatus.compareToIgnoreCase("cancelled") == 0) { return true; } return false; } public void cancel() { setOrderStatus("cancelled"); } @Override public int hashCode() { int hash = 0; hash += (this.orderID != null ? this.orderID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof OrderDataBean)) { return false; } OrderDataBean other = (OrderDataBean) object; if (this.orderID != other.orderID && (this.orderID == null || !this.orderID.equals(other.orderID))) { return false; } return true; } }
11,568
33.951662
194
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/entities/QuoteDataBean.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.entities; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Entity(name = "quoteejb") @Table(name = "quoteejb") @NamedQueries({ @NamedQuery(name = "quoteejb.allQuotes", query = "SELECT q FROM quoteejb q")}) @NamedNativeQueries({ @NamedNativeQuery(name = "quoteejb.quoteForUpdate", query = "select * from quoteejb q where q.symbol=? for update", resultClass = com.ibm.websphere.samples.daytrader.entities.QuoteDataBean.class) }) public class QuoteDataBean implements Serializable { /* Accessor methods for persistent fields */ private static final long serialVersionUID = 1847932261895838791L; @Id @NotNull @Column(name = "SYMBOL", nullable = false) private String symbol; /* symbol */ @Column(name = "COMPANYNAME") private String companyName; /* companyName */ @NotNull @Column(name = "VOLUME", nullable = false) private double volume; /* volume */ @Column(name = "PRICE") private BigDecimal price; /* price */ @Column(name = "OPEN1") private BigDecimal open1; /* open1 price */ @Column(name = "LOW") private BigDecimal low; /* low price */ @Column(name = "HIGH") private BigDecimal high; /* high price */ @NotNull @Column(name = "CHANGE1", nullable = false) private double change1; /* price change */ /* Accessor methods for relationship fields are not kept in the DataBean */ public QuoteDataBean() { } public QuoteDataBean(String symbol, String companyName, double volume, BigDecimal price, BigDecimal open, BigDecimal low, BigDecimal high, double change) { setSymbol(symbol); setCompanyName(companyName); setVolume(volume); setPrice(price); setOpen(open); setLow(low); setHigh(high); setChange(change); } public static QuoteDataBean getRandomInstance() { return new QuoteDataBean(TradeConfig.rndSymbol(), // symbol TradeConfig.rndSymbol() + " Incorporated", // Company Name TradeConfig.rndFloat(100000), // volume TradeConfig.rndBigDecimal(1000.0f), // price TradeConfig.rndBigDecimal(1000.0f), // open1 TradeConfig.rndBigDecimal(1000.0f), // low TradeConfig.rndBigDecimal(1000.0f), // high TradeConfig.rndFloat(100000) // volume ); } // Create a "zero" value quoteDataBean for the given symbol public QuoteDataBean(String symbol) { setSymbol(symbol); } @Override public String toString() { return "\n\tQuote Data for: " + getSymbol() + "\n\t\t companyName: " + getCompanyName() + "\n\t\t volume: " + getVolume() + "\n\t\t price: " + getPrice() + "\n\t\t open1: " + getOpen() + "\n\t\t low: " + getLow() + "\n\t\t high: " + getHigh() + "\n\t\t change1: " + getChange(); } public String toHTML() { return "<BR>Quote Data for: " + getSymbol() + "<LI> companyName: " + getCompanyName() + "</LI>" + "<LI> volume: " + getVolume() + "</LI>" + "<LI> price: " + getPrice() + "</LI>" + "<LI> open1: " + getOpen() + "</LI>" + "<LI> low: " + getLow() + "</LI>" + "<LI> high: " + getHigh() + "</LI>" + "<LI> change1: " + getChange() + "</LI>"; } public void print() { Log.log(this.toString()); } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getOpen() { return open1; } public void setOpen(BigDecimal open) { this.open1 = open; } public BigDecimal getLow() { return low; } public void setLow(BigDecimal low) { this.low = low; } public BigDecimal getHigh() { return high; } public void setHigh(BigDecimal high) { this.high = high; } public double getChange() { return change1; } public void setChange(double change) { this.change1 = change; } public double getVolume() { return volume; } public void setVolume(double volume) { this.volume = volume; } @Override public int hashCode() { int hash = 0; hash += (this.symbol != null ? this.symbol.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof QuoteDataBean)) { return false; } QuoteDataBean other = (QuoteDataBean) object; if (this.symbol != other.symbol && (this.symbol == null || !this.symbol.equals(other.symbol))) { return false; } return true; } }
6,232
29.257282
220
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/util/CompleteOrderThread.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.util; import javax.ejb.EJBException; import javax.naming.InitialContext; import javax.transaction.UserTransaction; import com.ibm.websphere.samples.daytrader.TradeServices; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBBean; public class CompleteOrderThread implements Runnable { final Integer orderID; boolean twoPhase; public CompleteOrderThread (Integer id, boolean twoPhase) { orderID = id; this.twoPhase = twoPhase; } @Override public void run() { TradeServices trade; UserTransaction ut = null; try { // TODO: Sometimes, rarely, the commit does not complete before the find in completeOrder (leads to null order) // Adding delay here for now, will try to find a better solution in the future. Thread.sleep(500); InitialContext context = new InitialContext(); ut = (UserTransaction) context.lookup("java:comp/UserTransaction"); ut.begin(); if (TradeConfig.getRunTimeMode() == TradeConfig.EJB3) { trade = (TradeSLSBBean) context.lookup("java:module/TradeSLSBBean"); } else { trade = new TradeDirect(); } trade.completeOrder(orderID, twoPhase); ut.commit(); } catch (Exception e) { try { ut.rollback(); } catch (Exception e1) { throw new EJBException(e1); } throw new EJBException(e); } } }
2,522
34.041667
127
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/util/FinancialUtils.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.util; import java.math.BigDecimal; import java.util.Collection; import java.util.Iterator; import com.ibm.websphere.samples.daytrader.entities.HoldingDataBean; public class FinancialUtils { public static final int ROUND = BigDecimal.ROUND_HALF_UP; public static final int SCALE = 2; public static final BigDecimal ZERO = (new BigDecimal(0.00)).setScale(SCALE); public static final BigDecimal ONE = (new BigDecimal(1.00)).setScale(SCALE); public static final BigDecimal HUNDRED = (new BigDecimal(100.00)).setScale(SCALE); public static BigDecimal computeGain(BigDecimal currentBalance, BigDecimal openBalance) { return currentBalance.subtract(openBalance).setScale(SCALE); } public static BigDecimal computeGainPercent(BigDecimal currentBalance, BigDecimal openBalance) { if (openBalance.doubleValue() == 0.0) { return ZERO; } BigDecimal gainPercent = currentBalance.divide(openBalance, ROUND).subtract(ONE).multiply(HUNDRED); return gainPercent; } public static BigDecimal computeHoldingsTotal(Collection<?> holdingDataBeans) { BigDecimal holdingsTotal = new BigDecimal(0.0).setScale(SCALE); if (holdingDataBeans == null) { return holdingsTotal; } Iterator<?> it = holdingDataBeans.iterator(); while (it.hasNext()) { HoldingDataBean holdingData = (HoldingDataBean) it.next(); BigDecimal total = holdingData.getPurchasePrice().multiply(new BigDecimal(holdingData.getQuantity())); holdingsTotal = holdingsTotal.add(total); } return holdingsTotal.setScale(SCALE); } public static String printGainHTML(BigDecimal gain) { String htmlString, arrow; if (gain.doubleValue() < 0.0) { htmlString = "<FONT color=\"#ff0000\">"; arrow = "arrowdown.gif"; } else { htmlString = "<FONT color=\"#009900\">"; arrow = "arrowup.gif"; } htmlString += gain.setScale(SCALE, ROUND) + "</FONT><IMG src=\"images/" + arrow + "\" width=\"10\" height=\"10\" border=\"0\"></IMG>"; return htmlString; } public static String printChangeHTML(double change) { String htmlString, arrow; if (change < 0.0) { htmlString = "<FONT color=\"#ff0000\">"; arrow = "arrowdown.gif"; } else { htmlString = "<FONT color=\"#009900\">"; arrow = "arrowup.gif"; } htmlString += change + "</FONT><IMG src=\"images/" + arrow + "\" width=\"10\" height=\"10\" border=\"0\"></IMG>"; return htmlString; } public static String printGainPercentHTML(BigDecimal gain) { String htmlString, arrow; if (gain.doubleValue() < 0.0) { htmlString = "(<B><FONT color=\"#ff0000\">"; arrow = "arrowdown.gif"; } else { htmlString = "(<B><FONT color=\"#009900\">+"; arrow = "arrowup.gif"; } htmlString += gain.setScale(SCALE, ROUND); htmlString += "%</FONT></B>)<IMG src=\"images/" + arrow + "\" width=\"10\" height=\"10\" border=\"0\"></IMG>"; return htmlString; } public static String printQuoteLink(String symbol) { return "<A href=\"app?action=quotes&symbols=" + symbol + "\">" + symbol + "</A>"; } }
4,026
37.352381
142
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/util/KeyBlock.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.util; import java.util.AbstractSequentialList; import java.util.ListIterator; public class KeyBlock extends AbstractSequentialList<Object> { // min and max provide range of valid primary keys for this KeyBlock private int min = 0; private int max = 0; private int index = 0; /** * Constructor for KeyBlock */ public KeyBlock() { super(); min = 0; max = 0; index = min; } /** * Constructor for KeyBlock */ public KeyBlock(int min, int max) { super(); this.min = min; this.max = max; index = min; } /** * @see AbstractCollection#size() */ @Override public int size() { return (max - min) + 1; } /** * @see AbstractSequentialList#listIterator(int) */ @Override public ListIterator<Object> listIterator(int arg0) { return new KeyBlockIterator(); } class KeyBlockIterator implements ListIterator<Object> { /** * @see ListIterator#hasNext() */ @Override public boolean hasNext() { return index <= max; } /** * @see ListIterator#next() */ @Override public synchronized Object next() { if (index > max) { throw new java.lang.RuntimeException("KeyBlock:next() -- Error KeyBlock depleted"); } return new Integer(index++); } /** * @see ListIterator#hasPrevious() */ @Override public boolean hasPrevious() { return index > min; } /** * @see ListIterator#previous() */ @Override public Object previous() { return new Integer(--index); } /** * @see ListIterator#nextIndex() */ @Override public int nextIndex() { return index - min; } /** * @see ListIterator#previousIndex() */ @Override public int previousIndex() { throw new UnsupportedOperationException("KeyBlock: previousIndex() not supported"); } /** * @see ListIterator#add() */ @Override public void add(Object o) { throw new UnsupportedOperationException("KeyBlock: add() not supported"); } /** * @see ListIterator#remove() */ @Override public void remove() { throw new UnsupportedOperationException("KeyBlock: remove() not supported"); } /** * @see ListIterator#set(Object) */ @Override public void set(Object arg0) { } } }
3,416
23.407143
99
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/util/Log.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.util; import java.util.Collection; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; public class Log { private final static Logger log = Logger.getLogger("daytrader"); // A general purpose, high performance logging, tracing, statistic service public static void log(String message) { log.log(Level.INFO, message); } public static void log(String msg1, String msg2) { log(msg1 + msg2); } public static void log(String msg1, String msg2, String msg3) { log(msg1 + msg2 + msg3); } public static void error(String message) { message = "Error: " + message; log.severe(message); } public static void error(String message, Throwable e) { error(message + "\n\t" + e.toString()); e.printStackTrace(System.out); } public static void error(String msg1, String msg2, Throwable e) { error(msg1 + "\n" + msg2 + "\n\t", e); } public static void error(String msg1, String msg2, String msg3, Throwable e) { error(msg1 + "\n" + msg2 + "\n" + msg3 + "\n\t", e); } public static void error(Throwable e, String message) { error(message + "\n\t", e); e.printStackTrace(System.out); } public static void error(Throwable e, String msg1, String msg2) { error(msg1 + "\n" + msg2 + "\n\t", e); } public static void error(Throwable e, String msg1, String msg2, String msg3) { error(msg1 + "\n" + msg2 + "\n" + msg3 + "\n\t", e); } public static void trace(String message) { log.log(Level.FINE, message + " threadID=" + Thread.currentThread()); } public static void trace(String message, Object parm1) { trace(message + "(" + parm1 + ")"); } public static void trace(String message, Object parm1, Object parm2) { trace(message + "(" + parm1 + ", " + parm2 + ")"); } public static void trace(String message, Object parm1, Object parm2, Object parm3) { trace(message + "(" + parm1 + ", " + parm2 + ", " + parm3 + ")"); } public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4) { trace(message + "(" + parm1 + ", " + parm2 + ", " + parm3 + ")" + ", " + parm4); } public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4, Object parm5) { trace(message + "(" + parm1 + ", " + parm2 + ", " + parm3 + ")" + ", " + parm4 + ", " + parm5); } public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4, Object parm5, Object parm6) { trace(message + "(" + parm1 + ", " + parm2 + ", " + parm3 + ")" + ", " + parm4 + ", " + parm5 + ", " + parm6); } public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4, Object parm5, Object parm6, Object parm7) { trace(message + "(" + parm1 + ", " + parm2 + ", " + parm3 + ")" + ", " + parm4 + ", " + parm5 + ", " + parm6 + ", " + parm7); } public static void traceEnter(String message) { log.log(Level.FINE,"Method enter --" + message); } public static void traceExit(String message) { log.log(Level.FINE,"Method exit --" + message); } public static void stat(String message) { log(message); } public static void debug(String message) { log.log(Level.INFO,message); } public static void print(String message) { log(message); } public static void printObject(Object o) { log("\t" + o.toString()); } public static void printCollection(Collection<?> c) { log("\t---Log.printCollection -- collection size=" + c.size()); Iterator<?> it = c.iterator(); while (it.hasNext()) { log("\t\t" + it.next().toString()); } log("\t---Log.printCollection -- complete"); } public static void printCollection(String message, Collection<?> c) { log(message); printCollection(c); } public static boolean doActionTrace() { return getTrace() || getActionTrace(); } public static boolean doTrace() { return getTrace(); } public static boolean doDebug() { return true; } public static boolean doStat() { return true; } /** * Gets the trace * * @return Returns a boolean */ public static boolean getTrace() { return TradeConfig.getTrace(); } /** * Gets the trace value for Trade actions only * * @return Returns a boolean */ public static boolean getActionTrace() { return TradeConfig.getActionTrace(); } /** * Sets the trace * * @param trace * The trace to set */ public static void setTrace(boolean traceValue) { TradeConfig.setTrace(traceValue); } /** * Sets the trace value for Trade actions only * * @param trace * The trace to set */ public static void setActionTrace(boolean traceValue) { TradeConfig.setActionTrace(traceValue); } }
5,860
28.305
144
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/util/MDBStats.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.util; /** * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. To enable and disable the creation of type * comments go to Window>Preferences>Java>Code Generation. */ public class MDBStats extends java.util.HashMap<String, TimerStat> { private static final long serialVersionUID = -3759835921094193760L; // Singleton class private static MDBStats mdbStats = null; private MDBStats() { } public static synchronized MDBStats getInstance() { if (mdbStats == null) { mdbStats = new MDBStats(); } return mdbStats; } public TimerStat addTiming(String type, long sendTime, long recvTime) { TimerStat stats = null; synchronized (type) { stats = get(type); if (stats == null) { stats = new TimerStat(); } long time = recvTime - sendTime; if (time > stats.getMax()) { stats.setMax(time); } if (time < stats.getMin()) { stats.setMin(time); } stats.setCount(stats.getCount() + 1); stats.setTotalTime(stats.getTotalTime() + time); put(type, stats); } return stats; } public synchronized void reset() { clear(); } }
2,025
28.362319
80
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/util/TimerStat.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.util; /** * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. To enable and disable the creation of type * comments go to Window>Preferences>Java>Code Generation. */ public class TimerStat { private double min = 1000000000.0, max = 0.0, totalTime = 0.0; private int count; /** * Returns the count. * * @return int */ public int getCount() { return count; } /** * Returns the max. * * @return double */ public double getMax() { return max; } /** * Returns the min. * * @return double */ public double getMin() { return min; } /** * Sets the count. * * @param count * The count to set */ public void setCount(int count) { this.count = count; } /** * Sets the max. * * @param max * The max to set */ public void setMax(double max) { this.max = max; } /** * Sets the min. * * @param min * The min to set */ public void setMin(double min) { this.min = min; } /** * Returns the totalTime. * * @return double */ public double getTotalTime() { return totalTime; } /** * Sets the totalTime. * * @param totalTime * The totalTime to set */ public void setTotalTime(double totalTime) { this.totalTime = totalTime; } /** * Returns the max in Secs * * @return double */ public double getMaxSecs() { return max / 1000.0; } /** * Returns the min in Secs * * @return double */ public double getMinSecs() { return min / 1000.0; } /** * Returns the average time in Secs * * @return double */ public double getAvgSecs() { double avg = getTotalTime() / getCount(); return avg / 1000.0; } }
2,717
19.283582
80
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/util/TradeConfig.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.util; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Random; /** * TradeConfig is a JavaBean holding all configuration and runtime parameters * for the Trade application TradeConfig sets runtime parameters such as the * RunTimeMode (EJB, JDBC, EJB_ALT) * */ public class TradeConfig { /* Trade Runtime Configuration Parameters */ /* Trade Runtime Mode parameters */ public static String[] runTimeModeNames = { "Full EJB3", "Direct (JDBC)"}; public static final int EJB3 = 0; public static final int DIRECT = 1; public static int runTimeMode = EJB3; public static String[] orderProcessingModeNames = { "Sync", "Async_2-Phase", "Async_ManagedThread" }; public static final int SYNCH = 0; public static final int ASYNCH_2PHASE = 1; public static final int ASYNCH_MANAGEDTHREAD = 2; public static int orderProcessingMode = SYNCH; public static String[] accessModeNames = { "Standard", "WebServices" }; public static final int STANDARD = 0; private static int accessMode = STANDARD; /* Trade Web Interface parameters */ public static String[] webInterfaceNames = { "JSP", "JSP-Images" }; public static final int JSP = 0; public static final int JSP_Images = 1; public static int webInterface = JSP; /* Trade Caching Type parameters public static String[] cachingTypeNames = { "DistributedMap", "No Caching" }; public static final int DISTRIBUTEDMAP = 0; public static final int NO_CACHING = 1; public static int cachingType = NO_CACHING; public static int distributedMapCacheSize = 100000; */ /* Trade Database Scaling parameters */ private static int MAX_USERS = 15000; private static int MAX_QUOTES = 10000; /* Trade Database specific paramters */ public static String JDBC_UID = null; public static String JDBC_PWD = null; public static String DS_NAME = "java:comp/env/jdbc/TradeDataSource"; /* Trade XA Datasource specific parameters */ public static boolean JDBCDriverNeedsGlobalTransation = false; /* Trade Config Miscellaneous itmes */ public static String DATASOURCE = "java:comp/env/jdbc/TradeDataSource"; public static int KEYBLOCKSIZE = 1000; public static int QUOTES_PER_PAGE = 10; public static boolean RND_USER = true; // public static int RND_SEED = 0; private static int MAX_HOLDINGS = 10; private static int count = 0; private static Object userID_count_semaphore = new Object(); private static int userID_count = 0; private static String hostName = null; private static Random r0 = new Random(System.currentTimeMillis()); // private static Random r1 = new Random(RND_SEED); private static Random randomNumberGenerator = r0; public static final String newUserPrefix = "ru:"; public static final int verifyPercent = 5; private static boolean trace = false; private static boolean actionTrace = false; private static boolean updateQuotePrices = true; private static int primIterations = 1; private static boolean longRun = true; private static boolean publishQuotePriceChange = true; private static int percentSentToWebsocket = 5; private static boolean displayOrderAlerts = true; private static boolean useRemoteEJBInterface = false; /** * -1 means every operation 0 means never perform a market summary > 0 means * number of seconds between summaries. These will be synchronized so only * one transaction in this period will create a summary and will cache its * results. */ private static int marketSummaryInterval = 20; /* * Penny stocks is a problem where the random price change factor gets a * stock down to $.01. In this case trade jumpstarts the price back to $6.00 * to keep the math interesting. */ public static BigDecimal PENNY_STOCK_PRICE; public static BigDecimal PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER; static { PENNY_STOCK_PRICE = new BigDecimal(0.01); PENNY_STOCK_PRICE = PENNY_STOCK_PRICE.setScale(2, BigDecimal.ROUND_HALF_UP); PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER = new BigDecimal(600.0); PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER.setScale(2, BigDecimal.ROUND_HALF_UP); } /* * CJB (DAYTRADER-25) - Also need to impose a ceiling on the quote price to * ensure prevent account and holding balances from exceeding the databases * decimal precision. At some point, this maximum value can be used to * trigger a stock split. */ public static BigDecimal MAXIMUM_STOCK_PRICE; public static BigDecimal MAXIMUM_STOCK_SPLIT_MULTIPLIER; static { MAXIMUM_STOCK_PRICE = new BigDecimal(400); MAXIMUM_STOCK_PRICE.setScale(2, BigDecimal.ROUND_HALF_UP); MAXIMUM_STOCK_SPLIT_MULTIPLIER = new BigDecimal(0.5); MAXIMUM_STOCK_SPLIT_MULTIPLIER.setScale(2, BigDecimal.ROUND_HALF_UP); } /* * Trade Scenario actions mixes. Each of the array rows represents a * specific Trade Scenario Mix. The columns give the percentages for each * action in the column header. Note: "login" is always 0. logout represents * both login and logout (because each logout operation will cause a new * login when the user context attempts the next action. */ /* Trade Scenario Workload parameters */ public static final int HOME_OP = 0; public static final int QUOTE_OP = 1; public static final int LOGIN_OP = 2; public static final int LOGOUT_OP = 3; public static final int REGISTER_OP = 4; public static final int ACCOUNT_OP = 5; public static final int PORTFOLIO_OP = 6; public static final int BUY_OP = 7; public static final int SELL_OP = 8; public static final int UPDATEACCOUNT_OP = 9; private static int[][] scenarioMixes = { // h q l o r a p b s u { 20, 40, 0, 4, 2, 10, 12, 4, 4, 4 }, // STANDARD { 20, 40, 0, 4, 2, 7, 7, 7, 7, 6 }, // High Volume }; private static char[] actions = { 'h', 'q', 'l', 'o', 'r', 'a', 'p', 'b', 's', 'u' }; private static int sellDeficit = 0; // Tracks the number of buys over sell when a users portfolio is empty // Used to maintain the correct ratio of buys/sells /* JSP pages for all Trade Actions */ public static final int WELCOME_PAGE = 0; public static final int REGISTER_PAGE = 1; public static final int PORTFOLIO_PAGE = 2; public static final int QUOTE_PAGE = 3; public static final int HOME_PAGE = 4; public static final int ACCOUNT_PAGE = 5; public static final int ORDER_PAGE = 6; public static final int CONFIG_PAGE = 7; public static final int STATS_PAGE = 8; public static final int MARKET_SUMMARY_PAGE = 9; // FUTURE Add XML/XSL View public static String[][] webUI = { { "/welcome.jsp", "/register.jsp", "/portfolio.jsp", "/quote.jsp", "/tradehome.jsp", "/account.jsp", "/order.jsp", "/config.jsp", "/runStats.jsp", "/marketSummary.jsp" }, // JSP Interface { "/welcomeImg.jsp", "/registerImg.jsp", "/portfolioImg.jsp", "/quoteImg.jsp", "/tradehomeImg.jsp", "/accountImg.jsp", "/orderImg.jsp", "/config.jsp", "/runStats.jsp", "/marketSummary.jsp" }, // JSP Interface }; // FUTURE: // If a "trade2.properties" property file is supplied, reset the default // values // to match those specified in the file. This provides a persistent runtime // property mechanism during server startup /** * Return the hostname for this system Creation date: (2/16/2000 9:02:25 PM) */ private static String getHostname() { try { if (hostName == null) { hostName = java.net.InetAddress.getLocalHost().getHostName(); // Strip of fully qualifed domain if necessary try { hostName = hostName.substring(0, hostName.indexOf('.')); } catch (Exception e) { } } } catch (Exception e) { Log.error("Exception getting local host name using 'localhost' - ", e); hostName = "localhost"; } return hostName; } /** * Return a Trade UI Web page based on the current configuration This may * return a JSP page or a Servlet page Creation date: (3/14/2000 9:08:34 PM) */ public static String getPage(int pageNumber) { return webUI[webInterface][pageNumber]; } /** * Return the list of run time mode names Creation date: (3/8/2000 5:58:34 * PM) * * @return java.lang.String[] */ public static java.lang.String[] getRunTimeModeNames() { return runTimeModeNames; } private static int scenarioCount = 0; /** * Return a Trade Scenario Operation based on the setting of the current mix * (TradeScenarioMix) Creation date: (2/10/2000 9:08:34 PM) */ public static char getScenarioAction(boolean newUser) { int r = rndInt(100); // 0 to 99 = 100 int i = 0; int sum = scenarioMixes[0][i]; while (sum <= r) { i++; sum += scenarioMixes[0][i]; } incrementScenarioCount(); /* * In TradeScenarioServlet, if a sell action is selected, but the users * portfolio is empty, a buy is executed instead and sellDefecit is * incremented. This allows the number of buy/sell operations to stay in * sync w/ the given Trade mix. */ if ((!newUser) && (actions[i] == 'b')) { synchronized (TradeConfig.class) { if (sellDeficit > 0) { sellDeficit--; return 's'; // Special case for TradeScenarioServlet to note this is a // buy switched to a sell to fix sellDeficit } } } return actions[i]; } public static String getUserID() { String userID; if (RND_USER) { userID = rndUserID(); } else { userID = nextUserID(); } return userID; } private static final BigDecimal orderFee = new BigDecimal("24.95"); private static final BigDecimal cashFee = new BigDecimal("0.0"); public static BigDecimal getOrderFee(String orderType) { if ((orderType.compareToIgnoreCase("BUY") == 0) || (orderType.compareToIgnoreCase("SELL") == 0)) { return orderFee; } return cashFee; } /** * Increment the sell deficit counter Creation date: (6/21/2000 11:33:45 AM) */ public static synchronized void incrementSellDeficit() { sellDeficit++; } public static String nextUserID() { String userID; synchronized (userID_count_semaphore) { userID = "uid:" + userID_count; userID_count++; if (userID_count % MAX_USERS == 0) { userID_count = 0; } } return userID; } public static double random() { return randomNumberGenerator.nextDouble(); } public static String rndAddress() { return rndInt(1000) + " Oak St."; } public static String rndBalance() { // Give all new users a cool mill in which to trade return "1000000"; } public static String rndCreditCard() { return rndInt(100) + "-" + rndInt(1000) + "-" + rndInt(1000) + "-" + rndInt(1000); } public static String rndEmail(String userID) { return userID + "@" + rndInt(100) + ".com"; } public static String rndFullName() { return "first:" + rndInt(1000) + " last:" + rndInt(5000); } public static int rndInt(int i) { return (new Float(random() * i)).intValue(); } public static float rndFloat(int i) { return (new Float(random() * i)).floatValue(); } public static BigDecimal rndBigDecimal(float f) { return (new BigDecimal(random() * f)).setScale(2, BigDecimal.ROUND_HALF_UP); } public static boolean rndBoolean() { return randomNumberGenerator.nextBoolean(); } /** * Returns a new Trade user Creation date: (2/16/2000 8:50:35 PM) */ public static synchronized String rndNewUserID() { return newUserPrefix + getHostname() + System.currentTimeMillis() + count++; } public static float rndPrice() { return ((new Integer(rndInt(200))).floatValue()) + 1.0f; } private static final BigDecimal ONE = new BigDecimal(1.0); public static BigDecimal getRandomPriceChangeFactor() { // CJB (DAYTRADER-25) - Vary change factor between 1.1 and 0.9 double percentGain = rndFloat(1) * 0.1; if (random() < .5) { percentGain *= -1; } percentGain += 1; // change factor is between +/- 20% BigDecimal percentGainBD = (new BigDecimal(percentGain)).setScale(2, BigDecimal.ROUND_HALF_UP); if (percentGainBD.doubleValue() <= 0.0) { percentGainBD = ONE; } return percentGainBD; } public static float rndQuantity() { return ((new Integer(rndInt(200))).floatValue()) + 1.0f; } public static String rndSymbol() { return "s:" + rndInt(MAX_QUOTES - 1); } public static String rndSymbols() { String symbols = ""; int num_symbols = rndInt(QUOTES_PER_PAGE); for (int i = 0; i <= num_symbols; i++) { symbols += "s:" + rndInt(MAX_QUOTES - 1); if (i < num_symbols) { symbols += ","; } } return symbols; } public static String rndUserID() { String nextUser = getNextUserIDFromDeck(); if (Log.doTrace()) { Log.trace("TradeConfig:rndUserID -- new trader = " + nextUser); } return nextUser; } private static synchronized String getNextUserIDFromDeck() { int numUsers = getMAX_USERS(); if (deck == null) { deck = new ArrayList<Integer>(numUsers); for (int i = 0; i < numUsers; i++) { deck.add(i, new Integer(i)); } java.util.Collections.shuffle(deck, r0); } if (card >= numUsers) { card = 0; } return "uid:" + deck.get(card++); } // Trade implements a card deck approach to selecting // users for trading with tradescenarioservlet private static ArrayList<Integer> deck = null; private static int card = 0; /** * Set the list of run time mode names Creation date: (3/8/2000 5:58:34 PM) * * @param newRunTimeModeNames * java.lang.String[] */ public static void setRunTimeModeNames(java.lang.String[] newRunTimeModeNames) { runTimeModeNames = newRunTimeModeNames; } /** * This is a convenience method for servlets to set Trade configuration * parameters from servlet initialization parameters. The servlet provides * the init param and its value as strings. This method then parses the * parameter, converts the value to the correct type and sets the * corresponding TradeConfig parameter to the converted value * */ public static void setConfigParam(String parm, String value) { Log.log("TradeConfig setting parameter: " + parm + "=" + value); // Compare the parm value to valid TradeConfig parameters that can be // set // by servlet initialization // First check the proposed new parm and value - if empty or null ignore // it if (parm == null) { return; } parm = parm.trim(); if (parm.length() <= 0) { return; } if (value == null) { return; } value = value.trim(); if (parm.equalsIgnoreCase("runTimeMode")) { try { for (int i = 0; i < runTimeModeNames.length; i++) { if (value.equalsIgnoreCase(runTimeModeNames[i])) { runTimeMode = i; break; } } } catch (Exception e) { // >>rjm Log.error("TradeConfig.setConfigParm(..): minor exception caught" + "trying to set runtimemode to " + value + "reverting to current value: " + runTimeModeNames[runTimeMode], e); } // If the value is bad, simply revert to current } else if (parm.equalsIgnoreCase("orderProcessingMode")) { try { for (int i = 0; i < orderProcessingModeNames.length; i++) { if (value.equalsIgnoreCase(orderProcessingModeNames[i])) { orderProcessingMode = i; break; } } } catch (Exception e) { Log.error("TradeConfig.setConfigParm(..): minor exception caught" + "trying to set orderProcessingMode to " + value + "reverting to current value: " + orderProcessingModeNames[orderProcessingMode], e); } // If the value is bad, simply revert to current } else if (parm.equalsIgnoreCase("accessMode")) { try { for (int i = 0; i < accessModeNames.length; i++) { if (value.equalsIgnoreCase(accessModeNames[i])) { accessMode = i; break; } } } catch (Exception e) { Log.error("TradeConfig.setConfigParm(..): minor exception caught" + "trying to set accessMode to " + value + "reverting to current value: " + accessModeNames[accessMode], e); } } else if (parm.equalsIgnoreCase("WebInterface")) { try { for (int i = 0; i < webInterfaceNames.length; i++) { if (value.equalsIgnoreCase(webInterfaceNames[i])) { webInterface = i; break; } } } catch (Exception e) { Log.error("TradeConfig.setConfigParm(..): minor exception caught" + "trying to set WebInterface to " + value + "reverting to current value: " + webInterfaceNames[webInterface], e); } // If the value is bad, simply revert to current } /*else if (parm.equalsIgnoreCase("CachingType")) { try { for (int i = 0; i < cachingTypeNames.length; i++) { if (value.equalsIgnoreCase(cachingTypeNames[i])) { cachingType = i; break; } } } catch (Exception e) { Log.error("TradeConfig.setConfigParm(..): minor exception caught" + "trying to set CachingType to " + value + "reverting to current value: " + cachingTypeNames[cachingType], e); } // If the value is bad, simply revert to current }*/ else if (parm.equalsIgnoreCase("maxUsers")) { try { MAX_USERS = Integer.parseInt(value); } catch (Exception e) { Log.error("TradeConfig.setConfigParm(..): minor exception caught" + "Setting maxusers, error parsing string to int:" + value + "revering to current value: " + MAX_USERS, e); } // On error, revert to saved } else if (parm.equalsIgnoreCase("maxQuotes")) { try { MAX_QUOTES = Integer.parseInt(value); } catch (Exception e) { // >>rjm Log.error("TradeConfig.setConfigParm(...) minor exception caught" + "Setting max_quotes, error parsing string to int " + value + "reverting to current value: " + MAX_QUOTES, e); // <<rjm } // On error, revert to saved } else if (parm.equalsIgnoreCase("primIterations")) { try { primIterations = Integer.parseInt(value); } catch (Exception e) { Log.error("TradeConfig.setConfigParm(..): minor exception caught" + "Setting primIterations, error parsing string to int:" + value + "revering to current value: " + primIterations, e); } // On error, revert to saved } /*else if (parm.equalsIgnoreCase("DistMapCacheSize")) { try { distributedMapCacheSize = Integer.parseInt(value); } catch (Exception e) { // >>rjm Log.error("TradeConfig.setConfigParm(...) minor exception caught" + "Setting distributedMapCacheSize, error parsing string" + value + "reverting to current value: " + distributedMapCacheSize, e); // <<rjm } // On error, revert to saved }*/ } /** * Gets the orderProcessingModeNames * * @return Returns a String[] */ public static String[] getOrderProcessingModeNames() { return orderProcessingModeNames; } /** * Gets the webInterfaceNames * * @return Returns a String[] */ public static String[] getWebInterfaceNames() { return webInterfaceNames; } /** * Gets the webInterfaceNames * * @return Returns a String[] */ /*public static String[] getCachingTypeNames() { return cachingTypeNames; }*/ /** * Gets the scenarioMixes * * @return Returns a int[][] */ public static int[][] getScenarioMixes() { return scenarioMixes; } /** * Gets the trace * * @return Returns a boolean */ public static boolean getTrace() { return trace; } /** * Sets the trace * * @param trace * The trace to set */ public static void setTrace(boolean traceValue) { trace = traceValue; } /** * Gets the mAX_USERS. * * @return Returns a int */ public static int getMAX_USERS() { return MAX_USERS; } /** * Sets the mAX_USERS. * * @param mAX_USERS * The mAX_USERS to set */ public static void setMAX_USERS(int mAX_USERS) { MAX_USERS = mAX_USERS; deck = null; // reset the card deck for selecting users } /** * Gets the mAX_QUOTES. * * @return Returns a int */ public static int getMAX_QUOTES() { return MAX_QUOTES; } /** * Sets the mAX_QUOTES. * * @param mAX_QUOTES * The mAX_QUOTES to set */ public static void setMAX_QUOTES(int mAX_QUOTES) { MAX_QUOTES = mAX_QUOTES; } /** * Gets the mAX_HOLDINGS. * * @return Returns a int */ public static int getMAX_HOLDINGS() { return MAX_HOLDINGS; } /** * Sets the mAX_HOLDINGS. * * @param mAX_HOLDINGS * The mAX_HOLDINGS to set */ public static void setMAX_HOLDINGS(int mAX_HOLDINGS) { MAX_HOLDINGS = mAX_HOLDINGS; } /** * Gets the actionTrace. * * @return Returns a boolean */ public static boolean getActionTrace() { return actionTrace; } /** * Sets the actionTrace. * * @param actionTrace * The actionTrace to set */ public static void setActionTrace(boolean actionTrace) { TradeConfig.actionTrace = actionTrace; } /** * Gets the scenarioCount. * * @return Returns a int */ public static int getScenarioCount() { return scenarioCount; } /** * Sets the scenarioCount. * * @param scenarioCount * The scenarioCount to set */ public static void setScenarioCount(int scenarioCount) { TradeConfig.scenarioCount = scenarioCount; } public static synchronized void incrementScenarioCount() { scenarioCount++; } /** * Gets the jdbc driver needs global transaction Some XA Drivers require a * global transaction to be started for all SQL calls. To work around this, * set this to true to cause the direct mode to start a user transaction. * * @return Returns a boolean */ public static boolean getJDBCDriverNeedsGlobalTransation() { return JDBCDriverNeedsGlobalTransation; } /** * Sets the jdbc driver needs global transaction * * @param JDBCDriverNeedsGlobalTransationVal * the value */ public static void setJDBCDriverNeedsGlobalTransation(boolean JDBCDriverNeedsGlobalTransationVal) { JDBCDriverNeedsGlobalTransation = JDBCDriverNeedsGlobalTransationVal; } /** * Gets the updateQuotePrices. * * @return Returns a boolean */ public static boolean getUpdateQuotePrices() { return updateQuotePrices; } /** * Sets the updateQuotePrices. * * @param updateQuotePrices * The updateQuotePrices to set */ public static void setUpdateQuotePrices(boolean updateQuotePrices) { TradeConfig.updateQuotePrices = updateQuotePrices; } public static int getPrimIterations() { return primIterations; } public static void setPrimIterations(int iter) { primIterations = iter; } public static boolean getLongRun() { return longRun; } public static void setLongRun(boolean longRun) { TradeConfig.longRun = longRun; } public static void setPublishQuotePriceChange(boolean publishQuotePriceChange) { TradeConfig.publishQuotePriceChange = publishQuotePriceChange; } public static boolean getPublishQuotePriceChange() { return publishQuotePriceChange; } public static void setMarketSummaryInterval(int seconds) { TradeConfig.marketSummaryInterval = seconds; } public static int getMarketSummaryInterval() { return TradeConfig.marketSummaryInterval; } public static void setRunTimeMode(int value) { runTimeMode = value; } public static int getRunTimeMode() { return runTimeMode; } public static void setOrderProcessingMode(int value) { orderProcessingMode = value; } public static int getOrderProcessingMode() { return orderProcessingMode; } public static void setAccessMode(int value) { accessMode = value; } public static int getAccessMode() { return accessMode; } public static void setWebInterface(int value) { webInterface = value; } public static int getWebInterface() { return webInterface; } /*public static void setCachingType(int value) { cachingType = value; } public static int getCachingType() { return cachingType; } */ public static void setDisplayOrderAlerts(boolean value) { displayOrderAlerts = value; } public static boolean getDisplayOrderAlerts() { return displayOrderAlerts; } /* public static void setDistributedMapCacheSize(int value) { distributedMapCacheSize = value; } public static int getDistributedMapCacheSize() { return distributedMapCacheSize; }*/ public static void setPercentSentToWebsocket(int value) { percentSentToWebsocket = value; } public static int getPercentSentToWebsocket() { return percentSentToWebsocket; } public static void setUseRemoteEJBInterface(boolean value) { useRemoteEJBInterface = value; } public static boolean useRemoteEJBInterface() { return useRemoteEJBInterface; } }
28,634
31.725714
158
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-ejb/src/main/java/com/ibm/websphere/samples/daytrader/util/WebSocketJMSMessage.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.util; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE}) public @interface WebSocketJMSMessage { }
1,027
31.125
89
java