com.threewks.thundr.bigmetrics.admin.BigMetricsQueryController.java Source code

Java tutorial

Introduction

Here is the source code for com.threewks.thundr.bigmetrics.admin.BigMetricsQueryController.java

Source

/*
 * This file is a component of thundr, a software library from 3wks.
 * Read more: http://www.3wks.com.au/thundr
 * Copyright (C) 2014 3wks, <thundr@3wks.com.au>
 *
 * 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.threewks.thundr.bigmetrics.admin;

import static com.atomicleopard.expressive.Expressive.map;

import java.util.HashMap;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;

import com.atomicleopard.expressive.Expressive;
import com.threewks.thundr.bigmetrics.BigMetricsService;
import com.threewks.thundr.bigmetrics.bigquery.BigQueryService;
import com.threewks.thundr.bigmetrics.bigquery.ExportResult;
import com.threewks.thundr.bigmetrics.bigquery.QueryResult;
import com.threewks.thundr.http.StatusCode;
import com.threewks.thundr.logger.Logger;
import com.threewks.thundr.view.json.JsonView;

public class BigMetricsQueryController {

    private final BigQueryService bigQueryService;
    private final BigMetricsService bigMetricsService;
    private String bucketName;

    public BigMetricsQueryController(BigQueryService bigQueryService, BigMetricsService bigMetricsService,
            String bigmetricsAdminExportBucket) {
        this.bigQueryService = bigQueryService;
        this.bigMetricsService = bigMetricsService;
        this.bucketName = bigmetricsAdminExportBucket;
    }

    public JsonView executeQuery(String query) {
        if (StringUtils.isBlank(query)) {
            return new JsonView("No query specified").withStatusCode(StatusCode.BadRequest);
        }
        try {
            Logger.info("Starting query: '%s'", query);
            String reference = bigMetricsService.startQuery(query);
            return new JsonView(Expressive.map("jobId", reference)).withStatusCode(StatusCode.Accepted);
        } catch (RuntimeException e) {
            Logger.warn("Failed to run query %s: %s", query, e.getMessage());
            return new JsonView("Failed " + e.getMessage()).withStatusCode(StatusCode.InternalServerError);
        }
    }

    public JsonView status(String queryId) {
        BigQueryService.JobStatus jobStatus = bigQueryService.getJobStatus(queryId);
        if (jobStatus != BigQueryService.JobStatus.Error) {
            boolean complete = jobStatus == BigQueryService.JobStatus.Success ? true : false;
            return new JsonView(map("complete", complete));
        } else {
            return new JsonView(new HashMap<>()).withStatusCode(StatusCode.BadRequest);
        }
    }

    public JsonView queryResults(String queryId, Long pageSize, String pageToken) {
        try {
            pageToken = StringUtils.trimToNull(pageToken);
            pageSize = clamp(pageSize, 1, 10000, 1000);

            boolean ready = bigMetricsService.isQueryComplete(queryId);
            if (!ready) {
                return new JsonView("Processing").withStatusCode(StatusCode.Accepted);
            }
            QueryResult queryResult = bigMetricsService.queryResult(queryId, pageSize, pageToken);
            return new JsonView(queryResult);
        } catch (RuntimeException e) {
            Logger.warn("Failed to check query results for job id %s: %s", queryId, e.getMessage());
            return new JsonView("Failed " + e.getMessage()).withStatusCode(StatusCode.InternalServerError);
        }
    }

    public JsonView exportQueryResults(String queryId) {
        String objectName = String.format("%s.csv", UUID.randomUUID().toString());
        ExportResult exportResult = bigQueryService.exportQueryResults(queryId, bucketName, objectName);
        return new JsonView(exportResult);
    }

    private Long clamp(Long limit, long min, long max, long def) {
        limit = limit == null ? def : limit;
        return Math.min(max, Math.max(min, limit));
    }

}