Отсутствующий основной атрибут в файле jar, файл MANIFEST.MF находится в папке META-INF - PullRequest
0 голосов
/ 05 июля 2018

Я не могу запустить созданный Maven файл JAR из командной строки. Использую команду ниже, чтобы выполнить мой файл JAR ElasticSearchUtility-1.0.0-SNAPSHOT.jar.

java -jar ElasticSearchUtility-1.0.0-SNAPSHOT.jar

Получаю следующее сообщение:

no main manifest attribute, in ElasticSearchUtility-1.0.0-SNAPSHOT.jar

У меня следующий файл Java

Document.java  (POJO Class)
DocumentIndex   (Main Class)

Я скомпилировал этот проект maven и сгенерировал файл .jar. Пока я выполняю этот .jar файл, он не выполняется.

Пожалуйста, найдите структуру моего проекта

enter image description here

Обновлено pom.xml

<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>ElasticSearchUtility</groupId>
<artifactId>ElasticSearchUtility</artifactId>
<version>1.0.0-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>6.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>6.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>rest</artifactId>
        <version>5.1.2</version>
    </dependency>

</dependencies>

<build>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>false</downloadJavadocs>
                </configuration>
            </plugin>

            <!-- Set a compiler level -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <!-- Make this jar executable -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>**/log4j.properties</exclude>
                    </excludes>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>ProjectJar.project.App</mainClass>
                            <classpathPrefix>dependency-jars/</classpathPrefix>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <!-- Copy project dependency -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.5.1</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <!-- exclude junit, we need runtime dependency only -->
                            <includeScope>runtime</includeScope>
                            <outputDirectory>${project.build.directory}/dependency-
                                jars/</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            </plugins>
    </build>
    </project>

Пожалуйста, найдите мой основной класс ниже.

открытый класс DocumentIndex {

private final static String INDEX = "documents_local";  //Documents Table with file Path - Source
private final static String ATTACHMENT = "document_attachment_dev"; // Documents with Attachment...  -- Destination //document_attachment//
private final static String TYPE = "doc";
private static final Logger logger = Logger.getLogger(Thread.currentThread().getStackTrace()[0].getClassName());

public static void main(String args[]) throws IOException {


    RestHighLevelClient restHighLevelClient = null;
    Document doc=new Document();

    logger.info("Started Indexing the Document.....");

    try {
        restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }


    //Fetching Id, FilePath & FileName from Document Index. 
    SearchRequest searchRequest = new SearchRequest(INDEX); 
    searchRequest.types(TYPE);
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    QueryBuilder qb = QueryBuilders.matchAllQuery();
    searchSourceBuilder.query(qb);
    searchSourceBuilder.size(3000);
    searchRequest.source(searchSourceBuilder);
    SearchResponse searchResponse = null;
    try {
         searchResponse = restHighLevelClient.search(searchRequest);
    } catch (IOException e) {
        e.getLocalizedMessage();
    }

    SearchHit[] searchHits = searchResponse.getHits().getHits();
    long totalHits=searchResponse.getHits().totalHits;
    logger.info("Total Hits --->"+totalHits);

    int line=1;

    Map<String, Object> jsonMap ;
    for (SearchHit hit : searchHits) {

        String encodedfile = null;
        File file=null;

        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        doc.setId((int) sourceAsMap.get("id"));
        doc.setApp_language(sourceAsMap.get("app_language").toString());

        String filepath=doc.getPath().concat(doc.getFilename());

        logger.info("Line Number--> "+line+++"ID---> "+doc.getId()+"File Path --->"+filepath);

        try(PrintWriter out = new PrintWriter(new FileOutputStream(new File("d:\\AllFilePath.txt"), true))  ){
            out.println("Line Number--> "+line+"ID---> "+doc.getId()+"File Path --->"+filepath);
        }

        file = new File(filepath);
        if(file.exists() && !file.isDirectory()) {
            try {
                  try(PrintWriter out = new PrintWriter(new FileOutputStream(new File("d:\\AvailableFile.txt"), true))  ){
                        out.println("Line Number--> "+line+++"ID---> "+doc.getId()+"File Path --->"+filepath);
                    }
                FileInputStream fileInputStreamReader = new FileInputStream(file);
                byte[] bytes = new byte[(int) file.length()];
                fileInputStreamReader.read(bytes);
                encodedfile = new String(Base64.getEncoder().encodeToString(bytes));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        jsonMap = new HashMap<>();
        jsonMap.put("id", doc.getId());
        jsonMap.put("app_language", doc.getApp_language());
        jsonMap.put("fileContent", encodedfile);

        String id=Long.toString(doc.getId());

        IndexRequest request = new IndexRequest(ATTACHMENT, "doc", id )
                .source(jsonMap)
                .setPipeline(ATTACHMENT);


        try {
            IndexResponse response = restHighLevelClient.index(request);
        } catch(ElasticsearchException e) {
            if (e.status() == RestStatus.CONFLICT) {
            }
            e.printStackTrace();
        }

        line++;

    }

    logger.info("Indexing done.....");


}

}

Я получаю ошибку ниже при компиляции моего pom.xml файла

Failed to execute goal org.apache.maven.plugins:maven-dependency-plugin:2.5.1:copy-dependencies (copy-dependencies) on project ElasticSearchUtility: Error copying artifact from C:\Users\10641516\.m2\repository\org\apache\lucene\lucene-sandbox\7.1.0\lucene-sandbox-7.1.0.jar to D:\Karthikeyan\ElasticSearch\ElasticSearch_Tesing\target\dependency-
    [ERROR] jars\lucene-sandbox-7.1.0.jar: The filename, directory name, or volume label syntax is incorrect

1 Ответ

0 голосов
/ 05 июля 2018

Вы добавили плагин компилятора, но не указали, какой класс является вашим основным классом. Вот почему вы получаете точную ошибку no main manifest attribute, так как компилятор не может ее найти. Поскольку основной класс служит точкой входа для вашего приложения, он не может быть запущен.

Чтобы решить эту проблему, добавьте ваш основной класс DocumentIndex в конфигурацию внутри pom.xml. Внутри тега конфигурации вашего плагина компилятора maven добавьте:

    <archive>
      <manifest>
        <addClasspath>true</addClasspath>
        <classpathPrefix>lib/</classpathPrefix>
        <mainClass>com.mypackage.DocumentIndex</mainClass>
      </manifest>
    </archive>

См. Также этот ответ .

...