Skip to content

Commit

Permalink
refactor(sonarcloud): fix code smells (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
rbioteau authored Jul 2, 2020
1 parent c778cce commit 22945a5
Show file tree
Hide file tree
Showing 11 changed files with 393 additions and 107 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
<!-- Connector dependencies -->
<retrofit.version>2.9.0</retrofit.version>
<logging-interceptor.version>3.11.0</logging-interceptor.version>
<lombok.version>1.18.2</lombok.version>
<lombok.version>1.18.12</lombok.version>

<!-- Bonita -->
<bonita.engine.version>7.7.0</bonita.engine.version>
Expand Down
1 change: 0 additions & 1 deletion src/assembly/all-assembly.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>all</id>
<formats>
<!-- <format>dir</format>-->
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;

Expand All @@ -39,11 +40,11 @@ public class UIPathAddToQueueConnector extends UIPathConnector {
static final String QUEUE_NAME = "queueName";
static final String REFERENCE_INPUT = "reference";
static final String QUEUE_CONTENT = "queueContent";
private static final String PRIORITY_INPUT = "priority";
private static final String DUE_DATE_INPUT = "dueDate";
private static final String DEFER_DATE_INPUT = "deferDate";
private static final String ITEM_ID_OUTPUT = "itemId";
private static final String ITEM_KEY_OUTPUT = "itemKey";
static final String PRIORITY_INPUT = "priority";
static final String DUE_DATE_INPUT = "dueDate";
static final String DEFER_DATE_INPUT = "deferDate";
static final String ITEM_ID_OUTPUT = "itemId";
static final String ITEM_KEY_OUTPUT = "itemKey";

@Override
public void validateInputParameters() throws ConnectorValidationException {
Expand Down Expand Up @@ -86,9 +87,11 @@ protected void executeBusinessLogic() throws ConnectorException {
.setName(getQueueName())
.setPriority(getPriority());
getReference().ifPresent(itemData::setReference);
Optional<Map> content = getContent();
Optional<Map<Object, Object>> content = getContent();
if (content.isPresent()) {
Map<String, Object> contentMap = content.get();
Map<String, Object> contentMap = content.get().entrySet().stream().collect(Collectors.toMap(
entry -> entry.getKey().toString(),
Entry<Object, Object>::getValue));
itemData.setContent(contentMap.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
Expand Down Expand Up @@ -124,12 +127,12 @@ Optional<String> getReference() {
return Optional.ofNullable((String) getInputParameter(REFERENCE_INPUT));
}

Optional<Map> getContent() {
Optional<Map<Object,Object>> getContent() {
Object inputParameter = getInputParameter(QUEUE_CONTENT);
if (inputParameter instanceof List) {
return Optional.of(toMap(inputParameter));
}
return Optional.ofNullable((Map) getInputParameter(QUEUE_CONTENT));
return Optional.ofNullable((Map<Object,Object>) getInputParameter(QUEUE_CONTENT));
}

String getPriority() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public abstract class UIPathConnector extends AbstractConnector {

@Override
public void validateInputParameters() throws ConnectorValidationException {
checkcloudInput();
checkCloudInput();
if (isCloud()) {
checkMandatoryStringInput(ACCOUNT_LOGICAL_NAME);
checkMandatoryStringInput(TENANT_LOGICAL_NAME);
Expand All @@ -62,7 +62,7 @@ public void validateInputParameters() throws ConnectorValidationException {
}
}

protected void checkcloudInput() throws ConnectorValidationException {
protected void checkCloudInput() throws ConnectorValidationException {
Boolean value = null;
try {
value = (Boolean) getInputParameter(CLOUD);
Expand Down Expand Up @@ -153,7 +153,7 @@ protected UIPathService createService() {
Builder retrofitBuilder = new Retrofit.Builder()
.addConverterFactory(new WrappedAttributeConverter(mapper))
.addConverterFactory(JacksonConverterFactory.create())
.baseUrl(appendTraillingSlash(getUrl()));
.baseUrl(getUrl());

if (client != null) {
retrofitBuilder.client(client);
Expand Down Expand Up @@ -195,13 +195,14 @@ String getPassword() {
}

String getUrl() {
return isCloud()
? String.format("%s/%s/%s", CLOUD_ORCHESTRATOR_BASE_URL, getAccountLogicalName(), getTenantLogicalName())
: (String) getInputParameter(URL);
return appendTraillingSlash(isCloud()
? String.format("%s/%s/%s", CLOUD_ORCHESTRATOR_BASE_URL, getAccountLogicalName(),
getTenantLogicalName())
: (String) getInputParameter(URL));
}

Boolean isCloud() {
return (Boolean) getInputParameter(CLOUD);
boolean isCloud() {
return (boolean) getInputParameter(CLOUD);
}

String getAccountLogicalName() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,29 +102,29 @@ Optional<String> getStrategy() {
return Optional.ofNullable((String) getInputParameter(STRATEGY));
}

Optional<Map> getInputArguments() {
Optional<Map<Object, Object>> getInputArguments() {
Object inputParameter = getInputParameter(INPUT_ARGS);
if (inputParameter instanceof List) {
return Optional.of(toMap(inputParameter));
}
return Optional.ofNullable((Map) getInputParameter(INPUT_ARGS));
return Optional.ofNullable((Map<Object, Object>) getInputParameter(INPUT_ARGS));
}

void checkArgsInput() throws ConnectorValidationException {
Optional<Map> inputArguments = getInputArguments();
Optional<Map<Object, Object>> inputArguments = getInputArguments();
if (inputArguments.isPresent()) {
Map map = inputArguments.get();
Set nonStringKeys = (Set) map.keySet().stream().filter(key -> !(key instanceof String))
Map<Object, Object> map = inputArguments.get();
Set<?> nonStringKeys = map.keySet().stream().filter(key -> !(key instanceof String))
.collect(Collectors.toSet());
if (!nonStringKeys.isEmpty()) {
throw new ConnectorValidationException(
String.format("Only String keys are allowed in job input arguments. Found %s.", nonStringKeys));
}
Set nonSerializableValue = (Set) map.values().stream().filter(value -> {
Set<?> nonSerializableValue = map.values().stream().filter(value -> {
try {
mapper.writeValueAsString(value);
return false;
} catch (Throwable t) {
} catch (Exception e) {
return true;
}
}).collect(Collectors.toSet());
Expand All @@ -136,8 +136,8 @@ void checkArgsInput() throws ConnectorValidationException {
}
}

private Map<String, Object> handleInputArgs() {
return getInputArguments().orElse(new HashMap<String, Object>());
private Map<Object, Object> handleInputArgs() {
return getInputArguments().orElse(new HashMap<>());
}

List<Job> startJobs(String token, Release release, List<Integer> robotIds)
Expand Down Expand Up @@ -167,12 +167,10 @@ List<Job> startJobs(String token, Release release, List<Integer> robotIds)
throw new ConnectorException("Failed to start job.", e);
}
if (!response.isSuccessful()) {
LOGGER.error(response.toString());
try {
throw new ConnectorException(response.errorBody().string());
} catch (IOException e) {
throw new ConnectorException("Failed to read response body.", e);
if (LOGGER.isErrorEnabled()) {
LOGGER.error(response.toString());
}
throw new ConnectorException("Failed to start job: " + response.message());
}
return response.body();
}
Expand Down Expand Up @@ -224,11 +222,7 @@ List<Release> releases(String token) throws ConnectorException {
throw new ConnectorException("Failed to retrieve releases.", e);
}
if (!response.isSuccessful()) {
try {
throw new ConnectorException(response.errorBody().string());
} catch (IOException e) {
throw new ConnectorException("Failed to read response body.", e);
}
throw new ConnectorException("Failed to retrieve releases: " + response.message());
}
return response.body();
}
Expand All @@ -241,11 +235,7 @@ List<Robot> robots(String token) throws ConnectorException {
throw new ConnectorException("Failed to retrieve robots.", e);
}
if (!response.isSuccessful()) {
try {
throw new ConnectorException(response.errorBody().string());
} catch (IOException e) {
throw new ConnectorException("Failed to read response body.", e);
}
throw new ConnectorException("Failed to retrieve robots: " + response.message());
}
return response.body();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,20 @@
*/
package org.bonitasoft.engine.connector.uipath.model;

import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class CloudAuthentication {

private String grant_type;
private String client_id;
private String refresh_token;
@JsonProperty("grant_type")
private String grantType;
@JsonProperty("client_id")
private String clientId;
@JsonProperty("refresh_token")
private String refreshToken;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/**
* Copyright (C) 2020 Bonitasoft S.A.
* Bonitasoft, 32 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.engine.connector.uipath;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.spy;

import java.util.HashMap;
import java.util.Map;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;

class UIPathAddToQueueConnectorTest {

public static WireMockRule uiPathService;

@BeforeAll
public static void startMockServer() {
uiPathService = new WireMockRule(8888);
uiPathService.start();
}

@AfterAll
public static void stopMockServer() {
uiPathService.stop();
}

@BeforeEach
public void configureStubs() throws Exception {
uiPathService.stubFor(WireMock.post(WireMock.urlEqualTo("/api/account/authenticate"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBodyFile("mock.authenticate.response.json")));

uiPathService
.stubFor(WireMock.post(WireMock.urlEqualTo("/odata/Queues/UiPathODataSvc.AddQueueItem"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBodyFile("mock.addToQueue.response.json")));
}

private UIPathAddToQueueConnector createConnector() throws Exception {
UIPathAddToQueueConnector connector = spy(new UIPathAddToQueueConnector());
Map<String, Object> parameters = new HashMap<>();
parameters.put(UIPathConnector.CLOUD, false);
parameters.put(UIPathConnector.URL, "http://localhost:8888");
parameters.put(UIPathConnector.TENANT, "a_tenant");
parameters.put(UIPathConnector.USER, "admin");
parameters.put(UIPathConnector.PASSWORD, "somePassowrd");
parameters.put(UIPathAddToQueueConnector.QUEUE_NAME, "myQueue");
Map<String, Object> content = new HashMap<>();
content.put("hello", "world");
parameters.put(UIPathAddToQueueConnector.QUEUE_CONTENT, content);
connector.setInputParameters(parameters);
connector.validateInputParameters();
return connector;
}

@Test
void should_add_item_to_queue() throws Exception {
UIPathAddToQueueConnector connector = createConnector();

connector.connect();
Map<String, Object> outputs = connector.execute();

assertThat(outputs).containsEntry(UIPathAddToQueueConnector.ITEM_ID_OUTPUT, 39578029L)
.containsEntry(UIPathAddToQueueConnector.ITEM_KEY_OUTPUT,"ef306441-f7a6-4fad-ba8a-d09ec1237e2c");
}

}
Loading

0 comments on commit 22945a5

Please sign in to comment.