text:
package org.apache.hadoop.hdfs.protocolPB;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.fs.BatchedRemoteIterator.BatchedEntries;
import org.apache.hadoop.fs.permission.FsCreateModes;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.AddBlockFlag;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.Options.Rename;
import org.apache.hadoop.fs.QuotaUsage;
import org.apache.hadoop.hdfs.protocol.AddingECPolicyResponse;
import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo;
import org.apache.hadoop.hdfs.protocol.CachePoolEntry;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.EncryptionZone;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LastBlockWithStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.RollingUpgradeInfo;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.GetAclStatusRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.GetAclStatusResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.ModifyAclEntriesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.ModifyAclEntriesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclEntriesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclEntriesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveDefaultAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveDefaultAclResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.SetAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.SetAclResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AbandonBlockRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AbandonBlockResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddBlockRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddBlockResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCacheDirectiveResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCachePoolResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AllowSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AllowSnapshotResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AppendRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AppendResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CheckAccessRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CheckAccessResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CompleteRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CompleteResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ConcatRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ConcatResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSnapshotResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSymlinkRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSymlinkResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DatanodeStorageReportProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteSnapshotResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DisallowSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DisallowSnapshotResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FinalizeUpgradeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FinalizeUpgradeResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FsyncRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FsyncResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetAdditionalDatanodeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetAdditionalDatanodeResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetBlockLocationsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetBlockLocationsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetBlockLocationsResponseProto.Builder;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetContentSummaryRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetContentSummaryResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetCurrentEditLogTxidRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetCurrentEditLogTxidResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeReportResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeStorageReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeStorageReportResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetEditsFromTxidRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetEditsFromTxidResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileInfoRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileInfoResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileLinkInfoRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileLinkInfoResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFsStatsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFsStatusRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetLinkTargetRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetLinkTargetResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetListingRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetListingResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetPreferredBlockSizeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetPreferredBlockSizeResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetQuotaUsageRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetQuotaUsageResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetServerDefaultsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetServerDefaultsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshotDiffReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshotDiffReportResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshottableDirListingRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshottableDirListingResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePoliciesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePoliciesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePolicyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.IsFileClosedRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.IsFileClosedResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCacheDirectivesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCacheDirectivesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCachePoolsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCachePoolsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCorruptFileBlocksRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCorruptFileBlocksResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MetaSaveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MetaSaveResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MkdirsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MkdirsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCacheDirectiveResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCachePoolResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RecoverLeaseRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RecoverLeaseResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RefreshNodesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RefreshNodesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCacheDirectiveResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCachePoolResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UnsetStoragePolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UnsetStoragePolicyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.Rename2RequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.Rename2ResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameSnapshotResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenewLeaseRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenewLeaseResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ReportBadBlocksRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ReportBadBlocksResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RestoreFailedStorageRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RestoreFailedStorageResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollEditsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollEditsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SaveNamespaceRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SaveNamespaceResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetBalancerBandwidthRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetBalancerBandwidthResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetOwnerRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetOwnerResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetPermissionRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetPermissionResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetQuotaRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetQuotaResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetReplicationRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetReplicationResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetSafeModeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetSafeModeResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetStoragePolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetStoragePolicyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetTimesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetTimesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.TruncateRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.TruncateResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdateBlockForPipelineRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdateBlockForPipelineResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdatePipelineRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdatePipelineResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.CreateEncryptionZoneResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.CreateEncryptionZoneRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.GetEZForPathResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.GetEZForPathRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.ListEncryptionZonesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.ListEncryptionZonesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.AddErasureCodingPoliciesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.AddErasureCodingPoliciesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.GetErasureCodingPoliciesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.GetErasureCodingPoliciesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.GetErasureCodingPolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.GetErasureCodingPolicyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.SetErasureCodingPolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.SetErasureCodingPolicyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.UnsetErasureCodingPolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ErasureCodingProtos.UnsetErasureCodingPolicyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.BlockStoragePolicyProto;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeIDProto;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeInfoProto;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.LocatedBlockProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.GetXAttrsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.GetXAttrsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.ListXAttrsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.ListXAttrsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.RemoveXAttrRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.RemoveXAttrResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.SetXAttrRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.SetXAttrResponseProto;
import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.proto.SecurityProtos.CancelDelegationTokenRequestProto;
import org.apache.hadoop.security.proto.SecurityProtos.CancelDelegationTokenResponseProto;
import org.apache.hadoop.security.proto.SecurityProtos.GetDelegationTokenRequestProto;
import org.apache.hadoop.security.proto.SecurityProtos.GetDelegationTokenResponseProto;
import org.apache.hadoop.security.proto.SecurityProtos.RenewDelegationTokenRequestProto;
import org.apache.hadoop.security.proto.SecurityProtos.RenewDelegationTokenResponseProto;
import org.apache.hadoop.security.token.Token;

import com.google.protobuf.RpcController;
import com.google.protobuf.ServiceException;

/**
 * This class is used on the server side. Calls come across the wire for the
 * for protocol {@link ClientNamenodeProtocolPB}.
 * This class translates the PB data types
 * to the native data types used inside the NN as specified in the generic
 * ClientProtocol.
 */
