sft.LoginAndBookSFT.java Source code

Java tutorial

Introduction

Here is the source code for sft.LoginAndBookSFT.java

Source

/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package sft;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import sft.example.Example;
import sft.example.Seat;

import com.google.gson.Gson;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform
 * form-based logon.
 */
public class LoginAndBookSFT {

    private static String username;

    private static String password;

    private static ArrayList<String> bookings;

    public void startBooking() throws URISyntaxException, MalformedURLException, ProtocolException, IOException {
        final BasicCookieStore cookieStore = new BasicCookieStore();
        final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        try {
            // get cookie
            final HttpGet httpget = new HttpGet("https://sft.ticketack.com");
            final CloseableHttpResponse response1 = httpclient.execute(httpget);
            try {
                final HttpEntity entity = response1.getEntity();

                System.out.println("Login form get: " + response1.getStatusLine());
                EntityUtils.consume(entity);

                System.out.println("Initial set of cookies:");
                final List<Cookie> _cookies = cookieStore.getCookies();
                if (_cookies.isEmpty()) {
                    System.out.println("None");
                } else {
                    for (int i = 0; i < _cookies.size(); i++) {
                        System.out.println("- " + _cookies.get(i).toString());
                    }
                }
            } finally {
                response1.close();
            }

            // login
            final HttpUriRequest login = RequestBuilder.post()
                    .setUri(new URI("https://sft.ticketack.com/ticket/view/"))
                    .addParameter("ticket_number", username).addParameter("ticket_key", password).build();
            final CloseableHttpResponse response2 = httpclient.execute(login);
            try {
                final HttpEntity entity = response2.getEntity();

                System.out.println("Login form get: " + response2.getStatusLine());
                EntityUtils.consume(entity);

                System.out.println("Post logon cookies:");
                final List<Cookie> cookies = cookieStore.getCookies();
                if (cookies.isEmpty()) {
                    System.out.println("None");
                } else {
                    for (int i = 0; i < cookies.size(); i++) {
                        // System.out.println("- " + cookies.get(i).toString());
                    }
                }
            } finally {
                response2.close();
            }
        } finally {
            httpclient.close();
        }

        final Cookie _cookie = cookieStore.getCookies().get(0);
        final String mightyCooke = "PHPSESSID=" + _cookie.getValue();

        for (final String _booking : bookings) {

            // get free seatings
            // json https://sft.ticketack.com/screening/infos_json/02c101f9-c62a-445e-ad72-19fb32db34c0
            final String _json = doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/infos_json/");

            final Gson gson = new Gson();
            final Example _allInfos = gson.fromJson(_json, Example.class);

            if (_allInfos.getCinemaHall().getMap() != null) {

                final String _mySeat = getMeAFreeSeat(_json);

                // book on seating
                // 02c101f9-c62a-445e-ad72-19fb32db34c0?format=json&overbook=false&seat=Parkett%20Rechts:1:16
                try {
                    if (_mySeat != null)
                        doGet(mightyCooke,
                                _booking + "?format=json&overbook=true&seat=" + URLEncoder.encode(_mySeat, "UTF-8"),
                                "https://sft.ticketack.com/screening/book_on_ticket/");
                } catch (final MalformedURLException exception) {
                    System.err.println("Error: " + exception.getMessage());
                } catch (final ProtocolException exception) {
                    System.err.println("Error: " + exception.getMessage());
                } catch (final UnsupportedEncodingException exception) {
                    System.err.println("Error: " + exception.getMessage());
                } catch (final IOException exception) {
                    System.err.println("Error: " + exception.getMessage());
                }
                System.out.println("booking (seat) done for: " + _booking);

            } else {

                // book
                // https://sft.ticketack.com/screening/book_on_ticket/76c039cc-d1d5-40a1-9a5d-2b1cd4c47799
                // Cookie:PHPSESSID=s1a6a8casfhidfq68tqn2cb565
                doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/book_on_ticket/");
                System.out.println("booking done for: " + _booking);
            }

        }

        System.out.println("All done!");

    }

    /**
     * @param _json
     * @return
     */
    private String getMeAFreeSeat(final String _json) {
        String _mySeat = null;

        final Gson gson = new Gson();
        final Example _allSeatings = gson.fromJson(_json, Example.class);

        final List<Seat> _seatList = _allSeatings.getCinemaHall().getMap().getSeats();

        for (final Seat _seat : _seatList) {

            if (_seat.getCategory().equalsIgnoreCase("sector_all") && _seat.getStatus().equalsIgnoreCase("free")) {
                _mySeat = _seat.getLabel();
                break;

            }

        }

        System.err.println(_mySeat);
        return _mySeat;
    }

    /**
     * @param mightyCooke
     * @param _booking
     * @param url
     * @return
     * @throws MalformedURLException
     * @throws IOException
     * @throws ProtocolException
     */
    private String doGet(final String mightyCooke, final String _booking, final String url)
            throws MalformedURLException, IOException, ProtocolException {

        final URL obj = new URL(url + _booking);
        final HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("Cookie", mightyCooke);

        final int responseCode = con.getResponseCode();
        System.out.println("Sending 'GET' request to URL : " + url + _booking);
        System.out.println("Response Code : " + responseCode);

        final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        final StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    /**
     * @return the username
     */
    public static String getUsername() {
        return username;
    }

    /**
     * @param username Sets the username.
     */
    public void setUsername(final String username) {
        LoginAndBookSFT.username = username;
    }

    /**
     * @return the password
     */
    public static String getPassword() {
        return password;
    }

    /**
     * @param password Sets the password.
     */
    public void setPassword(final String password) {
        LoginAndBookSFT.password = password;
    }

    /**
     * @return the bookings
     */
    public static ArrayList<String> getBookings() {
        return bookings;
    }

    /**
     * @param bookings Sets the bookings.
     */
    public void setBookings(final ArrayList<String> bookings) {
        LoginAndBookSFT.bookings = bookings;
    }
}