NoClassDefFoundError: com/google/cloud/kms/v1/KeyManagementServiceClient

Я пишу здесь впервые, поэтому прошу прощения, если я должен добавить больше к вопросу. Я создаю приложение с java и пытаюсь создать соединение KeyManagementServiceClient в Google Cloud. Программа строится правильно, но когда я запускаю приведенную ниже функцию, я получаю ошибку NoClassDefFound в отношении com/google/cloud/kms/v1/KeyManagementServiceClient.

try (KeyManagementServiceClient client = KeyManagementServiceClient.create())

Я использую maven, и все мои исследования этой проблемы приводят меня к мысли, что у меня есть проблема с моим файлом pom.xml, который я включил ниже, но попытка исправления не помогла избавиться от ошибки.

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>
  <artifactId>encryptiontobucket</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>my-app</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-kms-bom</artifactId>
        <version>1.40.0</version>
        <type>pom</type>
        <scope>import</scope>
       </dependency>
     </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-kms</artifactId>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Если кто-то может помочь мне исправить ошибку, я был бы очень признателен! Кроме того, дайте мне знать, если что-то еще необходимо, чтобы понять проблему.

EDIT: Ниже приведен мой код. Сначала я создал проект maven под названием my-app, в котором есть файл pom.xml. Моя программа EncryptionToBucket.java находится в каталоге в папке приложения, созданной по умолчанию maven. Чтобы воспроизвести проблему:

  1. Поместите программу в указанное выше место.
  2. Запустить mvn-пакет
  3. Запустите java -cp target\my-app-1.0-SNAPSHOT.jar EncryptionToBucket
  4. Введите случайный идентификатор проекта, выберите случайный идентификатор местоположения и нажмите кнопку «Создать новый ключ», и в командной строке появится ошибка.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRing;
import com.google.cloud.kms.v1.LocationName;
import java.io.IOException;


class EncryptionToBucket implements ActionListener{
    private String projectId,locationId, keyRingPath, keyNamePath, asymmKey;
    private JButton createNewKeyRing, createNewKey, encryptData, back, back2, createNewSigningKey;
    private JTextField projText, keyRingTField, keyNameTField, asymmKeyEntry;
    private JComboBox locations;
    private JFrame initialFrame, keyRingFrame, keyFrame;

    public EncryptionToBucket(){
        initialInfoPage();
    }

