Android Open Source - AndroidPlaces Places Request






From Project

Back to project page AndroidPlaces.

License

The source code is released under:

Apache License

If you think the Android project AndroidPlaces listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 * Copyright (C) 2014 Brian Lee//from  w ww  .  j a  va  2s. co  m
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tigerpenguin.places.request;

import android.content.Context;
import android.os.AsyncTask;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.tigerpenguin.places.R;
import com.tigerpenguin.places.response.PlacesResponse;
import com.tigerpenguin.places.response.PlacesResponseFactory;
import com.tigerpenguin.places.responsehandler.PlacesResponseHandler;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public abstract class PlacesRequest<RequestT extends PlacesRequest, ResponseT extends PlacesResponse> {

    private static final String BASE_URL = "https://maps.googleapis.com/maps/api/place/";
    private static final String PARAM_API_KEY = "key";

    private final String apiKey;
    private final PlacesResponseHandler<ResponseT> placesResponseHandler;
    private final Map<String, String> parameters = new HashMap<String, String>();

    private boolean validated;

    protected abstract String getRequestPath();

    protected abstract PlacesResponseFactory<RequestT, ResponseT> getResponseFactory();

    protected abstract RequestT getThis();

    protected PlacesRequest(Context context, PlacesResponseHandler<ResponseT> placesResponseHandler) {
        if (context == null || placesResponseHandler == null) {
            throw new IllegalArgumentException("context and placesResponseHandler can't be null");
        }

        apiKey = context.getString(R.string.placesApiKey);
        if (apiKey == null || apiKey.trim().length() == 0) {
            throw new IllegalArgumentException("Places Api key must be valid");
        }
        this.placesResponseHandler = placesResponseHandler;
    }

    protected static final boolean isEmpty(String value) {
        return value == null || value.trim().isEmpty();
    }

    public final void execute() throws InvalidRequestException {
        validate();
        if (!validated) {
            throw new IllegalStateException("super.validate() was not called!");
        } else {
            validated = false;
        }

        try {
            URL url = new URL(createUrl());
            new RequestTask(url).execute();
        } catch (MalformedURLException e) {
            throw new InvalidRequestException("Unable to create valid url due to MalformedUrl");
        } catch (UnsupportedEncodingException e) {
            throw new InvalidRequestException("Unable to create valid url due to UnsupportedEncoding");
        }
    }

    protected final void setParameter(String key, String value) {
        if (isEmpty(value)) {
            removeParameter(key);
        } else {
            parameters.put(key, value);
        }
    }

    protected final String getParameter(String key) {
        return parameters.get(key);
    }

    protected final void removeParameter(String key) {
        parameters.remove(key);
    }

    protected final void checkParameterDefined(String parameter, String errorMessage) throws InvalidRequestException {
        String value = getParameter(parameter);
        if (value == null || value.isEmpty()) {
            throw new InvalidRequestException(errorMessage);
        }
    }

    protected void validate() throws InvalidRequestException {
        validated = true;
    }

    /* Exposed for testing */
    final String createUrl() throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        sb.append(BASE_URL)
                .append(getRequestPath())
                .append(PARAM_API_KEY).append("=").append(apiKey);

        appendParameters(sb, parameters);

        return sb.toString();
    }

    private void appendParameters(StringBuilder sb, Map<String, String> parameterMap)
            throws UnsupportedEncodingException {
        for (Map.Entry<String, String> param : parameterMap.entrySet()) {
            sb.append("&")
                    .append(param.getKey())
                    .append("=")
                    .append(URLEncoder.encode(param.getValue(), "UTF-8"));
        }
    }

    private class RequestTask extends AsyncTask<Void, Void, ResponseT> {

        private final URL url;

        RequestTask(URL url) {
            this.url = url;
        }

        @Override
        protected ResponseT doInBackground(Void... params) {
            ResponseT response = null;

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();

            try {
                Response httpResponse = client.newCall(request).execute();
                String json = httpResponse.body().string();
                response = getResponseFactory().createResponse(getThis(), json);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPostExecute(ResponseT response) {
            placesResponseHandler.handleResponse(response);
        }
    }
}




Java Source Code List

com.tigerpenguin.demo.places.PlaceDetailActivity.java
com.tigerpenguin.demo.places.PlaceResultAdapter.java
com.tigerpenguin.demo.places.PlaceResultsFragment.java
com.tigerpenguin.demo.places.PlaceReviewAdapter.java
com.tigerpenguin.demo.places.PlaceReviewsFragment.java
com.tigerpenguin.demo.places.PlaceThumbnailAdapter.java
com.tigerpenguin.demo.places.PlaceThumbnailsFragment.java
com.tigerpenguin.demo.places.PlacesDemo.java
com.tigerpenguin.places.PlacesTest.java
com.tigerpenguin.places.deserializer.HtmlStringDeserializer.java
com.tigerpenguin.places.deserializer.PlaceTypeDeserializer.java
com.tigerpenguin.places.model.AddressComponent.java
com.tigerpenguin.places.model.AspectRating.java
com.tigerpenguin.places.model.AspectType.java
com.tigerpenguin.places.model.DayOfWeek.java
com.tigerpenguin.places.model.DayTime.java
com.tigerpenguin.places.model.Geometry.java
com.tigerpenguin.places.model.JsonModel.java
com.tigerpenguin.places.model.Language.java
com.tigerpenguin.places.model.OpeningHours.java
com.tigerpenguin.places.model.Period.java
com.tigerpenguin.places.model.Photo.java
com.tigerpenguin.places.model.PlaceDetail.java
com.tigerpenguin.places.model.PlaceLocation.java
com.tigerpenguin.places.model.PlaceType.java
com.tigerpenguin.places.model.Place.java
com.tigerpenguin.places.model.PriceLevel.java
com.tigerpenguin.places.model.RankBy.java
com.tigerpenguin.places.model.Review.java
com.tigerpenguin.places.model.StatusCode.java
com.tigerpenguin.places.request.InvalidRequestException.java
com.tigerpenguin.places.request.NearbySearchRequestTest.java
com.tigerpenguin.places.request.NearbySearchRequest.java
com.tigerpenguin.places.request.PlaceDetailRequestTest.java
com.tigerpenguin.places.request.PlaceDetailRequest.java
com.tigerpenguin.places.request.PlaceSearchRequestTest.java
com.tigerpenguin.places.request.PlaceSearchRequest.java
com.tigerpenguin.places.request.PlacesRequestTest.java
com.tigerpenguin.places.request.PlacesRequest.java
com.tigerpenguin.places.request.RequestTest.java
com.tigerpenguin.places.response.NearbySearchResponseFactory.java
com.tigerpenguin.places.response.NearbySearchResponse.java
com.tigerpenguin.places.response.PlaceDetailResponseFactory.java
com.tigerpenguin.places.response.PlaceDetailResponse.java
com.tigerpenguin.places.response.PlaceSearchResponse.java
com.tigerpenguin.places.response.PlacesResponseFactory.java
com.tigerpenguin.places.response.PlacesResponse.java
com.tigerpenguin.places.responsehandler.NearbySearchHandlerFragment.java
com.tigerpenguin.places.responsehandler.PlaceDetailResponseHandlerFragment.java
com.tigerpenguin.places.responsehandler.PlacesResponseHandler.java
com.tigerpenguin.widget.simpleratingbar.MockAttributes.java
com.tigerpenguin.widget.simpleratingbar.SimpleRatingBarAttributes.java
com.tigerpenguin.widget.simpleratingbar.SimpleRatingBarTest.java
com.tigerpenguin.widget.simpleratingbar.SimpleRatingBar.java