or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

bean-management.mddatabase-orm.mddatabase-upgrades.mdframework-integration.mdindex.mdlifecycle-events.mdportlet-framework.mdservice-layer.mdtemplate-processing.mdutility-services.mdweb-security.md

utility-services.mddocs/

0

# Utility Services

1

2

Core utilities including formatting, minification, file operations, XML processing, and portal-specific utility implementations providing essential support services for the Liferay portal framework.

3

4

## Capabilities

5

6

### Core Portal Utilities

7

8

Essential utility implementations for portal configuration, file operations, localization, and layout management.

9

10

```java { .api }

11

/**

12

* Portal utility class providing common portal operations

13

*/

14

public class PortalUtil {

15

16

/**

17

* Gets portal URL for the current request

18

* @param request HTTP servlet request

19

* @return portal URL string

20

*/

21

public static String getPortalURL(HttpServletRequest request);

22

23

/**

24

* Gets current user from request

25

* @param request HTTP servlet request

26

* @return User object or null if not found

27

*/

28

public static User getUser(HttpServletRequest request);

29

30

/**

31

* Gets company ID from request

32

* @param request HTTP servlet request

33

* @return company ID

34

*/

35

public static long getCompanyId(HttpServletRequest request);

36

37

/**

38

* Escapes HTML content for safe output

39

* @param content content to escape

40

* @return HTML-escaped content

41

*/

42

public static String escapeHTML(String content);

43

44

/**

45

* Unescapes HTML entities

46

* @param content HTML content to unescape

47

* @return unescaped content

48

*/

49

public static String unescapeHTML(String content);

50

}

51

52

/**

53

* File utility class for file operations

54

*/

55

public class FileUtil {

56

57

/**

58

* Reads file content as string

59

* @param file file to read

60

* @return file content as string

61

* @throws IOException if file cannot be read

62

*/

63

public static String read(File file) throws IOException;

64

65

/**

66

* Writes string content to file

67

* @param file target file

68

* @param content content to write

69

* @throws IOException if file cannot be written

70

*/

71

public static void write(File file, String content) throws IOException;

72

73

/**

74

* Copies file from source to destination

75

* @param source source file

76

* @param destination destination file

77

* @throws IOException if copy fails

78

*/

79

public static void copy(File source, File destination) throws IOException;

80

81

/**

82

* Gets file extension

83

* @param fileName file name

84

* @return file extension or empty string

85

*/

86

public static String getExtension(String fileName);

87

88

/**

89

* Creates directories if they don't exist

90

* @param directory directory to create

91

* @return true if directory exists or was created

92

*/

93

public static boolean mkdirs(File directory);

94

}

95

```

96

97

### Text and Content Formatting

98

99

Text and content formatting utilities for various data types and output formats.

100

101

```java { .api }

102

/**

103

* Format utility class for text and content formatting

104

*/

105

public class FormatUtil {

106

107

/**

108

* Formats date using specified pattern

109

* @param date date to format

110

* @param pattern date format pattern

111

* @param locale locale for formatting

112

* @return formatted date string

113

*/

114

public static String formatDate(Date date, String pattern, Locale locale);

115

116

/**

117

* Formats number using locale-specific formatting

118

* @param number number to format

119

* @param locale locale for formatting

120

* @return formatted number string

121

*/

122

public static String formatNumber(Number number, Locale locale);

123

124

/**

125

* Formats currency amount

126

* @param amount currency amount

127

* @param currencyCode currency code (USD, EUR, etc.)

128

* @param locale locale for formatting

129

* @return formatted currency string

130

*/

131

public static String formatCurrency(double amount, String currencyCode, Locale locale);

132

133

/**

134

* Formats file size in human-readable format

135

* @param sizeInBytes file size in bytes

136

* @return formatted size string (KB, MB, GB)

137

*/

138

public static String formatFileSize(long sizeInBytes);

139

140

/**

141

* Truncates text to specified length with ellipsis

142

* @param text text to truncate

143

* @param maxLength maximum length

144

* @return truncated text with ellipsis if needed

145

*/

146

public static String truncate(String text, int maxLength);

147

}

148

```

149

150

### CSS and JavaScript Minification

151

152

Asset minification services for optimizing CSS and JavaScript resources.

153

154

