001/*
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019
020package org.apache.hadoop.hbase.rest;
021
022import java.io.IOException;
023import java.net.URI;
024import java.util.Collections;
025import java.util.HashMap;
026import java.util.Map;
027
028import javax.ws.rs.Consumes;
029import javax.ws.rs.POST;
030import javax.ws.rs.PUT;
031import javax.ws.rs.Path;
032import javax.ws.rs.PathParam;
033import javax.ws.rs.core.Context;
034import javax.ws.rs.core.Response;
035import javax.ws.rs.core.UriBuilder;
036import javax.ws.rs.core.UriInfo;
037
038import org.apache.yetus.audience.InterfaceAudience;
039import org.slf4j.Logger;
040import org.slf4j.LoggerFactory;
041import org.apache.hadoop.hbase.TableNotFoundException;
042import org.apache.hadoop.hbase.filter.Filter;
043import org.apache.hadoop.hbase.rest.model.ScannerModel;
044
045@InterfaceAudience.Private
046public class ScannerResource extends ResourceBase {
047
048  private static final Logger LOG = LoggerFactory.getLogger(ScannerResource.class);
049
050  static final Map<String,ScannerInstanceResource> scanners =
051   Collections.synchronizedMap(new HashMap<String,ScannerInstanceResource>());
052
053  TableResource tableResource;
054
055  /**
056   * Constructor
057   * @param tableResource
058   * @throws IOException
059   */
060  public ScannerResource(TableResource tableResource)throws IOException {
061    super();
062    this.tableResource = tableResource;
063  }
064
065  static boolean delete(final String id) {
066    ScannerInstanceResource instance = scanners.remove(id);
067    if (instance != null) {
068      instance.generator.close();
069      return true;
070    } else {
071      return false;
072    }
073  }
074
075  Response update(final ScannerModel model, final boolean replace,
076      final UriInfo uriInfo) {
077    servlet.getMetrics().incrementRequests(1);
078    if (servlet.isReadOnly()) {
079      return Response.status(Response.Status.FORBIDDEN)
080        .type(MIMETYPE_TEXT).entity("Forbidden" + CRLF)
081        .build();
082    }
083    byte[] endRow = model.hasEndRow() ? model.getEndRow() : null;
084    RowSpec spec = null;
085    if (model.getLabels() != null) {
086      spec = new RowSpec(model.getStartRow(), endRow, model.getColumns(), model.getStartTime(),
087          model.getEndTime(), model.getMaxVersions(), model.getLabels());
088    } else {
089      spec = new RowSpec(model.getStartRow(), endRow, model.getColumns(), model.getStartTime(),
090          model.getEndTime(), model.getMaxVersions());
091    }
092
093    try {
094      Filter filter = ScannerResultGenerator.buildFilterFromModel(model);
095      String tableName = tableResource.getName();
096      ScannerResultGenerator gen =
097        new ScannerResultGenerator(tableName, spec, filter, model.getCaching(),
098          model.getCacheBlocks());
099      String id = gen.getID();
100      ScannerInstanceResource instance =
101        new ScannerInstanceResource(tableName, id, gen, model.getBatch());
102      scanners.put(id, instance);
103      if (LOG.isTraceEnabled()) {
104        LOG.trace("new scanner: " + id);
105      }
106      UriBuilder builder = uriInfo.getAbsolutePathBuilder();
107      URI uri = builder.path(id).build();
108      servlet.getMetrics().incrementSucessfulPutRequests(1);
109      return Response.created(uri).build();
110    } catch (Exception e) {
111      servlet.getMetrics().incrementFailedPutRequests(1);
112      if (e instanceof TableNotFoundException) {
113        return Response.status(Response.Status.NOT_FOUND)
114          .type(MIMETYPE_TEXT).entity("Not found" + CRLF)
115          .build();
116      } else if (e instanceof RuntimeException) {
117        return Response.status(Response.Status.BAD_REQUEST)
118          .type(MIMETYPE_TEXT).entity("Bad request" + CRLF)
119          .build();
120      }
121      return Response.status(Response.Status.SERVICE_UNAVAILABLE)
122        .type(MIMETYPE_TEXT).entity("Unavailable" + CRLF)
123        .build();
124    }
125  }
126
127  @PUT
128  @Consumes({MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF,
129    MIMETYPE_PROTOBUF_IETF})
130  public Response put(final ScannerModel model,
131      final @Context UriInfo uriInfo) {
132    if (LOG.isTraceEnabled()) {
133      LOG.trace("PUT " + uriInfo.getAbsolutePath());
134    }
135    return update(model, true, uriInfo);
136  }
137
138  @POST
139  @Consumes({MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF,
140    MIMETYPE_PROTOBUF_IETF})
141  public Response post(final ScannerModel model,
142      final @Context UriInfo uriInfo) {
143    if (LOG.isTraceEnabled()) {
144      LOG.trace("POST " + uriInfo.getAbsolutePath());
145    }
146    return update(model, false, uriInfo);
147  }
148
149  @Path("{scanner: .+}")
150  public ScannerInstanceResource getScannerInstanceResource(
151      final @PathParam("scanner") String id) throws IOException {
152    ScannerInstanceResource instance = scanners.get(id);
153    if (instance == null) {
154      servlet.getMetrics().incrementFailedGetRequests(1);
155      return new ScannerInstanceResource();
156    } else {
157      servlet.getMetrics().incrementSucessfulGetRequests(1);
158    }
159    return instance;
160  }
161}