addSucceededListener() is triggered before I upload the file.

Hello, community. I am new to Java and Vaadin in particular. Please explain to me why addSucceededListener() is triggered earlier (when loading a page) than I download a file?

@Route("")
public class UploadView extends VerticalLayout {
    @Autowired
    PictureRepository pictureRepository;

    @Autowired
    GoogleCloudAiAssistantRecognition googleCloudAiAssistantRecognition;

    public UploadView() throws IOException {
		this.pictureRepository = pictureRepository;
        this.googleCloudAiAssistantRecognition = googleCloudAiAssistantRecognition;
	
        add(new H1("Assistant recognition by Google Vision"));

        MemoryBuffer buffer = new MemoryBuffer();
        Upload upload = new Upload(buffer);
        upload.setAcceptedFileTypes("image/jpeg", "image/png", "image/gif");
        upload.setMaxFileSize(10485760);
        Div output = new Div();

        InputStream inputStream = buffer.getInputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream);

        upload.addSucceededListener(event -> {
            add(new H1(event.getMIMEType()));
            Component component = createComponent(event.getMIMEType(), event.getFileName(), buffer.getInputStream());
            showOutput(event.getFileName(), component, output);

            PictureModel pictureModel = new PictureModel(event.getFileName(), event.getMIMEType(), bytes);
            Long picId = pictureRepository.save(pictureModel).getId();

            List<TagModel> tags = null;
            try {
                tags = googleCloudAiAssistantRecognition.detect(picId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            pictureModel.setTagModel(tags);
            pictureRepository.save(pictureModel);
        });

        add(upload, output);
    }

    private Component createComponent(String mimeType, String fileName,
                                      InputStream stream) {
        if (mimeType.startsWith("text")) {
            return createTextComponent(stream);
        } else if (mimeType.startsWith("image")) {
            Image image = new Image();
            try {

                byte[] bytes = IOUtils.toByteArray(stream);
                image.getElement().setAttribute("src", new StreamResource(
                        fileName, () -> new ByteArrayInputStream(bytes)));
                try (ImageInputStream in = ImageIO.createImageInputStream(
                        new ByteArrayInputStream(bytes))) {
                    final Iterator<ImageReader> readers = ImageIO
                            .getImageReaders(in);
                    if (readers.hasNext()) {
                        ImageReader reader = readers.next();
                        try {
                            reader.setInput(in);
                            image.setWidth(reader.getWidth(0) + "px");
                            image.setHeight(reader.getHeight(0) + "px");
                        } finally {
                            reader.dispose();
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            return image;
        }
        Div content = new Div();
        String text = String.format("Mime type: '%s'\nSHA-256 hash: '%s'",
                mimeType, MessageDigestUtil.sha256(stream.toString()));
        content.setText(text);
        return content;

    }

    private Component createTextComponent(InputStream stream) {
        String text;
        try {
            text = IOUtils.toString(stream, StandardCharsets.UTF_8);
        } catch (IOException e) {
            text = "exception reading stream";
        }
        return new Text(text);
    }

    private void showOutput(String text, Component content,
                            HasComponents outputContainer) {
        HtmlComponent p = new HtmlComponent(Tag.P);
        p.getElement().setText(text);
        outputContainer.add(p);
        outputContainer.add(content);
    }
}

18461929.png

Looks like there’s already an answer to the same question on StackOverflow: https://stackoverflow.com/questions/64475277/addsucceededlistener-is-triggered-before-i-upload-the-file

Olli Tietäväinen:
Looks like there’s already an answer to the same question on StackOverflow: https://stackoverflow.com/questions/64475277/addsucceededlistener-is-triggered-before-i-upload-the-file

The problem is that many Listener listeners do not work in principle, all of them are executed before the file is loaded, even addFinishedListener(). I can see that I’m not alone in this problem, I found a workaround so far with upload.getElement().addEventListener(“upload-success” …

I also noticed that everything worked fine initially, until I started adding new Maven dependencies (I’m afraid I can’t say at what point I didn’t use git immediately).

[Link about this problem]
(https://github.com/vaadin/vaadin-upload-flow/issues/134)

UploadView.class

@Route("")
public class UploadView extends VerticalLayout {
    @Autowired
    PictureRepository pictureRepository;

    @Autowired
    GoogleCloudAiAssistantRecognition googleCloudAiAssistantRecognition;

    public UploadView() {
		this.pictureRepository = pictureRepository;
        this.googleCloudAiAssistantRecognition = googleCloudAiAssistantRecognition;
	
        MenuBar menuBar = new MenuBar();
        menuBar.addThemeVariants(MenuBarVariant.LUMO_PRIMARY);

        MenuItem resultsItem = menuBar.addItem("Get Results");
        MenuItem tagItem = menuBar.addItem("Edit Tag");

        resultsItem.addClickListener(e -> UI.getCurrent().navigate("ai-result"));
        tagItem.addClickListener(e -> UI.getCurrent().navigate("edit-tag"));

        add(menuBar, new H1("Assistant recognition by Google Vision"));

        MemoryBuffer buffer = new MemoryBuffer();
        Upload upload = new Upload(buffer);
        upload.setAcceptedFileTypes("image/jpeg", "image/png", "image/gif");
        upload.setMaxFileSize(10485760);
        Div output = new Div();

        upload.addFinishedListener(event -> {
            if (!upload.isUploading()) {
                InputStream inputStream = buffer.getInputStream();
                byte[] bytes = new byte[0]
;
                try {
                    bytes = IOUtils.toByteArray(inputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                add(new H1(event.getMIMEType()));
                Component component = createComponent(event.getMIMEType(), event.getFileName(), inputStream);
                showOutput(event.getFileName(), component, output);

                PictureModel pictureModel = new PictureModel(event.getFileName(), event.getMIMEType(), bytes);
                Long picId = pictureRepository.save(pictureModel).getId();

                List<TagModel> tags = null;
                try {
                    tags = googleCloudAiAssistantRecognition.detect(picId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                pictureModel.setTagModel(tags);
                pictureRepository.save(pictureModel);
            }
        });

/*        upload.getElement().addEventListener("upload-success", e -> {
            System.out.println(e.getEventData());
        });*/

        add(upload, output);
    }

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.prosvirnin</groupId>
    <artifactId>assistant-recognition</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>assistant-recognition</name>
    <description>Assistant recognition by Google Vision</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <repositories>
        <repository>
            <id>jcenter-snapshots</id>
            <name>jcenter</name>
            <url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
        </repository>
    </repositories>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

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

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>google-cloud-vision</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

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

        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

    <pluginRepositories>
        <pluginRepository>
            <id>pvsstudio-maven-repo</id>
            <url>http://files.viva64.com/java/pvsstudio-maven-repository/</url>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>com.pvsstudio</groupId>
                <artifactId>pvsstudio-maven-plugin</artifactId>
                <version>7.09.41421</version>
                <configuration>
                    <analyzer>
                        <outputType>text</outputType>
                        <outputFile>path/to/output.txt</outputFile>
                    </analyzer>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Olli Tietäväinen:
Looks like there’s already an answer to the same question on StackOverflow: https://stackoverflow.com/questions/64475277/addsucceededlistener-is-triggered-before-i-upload-the-file

[YouTube]
(https://youtu.be/Qmzqms_pvJo) This video will help you better understand the problem.

I guess the best way forward this point would be to try to reduce the problem to a minimum reproducible example and file the information to a GitHub ticket at https://github.com/vaadin/vaadin-flow-components/issues