blob: b78cc57e45caa342ed927d36f23a746bb6c3f3f5 [file] [log] [blame]
Stuart McCulloch5ec302d2008-12-04 07:58:07 +00001/*
2 * $Header: /cvs/xierpa/aQute.util.jar/src/aQute/lib/osgi/Instruction.java,v 1.1 2007-01-03 19:54:32 pkriens Exp $
3 *
4 * Copyright (c) OSGi Alliance (2006). All Rights Reserved.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19package aQute.lib.osgi;
20
21import java.util.regex.*;
22
23public class Instruction {
24 Pattern pattern;
25 String instruction;
26 boolean negated;
27 boolean optional;
28
29 public Instruction(String instruction, boolean negated) {
30 this.instruction = instruction;
31 this.negated = negated;
32 }
33
34 public boolean matches(String value) {
35 return getMatcher(value).matches();
36 }
37
38 public boolean isNegated() {
39 return negated;
40 }
41
42 public String getPattern() {
43 return instruction;
44 }
45
46 /**
47 * Convert a string based pattern to a regular expression based pattern.
48 * This is called an instruction, this object makes it easier to handle the
49 * different cases
50 *
51 * @param string
52 * @return
53 */
54 public static Instruction getPattern(String string) {
55 boolean negated = false;
56 if (string.startsWith("!")) {
57 negated = true;
58 string = string.substring(1);
59 }
60 StringBuffer sb = new StringBuffer();
61 for (int c = 0; c < string.length(); c++) {
62 switch (string.charAt(c)) {
63 case '.':
64 sb.append("\\.");
65 break;
66 case '*':
67 sb.append(".*");
68 break;
69 case '?':
70 sb.append(".?");
71 break;
72 default:
73 sb.append(string.charAt(c));
74 break;
75 }
76 }
77 string = sb.toString();
78 if (string.endsWith("\\..*")) {
79 sb.append("|");
80 sb.append(string.substring(0, string.length() - 4));
81 }
82 return new Instruction(sb.toString(), negated);
83 }
84
85 public String toString() {
86 return getPattern();
87 }
88
89 public Matcher getMatcher(String value) {
90 if (pattern == null) {
91 pattern = Pattern.compile(instruction);
92 }
93 return pattern.matcher(value);
94 }
95
96 public int hashCode() {
97 return instruction.hashCode();
98 }
99
100 public boolean equals(Object other) {
101 return other != null && (other instanceof Instruction)
102 && instruction.equals(((Instruction) other).instruction);
103 }
104
105 public void setOptional() {
106 optional = true;
107 }
108
109 public boolean isOptional() {
110 return optional;
111 }
112
113}