Line data Source code
1 : // Copyright (C) 2014 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.change; 16 : 17 : import com.google.common.base.CharMatcher; 18 : import com.google.common.base.Strings; 19 : import java.util.Collections; 20 : import java.util.HashSet; 21 : import java.util.Set; 22 : import java.util.regex.Matcher; 23 : import java.util.regex.Pattern; 24 : 25 : public class HashtagsUtil { 26 : public static class InvalidHashtagException extends Exception { 27 : private static final long serialVersionUID = 1L; 28 : 29 : static InvalidHashtagException hashtagsMayNotContainCommas() { 30 1 : return new InvalidHashtagException("hashtags may not contain commas"); 31 : } 32 : 33 : InvalidHashtagException(String message) { 34 1 : super(message); 35 1 : } 36 : } 37 : 38 9 : private static final CharMatcher LEADER = CharMatcher.whitespace().or(CharMatcher.is('#')); 39 : private static final String PATTERN = "(?:\\s|\\A)#[\\p{L}[0-9]-_]+"; 40 : 41 : public static String cleanupHashtag(String hashtag) { 42 9 : hashtag = LEADER.trimLeadingFrom(hashtag); 43 9 : hashtag = CharMatcher.whitespace().trimTrailingFrom(hashtag); 44 9 : return hashtag; 45 : } 46 : 47 : public static Set<String> extractTags(String input) { 48 1 : Set<String> result = new HashSet<>(); 49 1 : if (!Strings.isNullOrEmpty(input)) { 50 1 : Matcher matcher = Pattern.compile(PATTERN).matcher(input); 51 1 : while (matcher.find()) { 52 1 : result.add(cleanupHashtag(matcher.group())); 53 : } 54 : } 55 1 : return result; 56 : } 57 : 58 : static Set<String> extractTags(Set<String> input) throws InvalidHashtagException { 59 8 : if (input == null) { 60 8 : return Collections.emptySet(); 61 : } 62 8 : HashSet<String> result = new HashSet<>(); 63 8 : for (String hashtag : input) { 64 8 : if (hashtag.contains(",")) { 65 1 : throw InvalidHashtagException.hashtagsMayNotContainCommas(); 66 : } 67 8 : hashtag = cleanupHashtag(hashtag); 68 8 : if (!hashtag.isEmpty()) { 69 8 : result.add(hashtag); 70 : } 71 8 : } 72 8 : return result; 73 : } 74 : 75 : private HashtagsUtil() {} 76 : }