Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
GtanSndil committed Feb 15, 2024
1 parent e50fddf commit 3c218e1
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public ResponseEntity<String> filteredSearchTextByType(
description = "type à selectionner",
required = true) @RequestParam DDIItemType ddiItemType
) {
return colecticaService.SearchTexteByType(index, texte, ddiItemType );
return colecticaService.searchTexteByType(index, texte, ddiItemType );
}

@GetMapping("/filtered-search/type/")
Expand All @@ -108,7 +108,7 @@ public ResponseEntity<String> searchByType(
@Parameter(
description = "type à selectionner",
required = true) @RequestParam DDIItemType ddiItemType) {
return colecticaService.SearchByType(index, ddiItemType);
return colecticaService.searchByType(index, ddiItemType);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ public ResponseEntity<?> transformFileForComplexCodeList(@RequestParam("file") M
@Operation(summary = "Send an update to Colectica Repository via Colectica API ",
description = "Send a json make with /replace-xml-parameters/{Type}/{Label}/{Version}/{Name}/{VersionResponsibility} COPYCOMMIT is for Upload a new object not for update")
public ResponseEntity<String> sendUpdateColectica(
@RequestBody String DdiUpdatingInJson,
@RequestBody String ddiUpdatingInJson,
@RequestParam("transactionType") TransactionType transactionType
) throws IOException {
return colecticaService.sendUpdateColectica(DdiUpdatingInJson, transactionType);
return colecticaService.sendUpdateColectica(ddiUpdatingInJson, transactionType);

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@ public interface ColecticaService {

ResponseEntity<String> filteredSearchText(String index, String texte);

ResponseEntity<String> SearchTexteByType(String index, String texte, DDIItemType type);
ResponseEntity<String> SearchByType(String index, DDIItemType type);
ResponseEntity<String> searchTexteByType(String index, String texte, DDIItemType type);
ResponseEntity<String> searchByType(String index, DDIItemType type);
ResponseEntity<List<Map<String,String>>> getJsonWithChild(String identifier, String outputField, String fieldLabelName) throws Exception;

String convertXmlToJson(String uuid) throws ExceptionColecticaUnreachable, JsonProcessingException;
String replaceXmlParameters(String inputXml, DDIItemType type, String label, int version, String name, String idepUtilisateur);

ResponseEntity<?> getByType(DDIItemType type) throws IOException, ExceptionColecticaUnreachable;

ResponseEntity<String> sendUpdateColectica(String DdiUpdatingInJson, TransactionType transactionType) throws IOException;
ResponseEntity<String> sendUpdateColectica(String ddiUpdatingInJson, TransactionType transactionType) throws IOException;

ResponseEntity<?> transformFile(
MultipartFile file,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,18 @@
@Service
public class ColecticaServiceImpl implements ColecticaService {

private final static String CONTENT_TYPE = "Content-Type";
private final static String APPLICATION_XML = "application/xml";
private final static String APPLICATION_JSON = "application/json";
private final static String AUTHORIZATION = "Authorization";
private final static String BEARER = "Bearer ";
private final static String HTTP = "http://";
private final static String VERSION = "version";
private final static String SEARCH = "/_search";
private final static String BASIC = "Basic ";
private final static String ERREUR_COLECTICA = "Une erreur s'est produite lors de la requête vers Colectica.";
private final static String ERREUR_ELASTICSEARCH = "Une erreur s'est produite lors de la requête Elasticsearch.";
private final static String TRANSACTIONID = "{\"TransactionId\":";
private static final String CONTENT_TYPE = "Content-Type";
private static final String APPLICATION_XML = "application/xml";
private static final String APPLICATION_JSON = "application/json";
private static final String AUTHORIZATION = "Authorization";
private static final String BEARER = "Bearer ";
private static final String HTTP = "http://";
private static final String VERSION = "version";
private static final String SEARCH = "/_search";
private static final String BASIC = "Basic ";
private static final String ERREUR_COLECTICA = "Une erreur s'est produite lors de la requête vers Colectica.";
private static final String ERREUR_ELASTICSEARCH = "Une erreur s'est produite lors de la requête Elasticsearch.";
private static final String TRANSACTIONID = "{\"TransactionId\":";



Expand Down Expand Up @@ -167,9 +167,7 @@ private ResponseEntity<String> searchColecticaFragmentByUuid(String uuid) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ERREUR_COLECTICA);
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ExceptionColecticaUnreachable e) {
} catch (IOException|ExceptionColecticaUnreachable e) {
throw new RuntimeException(e);
}
}
Expand Down Expand Up @@ -212,9 +210,7 @@ private ResponseEntity<String> searchColecticaInstanceByUuid(String uuid) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ERREUR_COLECTICA);
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ExceptionColecticaUnreachable e) {
} catch (IOException|ExceptionColecticaUnreachable e) {
throw new RuntimeException(e);
}
}
Expand All @@ -232,7 +228,7 @@ public ResponseEntity<String> filteredSearchText(String index, String texte) {
}

