/** * Method that allows the Manager to view room availability by date. * * @param date date that Manager chooses to view * @author Aishwarya Borkar */ public void updateViewByDay(Calendar date) { String roomInformation = ""; for (int i = 0; i < roomList.size(); i++) { Room room = roomList.get(i); for (int j = 0; j < room.reservations.size(); j++) { Reservation r = room.reservations.get(j); if (r.occupied(date)) { room.setAvailable(false); for (ChangeListener l : listeners) { l.stateChanged(new ChangeEvent(this)); } String email = r.getGuestEmail(); AccountList al = new AccountList(); if (al.accountFoundInList(email)) { roomInformation = "Guest " + email + "Price: " + room.getRate() + "Room number: " + room.getRoomNumber(); } } else { room.setAvailable(true); for (ChangeListener l : listeners) { l.stateChanged(new ChangeEvent(this)); } } } } }
public void showPrevWinner(Reservation obj) { TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); String m_deviceId = TelephonyMgr.getDeviceId(); JsonObject bidPrevData = new JsonObject(); // ValueProvider obj1 = new ValueProvider(); JsonObject bidPrevDataBody = new JsonObject(); bidPrevData.addProperty("user_id", "user4"); bidPrevData.addProperty("room_no", obj.getLocation()); bidPrevData.addProperty("start_time", String.valueOf(obj.getStartDate().getTime())); bidPrevData.addProperty("end_time", String.valueOf(obj.getEndDate().getTime())); bidPrevData.addProperty("temperature_f", "0"); // bidData.addProperty("temperature_f", temp_1.getValue(); bidPrevData.addProperty("bid_amount", "0"); bidPrevData.addProperty("timestamp", date.getTime()); bidPrevDataBody.add("bidTemperature", bidPrevData); JsonObject creditData = new JsonObject(); JsonObject creditDataBody = new JsonObject(); creditData.addProperty("user_id", "user4"); creditDataBody.add("UserCredit", creditData); // Gets winning temperature before with bidding is done new GetWinnerHistory(this).execute(bidPrevDataBody.toString()); // // // Gets user credit before the bid is done. new GetCreditController(this).execute(creditDataBody.toString()); // currentWinner.setText(obj1.getPrevWinner()); // // myCoins.setText(obj1.getCredit()); }
/** * Counts the number of instances in EC2 currently running that are using the specified image and * a template. * * @param ami If AMI is left null, then all instances are counted and template description is * ignored. * <p>This includes those instances that may be started outside Jenkins. * @param templateDesc */ public int countCurrentEC2Slaves(String ami, String templateDesc) throws AmazonClientException { int n = 0; for (Reservation r : connect().describeInstances().getReservations()) { for (Instance i : r.getInstances()) { if (isEc2ProvisionedAmiSlave(i, ami, templateDesc)) { InstanceStateName stateName = InstanceStateName.fromValue(i.getState().getName()); if (stateName == InstanceStateName.Pending || stateName == InstanceStateName.Running) { EC2AbstractSlave foundSlave = null; for (EC2AbstractSlave ec2Node : NodeIterator.nodes(EC2AbstractSlave.class)) { if (ec2Node.getInstanceId().equals(i.getInstanceId())) { foundSlave = ec2Node; break; } } // Don't count disconnected slaves as being used, we will connected them later is // required if (foundSlave != null && foundSlave.toComputer().isOffline()) continue; n++; } } } } // Count pending spot requests too for (SpotInstanceRequest sir : connect().describeSpotInstanceRequests().getSpotInstanceRequests()) { // Count Spot requests that are open and still have a // chance to be active. if (sir.getState().equals("open")) { n++; } } return n; }
public Reservation reconstructReservation(CalendarEntry calEntry) { Reservation reservation = new Reservation(); reservation.setReservationID(String.valueOf(calEntry.getEntryID())); reservation.setStatus(calEntry.getStatus()); reservation.setResource(reconstructResource(calEntry)); return reservation; }
@Override public void put(final Reservation reservation) { log.trace("ReservationManagerImpl.put({})", reservation); checkRunning(); reservationsCacheLock.lock(); try { CacheItem<Reservation> item = new CacheItem<Reservation>(stopwatchProvider.get(), reservation); reservationsBySrk.put(reservation.getSecretReservationKeys(), item); for (NodeUrn nodeUrn : reservation.getNodeUrns()) { List<CacheItem<Reservation>> entry = reservationsByNodeUrn.get(nodeUrn); if (entry == null) { entry = Lists.newArrayList(); reservationsByNodeUrn.put(nodeUrn, entry); } entry.add(item); } } finally { reservationsCacheLock.unlock(); } }
/** * Return all reservations of user define by user name. * * @param user User name * @return ArrayList Reservation */ public ArrayList<Reservation> getUserReservation(String user) { if (doLog) Log.d(TAG, "get reservations for user"); ArrayList<Reservation> comments = new ArrayList<Reservation>(); Cursor cursor = database.query( MySQLiteOpenHelper.TABLE_RESERVATION, allColumnsReservation, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Reservation record = cursorToReservation(cursor); if (record.getUser().equals(user)) { comments.add(record); } cursor.moveToNext(); } cursor.close(); if (doLog) Log.d(TAG, comments.size() + "is returned"); return comments; }
/** * Send data. * * @param obj the obj */ public void sendData(Reservation obj) { JsonObject bidData = new JsonObject(); JsonObject bidDataBody = new JsonObject(); TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); String m_deviceId = TelephonyMgr.getDeviceId(); bidData.addProperty("user_id", "user4"); bidData.addProperty("room_no", obj.getLocation()); bidData.addProperty("start_time", String.valueOf(obj.getStartDate().getTime())); bidData.addProperty("end_time", String.valueOf(obj.getEndDate().getTime())); bidData.addProperty("temperature_f", temp_1.getText().toString()); // bidData.addProperty("temperature_f", temp_1.getValue(); bidData.addProperty("bid_amount", coins_1.getText().toString()); bidData.addProperty("timestamp", date.getTime()); bidDataBody.add("bidTemperature", bidData); // GetBidResult winTemp = new GetBidResult(); // Log.d("test_2", winTemp.doInBackground()); // currentWinner.setText(winTemp.doInBackground()); Log.d("test_2", bidDataBody.toString()); new BidTemperatureController(this).execute(bidDataBody.toString()); // Adding credits data // Log.d("test_2", creditDataBody.toString()); }
public void makeSeatings() { int rows = theater.getRows(); int seatsInRow = theater.getSeatsInRow(); MySQL.getReservations(); for (Reservation reservation : MySQL.sendReservations()) { for (int i = 0; i < reservation.getSeats().get(0).length - 1; i++) { pladser[reservation.getRows().get(0)][reservation.getSeats().get(0)[i]] = true; } } }
/** * Prüfe, ob eine Ressource für ein bestimmten Appointment reserviert ist. * * @param alloc * @param when * @return <code>true</code>, wenn die Ressource reserviert ist. <code>false</code> sonst */ private boolean isReserved(Allocatable alloc, Appointment when) { Reservation reservation = when.getReservation(); Appointment[] restrictions = reservation.getRestriction(alloc); for (int restIt = 0, restLen = restrictions.length; restIt < restLen; restIt++) { if (when.equals(restrictions[restIt])) return true; } return (restrictions.length == 0); }
/** * Insert ArrayList<Reservation> inserting Reservation into database. If is in database * Reservation with same reservation id reservation will not be inserted. * * @param res ArrayList of Reservation */ public void createReservation(ArrayList<Reservation> res) { if (doLog) Log.d(TAG, "create reservations"); Iterator<Reservation> it = res.iterator(); Reservation help; while (it.hasNext()) { help = it.next(); if (!getReservationsById(help.getReservationId())) { createReservation(help); } } }
public static void sortAll() { nameSort = reservations.clone(); dateArriveSort = reservations.clone(); dateDepartSort = reservations.clone(); Reservation.setCompare(nameSort, Reservation.NAME); Sorts.quickSort(nameSort); Reservation.setCompare(dateArriveSort, Reservation.ARRIVAL); Sorts.quickSort(dateArriveSort); Reservation.setCompare(dateArriveSort, Reservation.DEPART); Sorts.quickSort(dateDepartSort); }
/** * Fügt einem iCal-Event den Termin-Namen aus dem übergebenen Appointment-Objekt hinzu. * * @param appointment */ private void addEventNameToEvent(Appointment appointment, PropertyList properties) { Reservation reservation = appointment.getReservation(); final Locale locale = raplaLocale.getLocale(); String eventDescription = NameFormatUtil.getExportName(appointment, locale); if (reservation .getClassification() .getType() .getAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT_EXPORT) == null) { eventDescription += getAttendeeString(appointment); } properties.add(new Summary(eventDescription)); }
/** * Check if reservation with same reservation id is not already in database. * * @param id Reservation id * @return True if exist. */ public boolean getReservationsById(long id) { ArrayList<Reservation> res = getAllReservations(); Iterator<Reservation> it = res.iterator(); while (it.hasNext()) { Reservation help = it.next(); Log.d(TAG, help.getUser() + " " + help.getReservationId()); if (help.getReservationId() == id) { if (doLog) Log.d(TAG, "reservation with id: " + id + " exist"); return true; } } if (doLog) Log.d(TAG, "reservation with id: " + id + " doesnt exist"); return false; }
/** Query amazon to get ASG name. Currently not available as part of instance info api. */ private String populateASGName(String region, String instanceId) { AmazonEC2 client = new AmazonEC2Client(provider.getCredentials()); client.setEndpoint("ec2." + region + ".amazonaws.com"); DescribeInstancesRequest desc = new DescribeInstancesRequest().withInstanceIds(instanceId); DescribeInstancesResult res = client.describeInstances(desc); for (Reservation resr : res.getReservations()) { for (Instance ins : resr.getInstances()) { for (com.amazonaws.services.ec2.model.Tag tag : ins.getTags()) { if (tag.getKey().equals("aws:autoscaling:groupName")) return tag.getValue(); } } } return null; }
@Override public Optional<Reservation> lookup(final Set<SecretReservationKey> srks) { log.trace("ReservationCacheImpl.lookup({})", srks); checkRunning(); CacheItem<Reservation> item = reservationsBySrk.get(srks); if (item != null) { if (item.isOutdated()) { return Optional.absent(); } Reservation reservation = item.get(); reservation.touch(); return Optional.of(reservation); } return Optional.absent(); }
@Override public void checkOut(Integer reservId) { if (reservId == null) { throw new NullPointerException("Id is null"); } if (reservId < 0) { throw new IllegalArgumentException("ID can't be negative"); } Reservation reservation = reservManag.findReservation(reservId); int roomId = reservation.getIdRoom(); reservManag.deleteReservation(reservation); roomManag.editRoom(roomManag.findRoom(roomId), 0); }
@Override public String retriableCall() throws IllegalStateException { DescribeInstancesRequest desc = new DescribeInstancesRequest().withInstanceIds(instanceId); DescribeInstancesResult res = client.describeInstances(desc); for (Reservation resr : res.getReservations()) { for (Instance ins : resr.getInstances()) { for (com.amazonaws.services.ec2.model.Tag tag : ins.getTags()) { if (tag.getKey().equals("aws:autoscaling:groupName")) return tag.getValue(); } } } logger.warn("Couldn't determine ASG name"); throw new IllegalStateException("Couldn't determine ASG name"); }
@Override public Reservation chceckIn( String responsiblePerson, String account, Date dateOfCheckIn, int duration, int numBeds) throws SQLException { if (responsiblePerson == null) { throw new NullPointerException("Responsible person is null"); } if (account == null) { throw new NullPointerException("Account is null"); } if (dateOfCheckIn == null) { throw new NullPointerException("Date is null"); } if (duration <= 0) { throw new IllegalArgumentException("duration can't be negative or zero"); } if (numBeds <= 0) { throw new IllegalArgumentException("Number of Beds can'ŧ be negative or zero"); } Reservation reservation = new Reservation(responsiblePerson, account, dateOfCheckIn, duration, numBeds); Room room = null; Set<Room> rooms = roomManag.findAllFreeRooms(); for (Room rm : rooms) { if (rm.getNumberOfBeds() == numBeds && rm.getIdRes() == 0) { room = rm; break; } } if (room == null) { return null; } reservation.setIdRoom(room.getId()); reservation = reservManag.storeReservation(reservation); roomManag.editRoom(room, reservation.getId()); return reservation; }
public static String formatReservation(Reservation r) { String str = r.toString(); String formatted = str.substring(0, str.indexOf(" ")); int period = daySchedule[SchoolCalendar.dates[r.month - 1][r.date - 1] - 'a'][r.period]; formatted += (period == 0 ? " after school" : " during period " + period) + " " + roomInfo[r.roomID]; return formatted; }
public void onClick(View v) { if (v.getId() == R.id.confirm) { // add code to remove the reservation dateFormat = new SimpleDateFormat("MM/dd/yyyy h:mm a", Locale.US); DateFormat transDateFormat = new SimpleDateFormat("MM/dd/yyyy"); DateFormat transTimeFormat = new SimpleDateFormat("h:mm a"); Long checkDate = null; Long returnDate = null; Date date = new Date(); String resNum = ""; for (Reservation temp : otterLibrary.reservations) { if (myBook.equals(temp.getReservedBook())) { System.out.println("they are equal"); otterLibrary.availableBooks.add( myBook); // this should let the book be available for a hold again checkDate = temp.getCheckoutDate(); returnDate = temp.getReturnDate(); resNum = Integer.toString(temp.getReservationNumber()); } } otterLibrary.addToLogs("----------------", "---------------"); otterLibrary.addToLogs("Transaction Type: ", "Cancel Hold"); otterLibrary.addToLogs("Customer's Username: "******"Book Title: ", myBook.getTitle()); otterLibrary.addToLogs("Pickup Date: ", dateFormat.format(checkDate)); otterLibrary.addToLogs("Return Date: ", dateFormat.format(returnDate)); otterLibrary.addToLogs("Reservation Number: ", resNum); otterLibrary.addToLogs( "Transaction Date: ", transDateFormat.format(date)); // double check this otterLibrary.addToLogs("Transaction Time: ", transTimeFormat.format(date)); otterLibrary.addToLogs("----------------", "---------------"); Intent i = new Intent(this, MainActivity.class); startActivity(i); } }
/* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public final void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bidding_main); // How to get values from intent call Bundle b = getIntent().getExtras(); final Reservation obj = (Reservation) b.getSerializable("SelectedList"); myCoins = (TextView) findViewById(R.id.tvTotCoins); buttonBid = (Button) findViewById(R.id.buttonBid); bAmount = (Button) findViewById(R.id.BarGraph); // testButton = (Button) findViewById(R.id.test); display = (TextView) findViewById(R.id.tvDisplay); // userEmail = (TextView) findViewById(R.id.) display.setText(obj.toString()); temp_1 = (EditText) findViewById(R.id.etTemp); coins_1 = (EditText) findViewById(R.id.etCoins); currentWinner = (EditText) findViewById(R.id.etWinTempVal); showPrevWinner(obj); // Intent m = new Intent(this, UserPreferencesController.class); // startActivity(m); buttonBid.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { sendData(obj); } }); bAmount.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { showGraph(v); } }); }
@Override public Optional<Reservation> lookup(final NodeUrn nodeUrn, final DateTime timestamp) { log.trace("ReservationCacheImpl.lookup({}, {})", nodeUrn, timestamp); checkRunning(); synchronized (reservationsByNodeUrn) { final List<CacheItem<Reservation>> entry = reservationsByNodeUrn.get(nodeUrn); if (entry == null) { log.trace("ReservationManagerImpl.lookup() CACHE MISS"); return Optional.absent(); } for (CacheItem<Reservation> item : entry) { final Interval effectiveInterval; final Reservation reservation = item.get(); final DateTime reservationStart = reservation.getInterval().getStart(); final DateTime reservationCancellation = reservation.getCancelled(); if (reservationCancellation != null) { if (reservationCancellation.isBefore(reservationStart)) { continue; } else { effectiveInterval = new Interval(reservationStart, reservationCancellation); } } else { effectiveInterval = reservation.getInterval(); } if (effectiveInterval.contains(timestamp)) { if (!item.isOutdated()) { item.touch(); log.trace("ReservationManagerImpl.lookup() CACHE HIT"); return Optional.of(reservation); } } } } return Optional.absent(); }
private Reservation cursorToReservation(Cursor cursor) { Reservation comment = new Reservation(); comment.setReservationId(cursor.getLong(0)); comment.setUser(cursor.getString(1)); comment.setPassword(cursor.getString(2)); comment.setStart(cursor.getLong(3)); comment.setEnd(cursor.getLong(4)); comment.setUserId(cursor.getLong(5)); return comment; }
private void addDescriptionToEvent(Appointment appointment, PropertyList properties) { Reservation reservation = appointment.getReservation(); String eventDescription; if (reservation .getClassification() .getType() .getAnnotation(DynamicTypeAnnotations.KEY_DESCRIPTION_FORMAT_EXPORT) != null) { eventDescription = reservation.format( raplaLocale.getLocale(), DynamicTypeAnnotations.KEY_DESCRIPTION_FORMAT_EXPORT, appointment); } else { eventDescription = null; } if (eventDescription != null) { properties.add(new Description(eventDescription)); } }
public String getAttendeeString(Appointment appointment) { String attendeeString = ""; Reservation raplaReservation = appointment.getReservation(); Allocatable[] raplaPersons = raplaReservation.getPersons(); for (int i = 0; i < raplaPersons.length; i++) { if (!isReserved(raplaPersons[i], appointment)) continue; attendeeString += raplaPersons[i].getName(raplaLocale.getLocale()); attendeeString = attendeeString.trim(); if (i != raplaPersons.length - 1) { attendeeString += ", "; } else { attendeeString = " [" + attendeeString + "]"; } } return attendeeString; }
@Override public void remove(Reservation reservation) { log.trace("ReservationCacheImpl.remove({})", reservation); checkRunning(); reservationsCacheLock.lock(); try { int removedNodeCacheEntries = 0; for (Iterator<Map.Entry<NodeUrn, List<CacheItem<Reservation>>>> cacheIterator = reservationsByNodeUrn.entrySet().iterator(); cacheIterator.hasNext(); ) { final Map.Entry<NodeUrn, List<CacheItem<Reservation>>> entry = cacheIterator.next(); for (Iterator<CacheItem<Reservation>> itemIt = entry.getValue().iterator(); itemIt.hasNext(); ) { final CacheItem<Reservation> item = itemIt.next(); final Reservation res = item.get(); if (res == reservation) { itemIt.remove(); removedNodeCacheEntries++; } } if (entry.getValue().isEmpty()) { cacheIterator.remove(); } } log.trace("ReservationCacheImpl removed {} node cache entries", removedNodeCacheEntries); reservationsBySrk.remove(reservation.getSecretReservationKeys()); } finally { reservationsCacheLock.unlock(); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Loginse user bilgilerini al, textboxlari readonly yap, degilse textboxtakileri al User user = (User) request.getSession().getAttribute("user"); if (user == null) { String name = request.getParameter("reservation-name"); String lastName = request.getParameter("reservation-lastname"); String email = request.getParameter("reservation-email"); String phone = request.getParameter("reservation-phone"); } else { String name = user.getFirstName(); String lastName = user.getLastName(); String email = user.getEmail(); String phone = user.getPhoneNumber(); } Address pickup = new Address(); pickup.setBuildingNo(Integer.parseInt(request.getParameter("pickupbuilding-no"))); pickup.setStreet(request.getParameter("pickupstreet")); pickup.setCity(request.getParameter("pickuphomecity")); pickup.setState(request.getParameter("pickupstate")); pickup.setZip(Integer.parseInt(request.getParameter("pickuphomezip"))); pickup.setCountry(request.getParameter("pickupcountry")); Address destination = new Address(); destination.setBuildingNo(Integer.parseInt(request.getParameter("destinationbuilding-no"))); destination.setStreet(request.getParameter("destinationstreet")); destination.setCity(request.getParameter("destinationhomecity")); destination.setState(request.getParameter("destinationstate")); destination.setZip(Integer.parseInt(request.getParameter("destinationzip"))); destination.setCountry(request.getParameter("destinationcountry")); int passengerNo = Integer.parseInt(request.getParameter("passenger-no")); int luggageNo = Integer.parseInt(request.getParameter("luggage-no")); double fareMultiplier = 0; String vehicleType = request.getParameter("vehicle-radio"); if ("sedan".equals(vehicleType)) { fareMultiplier = 3; } else if ("suv".equals(vehicleType)) { fareMultiplier = 5; } else if ("blackcar".equals(vehicleType)) { fareMultiplier = 4.5; } ReservationService service = new ReservationService(); double distance = service.calculateDistance(pickup, destination); double initialFare = 10; double amount = fareMultiplier * distance + initialFare; boolean isPet = false; // isPet is going to be retrieved from checkbox // boolean isCash = request.getParameter("payment-method"); boolean isCash = false; Payment payment = new Payment(isCash); payment.setAmount(amount); if (!isCash) { if (!payment.isPaid()) { // chargeCustormer(); } // payment.setCredit() } Reservation reservation = new Reservation(); reservation.setComment("Write a comment"); }
/** * Provisions an On-demand EC2 slave by launching a new instance or starting a previously-stopped * instance. */ private EC2AbstractSlave provisionOndemand( TaskListener listener, Label requiredLabel, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logProvisionInfo(logger, "Considering launching " + ami + " for template " + description); KeyPair keyPair = getKeyPair(ec2); RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1); InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); riRequest.setEbsOptimized(ebsOptimized); if (useEphemeralDevices) { setupEphemeralDeviceMapping(riRequest); } else { setupCustomDeviceMapping(riRequest); } if (stopOnTerminate) { riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Stop); logProvisionInfo( logger, "Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Stop"); } else { riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate); logProvisionInfo( logger, "Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Terminate"); } List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); if (getUseDedicatedTenancy()) { placement.setTenancy("dedicated"); } riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } if (StringUtils.isNotBlank(getSubnetId())) { if (getAssociatePublicIp()) { net.setSubnetId(getSubnetId()); } else { riRequest.setSubnetId(getSubnetId()); } diFilters.add(new Filter("subnet-id").withValues(getSubnetId())); /* * If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> groupIds = getEc2SecurityGroups(ec2); if (!groupIds.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(groupIds); } else { riRequest.setSecurityGroupIds(groupIds); } diFilters.add(new Filter("instance.group-id").withValues(groupIds)); } } } else { /* No subnet: we can use standard security groups by name */ riRequest.setSecurityGroups(securityGroupSet); if (!securityGroupSet.isEmpty()) { diFilters.add(new Filter("instance.group-name").withValues(securityGroupSet)); } } String userDataString = Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8)); riRequest.setUserData(userDataString); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); riRequest.setInstanceType(type.toString()); diFilters.add(new Filter("instance-type").withValues(type.toString())); if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); riRequest.withNetworkInterfaces(net); } boolean hasCustomTypeTag = false; HashSet<Tag> instTags = null; if (tags != null && !tags.isEmpty()) { instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); diFilters.add(new Filter("tag:" + t.getName()).withValues(t.getValue())); if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { hasCustomTypeTag = true; } } } if (!hasCustomTypeTag) { if (instTags == null) { instTags = new HashSet<Tag>(); } // Append template description as well to identify slaves provisioned per template instTags.add( new Tag( EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, EC2Cloud.getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_DEMAND, description))); } DescribeInstancesRequest diRequest = new DescribeInstancesRequest(); diRequest.setFilters(diFilters); logProvision(logger, "Looking for existing instances with describe-instance: " + diRequest); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); EC2AbstractSlave[] ec2Node = new EC2AbstractSlave[1]; Instance existingInstance = null; if (!provisionOptions.contains(ProvisionOptions.FORCE_CREATE)) { reservationLoop: for (Reservation reservation : diResult.getReservations()) { for (Instance instance : reservation.getInstances()) { if (checkInstance(logger, instance, requiredLabel, ec2Node)) { existingInstance = instance; logProvision( logger, "Found existing instance: " + existingInstance + ((ec2Node[0] != null) ? (" node: " + ec2Node[0].getInstanceId()) : "")); break reservationLoop; } } } } if (existingInstance == null) { if (!provisionOptions.contains(ProvisionOptions.FORCE_CREATE) && !provisionOptions.contains(ProvisionOptions.ALLOW_CREATE)) { logProvision(logger, "No existing instance found - but cannot create new instance"); return null; } if (StringUtils.isNotBlank(getIamInstanceProfile())) { riRequest.setIamInstanceProfile( new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } // Have to create a new instance Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0); /* Now that we have our instance, we can set tags on it */ if (instTags != null) { updateRemoteTags(ec2, instTags, "InvalidInstanceID.NotFound", inst.getInstanceId()); // That was a remote request - we should also update our // local instance data. inst.setTags(instTags); } logProvisionInfo(logger, "No existing instance found - created new instance: " + inst); return newOndemandSlave(inst); } if (existingInstance .getState() .getName() .equalsIgnoreCase(InstanceStateName.Stopping.toString()) || existingInstance .getState() .getName() .equalsIgnoreCase(InstanceStateName.Stopped.toString())) { List<String> instances = new ArrayList<String>(); instances.add(existingInstance.getInstanceId()); StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); logProvisionInfo( logger, "Found stopped instance - starting it: " + existingInstance + " result:" + siResult); } else { // Should be pending or running at this point, just let it come up logProvisionInfo( logger, "Found existing pending or running: " + existingInstance.getState().getName() + " instance: " + existingInstance); } if (ec2Node[0] != null) { logProvisionInfo(logger, "Using existing slave: " + ec2Node[0].getInstanceId()); return ec2Node[0]; } // Existing slave not found logProvision(logger, "Creating new slave for existing instance: " + existingInstance); return newOndemandSlave(existingInstance); } catch (FormException e) { throw new AssertionError(e); // we should have discovered all // configuration issues upfront } catch (InterruptedException e) { throw new RuntimeException(e); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book_select_cancel); Spinner bookSpinner = (Spinner) findViewById(R.id.bookSpinner); View select = findViewById(R.id.confirm); select.setOnClickListener(this); received = getIntent().getExtras(); myCustomer = received.getParcelable("customer"); ArrayList<Book> booksForSpinner = new ArrayList<>(); for (Reservation temp : otterLibrary.reservations) { if (myCustomer.equals(temp.getReservedBy())) { booksForSpinner.add(temp.getReservedBook()); } } List<String> titleList = new ArrayList<String>(); for (int i = 0; i < booksForSpinner.size(); i++) { titleList.add(booksForSpinner.get(i).getTitle()); } ArrayList<String> infoList = new ArrayList<String>(); for (Book temp : booksForSpinner) { infoList.add("Author: " + temp.getAuthor()); infoList.add("ISBN: " + temp.getIsbn()); infoList.add("Hourly Fee: " + temp.getFormattedFee()); } ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, titleList); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); bookSpinner.setAdapter(dataAdapter); bookSpinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView author = (TextView) findViewById(R.id.textView5); TextView isbn = (TextView) findViewById(R.id.textView7); TextView fee = (TextView) findViewById(R.id.textView8); String title = parent.getItemAtPosition(position).toString(); System.out.println(title); for (Book temp : otterLibrary.books) { if (temp.getTitle().equals(title)) { author.setText("Author: " + temp.getAuthor()); isbn.setText("ISBN: " + temp.getIsbn()); fee.setText("Hourly Fee: " + temp.getFormattedFee()); myBook = temp; } } } @Override public void onNothingSelected(AdapterView<?> parent) {} }); }
/** * Insert reservation into database. * * @param res Reservation */ public void createReservation(Reservation res) { if (doLog) Log.d(TAG, "DatabaseController - creating reservation"); Log.d( TAG, res.getReservationId() + " - " + res.getUser() + " - " + res.getStart() + " - " + res.getEnd() + " - " + res.getUserId()); ContentValues values = new ContentValues(); values.put(MySQLiteOpenHelper.COLUMN_RESERVATION_ID, res.getReservationId()); values.put(MySQLiteOpenHelper.COLUMN_USER, res.getUser()); values.put(MySQLiteOpenHelper.COLUMN_USER_PASSWORD, res.getPassword()); values.put(MySQLiteOpenHelper.COLUMN_RESERVATION_START, res.getStart()); values.put(MySQLiteOpenHelper.COLUMN_RESERVATION_END, res.getEnd()); values.put(MySQLiteOpenHelper.COLUMN_USER_ID, res.getUserId()); database.insert(MySQLiteOpenHelper.TABLE_RESERVATION, null, values); if (doLog) Log.d(TAG, "reservation created"); }