```java { .api }

155

/**

156

* CSS minification service

157

*/

158

public class CSSMinifier {

159

160

/**

161

* Minifies CSS content by removing whitespace and comments

162

* @param css CSS content to minify

163

* @return minified CSS content

164

*/

165

public static String minify(String css);

166

167

/**

168

* Minifies CSS file and saves to output file

169

* @param inputFile input CSS file

170

* @param outputFile output minified CSS file

171

* @throws IOException if file operations fail

172

*/

173

public static void minifyFile(File inputFile, File outputFile) throws IOException;

174

175

/**

176

* Compresses CSS with advanced optimizations

177

* @param css CSS content to compress

178

* @param aggressive true for aggressive compression

179

* @return compressed CSS content

180

*/

181

public static String compress(String css, boolean aggressive);

182

}

183

184

/**

185

* JavaScript minification service

186

*/

187

public class JavaScriptMinifier {

188

189

/**

190

* Minifies JavaScript content

191

* @param javascript JavaScript content to minify

192

* @return minified JavaScript content

193

*/

194

public static String minify(String javascript);

195

196

/**

197

* Minifies JavaScript file and saves to output file

198

* @param inputFile input JavaScript file

199

* @param outputFile output minified JavaScript file

200

* @throws IOException if file operations fail

201

*/

202

public static void minifyFile(File inputFile, File outputFile) throws IOException;

203

204

/**

205

* Obfuscates JavaScript code

206

* @param javascript JavaScript content to obfuscate

207

* @return obfuscated JavaScript content

208

*/

209

public static String obfuscate(String javascript);

210

}

211

```

212

213

### File Upload Processing

214

215

File upload processing utilities for handling multipart form data and file uploads.

216

217

```java { .api }

218

/**

219

* File upload utility for processing multipart requests

220

*/

221

public class UploadUtil {

222

223

/**

224

* Processes multipart request and extracts uploaded files

225

* @param request HTTP servlet request with multipart data

226

* @return Map of parameter names to uploaded files

227

* @throws IOException if upload processing fails

228

*/

229

public static Map<String, FileItem> processUpload(HttpServletRequest request)

230

throws IOException;

231

232

/**

233

* Gets uploaded file from request parameter

234

* @param request HTTP servlet request

235

* @param parameterName form parameter name

236

* @return FileItem representing uploaded file

237

*/

238

public static FileItem getFileItem(HttpServletRequest request, String parameterName);

239

240

/**

241

* Validates uploaded file against security constraints

242

* @param fileItem uploaded file item

243

* @param allowedExtensions allowed file extensions

244

* @param maxSizeInBytes maximum file size

245

* @return true if file passes validation

246

*/

247

public static boolean validateUpload(FileItem fileItem, String[] allowedExtensions,

248

long maxSizeInBytes);

249

250

/**

251

* Saves uploaded file to specified directory

252

* @param fileItem uploaded file item

253

* @param destinationDir destination directory

254

* @return saved file instance

255

* @throws IOException if save operation fails

256

*/

257

public static File saveUploadedFile(FileItem fileItem, File destinationDir)

258

throws IOException;

259

}

260

261

/**

262

* File item representing an uploaded file

263

*/

264

public interface FileItem {

265

266

/**

267

* Gets original filename as uploaded by client

268

* @return original filename

269

*/

270

String getFileName();

271

272

/**

273

* Gets content type of uploaded file

274

* @return MIME content type

275

*/

276

String getContentType();

277

278

/**

279

* Gets size of uploaded file in bytes

280

* @return file size in bytes

281

*/

282

long getSize();

283

284

/**

285

* Gets uploaded file content as byte array

286

* @return file content bytes

287

*/

288

byte[] getBytes();

289

290

/**

291

* Gets input stream for reading file content

292

* @return InputStream for file content

293

* @throws IOException if stream cannot be created

294

*/

295

InputStream getInputStream() throws IOException;

296

}

297

```

298

299

### XML Processing and Manipulation

300

301

XML processing and manipulation utilities for working with XML documents and data.

302

303

```java { .api }

304

/**

305

* XML utility class for XML processing operations

306

*/

307

public class XMLUtil {

308

309

/**

310

* Parses XML string into Document object

311

* @param xmlContent XML content as string

312

* @return parsed Document object

313

* @throws XMLException if parsing fails

314

*/

315

public static Document parseXML(String xmlContent) throws XMLException;

316

317

/**

318

* Converts Document object to XML string

319

* @param document XML document

320

* @return XML content as string

321

*/

322

public static String documentToString(Document document);

323

324

/**

325

* Evaluates XPath expression against XML document

326

* @param document XML document

327

* @param xpathExpression XPath expression

328

* @return evaluation result

329

* @throws XPathException if evaluation fails

330

*/

331

public static Object evaluateXPath(Document document, String xpathExpression)

332

throws XPathException;

333

334

/**

335

* Transforms XML using XSLT stylesheet

336

* @param xmlDocument source XML document

337

* @param xsltStylesheet XSLT stylesheet

338

* @return transformed XML result

339

* @throws TransformationException if transformation fails

340

*/

341

public static String transform(Document xmlDocument, String xsltStylesheet)

342

throws TransformationException;

343

344

/**

345

* Validates XML against XSD schema

346

* @param xmlContent XML content to validate

347

* @param xsdSchema XSD schema for validation

348

* @return true if XML is valid

349

* @throws ValidationException if validation process fails

350

*/

351

public static boolean validateXML(String xmlContent, String xsdSchema)

352

throws ValidationException;

353

}

354

355

/**

356

* XML configuration reader for portal configuration files

357

*/

358

public class XMLConfigurationReader {

359

360

/**

361

* Reads configuration from XML file

362

* @param configFile XML configuration file

363

* @return Configuration object

364

* @throws ConfigurationException if reading fails

365

*/

366

public static Configuration readConfiguration(File configFile)

367

throws ConfigurationException;

368

369

/**

370

* Gets configuration property value

371

* @param configuration configuration object

372

* @param propertyPath dot-separated property path

373

* @return property value or null if not found

374

*/

375

public static String getProperty(Configuration configuration, String propertyPath);

376

377

/**

378

* Gets configuration property as list

379

* @param configuration configuration object

380

* @param propertyPath dot-separated property path

381

* @return list of property values

382

*/

383

public static List<String> getPropertyList(Configuration configuration, String propertyPath);

384

}

385

```

