summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/gui/window/ImagePublishedWindow.java
blob: b02b5cf7374f9f55ff3d04301e9c4a893af4a128 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package org.openslx.dozmod.gui.window;

import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.openslx.bwlp.thrift.iface.ImageSummaryRead;
import org.openslx.bwlp.thrift.iface.Organization;
import org.openslx.bwlp.thrift.iface.UserInfo;
import org.openslx.dozmod.Branding;
import org.openslx.dozmod.gui.Gui;
import org.openslx.dozmod.gui.MainWindow;
import org.openslx.dozmod.gui.control.table.ListTable.ListModel;
import org.openslx.dozmod.gui.helper.MessageType;
import org.openslx.dozmod.gui.helper.TextChangeListener;
import org.openslx.dozmod.gui.helper.UiFeedback;
import org.openslx.dozmod.gui.window.layout.ImagePublishedWindowLayout;
import org.openslx.dozmod.thrift.ImagePublishedDetailsActions;
import org.openslx.dozmod.thrift.Session;
import org.openslx.dozmod.thrift.ThriftActions;
import org.openslx.dozmod.thrift.ThriftActions.DownloadCallback;
import org.openslx.dozmod.thrift.ThriftError;
import org.openslx.dozmod.thrift.cache.ImagePublishedCache;
import org.openslx.dozmod.thrift.cache.OrganizationCache;
import org.openslx.dozmod.thrift.cache.UserCache;
import org.openslx.sat.thrift.version.Feature;
import org.openslx.thrifthelper.TConst;
import org.openslx.thrifthelper.ThriftManager;
import org.openslx.util.QuickTimer;
import org.openslx.util.QuickTimer.Task;

@SuppressWarnings("serial")
public class ImagePublishedWindow extends ImagePublishedWindowLayout implements UiFeedback, DownloadCallback {

	private final static Logger LOGGER = Logger.getLogger(ImagePublishedWindow.class);
	private final ImagePublishedWindow me = this;

	// Filtering: matches against image's name, user's first/last name or email and organisation name of the owner
	private Pattern searchFieldPattern = null;
	private final RowFilter<ListModel<ImageSummaryRead>, Integer> filterSearchTerm = new RowFilter<ListModel<ImageSummaryRead>, Integer>() {
		public boolean include(Entry<? extends ListModel<ImageSummaryRead>, ? extends Integer> entry) {
			// match against image names first
			ImageSummaryRead image = imagePublishedTable.getModelRow(entry.getIdentifier());
			if (searchFieldPattern.matcher(image.imageName).find())
				return true;
			// match against users
			UserInfo user = UserCache.find(image.ownerId);
			if (user == null)
				return false;
			if (searchFieldPattern.matcher(user.firstName).find())
				return true;
			if (searchFieldPattern.matcher(user.lastName).find())
				return true;
			if (searchFieldPattern.matcher(user.eMail).find())
				return true;
			// match against organizations
			Organization org = OrganizationCache.find(user);
			if (org == null)
				return false;
			if (searchFieldPattern.matcher(org.displayName).find())
				return true;
			return false;
		}
	};

