[LIB-13] Add regular expressions classes
[chesshog-scanner.git] / src / main / java / org / hedgecode / chess / scanner / regex / RegexType.java
1 /*
2  * Copyright (c) 2019-2020. Developed by Hedgecode.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.hedgecode.chess.scanner.regex;
18
19 import java.io.UnsupportedEncodingException;
20 import java.net.URLEncoder;
21
22 import org.hedgecode.chess.scanner.ChessHogScannerConstants;
23
24 /**
25  * RegexType
26  *
27  * @author Dmitry Samoshin aka gotty
28  */
29 public enum RegexType {
30
31     TOURNAMENT {
32         @Override
33         public String format(String target, RegexParams params) {
34             if (params.getPageId() != null) {
35                 target = target.replace(
36                         RegexParams.PAGE_ID,
37                         params.getPageId()
38                 );
39             }
40             return target.replace(
41                     RegexParams.TOURNAMENT_ID,
42                     params.getTournamentId()
43             );
44         }
45     },
46
47     GAME {
48         @Override
49         public String format(String target, RegexParams params) {
50             return target.replace(
51                     RegexParams.GAME_ID,
52                     params.getGameId()
53             );
54         }
55     },
56
57     QUERY {
58         @Override
59         public String format(String target, RegexParams params) {
60             try {
61                 return target.replace(
62                         RegexParams.QUERY,
63                         params.isUrlEncode()
64                                 ? URLEncoder.encode(params.getQuery(), ChessHogScannerConstants.CHARSET.name())
65                                 : params.getQuery()
66                 );
67             } catch (UnsupportedEncodingException e) {
68                 return null;
69             }
70         }
71     };
72
73     public abstract String format(String target, RegexParams params);
74
75 }