Update a user password via Developer Console
System.setPassword('USER_ID', 'NEW_PASSWORD');
$ ls ./snippets
Ready-to-copy Salesforce snippets for everyday work.
System.setPassword('USER_ID', 'NEW_PASSWORD');
A convenient way to group related code and collapse entire sections in IntelliJ IDEA and VS Code.
public with sharing class ExampleService {
//region Public Methods
public static void publicExampleOne() {
}
public static void publicExampleTwo() {
}
//endregion
//region Private Methods
private static void privateExampleOne() {
}
private static void privateExampleTwo() {
}
//endregion
}
Builds a map of active controlling picklist values to their allowed dependent values using Salesforce field dependency metadata.
public with sharing class DependentPicklistUtils {
private static final String BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
/**
* @description Builds a map of controlling picklist values to their allowed dependent values.
* Example: Map<String, List<String>> statusToSubstatus =
* DependentPicklistUtils.getValues(YourObject__c.Substatus__c);
* @param dependentField The dependent picklist field whose controlling-value map is required.
* @return A map where each controlling field value contains its allowed dependent field values.
*/
public static Map<String, List<String>> getValues(Schema.SObjectField dependentField) {
Schema.DescribeFieldResult dependentDescribe = dependentField.getDescribe();
Schema.SObjectField controllingField = dependentDescribe.getController();
if (controllingField == null) {
return new Map<String, List<String>>();
}
List<Schema.PicklistEntry> controllingValues = controllingField.getDescribe().getPicklistValues();
Map<String, List<String>> result = new Map<String, List<String>>();
for (Schema.PicklistEntry controllingValue : controllingValues) {
if (controllingValue.isActive()) {
result.put(controllingValue.getValue(), new List<String>());
}
}
for (Schema.PicklistEntry dependentValue : dependentDescribe.getPicklistValues()) {
if (!dependentValue.isActive()) {
continue;
}
Map<String, Object> serializedValue = (Map<String, Object>) JSON.deserializeUntyped(JSON.serialize(dependentValue));
String validFor = (String) serializedValue.get('validFor');
if (String.isBlank(validFor)) {
continue;
}
for (Integer index = 0; index < controllingValues.size(); index++) {
Schema.PicklistEntry controllingValue = controllingValues[index];
if (!controllingValue.isActive() || !isValidFor(validFor, index)) {
continue;
}
result.get(controllingValue.getValue()).add(dependentValue.getValue());
}
}
return result;
}
private static Boolean isValidFor(String validFor, Integer controllingIndex) {
Integer characterIndex = controllingIndex / 6;
if (characterIndex >= validFor.length()) {
return false;
}
Integer bitIndex = 5 - Math.mod(controllingIndex, 6);
Integer characterValue = BASE64_CHARS.indexOf(
validFor.substring(characterIndex, characterIndex + 1)
);
return (characterValue & (1 << bitIndex)) != 0;
}
}
@IsTest
private class DependentPicklistUtilsTest {
@IsTest
static void getValues_returnsDependentValuesGroupedByControllingValue() {
Test.startTest();
Map<String, List<String>> statusToSubstatus = DependentPicklistUtils.getValues(YourObject__c.Substatus__c);
Test.stopTest();
Assert.isFalse(statusToSubstatus.isEmpty());
Assert.isTrue(statusToSubstatus.containsKey('Example Status'));
Assert.isTrue(statusToSubstatus.get('Example Status').contains('Example Substatus'));
}
}
Generates a cryptographically random UUID and sets the required version 4 and RFC variant bits.
public with sharing class UuidUtils {
private static final String HEX_CHARS = '0123456789abcdef';
/**
* @description Generates a cryptographically random UUID with version 4 and RFC variant bits.
* Example: String uuid = UuidUtils.generateV4();
* @return A lowercase UUID v4 in xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx format.
*/
public static String generateV4() {
String randomHex = EncodingUtil.convertToHex(Crypto.generateAesKey(128)).toLowerCase();
Integer variantIndex = 8 + Math.mod(HEX_CHARS.indexOf(randomHex.substring(16, 17)), 4);
randomHex = randomHex.substring(0, 12) +
'4' +
randomHex.substring(13, 16) +
HEX_CHARS.substring(variantIndex, variantIndex + 1) +
randomHex.substring(17);
return randomHex.substring(0, 8) + '-' +
randomHex.substring(8, 12) + '-' +
randomHex.substring(12, 16) + '-' +
randomHex.substring(16, 20) + '-' +
randomHex.substring(20);
}
}
@IsTest
private class UuidUtilsTest {
@IsTest
static void generateV4_returnsUniqueUuidV4Values() {
Test.startTest();
String firstUuid = UuidUtils.generateV4();
String secondUuid = UuidUtils.generateV4();
Test.stopTest();
String uuidV4Pattern = '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$';
Assert.areNotEqual(firstUuid, secondUuid);
Assert.isTrue(Pattern.matches(uuidV4Pattern, firstUuid));
Assert.isTrue(Pattern.matches(uuidV4Pattern, secondUuid));
}
}
Creates reusable HTTP mocks with a configurable status code, response body, and headers for Apex integration tests.
@IsTest
public class HttpCalloutMockBuilder implements HttpCalloutMock {
private Integer statusCode = 200;
private String responseBody = '';
private Map<String, String> responseHeaders = new Map<String, String>();
/**
* @description Sets the HTTP status code returned by the mock.
* Example: new HttpCalloutMockBuilder().withStatusCode(201);
* @param value The response status code.
* @return The same builder instance.
*/
public HttpCalloutMockBuilder withStatusCode(Integer value) {
statusCode = value;
return this;
}
/**
* @description Sets the response body returned by the mock.
* @param value The response body.
* @return The same builder instance.
*/
public HttpCalloutMockBuilder withBody(String value) {
responseBody = value;
return this;
}
/**
* @description Adds or replaces a response header.
* @param name The header name.
* @param value The header value.
* @return The same builder instance.
*/
public HttpCalloutMockBuilder withHeader(String name, String value) {
responseHeaders.put(name, value);
return this;
}
public HttpResponse respond(HttpRequest request) {
HttpResponse response = new HttpResponse();
response.setStatusCode(statusCode);
response.setBody(responseBody);
for (String headerName : responseHeaders.keySet()) {
response.setHeader(headerName, responseHeaders.get(headerName));
}
return response;
}
}
@IsTest
private class HttpCalloutMockBuilderTest {
@IsTest
static void builder_returnsConfiguredResponse() {
HttpCalloutMock mock = new HttpCalloutMockBuilder()
.withStatusCode(201)
.withBody('{"success":true}')
.withHeader('Content-Type', 'application/json');
Test.setMock(HttpCalloutMock.class, mock);
HttpRequest request = new HttpRequest();
request.setEndpoint('https://example.com/api');
request.setMethod('POST');
Test.startTest();
HttpResponse response = new Http().send(request);
Test.stopTest();
Assert.areEqual(201, response.getStatusCode());
Assert.areEqual('{"success":true}', response.getBody());
Assert.areEqual('application/json', response.getHeader('Content-Type'));
}
}
Generates a cryptographically random lowercase hex token with a configurable length from 1 to 64 characters.
public with sharing class SecureTokenUtils {
public class InvalidTokenLengthException extends Exception {
}
/**
* @description Generates a cryptographically random lowercase hex token.
* Example: String token = SecureTokenUtils.generate(32);
* @param length The required token length from 1 to 64 characters.
* @return A random lowercase hex token with the requested length.
*/
public static String generate(Integer length) {
if (length == null || length < 1 || length > 64) {
throw new InvalidTokenLengthException('Token length must be between 1 and 64 characters.');
}
String randomHex = EncodingUtil.convertToHex(Crypto.generateAesKey(256)).toLowerCase();
return randomHex.substring(0, length);
}
}
@IsTest
private class SecureTokenUtilsTest {
@IsTest
static void generate_returnsUniqueTokenWithRequestedLength() {
Test.startTest();
String firstToken = SecureTokenUtils.generate(32);
String secondToken = SecureTokenUtils.generate(32);
Test.stopTest();
Assert.areEqual(32, firstToken.length());
Assert.isTrue(Pattern.matches('^[0-9a-f]{32}$', firstToken));
Assert.areNotEqual(firstToken, secondToken);
}
@IsTest
static void generate_throwsExceptionForInvalidLength() {
try {
SecureTokenUtils.generate(65);
Assert.fail('Expected InvalidTokenLengthException.');
} catch (SecureTokenUtils.InvalidTokenLengthException exceptionValue) {
Assert.isTrue(exceptionValue.getMessage().contains('between 1 and 64'));
}
}
}
No snippets match your filter.