001/**
002 * Copyright (C) 2006-2023 Talend Inc. - www.talend.com
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.talend.sdk.component.sample;
017
018import java.io.File;
019import java.io.FileNotFoundException;
020import java.io.IOException;
021import java.io.PrintStream;
022import java.io.Serializable;
023
024import javax.annotation.PostConstruct;
025import javax.annotation.PreDestroy;
026
027import org.talend.sdk.component.api.configuration.Option;
028import org.talend.sdk.component.api.processor.ElementListener;
029import org.talend.sdk.component.api.processor.Processor;
030
031@Processor(name = "writer")
032public class UserWriter implements Serializable {
033
034    private final File file;
035
036    private final FileService service;
037
038    private transient PrintStream writer;
039
040    public UserWriter(@Option("file") final File file, final FileService service) {
041        this.file = file;
042        this.service = service;
043    }
044
045    // tag::open[]
046    @PostConstruct
047    public void open() throws FileNotFoundException {
048        writer = service.createOutput(file);
049    }
050    // end::open[]
051
052    // tag::write[]
053    @ElementListener
054    public void write(final User user) throws IOException {
055        writer.println(user.getId() + ";" + user.getName());
056    }
057    // end::write[]
058
059    // tag::close[]
060    @PreDestroy
061    public void close() throws IOException {
062        if (writer != null) {
063            writer.close();
064        }
065    }
066    // end::close[]
067}