Search in sources :

Example 1 with BadRequestException

use of fr.gouv.vitamui.commons.api.exception.BadRequestException in project vitam-ui by ProgrammeVitam.

the class AccessContractInternalService method patch.

public AccessContractDto patch(VitamContext vitamContext, final Map<String, Object> partialDto) {
    String id = (String) partialDto.get("identifier");
    if (id == null) {
        throw new BadRequestException("id must be one the the update criteria");
    }
    partialDto.remove("id");
    partialDto.remove("identifier");
    try {
        LOGGER.info("Patch Access Contract EvIdAppSession : {} ", vitamContext.getApplicationSessionId());
        // Fix because Vitam doesn't allow String Array as action value (transformed to a string representation"[value1, value2]"
        // Manual setting instead of updateRequest.addActions( UpdateActionHelper.set(fieldsUpdated));
        JsonNode fieldsUpdated = convertMapPartialDtoToUpperCaseVitamFields(partialDto);
        ObjectNode action = JsonHandler.createObjectNode();
        action.set("$set", fieldsUpdated);
        ArrayNode actions = JsonHandler.createArrayNode();
        actions.add(action);
        ObjectNode query = JsonHandler.createObjectNode();
        query.set("$action", actions);
        LOGGER.debug("Send AccessContract update request: {}", query);
        RequestResponse requestResponse = vitamUIAccessContractService.patchAccessContract(vitamContext, id, query);
        final AccessContractVitamDto accessContractVitamDto = objectMapper.treeToValue(requestResponse.toJsonNode(), AccessContractVitamDto.class);
        return converter.convertVitamToDto(accessContractVitamDto);
    } catch (InvalidParseOperationException | AccessExternalClientException | JsonProcessingException e) {
        throw new InternalServerException("Can't patch access contract", e);
    }
}
Also used : AccessContractVitamDto(fr.gouv.vitamui.referential.common.dto.AccessContractVitamDto) AccessExternalClientException(fr.gouv.vitam.access.external.common.exception.AccessExternalClientException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) InternalServerException(fr.gouv.vitamui.commons.api.exception.InternalServerException) BadRequestException(fr.gouv.vitamui.commons.api.exception.BadRequestException) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) RequestResponse(fr.gouv.vitam.common.model.RequestResponse) InvalidParseOperationException(fr.gouv.vitam.common.exception.InvalidParseOperationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 2 with BadRequestException

use of fr.gouv.vitamui.commons.api.exception.BadRequestException in project vitam-ui by ProgrammeVitam.

the class ArchiveSearchInternalService method reclassification.

public String reclassification(final VitamContext vitamContext, final ReclassificationCriteriaDto reclassificationCriteriaDto) throws VitamClientException {
    if (reclassificationCriteriaDto == null) {
        throw new BadRequestException("Error reclassification criteria");
    }
    LOGGER.debug("Reclassification Object : {}", reclassificationCriteriaDto.toString());
    JsonNode dslQuery = mapRequestToDslQuery(reclassificationCriteriaDto.getSearchCriteriaDto());
    ArrayNode array = JsonHandler.createArrayNode();
    ((ObjectNode) dslQuery).putPOJO("$action", reclassificationCriteriaDto.getAction());
    Arrays.stream(new String[] { "$projection", "$filter", "$facets" }).forEach(((ObjectNode) dslQuery)::remove);
    array.add(dslQuery);
    LOGGER.debug("Reclassification query : {}", array.toPrettyString());
    RequestResponse<JsonNode> jsonNodeRequestResponse = unitService.reclassification(vitamContext, array);
    return jsonNodeRequestResponse.toJsonNode().findValue(OPERATION_IDENTIFIER).textValue();
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) BadRequestException(fr.gouv.vitamui.commons.api.exception.BadRequestException) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 3 with BadRequestException

use of fr.gouv.vitamui.commons.api.exception.BadRequestException in project vitam-ui by ProgrammeVitam.

the class ArchiveSearchInternalService method mapRequestToSelectMultiQuery.

/**
 * Map search query to DSl Query Json node
 *
 * @param searchQuery
 * @return
 */
public SelectMultiQuery mapRequestToSelectMultiQuery(SearchCriteriaDto searchQuery) throws VitamClientException {
    if (searchQuery == null) {
        throw new BadRequestException("Can't parse null criteria");
    }
    SelectMultiQuery selectMultiQuery;
    Optional<String> orderBy = Optional.empty();
    Optional<DirectionDto> direction = Optional.empty();
    try {
        if (searchQuery.getSortingCriteria() != null) {
            direction = Optional.of(searchQuery.getSortingCriteria().getSorting());
            orderBy = Optional.of(searchQuery.getSortingCriteria().getCriteria());
        }
        selectMultiQuery = createSelectMultiQuery(searchQuery.getCriteriaList());
        if (orderBy.isPresent()) {
            if (direction.isPresent() && DirectionDto.DESC.equals(direction.get())) {
                selectMultiQuery.addOrderByDescFilter(orderBy.get());
            } else {
                selectMultiQuery.addOrderByAscFilter(orderBy.get());
            }
        }
        selectMultiQuery.setLimitFilter(searchQuery.getPageNumber() * searchQuery.getSize(), searchQuery.getSize());
        selectMultiQuery.trackTotalHits(searchQuery.isTrackTotalHits());
        LOGGER.debug("Final query: {}", selectMultiQuery.getFinalSelect().toPrettyString());
    } catch (InvalidCreateOperationException ioe) {
        throw new VitamClientException("Unable to find archive units with pagination", ioe);
    } catch (InvalidParseOperationException e) {
        throw new BadRequestException("Can't parse criteria as Vitam query" + e.getMessage());
    }
    return selectMultiQuery;
}
Also used : SelectMultiQuery(fr.gouv.vitam.common.database.builder.request.multiple.SelectMultiQuery) InvalidCreateOperationException(fr.gouv.vitam.common.database.builder.request.exception.InvalidCreateOperationException) DirectionDto(fr.gouv.vitamui.commons.api.domain.DirectionDto) VitamClientException(fr.gouv.vitam.common.exception.VitamClientException) BadRequestException(fr.gouv.vitamui.commons.api.exception.BadRequestException) InvalidParseOperationException(fr.gouv.vitam.common.exception.InvalidParseOperationException)

Example 4 with BadRequestException

use of fr.gouv.vitamui.commons.api.exception.BadRequestException in project vitam-ui by ProgrammeVitam.

the class ArchiveSearchInternalService method exportToCsvSearchArchiveUnitsByCriteriaAndParams.

/**
 * export ToCsv Search ArchiveUnits By Criteria And Params by language
 *
 * @param searchQuery
 * @param exportSearchResultParam
 * @param vitamContext
 * @return
 * @throws VitamClientException
 */
private Resource exportToCsvSearchArchiveUnitsByCriteriaAndParams(final SearchCriteriaDto searchQuery, final ExportSearchResultParam exportSearchResultParam, final VitamContext vitamContext) throws VitamClientException {
    try {
        archiveSearchAgenciesInternalService.mapAgenciesNameToCodes(searchQuery, vitamContext);
        List<ArchiveUnitCsv> unitCsvList = exportArchiveUnitsByCriteriaToCsvFile(searchQuery, vitamContext);
        // create a write
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8.name());
        // header record
        String[] headerRecordFr = exportSearchResultParam.getHeaders().toArray(new String[exportSearchResultParam.getHeaders().size()]);
        SimpleDateFormat dateFormat = new SimpleDateFormat(exportSearchResultParam.getPatternDate());
        // create a csv writer
        ICSVWriter csvWriter = new CSVWriterBuilder(writer).withSeparator(exportSearchResultParam.getSeparator()).withQuoteChar(ICSVWriter.NO_QUOTE_CHARACTER).withEscapeChar(ICSVWriter.DEFAULT_ESCAPE_CHARACTER).withLineEnd(ICSVWriter.DEFAULT_LINE_END).build();
        // write header record
        csvWriter.writeNext(headerRecordFr);
        // write data records
        unitCsvList.stream().forEach(archiveUnitCsv -> {
            String startDt = null;
            String endDt = null;
            if (archiveUnitCsv.getStartDate() != null) {
                try {
                    startDt = dateFormat.format(LocalDateUtil.getDate(archiveUnitCsv.getStartDate()));
                } catch (ParseException e) {
                    LOGGER.error("Error parsing starting date {} ", archiveUnitCsv.getStartDate());
                }
            }
            if (archiveUnitCsv.getEndDate() != null) {
                try {
                    endDt = dateFormat.format(LocalDateUtil.getDate(archiveUnitCsv.getEndDate()));
                } catch (ParseException e) {
                    LOGGER.error("Error parsing end date {} ", archiveUnitCsv.getEndDate());
                }
            }
            csvWriter.writeNext(new String[] { archiveUnitCsv.getId(), archiveUnitCsv.getArchiveUnitType(), archiveUnitCsv.getOriginatingAgencyName(), exportSearchResultParam.getDescriptionLevelMap().get(archiveUnitCsv.getDescriptionLevel()), archiveUnitCsv.getTitle(), startDt, endDt, archiveUnitCsv.getDescription() });
        });
        // close writers
        csvWriter.close();
        writer.close();
        return new ByteArrayResource(outputStream.toByteArray());
    } catch (IOException ex) {
        throw new BadRequestException("Unable to export csv file ", ex);
    }
}
Also used : CSVWriterBuilder(com.opencsv.CSVWriterBuilder) ArchiveUnitCsv(fr.gouv.vitamui.archives.search.common.dto.ArchiveUnitCsv) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayResource(org.springframework.core.io.ByteArrayResource) IOException(java.io.IOException) ICSVWriter(com.opencsv.ICSVWriter) BadRequestException(fr.gouv.vitamui.commons.api.exception.BadRequestException) OutputStreamWriter(java.io.OutputStreamWriter) ParseException(java.text.ParseException) DateTimeParseException(java.time.format.DateTimeParseException) SimpleDateFormat(java.text.SimpleDateFormat) Writer(java.io.Writer) ICSVWriter(com.opencsv.ICSVWriter) OutputStreamWriter(java.io.OutputStreamWriter)

