Существуют ли классы Java для ответов Camunda Rest? - PullRequest
1 голос
/ 23 октября 2019

Привет, коллеги-программисты,

В настоящее время я пытаюсь настроить вызовы REST из Spring на мой локальный экземпляр camunda, используя api camunda rest.

Вот как я его настроил:

  1. На моем localhost:8080 запущен локальный контейнер док-станции camunda, например: https://hub.docker.com/r/camunda/camunda-bpm-platform (я проверил звонки с почтальоном, и они работают)

  2. В моем pom.xml:

        <dependency>
            <groupId>org.camunda.bpm.springboot</groupId>
            <artifactId>camunda-bpm-spring-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.camunda.bpm</groupId>
            <artifactId>camunda-engine-rest-core</artifactId>
            <version>7.11.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectreactor</groupId>
            <artifactId>reactor-spring</artifactId>
            <version>1.0.1.RELEASE</version>
        </dependency>
создан проект maven с использованием нескольких зависимостей камунды и остальных. Написал простой сервис для вызова покоя из Spring (взято из https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-webclient):
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class MyExampleService {

    private final WebClient webClient;

    public MyExampleService (WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("http://localhost:8080").build();
    }

    @Override
    public ProcessDefinitionEntity[] getCamundaProcesses() {

        ProcessDefinitionEntity[] myResponse = this.webClient.get().uri("/engine-rest/process-definition/")
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError, response -> {
                    System.out.println("4xx eror");
                    return Mono.error(new RuntimeException("4xx"));
                })
                .onStatus(HttpStatus::is5xxServerError, response -> {
                    System.out.println("5xx eror");
                    return Mono.error(new RuntimeException("5xx"));
                })
                .bodyToMono(ProcessDefinitionEntity[].class)
                .block();

        return myResponse;
}

Так что я в основном использовал Spring WebClient для вызова покоя на localhost:8080/engine-rest/deployment/, что должно дать мнесписок всех процессов в виде JSON (в соответствии с https://docs.camunda.org/manual/latest/reference/rest/deployment/get-query/).

Теперь, когда я преобразую ответ непосредственно в ProcessDefinitionEntity [], он не будет преобразовывать JSON в него. Я также пробовал другие классы из Camunda JavaAPI (https://docs.camunda.org/javadoc/camunda-bpm-platform/7.11/) как ProcessDefinitionDto.

Кажется, что ни один из классов не соответствует должным образом полученному ответу от камунды. Ответ выглядит так:

[
    {
        "id": "invoice:1:cdbc3f02-e6a1-11e9-8de8-0242ac110002",
        "key": "invoice",
        "category": "http://www.omg.org/spec/BPMN/20100524/MODEL",
        "description": null,
        "name": "Invoice Receipt",
        "version": 1,
        "resource": "invoice.v1.bpmn",
        "deploymentId": "cda115de-e6a1-11e9-8de8-0242ac110002",
        "diagram": null,
        "suspended": false,
        "tenantId": null,
        "versionTag": "V1.0",
        "historyTimeToLive": 30,
        "startableInTasklist": true
    },
    {
        "id": "invoice:2:ce03f66c-e6a1-11e9-8de8-0242ac110002",
        "key": "invoice",
        "category": "http://www.omg.org/spec/BPMN/20100524/MODEL",
        "description": null,
        "name": "Invoice Receipt",
        "version": 2,
        "resource": "invoice.v2.bpmn",
        "deploymentId": "cdfbb908-e6a1-11e9-8de8-0242ac110002",
        "diagram": null,
        "suspended": false,
        "tenantId": null,
        "versionTag": "V2.0",
        "historyTimeToLive": 45,
        "startableInTasklist": true
    }
]

(это всего лишь два стандартных процесса, которые находятся в контейнере Docker)

Существуют ли классы в Java Caminda API, которые правильно соответствуют ответам от API Api Camunda?

С наилучшими пожеланиями,

Себастьян

Ответы [ 2 ]

1 голос
/ 26 октября 2019

Классы в

org.camunda.bpm.engine.rest.dto.runtime

подходят.

<dependency>
  <groupId>org.camunda.bpm</groupId>
  <artifactId>camunda-engine-rest-core</artifactId>
</dependency>

Вв вашем случае это будет ProcessDefinitionDto Пример использования с шаблоном Spring REST:

@Service
@Slf4j
public class RuntimeServiceImpl implements RuntimeService {

    private final RestTemplate rest;
    @Value("${camunda.server.rest.url}")
    private String restURL;

    public RuntimeServiceImpl(RestTemplateBuilder builder) {
        this.rest = builder.build();
    }

    public ProcessDefinitionDto[] getProcessDefinitions() {

        ResponseEntity<ProcessDefinitionDto[]> response = rest.getForEntity(restURL + "process-definition/",
                ProcessDefinitionDto[].class);
        ProcessDefinitionDto[] processes = response.getBody();

        Arrays.stream(processes).forEach(pd -> log.info("Found process definition {} with id {} and key {}", pd.getName(), pd.getId(), pd.getKey()));

        return processes;
    }
}

Полный клиентский проект: https://github.com/rob2universe/camunda-rest-client

внешний клиентский класс содержит дополнительные интерфейсы и DTO, которые вы можете использовать повторно, такие как

org.camunda.bpm.client.topic.impl.dto.FetchAndLockRequestDto;org.camunda.bpm.client.topic.impl.dto.TopicRequestDto;

Или просто используйте / fork полный клиентский проект. Там для вас уже проделана большая работа.

0 голосов
/ 25 октября 2019

Вы ищете правильный пакет? В кодовой базе Camunda имеется несколько классов ProcessDefinitionDto. Тот, который вы ищете, находится в пакете org.camunda.bpm.engine.rest.dto.repository в camunda-engine-rest-core.jar

Класс выглядит так, что точно соответствует вашему выводу:

package org.camunda.bpm.engine.rest.dto.repository;

import org.camunda.bpm.engine.repository.ProcessDefinition;

public class ProcessDefinitionDto {

  protected String id;
  protected String key;
  protected String category;
  protected String description;
  protected String name;
  protected int version;
  protected String resource;
  protected String deploymentId;
  protected String diagram;
  protected boolean suspended;
  protected String tenantId;
  protected String versionTag;
  protected Integer historyTimeToLive;
  protected boolean isStartableInTasklist;

  ...
...