Ответы пользователя по тегу Java
  • Как правильно сделать возможность выбора базы данных при запуске приложения?

    @DS1977
    public class EntityManagerFactory {
    
        public static EntityManager get() {
            Map<String, Object> properties = new HashMap<>();
            properties.put("javax.persistence.jdbc.url", Config.DATABASE_URL);
            properties.put("javax.persistence.jdbc.driver", Config.DATABASE_DRIVER);
            properties.put("javax.persistence.jdbc.user", Config.DATABASE_USER);
            properties.put("javax.persistence.jdbc.password", Config.DATABASE_PWD);
            properties.put(PersistenceUnitProperties.WEAVING, "static");
            return new PersistenceProvider().createEntityManagerFactory("dbsource_pu", properties).createEntityManager();
        }
    }
    Ответ написан
    Комментировать
  • Как правильно собрать проект с зависимостями maven?

    @DS1977
    Или
    <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-shade-plugin</artifactId>
                            <version>2.3</version>
                            <configuration>
                                <createDependencyReducedPom>true</createDependencyReducedPom>
                                <filters>
                                    <filter>
                                        <artifact>*:*</artifact>
                                        <excludes>
                                            <exclude>META-INF/*.SF</exclude>
                                            <exclude>META-INF/*.DSA</exclude>
                                            <exclude>META-INF/*.RSA</exclude>
                                        </excludes>
                                    </filter>
                                </filters>
                            </configuration>
                            <executions>
                                <execution>
                                    <phase>package</phase>
                                    <goals>
                                        <goal>shade</goal>
                                    </goals>
                                    <configuration>
                                        <transformers>
                                            <transformer
                                                    implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                                            <transformer
                                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                                <mainClass>my.package.Starter</mainClass>
                                            </transformer>
                                        </transformers>
                                    </configuration>
                                </execution>
                            </executions>
                        </plugin>

    Ответ написан
    Комментировать
  • Как "переехать" на Liquibase?

    @DS1977
    В принципе у нас, в свое время, был такой же подход.
    На всякий случай упомяну:
    - Мы помнили что рано или поздно придется обновлять существующую(рабочую) базу данных, и не забывали о preconditions для каждого set'a
    - Мы написали тесты для миграции с помощью dunit, dbunit-rules и yandex postgresql-embedded
    Ответ написан
    Комментировать
  • Как выполнить настройку pom.xml с несколькими "родителями"?

    @DS1977
    Можно попробобать с bom

    Не самое простое решение, но другое мне не приходит в голову:
    bom-pom
    <project>
        <modelVersion>4.0.0</modelVersion>
        <groupId>ru.zeratustra</groupId>
        <artifactId>bom</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>pom</packaging>
     <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>ru.zeratustra</groupId>
                    <artifactId>parent1</artifactId>
                    <scope>import</scope>
                    <version>${parent1.version}</version>
                    <type>pom</type>
                </dependency>
                <dependency>
                    <groupId>ru.zeratustra</groupId>
                    <artifactId>parent2</artifactId>
                    <scope>import</scope>
                    <version>${parent2.version}</version>
                    <type>pom</type>
                </dependency>
           </dependencies>
     </dependencyManagement>
      </project>

    Ответ написан
  • Как написать Maven-плагин, который автоматизирует формирование архива с обновлением, в момент сборки проекта?

    @DS1977
    Не знаю правильно или нет, но я делаю так:
    1. Собираю все библиотеки в один jar:
    <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-shade-plugin</artifactId>
                            <version>2.3</version>
                            <configuration>
                                <createDependencyReducedPom>true</createDependencyReducedPom>
                                <filters>
                                    <filter>
                                        <artifact>*:*</artifact>
                                        <excludes>
                                            <exclude>META-INF/*.SF</exclude>
                                            <exclude>META-INF/*.DSA</exclude>
                                            <exclude>META-INF/*.RSA</exclude>
                                        </excludes>
                                    </filter>
                                </filters>
                            </configuration>
                            <executions>
                                <execution>
                                    <phase>package</phase>
                                    <goals>
                                        <goal>shade</goal>
                                    </goals>
                                    <configuration>
                                        <transformers>
                                            <transformer
                                                    implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                                            <transformer
                                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                                <mainClass>com.example.Main</mainClass>
                                            </transformer>
                                        </transformers>
                                    </configuration>
                                </execution>
                            </executions>
                        </plugin>

    2. Архивирую
    <plugin>
                            <artifactId>maven-assembly-plugin</artifactId>
                            <version>2.5.3</version>
                            <configuration>
                                <descriptor>src/main/assembly/dep.xml</descriptor>
                            </configuration>
                            <executions>
                                <execution>
                                    <id>create-archive</id>
                                    <phase>package</phase>
                                    <goals>
                                        <goal>single</goal>
                                    </goals>
                                </execution>
                            </executions>
                        </plugin>

    dep.xml
    <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
        <id>src</id>
        <formats>
            <format>tar.gz</format>
        </formats>
        <includeBaseDirectory>false</includeBaseDirectory>
        <fileSets>
            <fileSet>
                <directory>${project.basedir}</directory>
                <includes>
                    <include>README*</include>
                    <include>LICENSE*</include>
                    <include>NOTICE*</include>
                </includes>
                <useDefaultExcludes>true</useDefaultExcludes>
            </fileSet>
            <fileSet>
                <directory>${project.basedir}</directory>
                <outputDirectory>/</outputDirectory>
                <includes>
                    <include>config.properties</include>
                    <include>start.sh</include>
                    <include>start.bat</include>
                </includes>
            </fileSet>
        </fileSets>
        <files>
            <file>
                <outputDirectory>/</outputDirectory>
                <source>${project.build.directory}/myproject-${project.version}.jar</source>
                <destName>myproject.jar</destName>
            </file>
        </files>
    </assembly>


    3. Конфигурирую deployment:
    <plugin>
                            <artifactId>maven-deploy-plugin</artifactId>
                            <version>2.8.2</version>
                            <executions>
                                <execution>
                                    <id>deploy-binaries</id>
                                    <goals>
                                        <goal>deploy-file</goal>
                                    </goals>
                                    <configuration>
                                        <file>target/myproject-${project.version}-src.tar.gz</file>
                                        <repositoryId>repo</repositoryId>
                                        <artifactId>${project.artifactId}</artifactId>
                                        <groupId>${project.groupId}</groupId>
                                        <version>${project.version}</version>
                                        <packaging>tgz</packaging>
                                    </configuration>
                                </execution>
                            </executions>
                        </plugin>



    Прописать build-number в файл можно с ant-plugin:
    Смотреть тута
    Ответ написан
    Комментировать
  • Какая java ee sdk подойдет для разработки?

    @DS1977
    Вопрос не совсем ясен.

    JEE-API's и реализации добавляются в конкретные проекты самими разработчиками,
    как обычные библиотеки.
    Дальше писать не буду, информации по JEE более чем достаточно.
    Ответ написан
  • Golang cipher AES decrypt. Как раскодировать string закодированный на Java?

    @DS1977 Автор вопроса
    Мое решение

    Java
    public static String encryptGCM(String data) throws CryptException {
        try {
            SecureRandom random = SecureRandom.getInstanceStrong();
            byte[] iv = new byte[12];
            random.nextBytes(iv);
            log.trace("IV: {}", Arrays.toString(iv));
            Key key = generateGcmKey();
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            GCMParameterSpec spec = new GCMParameterSpec(128, iv);
            cipher.init(Cipher.ENCRYPT_MODE, key, spec);
            byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
            log.trace("encrypted: {}", Arrays.toString(cipherText));
            byte[] result = new byte[cipherText.length + iv.length];
            System.arraycopy(iv, 0, result, 0, iv.length);
            System.arraycopy(cipherText, 0, result, iv.length, cipherText.length);
            log.trace("Not encoded result: {}", Arrays.toString(result));
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception ex) {
            log.error("Failure occured while encrypt text value!", ex);
            throw new CryptException(data, ex);
        }
    }
    
    private static Key generateGcmKey() throws CryptException {
        try {
            SecretKey originalKey = new SecretKeySpec(KEY.getBytes(), 0, KEY.getBytes().length, ALGO);
            log.trace("Encoded key: {}", Base64.getEncoder().encodeToString(originalKey.getEncoded()));
            return originalKey;
        } catch (Exception ex) {
            log.error("Failure occured while generate key!", ex);
            throw new CryptException("Failure occured while generate key!", ex);
        }
    }

    GO
    func decode(data string) (string, error) {
      ciphertext, _ := base64.StdEncoding.DecodeString(data)
      key, _ := base64.URLEncoding.DecodeString(decodeKey)
      c, err := aes.NewCipher([]byte(key))
      if err != nil {
        return "", err
      }
    
      gcm, err := cipher.NewGCM(c)
      if err != nil {
        return "", err
      }
    
       nonceSize := 12
       if len(ciphertext) < nonceSize {
         return  "", errors.New("ciphertext too short")
       }
    
       nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
    
       result, err := gcm.Open(nil, nonce, ciphertext, nil)
       if err != nil {
         return "", err
       }
       return string(result), nil
     }

    Ответ написан
    Комментировать