Example 5 with BadRequestException

use of fr.gouv.vitamui.commons.api.exception.BadRequestException in project vitam-ui by ProgrammeVitam.

the class ArchiveSearchAgenciesInternalService method findOriginAgenciesByCriteria.

public List<AgencyModelDto> findOriginAgenciesByCriteria(VitamContext vitamContext, String field, List<String> originAgenciesCodes) throws VitamClientException {
    List<AgencyModelDto> agencies = new ArrayList<>();
    if (originAgenciesCodes != null && !originAgenciesCodes.isEmpty()) {
        LOGGER.info("Finding originating agencies by field {}  values {} ", field, originAgenciesCodes);
        Map<String, Object> searchCriteriaMap = new HashMap<>();
        searchCriteriaMap.put(field, originAgenciesCodes);
        try {
            JsonNode queryOriginAgencies = VitamQueryHelper.createQueryDSL(searchCriteriaMap, 0, originAgenciesCodes.size(), Optional.empty(), Optional.empty());
            RequestResponse<AgenciesModel> requestResponse = agencyService.findAgencies(vitamContext, queryOriginAgencies);
            agencies = objectMapper.treeToValue(requestResponse.toJsonNode(), AgencyResponseDto.class).getResults();
        } catch (InvalidCreateOperationException e) {
            throw new VitamClientException("Unable to find the agencies ", e);
        } catch (InvalidParseOperationException | JsonProcessingException e1) {
            throw new BadRequestException("Error parsing query ", e1);
        }
    }
    LOGGER.info("origin agencies  found {} ", agencies);
    return agencies;
}
Also used : HashMap(java.util.HashMap) VitamClientException(fr.gouv.vitam.common.exception.VitamClientException) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) InvalidParseOperationException(fr.gouv.vitam.common.exception.InvalidParseOperationException) AgencyModelDto(fr.gouv.vitamui.commons.api.domain.AgencyModelDto) InvalidCreateOperationException(fr.gouv.vitam.common.database.builder.request.exception.InvalidCreateOperationException) BadRequestException(fr.gouv.vitamui.commons.api.exception.BadRequestException) AgenciesModel(fr.gouv.vitam.common.model.administration.AgenciesModel) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