	public ImagePublishedWindow(Frame modalParent) {
		super(modalParent);

		// Hook when user presses X (top right)
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				dispose();
			}
		});

		btnClose.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});

		btnSatDownload.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				ImageSummaryRead item = imagePublishedTable.getSelectedItem();
				if (item == null)
					return;
				String transferToken = null;
				try {
					transferToken = ThriftManager.getSatClient()
							.requestImageReplication(Session.getSatelliteToken(), item.latestVersionId);
				} catch (TException ex) {
					ThriftError.showMessage(me, LOGGER, ex, "Could not start download");
					return;
				}
				MainWindow.addPassiveTransfer(transferToken, item.imageName, false);
				Gui.showMessageBox(ImagePublishedWindow.this,
						"Die Übertragung läuft direkt zwischen Satellitenserver und"
								+ " dem " + Branding.getServiceName() + " Zentral-Server.\n"
								+ "Wenn Sie die " + Branding.getApplicationName() + " schließen, wird der Transfer trotzdem"
								+ "weiterlaufen.",
						MessageType.INFO, null, null);
			}
		});

		btnDownload.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				final ImageSummaryRead item = imagePublishedTable.getSelectedItem();
				if (item == null)
					return;
				btnDownload.setEnabled(false);
				ThriftActions.initDownload((JFrame) SwingUtilities.getWindowAncestor(me),
						item.latestVersionId, item.imageName, item.virtId, item.osId, item.fileSize, null);
			}
		});

		txtSearch.getDocument().addDocumentListener(new TextChangeListener() {
			@Override
			public void changed() {
				String str = txtSearch.getText();
				if (str == null || str.isEmpty()) {
					searchFieldPattern = null;
				} else {
					try {
						searchFieldPattern = Pattern.compile(str, Pattern.CASE_INSENSITIVE);
						txtSearch.setForeground(UIManager.getColor("TextField.foreground"));
					} catch (PatternSyntaxException ex) {
						txtSearch.setForeground(Color.RED);
					}
				}
				applyFilterOnTable();
			}
		});

		imagePublishedTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				ImageSummaryRead item = imagePublishedTable.getSelectedItem();
				updateAvailableOptions(item);
			}
		});

		imagePublishedTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
					ImageSummaryRead item = imagePublishedTable.getSelectedItem();
					if (item == null || item.getImageBaseId() == null)
						return;
					ImageDetailsWindow.open(JOptionPane.getFrameForComponent(ImagePublishedWindow.this),
							item.getImageBaseId(), null, new ImagePublishedDetailsActions(
									JOptionPane.getFrameForComponent(ImagePublishedWindow.this)));
				}
				processClick(e);
			}

			@Override
			public void mousePressed(MouseEvent e) {
				processClick(e);
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				processClick(e);
			}

			private void processClick(MouseEvent e) {
				// TODO popup menu?
			}
		});

		// init buttons state
		btnSatDownload.setVisible(Session.isImagePublishSupported());
		updateAvailableOptions(null);

		// init data
		refreshList(true, 0);
	}

	private void updateAvailableOptions(ImageSummaryRead item) {
		btnDownload.setEnabled(item != null);
		if (Session.isImagePublishSupported())
			btnSatDownload.setEnabled(item != null);
	}

	/**
	 * Called when a change occurs in the filter search field
	 */
	private void applyFilterOnTable() {
		// List for filters
		List<RowFilter<ListModel<ImageSummaryRead>, Integer>> filters = new ArrayList<>();

		// string for text in filter text field
		if (searchFieldPattern != null) {
			filters.add(filterSearchTerm);
		}

		// for using multiple filters if we need it one day
		RowFilter<ListModel<ImageSummaryRead>, Integer> andFilters = RowFilter.andFilter(filters);
		imagePublishedTable.getRowSorter().setRowFilter(andFilters);
	}

	/**
	 * Callback when download initialized
	 * 
	 * @param success
	 *            true if downloading, false otherwise
	 */
	@Override
	public void downloadInitialized(boolean success) {
		if (!success) {
			Gui.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnDownload.setEnabled(true);
				}
			});
		}
	}

	/**
	 * Refreshes the image list in the table
	 * 
	 * @param forceRefresh
	 *            true to force a refresh, false to use the cached list
	 */
	public void refreshList(final boolean forceRefresh, int delay) {
		QuickTimer.scheduleOnce(new Task() {
			@Override
			public void fire() {
				final List<ImageSummaryRead> imagePublishedList = ImagePublishedCache.get(forceRefresh);
				if (imagePublishedList == null)
					return;
				// 04.2018: Safety check to hide the non-vmware images from the list
				// in case they somehow manage to get published. Remove this when we
				// support publishing images from other hypervisors.
				if (Session.hasFeature(Feature.MULTIPLE_HYPERVISORS)) {
					for (Iterator<ImageSummaryRead> iter = imagePublishedList.listIterator(); iter
							.hasNext();) {
						ImageSummaryRead current = iter.next();
						if (current != null && !current.virtId.equals(TConst.VIRT_VMWARE)) {
							iter.remove();
						}
					}
				}
				Gui.asyncExec(new Runnable() {
					@Override
					public void run() {
						imagePublishedTable.setData(imagePublishedList, true);
					}
				});
			}
		}, delay);
	}

	/**
	 * Opens a new ImageDetailsWindow showing the details of the image with ID =
	 * imageBaseId
	 * 
	 * @param modalParent
	 *            parent of this window
	 * @param imageBaseId
	 *            id of the image to set the details of
	 */
	public static void open(Frame modalParent) {
		ImagePublishedWindow win = new ImagePublishedWindow(modalParent);
		win.setVisible(true);
	}

	/* *******************************************************************************
	 * 
	 * Dialog class overrides
	 * 
	 * **************************************************************************
	 * *****
	 */
	@SuppressWarnings("deprecation")
	@Override
	public void show() {
		if (!isVisible()) {
			pack();
			MainWindow.centerShell(this);
		}
		super.show();
	}

	@Override
	public boolean wantConfirmQuit() {
		return false;
	}

	@Override
	public void escapePressed() {
		dispose();
	}
}