@Override
public ResponseEntity<String> SearchByType(String index, DDIItemType type) {
public ResponseEntity<String> searchByType(String index, DDIItemType type) {
ResponseEntity<String> responseEntity = searchType(index, String.valueOf(type.getUUID()).toLowerCase());
if (responseEntity.getStatusCode().is2xxSuccessful()) {
String responseBody = (String) responseEntity.getBody();
Expand All @@ -244,10 +240,10 @@ public ResponseEntity<String> SearchByType(String index, DDIItemType type) {
}

@Override
public ResponseEntity<String> SearchTexteByType(String index,String texte, DDIItemType type) {
public ResponseEntity<String> searchTexteByType(String index, String texte, DDIItemType type) {
ResponseEntity<String> responseEntity = searchTextByType(index, texte, String.valueOf(type.getUUID()).toLowerCase());
if (responseEntity.getStatusCode().is2xxSuccessful()) {
String responseBody = (String) responseEntity.getBody();
String responseBody = (String) responseEntity.getBody();
String filteredResponse = filterAndTransformResponse(responseBody);
return ResponseEntity.ok(filteredResponse);
} else {
Expand All @@ -269,8 +265,8 @@ private ResponseEntity<String> searchType(String index,String type) {
}
else {
httpPost = new HttpPost(HTTP + elasticHost + ":" + elasticHostPort + "/" + index + SEARCH);
String token = Base64.getEncoder().encodeToString((apiId + ":" + apiKey).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(AUTHORIZATION, BASIC + token);
String tokenElastic = Base64.getEncoder().encodeToString((apiId + ":" + apiKey).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(AUTHORIZATION, BASIC + tokenElastic);

Check failure

Code scanning / SonarCloud

Basic authentication should not be used High

Use a more secure method than basic authentication. See more on SonarCloud
httpPost.setHeader(CONTENT_TYPE, APPLICATION_JSON);
httpPost.setEntity(entity);
}
Expand All @@ -297,8 +293,8 @@ private ResponseEntity<String> searchText(String index, String texte) {
httpGet = new HttpGet("https://" + elasticHost + ":" + elasticHostPort + "/" + index + "/_search?q=" + encodedTexte);
} else {
httpGet = new HttpGet(HTTP + elasticHost + ":" + elasticHostPort + "/" + index + "/_search?q=*" + encodedTexte + "*");
String token = Base64.getEncoder().encodeToString((apiId + ":" + apiKey).getBytes(StandardCharsets.UTF_8));
httpGet.addHeader(AUTHORIZATION, BASIC + token);
String tokenElastic = Base64.getEncoder().encodeToString((apiId + ":" + apiKey).getBytes(StandardCharsets.UTF_8));
httpGet.addHeader(AUTHORIZATION, BASIC + tokenElastic);

Check failure

Code scanning / SonarCloud

Basic authentication should not be used High

Use a more secure method than basic authentication. See more on SonarCloud
}

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
Expand All @@ -317,8 +313,8 @@ private ResponseEntity<String> searchTextByType(String index, String texte, Stri

// Ajouter l'en-tête pour l'authentification et le type de contenu si nécessaire
if (!elasticHost.contains("kube")) {
String token = Base64.getEncoder().encodeToString((apiId + ":" + apiKey).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(AUTHORIZATION, BASIC + token);
String tokenElastic = Base64.getEncoder().encodeToString((apiId + ":" + apiKey).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(AUTHORIZATION, BASIC + tokenElastic);

Check failure

Code scanning / SonarCloud

Basic authentication should not be used High

Use a more secure method than basic authentication. See more on SonarCloud
httpPost.setHeader(CONTENT_TYPE, APPLICATION_JSON);
}

Expand Down Expand Up @@ -423,9 +419,7 @@ public ResponseEntity<List<Map<String,String>>> getJsonWithChild(String identifi
} else {
return ResponseEntity.status(response.getStatusCode()).body(null);
}
} catch (HttpClientErrorException e) {
return ResponseEntity.status(e.getStatusCode()).body(null);
} catch (HttpServerErrorException e) {
} catch (HttpClientErrorException|HttpServerErrorException e) {
return ResponseEntity.status(e.getStatusCode()).body(null);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
Expand Down Expand Up @@ -524,8 +518,7 @@ public String replaceXmlParameters(@RequestBody String inputXml,
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document2), new StreamResult(writer));
InputStream xsltStream2 = getClass().getResourceAsStream("/DDIxmltojsonForOneObject.xsl");
String jsonContent = transformToJson(new ByteArrayResource(writer.toString().getBytes(StandardCharsets.UTF_8)), xsltStream2, idepUtilisateur,version);
return jsonContent;
return transformToJson(new ByteArrayResource(writer.toString().getBytes(StandardCharsets.UTF_8)), xsltStream2, idepUtilisateur,version);


} catch (Exception e) {
Expand All @@ -548,8 +541,7 @@ private String transformToJson(Resource resultResource, InputStream xsltFileJson
StringWriter xmlWriter = new StringWriter();
StreamResult xmlResult = new StreamResult(xmlWriter);
transformer.transform(text, xmlResult);
String jsonContent = xmlWriter.toString();
return jsonContent;
return xmlWriter.toString();
}

@Override
Expand Down Expand Up @@ -586,7 +578,7 @@ public ResponseEntity<?> getByType(DDIItemType type) throws IOException, Excepti
}

@Override
public ResponseEntity<String> sendUpdateColectica(String DdiUpdatingInJson, TransactionType transactionType) {
public ResponseEntity<String> sendUpdateColectica(String ddiUpdatingInJson, TransactionType transactionType) {
try {
// Étape 1: Initialiser la transaction
String initTransactionUrl = serviceUrl + "/api/v1/transaction";
Expand Down Expand Up @@ -618,7 +610,7 @@ public ResponseEntity<String> sendUpdateColectica(String DdiUpdatingInJson, Tran
populateTransactionHeaders.setContentType(MediaType.APPLICATION_JSON);
populateTransactionHeaders.setBearerAuth(authentToken);
// Créez un objet de demande pour peupler la transaction ici avec transactionId et DdiUpdatingInJson
String updatedJson = DdiUpdatingInJson.replaceFirst("\\{", TRANSACTIONID + transactionId + ",");
String updatedJson = ddiUpdatingInJson.replaceFirst("\\{", TRANSACTIONID + transactionId + ",");
HttpEntity<String> populateTransactionRequest = new HttpEntity<>(updatedJson, populateTransactionHeaders);
ResponseEntity<String> populateTransactionResponse = restTemplate.exchange(
populateTransactionUrl,
Expand Down Expand Up @@ -669,8 +661,7 @@ private int extractTransactionId(String responseBody) {
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
int transactionId = jsonNode.get("TransactionId").asInt();
return transactionId;
return jsonNode.get("TransactionId").asInt();
} catch (Exception e) {
e.printStackTrace();
return -1;
Expand Down Expand Up @@ -851,8 +842,7 @@ private String transformToXml(MultipartFile file, InputStream xsltFile, String i
StringWriter xmlWriter = new StringWriter();
StreamResult xmlResult = new StreamResult(xmlWriter);
transformer.transform(text, xmlResult);
String xmlContent = xmlWriter.toString();
return xmlContent;
return xmlWriter.toString();
}

private String transformToXmlForComplexList(MultipartFile file, InputStream xsltFile, String idValue, String nomenclatureName,
Expand Down Expand Up @@ -890,8 +880,7 @@ private String transformToXmlForComplexList(MultipartFile file, InputStream xslt
StringWriter xmlWriter = new StringWriter();
StreamResult xmlResult = new StreamResult(xmlWriter);
transformer.transform(text, xmlResult);
String xmlContent = xmlWriter.toString();
return xmlContent;
return xmlWriter.toString();
}

private String transformToJson(Resource resultResource, InputStream xsltFileJson, String idepUtilisateur) throws IOException, TransformerException {
Expand All @@ -907,8 +896,7 @@ private String transformToJson(Resource resultResource, InputStream xsltFileJson
StringWriter xmlWriter = new StringWriter();
StreamResult xmlResult = new StreamResult(xmlWriter);
transformer.transform(text, xmlResult);
String jsonContent = xmlWriter.toString();
return jsonContent;
return xmlWriter.toString();
}

@Override
Expand Down
4 changes: 0 additions & 4 deletions src/main/java/fr/insee/rmes/config/ApplicationContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
Expand All @@ -20,16 +19,13 @@
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.auth.NTLMSchemeFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ public String getKeycloakAccessToken() throws ExceptionColecticaUnreachable, Jso
} else {

String token = getAuthToken();
String accessToken = extractAccessToken(token);
return accessToken;
return extractAccessToken(token);
}

}
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/fr/insee/rmes/utils/ddi/DDIDocumentBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -306,12 +306,12 @@ public void importChildByParent(String parentName, Node childNode) {
}

public NodeList getElementByTagName(String name) {
NodeList nodeList = packagedDocument.getElementsByTagName(name);
return nodeList;
return packagedDocument.getElementsByTagName(name);
}

public void importChild(Node childNode) {
Node node, clonedNode;
Node node;
Node clonedNode ;
node = packagedDocument.getLastChild();
clonedNode = childNode.cloneNode(true);
node.appendChild(packagedDocument.adoptNode(clonedNode));
Expand Down

0 comments on commit 3c218e1

Please sign in to comment.