001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.security.visibility;
019
020import org.apache.hadoop.hbase.util.Bytes;
021import org.apache.yetus.audience.InterfaceAudience;
022
023/**
024 * This contains a visibility expression which can be associated with a cell. When it is set with a
025 * Mutation, all the cells in that mutation will get associated with this expression. A visibility
026 * expression can contain visibility labels combined with logical operators AND(&), OR(|) and
027 * NOT(!)
028 */
029@InterfaceAudience.Public
030public class CellVisibility {
031
032  private String expression;
033
034  public CellVisibility(String expression) {
035    this.expression = expression;
036  }
037
038  /** Returns The visibility expression */
039  public String getExpression() {
040    return this.expression;
041  }
042
043  @Override
044  public String toString() {
045    return this.expression;
046  }
047
048  /**
049   * Helps in quoting authentication Strings. Use this if unicode characters to be used in
050   * expression or special characters like '(', ')', '"','\','&','|','!'
051   */
052  public static String quote(String auth) {
053    return quote(Bytes.toBytes(auth));
054  }
055
056  /**
057   * Helps in quoting authentication Strings. Use this if unicode characters to be used in
058   * expression or special characters like '(', ')', '"','\','&','|','!'
059   */
060  public static String quote(byte[] auth) {
061    int escapeChars = 0;
062
063    for (int i = 0; i < auth.length; i++)
064      if (auth[i] == '"' || auth[i] == '\\') escapeChars++;
065
066    byte[] escapedAuth = new byte[auth.length + escapeChars + 2];
067    int index = 1;
068    for (int i = 0; i < auth.length; i++) {
069      if (auth[i] == '"' || auth[i] == '\\') {
070        escapedAuth[index++] = '\\';
071      }
072      escapedAuth[index++] = auth[i];
073    }
074
075    escapedAuth[0] = '"';
076    escapedAuth[escapedAuth.length - 1] = '"';
077
078    return Bytes.toString(escapedAuth);
079  }
080}