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