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.yetus.audience.InterfaceAudience;
021import org.apache.hadoop.hbase.util.Bytes;
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
027 * operators AND(&), OR(|) and 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  /**
039   * @return The visibility expression
040   */
041  public String getExpression() {
042    return this.expression;
043  }
044
045  @Override
046  public String toString() {
047    return this.expression;
048  }
049
050  /**
051   * Helps in quoting authentication Strings. Use this if unicode characters to
052   * be used in expression or special characters like '(', ')',
053   * '"','\','&','|','!'
054   */
055  public static String quote(String auth) {
056    return quote(Bytes.toBytes(auth));
057  }
058
059  /**
060   * Helps in quoting authentication Strings. Use this if unicode characters to
061   * be used in expression or special characters like '(', ')',
062   * '"','\','&','|','!'
063   */
064  public static String quote(byte[] auth) {
065    int escapeChars = 0;
066
067    for (int i = 0; i < auth.length; i++)
068      if (auth[i] == '"' || auth[i] == '\\')
069        escapeChars++;
070
071    byte[] escapedAuth = new byte[auth.length + escapeChars + 2];
072    int index = 1;
073    for (int i = 0; i < auth.length; i++) {
074      if (auth[i] == '"' || auth[i] == '\\') {
075        escapedAuth[index++] = '\\';
076      }
077      escapedAuth[index++] = auth[i];
078    }
079
080    escapedAuth[0] = '"';
081    escapedAuth[escapedAuth.length - 1] = '"';
082
083    return Bytes.toString(escapedAuth);
084  }
085}