Best Webmock_ruby code snippet using HTTP.halt
app.rb
Source:app.rb
...162 is_error: false,163 message: message,164 }.to_json165 end166 def halt_with_error(status = 500, message = 'unknown')167 headers = {168 'Content-Type' => 'application/json',169 }170 response = {171 is_error: true,172 message: message,173 }174 halt status, headers, response.to_json175 end176 end177 post '/initialize' do178 db.query('TRUNCATE seat_reservations')179 db.query('TRUNCATE reservations')180 db.query('TRUNCATE users')181 content_type :json182 {183 available_days: AVAILABLE_DAYS,184 language: 'ruby',185 }.to_json186 end187 get '/api/settings' do188 payment_api = ENV['PAYMENT_API'] || 'http://127.0.0.1:5000'189 content_type :json190 { payment_api: payment_api }.to_json191 end192 get '/api/stations' do193 stations = db.query('SELECT * FROM `station_master` ORDER BY `id`').map do |station|194 station.slice(:id, :name, :is_stop_express, :is_stop_semi_express, :is_stop_local)195 end196 content_type :json197 stations.to_json198 end199 get '/api/train/search' do200 date = Time.iso8601(params[:use_at]).getlocal201 halt_with_error 404, 'äºç´å¯è½æéå¤ã§ã' unless check_available_date(date)202 from_station = db.xquery(203 'SELECT * FROM station_master WHERE name = ?',204 params[:from],205 ).first206 if from_station.nil?207 puts 'fromStation: no rows'208 halt_with_error 400, 'fromStation: no rows'209 end210 to_station = db.xquery(211 'SELECT * FROM station_master WHERE name = ?',212 params[:to],213 ).first214 if to_station.nil?215 puts 'toStation: no rows'216 halt_with_error 400, 'toStation: no rows'217 end218 is_nobori = from_station[:distance] > to_station[:distance]219 usable_train_class_list = get_usable_train_class_list(from_station, to_station)220 train_list = if params[:train_class].nil? || params[:train_class].empty?221 db.xquery(222 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` IN (?) AND `is_nobori` = ?',223 date.strftime('%Y/%m/%d'),224 usable_train_class_list,225 is_nobori,226 )227 else228 db.xquery(229 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` IN (?) AND `is_nobori` = ? AND `train_class` = ?',230 date.strftime('%Y/%m/%d'),231 usable_train_class_list,232 is_nobori,233 params[:train_class],234 )235 end236 stations = db.xquery(237 "SELECT * FROM `station_master` ORDER BY `distance` #{is_nobori ? 'DESC' : 'ASC'}",238 )239 puts "From #{from_station}"240 puts "To #{to_station}"241 train_search_response_list = []242 train_list.each do |train|243 is_seeked_to_first_station = false244 is_contains_origin_station = false245 is_contains_dest_station = false246 i = 0247 stations.each do |station|248 unless is_seeked_to_first_station249 # é§
ãªã¹ããåè»ã®çºé§
ã¾ã§èªã¿é£ã°ãã¦é åºãããã250 # åè»ã®çºé§
以åã¯æ¢ã¾ããªãã®ã§ç¡è¦ãã¦è¯ã251 if station[:name] == train[:start_station]252 is_seeked_to_first_station = true253 else254 next255 end256 end257 if station[:id] == from_station[:id]258 # çºé§
ãçµè·¯ä¸ã«æã¤ç·¨æã®å ´åãã©ã°ãç«ã¦ã259 is_contains_origin_station = true260 end261 if station[:id] == to_station[:id]262 if is_contains_origin_station263 # çºé§
ã¨çé§
ãçµè·¯ä¸ã«æã¤ç·¨æã®å ´å264 is_contains_dest_station = true265 else266 # åºçºé§
ããå
ã«çµç¹ãè¦ã¤ãã£ãã¨ã267 puts 'ãªãããããã'268 end269 break270 end271 if station[:name] == train[:last_station]272 # é§
ãè¦ã¤ãããªãã¾ã¾å½è©²ç·¨æã®çµç¹ã«çãã¦ãã¾ã£ãã¨ã273 break274 end275 i += 1276 end277 if is_contains_origin_station && is_contains_dest_station278 # åè»æ
å ±279 departure = db.xquery(280 'SELECT `departure` FROM `train_timetable_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ? AND `station` = ?',281 date.strftime('%Y/%m/%d'),282 train[:train_class],283 train[:train_name],284 from_station[:name],285 cast: false,286 ).first287 departure_date = Time.parse("#{date.strftime('%Y/%m/%d')} #{departure[:departure]} +09:00 JST")288 next unless date < departure_date289 arrival = db.xquery(290 'SELECT `arrival` FROM `train_timetable_master` WHERE date = ? AND `train_class` = ? AND `train_name` = ? AND `station` = ?',291 date.strftime('%Y/%m/%d'),292 train[:train_class],293 train[:train_name],294 to_station[:name],295 cast: false,296 ).first297 premium_avail_seats = get_available_seats(train, from_station, to_station, 'premium', false)298 premium_smoke_avail_seats = get_available_seats(train, from_station, to_station, 'premium', true)299 reserved_avail_seats = get_available_seats(train, from_station, to_station, 'reserved', false)300 reserved_smoke_avail_seats = get_available_seats(train, from_station, to_station, 'reserved', true)301 premium_avail = 'â'302 if premium_avail_seats.length.zero?303 premium_avail = 'Ã'304 elsif premium_avail_seats.length < 10305 premium_avail = 'â³'306 end307 premium_smoke_avail = 'â'308 if premium_smoke_avail_seats.length.zero?309 premium_smoke_avail = 'Ã'310 elsif premium_smoke_avail_seats.length < 10311 premium_smoke_avail = 'â³'312 end313 reserved_avail = 'â'314 if reserved_avail_seats.length.zero?315 reserved_avail = 'Ã'316 elsif reserved_avail_seats.length < 10317 reserved_avail = 'â³'318 end319 reserved_smoke_avail = 'â'320 if reserved_smoke_avail_seats.length.zero?321 reserved_smoke_avail = 'Ã'322 elsif reserved_smoke_avail_seats.length < 10323 reserved_smoke_avail = 'â³'324 end325 # 空å¸æ
å ±326 seat_availability = {327 premium: premium_avail,328 premium_smoke: premium_smoke_avail,329 reserved: reserved_avail,330 reserved_smoke: reserved_smoke_avail,331 non_reserved: 'â',332 }333 # æéè¨ç®334 premium_fare = fare_calc(date, from_station[:id], to_station[:id], train[:train_class], 'premium')335 premium_fare = premium_fare * params[:adult].to_i + premium_fare / 2 * params[:child].to_i336 reserved_fare = fare_calc(date, from_station[:id], to_station[:id], train[:train_class], 'reserved')337 reserved_fare = reserved_fare * params[:adult].to_i + reserved_fare / 2 * params[:child].to_i338 non_reserved_fare = fare_calc(date, from_station[:id], to_station[:id], train[:train_class], 'non-reserved')339 non_reserved_fare = non_reserved_fare * params[:adult].to_i + non_reserved_fare / 2 * params[:child].to_i340 fare_information = {341 premium: premium_fare,342 premium_smoke: premium_fare,343 reserved: reserved_fare,344 reserved_smoke: reserved_fare,345 non_reserved: non_reserved_fare,346 }347 train_search_response = {348 train_class: train[:train_class],349 train_name: train[:train_name],350 start: train[:start_station],351 last: train[:last_station],352 departure: from_station[:name],353 arrival: to_station[:name],354 departure_time: departure[:departure],355 arrival_time: arrival[:arrival],356 seat_availability: seat_availability,357 seat_fare: fare_information,358 }359 train_search_response_list << train_search_response360 break if train_search_response_list.length >= 10361 end362 end363 content_type :json364 train_search_response_list.to_json365 end366 get '/api/train/seats' do367 date = Time.iso8601(params[:date]).getlocal368 halt_with_error 404, 'äºç´å¯è½æéå¤ã§ã' unless check_available_date(date)369 train = db.xquery(370 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',371 date.strftime('%Y/%m/%d'),372 params[:train_class],373 params[:train_name],374 ).first375 halt_with_error 404, 'åè»ãåå¨ãã¾ãã' if train.nil?376 from_name = params[:from]377 from_station = db.xquery(378 'SELECT * FROM `station_master` WHERE `name` = ?',379 from_name,380 ).first381 if from_station.nil?382 puts 'fromStation: no rows'383 halt_with_error 400, 'fromStation: no rows'384 end385 to_name = params[:to]386 to_station = db.xquery(387 'SELECT * FROM `station_master` WHERE `name` = ?',388 to_name,389 ).first390 if to_station.nil?391 puts 'toStation: no rows'392 halt_with_error 400, 'toStation: no rows'393 end394 usable_train_class_list = get_usable_train_class_list(from_station, to_station)395 unless usable_train_class_list.include?(train[:train_class])396 puts 'invalid train_class'397 halt_with_error 400, 'invalid train_class'398 end399 seat_list = db.xquery(400 'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? ORDER BY `seat_row`, `seat_column`',401 params[:train_class],402 params[:car_number],403 )404 seat_information_list = []405 seat_list.each do |seat|406 s = {407 row: seat[:seat_row],408 column: seat[:seat_column],409 class: seat[:seat_class],410 is_smoking_seat: seat[:is_smoking_seat],411 is_occupied: false412 }413 query = <<__EOF414 SELECT415 `s`.*416 FROM417 `seat_reservations` `s`,418 `reservations` `r`419 WHERE420 `r`.`date` = ? AND421 `r`.`train_class` = ? AND422 `r`.`train_name` = ? AND423 `car_number` = ? AND424 `seat_row` = ? AND425 `seat_column` = ?426__EOF427 seat_reservation_list = db.xquery(428 query,429 date.strftime('%Y/%m/%d'),430 seat[:train_class],431 params[:train_name],432 seat[:car_number],433 seat[:seat_row],434 seat[:seat_column],435 )436 p seat_reservation_list437 seat_reservation_list.each do |seat_reservation|438 reservation = db.xquery(439 'SELECT * FROM `reservations` WHERE `reservation_id` = ?',440 seat_reservation[:reservation_id],441 ).first442 departure_station = db.xquery(443 'SELECT * FROM `station_master` WHERE `name` = ?',444 reservation[:departure],445 ).first446 arrival_station = db.xquery(447 'SELECT * FROM `station_master` WHERE `name` = ?',448 reservation[:arrival],449 ).first450 if train[:is_nobori]451 # ä¸ã452 if to_station[:id] < arrival_station[:id] && from_station[:id] <= arrival_station[:id]453 # pass454 elsif to_station[:id] >= departure_station[:id] && from_station[:id] > departure_station[:id]455 # pass456 else457 s[:is_occupied] = true458 end459 else460 # ä¸ã461 if from_station[:id] < departure_station[:id] && to_station[:id] <= departure_station[:id]462 # pass463 elsif from_station[:id] >= arrival_station[:id] && to_station[:id] > arrival_station[:id]464 # pass465 else466 s[:is_occupied] = true467 end468 end469 end470 puts s[:is_occupied] ? 'true' : 'false'471 seat_information_list << s472 end473 # åå·è»ã®æ
å ±474 simple_car_information_list = []475 i = 1476 loop do477 seat = db.xquery(478 'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? ORDER BY `seat_row`, `seat_column` LIMIT 1',479 params[:train_class],480 i,481 ).first482 break if seat.nil?483 simple_car_information = {484 car_number: i,485 seat_class: seat[:seat_class],486 }487 simple_car_information_list << simple_car_information488 i += 1489 end490 c = {491 date: date.strftime('%Y/%m/%d'),492 train_class: params[:train_class],493 train_name: params[:train_name],494 car_number: params[:car_number].to_i,495 seats: seat_information_list,496 cars: simple_car_information_list,497 }498 content_type :json499 c.to_json500 end501 post '/api/train/reserve' do502 date = Time.iso8601(body_params[:date]).getlocal503 halt_with_error 404, 'äºç´å¯è½æéå¤ã§ã' unless check_available_date(date)504 db.query('BEGIN')505 begin506 tmas = begin507 db.xquery(508 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',509 date.strftime('%Y/%m/%d'),510 body_params[:train_class],511 body_params[:train_name],512 ).first513 rescue Mysql2::Error => e514 db.query('ROLLBACK')515 puts e.message516 halt_with_error 500, 'åè»ãã¼ã¿ã®åå¾ã«å¤±æãã¾ãã'517 end518 if tmas.nil?519 db.query('ROLLBACK')520 halt_with_error 404, 'åè»ãã¼ã¿ãã¿ã¤ããã¾ãã'521 end522 puts tmas523 # åè»èªä½ã®é§
IDãæ±ãã524 departure_station = begin525 db.xquery(526 'SELECT * FROM `station_master` WHERE `name` = ?',527 tmas[:start_station],528 ).first529 rescue Mysql2::Error => e530 db.query('ROLLBACK')531 puts e.message532 halt_with_error 500, 'ãªã¯ã¨ã¹ããããåè»ã®å§çºé§
ãã¼ã¿ã®åå¾ã«å¤±æãã¾ãã'533 end534 if departure_station.nil?535 db.query('ROLLBACK')536 halt_with_error 404, 'ãªã¯ã¨ã¹ããããåè»ã®å§çºé§
ãã¼ã¿ãã¿ã¤ããã¾ãã'537 end538 # Arrive539 arrival_station = begin540 db.xquery(541 'SELECT * FROM `station_master` WHERE `name` = ?',542 tmas[:last_station],543 ).first544 rescue Mysql2::Error => e545 db.query('ROLLBACK')546 puts e.message547 halt_with_error 500, 'ãªã¯ã¨ã¹ããããåè»ã®çµçé§
ãã¼ã¿ã®åå¾ã«å¤±æãã¾ãã'548 end549 if arrival_station.nil?550 db.query('ROLLBACK')551 halt_with_error 404, 'ãªã¯ã¨ã¹ããããåè»ã®çµçé§
ãã¼ã¿ãã¿ã¤ããã¾ãã'552 end553 # From554 from_station = begin555 db.xquery(556 'SELECT * FROM `station_master` WHERE `name` = ?',557 body_params[:departure],558 ).first559 rescue Mysql2::Error => e560 db.query('ROLLBACK')561 puts e.message562 halt_with_error 500, 'ä¹è»é§
ãã¼ã¿ã®åå¾ã«å¤±æãã¾ãã'563 end564 if from_station.nil?565 db.query('ROLLBACK')566 halt_with_error 404, "ä¹è»é§
ãã¼ã¿ãã¿ã¤ããã¾ãã #{body_params[:departure]}"567 end568 # To569 to_station = begin570 db.xquery(571 'SELECT * FROM `station_master` WHERE `name` = ?',572 body_params[:arrival],573 ).first574 rescue Mysql2::Error => e575 db.query('ROLLBACK')576 puts e.message577 halt_with_error 500, 'éè»é§
é§
ãã¼ã¿ã®åå¾ã«å¤±æãã¾ãã'578 end579 if to_station.nil?580 db.query('ROLLBACK')581 halt_with_error 404, "éè»é§
é§
ãã¼ã¿ãã¿ã¤ããã¾ãã #{body_params[:arrival]}"582 end583 case body_params[:train_class]584 when 'æé'585 if !from_station[:is_stop_express] || !to_station[:is_stop_express]586 db.query('ROLLBACK')587 halt_with_error 400, 'æéã®æ¢ã¾ããªãé§
ã§ã'588 end589 when 'ä¸é'590 if !from_station[:is_stop_semi_express] || !to_station[:is_stop_semi_express]591 db.query('ROLLBACK')592 halt_with_error 400, 'ä¸éã®æ¢ã¾ããªãé§
ã§ã'593 end594 when 'é
ããã¤'595 if !from_station[:is_stop_local] || !to_station[:is_stop_local]596 db.query('ROLLBACK')597 halt_with_error 400, 'é
ããã¤ã®æ¢ã¾ããªãé§
ã§ã'598 end599 else600 db.query('ROLLBACK')601 halt_with_error 400, 'ãªã¯ã¨ã¹ããããåè»ã¯ã©ã¹ãä¸æã§ã'602 end603 # éè¡ãã¦ããªãåºéãäºç´ãã¦ããªãããã§ãã¯ãã604 if tmas[:is_nobori]605 if from_station[:id] > departure_station[:id] || to_station[:id] > departure_station[:id]606 db.query('ROLLBACK')607 halt_with_error 400, 'ãªã¯ã¨ã¹ããããåºéã«åè»ãéè¡ãã¦ããªãåºéãå«ã¾ãã¦ãã¾ã'608 end609 if arrival_station[:id] >= from_station[:id] || arrival_station[:id] > to_station[:id]610 db.query('ROLLBACK')611 halt_with_error 400, 'ãªã¯ã¨ã¹ããããåºéã«åè»ãéè¡ãã¦ããªãåºéãå«ã¾ãã¦ãã¾ã'612 end613 else614 if from_station[:id] < departure_station[:id] || to_station[:id] < departure_station[:id]615 db.query('ROLLBACK')616 halt_with_error 400, 'ãªã¯ã¨ã¹ããããåºéã«åè»ãéè¡ãã¦ããªãåºéãå«ã¾ãã¦ãã¾ã'617 end618 if arrival_station[:id] <= from_station[:id] || arrival_station[:id] < to_station[:id]619 db.query('ROLLBACK')620 halt_with_error 400, 'ãªã¯ã¨ã¹ããããåºéã«åè»ãéè¡ãã¦ããªãåºéãå«ã¾ãã¦ãã¾ã'621 end622 end623 # ããã¾ã座å¸æ¤ç´¢624 # seatsã空ç½ã®æã«çºåãã625 if body_params[:seats].empty?626 if body_params[:seat_class] != 'non-reserved'627 train = begin628 db.xquery(629 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',630 date.strftime('%Y/%m/%d'),631 body_params[:train_class],632 body_params[:train_name],633 ).first634 rescue Mysql2::Error => e635 db.query('ROLLBACK')636 puts e.message637 halt_with_error 400, e.message638 end639 if train.nil?640 db.query('ROLLBACK')641 halt_with_error 404, 'train is not found'642 end643 usable_train_class_list = get_usable_train_class_list(from_station, to_station)644 unless usable_train_class_list.include?(train[:train_class])645 err = 'invalid train_class'646 puts err647 db.query('ROLLBACK')648 halt_with_error 400, err649 end650 body_params[:seats] = [] # 座å¸ãªã¯ã¨ã¹ãæ
å ±ã¯ç©ºã«651 (1..16).each do |carnum|652 seat_list = begin653 db.xquery(654 'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? AND `seat_class` = ? AND `is_smoking_seat` = ? ORDER BY `seat_row`, `seat_column`',655 body_params[:train_class],656 carnum,657 body_params[:seat_class],658 !!body_params[:is_smoking_seat],659 )660 rescue Mysql2::Error => e661 db.query('ROLLBACK')662 puts e.message663 halt_with_error 400, e.message664 end665 seat_information_list = []666 seat_list.each do |seat|667 s = {668 row: seat[:seat_row],669 column: seat[:seat_column],670 class: seat[:seat_class],671 is_smoking_seat: seat[:is_smoking_seat],672 is_occupied: false,673 }674 seat_reservation_list = begin675 db.xquery(676 'SELECT `s`.* FROM `seat_reservations` `s`, `reservations` `r` WHERE `r`.`date` = ? AND `r`.`train_class` = ? AND `r`.`train_name` = ? AND `car_number` = ? AND `seat_row` = ? AND `seat_column` = ? FOR UPDATE',677 date.strftime('%Y/%m/%d'),678 seat[:train_class],679 body_params[:train_name],680 seat[:car_number],681 seat[:seat_row],682 seat[:seat_column],683 )684 rescue Mysql2::Error => e685 db.query('ROLLBACK')686 puts e.message687 halt_with_error 400, e.message688 end689 seat_reservation_list.each do |seat_reservation|690 reservation = begin691 db.xquery(692 'SELECT * FROM `reservations` WHERE `reservation_id` = ? FOR UPDATE',693 seat_reservation[:reservation_id],694 ).first695 rescue Mysql2::Error => e696 db.query('ROLLBACK')697 puts e.message698 halt_with_error 400, e.message699 end700 if reservation.nil?701 db.query('ROLLBACK')702 halt_with_error 404, 'reservation is not found'703 end704 departure_station = begin705 db.xquery(706 'SELECT * FROM `station_master` WHERE `name` = ?',707 reservation[:departure],708 ).first709 rescue Mysql2::Error => e710 db.query('ROLLBACK')711 puts e.message712 halt_with_error 400, e.message713 end714 if departure_station.nil?715 db.query('ROLLBACK')716 halt_with_error 404, 'departure_station is not found'717 end718 arrival_station = begin719 db.xquery(720 'SELECT * FROM `station_master` WHERE `name` = ?',721 reservation[:arrival],722 ).first723 rescue Mysql2::Error => e724 db.query('ROLLBACK')725 puts e.message726 halt_with_error 400, e.message727 end728 if arrival_station.nil?729 db.query('ROLLBACK')730 halt_with_error 404, 'arrival_station is not found'731 end732 if train[:is_nobori]733 # ä¸ã734 if to_station[:id] < arrival_station[:id] && from_station[:id] <= arrival_station[:id]735 # pass736 elsif to_station[:id] >= departure_station[:id] && from_station[:id] > departure_station[:id]737 # pass738 else739 s[:is_occupied] = true740 end741 else742 # ä¸ã743 if from_station[:id] < departure_station[:id] && to_station[:id] <= departure_station[:id]744 # pass745 elsif from_station[:id] >= arrival_station[:id] && to_station[:id] > arrival_station[:id]746 # pass747 else748 s[:is_occupied] = true749 end750 end751 end752 seat_information_list << s753 end754 # ææ§äºç´å¸ã¨ãã®ä»ã®åè£å¸ãé¸åº755 vague_seat = {}756 reserved = false757 vargue = true758 seatnum = body_params[:adult] + body_params[:child] - 1 # å
¨ä½ã®äººæ°ããããã¾ãæå®å¸åãå¼ãã¦ãã759 if body_params[:column].nil? || body_params[:column].empty? # A/B/C/D/Eãæå®ããªããã°ã空ãã¦ããé©å½ãªæå®å¸ãåãããã¾ãã¢ã¼ã760 seatnum = body_params[:adult] + body_params[:child] # ããã¾ãæå®ãã大人ï¼å°äººåã®åº§å¸ãåã761 reserved = true # dummy762 vargue = false # dummy763 end764 candidate_seats = []765 # ã·ã¼ãåã ãåãã¦äºç´ã§ããå¸ãæ¤ç´¢766 i = 0767 seat_information_list.each do |seat|768 if seat[:column] == body_params[:column] && !seat[:is_occupied] && !reserved && vargue # ããã¾ãå¸ãããã¦ã769 vague_seat = seat770 reserved = true771 elsif !seat[:is_occupied] && i < seatnum # åã«å¸ãããã¦ã772 candidate_seats << {773 row: seat[:row],774 column: seat[:column],775 }776 i += 1777 end778 end779 if vargue && reserved780 body_params[:seats] << vague_seat781 end782 if i > 0783 body_params[:seats].concat(candidate_seats)784 end785 if body_params[:seats].length < body_params[:adult] + body_params[:child]786 # ãªã¯ã¨ã¹ãã«å¯¾ãã¦å¸æ°ã足ãã¦ãªã787 # 次ã®å·è»ã«ãã¤ããã788 puts '-----------------'789 puts "ç¾å¨æ¤ç´¢ä¸ã®è»ä¸¡: #{carnum}å·è», ãªã¯ã¨ã¹ã座å¸æ°: #{body_params[:adult] + body_params[:child]}, äºç´ã§ããããªåº§å¸æ°: #{body_params[:seats].length}, ä¸è¶³æ°: #{body_params[:adult] + body_params[:child] - body_params[:seats].length}"790 puts 'ãªã¯ã¨ã¹ãã«å¯¾ãã¦åº§å¸æ°ãä¸è¶³ãã¦ããããã次ã®è»ä¸¡ãæ¤ç´¢ãã¾ãã'791 body_params[:seats] = []792 if carnum == 16793 puts 'ãã®æ°å¹¹ç·ã«ã¾ã¨ãã¦äºç´ã§ããå¸æ°ããªãã£ãããæ¤ç´¢ããããã'794 break795 end796 end797 puts "空ãå®ç¸¾: #{carnum}å·è» ã·ã¼ã: #{body_params[:seats]} å¸æ°: #{body_params[:seats].length}"798 if body_params[:seats].length >= body_params[:adult] + body_params[:child]799 puts 'äºç´æ
å ±ã«è¿½å ããã'800 body_params[:seats] = body_params[:seats][0, body_params[:adult] + body_params[:child]]801 body_params[:car_number] = carnum802 break803 end804 end805 if body_params[:seats].length.zero?806 db.query('ROLLBACK')807 halt_with_error 404, 'ããã¾ã座å¸äºç´ãã§ãã¾ããã§ãããæå®ããå¸ããããã¯1è»ä¸¡å
ã«å¸æã®å¸æ°ããç¨æã§ãã¾ããã§ããã'808 end809 end810 else811 # 座å¸æ
å ±ã®Validate812 body_params[:seats].each do |z|813 puts "XXXX #{z}"814 seat_list = begin815 db.xquery(816 'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? AND `seat_column` = ? AND `seat_row` = ? AND `seat_class` = ?',817 body_params[:train_class],818 body_params[:car_number],819 z[:column],820 z[:row],821 body_params[:seat_class],822 )823 rescue Mysql2::Error => e824 puts e.message825 db.query('ROLLBACK')826 halt_with_error 400, e.message827 end828 if seat_list.to_a.empty?829 db.query('ROLLBACK')830 halt_with_error 404, 'ãªã¯ã¨ã¹ãããã座å¸æ
å ±ã¯åå¨ãã¾ãããå·è»ã»å«ç
å¸ã»åº§å¸ã¯ã©ã¹ãªã©çµã¿åãããè¦ç´ãã¦ãã ãã'831 end832 end833 end834 reservations = begin835 db.xquery(836 'SELECT * FROM `reservations` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ? FOR UPDATE',837 date.strftime('%Y/%m/%d'),838 body_params[:train_class],839 body_params[:train_name],840 )841 rescue Mysql2::Error => e842 puts e.message843 db.query('ROLLBACK')844 halt_with_error 500, 'åè»äºç´æ
å ±ã®åå¾ã«å¤±æãã¾ãã'845 end846 reservations.each do |reservation|847 break if body_params[:seat_class] == 'non-reserved'848 # train_masterããåè»æ
å ±ãåå¾(ä¸ãã»ä¸ããåãã)849 tmas = begin850 db.xquery(851 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',852 date.strftime('%Y/%m/%d'),853 body_params[:train_class],854 body_params[:train_name],855 ).first856 rescue Mysql2::Error => e857 puts e.message858 db.query('ROLLBACK')859 halt_with_error 500, 'åè»ãã¼ã¿ã®åå¾ã«å¤±æãã¾ãã'860 end861 if tmas.nil?862 db.query('ROLLBACK')863 halt_with_error 404, 'åè»ãã¼ã¿ãã¿ã¤ããã¾ãã'864 end865 # äºç´æ
å ±ã®ä¹è»åºéã®é§
IDãæ±ãã866 # From867 reserved_from_station = begin868 db.xquery(869 'SELECT * FROM `station_master` WHERE `name` = ?',870 reservation[:departure],871 ).first872 rescue Mysql2::Error => e873 puts e.message874 db.query('ROLLBACK')875 halt_with_error 500, 'äºç´æ
å ±ã«è¨è¼ãããåè»ã®ä¹è»é§
ãã¼ã¿ã®åå¾ã«å¤±æãã¾ãã'876 end877 if reserved_from_station.nil?878 db.query('ROLLBACK')879 halt_with_error 404, 'äºç´æ
å ±ã«è¨è¼ãããåè»ã®ä¹è»é§
ãã¼ã¿ãã¿ã¤ããã¾ãã'880 end881 # To882 reserved_to_station = begin883 db.xquery(884 'SELECT * FROM `station_master` WHERE `name` = ?',885 reservation[:arrival],886 ).first887 rescue Mysql2::Error => e888 puts e.message889 db.query('ROLLBACK')890 halt_with_error 500, 'äºç´æ
å ±ã«è¨è¼ãããåè»ã®éè»é§
ãã¼ã¿ã®åå¾ã«å¤±æãã¾ãã'891 end892 if reserved_to_station.nil?893 db.query('ROLLBACK')894 halt_with_error 404, 'äºç´æ
å ±ã«è¨è¼ãããåè»ã®éè»é§
ãã¼ã¿ãã¿ã¤ããã¾ãã'895 end896 # äºç´ã®åºééè¤å¤å®897 secdup = false898 if tmas[:is_nobori]899 # ä¸ã900 if to_station[:id] < reserved_to_station[:id] && from_station[:id] <= reserved_to_station[:id]901 # pass902 elsif to_station[:id] >= reserved_from_station[:id] && from_station > reserved_from_station[:id]903 # pass904 else905 secdup = true906 end907 else908 # ä¸ã909 if from_station[:id] < reserved_from_station[:id] && to_station[:id] <= reserved_from_station[:id]910 # pass911 elsif from_station[:id] >= reserved_to_station[:id] && to_station[:id] > reserved_to_station[:id]912 # pass913 else914 secdup = true915 end916 end917 if secdup918 # åºééè¤ã®å ´åã¯æ´ã«åº§å¸ã®éè¤ããã§ãã¯ãã919 seat_reservations = begin920 db.xquery(921 'SELECT * FROM `seat_reservations` WHERE `reservation_id` = ? FOR UPDATE',922 reservation[:reservation_id],923 )924 rescue Mysql2::Error => e925 puts e.message926 db.query('ROLLBACK')927 halt_with_error 500, '座å¸äºç´æ
å ±ã®åå¾ã«å¤±æãã¾ãã'928 end929 seat_reservations.each do |v|930 body_params[:seats].each do |seat|931 if v[:car_number] == body_params[:car_number] && v[:seat_row] == seat[:row] && v[:seat_column] == seat[:column]932 db.query('ROLLBACK')933 puts "Duplicated #{reservation}"934 halt_with_error 400, 'ãªã¯ã¨ã¹ãã«æ¢ã«äºç´ãããå¸ãå«ã¾ãã¦ãã¾ã'935 end936 end937 end938 end939 end940 # 3段éã®äºç´åãã§ãã¯çµãã941 # èªç±å¸ã¯å¼·å¶çã«Seatsæ
å ±ãããã¼ã«ããï¼èªç±å¸ãªã®ã«å¸æå®äºç´ã¯ä¸å¯ï¼942 if body_params[:seat_class] == 'non-reserved'943 body_params[:seats] = []944 body_params[:car_number] = 0945 (body_params[:adult] + body_params[:child]).times do946 body_params[:seats] << {947 row: 0,948 column: '',949 }950 end951 end952 # éè³è¨ç®953 fare = begin954 case body_params[:seat_class]955 when 'premium', 'reserved', 'non-reserved'956 fare_calc(date, from_station[:id], to_station[:id], body_params[:train_class], body_params[:seat_class])957 else958 raise Error, 'ãªã¯ã¨ã¹ãããã座å¸ã¯ã©ã¹ãä¸æã§ã'959 end960 rescue Error, ErrorNoRows => e961 db.query('ROLLBACK')962 puts "fareCalc #{e.message}"963 halt_with_error 400, e.message964 end965 sum_fare = (body_params[:adult] * fare) + (body_params[:child] * fare) / 2966 puts 'SUMFARE'967 # userIDåå¾ããã°ã¤ã³ãã¦ãªãã¨æãããã968 user, status, message = get_user969 if status != 200970 db.query('ROLLBACK')971 puts message972 halt_with_error status, message973 end974 # äºç´IDçºè¡ã¨äºç´æ
å ±ç»é²975 begin976 db.xquery(977 'INSERT INTO `reservations` (`user_id`, `date`, `train_class`, `train_name`, `departure`, `arrival`, `status`, `payment_id`, `adult`, `child`, `amount`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',978 user[:id],979 date.strftime('%Y/%m/%d'),980 body_params[:train_class],981 body_params[:train_name],982 body_params[:departure],983 body_params[:arrival],984 'requesting',985 'a',986 body_params[:adult],987 body_params[:child],988 sum_fare,989 )990 rescue Mysql2::Error => e991 db.query('ROLLBACK')992 puts e.message993 halt_with_error 400, "äºç´ã®ä¿åã«å¤±æãã¾ããã #{e.message}"994 end995 id = db.last_id # äºç´ID996 if id.nil?997 db.query('ROLLBACK')998 halt_with_error 500, 'äºç´IDã®åå¾ã«å¤±æãã¾ãã'999 end1000 # å¸ã®äºç´æ
å ±ç»é²1001 # reservationsã¬ã³ã¼ã1ã«å¯¾ãã¦seat_reservationstã1以ä¸ç»é²ããã1002 body_params[:seats].each do |v|1003 db.xquery(1004 'INSERT INTO `seat_reservations` (`reservation_id`, `car_number`, `seat_row`, `seat_column`) VALUES (?, ?, ?, ?)',1005 id,1006 body_params[:car_number],1007 v[:row],1008 v[:column],1009 )1010 rescue Mysql2::Error => e1011 db.query('ROLLBACK')1012 puts e.message1013 halt_with_error 500, '座å¸äºç´ã®ç»é²ã«å¤±æãã¾ãã'1014 end1015 rescue => e1016 puts e.message1017 db.query('ROLLBACK')1018 halt_with_error 500, e.message1019 end1020 response = {1021 reservation_id: id,1022 amount: sum_fare,1023 is_ok: true1024 }1025 db.query('COMMIT')1026 content_type :json1027 response.to_json1028 end1029 post '/api/train/reservation/commit' do1030 db.query('BEGIN')1031 begin1032 # äºç´IDã§æ¤ç´¢1033 reservation = begin1034 db.xquery(1035 'SELECT * FROM `reservations` WHERE `reservation_id` = ?',1036 body_params[:reservation_id],1037 ).first1038 rescue Mysql2::Error => e1039 db.query('ROLLBACK')1040 puts e.message1041 halt_with_error 500, 'äºç´æ
å ±ã®åå¾ã«å¤±æãã¾ãã'1042 end1043 if reservation.nil?1044 db.query('ROLLBACK')1045 halt_with_error 404, 'äºç´æ
å ±ãã¿ã¤ããã¾ãã'1046 end1047 # æ¯æãåã®ã¦ã¼ã¶ãã§ãã¯ãæ¬äººä»¥å¤ã®ã¦ã¼ã¶ã®äºç´ãæ¯æã£ãããã£ã³ã»ã«ã§ãã¦ã¯ãããªãã1048 user, status, message = get_user1049 if status != 2001050 db.query('ROLLBACK')1051 puts message1052 halt_with_error status, message1053 end1054 if reservation[:user_id] != user[:id]1055 db.query('ROLLBACK')1056 halt_with_error 403, 'ä»ã®ã¦ã¼ã¶IDã®æ¯æãã¯ã§ãã¾ãã'1057 end1058 # äºç´æ
å ±ã®æ¯æãã¹ãã¼ã¿ã¹ç¢ºèª1059 if reservation[:status] == 'done'1060 db.query('ROLLBACK')1061 halt_with_error 403, 'æ¢ã«æ¯æããå®äºãã¦ããäºç´IDã§ã'1062 end1063 # 決æ¸ãã1064 pay_info = {1065 card_token: body_params[:card_token],1066 reservation_id: body_params[:reservation_id],1067 amount: reservation[:amount],1068 }1069 payment_api = ENV['PAYMENT_API'] || 'http://payment:5000'1070 uri = URI.parse("#{payment_api}/payment")1071 req = Net::HTTP::Post.new(uri)1072 req.body = {1073 payment_information: pay_info1074 }.to_json1075 req['Content-Type'] = 'application/json'1076 http = Net::HTTP.new(uri.host, uri.port)1077 http.use_ssl = uri.scheme == 'https'1078 res = http.start { http.request(req) }1079 # ãªã¯ã¨ã¹ã失æ1080 if res.code != '200'1081 db.query('ROLLBACK')1082 puts res.code1083 halt_with_error 500, '決æ¸ã«å¤±æãã¾ãããã«ã¼ããã¼ã¯ã³ãæ¯æãIDãééã£ã¦ããå¯è½æ§ãããã¾ã'1084 end1085 # ãªã¯ã¨ã¹ãåãåºã1086 output = begin1087 JSON.parse(res.body, symbolize_names: true)1088 rescue JSON::ParserError => e1089 db.query('ROLLBACK')1090 puts e.message1091 halt_with_error 500, 'JSON parseã«å¤±æãã¾ãã'1092 end1093 # äºç´æ
å ±ã®æ´æ°1094 begin1095 db.xquery(1096 'UPDATE `reservations` SET `status` = ?, `payment_id` = ? WHERE `reservation_id` = ?',1097 'done',1098 output[:payment_id],1099 body_params[:reservation_id],1100 )1101 rescue Mysql2::Error => e1102 db.query('ROLLBACK')1103 puts e.message1104 halt_with_error 500, 'äºç´æ
å ±ã®æ´æ°ã«å¤±æãã¾ãã'1105 end1106 rescue => e1107 puts e.message1108 db.query('ROLLBACK')1109 halt_with_error 500, e.message1110 end1111 rr = {1112 is_ok: true1113 }1114 db.query('COMMIT')1115 content_type :json1116 rr.to_json1117 end1118 get '/api/auth' do1119 user, status, message = get_user1120 if status != 2001121 puts message1122 halt_with_error status, message1123 end1124 content_type :json1125 { email: user[:email] }.to_json1126 end1127 post '/api/auth/signup' do1128 salt = SecureRandom.random_bytes(1024)1129 super_secure_password = OpenSSL::PKCS5.pbkdf2_hmac(1130 body_params[:password],1131 salt,1132 100,1133 256,1134 'sha256',1135 )1136 db.xquery(1137 'INSERT INTO `users` (`email`, `salt`, `super_secure_password`) VALUES (?, ?, ?)',1138 body_params[:email],1139 salt,1140 super_secure_password,1141 )1142 message_response('registration complete')1143 rescue Mysql2::Error => e1144 puts e.message1145 halt_with_error 502, 'user registration failed'1146 end1147 post '/api/auth/login' do1148 user = db.xquery(1149 'SELECT * FROM `users` WHERE `email` = ?',1150 body_params[:email],1151 ).first1152 halt_with_error 403, 'authentication failed' if user.nil?1153 challenge_password = OpenSSL::PKCS5.pbkdf2_hmac(1154 body_params[:password],1155 user[:salt],1156 100,1157 256,1158 'sha256',1159 )1160 halt_with_error 403, 'authentication failed' if user[:super_secure_password] != challenge_password1161 session[:user_id] = user[:id]1162 message_response 'autheticated'1163 end1164 post '/api/auth/logout' do1165 session[:user_id] = 01166 message_response 'logged out'1167 end1168 get '/api/user/reservations' do1169 user, status, message = get_user1170 if status != 2001171 halt_with_error status, message1172 end1173 reservation_list = db.xquery(1174 'SELECT * FROM `reservations` WHERE `user_id` = ?',1175 user[:id],1176 )1177 reservation_response_list = reservation_list.to_a.map do |r|1178 make_reservation_response(r)1179 end1180 content_type :json1181 reservation_response_list.to_json1182 end1183 get '/api/user/reservations/:item_id' do1184 user, status, message = get_user1185 if status != 2001186 halt_with_error status, message1187 end1188 item_id = params[:item_id].to_i1189 if item_id <= 01190 halt_with_error 400, 'incorrect item id'1191 end1192 reservation = db.xquery(1193 'SELECT * FROM `reservations` WHERE `reservation_id` = ? AND `user_id` = ?',1194 item_id,1195 user[:id],1196 ).first1197 halt_with_error 404, 'Reservation not found' if reservation.nil?1198 reservation_response = make_reservation_response(reservation)1199 content_type :json1200 reservation_response.to_json1201 end1202 post '/api/user/reservations/:item_id/cancel' do1203 user, code, message = get_user1204 if code != 2001205 halt_with_error code, message1206 end1207 item_id = params[:item_id].to_i1208 if item_id <= 01209 halt_with_error 400, 'incorrect item id'1210 end1211 db.query('BEGIN')1212 reservation = begin1213 db.xquery(1214 'SELECT * FROM `reservations` WHERE `reservation_id` = ? AND `user_id` = ?',1215 item_id,1216 user[:id],1217 ).first1218 rescue Mysql2::Error => e1219 db.query('ROLLBACK')1220 puts e.message1221 halt_with_error 500, 'äºç´æ
å ±ã®æ¤ç´¢ã«å¤±æãã¾ãã'1222 end1223 if reservation.nil?1224 db.query('ROLLBACK')1225 halt_with_error 404, 'reservations naiyo'1226 end1227 case reservation[:status]1228 when 'rejected'1229 db.query('ROLLBACK')1230 halt_with_error 500, 'ä½ããã®çç±ã«ããäºç´ã¯Rejectedç¶æ
ã§ã'1231 when 'done'1232 # æ¯æãããã£ã³ã»ã«ãã1233 payment_api = ENV['PAYMENT_API'] || 'http://payment:5000'1234 uri = URI.parse("#{payment_api}/payment/#{reservation[:payment_id]}")1235 req = Net::HTTP::Delete.new(uri)1236 req.body = {1237 payment_id: reservation[:payment_id]1238 }.to_json1239 req['Content-Type'] = 'application/json'1240 http = Net::HTTP.new(uri.host, uri.port)1241 http.use_ssl = uri.scheme == 'https'1242 res = http.start { http.request(req) }1243 # ãªã¯ã¨ã¹ã失æ1244 if res.code != '200'1245 db.query('ROLLBACK')1246 puts res.code1247 halt_with_error 500, '決æ¸ã«å¤±æãã¾ãããæ¯æãIDãééã£ã¦ããå¯è½æ§ãããã¾ã'1248 end1249 # ãªã¯ã¨ã¹ãåãåºã1250 output = begin1251 JSON.parse(res.body, symbolize_names: true)1252 rescue JSON::ParserError => e1253 db.query('ROLLBACK')1254 puts e.message1255 halt_with_error 500, 'JSON parseã«å¤±æãã¾ãã'1256 end1257 puts output1258 else1259 # pass1260 end1261 begin1262 db.xquery(1263 'DELETE FROM `reservations` WHERE `reservation_id` = ? AND `user_id` = ?',1264 item_id,1265 user[:id],1266 )1267 rescue Mysql2::Error => e1268 db.query('ROLLBACK')1269 puts e.message1270 halt_with_error 500, e.message1271 end1272 begin1273 db.xquery(1274 'DELETE FROM `seat_reservations` WHERE `reservation_id` = ?',1275 item_id,1276 )1277 rescue Mysql2::Error => e1278 db.query('ROLLBACK')1279 puts e.message1280 halt_with_error 500, e.message1281 end1282 db.query('COMMIT')1283 message_response 'cancell complete'1284 end1285 error do |e|1286 content_type :json1287 { is_error: true, message: e.message }.to_json1288 end1289 end1290end...
ipam_api.rb
Source:ipam_api.rb
...44 mac = validate_mac!(params[:mac]) unless mac_param.nil? || mac_param.empty?45 cidr = validate_cidr!(params[:address], params[:prefix])46 group_name = get_request_group(params)47 next_ip = provider.get_next_ip(mac, cidr, group_name)48 halt 404, { error: ERRORS[:no_free_ips] }.to_json if next_ip.nil?49 next_ip.to_json50 rescue Proxy::Validations::Error => e51 logger.warn(e.message)52 halt 400, { error: e.to_s }.to_json53 rescue RuntimeError => e54 logger.warn(e.message)55 halt 500, { error: e.message }.to_json56 rescue Errno::ECONNREFUSED, Errno::ECONNRESET57 logger.warn(ERRORS[:no_connection])58 halt 500, { error: ERRORS[:no_connection] }.to_json59 end60 end61 # Gets the subnet from External IPAM62 #63 # Inputs: 1. address: Network address of the subnet64 # 2. prefix: Network prefix(e.g. 24)65 # 3. group(optional): The name of the External IPAM group66 #67 # Returns:68 # Response if subnet exists:69 # ===========================70 # Http Code: 20071 # JSON Response:72 # {"data": {73 # "id": "33",74 # "subnet": "10.20.30.0",75 # "description": "Subnet description",76 # "mask": "29"}77 # }78 #79 # Response if subnet does not exist:80 # ===========================81 # Http Code: 40482 # JSON Response:83 # {"error": "No subnets found"}84 get '/subnet/:address/:prefix' do85 content_type :json86 begin87 validate_required_params!([:address, :prefix], params)88 cidr = validate_cidr!(params[:address], params[:prefix])89 group_name = get_request_group(params)90 subnet = provider.get_ipam_subnet(cidr, group_name)91 halt 404, { error: ERRORS[:no_subnet] }.to_json if subnet.nil?92 subnet.to_json93 rescue Proxy::Validations::Error => e94 logger.warn(e.message)95 halt 400, { error: e.to_s }.to_json96 rescue RuntimeError => e97 logger.warn(e.message)98 halt 500, { error: e.message }.to_json99 rescue Errno::ECONNREFUSED, Errno::ECONNRESET100 logger.warn(ERRORS[:no_connection])101 halt 500, { error: ERRORS[:no_connection] }.to_json102 end103 end104 # Get a list of groups from External IPAM105 #106 # Returns:107 # Response if success:108 # ===========================109 # Http Code: 200110 # JSON Response:111 # {"data": [112 # {"id": "1", "name": "Group 1", "description": "This is group 1"},113 # {"id": "2", "name": "Group 2", "description": "This is group 2"}114 # ]}115 #116 # Response if no groups exist:117 # ===========================118 # Http Code: 404119 # JSON Response:120 # {"error": "Groups are not supported"}121 #122 # Response if groups are not supported:123 # ===========================124 # Http Code: 500125 # JSON Response:126 # {"error": "Groups are not supported"}127 get '/groups' do128 content_type :json129 begin130 halt 500, { error: ERRORS[:groups_not_supported] }.to_json unless provider.groups_supported?131 groups = provider.get_ipam_groups132 groups.to_json133 rescue Proxy::Validations::Error => e134 logger.warn(e.message)135 halt 400, { error: e.to_s }.to_json136 rescue RuntimeError => e137 logger.warn(e.message)138 halt 500, { error: e.message }.to_json139 rescue Errno::ECONNREFUSED, Errno::ECONNRESET140 logger.warn(ERRORS[:no_connection])141 halt 500, { error: ERRORS[:no_connection] }.to_json142 end143 end144 # Get a group from External IPAM145 #146 # Inputs: 1. group: The name of the External IPAM group147 #148 # Returns:149 # Response if success:150 # ===========================151 # Http Code: 200152 # JSON Response:153 # {"data": {"id": "1", "name": "Group 1", "description": "This is group 1"}}154 #155 # Response if group not found:156 # ===========================157 # Http Code: 404158 # JSON Response:159 # {"error": "Group not Found"}160 #161 # Response if groups are not supported:162 # ===========================163 # Http Code: 500164 # JSON Response:165 # {"error": "Groups are not supported"}166 get '/groups/:group' do167 content_type :json168 begin169 validate_required_params!([:group], params)170 group_name = get_request_group(params)171 group = provider.get_ipam_group(group_name)172 halt 404, { error: ERRORS[:no_group] }.to_json if group.nil?173 group.to_json174 rescue Proxy::Validations::Error => e175 logger.warn(e.message)176 halt 400, { error: e.to_s }.to_json177 rescue RuntimeError => e178 logger.warn(e.message)179 halt 500, { error: e.message }.to_json180 rescue Errno::ECONNREFUSED, Errno::ECONNRESET181 logger.warn(ERRORS[:no_connection])182 halt 500, { error: ERRORS[:no_connection] }.to_json183 end184 end185 # Get a list of subnets for a given External IPAM group186 #187 # Input: 1. group: The name of the External IPAM group188 #189 # Returns:190 # Response if success:191 # ===========================192 # Http Code: 200193 # JSON Response:194 # {"data":[195 # {"subnet":"10.20.30.0","mask":"29","description":"This is a subnet"},196 # {"subnet":"40.50.60.0","mask":"29","description":"This is another subnet"}197 # ]}198 #199 # Response if no subnets exist in group:200 # ===========================201 # Http Code: 404202 # JSON Response:203 # {"error": "No subnets found in External IPAM group"}204 #205 # Response if groups are not supported:206 # ===========================207 # Http Code: 500208 # JSON Response:209 # {"error": "Groups are not supported"}210 get '/groups/:group/subnets' do211 content_type :json212 begin213 validate_required_params!([:group], params)214 group_name = get_request_group(params)215 subnets = provider.get_ipam_subnets(group_name)216 halt 404, { error: ERRORS[:no_subnets_in_group] }.to_json if subnets.nil?217 subnets.to_json218 rescue Proxy::Validations::Error => e219 logger.warn(e.message)220 halt 400, { error: e.to_s }.to_json221 rescue RuntimeError => e222 logger.warn(e.message)223 halt 500, { error: e.message }.to_json224 rescue Errno::ECONNREFUSED, Errno::ECONNRESET225 logger.warn(ERRORS[:no_connection])226 halt 500, { error: ERRORS[:no_connection] }.to_json227 end228 end229 # Checks whether an IP address has already been taken in External IPAM230 #231 # Inputs: 1. address: The network address of the IPv4 or IPv6 subnet.232 # 2. prefix: The subnet prefix(e.g. 24)233 # 3. ip: IP address to be queried234 # 4. group(optional): The name of the External IPAM Group, containing the subnet to check235 #236 # Returns:237 # Response if exists:238 # ===========================239 # Http Code: 200240 # Response: true241 #242 # Response if not exists:243 # ===========================244 # Http Code: 200245 # JSON Response: false246 get '/subnet/:address/:prefix/:ip' do247 content_type :json248 begin249 validate_required_params!([:address, :prefix, :ip], params)250 ip = validate_ip!(params[:ip])251 cidr = validate_cidr!(params[:address], params[:prefix])252 group_name = get_request_group(params)253 subnet = provider.get_ipam_subnet(cidr, group_name)254 halt 404, { error: ERRORS[:no_subnet] }.to_json if subnet.nil?255 validate_ip_in_cidr!(ip, cidr)256 ip_exists = provider.ip_exists?(ip, subnet[:id], group_name)257 halt 200, ip_exists.to_json258 rescue Proxy::Validations::Error => e259 logger.warn(e.message)260 halt 400, { error: e.to_s }.to_json261 rescue RuntimeError => e262 logger.warn(e.message)263 halt 500, { error: e.message }.to_json264 rescue Errno::ECONNREFUSED, Errno::ECONNRESET265 logger.warn(ERRORS[:no_connection])266 halt 500, { error: ERRORS[:no_connection] }.to_json267 end268 end269 # Adds an IP address to the specified subnet for the specified IPAM provider270 #271 # Params: 1. address: The network address of the IPv4 or IPv6 subnet272 # 2. prefix: The subnet prefix(e.g. 24)273 # 3. ip: IP address to be added274 # 4. group(optional): The name of the External IPAM Group, containing the subnet to add ip to275 #276 # Returns:277 # Response if added successfully:278 # ===========================279 # Http Code: 201280 # Response: Empty281 #282 # Response if not added successfully:283 # ===========================284 # Http Code: 500285 # JSON Response:286 # {"error": "Unable to add IP to External IPAM"}287 post '/subnet/:address/:prefix/:ip' do288 content_type :json289 begin290 validate_required_params!([:address, :ip, :prefix], params)291 ip = validate_ip!(params[:ip])292 cidr = validate_cidr!(params[:address], params[:prefix])293 group_name = get_request_group(params)294 subnet = provider.get_ipam_subnet(cidr, group_name)295 halt 404, { error: ERRORS[:no_subnet] }.to_json if subnet.nil?296 add_ip_params = { cidr: cidr, subnet_id: subnet[:id], group_name: group_name }297 validate_ip_in_cidr!(ip, cidr)298 ip_added = provider.add_ip_to_subnet(ip, add_ip_params) # Returns nil on success299 halt 500, ip_added.to_json unless ip_added.nil?300 status 201301 rescue Proxy::Validations::Error => e302 logger.warn(e.message)303 halt 400, { error: e.to_s }.to_json304 rescue RuntimeError => e305 logger.warn(e.message)306 halt 500, { error: e.message }.to_json307 rescue Errno::ECONNREFUSED, Errno::ECONNRESET308 logger.warn(ERRORS[:no_connection])309 halt 500, { error: ERRORS[:no_connection] }.to_json310 end311 end312 # Deletes IP address from a given subnet313 #314 # Params: 1. address: The network address of the IPv4 or IPv6 subnet315 # 2. prefix: The subnet prefix(e.g. 24)316 # 3. ip: IP address to be deleted317 # 4. group(optional): The name of the External IPAM Group, containing the subnet to delete ip from318 #319 # Returns:320 # Response if deleted successfully:321 # ===========================322 # Http Code: 200323 # Response: Empty324 #325 # Response if not added successfully:326 # ===========================327 # Http Code: 500328 # JSON Response:329 # {"error": "Unable to delete IP from External IPAM"}330 delete '/subnet/:address/:prefix/:ip' do331 content_type :json332 begin333 validate_required_params!([:address, :ip, :prefix], params)334 ip = validate_ip!(params[:ip])335 cidr = validate_cidr!(params[:address], params[:prefix])336 group_name = get_request_group(params)337 subnet = provider.get_ipam_subnet(cidr, group_name)338 halt 404, { error: ERRORS[:no_subnet] }.to_json if subnet.nil?339 del_ip_params = { cidr: cidr, subnet_id: subnet[:id], group_name: group_name }340 validate_ip_in_cidr!(ip, cidr)341 ip_deleted = provider.delete_ip_from_subnet(ip, del_ip_params) # Returns nil on success342 halt 500, ip_deleted.to_json unless ip_deleted.nil?343 halt 204344 rescue Proxy::Validations::Error => e345 logger.warn(e.message)346 halt 400, { error: e.to_s }.to_json347 rescue RuntimeError => e348 logger.warn(e.message)349 halt 500, { error: e.message }.to_json350 rescue Errno::ECONNREFUSED, Errno::ECONNRESET351 logger.warn(ERRORS[:no_connection])352 halt 500, { error: ERRORS[:no_connection] }.to_json353 end354 end355 end356end...
requester.rb
Source:requester.rb
...11 # Filters out bad requests before performing any routing12 before do13 config = BeEF::Core::Configuration.instance14 # Require a valid API token from a valid IP address15 halt 401 unless params[:token] == config.get('beef.api_token')16 halt 403 unless BeEF::Core::Rest.permitted_source?(request.ip)17 H = BeEF::Core::Models::Http18 HB = BeEF::Core::Models::HookedBrowser19 headers 'Content-Type' => 'application/json; charset=UTF-8',20 'Pragma' => 'no-cache',21 'Cache-Control' => 'no-cache',22 'Expires' => '0'23 end24 # Returns a request by ID25 get '/request/:id' do26 begin27 id = params[:id]28 raise InvalidParamError, 'id' unless BeEF::Filters::nums_only?(id)29 requests = H.find(id)30 halt 404 if requests.nil?31 result = {}32 result[:count] = requests.length33 result[:requests] = []34 requests.each do |request|35 result[:requests] << request2hash(request)36 end37 result.to_json38 rescue InvalidParamError => e39 print_error e.message40 halt 40041 rescue StandardError => e42 print_error "Internal error while retrieving request with id #{id} (#{e.message})"43 halt 50044 end45 end46 # Returns all requestes given a specific hooked browser id47 get '/requests/:id' do48 begin49 id = params[:id]50 raise InvalidParamError, 'id' unless BeEF::Filters.is_valid_hook_session_id?(id)51 requests = H.where(:hooked_browser_id => id)52 halt 404 if requests.nil?53 result = {}54 result[:count] = requests.length55 result[:requests] = []56 requests.each do |request|57 result[:requests] << request2hash(request)58 end59 result.to_json60 rescue InvalidParamError => e61 print_error e.message62 halt 40063 rescue StandardError => e64 print_error "Internal error while retrieving request list for hooked browser with id #{id} (#{e.message})"65 halt 50066 end67 end68 # Return a response by ID69 get '/response/:id' do70 begin71 # super debugging72 error = {}73 error[:code]=074 id = params[:id]75 raise InvalidParamError, 'id' unless BeEF::Filters::nums_only?(id)76 error[:code]=177 responses = H.find(id) || nil78 error[:code]=279 halt 404 if responses.nil?80 error[:code]=381 result = {}82 result[:success] = 'true'83 error[:code]=484 result[:result] = response2hash(responses)85 error[:code]=586 result.to_json87 rescue InvalidParamError => e88 print_error e.message89 halt 40090 rescue StandardError => e91 print_error "Internal error while retrieving response with id #{id} (#{e.message})"92 93 error[:id] = id94 error[:message] = e.message95 error.to_json96 # halt 50097 end98 end99 # Deletes a specific response given its id100 delete '/response/:id' do101 begin102 id = params[:id]103 raise InvalidParamError, 'id' unless BeEF::Filters::nums_only?(id)104 responses = H.find(id) || nil105 halt 404 if responses.nil?106 result = {}107 result['success'] = H.delete(id)108 result.to_json109 rescue InvalidParamError => e110 print_error e.message111 halt 400112 rescue StandardError => e113 print_error "Internal error while removing response with id #{id} (#{e.message})"114 halt 500115 end116 end117 # Send a new HTTP request to the hooked browser118 post '/send/:id' do119 begin120 id = params[:id]121 proto = params[:proto].to_s || 'http'122 raw_request = params['raw_request'].to_s123 zombie = HB.where(:session => id).first || nil124 halt 404 if zombie.nil?125 # @TODO: move most of this to the model126 if raw_request == ''127 raise InvalidParamError, 'raw_request'128 end129 if proto !~ /\Ahttps?\z/130 raise InvalidParamError, 'raw_request: Invalid request URL scheme'131 end132 req_parts = raw_request.split(/ |\n/)133 verb = req_parts[0]134 if not BeEF::Filters.is_valid_verb?(verb)135 raise InvalidParamError, 'raw_request: Only HEAD, GET, POST, OPTIONS, PUT or DELETE requests are supported'136 end137 uri = req_parts[1]138 if not BeEF::Filters.is_valid_url?(uri)139 raise InvalidParamError, 'raw_request: Invalid URI'140 end141 version = req_parts[2]142 if not BeEF::Filters.is_valid_http_version?(version)143 raise InvalidParamError, 'raw_request: Invalid HTTP version'144 end145 host_str = req_parts[3]146 if not BeEF::Filters.is_valid_host_str?(host_str)147 raise InvalidParamError, 'raw_request: Invalid HTTP version'148 end149 # Validate target hsot150 host = req_parts[4]151 host_parts = host.split(/:/)152 host_name = host_parts[0]153 host_port = host_parts[1] || nil154 unless BeEF::Filters.is_valid_hostname?(host_name)155 raise InvalidParamError, 'raw_request: Invalid HTTP HostName'156 end157 host_port = host_parts[1] || nil158 if host_port.nil? || !BeEF::Filters::nums_only?(host_port)159 host_port = proto.eql?('https') ? 443 : 80160 end161 # Save the new HTTP request162 http = H.new(163 :hooked_browser_id => zombie.session,164 :request => raw_request,165 :method => verb,166 :proto => proto,167 :domain => host_name,168 :port => host_port,169 :path => uri,170 :request_date => Time.now,171 :allow_cross_domain => "true",172 )173 print_debug "added new http request for #{zombie.session}"174 print_debug http.to_json175 if verb.eql?('POST') || verb.eql?('PUT')176 req_parts.each_with_index do |value, index|177 if value.match(/^Content-Length/i)178 http.content_length = req_parts[index+1]179 end180 end181 end182 http.save183 result = request2hash(http)184 print_debug "[Requester] Sending HTTP request through zombie [ip: #{zombie.ip}] : #{result}"185 #result.to_json186 rescue InvalidParamError => e187 print_error e.message188 halt 400189 rescue StandardError => e190 print_error "Internal error while removing network host with id #{id} (#{e.message})"191 halt 500192 end193 end194 # Convert a request object to Hash195 def request2hash(http)196 {197 :id => http.id,198 :proto => http.proto,199 :domain => http.domain,200 :port => http.port,201 :path => http.path,202 :has_ran => http.has_ran,203 :method => http.method,204 :request_date => http.request_date,205 :response_date => http.response_date,...
halt
Using AI Code Generation
1 halt 500, {'Content-Type' => 'text/plain'}, 'Something went wrong!'2 throw :halt, [500, {'Content-Type' => 'text/plain'}, 'Something went wrong!']3 throw :halt, [500, {'Content-Type' => 'text/plain'}, ['Something went wrong!']]
halt
Using AI Code Generation
1 halt 500, {'Content-Type' => 'text/plain'}, "Internal Server Error"2 halt [500, {'Content-Type' => 'text/plain'}, "Internal Server Error"]3 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error"]4 halt [500, {'Content-Type' => 'text/plain'}, ["Internal Server Error"]]5 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]6 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]7 halt 500, "Internal Server Error", {'Content-Type' => 'text/plain'}8 halt 500, "Internal Server Error", {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]
halt
Using AI Code Generation
1 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented"2 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"]3 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented", "Not Implemented"]4 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented", "Not Implemented"5 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented", ["Not Implemented"]6 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], "Not Implemented"7 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["Not Implemented"]8 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["Not Implemented"], "Not Implemented"9 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["
halt
Using AI Code Generation
1 halt 500, {'Content-Type' => 'text/plain'}, 'Internal Server Error'2 halt 500, {'Content-Type' => 'text/plain'}, ['Internal Server Error']3 halt 500, {'Content-Type' => 'text/plain'}, 'Internal Server Error'4 halt 500, {'Content-Type' => 'text/plain'}, ['Internal Server Error']5 halt 500, {'Content-Type' => 'text/plain'}, ['Internal Server Error']6 halt 500, {'Content-Type' => 'text/plain'}, 'Internal Server Error'
halt
Using AI Code Generation
1 halt 500, {'Content-Type' => 'text/plain'}, 'Internal Server Error'2 halt 500, {'Content-Type' => 'text/plain'}, ['Internal', ' Server Error']3 halt 500, {'Content-Type' => 'text/plain'}, File.read('500.html')4 halt 500, {'Content-Type' => 'text/plain'}, File.open('500.html')5 halt 500, {'Content-Type' => 'text/plain'}, File.open('500.html', 'r')6 halt 500, {'Content-Type' => 'text/plain'}, File.open('500.html', 'r').read
halt
Using AI Code Generation
1 halt 500, {'Content-Type' => 'text/plain'}, "Internal Server Error"2 halt [500, {'Content-Type' => 'text/plain'}, "Internal Server Error"]3 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error"]4 halt [500, {'Content-Type' => 'text/plain'}, ["Internal Server Error"]]5 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]6 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]7 halt 500, "Internal Server Error", {'Content-Type' => 'text/plain'}8 halt 500, "Internal Server Error", {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]
halt
Using AI Code Generation
1 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented"2 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"]3 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented", "Not Implemented"]4 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented", "Not Implemented"5 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented", ["Not Implemented"]6 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], "Not Implemented"7 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["Not Implemented"]8 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["Not Implemented"], "Not Implemented"9 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!