    public void keyRingCreation() {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
     try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project and location.
        // LocationName locationName = LocationName.of(projectId, locationId);

      // Build the key ring to create.
        //KeyRing keyRing = KeyRing.newBuilder().build();

      // Create the key ring.
        // KeyRing createdKeyRing = client.createKeyRing(locationName, asymmKey, keyRing);
         //System.out.printf("Created key ring %s%n", createdKeyRing.getName());
        }catch (IOException e){
            //System.out.println("Rut Row");
        }
  
    }
    

    public static void main(String args[]){
        EncryptionToBucket constructor = new EncryptionToBucket();
    }

    public void initialInfoPage(){
        /*TODO: Remove Gaps
        */
        initialFrame = new JFrame("Enter Information");
        initialFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initialFrame.setSize(500, 500);
        initialFrame.setResizable(false);
        initialFrame.setLocationRelativeTo(null);

        JLabel proj = new JLabel("Project ID: ");
        JLabel location = new JLabel("Location ID: ");

        projText = new JTextField(10);
        projText.setText(projectId);
        String[] locationIds= {" ", "asia-east1", "asia-east2", "asia-northeast1", "asia-northeast2", "asia-northeast3", "asia-south1", "asia-southeast1", "asia-southeast2", "australia-southeast1", "europe-north1", "europe-west1", "europe-west2", "europe-west3", "europe-west4", "europe-west6", "northamerica-northeast1", "southamerica-east1", "us-central1", "us-east1", "us-east4", "us-west1", "us-west2", "us-west3", "us-west4"};
        locations = new JComboBox(locationIds);
        locations.setSelectedItem(locationId);

        GridLayout layout = new GridLayout(2,0);
        JPanel topPane = new JPanel(layout);
        JPanel topPane1 = new JPanel();
        JPanel topPane2 = new JPanel();
        topPane1.add(proj);
        topPane1.add(projText);
        topPane2.add(location);
        topPane2.add(locations);
        topPane.add(topPane1);
        topPane.add(topPane2);
        
         JPanel secondTierPane = new JPanel(new GridLayout(2,0));
         JPanel secondTierPane1 = new JPanel();
         JPanel secondTierPane2 = new JPanel();
         JLabel keyRingName = new JLabel("Key Ring Path: ");
         secondTierPane1.add(keyRingName);
         keyRingTField = new JTextField(10);
         keyRingTField.setText(keyRingPath);
         secondTierPane1.add(keyRingTField);
         secondTierPane.add(secondTierPane1);
         createNewKeyRing = new JButton("Create a New Key Ring");
         createNewKeyRing.addActionListener(this);
         secondTierPane2.add(createNewKeyRing);
         secondTierPane.add(secondTierPane2);


         JPanel thirdTierPane = new JPanel(new GridLayout(2,0));
         JPanel thirdTierPane1 = new JPanel();
         JPanel thirdTierPane2 = new JPanel();
         JLabel keyName = new JLabel("Key Path: ");
         thirdTierPane1.add(keyName);
         keyNameTField = new JTextField(10);
         keyNameTField.setText(keyNamePath);
         thirdTierPane1.add(keyNameTField);
         thirdTierPane.add(thirdTierPane1);
         createNewKey = new JButton("Create a New Key");
         createNewKey.addActionListener(this);
         thirdTierPane2.add(createNewKey);
         thirdTierPane.add(thirdTierPane2);

         JPanel bottomPane = new JPanel();
         encryptData = new JButton("Encrypt Data"); 
         bottomPane.add(encryptData);

         JPanel main = new JPanel(new GridLayout(4,1));

         main.add(topPane);
         main.add(secondTierPane);
         main.add(thirdTierPane);
         main.add(bottomPane);
        
        initialFrame.add(main);
        initialFrame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e){
        
        if(e.getSource() == createNewKeyRing){
            projectId = projText.getText();
            locationId = locations.getSelectedItem().toString();
            //initialFrame.setVisible(false);
            keyRingPage();
        }else if(e.getSource() == createNewKey){
            if(projText.getText().isEmpty()){
                JOptionPane errormessage = new JOptionPane();
                errormessage.showMessageDialog(null, "A projectId is needed to create a key ring!", "alert", JOptionPane.ERROR_MESSAGE);
            }else{
                projectId = projText.getText();
            }
            locationId = locations.getSelectedItem().toString();
            keyRingPath = keyRingTField.getText();
            initialFrame.setVisible(false);
            keyPage();
        }else if(e.getSource() == encryptData){

        }else if(e.getSource() == back || e.getSource() == back2){
            if(keyRingFrame.isVisible()){
                asymmKey = asymmKeyEntry.getText();
                keyRingFrame.setVisible(false);
                keyRingCreation();
            }else if(keyFrame.isVisible()){
                keyFrame.setVisible(false);
            }
            initialInfoPage();
        }
        
    }

    public void keyRingPage(){
    /*
    TODO: Key Ring Creation Code
    */

        keyRingFrame = new JFrame("Key Ring Creation");
        keyRingFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        keyRingFrame.setSize(500, 400);
        keyRingFrame.setResizable(true);
        keyRingFrame.setLocationRelativeTo(null);

        JPanel main = new JPanel(new GridLayout (3,2));
        
        JPanel topPane = new JPanel();
        topPane.setLayout(new BoxLayout(topPane, BoxLayout.PAGE_AXIS));
        JLabel projectsId = new JLabel("Project ID: " + projectId);
        projectsId.setAlignmentX(Component.CENTER_ALIGNMENT);
        JLabel locationsId = new JLabel("Location ID: " + locationId);
        locationsId.setAlignmentX(Component.CENTER_ALIGNMENT);
        topPane.add(projectsId);
        topPane.add(locationsId);
        main.add(topPane);

        JPanel midPane = new JPanel();
        midPane.setLayout(new BoxLayout(midPane, BoxLayout.PAGE_AXIS));
        JLabel asymmKeyName = new JLabel("Asymmetric Signing Key: ");
        midPane.add(asymmKeyName);
        asymmKeyEntry = new JTextField(10);
        //asymmKeyEntry.setPreferredSize();
        asymmKeyEntry.setAlignmentX(Component.CENTER_ALIGNMENT);
        midPane.add(asymmKeyEntry);
        createNewSigningKey = new JButton("Create New Signing Key");
        midPane.add(createNewSigningKey);
        main.add(midPane);

        JPanel lowPane = new JPanel();
        back = new JButton("Create Key Ring");
        back.addActionListener(this);
        lowPane.add(back);
        main.add(lowPane);

        keyRingFrame.add(main);
        keyRingFrame.setVisible(true);
    }

    public void keyPage(){
        keyFrame = new JFrame("Key Ring Creation");
        keyFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        keyFrame.setSize(500, 400);
        keyFrame.setResizable(true);
        keyFrame.setLocationRelativeTo(null);

        JPanel main = new JPanel();
        back2 = new JButton("Enter");
        back2.addActionListener(this);
        main.add(back2);
        keyFrame.add(main);
        keyFrame.setVisible(true);
    }
    

}




person rdickens286    schedule 02.09.2020    source источник
comment
Я скопировал ваш pom.xml и построил его, он работает без ошибок, поделитесь, пожалуйста, более подробной информацией.   -  person Abrar Ansari    schedule 02.09.2020
comment
Здание не ошибка. В моем Java-коде используется набор функций Java Swing, которые все работают нормально, но как только команда try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) (с или без try/catch выдает мне эту ошибку.   -  person rdickens286    schedule 02.09.2020
comment
поделится вашим кодом.   -  person Abrar Ansari    schedule 03.09.2020
comment
Мой код теперь доступен   -  person rdickens286    schedule 03.09.2020
comment
Вам нужно запустить банку с полным путем к классам, иначе подобные библиотеки будут недоступны.   -  person Thorbjørn Ravn Andersen    schedule 03.09.2020
comment
@ ThorbjørnRavnAndersen, как мне это сделать, могу ли я установить путь к классам как переменную среды или мне следует использовать -cp каждый раз с очень длинным путем к классам   -  person rdickens286    schedule 03.09.2020
comment
Я также сталкиваюсь с точно такой же проблемой. Пожалуйста, предложите, если у кого есть идеи, как это исправить.   -  person Soumik Das    schedule 29.07.2021


Ответы (2)


Чтобы установить клиентскую библиотеку, перейдите по ссылке ниже

https://cloud.google.com/kms/docs/reference/libraries#installing_the_client_library

Если вы используете Maven, добавьте следующее в файл pom.xml.

    <dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>9.1.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-kms</artifactId>
  </dependency>
</dependencies>
person Pejvak    schedule 03.09.2020
comment
Не удалось добавить это в pom.xml, я все равно получаю ту же ошибку. - person rdickens286; 04.09.2020
comment
Я уже использовал это, но все равно не повезло - person Soumik Das; 29.07.2021

Я также столкнулся с этой проблемой.

Использовал приведенный ниже вариант, который решил мою проблему:

        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>google-cloud-kms</artifactId>
            <version>0.72.0-beta</version>
        </dependency>
person Soumik Das    schedule 29.07.2021