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.hdfs.server.datanode.web.resources;
019
020import java.io.IOException;
021import java.io.OutputStream;
022import java.lang.annotation.Annotation;
023import java.lang.reflect.Type;
024
025import javax.ws.rs.core.MediaType;
026import javax.ws.rs.core.MultivaluedMap;
027import javax.ws.rs.ext.MessageBodyWriter;
028import javax.ws.rs.ext.Provider;
029
030import org.apache.hadoop.hdfs.DFSClient;
031import org.apache.hadoop.hdfs.client.HdfsDataInputStream;
032import org.apache.hadoop.io.IOUtils;
033
034/**
035 * A response entity for a HdfsDataInputStream.
036 */
037public class OpenEntity {
038  private final HdfsDataInputStream in;
039  private final long length;
040  private final DFSClient dfsclient;
041  
042  OpenEntity(final HdfsDataInputStream in, final long length,
043      final DFSClient dfsclient) {
044    this.in = in;
045    this.length = length;
046    this.dfsclient = dfsclient;
047  }
048  
049  /**
050   * A {@link MessageBodyWriter} for {@link OpenEntity}.
051   */
052  @Provider
053  public static class Writer implements MessageBodyWriter<OpenEntity> {
054
055    @Override
056    public boolean isWriteable(Class<?> clazz, Type genericType,
057        Annotation[] annotations, MediaType mediaType) {
058      return clazz == OpenEntity.class
059          && MediaType.APPLICATION_OCTET_STREAM_TYPE.isCompatible(mediaType);
060    }
061
062    @Override
063    public long getSize(OpenEntity e, Class<?> type, Type genericType,
064        Annotation[] annotations, MediaType mediaType) {
065      return e.length;
066    }
067
068    @Override
069    public void writeTo(OpenEntity e, Class<?> type, Type genericType,
070        Annotation[] annotations, MediaType mediaType,
071        MultivaluedMap<String, Object> httpHeaders, OutputStream out
072        ) throws IOException {
073      try {
074        IOUtils.copyBytes(e.in, out, e.length, false);
075      } finally {
076        IOUtils.cleanup(DatanodeWebHdfsMethods.LOG, e.in);
077        IOUtils.cleanup(DatanodeWebHdfsMethods.LOG, e.dfsclient);
078      }
079    }
080  }
081}