Примеры использования API Диадок SDK

В связи с тем, что для языка java Диадок не предоставляет примеров кода, привожу свои наработки. В заметке можно найти код для отправки неформализованного сообщения, поиска организации, поиска последнего события в ящике, листинг всех организаций и их сотрудников для своей учетки, создание департамента.

Для сборки проекта с предоставленным исходником вам нужно будет добавить в локальный репозиторий несколько артифактов: сам sdk и его зависимости из JCP:

mvn install:install-file -Dfile=D:\soft\diadok\diadocsdk-3.2.3.jar -DgroupId=ru.kontur.diadoc -DartifactId=diadocsdk -Dversion=3.2.3 -Dpackaging=jar
 
mvn install:install-file -Dfile=D:\soft\diadok\jcp-2.0.40450-A\JCP.jar -DgroupId=ru.CryptoPro -DartifactId=JCP -Dversion=2.0.40450-A -Dpackaging=jar
mvn install:install-file -Dfile=D:\soft\diadok\jcp-2.0.40450-A\asn1rt.jar -DgroupId=com.objsys.asn1j -DartifactId=asn1rt -Dversion=2.0.40450-A -Dpackaging=jar
mvn install:install-file -Dfile=D:\soft\diadok\jcp-2.0.40450-A\ASN1P.jar -DgroupId=ru.CryptoPro -DartifactId=ASN1P -Dversion=2.0.40450-A -Dpackaging=jar
mvn install:install-file -Dfile=D:\soft\diadok\jcp-2.0.40450-A\JCryptoP.jar -DgroupId=ru.CryptoPro -DartifactId=JCryptoP -Dversion=2.0.40450-A -Dpackaging=jar

Зависимости проекта:

<dependency>
            <groupid>ru.kontur.diadoc</groupid>
            <artifactid>diadocsdk</artifactid>
            <version>3.2.3</version>
        </dependency>
 
<!-- deps for SDK -->
        <dependency>
            <groupid>com.google.protobuf</groupid>
            <artifactid>protobuf-java</artifactid>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupid>javax.mail</groupid>
            <artifactid>mail</artifactid>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupid>org.apache.httpcomponents</groupid>
            <artifactid>httpclient</artifactid>
            <version>4.5.6</version>
        </dependency>
 
        <dependency>
            <groupid>org.bouncycastle</groupid>
            <artifactid>bcprov-jdk14</artifactid>
            <version>1.65</version>
        </dependency>
        <!-- http://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupid>commons-io</groupid>
            <artifactid>commons-io</artifactid>
            <version>2.6</version>
        </dependency>
        <!-- http://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupid>com.google.code.gson</groupid>
            <artifactid>gson</artifactid>
            <version>2.8.5</version>
        </dependency>
 
        <!-- deps related to JCP -->
        <dependency>
            <groupid>ru.CryptoPro</groupid>
            <artifactid>JCP</artifactid>
            <version>2.0.40450-A</version>
        </dependency>
        <dependency>
            <groupid>com.objsys.asn1j</groupid>
            <artifactid>asn1rt</artifactid>
            <version>2.0.40450-A</version>
        </dependency>
        <dependency>
            <groupid>ru.CryptoPro</groupid>
            <artifactid>ASN1P</artifactid>
            <version>2.0.40450-A</version>
        </dependency>
        <dependency>
            <groupid>ru.CryptoPro</groupid>
            <artifactid>JCryptoP</artifactid>
            <version>2.0.40450-A</version>
        </dependency>

Исходник:

package ru.outofrange.diadoc.cli;
 
import Diadoc.Api.CertificateHelper;
import Diadoc.Api.DiadocApi;
import Diadoc.Api.Proto.*;
import Diadoc.Api.Proto.Departments.DepartmentProtos;
import Diadoc.Api.Proto.Departments.DepartmentToCreateProtos;
import Diadoc.Api.Proto.Departments.RoutingProtos;
import Diadoc.Api.Proto.Docflow.AttachmentProtos;
import Diadoc.Api.Proto.Employees.EmployeeToCreateProtos;
import Diadoc.Api.Proto.Events.DiadocMessage_GetApiProtos;
import Diadoc.Api.Proto.Events.DiadocMessage_PostApiProtos;
import Diadoc.Api.auth.DiadocCredentials;
import Diadoc.Api.events.EventsClient;
import Diadoc.Api.exceptions.DiadocSdkException;
import Diadoc.Api.message.MessageClient;
import com.google.protobuf.ByteString;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.HttpResponseException;
import util.KeyStoreUtil;
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.*;
import java.security.cert.X509Certificate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Properties;
 
public class CLI {
 
    private static String CERT_ALIAS = "DiadocCert";
    private static String PASSWORD_FOR_KEYSTORE = "changeit";
 
