0
# Parameter Handling
1
2
Type-safe parameter converters for common data types with automatic parsing, validation, and error handling for JAX-RS resource methods. These parameter wrappers provide consistent error handling and HTTP 400 responses for invalid input.
3
4
## Capabilities
5
6
### AbstractParam Base Class
7
8
Base class for all parameter types providing common parsing, validation, and error handling functionality.
9
10
```java { .api }
11
/**
12
* Abstract base class for Jersey parameter types with error handling
13
* @param <T> the type of value wrapped by the parameter
14
*/
15
public abstract class AbstractParam<T> {
16
17
/** Creates parameter with input value using default parameter name */
18
protected AbstractParam(String input);
19
20
/** Creates parameter with input value and custom parameter name */
21
protected AbstractParam(String input, String parameterName);
22
23
/** Gets the parsed and validated value */
24
public T get();
25
26
/** Parses the string input into the target type */
27
protected abstract T parse(String input) throws Exception;
28
29
/** Generates error message for parsing failures */
30
protected String errorMessage(Exception e);
31
32
/** Gets HTTP status code for parsing errors (default: BAD_REQUEST) */
33
protected Response.Status getErrorStatus();
34
35
/** Generates ErrorMessage for client response */
36
protected ErrorMessage generateErrorMessage(String input, Exception e);
37
}
38
```
39
40
### UUIDParam
41
42
Parameter wrapper for UUID values with automatic parsing and validation.
43
44
```java { .api }
45
/**
46
* Parameter wrapper for UUID values
47
* Throws 400 Bad Request for invalid UUID strings
48
*/
49
public class UUIDParam extends AbstractParam<UUID> {
50
51
/** Creates UUIDParam from string input */
52
public UUIDParam(String input);
53
54
/** Creates UUIDParam with custom parameter name for error messages */
55
public UUIDParam(String input, String parameterName);
56
}
57
```
58
59
**Usage Examples:**
60
61
```java
62
import io.dropwizard.jersey.params.UUIDParam;
63
import jakarta.ws.rs.*;
64
import java.util.UUID;
65
66
@Path("/users")
67
public class UserResource {
68
69
@GET
70
@Path("/{id}")
71
public User getUser(@PathParam("id") UUIDParam userId) {
72
UUID id = userId.get(); // Automatic UUID parsing
73
return userService.findById(id);
74
}
75
76
@GET
77
public List<User> getUsers(@QueryParam("organizationId") UUIDParam orgId) {
78
if (orgId != null) {
79
return userService.findByOrganization(orgId.get());
80
}
81
return userService.findAll();
82
}
83
}
84
```
85
86
### IntParam
87
88
Parameter wrapper for integer values with validation.
89
90
```java { .api }
91
/**
92
* Parameter wrapper for integer values
93
* Returns 400 Bad Request for non-decimal values
94
* @deprecated Use OptionalInt instead
95
*/
96
@Deprecated
97
public class IntParam extends AbstractParam<Integer> {
98
99
/** Creates IntParam from string input */
100
public IntParam(String input);
101
102
/** Creates IntParam with custom parameter name */
103
public IntParam(String input, String parameterName);
104
}
105
```
106
107
### LongParam
108
109
Parameter wrapper for long values with validation.
110
111
```java { .api }
112
/**
113
* Parameter wrapper for long values
114
* Returns 400 Bad Request for non-decimal values
115
* @deprecated Use OptionalLong instead
116
*/
117
@Deprecated
118
public class LongParam extends AbstractParam<Long> {
119
120
/** Creates LongParam from string input */
121
public LongParam(String input);
122
123
/** Creates LongParam with custom parameter name */
124
public LongParam(String input, String parameterName);
125
}
126
```
127
128
### NonEmptyStringParam
129
130
Parameter wrapper for non-empty string values with validation.
131
132
```java { .api }
133
/**
134
* Parameter wrapper for non-empty strings
135
* Returns 400 Bad Request for null, empty, or whitespace-only strings
136
*/
137
public class NonEmptyStringParam extends AbstractParam<String> {
138
139
/** Creates NonEmptyStringParam from string input */
140
public NonEmptyStringParam(String input);
141
142
/** Creates NonEmptyStringParam with custom parameter name */
143
public NonEmptyStringParam(String input, String parameterName);
144
}
145
```
146
147
**Usage Examples:**
148
149
```java
150
import io.dropwizard.jersey.params.*;
151
import jakarta.ws.rs.*;
152
153
@Path("/api")
154
public class ApiResource {
155
156
@GET
157
@Path("/search")
158
public SearchResults search(@QueryParam("q") NonEmptyStringParam query,
159
@QueryParam("limit") IntParam limit) {
160
String searchTerm = query.get(); // Guaranteed non-empty
161
int resultLimit = limit != null ? limit.get() : 10;
162
return searchService.search(searchTerm, resultLimit);
163
}
164
165
@GET
166
@Path("/items/{id}")
167
public Item getItem(@PathParam("id") LongParam itemId) {
168
Long id = itemId.get(); // Automatic long parsing
169
return itemService.findById(id);
170
}
171
}
172
```
173
174
### Parameter Converters
175
176
Provider classes that enable automatic conversion of string parameters to AbstractParam types.
177
178
```java { .api }
179
/**
180
* Abstract parameter converter for AbstractParam types
181
*/
182
public abstract class AbstractParamConverter<T> implements ParamConverter<T> {
183
public T fromString(String value);
184
public String toString(T value);
185
}
186
187
/**
188
* Parameter converter provider for AbstractParam types
189
* Automatically registers converters for all AbstractParam subclasses
190
*/
191
public class AbstractParamConverterProvider implements ParamConverterProvider {
192
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations);
193
}
194
```
195
196
## Error Handling
197
198
All parameter types provide consistent error handling:
199
200
### Validation Errors
201
202
When parameter parsing fails, a `WebApplicationException` is thrown with:
203
- HTTP 400 (Bad Request) status
204
- Descriptive error message indicating the parameter name and validation failure
205
- Consistent JSON error format via `ErrorMessage`
206
207
### Custom Error Messages
208
209
```java
210
public class CustomUUIDParam extends AbstractParam<UUID> {
211
212
public CustomUUIDParam(String input) {
213
super(input, "User ID");
214
}
215
216
@Override
217
protected String errorMessage(Exception e) {
218
return "User ID must be a valid UUID format";
219
}
220
221
@Override
222
protected UUID parse(String input) throws Exception {
223
return UUID.fromString(input);
224
}
225
}
226
```
227
228
## Integration with Validation
229
230
Parameter types work seamlessly with Bean Validation:
231
232
```java
233
import jakarta.validation.constraints.*;
234
import jakarta.validation.Valid;
235
import io.dropwizard.jersey.params.UUIDParam;
236
237
@Path("/users")
238
public class UserResource {
239
240
@POST
241
public User createUser(@Valid @NotNull CreateUserRequest request,
242
@QueryParam("organizationId") UUIDParam orgId) {
243
// Both parameter validation and bean validation are applied
244
UUID organizationId = orgId.get(); // Parameter parsing validated
245
// request object validated by Bean Validation
246
return userService.create(request, organizationId);
247
}
248
}
249
250
public class CreateUserRequest {
251
@NotBlank
252
@Size(min = 2, max = 50)
253
private String name;
254
255
256
private String email;
257
258
// getters and setters
259
}
260
```
261
262
## Best Practices
263
264
### Use Appropriate Types
265
266
```java
267
// Good - use UUIDParam for UUID path/query parameters
268
@Path("/{userId}")
269
public User getUser(@PathParam("userId") UUIDParam userId) {
270
return userService.findById(userId.get());
271
}
272
273
// Good - use NonEmptyStringParam for required string parameters
274
@GET
275
public List<Item> search(@QueryParam("q") NonEmptyStringParam query) {
276
return searchService.search(query.get());
277
}
278
279
// Consider Optional types for new code instead of deprecated IntParam/LongParam
280
@GET
281
public List<Item> getItems(@QueryParam("limit") OptionalInt limit) {
282
int actualLimit = limit.orElse(10);
283
return itemService.getItems(actualLimit);
284
}
285
```
286
287
### Handle Null Parameters
288
289
```java
290
@GET
291
@Path("/users")
292
public List<User> getUsers(@QueryParam("organizationId") UUIDParam orgId) {
293
if (orgId != null) {
294
// orgId.get() is safe here - parsing already validated
295
return userService.findByOrganization(orgId.get());
296
}
297
return userService.findAll();
298
}
299
```
300
301
### Custom Parameter Types
302
303
```java
304
public class EmailParam extends AbstractParam<String> {
305
306
public EmailParam(String input) {
307
super(input, "Email");
308
}
309
310
@Override
311
protected String parse(String input) throws Exception {
312
if (input == null || !input.contains("@")) {
313
throw new IllegalArgumentException("Invalid email format");
314
}
315
return input.toLowerCase().trim();
316
}
317
318
@Override
319
protected String errorMessage(Exception e) {
320
return "Email must be a valid email address";
321
}
322
}
323
```