View Javadoc

1   /*
2    * Copyright 2012 smartics, Kronseder & Reiner GmbH
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  package de.smartics.ci.comm.command;
17  
18  import java.util.Map;
19  
20  import org.apache.commons.httpclient.HttpMethodBase;
21  import org.apache.commons.lang.StringUtils;
22  import org.slf4j.Logger;
23  import org.slf4j.LoggerFactory;
24  
25  import de.smartics.ci.comm.LogHelper;
26  import de.smartics.ci.comm.LogLevel;
27  
28  /**
29   * Abstract command that combines all every command needs.
30   *
31   * @param <T> the concrete type of the command.
32   */
33  public abstract class AbstractCommand<T extends Command<T>> implements
34      Command<T>
35  {
36    // ********************************* Fields *********************************
37  
38    // --- constants ------------------------------------------------------------
39  
40    /**
41     * Using the modulo operator this constant is used to calculate the main
42     * status code of a http response e.g 202 % 100 = 2.
43     */
44    protected static final int ERROR_CATEGORY_DESTINGUISHER = 100;
45  
46    /**
47     * Reference to the logger for this class.
48     */
49    private static final Logger LOG = LoggerFactory
50        .getLogger(AbstractCommand.class);
51  
52    // --- members --------------------------------------------------------------
53  
54    /**
55     * The log level for this command.
56     */
57    protected LogLevel logLevel;
58  
59    // ****************************** Initializer *******************************
60  
61    // ****************************** Constructors ******************************
62  
63    // ****************************** Inner Classes *****************************
64  
65    // ********************************* Methods ********************************
66  
67    // --- init -----------------------------------------------------------------
68  
69    // --- get&set --------------------------------------------------------------
70  
71    /**
72     * Sets the log level for this command.
73     *
74     * @param logLevel the log level for this command.
75     */
76    public final void setLogLevel(final LogLevel logLevel)
77    {
78      this.logLevel = logLevel;
79    }
80  
81    // --- business -------------------------------------------------------------
82  
83    /**
84     * Checks if the parameters are blank.
85     *
86     * @param params the String parameters to check.
87     * @throws CommandException when at leas one parameter is blan.
88     */
89    protected void checkParameterNotBlank(final String... params)
90      throws CommandException
91    {
92      if (params.length > 0)
93      {
94        for (final String param : params)
95        {
96          if (StringUtils.isBlank(param))
97          {
98            throw new CommandException("Parameter may not be blank!");
99          }
100       }
101     }
102   }
103 
104   /**
105    * Checks the result statusCode of a request.
106    *
107    * @param statusCode the status code returned from the ci system.
108    * @throws InvalidRequestException when the status code indicates an error.
109    */
110   protected void checkResult(final int statusCode)
111     throws InvalidRequestException
112   {
113     if (statusCode / ERROR_CATEGORY_DESTINGUISHER != 2)
114     {
115       if (statusCode / ERROR_CATEGORY_DESTINGUISHER == 3)
116       {
117         LogHelper.logError(LOG, logLevel, "found redirect!");
118       }
119       LogHelper.logError(LOG, logLevel, "CI Fehler: " + statusCode);
120       throw new InvalidRequestException("This request is invalid, statusCode: "
121                                         + statusCode);
122     }
123   }
124 
125   /**
126    * Checks the result statusCode of a request. Redirects are not handled as an
127    * error.
128    *
129    * @param statusCode the status code returned from the ci system.
130    * @throws InvalidRequestException when the status code indicates an error.
131    */
132   protected void checkResultRegardingRedirect(final int statusCode)
133     throws InvalidRequestException
134   {
135     if (statusCode / ERROR_CATEGORY_DESTINGUISHER == 3)
136     {
137       LogHelper.logInfo(LOG, logLevel, "Redirecting");
138     }
139     else
140     {
141       checkResult(statusCode);
142     }
143   }
144 
145   /**
146    * Build the query string using the given parameter.
147    *
148    * @param parameter the parameter for the query string.
149    * @return the queryString.
150    */
151   protected String buildQueryString(final Map<String, String> parameter)
152   {
153     final StringBuilder builder = new StringBuilder();
154     boolean isFirstParameter = true;
155 
156     for (final Map.Entry<String, String> entry : parameter.entrySet())
157     {
158       final String delimiter = fetchDelimiter(isFirstParameter);
159       builder.append(delimiter);
160       final String key = entry.getKey();
161       final String value = entry.getValue();
162       builder.append(key + "=" + value);
163       isFirstParameter = false;
164     }
165     return builder.toString();
166   }
167 
168   /**
169    * Fetch the delimiter between two parameters of a query string for a get
170    * command.
171    *
172    * @param isFirstParameter wether or not this is the first call.
173    * @return the delimiter.
174    */
175   protected String fetchDelimiter(final boolean isFirstParameter)
176   {
177     if (isFirstParameter)
178     {
179       return "";
180     }
181     else
182     {
183       return "&";
184     }
185   }
186 
187   /**
188    * Add request headers to the method.
189    *
190    * @param method the http method used to add request headers.
191    */
192   protected void addRequestHeaders(final HttpMethodBase method)
193   {
194     method.addRequestHeader("Content-Type", "application/xml; charset=UTF-8");
195   }
196 
197   // --- object basics --------------------------------------------------------
198 
199 }