    public static void main(String[] arg) throws DiadocSdkException {
 
        Properties prop = new Properties();
        try (InputStream input = CLI.class.getResourceAsStream("/application.properties")) {
            prop.load(input);
        } catch (
                IOException ex) {
            ex.printStackTrace();
        }
 
        String apiClientId = prop.getProperty("apiClientId");
        String url = prop.getProperty("apiUrl");
 
        KeyStore keyStore = KeyStoreUtil.loadKeyStore(PASSWORD_FOR_KEYSTORE);
        KeyStoreUtil.showCertificate(CERT_ALIAS, keyStore);
        System.out.println("----------------------------------------");
 
        X509Certificate x509 = KeyStoreUtil.getCertificate(CERT_ALIAS, keyStore);
 
        String filePath = "d:/soft/diadok/message_small.txt".replace('/', File.separatorChar);
 
        if (x509 == null) {
            System.out.println("can't get x509 cert from keystore");
            return;
        }
 
        DiadocApi api = new DiadocApi(apiClientId, url, null);
 
        String token = null;
        try {
 
            String login = prop.getProperty("lkLogin");
            String password = prop.getProperty("lkPassword");
 
            api.getAuthClient().authenticate(login, password);
 
            Credentials credentials = api.getAuthManager().getCredentialsProvider().getCredentials(AuthScope.ANY);
            if (credentials instanceof DiadocCredentials) {
                token = ((DiadocCredentials) credentials).getAuthToken();
            }
            System.out.println("token: " + token);
        } catch (DiadocSdkException e) {
            e.printStackTrace();
            return;
        }
 
        try {
            UserProtos.User user = api.getUserClient().getMyUser();
            System.out.println("количество облачных сертификатов " + user.getCloudCertificatesCount());
            System.out.println(user.getFirstName() + " " + user.getMiddleName() + " " + user.getLastName());
            //System.out.println(user.findInitializationErrors());
            System.out.println(user.getId());
        } catch (DiadocSdkException e) {
            e.printStackTrace();
        }
 
        String fromBoxId = prop.getProperty("fromBoxId");
        String toBoxId = prop.getProperty("toBoxId");
 
        System.out.println("----------------------------------------");
        System.out.println("Организации из учетки: ");
        try {
            OrganizationProtos.OrganizationList list = api.getOrganizationClient().getMyOrganizations();
            if (list.getOrganizationsCount() &gt; 0) {
                for (int i = 0; i &lt; list.getOrganizationsCount(); i++) {
                    OrganizationProtos.Organization organization = list.getOrganizations(i);
                    System.out.println(organization.getFullName());
 
                    List<organizationprotos.box> boxes = organization.getBoxesList();
                    boxes.forEach(box -&gt; {
                        System.out.println("box id " + box.getBoxId());
                    });
 
                    List<organizationprotos.department> departments = organization.getDepartmentsList();
                    if (departments.size() &gt; 0) {
                        System.out.println("Найдены департаменты: ");
                        departments.forEach(department -&gt; {
                            System.out.println("     " + department.getDepartmentId() + " | " + department.getName() + " | " + department.getAbbreviation()
                                    + " | ");
                        });
                    } else {
                        System.out.println("департаментов не найдено");
                    }
 
                    OrganizationUserProtos.OrganizationUsersList users = api.getOrganizationClient().getOrganizationUsers(organization.getOrgId());
                    if (users.getUsersCount() &gt; 0) {
                        System.out.println("Найдены сотрудники: ");
                        for (int j = 0; j &lt; users.getUsersCount(); j++) {
                            OrganizationUserProtos.OrganizationUser user = users.getUsers(j);
                            System.out.println("&gt;&gt; " + user.getId() + " " + user.getPosition() + " " + user.getName());
                        }
                    }
                }
            } else {
                System.out.println("организаций не найдено");
            }
        } catch (DiadocSdkException e) {
            e.printStackTrace();
        }
 
        System.out.println("----------------------------------------");
        System.out.println("Пример поиска организации: ");
        try {
            OrganizationProtos.OrganizationList organizations = api.getOrganizationClient().getOrganizationsByInnKpp("9621326428", "962101000");
 
            for (int i = 0; i &lt; organizations.getOrganizationsCount(); i++) {
                OrganizationProtos.Organization organization = organizations.getOrganizations(i);
                System.out.println(organization.getFullName());
 
                List<organizationprotos.box> boxes = organization.getBoxesList();
                boxes.forEach(box -&gt; {
                    System.out.println("box id " + box.getBoxId());
                });
            }
 
        } catch (DiadocSdkException e) {
            e.printStackTrace();
        }
 
        System.out.println("----------------------------------------");
 
        EventsClient eventsClient = api.getEventsClient();
        if (eventsClient != null) {
            DiadocMessage_GetApiProtos.BoxEvent event = null;
            try {
                event = eventsClient
                        .getLastEvent(fromBoxId);
            } catch (NullPointerException npe) {
                ExceptionUtils.printRootCauseStackTrace(npe);
            }
            if (event != null) {
                System.out.println("Найдено событие: ");
                System.out.println(event.getEventId());
            } else {
                System.out.println("Нет событий");
            }
            System.out.println("----------------------------------------");
        }
 
        // сюда попадаем, если аутентификация успешна
        String scriptFromCommandLine = "script1";
 
        if (scriptFromCommandLine.equals("script1")) {
            // сценарий - отправка через shelf
            // https://github.com/diadoc/diadocsdk-csharp/blob/master/Samples/Diadoc.Samples/SendLargeNonformalizedSample.cs
 
            filePath = "d:/soft/diadok/message_small.txt".replace('/', File.separatorChar);
            //filePath = "d:/soft/diadok/message_large.pdf".replace('/', File.separatorChar);
            //filePath = "d:/soft/diadok/message_extra_large.pdf".replace('/', File.separatorChar);
            try {
                byte[] bytes = Files.readAllBytes(new File(filePath).toPath());
                String shelfId = api.getShelfClient().uploadFileToShelf(bytes);
                System.out.println("returned shelf's id " + shelfId);
 
                // java.security.KeyStoreException: HDImageStore not found
                ByteString signature = ByteString.copyFrom(CertificateHelper.sign(x509, bytes));
                //ByteString signature = ByteString.copyFrom("1223ad5", "UTF-8");
 
                DiadocMessage_PostApiProtos.NonformalizedAttachment.Builder attachmentBuilder = DiadocMessage_PostApiProtos.NonformalizedAttachment.newBuilder();
                attachmentBuilder.setComment("Тестовая загрузка");
                attachmentBuilder.setNeedRecipientSignature(false);
                attachmentBuilder.setDocumentDate(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE));
                attachmentBuilder.setDocumentNumber("123");
                attachmentBuilder.setCustomDocumentId("custom 123");
                attachmentBuilder.setFileName("test.txt");
 
                DiadocMessage_PostApiProtos.SignedContent.Builder signedContentBuilder = DiadocMessage_PostApiProtos.SignedContent.newBuilder();
                signedContentBuilder.setNameOnShelf(shelfId);
                signedContentBuilder.setSignature(signature);
                attachmentBuilder.setSignedContent(signedContentBuilder.build());
 
                DiadocMessage_PostApiProtos.MessageToPost.Builder messageBuilder = DiadocMessage_PostApiProtos.MessageToPost.newBuilder();
                messageBuilder.setFromBoxId(fromBoxId);
                messageBuilder.setToBoxId(toBoxId);
                messageBuilder.addNonformalizedDocuments(attachmentBuilder.build());
 
                // отправка
                try {
                    DiadocMessage_GetApiProtos.Message response = api
                            .getMessageClient()
                            .postMessage(messageBuilder.build());
                    System.out.println("returned message's id " + response.getMessageId());
                    System.out.println("returned message's type " + response.getMessageType().name());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    ExceptionUtils.printRootCauseStackTrace(e);
                    if (e instanceof HttpResponseException) {
                        HttpResponseException hre = (HttpResponseException) e;
                        System.out.println(hre.getStatusCode() + " " + hre.getMessage());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (DiadocSdkException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (scriptFromCommandLine.equals("script2")) {
            try {
                // вызывается для создания департамента.
                DepartmentToCreateProtos.DepartmentToCreate.Builder depBuilder = DepartmentToCreateProtos.DepartmentToCreate.newBuilder();
                depBuilder.setAbbreviation("АПР");
 
                AddressProtos.Address.Builder addressBuilder = AddressProtos.Address.newBuilder();
 
                AddressProtos.RussianAddress.Builder ruBuilder = AddressProtos.RussianAddress.newBuilder();
                ruBuilder.setCity("Москва");
                ruBuilder.setRegion("40");
                ruBuilder.setStreet("Тестовая улица");
                ruBuilder.setZipCode("248056");
 
                addressBuilder.setRussianAddress(ruBuilder.build());
 
                depBuilder.setAddress(addressBuilder.build());
                depBuilder.setName("Тестовое имя");
 
                RoutingProtos.Routing.Builder routingBuilder = RoutingProtos.Routing.newBuilder();
                routingBuilder.setKpp(false);
                routingBuilder.setAddress(true);
 
                depBuilder.setRouting(routingBuilder.build());
 
                DepartmentProtos.Department department = api.getDepartmentClient().createDepartment(fromBoxId, depBuilder.build());
                System.out.println(department.getAbbreviation());
 
            } catch (DiadocSdkException e) {
                e.printStackTrace();
            }
        } 
    }
 
}
 
</organizationprotos.box></organizationprotos.department></organizationprotos.box>
You can leave a response, or trackback from your own site.

Leave a Reply