0
# Service Layer
1
2
Core portal services providing business logic implementations, HTTP endpoints, and permission checking capabilities for the Liferay portal framework.
3
4
## Capabilities
5
6
### Core Service Layer
7
8
The service layer provides the main business logic implementations for portal entities and operations.
9
10
```java { .api }
11
/**
12
* Base interface for all portal services providing common service patterns
13
*/
14
public interface BaseService {
15
16
/**
17
* Gets the service context for operations
18
* @return ServiceContext instance
19
*/
20
ServiceContext getServiceContext();
21
22
/**
23
* Sets the service context for operations
24
* @param serviceContext the service context to use
25
*/
26
void setServiceContext(ServiceContext serviceContext);
27
}
28
29
/**
30
* Local service interface providing direct access to service operations
31
*/
32
public interface LocalService extends BaseService {
33
34
/**
35
* Performs service operation with full privileges
36
* @param parameters operation parameters
37
* @return operation result
38
* @throws SystemException if operation fails
39
*/
40
Object performOperation(Object... parameters) throws SystemException;
41
42
/**
43
* Validates operation parameters and permissions
44
* @param parameters operation parameters
45
* @throws PortalException if validation fails
46
*/
47
void validateOperation(Object... parameters) throws PortalException;
48
}
49
50
/**
51
* Remote service interface providing secure remote access to service operations
52
*/
53
public interface RemoteService extends BaseService {
54
55
/**
56
* Performs service operation with permission checking
57
* @param parameters operation parameters
58
* @return operation result
59
* @throws SystemException if operation fails
60
* @throws PrincipalException if permission denied
61
*/
62
Object performSecureOperation(Object... parameters)
63
throws SystemException, PrincipalException;
64
}
65
```
66
67
### HTTP Service Endpoints
68
69
HTTP-specific service implementations providing REST and SOAP endpoints for portal services.
70
71
```java { .api }
72
/**
73
* Base HTTP service providing common HTTP endpoint functionality
74
*/
75
public abstract class BaseHTTPService {
76
77
/**
78
* Processes HTTP GET requests
79
* @param request HTTP servlet request
80
* @param response HTTP servlet response
81
* @throws ServletException if request processing fails
82
* @throws IOException if I/O error occurs
83
*/
84
protected void doGet(HttpServletRequest request, HttpServletResponse response)
85
throws ServletException, IOException;
86
87
/**
88
* Processes HTTP POST requests
89
* @param request HTTP servlet request
90
* @param response HTTP servlet response
91
* @throws ServletException if request processing fails
92
* @throws IOException if I/O error occurs
93
*/
94
protected void doPost(HttpServletRequest request, HttpServletResponse response)
95
throws ServletException, IOException;
96
97
/**
98
* Processes HTTP PUT requests
99
* @param request HTTP servlet request
100
* @param response HTTP servlet response
101
* @throws ServletException if request processing fails
102
* @throws IOException if I/O error occurs
103
*/
104
protected void doPut(HttpServletRequest request, HttpServletResponse response)
105
throws ServletException, IOException;
106
107
/**
108
* Processes HTTP DELETE requests
109
* @param request HTTP servlet request
110
* @param response HTTP servlet response
111
* @throws ServletException if request processing fails
112
* @throws IOException if I/O error occurs
113
*/
114
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
115
throws ServletException, IOException;
116
}
117
118
/**
119
* JSON web service providing REST API endpoints
120
*/
121
public class JSONWebService extends BaseHTTPService {
122
123
/**
124
* Processes JSON-based web service requests
125
* @param serviceName the service to invoke
126
* @param methodName the method to call
127
* @param parameters method parameters as JSON
128
* @return JSON response
129
* @throws Exception if service invocation fails
130
*/
131
public String invokeService(String serviceName, String methodName, String parameters)
132
throws Exception;
133
134
/**
135
* Serializes object to JSON format
136
* @param object the object to serialize
137
* @return JSON string representation
138
*/
139
protected String toJSON(Object object);
140
141
/**
142
* Deserializes JSON to object
143
* @param json JSON string
144
* @param clazz target class type
145
* @return deserialized object
146
*/
147
protected <T> T fromJSON(String json, Class<T> clazz);
148
}
149
150
/**
151
* SOAP web service providing SOAP API endpoints
152
*/
153
public class SOAPWebService extends BaseHTTPService {
154
155
/**
156
* Processes SOAP-based web service requests
157
* @param soapAction the SOAP action to perform
158
* @param soapMessage the SOAP message body
159
* @return SOAP response message
160
* @throws Exception if SOAP processing fails
161
*/
162
public String processSoapRequest(String soapAction, String soapMessage)
163
throws Exception;
164
165
/**
166
* Generates WSDL definition for the service
167
* @return WSDL XML definition
168
*/
169
public String generateWSDL();
170
}
171
```
172
173
### Service Utilities
174
175
Common utilities and helpers used across the service layer.
176
177
```java { .api }
178
/**
179
* Service context providing request context and user information
180
*/
181
public class ServiceContext {
182
183
/**
184
* Gets the current user ID
185
* @return user ID
186
*/
187
public long getUserId();
188
189
/**
190
* Sets the current user ID
191
* @param userId the user ID
192
*/
193
public void setUserId(long userId);
194
195
/**
196
* Gets the current company ID
197
* @return company ID
198
*/
199
public long getCompanyId();
200
201
/**
202
* Sets the current company ID
203
* @param companyId the company ID
204
*/
205
public void setCompanyId(long companyId);
206
207
/**
208
* Gets request attributes
209
* @return Map of request attributes
210
*/
211
public Map<String, Serializable> getAttributes();
212
213
/**
214
* Sets request attributes
215
* @param attributes Map of attributes to set
216
*/
217
public void setAttributes(Map<String, Serializable> attributes);
218
219
/**
220
* Gets workflow action if applicable
221
* @return workflow action constant
222
*/
223
public int getWorkflowAction();
224
225
/**
226
* Sets workflow action
227
* @param workflowAction the workflow action constant
228
*/
229
public void setWorkflowAction(int workflowAction);
230
}
231
232
/**
233
* Service locator for finding and accessing portal services
234
*/
235
public class ServiceLocator {
236
237
/**
238
* Locates local service by name
239
* @param serviceName the service name
240
* @return local service instance
241
* @throws ServiceException if service not found
242
*/
243
public static Object locateLocalService(String serviceName) throws ServiceException;
244
245
/**
246
* Locates remote service by name
247
* @param serviceName the service name
248
* @return remote service instance
249
* @throws ServiceException if service not found
250
*/
251
public static Object locateRemoteService(String serviceName) throws ServiceException;
252
253
/**
254
* Registers a service implementation
255
* @param serviceName the service name
256
* @param serviceImpl the service implementation
257
*/
258
public static void registerService(String serviceName, Object serviceImpl);
259
}
260
```
261
262
### Permission Checking
263
264
Security layer providing permission validation for service operations.
265
266
```java { .api }
267
/**
268
* Base permission checker for portal resources
269
*/
270
public abstract class BasePermissionChecker {
271
272
/**
273
* Checks if user has permission for the specified action on resource
274
* @param userId the user ID
275
* @param resourceName the resource name
276
* @param resourcePrimKey the resource primary key
277
* @param actionId the action ID
278
* @return true if user has permission
279
* @throws SystemException if permission check fails
280
*/
281
public abstract boolean hasPermission(long userId, String resourceName,
282
String resourcePrimKey, String actionId) throws SystemException;
283
284
/**
285
* Checks if user is owner of the resource
286
* @param userId the user ID
287
* @param resourceOwnerId the resource owner ID
288
* @return true if user is owner
289
*/
290
protected boolean isOwner(long userId, long resourceOwnerId);
291
292
/**
293
* Checks if user has administrative privileges
294
* @param userId the user ID
295
* @param companyId the company ID
296
* @return true if user is administrator
297
* @throws SystemException if check fails
298
*/
299
protected boolean isCompanyAdmin(long userId, long companyId) throws SystemException;
300
}
301
302
/**
303
* Resource permission checker for specific resource types
304
*/
305
public class ResourcePermissionChecker extends BasePermissionChecker {
306
307
/**
308
* Checks resource permissions with role-based access control
309
* @param userId the user ID
310
* @param resourceName the resource name
311
* @param resourcePrimKey the resource primary key
312
* @param actionId the action ID
313
* @return true if user has permission
314
* @throws SystemException if permission check fails
315
*/
316
@Override
317
public boolean hasPermission(long userId, String resourceName,
318
String resourcePrimKey, String actionId) throws SystemException;
319
320
/**
321
* Checks if user belongs to required role
322
* @param userId the user ID
323
* @param roleId the role ID
324
* @return true if user has role
325
*/
326
public boolean hasRole(long userId, long roleId);
327
328
/**
329
* Gets user's permissions for a resource
330
* @param userId the user ID
331
* @param resourceName the resource name
332
* @param resourcePrimKey the resource primary key
333
* @return List of action IDs user can perform
334
*/
335
public List<String> getResourceActions(long userId, String resourceName,
336
String resourcePrimKey);
337
}
338
339
/**
340
* Model permission checker for entity-specific permissions
341
*/
342
public class ModelPermissionChecker extends BasePermissionChecker {
343
344
/**
345
* Checks model-level permissions
346
* @param userId the user ID
347
* @param model the model instance
348
* @param actionId the action ID
349
* @return true if user has permission on model
350
* @throws SystemException if permission check fails
351
*/
352
public boolean hasModelPermission(long userId, Object model, String actionId)
353
throws SystemException;
354
355
/**
356
* Filters list of models based on user permissions
357
* @param userId the user ID
358
* @param models list of models to filter
359
* @param actionId the required action
360
* @return filtered list of models user can access
361
*/
362
public <T> List<T> filterByPermission(long userId, List<T> models, String actionId);
363
}
364
```
365
366
### Persistence Layer Constants
367
368
Constants used by the persistence layer for finder operations and queries.
369
370
```java { .api }
371
/**
372
* Constants for user group finder operations
373
*/
374
public class UserGroupFinderConstants {
375
376
/**
377
* Finder method name for finding user groups by organization
378
*/
379
public static final String FIND_BY_ORGANIZATION = "findByOrganization";
380
381
/**
382
* Finder method name for finding user groups by site
383
*/
384
public static final String FIND_BY_SITE = "findBySite";
385
386
/**
387
* Finder method name for finding user groups by user
388
*/
389
public static final String FIND_BY_USER = "findByUser";
390
391
/**
392
* Parameter name for organization ID
393
*/
394
public static final String PARAM_ORGANIZATION_ID = "organizationId";
395
396
/**
397
* Parameter name for site ID
398
*/
399
public static final String PARAM_SITE_ID = "siteId";
400
401
/**
402
* Parameter name for user ID
403
*/
404
public static final String PARAM_USER_ID = "userId";
405
}
406
```
407
408
## Usage Examples
409
410
**Service Implementation:**
411
412
```java
413
// Custom local service implementation
414
public class CustomLocalServiceImpl implements CustomLocalService {
415
416
@Override
417
public CustomEntity addCustomEntity(String name, String description,
418
ServiceContext serviceContext) throws SystemException, PortalException {
419
420
// Validate parameters
421
validateAddCustomEntity(name, description);
422
423
// Create entity
424
CustomEntity entity = new CustomEntity();
425
entity.setName(name);
426
entity.setDescription(description);
427
entity.setUserId(serviceContext.getUserId());
428
entity.setCompanyId(serviceContext.getCompanyId());
429
430
return customEntityPersistence.update(entity);
431
}
432
433
private void validateAddCustomEntity(String name, String description)
434
throws PortalException {
435
if (name == null || name.trim().isEmpty()) {
436
throw new CustomEntityNameException("Name is required");
437
}
438
if (description == null || description.trim().isEmpty()) {
439
throw new CustomEntityDescriptionException("Description is required");
440
}
441
}
442
}
443
```
444
445
**HTTP Service Endpoint:**
446
447
```java
448
// JSON web service endpoint
449
public class CustomJSONWebService extends JSONWebService {
450
451
@Override
452
protected void doGet(HttpServletRequest request, HttpServletResponse response)
453
throws ServletException, IOException {
454
455
String action = request.getParameter("action");
456
457
try {
458
if ("getCustomEntities".equals(action)) {
459
List<CustomEntity> entities = customLocalService.getCustomEntities();
460
String json = toJSON(entities);
461
writeResponse(response, json);
462
}
463
} catch (Exception e) {
464
writeErrorResponse(response, e.getMessage());
465
}
466
}
467
468
@Override
469
protected void doPost(HttpServletRequest request, HttpServletResponse response)
470
throws ServletException, IOException {
471
472
try {
473
String json = readRequestBody(request);
474
CustomEntity entity = fromJSON(json, CustomEntity.class);
475
476
ServiceContext serviceContext = createServiceContext(request);
477
CustomEntity result = customLocalService.addCustomEntity(
478
entity.getName(), entity.getDescription(), serviceContext);
479
480
writeResponse(response, toJSON(result));
481
} catch (Exception e) {
482
writeErrorResponse(response, e.getMessage());
483
}
484
}
485
}
486
```
487
488
**Permission Checking:**
489
490
```java
491
// Custom permission checker
492
public class CustomPermissionChecker extends BasePermissionChecker {
493
494
@Override
495
public boolean hasPermission(long userId, String resourceName,
496
String resourcePrimKey, String actionId) throws SystemException {
497
498
// Check basic permissions
499
if (isCompanyAdmin(userId, getCompanyId())) {
500
return true;
501
}
502
503
// Check resource-specific permissions
504
if ("CUSTOM_ENTITY".equals(resourceName)) {
505
return hasCustomEntityPermission(userId, resourcePrimKey, actionId);
506
}
507
508
return false;
509
}
510
511
private boolean hasCustomEntityPermission(long userId, String entityId,
512
String actionId) throws SystemException {
513
514
CustomEntity entity = customEntityPersistence.findByPrimaryKey(
515
Long.parseLong(entityId));
516
517
// Owner can perform all actions
518
if (isOwner(userId, entity.getUserId())) {
519
return true;
520
}
521
522
// Check role-based permissions
523
if ("VIEW".equals(actionId)) {
524
return hasRole(userId, RoleConstants.SITE_MEMBER);
525
} else if ("UPDATE".equals(actionId) || "DELETE".equals(actionId)) {
526
return hasRole(userId, RoleConstants.SITE_ADMINISTRATOR);
527
}
528
529
return false;
530
}
531
}
532
```
533
534
## Integration with Portal Framework
535
536
The service layer provides the foundation for all portal functionality:
537
538
- **Business Logic** - Core business rules and entity management
539
- **API Endpoints** - REST and SOAP web services for external integration
540
- **Security Integration** - Permission checking and access control
541
- **Transaction Management** - Database transaction coordination
542
- **Workflow Integration** - Business process and workflow support
543
- **Event Integration** - Service lifecycle events and notifications
544
- **Caching Support** - Performance optimization through caching
545
- **Multi-tenancy** - Company and site-specific service isolation
546
547
## Service Configuration
548
549
Services are typically configured through Spring configuration:
550
551
```xml
552
<!-- Local service configuration -->
553
<bean id="customLocalService"
554
class="com.company.service.impl.CustomLocalServiceImpl">
555
<property name="customEntityPersistence" ref="customEntityPersistence"/>
556
</bean>
557
558
<!-- Remote service configuration -->
559
<bean id="customRemoteService"
560
class="com.company.service.impl.CustomRemoteServiceImpl">
561
<property name="customLocalService" ref="customLocalService"/>
562
</bean>
563
564
<!-- HTTP service configuration -->
565
<bean id="customJSONWebService"
566
class="com.company.service.http.CustomJSONWebService">
567
<property name="customLocalService" ref="customLocalService"/>
568
</bean>
569
```
570
571
## Error Handling
572
573
Service layer error handling follows portal conventions:
574
575
- **SystemException** - System-level errors and database issues
576
- **PortalException** - Business logic validation errors
577
- **PrincipalException** - Security and permission errors
578
- **ServiceException** - Service location and configuration errors
579
- **ValidationException** - Input validation and constraint violations
580
581
Best practices include comprehensive input validation, proper exception handling, detailed error logging, and returning meaningful error messages to clients while maintaining security.