@InterfaceAudience.Private
@InterfaceStability.Stable
public class ClientNamenodeProtocolServerSideTranslatorPB implements
    ClientNamenodeProtocolPB {
  final private ClientProtocol server;
  static final DeleteSnapshotResponseProto VOID_DELETE_SNAPSHOT_RESPONSE =
      DeleteSnapshotResponseProto.newBuilder().build();
  static final RenameSnapshotResponseProto VOID_RENAME_SNAPSHOT_RESPONSE =
      RenameSnapshotResponseProto.newBuilder().build();
  static final AllowSnapshotResponseProto VOID_ALLOW_SNAPSHOT_RESPONSE =
      AllowSnapshotResponseProto.newBuilder().build();
  static final DisallowSnapshotResponseProto VOID_DISALLOW_SNAPSHOT_RESPONSE =
      DisallowSnapshotResponseProto.newBuilder().build();
  static final GetSnapshottableDirListingResponseProto
      NULL_GET_SNAPSHOTTABLE_DIR_LISTING_RESPONSE =
      GetSnapshottableDirListingResponseProto.newBuilder().build();
  static final SetStoragePolicyResponseProto VOID_SET_STORAGE_POLICY_RESPONSE =
      SetStoragePolicyResponseProto.newBuilder().build();
  static final UnsetStoragePolicyResponseProto
      VOID_UNSET_STORAGE_POLICY_RESPONSE =
      UnsetStoragePolicyResponseProto.newBuilder().build();

  private static final CreateResponseProto VOID_CREATE_RESPONSE =
  CreateResponseProto.newBuilder().build();

  private static final SetPermissionResponseProto VOID_SET_PERM_RESPONSE =
  SetPermissionResponseProto.newBuilder().build();

  private static final SetOwnerResponseProto VOID_SET_OWNER_RESPONSE =
  SetOwnerResponseProto.newBuilder().build();

  private static final AbandonBlockResponseProto VOID_ADD_BLOCK_RESPONSE =
  AbandonBlockResponseProto.newBuilder().build();

  private static final ReportBadBlocksResponseProto VOID_REP_BAD_BLOCK_RESPONSE =
  ReportBadBlocksResponseProto.newBuilder().build();

  private static final ConcatResponseProto VOID_CONCAT_RESPONSE =
  ConcatResponseProto.newBuilder().build();

  private static final Rename2ResponseProto VOID_RENAME2_RESPONSE =
  Rename2ResponseProto.newBuilder().build();

  private static final GetListingResponseProto VOID_GETLISTING_RESPONSE =
  GetListingResponseProto.newBuilder().build();

  private static final RenewLeaseResponseProto VOID_RENEWLEASE_RESPONSE =
  RenewLeaseResponseProto.newBuilder().build();

  private static final RefreshNodesResponseProto VOID_REFRESHNODES_RESPONSE =
  RefreshNodesResponseProto.newBuilder().build();

  private static final FinalizeUpgradeResponseProto VOID_FINALIZEUPGRADE_RESPONSE =
  FinalizeUpgradeResponseProto.newBuilder().build();

  private static final MetaSaveResponseProto VOID_METASAVE_RESPONSE =
  MetaSaveResponseProto.newBuilder().build();

  private static final GetFileInfoResponseProto VOID_GETFILEINFO_RESPONSE =
  GetFileInfoResponseProto.newBuilder().build();

  private static final GetFileLinkInfoResponseProto VOID_GETFILELINKINFO_RESPONSE =
  GetFileLinkInfoResponseProto.newBuilder().build();

  private static final SetQuotaResponseProto VOID_SETQUOTA_RESPONSE =
  SetQuotaResponseProto.newBuilder().build();

  private static final FsyncResponseProto VOID_FSYNC_RESPONSE =
  FsyncResponseProto.newBuilder().build();

  private static final SetTimesResponseProto VOID_SETTIMES_RESPONSE =
  SetTimesResponseProto.newBuilder().build();

  private static final CreateSymlinkResponseProto VOID_CREATESYMLINK_RESPONSE =
  CreateSymlinkResponseProto.newBuilder().build();

  private static final UpdatePipelineResponseProto
    VOID_UPDATEPIPELINE_RESPONSE =
  UpdatePipelineResponseProto.newBuilder().build();

  private static final CancelDelegationTokenResponseProto
      VOID_CANCELDELEGATIONTOKEN_RESPONSE =
          CancelDelegationTokenResponseProto.newBuilder().build();

  private static final SetBalancerBandwidthResponseProto
      VOID_SETBALANCERBANDWIDTH_RESPONSE =
        SetBalancerBandwidthResponseProto.newBuilder().build();

  private static final SetAclResponseProto
    VOID_SETACL_RESPONSE = SetAclResponseProto.getDefaultInstance();

  private static final ModifyAclEntriesResponseProto
    VOID_MODIFYACLENTRIES_RESPONSE = ModifyAclEntriesResponseProto
      .getDefaultInstance();

  private static final RemoveAclEntriesResponseProto
    VOID_REMOVEACLENTRIES_RESPONSE = RemoveAclEntriesResponseProto
      .getDefaultInstance();

  private static final RemoveDefaultAclResponseProto
    VOID_REMOVEDEFAULTACL_RESPONSE = RemoveDefaultAclResponseProto
      .getDefaultInstance();

  private static final RemoveAclResponseProto
    VOID_REMOVEACL_RESPONSE = RemoveAclResponseProto.getDefaultInstance();

  private static final SetXAttrResponseProto
    VOID_SETXATTR_RESPONSE = SetXAttrResponseProto.getDefaultInstance();

  private static final RemoveXAttrResponseProto
    VOID_REMOVEXATTR_RESPONSE = RemoveXAttrResponseProto.getDefaultInstance();

  private static final CheckAccessResponseProto
    VOID_CHECKACCESS_RESPONSE = CheckAccessResponseProto.getDefaultInstance();

  /**
   * Constructor
   *
   * @param server - the NN server
   * @throws IOException
   */
  public ClientNamenodeProtocolServerSideTranslatorPB(ClientProtocol server)
      throws IOException {
    this.server = server;
  }

  @Override
  public GetBlockLocationsResponseProto getBlockLocations(
      RpcController controller, GetBlockLocationsRequestProto req)
      throws ServiceException {
    try {
      LocatedBlocks b = server.getBlockLocations(req.getSrc(), req.getOffset(),
          req.getLength());
      Builder builder = GetBlockLocationsResponseProto
          .newBuilder();
      if (b != null) {
        builder.setLocations(PBHelperClient.convert(b)).build();
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetServerDefaultsResponseProto getServerDefaults(
      RpcController controller, GetServerDefaultsRequestProto req)
      throws ServiceException {
    try {
      FsServerDefaults result = server.getServerDefaults();
      return GetServerDefaultsResponseProto.newBuilder()
          .setServerDefaults(PBHelperClient.convert(result))
          .build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public CreateResponseProto create(RpcController controller,
      CreateRequestProto req) throws ServiceException {
    try {
      FsPermission masked = req.hasUnmasked() ?
          FsCreateModes.create(PBHelperClient.convert(req.getMasked()),
              PBHelperClient.convert(req.getUnmasked())) :
          PBHelperClient.convert(req.getMasked());
      HdfsFileStatus result = server.create(req.getSrc(),
          masked, req.getClientName(),
          PBHelperClient.convertCreateFlag(req.getCreateFlag()), req.getCreateParent(),
          (short) req.getReplication(), req.getBlockSize(),
          PBHelperClient.convertCryptoProtocolVersions(
              req.getCryptoProtocolVersionList()),
          req.getEcPolicyName());

      if (result != null) {
        return CreateResponseProto.newBuilder().setFs(PBHelperClient.convert(result))
            .build();
      }
      return VOID_CREATE_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public AppendResponseProto append(RpcController controller,
      AppendRequestProto req) throws ServiceException {
    try {
      EnumSetWritable<CreateFlag> flags = req.hasFlag() ?
          PBHelperClient.convertCreateFlag(req.getFlag()) :
          new EnumSetWritable<>(EnumSet.of(CreateFlag.APPEND));
      LastBlockWithStatus result = server.append(req.getSrc(),
          req.getClientName(), flags);
      AppendResponseProto.Builder builder = AppendResponseProto.newBuilder();
      if (result.getLastBlock() != null) {
        builder.setBlock(PBHelperClient.convertLocatedBlock(
            result.getLastBlock()));
      }
      if (result.getFileStatus() != null) {
        builder.setStat(PBHelperClient.convert(result.getFileStatus()));
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public SetReplicationResponseProto setReplication(RpcController controller,
      SetReplicationRequestProto req) throws ServiceException {
    try {
      boolean result =
          server.setReplication(req.getSrc(), (short) req.getReplication());
      return SetReplicationResponseProto.newBuilder().setResult(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public SetPermissionResponseProto setPermission(RpcController controller,
      SetPermissionRequestProto req) throws ServiceException {
    try {
      server.setPermission(req.getSrc(), PBHelperClient.convert(req.getPermission()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_SET_PERM_RESPONSE;
  }

  @Override
  public SetOwnerResponseProto setOwner(RpcController controller,
      SetOwnerRequestProto req) throws ServiceException {
    try {
      server.setOwner(req.getSrc(),
          req.hasUsername() ? req.getUsername() : null,
          req.hasGroupname() ? req.getGroupname() : null);
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_SET_OWNER_RESPONSE;
  }

  @Override
  public AbandonBlockResponseProto abandonBlock(RpcController controller,
      AbandonBlockRequestProto req) throws ServiceException {
    try {
      server.abandonBlock(PBHelperClient.convert(req.getB()), req.getFileId(),
          req.getSrc(), req.getHolder());
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_ADD_BLOCK_RESPONSE;
  }

  @Override
  public AddBlockResponseProto addBlock(RpcController controller,
      AddBlockRequestProto req) throws ServiceException {

    try {
      List<DatanodeInfoProto> excl = req.getExcludeNodesList();
      List<String> favor = req.getFavoredNodesList();
      EnumSet<AddBlockFlag> flags =
          PBHelperClient.convertAddBlockFlags(req.getFlagsList());
      LocatedBlock result = server.addBlock(
          req.getSrc(),
          req.getClientName(),
          req.hasPrevious() ? PBHelperClient.convert(req.getPrevious()) : null,
          (excl == null || excl.size() == 0) ? null : PBHelperClient.convert(excl
              .toArray(new DatanodeInfoProto[excl.size()])), req.getFileId(),
          (favor == null || favor.size() == 0) ? null : favor
              .toArray(new String[favor.size()]),
          flags);
      return AddBlockResponseProto.newBuilder()
          .setBlock(PBHelperClient.convertLocatedBlock(result)).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetAdditionalDatanodeResponseProto getAdditionalDatanode(
      RpcController controller, GetAdditionalDatanodeRequestProto req)
      throws ServiceException {
    try {
      List<DatanodeInfoProto> existingList = req.getExistingsList();
      List<String> existingStorageIDsList = req.getExistingStorageUuidsList();
      List<DatanodeInfoProto> excludesList = req.getExcludesList();
      LocatedBlock result = server.getAdditionalDatanode(req.getSrc(),
          req.getFileId(), PBHelperClient.convert(req.getBlk()),
          PBHelperClient.convert(existingList.toArray(
              new DatanodeInfoProto[existingList.size()])),
          existingStorageIDsList.toArray(
              new String[existingStorageIDsList.size()]),
          PBHelperClient.convert(excludesList.toArray(
              new DatanodeInfoProto[excludesList.size()])),
          req.getNumAdditionalNodes(), req.getClientName());
      return GetAdditionalDatanodeResponseProto.newBuilder().setBlock(
      PBHelperClient.convertLocatedBlock(result))
          .build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public CompleteResponseProto complete(RpcController controller,
      CompleteRequestProto req) throws ServiceException {
    try {
      boolean result =
          server.complete(req.getSrc(), req.getClientName(),
          req.hasLast() ? PBHelperClient.convert(req.getLast()) : null,
          req.hasFileId() ? req.getFileId() : HdfsConstants.GRANDFATHER_INODE_ID);
      return CompleteResponseProto.newBuilder().setResult(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public ReportBadBlocksResponseProto reportBadBlocks(RpcController controller,
      ReportBadBlocksRequestProto req) throws ServiceException {
    try {
      List<LocatedBlockProto> bl = req.getBlocksList();
      server.reportBadBlocks(PBHelperClient.convertLocatedBlocks(
          bl.toArray(new LocatedBlockProto[bl.size()])));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_REP_BAD_BLOCK_RESPONSE;
  }

  @Override
  public ConcatResponseProto concat(RpcController controller,
      ConcatRequestProto req) throws ServiceException {
    try {
      List<String> srcs = req.getSrcsList();
      server.concat(req.getTrg(), srcs.toArray(new String[srcs.size()]));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_CONCAT_RESPONSE;
  }

  @Override
  public RenameResponseProto rename(RpcController controller,
      RenameRequestProto req) throws ServiceException {
    try {
      boolean result = server.rename(req.getSrc(), req.getDst());
      return RenameResponseProto.newBuilder().setResult(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public Rename2ResponseProto rename2(RpcController controller,
      Rename2RequestProto req) throws ServiceException {
    // resolve rename options
    ArrayList<Rename> optionList = new ArrayList<Rename>();
    if(req.getOverwriteDest()) {
      optionList.add(Rename.OVERWRITE);
    } else if(req.hasMoveToTrash()) {
      optionList.add(Rename.TO_TRASH);
    }

    if(optionList.isEmpty()) {
      optionList.add(Rename.NONE);
    }

    try {
      server.rename2(req.getSrc(), req.getDst(),
          optionList.toArray(new Rename[optionList.size()]));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_RENAME2_RESPONSE;
  }

  @Override
  public TruncateResponseProto truncate(RpcController controller,
      TruncateRequestProto req) throws ServiceException {
    try {
      boolean result = server.truncate(req.getSrc(), req.getNewLength(),
          req.getClientName());
      return TruncateResponseProto.newBuilder().setResult(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public DeleteResponseProto delete(RpcController controller,
    DeleteRequestProto req) throws ServiceException {
    try {
      boolean result =  server.delete(req.getSrc(), req.getRecursive());
      return DeleteResponseProto.newBuilder().setResult(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public MkdirsResponseProto mkdirs(RpcController controller,
      MkdirsRequestProto req) throws ServiceException {
    try {
      FsPermission masked = req.hasUnmasked() ?
          FsCreateModes.create(PBHelperClient.convert(req.getMasked()),
              PBHelperClient.convert(req.getUnmasked())) :
          PBHelperClient.convert(req.getMasked());
      boolean result = server.mkdirs(req.getSrc(), masked,
          req.getCreateParent());
      return MkdirsResponseProto.newBuilder().setResult(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetListingResponseProto getListing(RpcController controller,
      GetListingRequestProto req) throws ServiceException {
    try {
      DirectoryListing result = server.getListing(
          req.getSrc(), req.getStartAfter().toByteArray(),
          req.getNeedLocation());
      if (result !=null) {
        return GetListingResponseProto.newBuilder().setDirList(
          PBHelperClient.convert(result)).build();
      } else {
        return VOID_GETLISTING_RESPONSE;
      }
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RenewLeaseResponseProto renewLease(RpcController controller,
      RenewLeaseRequestProto req) throws ServiceException {
    try {
      server.renewLease(req.getClientName());
      return VOID_RENEWLEASE_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RecoverLeaseResponseProto recoverLease(RpcController controller,
      RecoverLeaseRequestProto req) throws ServiceException {
    try {
      boolean result = server.recoverLease(req.getSrc(), req.getClientName());
      return RecoverLeaseResponseProto.newBuilder().setResult(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RestoreFailedStorageResponseProto restoreFailedStorage(
      RpcController controller, RestoreFailedStorageRequestProto req)
      throws ServiceException {
    try {
      boolean result = server.restoreFailedStorage(req.getArg());
      return RestoreFailedStorageResponseProto.newBuilder().setResult(result)
          .build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetFsStatsResponseProto getFsStats(RpcController controller,
      GetFsStatusRequestProto req) throws ServiceException {
    try {
      return PBHelperClient.convert(server.getStats());
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetDatanodeReportResponseProto getDatanodeReport(
      RpcController controller, GetDatanodeReportRequestProto req)
      throws ServiceException {
    try {
      List<? extends DatanodeInfoProto> result = PBHelperClient.convert(server
          .getDatanodeReport(PBHelperClient.convert(req.getType())));
      return GetDatanodeReportResponseProto.newBuilder()
          .addAllDi(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetDatanodeStorageReportResponseProto getDatanodeStorageReport(
      RpcController controller, GetDatanodeStorageReportRequestProto req)
      throws ServiceException {
    try {
      List<DatanodeStorageReportProto> reports = PBHelperClient.convertDatanodeStorageReports(
          server.getDatanodeStorageReport(PBHelperClient.convert(req.getType())));
      return GetDatanodeStorageReportResponseProto.newBuilder()
          .addAllDatanodeStorageReports(reports)
          .build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetPreferredBlockSizeResponseProto getPreferredBlockSize(
      RpcController controller, GetPreferredBlockSizeRequestProto req)
      throws ServiceException {
    try {
      long result = server.getPreferredBlockSize(req.getFilename());
      return GetPreferredBlockSizeResponseProto.newBuilder().setBsize(result)
          .build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public SetSafeModeResponseProto setSafeMode(RpcController controller,
      SetSafeModeRequestProto req) throws ServiceException {
    try {
      boolean result = server.setSafeMode(PBHelperClient.convert(req.getAction()),
          req.getChecked());
      return SetSafeModeResponseProto.newBuilder().setResult(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public SaveNamespaceResponseProto saveNamespace(RpcController controller,
      SaveNamespaceRequestProto req) throws ServiceException {
    try {
      final long timeWindow = req.hasTimeWindow() ? req.getTimeWindow() : 0;
      final long txGap = req.hasTxGap() ? req.getTxGap() : 0;
      boolean saved = server.saveNamespace(timeWindow, txGap);
      return SaveNamespaceResponseProto.newBuilder().setSaved(saved).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RollEditsResponseProto rollEdits(RpcController controller,
      RollEditsRequestProto request) throws ServiceException {
    try {
      long txid = server.rollEdits();
      return RollEditsResponseProto.newBuilder()
          .setNewSegmentTxId(txid)
          .build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RefreshNodesResponseProto refreshNodes(RpcController controller,
      RefreshNodesRequestProto req) throws ServiceException {
    try {
      server.refreshNodes();
      return VOID_REFRESHNODES_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }

  }

  @Override
  public FinalizeUpgradeResponseProto finalizeUpgrade(RpcController controller,
      FinalizeUpgradeRequestProto req) throws ServiceException {
    try {
      server.finalizeUpgrade();
      return VOID_FINALIZEUPGRADE_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RollingUpgradeResponseProto rollingUpgrade(RpcController controller,
      RollingUpgradeRequestProto req) throws ServiceException {
    try {
      final RollingUpgradeInfo info = server.rollingUpgrade(
          PBHelperClient.convert(req.getAction()));
      final RollingUpgradeResponseProto.Builder b = RollingUpgradeResponseProto.newBuilder();
      if (info != null) {
        b.setRollingUpgradeInfo(PBHelperClient.convert(info));
      }
      return b.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public ListCorruptFileBlocksResponseProto listCorruptFileBlocks(
      RpcController controller, ListCorruptFileBlocksRequestProto req)
      throws ServiceException {
    try {
      CorruptFileBlocks result = server.listCorruptFileBlocks(
          req.getPath(), req.hasCookie() ? req.getCookie(): null);
      return ListCorruptFileBlocksResponseProto.newBuilder()
          .setCorrupt(PBHelperClient.convert(result))
          .build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public MetaSaveResponseProto metaSave(RpcController controller,
      MetaSaveRequestProto req) throws ServiceException {
    try {
      server.metaSave(req.getFilename());
      return VOID_METASAVE_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }

  }

  @Override
  public GetFileInfoResponseProto getFileInfo(RpcController controller,
      GetFileInfoRequestProto req) throws ServiceException {
    try {
      HdfsFileStatus result = server.getFileInfo(req.getSrc());

      if (result != null) {
        return GetFileInfoResponseProto.newBuilder().setFs(
            PBHelperClient.convert(result)).build();
      }
      return VOID_GETFILEINFO_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetFileLinkInfoResponseProto getFileLinkInfo(RpcController controller,
      GetFileLinkInfoRequestProto req) throws ServiceException {
    try {
      HdfsFileStatus result = server.getFileLinkInfo(req.getSrc());
      if (result != null) {
        return GetFileLinkInfoResponseProto.newBuilder().setFs(
            PBHelperClient.convert(result)).build();
      } else {
        return VOID_GETFILELINKINFO_RESPONSE;
      }

    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetContentSummaryResponseProto getContentSummary(
      RpcController controller, GetContentSummaryRequestProto req)
      throws ServiceException {
    try {
      ContentSummary result = server.getContentSummary(req.getPath());
      return GetContentSummaryResponseProto.newBuilder()
          .setSummary(PBHelperClient.convert(result)).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public SetQuotaResponseProto setQuota(RpcController controller,
      SetQuotaRequestProto req) throws ServiceException {
    try {
      server.setQuota(req.getPath(), req.getNamespaceQuota(),
          req.getStoragespaceQuota(),
          req.hasStorageType() ?
          PBHelperClient.convertStorageType(req.getStorageType()): null);
      return VOID_SETQUOTA_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public FsyncResponseProto fsync(RpcController controller,
      FsyncRequestProto req) throws ServiceException {
    try {
      server.fsync(req.getSrc(), req.getFileId(),
          req.getClient(), req.getLastBlockLength());
      return VOID_FSYNC_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public SetTimesResponseProto setTimes(RpcController controller,
      SetTimesRequestProto req) throws ServiceException {
    try {
      server.setTimes(req.getSrc(), req.getMtime(), req.getAtime());
      return VOID_SETTIMES_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public CreateSymlinkResponseProto createSymlink(RpcController controller,
      CreateSymlinkRequestProto req) throws ServiceException {
    try {
      server.createSymlink(req.getTarget(), req.getLink(),
          PBHelperClient.convert(req.getDirPerm()), req.getCreateParent());
      return VOID_CREATESYMLINK_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetLinkTargetResponseProto getLinkTarget(RpcController controller,
      GetLinkTargetRequestProto req) throws ServiceException {
    try {
      String result = server.getLinkTarget(req.getPath());
      GetLinkTargetResponseProto.Builder builder = GetLinkTargetResponseProto
          .newBuilder();
      if (result != null) {
        builder.setTargetPath(result);
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public UpdateBlockForPipelineResponseProto updateBlockForPipeline(
      RpcController controller, UpdateBlockForPipelineRequestProto req)
      throws ServiceException {
    try {
      LocatedBlockProto result = PBHelperClient.convertLocatedBlock(
          server.updateBlockForPipeline(PBHelperClient.convert(req.getBlock()),
              req.getClientName()));
      return UpdateBlockForPipelineResponseProto.newBuilder().setBlock(result)
          .build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public UpdatePipelineResponseProto updatePipeline(RpcController controller,
      UpdatePipelineRequestProto req) throws ServiceException {
    try {
      List<DatanodeIDProto> newNodes = req.getNewNodesList();
      List<String> newStorageIDs = req.getStorageIDsList();
      server.updatePipeline(req.getClientName(),
          PBHelperClient.convert(req.getOldBlock()),
          PBHelperClient.convert(req.getNewBlock()),
          PBHelperClient.convert(newNodes.toArray(new DatanodeIDProto[newNodes.size()])),
          newStorageIDs.toArray(new String[newStorageIDs.size()]));
      return VOID_UPDATEPIPELINE_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetDelegationTokenResponseProto getDelegationToken(
      RpcController controller, GetDelegationTokenRequestProto req)
      throws ServiceException {
    try {
      Token<DelegationTokenIdentifier> token = server
          .getDelegationToken(new Text(req.getRenewer()));
      GetDelegationTokenResponseProto.Builder rspBuilder =
          GetDelegationTokenResponseProto.newBuilder();
      if (token != null) {
        rspBuilder.setToken(PBHelperClient.convert(token));
      }
      return rspBuilder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RenewDelegationTokenResponseProto renewDelegationToken(
      RpcController controller, RenewDelegationTokenRequestProto req)
      throws ServiceException {
    try {
      long result = server.renewDelegationToken(PBHelperClient
          .convertDelegationToken(req.getToken()));
      return RenewDelegationTokenResponseProto.newBuilder()
          .setNewExpiryTime(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public CancelDelegationTokenResponseProto cancelDelegationToken(
      RpcController controller, CancelDelegationTokenRequestProto req)
      throws ServiceException {
    try {
      server.cancelDelegationToken(PBHelperClient.convertDelegationToken(req
          .getToken()));
      return VOID_CANCELDELEGATIONTOKEN_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public SetBalancerBandwidthResponseProto setBalancerBandwidth(
      RpcController controller, SetBalancerBandwidthRequestProto req)
      throws ServiceException {
    try {
      server.setBalancerBandwidth(req.getBandwidth());
      return VOID_SETBALANCERBANDWIDTH_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetDataEncryptionKeyResponseProto getDataEncryptionKey(
      RpcController controller, GetDataEncryptionKeyRequestProto request)
      throws ServiceException {
    try {
      GetDataEncryptionKeyResponseProto.Builder builder =
          GetDataEncryptionKeyResponseProto.newBuilder();
      DataEncryptionKey encryptionKey = server.getDataEncryptionKey();
      if (encryptionKey != null) {
        builder.setDataEncryptionKey(PBHelperClient.convert(encryptionKey));
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public CreateSnapshotResponseProto createSnapshot(RpcController controller,
      CreateSnapshotRequestProto req) throws ServiceException {
    try {
      final CreateSnapshotResponseProto.Builder builder
          = CreateSnapshotResponseProto.newBuilder();
      final String snapshotPath = server.createSnapshot(req.getSnapshotRoot(),
          req.hasSnapshotName()? req.getSnapshotName(): null);
      if (snapshotPath != null) {
        builder.setSnapshotPath(snapshotPath);
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public DeleteSnapshotResponseProto deleteSnapshot(RpcController controller,
      DeleteSnapshotRequestProto req) throws ServiceException {
    try {
      server.deleteSnapshot(req.getSnapshotRoot(), req.getSnapshotName());
      return VOID_DELETE_SNAPSHOT_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public AllowSnapshotResponseProto allowSnapshot(RpcController controller,
      AllowSnapshotRequestProto req) throws ServiceException {
    try {
      server.allowSnapshot(req.getSnapshotRoot());
      return VOID_ALLOW_SNAPSHOT_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public DisallowSnapshotResponseProto disallowSnapshot(RpcController controller,
      DisallowSnapshotRequestProto req) throws ServiceException {
    try {
      server.disallowSnapshot(req.getSnapshotRoot());
      return VOID_DISALLOW_SNAPSHOT_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RenameSnapshotResponseProto renameSnapshot(RpcController controller,
      RenameSnapshotRequestProto request) throws ServiceException {
    try {
      server.renameSnapshot(request.getSnapshotRoot(),
          request.getSnapshotOldName(), request.getSnapshotNewName());
      return VOID_RENAME_SNAPSHOT_RESPONSE;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetSnapshottableDirListingResponseProto getSnapshottableDirListing(
      RpcController controller, GetSnapshottableDirListingRequestProto request)
      throws ServiceException {
    try {
      SnapshottableDirectoryStatus[] result = server
          .getSnapshottableDirListing();
      if (result != null) {
        return GetSnapshottableDirListingResponseProto.newBuilder().
            setSnapshottableDirList(PBHelperClient.convert(result)).build();
      } else {
        return NULL_GET_SNAPSHOTTABLE_DIR_LISTING_RESPONSE;
      }
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetSnapshotDiffReportResponseProto getSnapshotDiffReport(
      RpcController controller, GetSnapshotDiffReportRequestProto request)
      throws ServiceException {
    try {
      SnapshotDiffReport report = server.getSnapshotDiffReport(
          request.getSnapshotRoot(), request.getFromSnapshot(),
          request.getToSnapshot());
      return GetSnapshotDiffReportResponseProto.newBuilder()
          .setDiffReport(PBHelperClient.convert(report)).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public IsFileClosedResponseProto isFileClosed(
      RpcController controller, IsFileClosedRequestProto request)
      throws ServiceException {
    try {
      boolean result = server.isFileClosed(request.getSrc());
      return IsFileClosedResponseProto.newBuilder().setResult(result).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public AddCacheDirectiveResponseProto addCacheDirective(
      RpcController controller, AddCacheDirectiveRequestProto request)
      throws ServiceException {
    try {
      long id = server.addCacheDirective(
          PBHelperClient.convert(request.getInfo()),
          PBHelperClient.convertCacheFlags(request.getCacheFlags()));
      return AddCacheDirectiveResponseProto.newBuilder().
              setId(id).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public ModifyCacheDirectiveResponseProto modifyCacheDirective(
      RpcController controller, ModifyCacheDirectiveRequestProto request)
      throws ServiceException {
    try {
      server.modifyCacheDirective(
          PBHelperClient.convert(request.getInfo()),
          PBHelperClient.convertCacheFlags(request.getCacheFlags()));
      return ModifyCacheDirectiveResponseProto.newBuilder().build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RemoveCacheDirectiveResponseProto
      removeCacheDirective(RpcController controller,
          RemoveCacheDirectiveRequestProto request)
              throws ServiceException {
    try {
      server.removeCacheDirective(request.getId());
      return RemoveCacheDirectiveResponseProto.
          newBuilder().build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public ListCacheDirectivesResponseProto listCacheDirectives(
      RpcController controller, ListCacheDirectivesRequestProto request)
          throws ServiceException {
    try {
      CacheDirectiveInfo filter =
          PBHelperClient.convert(request.getFilter());
      BatchedEntries<CacheDirectiveEntry> entries =
        server.listCacheDirectives(request.getPrevId(), filter);
      ListCacheDirectivesResponseProto.Builder builder =
          ListCacheDirectivesResponseProto.newBuilder();
      builder.setHasMore(entries.hasMore());
      for (int i=0, n=entries.size(); i<n; i++) {
        builder.addElements(PBHelperClient.convert(entries.get(i)));
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public AddCachePoolResponseProto addCachePool(RpcController controller,
      AddCachePoolRequestProto request) throws ServiceException {
    try {
      server.addCachePool(PBHelperClient.convert(request.getInfo()));
      return AddCachePoolResponseProto.newBuilder().build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public ModifyCachePoolResponseProto modifyCachePool(RpcController controller,
      ModifyCachePoolRequestProto request) throws ServiceException {
    try {
      server.modifyCachePool(PBHelperClient.convert(request.getInfo()));
      return ModifyCachePoolResponseProto.newBuilder().build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RemoveCachePoolResponseProto removeCachePool(RpcController controller,
      RemoveCachePoolRequestProto request) throws ServiceException {
    try {
      server.removeCachePool(request.getPoolName());
      return RemoveCachePoolResponseProto.newBuilder().build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public ListCachePoolsResponseProto listCachePools(RpcController controller,
      ListCachePoolsRequestProto request) throws ServiceException {
    try {
      BatchedEntries<CachePoolEntry> entries =
        server.listCachePools(request.getPrevPoolName());
      ListCachePoolsResponseProto.Builder responseBuilder =
        ListCachePoolsResponseProto.newBuilder();
      responseBuilder.setHasMore(entries.hasMore());
      for (int i=0, n=entries.size(); i<n; i++) {
        responseBuilder.addEntries(PBHelperClient.convert(entries.get(i)));
      }
      return responseBuilder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public ModifyAclEntriesResponseProto modifyAclEntries(
      RpcController controller, ModifyAclEntriesRequestProto req)
      throws ServiceException {
    try {
      server.modifyAclEntries(req.getSrc(), PBHelperClient.convertAclEntry(req.getAclSpecList()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_MODIFYACLENTRIES_RESPONSE;
  }

  @Override
  public RemoveAclEntriesResponseProto removeAclEntries(
      RpcController controller, RemoveAclEntriesRequestProto req)
      throws ServiceException {
    try {
      server.removeAclEntries(req.getSrc(),
          PBHelperClient.convertAclEntry(req.getAclSpecList()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_REMOVEACLENTRIES_RESPONSE;
  }

  @Override
  public RemoveDefaultAclResponseProto removeDefaultAcl(
      RpcController controller, RemoveDefaultAclRequestProto req)
      throws ServiceException {
    try {
      server.removeDefaultAcl(req.getSrc());
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_REMOVEDEFAULTACL_RESPONSE;
  }

  @Override
  public RemoveAclResponseProto removeAcl(RpcController controller,
      RemoveAclRequestProto req) throws ServiceException {
    try {
      server.removeAcl(req.getSrc());
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_REMOVEACL_RESPONSE;
  }

  @Override
  public SetAclResponseProto setAcl(RpcController controller,
      SetAclRequestProto req) throws ServiceException {
    try {
      server.setAcl(req.getSrc(), PBHelperClient.convertAclEntry(req.getAclSpecList()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_SETACL_RESPONSE;
  }

  @Override
  public GetAclStatusResponseProto getAclStatus(RpcController controller,
      GetAclStatusRequestProto req) throws ServiceException {
    try {
      return PBHelperClient.convert(server.getAclStatus(req.getSrc()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public CreateEncryptionZoneResponseProto createEncryptionZone(
    RpcController controller, CreateEncryptionZoneRequestProto req)
    throws ServiceException {
    try {
      server.createEncryptionZone(req.getSrc(), req.getKeyName());
      return CreateEncryptionZoneResponseProto.newBuilder().build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetEZForPathResponseProto getEZForPath(
      RpcController controller, GetEZForPathRequestProto req)
      throws ServiceException {
    try {
      GetEZForPathResponseProto.Builder builder =
          GetEZForPathResponseProto.newBuilder();
      final EncryptionZone ret = server.getEZForPath(req.getSrc());
      if (ret != null) {
        builder.setZone(PBHelperClient.convert(ret));
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public ListEncryptionZonesResponseProto listEncryptionZones(
    RpcController controller, ListEncryptionZonesRequestProto req)
    throws ServiceException {
    try {
      BatchedEntries<EncryptionZone> entries = server
          .listEncryptionZones(req.getId());
      ListEncryptionZonesResponseProto.Builder builder =
          ListEncryptionZonesResponseProto.newBuilder();
      builder.setHasMore(entries.hasMore());
      for (int i=0; i<entries.size(); i++) {
        builder.addZones(PBHelperClient.convert(entries.get(i)));
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public SetErasureCodingPolicyResponseProto setErasureCodingPolicy(
      RpcController controller, SetErasureCodingPolicyRequestProto req)
      throws ServiceException {
    try {
      server.setErasureCodingPolicy(req.getSrc(), req.getEcPolicyName());
      return SetErasureCodingPolicyResponseProto.newBuilder().build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public UnsetErasureCodingPolicyResponseProto unsetErasureCodingPolicy(
      RpcController controller, UnsetErasureCodingPolicyRequestProto req)
      throws ServiceException {
    try {
      server.unsetErasureCodingPolicy(req.getSrc());
      return UnsetErasureCodingPolicyResponseProto.newBuilder().build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public SetXAttrResponseProto setXAttr(RpcController controller,
      SetXAttrRequestProto req) throws ServiceException {
    try {
      server.setXAttr(req.getSrc(), PBHelperClient.convertXAttr(req.getXAttr()),
          PBHelperClient.convert(req.getFlag()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_SETXATTR_RESPONSE;
  }

  @Override
  public GetXAttrsResponseProto getXAttrs(RpcController controller,
      GetXAttrsRequestProto req) throws ServiceException {
    try {
      return PBHelperClient.convertXAttrsResponse(server.getXAttrs(req.getSrc(),
          PBHelperClient.convertXAttrs(req.getXAttrsList())));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public ListXAttrsResponseProto listXAttrs(RpcController controller,
    ListXAttrsRequestProto req) throws ServiceException {
    try {
      return PBHelperClient.convertListXAttrsResponse(server.listXAttrs(req.getSrc()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public RemoveXAttrResponseProto removeXAttr(RpcController controller,
      RemoveXAttrRequestProto req) throws ServiceException {
    try {
      server.removeXAttr(req.getSrc(), PBHelperClient.convertXAttr(req.getXAttr()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_REMOVEXATTR_RESPONSE;
  }

  @Override
  public CheckAccessResponseProto checkAccess(RpcController controller,
     CheckAccessRequestProto req) throws ServiceException {
    try {
      server.checkAccess(req.getPath(), PBHelperClient.convert(req.getMode()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_CHECKACCESS_RESPONSE;
  }

  @Override
  public SetStoragePolicyResponseProto setStoragePolicy(
      RpcController controller, SetStoragePolicyRequestProto request)
      throws ServiceException {
    try {
      server.setStoragePolicy(request.getSrc(), request.getPolicyName());
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_SET_STORAGE_POLICY_RESPONSE;
  }

  @Override
  public UnsetStoragePolicyResponseProto unsetStoragePolicy(
      RpcController controller, UnsetStoragePolicyRequestProto request)
      throws ServiceException {
    try {
      server.unsetStoragePolicy(request.getSrc());
    } catch (IOException e) {
      throw new ServiceException(e);
    }
    return VOID_UNSET_STORAGE_POLICY_RESPONSE;
  }

  @Override
  public GetStoragePolicyResponseProto getStoragePolicy(
      RpcController controller, GetStoragePolicyRequestProto request)
      throws ServiceException {
    try {
      BlockStoragePolicyProto policy = PBHelperClient.convert(server
          .getStoragePolicy(request.getPath()));
      return GetStoragePolicyResponseProto.newBuilder()
          .setStoragePolicy(policy).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetStoragePoliciesResponseProto getStoragePolicies(
      RpcController controller, GetStoragePoliciesRequestProto request)
      throws ServiceException {
    try {
      BlockStoragePolicy[] policies = server.getStoragePolicies();
      GetStoragePoliciesResponseProto.Builder builder =
          GetStoragePoliciesResponseProto.newBuilder();
      if (policies == null) {
        return builder.build();
      }
      for (BlockStoragePolicy policy : policies) {
        builder.addPolicies(PBHelperClient.convert(policy));
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  public GetCurrentEditLogTxidResponseProto getCurrentEditLogTxid(RpcController controller,
      GetCurrentEditLogTxidRequestProto req) throws ServiceException {
    try {
      return GetCurrentEditLogTxidResponseProto.newBuilder().setTxid(
          server.getCurrentEditLogTxid()).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetEditsFromTxidResponseProto getEditsFromTxid(RpcController controller,
      GetEditsFromTxidRequestProto req) throws ServiceException {
    try {
      return PBHelperClient.convertEditsResponse(server.getEditsFromTxid(
          req.getTxid()));
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetErasureCodingPoliciesResponseProto getErasureCodingPolicies(RpcController controller,
      GetErasureCodingPoliciesRequestProto request) throws ServiceException {
    try {
      ErasureCodingPolicy[] ecPolicies = server.getErasureCodingPolicies();
      GetErasureCodingPoliciesResponseProto.Builder resBuilder = GetErasureCodingPoliciesResponseProto
          .newBuilder();
      for (ErasureCodingPolicy ecPolicy : ecPolicies) {
        resBuilder.addEcPolicies(PBHelperClient.convertErasureCodingPolicy(ecPolicy));
      }
      return resBuilder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public AddErasureCodingPoliciesResponseProto addErasureCodingPolicies(
      RpcController controller, AddErasureCodingPoliciesRequestProto request)
      throws ServiceException {
    try {
      ErasureCodingPolicy[] policies = request.getEcPoliciesList().stream()
          .map(PBHelperClient::convertErasureCodingPolicy)
          .toArray(ErasureCodingPolicy[]::new);
      AddingECPolicyResponse[] result = server
          .addErasureCodingPolicies(policies);

      List<HdfsProtos.AddingECPolicyResponseProto> responseProtos = Arrays
          .stream(result).map(PBHelperClient::convertAddingECPolicyResponse)
          .collect(Collectors.toList());
      AddErasureCodingPoliciesResponseProto response =
          AddErasureCodingPoliciesResponseProto.newBuilder()
            .addAllResponses(responseProtos).build();
      return response;
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetErasureCodingPolicyResponseProto getErasureCodingPolicy(RpcController controller,
      GetErasureCodingPolicyRequestProto request) throws ServiceException {
    try {
      ErasureCodingPolicy ecPolicy = server.getErasureCodingPolicy(request.getSrc());
      GetErasureCodingPolicyResponseProto.Builder builder = GetErasureCodingPolicyResponseProto.newBuilder();
      if (ecPolicy != null) {
        builder.setEcPolicy(PBHelperClient.convertErasureCodingPolicy(ecPolicy));
      }
      return builder.build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }

  @Override
  public GetQuotaUsageResponseProto getQuotaUsage(
      RpcController controller, GetQuotaUsageRequestProto req)
      throws ServiceException {
    try {
      QuotaUsage result = server.getQuotaUsage(req.getPath());
      return GetQuotaUsageResponseProto.newBuilder()
          .setUsage(PBHelperClient.convert(result)).build();
    } catch (IOException e) {
      throw new ServiceException(e);
    }
  }
}


text:
package org.testifyproject.junit4;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

import java.net.InetAddress;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.testifyproject.Instance;
import org.testifyproject.VirtualResourceInstance;
import org.testifyproject.annotation.Real;
import org.testifyproject.annotation.VirtualResource;

/**
 *
 * @author saden
 */
@VirtualResource("test")
@RunWith(UnitTest.class)
public class VirtualResourceTest {

    @Real
    VirtualResourceInstance<InetAddress> instance;

    @Real
    InetAddress resource;

    @Test
    public void verifyInjections() {
        assertThat(instance).isNotNull();
        assertThat(resource).isNotNull();
        assertThat(instance.getFqn()).isEqualTo("virtual.test.resource");

        Instance<InetAddress> resourceInstance = instance.getResource();
        assertThat(resourceInstance).isNotNull();
        assertThat(resourceInstance.getValue()).isEqualTo(resource);
    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef H_CLIENT
#define H_CLIENT

#include "net.h"

// connect to remote server
int s_connect(char* addr, int port);

/*
 * write a message in a stream socket
 * @return: 0 on success error code instead
 *	- (-1) write error
 *	- (-2) socket shutted down
 *
 * @sockfd: socket file
 * @message: message to send via socket
 * @len: message length
 */
int s_send(int sockfd, char* message, int len);

/*
 * read a message from a stream socket
 * @return: 0 on success error code instead
 *	- (-1) read error
 *	- (-2) socket shutted down
 *
 * @sockfd: socket file
 * @message: pointer in witch the message will be placed
 */
int s_receive(int sockfd, char **message);

#endif


text:
"use strict";
var TemplateVisitor = require("./template_visitor")["default"];
var processOpcodes = require("./utils").processOpcodes;
var forEach = require("../utils").forEach;

function FragmentOpcodeCompiler() {
  this.opcodes = [];
}

FragmentOpcodeCompiler.prototype.compile = function(ast) {
  var templateVisitor = new TemplateVisitor();
  templateVisitor.visit(ast);

  processOpcodes(this, templateVisitor.actions);

  return this.opcodes;
};

FragmentOpcodeCompiler.prototype.opcode = function(type, params) {
  this.opcodes.push([type, params]);
};

FragmentOpcodeCompiler.prototype.text = function(text, childIndex, childCount, isSingleRoot) {
  this.opcode('createText', [text.chars]);
  if (!isSingleRoot) { this.opcode('appendChild'); }
};

FragmentOpcodeCompiler.prototype.openElement = function(element) {
  this.opcode('createElement', [element.tag]);
  forEach(element.attributes, this.attribute, this);
};

FragmentOpcodeCompiler.prototype.closeElement = function(element, childIndex, childCount, isSingleRoot) {
  if (!isSingleRoot) { this.opcode('appendChild'); }
};

FragmentOpcodeCompiler.prototype.startProgram = function(program) {
  this.opcodes.length = 0;
  if (program.statements.length !== 1) {
    this.opcode('createFragment');
  }
};

FragmentOpcodeCompiler.prototype.endProgram = function(program) {
  this.opcode('returnNode');
};

FragmentOpcodeCompiler.prototype.mustache = function () {};

FragmentOpcodeCompiler.prototype.component = function () {};

FragmentOpcodeCompiler.prototype.block = function () {};

FragmentOpcodeCompiler.prototype.attribute = function(attr) {
  if (attr.value.type === 'text') {
    this.opcode('setAttribute', [attr.name, attr.value.chars]);
  }
};

FragmentOpcodeCompiler.prototype.setNamespace = function(namespace) {
  this.opcode('setNamespace', [namespace]);
};

exports.FragmentOpcodeCompiler = FragmentOpcodeCompiler;


text:
package stackresourcecommands

import (
	"github.com/rackspace/rack/commandoptions"
	"github.com/rackspace/rack/handler"
	"github.com/rackspace/rack/internal/github.com/codegangsta/cli"
	"github.com/rackspace/rack/internal/github.com/fatih/structs"
	"github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackresources"
	"github.com/rackspace/rack/util"
)

var getSchema = cli.Command{
	Name:        "get-schema",
	Usage:       util.Usage(commandPrefix, "get-schema", " [--type <resourceType> | --stdin type]"),
	Description: "Shows the interface schema for a specified resource type.",
	Action:      actionGetSchema,
	Flags:       commandoptions.CommandFlags(flagsGetSchema, keysGetSchema),
	BashComplete: func(c *cli.Context) {
		commandoptions.CompleteFlags(commandoptions.CommandFlags(flagsGetSchema, keysGetSchema))
	},
}

func flagsGetSchema() []cli.Flag {
	return []cli.Flag{
		cli.StringFlag{
			Name:  "type",
			Usage: "[optional; required if `stdin` isn't provided] The resource type.",
		},
		cli.StringFlag{
			Name:  "stdin",
			Usage: "[optional; required if `type` isn't provided] The field being piped into STDIN. Valid values are: type.",
		},
	}
}

type paramsGetSchema struct {
	resourceType string
}

var keysGetSchema = []string{"Attributes", "Properties", "ResourceType", "SupportStatus"}

type commandGetSchema handler.Command

func actionGetSchema(c *cli.Context) {
	command := &commandGetSchema{
		Ctx: &handler.Context{
			CLIContext: c,
		},
	}
	handler.Handle(command)
}

func (command *commandGetSchema) Context() *handler.Context {
	return command.Ctx
}

func (command *commandGetSchema) Keys() []string {
	return keysGetSchema
}

func (command *commandGetSchema) ServiceClientType() string {
	return serviceClientType
}
func (command *commandGetSchema) HandlePipe(resource *handler.Resource, item string) error {
	resource.Params.(*paramsGetSchema).resourceType = item
	return nil
}

func (command *commandGetSchema) HandleSingle(resource *handler.Resource) error {
	err := command.Ctx.CheckFlagsSet([]string{"type"})
	if err != nil {
		return err
	}

	resource.Params = &paramsGetSchema{
		resourceType: command.Ctx.CLIContext.String("type"),
	}
	return nil
}

func (command *commandGetSchema) HandleFlags(resource *handler.Resource) error {
	resource.Params = &paramsGetSchema{}
	return nil
}

func (command *commandGetSchema) Execute(resource *handler.Resource) {
	params := resource.Params.(*paramsGetSchema)
	resourceType := params.resourceType
	schema, err := stackresources.Schema(command.Ctx.ServiceClient, resourceType).Extract()
	if err != nil {
		resource.Err = err
		return
	}
	resource.Result = schema
}

func (command *commandGetSchema) StdinField() string {
	return "type"
}

func (command *commandGetSchema) PreCSV(resource *handler.Resource) error {
	resource.Result = structs.Map(resource.Result)
	resource.FlattenMap("Attributes")
	resource.FlattenMap("Properties")
	resource.FlattenMap("SupportStatus")
	return nil
}

func (command *commandGetSchema) PreTable(resource *handler.Resource) error {
	return command.PreCSV(resource)
}


text:
using System;
using System.Collections;
using System.IO;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Channels;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Mono.Remoting.Channels.Unix
{
	internal class UnixBinaryClientFormatterSink : IClientFormatterSink, IMessageSink, IClientChannelSink, IChannelSinkBase
	{
		UnixBinaryCore _binaryCore = UnixBinaryCore.DefaultInstance;
		IClientChannelSink _nextInChain;

		public UnixBinaryClientFormatterSink (IClientChannelSink nextSink)
		{
			_nextInChain = nextSink;
		}

		internal UnixBinaryCore BinaryCore
		{
			get { return _binaryCore; }
			set { _binaryCore = value; }
		}

		public IClientChannelSink NextChannelSink
		{
			get {
				return _nextInChain;
			}
		}

		public IMessageSink NextSink
		{
			get {
				// This is the last sink in the IMessageSink sink chain
				return null;
			}
		}

		public IDictionary Properties
		{
			get {
				return null;
			}
		}

		public void AsyncProcessRequest (IClientChannelSinkStack sinkStack,
						 IMessage msg,
						 ITransportHeaders headers,
						 Stream stream)
	        {
			// never called because the formatter sink is
			// always the first in the chain
			throw new NotSupportedException("UnixBinaryClientFormatterSink must be the first sink in the IClientChannelSink chain");
		}

		public void AsyncProcessResponse (IClientResponseChannelSinkStack sinkStack,
						  object state,
						  ITransportHeaders headers,
						  Stream stream)
		{
			IMessage replyMessage = (IMessage)_binaryCore.Deserializer.DeserializeMethodResponse (stream, null, (IMethodCallMessage)state);
			sinkStack.DispatchReplyMessage (replyMessage);
		}

		public Stream GetRequestStream (IMessage msg,
						ITransportHeaders headers)
		{
			// never called
			throw new NotSupportedException ();
		}

		public void ProcessMessage (IMessage msg,
					    ITransportHeaders requestHeaders,
					    Stream requestStream,
					    out ITransportHeaders responseHeaders,
					    out Stream responseStream)
		{
			// never called because the formatter sink is
			// always the first in the chain
			throw new NotSupportedException ();
		}

		public IMessageCtrl AsyncProcessMessage (IMessage msg,
			IMessageSink replySink)
		{
			ITransportHeaders transportHeaders = new TransportHeaders();
			Stream stream = _nextInChain.GetRequestStream(msg, transportHeaders);
			if (stream == null) stream = new MemoryStream ();

			_binaryCore.Serializer.Serialize (stream, msg, null);
			if (stream is MemoryStream) stream.Position = 0;

			ClientChannelSinkStack stack = new ClientChannelSinkStack(replySink);
			stack.Push (this, msg);

			_nextInChain.AsyncProcessRequest (stack, msg, transportHeaders, stream);

			// FIXME: No idea about how to implement IMessageCtrl
			return null;
		}

		public IMessage SyncProcessMessage (IMessage msg)
		{
			try {

				ITransportHeaders call_headers = new TransportHeaders();
				call_headers["__RequestUri"] = ((IMethodCallMessage)msg).Uri;
				call_headers["Content-Type"] = "application/octet-stream";

				Stream call_stream = _nextInChain.GetRequestStream(msg, call_headers);
				if (call_stream == null) call_stream = new MemoryStream ();

				// Serialize msg to the stream

				_binaryCore.Serializer.Serialize (call_stream, msg, null);
				if (call_stream is MemoryStream) call_stream.Position = 0;

				Stream response_stream;
				ITransportHeaders response_headers;

				_nextInChain.ProcessMessage (msg, call_headers, call_stream, out response_headers,
							    out response_stream);

				// Deserialize response_stream

				return (IMessage) _binaryCore.Deserializer.DeserializeMethodResponse (response_stream, null, (IMethodCallMessage)msg);

			} catch (Exception e) {
				 return new ReturnMessage (e, (IMethodCallMessage)msg);
			}
		}
	}
}


text:
import Ember from 'ember';
import layout from '../templates/components/flexberry-boundingbox';
import FlexberryMapActionsHandlerMixin from '../mixins/flexberry-map-actions-handler';

/**
  Component's CSS-classes names.
  JSON-object containing string constants with CSS-classes names related to component's .hbs markup elements.

  @property {Object} flexberryClassNames
  @property {String} flexberryClassNames.prefix Component's CSS-class names prefix ('flexberry-boundingbox').
  @property {String} flexberryClassNames.wrapper Component's wrapping
 CSS-class name ('flexberry-boundingbox').
  @readonly
  @static

  @for FlexberryBoundingboxComponent
*/
const flexberryClassNamesPrefix = 'flexberry-boundingbox';
const flexberryClassNames = {
  prefix: flexberryClassNamesPrefix,
  wrapper: flexberryClassNamesPrefix
};

/**
  Flexberry bounding box component.

  @class FlexberryBoundingboxComponent
  @extends Ember.Component
  @uses FlexberryMapActionsHandlerMixin
*/
export default Ember.Component.extend(FlexberryMapActionsHandlerMixin, {
  /**
    Leaflet map.

    @property _leafletMap
    @type L.Map
    @default null
    @private
  */
  _leafletMap: null,

  /**
    Reference to areaselect object.

    @property _areaSelect
    @type Object
    @default null
    @private
  */
  _areaSelect: null,

  /**
    Minimal latitude value binded to textbox.

    @property _minLat
    @type number
    @default -90
    @private
  */
  _minLat: -90,

  /**
    Maximal latitude value binded to textbox.

    @property _maxLat
    @type number
    @default 90
    @private
  */
  _maxLat: 90,

  /**
    Minimal longitude value binded to textbox.

    @property _minLng
    @type number
    @default -180
    @private
  */
  _minLng: -180,

  /**
    Maximal longitude value binded to textbox.

    @property _maxLng
    @type number
    @default 180
    @private
  */
  _maxLng: 180,

  /**
    Flag: indicates whether min latitude in textbox is valid or not.

    @property _minLatIsValid
    @type Boolean
    @readOnly
    @private
  */
  _minLatIsValid: Ember.computed('_minLat', function() {
    let minLat = parseFloat(this.get('_minLat'));

    return minLat >= -90 && minLat <= 90;
  }),

  /**
    Flag: indicates whether min longitude in textbox is valid or not.

    @property _minLngIsValid
    @type Boolean
    @readOnly
    @private
  */
  _minLngIsValid: Ember.computed('_minLng', function() {
    let minLng = parseFloat(this.get('_minLng'));

    return minLng >= -180 && minLng <= 180;
  }),

  /**
    Flag: indicates whether max latitude in textbox is valid or not.

    @property _maxLatIsValid
    @type Boolean
    @readOnly
    @private
  */
  _maxLatIsValid: Ember.computed('_maxLat', function() {
    let maxLat = parseFloat(this.get('_maxLat'));

    return maxLat >= -90 && maxLat <= 90;
  }),

  /**
    Flag: indicates whether max longitude in textbox is valid or not.

    @property _maxLngIsValid
    @type Boolean
    @readOnly
    @private
  */
  _maxLngIsValid: Ember.computed('_maxLng', function() {
    let maxLng = parseFloat(this.get('_maxLng'));

    return maxLng >= -180 && maxLng <= 180;
  }),

  /**
    Flag: indicates whether coordinates in textboxes are valid or not.

    @property _coordinatesAreValid
    @type Boolean
    @readOnly
    @private
  */
  _coordinatesAreValid: Ember.computed('_minLatIsValid', '_minLngIsValid', '_maxLatIsValid', '_maxLngIsValid', function() {
    return this.get('_minLatIsValid') && this.get('_minLngIsValid') && this.get('_maxLatIsValid') && this.get('_maxLngIsValid');
  }),

  /**
    Flag: indicates whether coordinates in textboxes are changed or not.

    @property _coordinatesAreChanged
    @type Boolean
    @readOnly
    @private
  */
  _coordinatesAreChanged: Ember.computed('_minLat', '_minLng', '_maxLat', '_maxLng', 'minLat', 'minLng', 'maxLat', 'maxLng', function() {
    if (parseFloat(this.get('_minLat')) !== parseFloat(this.get('minLat'))) {
      return true;
    }

    if (parseFloat(this.get('_minLng')) !== parseFloat(this.get('minLng'))) {
      return true;
    }

    if (parseFloat(this.get('_maxLat')) !== parseFloat(this.get('maxLat'))) {
      return true;
    }

    if (parseFloat(this.get('_maxLng')) !== parseFloat(this.get('maxLng'))) {
      return true;
    }

    return false;
  }),

  /**
    Flag: indicates whether areaselect neeed to be updated (in case of manual changes in coordanates) or not (in case of changes throught GUI).

    @property _needToUpdateAreaSelect
    @type Boolean
    @default true
    @private
  */
  _needToUpdateAreaSelect: true,

  /**
    Reference to component's template.
  */
  layout,

  /**
    Reference to component's CSS-classes names.
    Must be also a component's instance property to be available from component's .hbs template.
  */
  flexberryClassNames,

  /**
    Component's wrapping
 CSS-classes names.

    Any other CSS-class names can be added through component's 'class' property.
    ```handlebars
    {{flexberry-boundingbox class="my-class"}}
    ```

    @property classNames
    @type String[]
    @default ['flexberry-boundingbox']
  */
  classNames: [flexberryClassNames.wrapper],

  /**
    Minimal latitude value.

    @property minLat
    @type number
    @default -90
  */
  minLat: -90,

  /**
    Maximal latitude value.

    @property maxLat
    @type number
    @default 90
  */
  maxLat: 90,

  /**
    Minimal longitude value.

    @property minLng
    @type number
    @default -180
  */
  minLng: -180,

  /**
    Maximal longitude value.

    @property maxLng
    @type number
    @default 180
  */
  maxLng: 180,

  /**
    Map model to be displayed.

    @property maxLng
    @type NewPlatformFlexberryGISMap
    @default null
  */
  mapModel: null,

  /**
    Flag: indicates whether to show zoom-control or not.

    @property zoomControl
    @type Boolean
    @default true
  */
  zoomControl: true,

  /**
    Flag: indicates whether to show attribution-control or not.

    @property attributionControl
    @type Boolean
    @default false
  */
  attributionControl: false,

  /**
    Default width for area select.

    @property areaSelectDefaultWidth
    @type Number
    @default 100
  */
  areaSelectDefaultWidth: 100,

  /**
    Default height for area select.

    @property areaSelectDefaultHeight
    @type Number
    @default 100
  */
  areaSelectDefaultHeight: 100,

  /**
    Observes changes in reference to leaflet map.
    Initializes area select plugin.

    @method _leafletMapDidChange
    @private
  */
  _leafletMapDidChange: Ember.observer('_leafletMap', function() {
    let leafletMap = this.get('_leafletMap');
    if (Ember.isNone(leafletMap)) {
      return;
    }

    leafletMap.on('containerResizeStart', this._leafletMapOnContainerResizeStart, this);
    leafletMap.on('containerResizeEnd', this._leafletMapOnContainerResizeEnd, this);

    this._initizlizeAreaSelect();
  }),

  /**
    Handles leaflet map's 'resizeStart' event.

    @method _leafletMapOnContainerResizeStart
    @private
  */
  _leafletMapOnContainerResizeStart() {
    let areaSelect = this.get('_areaSelect');
    if (!Ember.isNone(areaSelect)) {
      // Temporary unbind 'change' event handler to avoid changes in coordinates while resize is in process.
      areaSelect.off('change', this._areaSelectOnChange, this);
    }
  },

  /**
    Handles leaflet map's 'resizeEnd' event.

    @method _leafletMapOnContainerResizeEnd
    @private
  */
  _leafletMapOnContainerResizeEnd() {
    let areaSelect = this.get('_areaSelect');
    if (Ember.isNone(areaSelect)) {
      this._initizlizeAreaSelect();
    } else {
      let leafletMap = this.get('_leafletMap');
      let leafletMapSize = leafletMap.getSize();
      this._updateAreaSelect({ fitBounds: areaSelect._width > leafletMapSize.x || areaSelect._height > leafletMapSize.y });
    }
  },

  /**
    Initializes area select.

    @method _initizlizeAreaSelect
    @private
  */
  _initizlizeAreaSelect() {
    let areaSelect = this.get('_areaSelect');
    if (!Ember.isNone(areaSelect)) {
      // Area select is already initialized.
      return;
    }

    let leafletMap = this.get('_leafletMap');
    if (Ember.isNone(leafletMap)) {
      return;
    }

    let leafletMapSize = leafletMap.getSize();
    if (leafletMapSize.x <= 0 || leafletMapSize.y <= 0) {
      // Map is invisible, so area select can't be initialized properly.
      return;
    }

    areaSelect = L.areaSelect({ width: this.get('areaSelectDefaultWidth'), height: this.get('areaSelectDefaultHeight') });
    this.set('_areaSelect', areaSelect);

    areaSelect.addTo(leafletMap);
    areaSelect.on('change', this._areaSelectOnChange, this);

    this._boundingBoxCoordinatesDidChange();
  },

  /**
    Observes changes in bounding box coordiantes.

    @method _bboxCoordinatesDidChange
    @private
  */
  _boundingBoxCoordinatesDidChange: Ember.observer('minLat', 'minLng', 'maxLat', 'maxLng', function() {
    Ember.run.once(this, '_updateBoundingBoxCoordiantes');
  }),

  /**
    Updtaes bounding box coordunates accirding tocoordinates specified in public properties.

    @method _updateBoundingBoxCoordiantes
    @private
  */
  _updateBoundingBoxCoordiantes() {
    let minLat = this.get('minLat');
    let minLng = this.get('minLng');
    let maxLat = this.get('maxLat');
    let maxLng = this.get('maxLng');

    // Update coordiantes in textboxes.
    this.setProperties({
      _minLat: minLat,
      _minLng: minLng,
      _maxLat: maxLat,
      _maxLng: maxLng
    });

    let leafletMap = this.get('_leafletMap');
    let areaSelect = this.get('_areaSelect');
    let coordinatesAreValid = this.get('_coordinatesAreValid');
    if (Ember.isNone(leafletMap) || Ember.isNone(areaSelect) || !coordinatesAreValid) {
      return;
    }

    // Update areaSelect if needed.
    if (this.get('_needToUpdateAreaSelect')) {
      this._updateAreaSelect({ fitBounds: true });
    } else {
      this.set('_needToUpdateAreaSelect', true);
    }

    let coordinatesBounds = [
      [minLng, minLat],
      [maxLng, minLat],
      [maxLng, maxLat],
      [minLng, maxLat],
      [minLng, minLat]
    ];

    if (minLat === -90 && maxLat === 90) {
      coordinatesBounds.splice(2, 0, [maxLng, 0]);
      coordinatesBounds.splice(5, 0, [minLng, 0]);
    }

    // If some of polygon's edges have length of 180 (for example from latitude -90 till latitude 90)
    // then PostGIS will throw an exception "Antipodal (180 degrees long) edge detected".
    // Workaround is to make each edge shorter (add additional points into polygon's edges).
    let bboxEWKT = `SRID=4326;POLYGON((` +
      `${minLng} ${minLat},` +
      `${minLng + (maxLng - minLng) * 0.5} ${minLat},` +
      `${maxLng} ${minLat},` +
      `${maxLng} ${minLat + (maxLat - minLat) * 0.5},` +
      `${maxLng} ${maxLat},` +
      `${minLng + (maxLng - minLng) * 0.5} ${maxLat},` +
      `${minLng} ${maxLat},` +
      `${minLng} ${minLat + (maxLat - minLat) * 0.5},` +
      `${minLng} ${minLat}))`;

    // Send 'boundingBoxChange' action to report about changes in bounds.
    this.sendAction('boundingBoxChange', {
      minLat: minLat,
      minLng: minLng,
      maxLat: maxLat,
      maxLng: maxLng,
      bounds: L.latLngBounds(L.latLng(minLat, minLng), L.latLng(maxLat, maxLng)),
      bboxEWKT: bboxEWKT,
      bboxGeoJSON: {
        type: 'Polygon',
        coordinates: [
          coordinatesBounds
        ],
        crs: {
          type: 'name',
          properties: {
            name: 'EPSG:4326'
          }
        }
      }
    });
  },

  /**
    Updtaes areaSelect according to coordinates specified in public properties.

    @method _updateAreaSelect
    @private
  */
  _updateAreaSelect(options) {
    options = options || {};
    let leafletMap = this.get('_leafletMap');
    let areaSelect = this.get('_areaSelect');
    if (Ember.isNone(leafletMap) || Ember.isNone(areaSelect)) {
      return;
    }

    let minLat = this.get('minLat');
    let minLng = this.get('minLng');
    let maxLat = this.get('maxLat');
    let maxLng = this.get('maxLng');

    let updateAreaSelect = () => {
      // Fit areaSelect to new bounds.
      let newWidth = Math.abs(
        leafletMap.latLngToLayerPoint(L.latLng(minLat, maxLng)).x) - Math.abs(leafletMap.latLngToLayerPoint(L.latLng(minLat, minLng)).x
      );
      let newHeight = Math.abs(
        leafletMap.latLngToLayerPoint(L.latLng(maxLat, minLng)).y) - Math.abs(leafletMap.latLngToLayerPoint(L.latLng(minLat, minLng)).y
      );
      areaSelect.setDimensions({ width: Math.abs(newWidth), height: Math.abs(newHeight) });
    };

    if (options.fitBounds) {
      // Temporary unbind 'change' event handler to avoid cyclic changes.
      areaSelect.off('change', this._areaSelectOnChange, this);

      // Fit map to new bounds.
      this._fitBoundsOfLeafletMap(L.latLngBounds(L.latLng(minLat, minLng), L.latLng(maxLat, maxLng))).then(() => {
        updateAreaSelect();
      }).catch((error) => {
        Ember.Logger.error(error);
      }).finally(() => {
        // Bind 'change' event handler again.
        areaSelect.on('change', this._areaSelectOnChange, this);
      });
    } else {
      // Temporary unbind 'change' event handler to avoid cyclic changes.
      areaSelect.off('change', this._areaSelectOnChange, this);

      updateAreaSelect();

      // Bind 'change' event handler again.
      areaSelect.on('change', this._areaSelectOnChange, this);
    }
  },

  /**
    Fits specified leaflet map's bounds.

    @method _fitBoundsOfLeafletMap
    @param {L.LatLngBounds} bounds Bounds to be fitted.
    @returns Ember.RSVP.Promise
    Promise which will be resolved when fitting will be finished.
  */
  _fitBoundsOfLeafletMap(bounds) {
    return new Ember.RSVP.Promise((resolve, reject) => {
      let leafletMap = this.get('_leafletMap');
      if (Ember.isNone(leafletMap)) {
        reject('Leaflet map is not defined');
      }

      leafletMap.once('moveend', () => {
        resolve();
      });

      leafletMap.fitBounds(bounds, {
        animate: false
      });
    });
  },

  /**
    Actions made when areaSelect.on('change') fires.

    @method _areaSelectOnChange
    @private
  */
  _areaSelectOnChange() {
    let areaSelect = this.get('_areaSelect');
    let bounds = areaSelect.getBounds();

    // Update component's public properties related to bounding box coordinates,
    // it will force '_bboxCoordinatesDidChange' observer to be called.
    this.set('_needToUpdateAreaSelect', false);
    this.setProperties({
      minLat: bounds.getSouth(),
      minLng: bounds.getWest(),
      maxLat: bounds.getNorth(),
      maxLng: bounds.getEast()
    });
  },

  /**
    Destroys DOM-related component's properties.
  */
  willDestroyElement() {
    let areaSelect = this.get('_areaSelect');
    if (!Ember.isNone(areaSelect)) {
      // Unbind 'change' event handler to avoid memory leaks.
      areaSelect.off('change', this._areaSelectOnChange, this);
      areaSelect.remove();
      this.set('_areaSelect', null);
    }

    let leafletMap = this.get('_leafletMap');
    if (!Ember.isNone(leafletMap)) {
      // Unbind 'containerResizeStart', 'containerResizeEnd' events handlers to avoid memory leaks.
      leafletMap.off('containerResizeStart', this._leafletMapOnContainerResizeStart, this);
      leafletMap.off('containerResizeEnd', this._leafletMapOnContainerResizeEnd, this);
    }

    this._super(...arguments);
  },

  actions: {
    /**
      This action is called when change borders button is pressed.

      @method actions.onButtonClick
    */
    onButtonClick() {
      if (!(this.get('_coordinatesAreValid') || this.get('_coordinatesAreChanged'))) {
        return;
      }

      // Update related public properties with coordiantes to force '_updateBoundingBoxCoordiantes' to be triggered.
      this.set('_needToUpdateAreaSelect', true);
      this.setProperties({
        minLat: parseFloat(this.get('_minLat')),
        minLng: parseFloat(this.get('_minLng')),
        maxLat: parseFloat(this.get('_maxLat')),
        maxLng: parseFloat(this.get('_maxLng'))
      });
    }
  }

  /**
    Component's action invoking when bounding box coordiantes did change.

    @method sendingActions.boundingBoxChange
    @param {Object} e Action's parameters.
    @param {Number} e.minLat Bounding box min latitude.
    @param {Number} e.minLng Bounding box min longitude.
    @param {Number} e.maxLat Bounding box max latitude.
    @param {Number} e.maxLng Bounding box max longitude.
    @param {L.LatLngBounds} e.bounds Bounds related to changed coordinates.
  */
});


text:
<?php if(!is_writable(APPPATH."controllers")):?>

	Directory application/controllers is not writeable. Please change folder permission.

<?php endif;?>

<?php if(!is_writable(APPPATH."models")):?>

	Directory application/models is not writeable.  Please change folder permission.

<?php endif;?>

<?php if(!is_writable(APPPATH."views")):?>

	Directory application/views is not writeable.  Please change folder permission.

<?php endif;?>

Model Generator

		<form action="<?=site_url("nip-igniter/generate-model")?>" method="post" id="formModelGenerator">

				Table Name
				<input id="inputTableName" placeholder="Table name..." class="form-control" name="table_name">

					<input id="checkboxGenerate" type="checkbox" name="is_crud" value="1">
					Generate CRUD ?

			<button class="btn btn-primary">Generate</button>
		</form>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Generated Content

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>