BadRequestException (fr.gouv.vitamui.commons.api.exception.BadRequestException)32 JsonNode (com.fasterxml.jackson.databind.JsonNode)17 VitamClientException (fr.gouv.vitam.common.exception.VitamClientException)13 PreconditionFailedException (fr.gouv.vitamui.commons.api.exception.PreconditionFailedException)9 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)8 Select (fr.gouv.vitam.common.database.builder.request.single.Select)8 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 InvalidParseOperationException (fr.gouv.vitam.common.exception.InvalidParseOperationException)7 UnavailableServiceException (fr.gouv.vitamui.commons.api.exception.UnavailableServiceException)7 IOException (java.io.IOException)7 Test (org.junit.Test)7 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)6 VitamContext (fr.gouv.vitam.common.client.VitamContext)6 InternalServerException (fr.gouv.vitamui.commons.api.exception.InternalServerException)6 InvalidCreateOperationException (fr.gouv.vitam.common.database.builder.request.exception.InvalidCreateOperationException)5 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 ForbiddenException (fr.gouv.vitamui.commons.api.exception.ForbiddenException)4 AccessExternalClientException (fr.gouv.vitam.access.external.common.exception.AccessExternalClientException)3 AgencyModelDto (fr.gouv.vitamui.commons.api.domain.AgencyModelDto)3 Criterion (fr.gouv.vitamui.commons.api.domain.Criterion)3