386

387

## Usage Examples

388

389

**Portal Utilities:**

390

391

```java

392

// Get portal information from request

393

String portalURL = PortalUtil.getPortalURL(request);

394

User currentUser = PortalUtil.getUser(request);

395

long companyId = PortalUtil.getCompanyId(request);

396

397

// HTML escaping for safe output

398

String userInput = request.getParameter("comment");

399

String safeOutput = PortalUtil.escapeHTML(userInput);

400

```

401

402

**File Operations:**

403

404

```java

405

// File reading and writing

406

File configFile = new File("/path/to/config.properties");

407

String content = FileUtil.read(configFile);

408

409

// Modify content

410

String updatedContent = content.replace("old.value", "new.value");

411

FileUtil.write(configFile, updatedContent);

412

413

// File copying

414

File source = new File("/source/file.txt");

415

File destination = new File("/destination/file.txt");

416

FileUtil.copy(source, destination);

417

```

418

419

**Text Formatting:**

420

421

```java

422

// Date formatting

423

Date now = new Date();

424

String formattedDate = FormatUtil.formatDate(now, "yyyy-MM-dd HH:mm:ss", Locale.US);

425

426

// Number formatting

427

double amount = 1234.56;

428

String formattedAmount = FormatUtil.formatCurrency(amount, "USD", Locale.US);

429

430

// File size formatting

431

long fileSize = 1024 * 1024 * 5; // 5 MB

432

String readableSize = FormatUtil.formatFileSize(fileSize); // "5.0 MB"

433

```

434

435

**Asset Minification:**

436

437

```java

438

// CSS minification

439

String cssContent = FileUtil.read(new File("styles.css"));

440

String minifiedCSS = CSSMinifier.minify(cssContent);

441

FileUtil.write(new File("styles.min.css"), minifiedCSS);

442

443

// JavaScript minification

444

String jsContent = FileUtil.read(new File("script.js"));

445

String minifiedJS = JavaScriptMinifier.minify(jsContent);

446

FileUtil.write(new File("script.min.js"), minifiedJS);

447

```

448

449

**File Upload Processing:**

450

451

```java

452

// Process multipart upload

453

Map<String, FileItem> uploads = UploadUtil.processUpload(request);

454

FileItem uploadedFile = uploads.get("fileUpload");

455

456

if (uploadedFile != null) {

457

// Validate upload

458

String[] allowedTypes = {".jpg", ".png", ".gif"};

459

boolean isValid = UploadUtil.validateUpload(uploadedFile, allowedTypes, 1024 * 1024); // 1MB max

460

461

if (isValid) {

462

// Save file

463

File uploadDir = new File("/uploads");

464

File savedFile = UploadUtil.saveUploadedFile(uploadedFile, uploadDir);

465

}

466

}

467

```

468

469

**XML Processing:**

470

471

```java

472

// Parse XML

473

String xmlContent = "<config><setting name='timeout'>30</setting></config>";

474

Document doc = XMLUtil.parseXML(xmlContent);

475

476

// XPath evaluation

477

String timeout = (String) XMLUtil.evaluateXPath(doc, "//setting[@name='timeout']/text()");

478

479

// XML transformation

480

String xsltStylesheet = "..."; // XSLT content

481

String transformedXML = XMLUtil.transform(doc, xsltStylesheet);

482

```

483

484

## Integration with Portal Framework

485

486

Utility services provide foundational support for:

487

488

- **Content Management** - File operations and XML processing

489

- **Asset Optimization** - CSS/JS minification for performance

490

- **User Interface** - Text formatting and HTML escaping

491

- **File Management** - Upload processing and validation

492

- **Configuration** - XML configuration reading and processing

493

- **Internationalization** - Locale-aware formatting utilities

494

495

## Error Handling

496

497

Common utility exceptions:

498

499

- **IOException** - File operation failures

500

- **XMLException** - XML parsing and processing errors

501

- **ConfigurationException** - Configuration reading failures

502

- **ValidationException** - Input validation errors

503

- **TransformationException** - XSLT transformation failures

504

505

Best practices include proper exception handling, input validation, resource cleanup, and comprehensive logging for debugging and monitoring utility operations.