Skip to content

Async action changes #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -3,175 +3,71 @@
* SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06
*/

package com.liferay.clarity;

import com.liferay.petra.string.StringBundler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONObject;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Mono;

/**
* @author Raymond Augé
* @author Gregory Amerson
* @author Brian Wing Shun Chan
*/
@RequestMapping("/object/action/account")
@RestController
public class ObjectActionAccountRestController extends BaseRestController {

@PostMapping
public ResponseEntity<String> post(
@AuthenticationPrincipal Jwt jwt, @RequestBody String json)
throws Exception {

log(jwt, _log, json);

JSONObject jsonObject = new JSONObject(json);

JSONObject objectEntryDTODistributorApplicationJSONObject =
jsonObject.getJSONObject("objectEntryDTODistributorApplication");

JSONObject propertiesJSONObject =
objectEntryDTODistributorApplicationJSONObject.getJSONObject(
"properties");

String accountEmailAddress = propertiesJSONObject.getString(
"applicantEmailAddress");

String accountName = propertiesJSONObject.getString("businessName");

String accountExternalReferenceCode = "ACCOUNT_".concat(
accountName.toUpperCase(
).replace(
' ', '_'
));

WebClient.Builder builder = WebClient.builder();

WebClient webClient = builder.baseUrl(
lxcDXPServerProtocol + "://" + lxcDXPMainDomain
).defaultHeader(
HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE
).defaultHeader(
HttpHeaders.AUTHORIZATION, "Bearer " + jwt.getTokenValue()
).defaultHeader(
HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE
).build();

webClient.post(
).uri(
"o/headless-admin-user/v1.0/accounts"
).bodyValue(
StringBundler.concat(
"{\"externalReferenceCode\": \"", accountExternalReferenceCode,
"\", \"name\": \"", accountName, "\", \"type\": \"business\"}")
).retrieve(
).toEntity(
String.class
).flatMap(
responseEntity -> _transform(responseEntity)
).doOnSuccess(
responseEntity -> _log(
"Created account: " + responseEntity.getBody())
).then(
webClient.post(
).uri(
StringBundler.concat(
"o/headless-admin-user/v1.0/accounts",
"/by-external-reference-code/",
accountExternalReferenceCode,
"/user-accounts/by-email-address/", accountEmailAddress)
).retrieve(
).toEntity(
String.class
).flatMap(
responseEntity -> _transform(responseEntity)
)
).doOnSuccess(
responseEntity -> _log("Assigned user: " + responseEntity.getBody())
).then(
webClient.get(
).uri(
uriBuilder -> uriBuilder.path(
StringBundler.concat(
"o/headless-admin-user/v1.0/accounts",
"/by-external-reference-code/",
accountExternalReferenceCode, "/account-roles")
).queryParam(
"filter", "name eq 'Account Administrator'"
).build()
).retrieve(
).bodyToMono(
String.class
).map(
pageJSON -> new JSONObject(
pageJSON
).getJSONArray(
"items"
).getJSONObject(
0
).getInt(
"id"
)
)
).flatMap(
accountRoleId -> webClient.post(
).uri(
StringBundler.concat(
"o/headless-admin-user/v1.0/accounts",
"/by-external-reference-code/",
accountExternalReferenceCode, "/account-roles/",
accountRoleId, "/user-accounts/by-email-address/",
accountEmailAddress)
).retrieve(
).toEntity(
String.class
).flatMap(
responseEntity -> _transform(responseEntity)
).doOnSuccess(
responseEntity -> _log(
"Assigned role: " + responseEntity.getBody())
)
).subscribe();

return new ResponseEntity<>(json, HttpStatus.OK);
}

private void _log(String message) {
if (_log.isInfoEnabled()) {
_log.info(message);
}
}

private Mono<ResponseEntity<String>> _transform(
ResponseEntity<String> responseEntity) {

HttpStatus httpStatus = responseEntity.getStatusCode();

if (httpStatus.is2xxSuccessful()) {
return Mono.just(responseEntity);
}

return Mono.error(new RuntimeException(httpStatus.getReasonPhrase()));
}

private static final Log _log = LogFactory.getLog(
ObjectActionAccountRestController.class);

}
package com.liferay.clarity;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Invoked when a new user account has been created.
*
* @author Raymond Augé
* @author Gregory Amerson
* @author Brian Wing Shun Chan
* @author dnebing
*/
@RequestMapping("/object/action/account")
@RestController
public class ObjectActionAccountRestController extends BaseRestController {

@Autowired
public ObjectActionAccountRestController(
UserCreatedRequestQueueManager queueManager) {

_queueManager = queueManager;
}

/**
* Invoked when a new user account has been created.
*
* @param jwt the JWT token
* @param json the user creation request in JSON format
* @return the response entity
* @throws Exception if an error occurs
*/
@PostMapping
public ResponseEntity<String> post(
@AuthenticationPrincipal Jwt jwt, @RequestBody String json)
throws Exception {

log(jwt, _log, json);

// Create the request instance

UserCreatedRequest request = new UserCreatedRequest(json, jwt);

// Enqueue the request

_queueManager.enqueue(request);

// Return a success response

return new ResponseEntity<>(json, HttpStatus.OK);
}

private static final Log _log = LogFactory.getLog(
ObjectActionAccountRestController.class);

private final UserCreatedRequestQueueManager _queueManager;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.liferay.clarity;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
* Creates the task executor which will be processing the user creation requests.
*
* @author dnebing
*/
@Configuration
public class TaskExecutorConfig {

@Bean
public TaskExecutor taskExecutor() {

// create a thread pool for the task executor

ThreadPoolTaskExecutor threadPoolTaskExecutor =
new ThreadPoolTaskExecutor();

// initialize to some reasonable values

threadPoolTaskExecutor.setCorePoolSize(0);
threadPoolTaskExecutor.setMaxPoolSize(10);
threadPoolTaskExecutor.setQueueCapacity(100);
threadPoolTaskExecutor.setThreadNamePrefix("CreateUserTaskExecutor-");

// initialize the task executor

threadPoolTaskExecutor.initialize();

// return the task executor

return threadPoolTaskExecutor;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.liferay.clarity;

import org.springframework.security.oauth2.jwt.Jwt;

/**
* Represents a user creation request.
*
* @author dnebing
*/
public class UserCreatedRequest {

public UserCreatedRequest(String userJSON, Jwt jwt) {
_userJSON = userJSON;
_jwt = jwt;
}

public Jwt getJwt() {
return _jwt;
}

public String getUserJSON() {
return _userJSON;
}

private final Jwt _jwt;
private final String _userJSON;

}
Loading