001
014
015 package com.liferay.portal.kernel.nio.intraband.welder.fifo;
016
017 import com.liferay.portal.kernel.nio.intraband.Intraband;
018 import com.liferay.portal.kernel.nio.intraband.RegistrationReference;
019 import com.liferay.portal.kernel.nio.intraband.welder.BaseWelder;
020
021 import java.io.File;
022 import java.io.FileInputStream;
023 import java.io.FileNotFoundException;
024 import java.io.FileOutputStream;
025 import java.io.IOException;
026
027 import java.nio.channels.FileChannel;
028
029 import java.util.concurrent.atomic.AtomicLong;
030
031
034 public class FIFOWelder extends BaseWelder {
035
036 public FIFOWelder() throws IOException {
037 String tempFolderName = System.getProperty("java.io.tmpdir");
038
039 long id = idCounter.getAndIncrement();
040
041 inputFIFOFile = new File(tempFolderName, "FIFO-INPUT-" + id);
042 outputFIFOFile = new File(tempFolderName, "FIFO-OUTPUT-" + id);
043
044 try {
045 FIFOUtil.createFIFO(inputFIFOFile);
046 FIFOUtil.createFIFO(outputFIFOFile);
047 }
048 catch (Exception e) {
049 throw new IOException(e);
050 }
051 }
052
053 @Override
054 protected void doDestroy() throws IOException {
055 readFileChannel.close();
056 writeFileChannel.close();
057 }
058
059 @Override
060 protected RegistrationReference weldClient(Intraband intraband)
061 throws IOException {
062
063
064
065 FileOutputStream fileOutputStream = new FileOutputStream(inputFIFOFile);
066
067 writeFileChannel = fileOutputStream.getChannel();
068
069 FileInputStream fileInputStream = new AutoRemoveFileInputStream(
070 outputFIFOFile);
071
072 readFileChannel = fileInputStream.getChannel();
073
074 return intraband.registerChannel(readFileChannel, writeFileChannel);
075 }
076
077 @Override
078 protected RegistrationReference weldServer(Intraband intraband)
079 throws IOException {
080
081
082
083 FileInputStream fileInputStream = new AutoRemoveFileInputStream(
084 inputFIFOFile);
085
086 readFileChannel = fileInputStream.getChannel();
087
088 FileOutputStream fileOutputStream = new FileOutputStream(
089 outputFIFOFile);
090
091 writeFileChannel = fileOutputStream.getChannel();
092
093 return intraband.registerChannel(readFileChannel, writeFileChannel);
094 }
095
096 protected static final AtomicLong idCounter = new AtomicLong(
097 System.currentTimeMillis());
098
099 protected final File inputFIFOFile;
100 protected final File outputFIFOFile;
101 protected transient FileChannel readFileChannel;
102 protected transient FileChannel writeFileChannel;
103
104 protected static class AutoRemoveFileInputStream extends FileInputStream {
105
106 public AutoRemoveFileInputStream(File file)
107 throws FileNotFoundException {
108
109 super(file);
110
111 _file = file;
112 }
113
114 @Override
115 public void close() throws IOException {
116 super.close();
117
118 if (!_file.delete()) {
119 _file.deleteOnExit();
120 }
121 }
122
123 private final File _file;
124
125 }
126
127 }