ccf61fae85acc0cf065c303aab480c51da2cd3c5
[public/netxms.git] / src / java / netxms-eclipse / FileManager / src / org / netxms / ui / eclipse / filemanager / views / AgentFileManager.java
1 /**
2 * NetXMS - open source network management system
3 * Copyright (C) 2003-2015 Raden Solutions
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19 package org.netxms.ui.eclipse.filemanager.views;
20
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.net.URLEncoder;
28 import java.util.List;
29 import org.eclipse.core.runtime.IProgressMonitor;
30 import org.eclipse.jface.action.Action;
31 import org.eclipse.jface.action.GroupMarker;
32 import org.eclipse.jface.action.IMenuListener;
33 import org.eclipse.jface.action.IMenuManager;
34 import org.eclipse.jface.action.IToolBarManager;
35 import org.eclipse.jface.action.MenuManager;
36 import org.eclipse.jface.action.Separator;
37 import org.eclipse.jface.commands.ActionHandler;
38 import org.eclipse.jface.util.LocalSelectionTransfer;
39 import org.eclipse.jface.viewers.CellEditor;
40 import org.eclipse.jface.viewers.ColumnViewerEditor;
41 import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent;
42 import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy;
43 import org.eclipse.jface.viewers.ICellModifier;
44 import org.eclipse.jface.viewers.ISelectionChangedListener;
45 import org.eclipse.jface.viewers.IStructuredSelection;
46 import org.eclipse.jface.viewers.SelectionChangedEvent;
47 import org.eclipse.jface.viewers.TextCellEditor;
48 import org.eclipse.jface.viewers.TreeViewerEditor;
49 import org.eclipse.jface.viewers.ViewerDropAdapter;
50 import org.eclipse.jface.window.Window;
51 import org.eclipse.swt.SWT;
52 import org.eclipse.swt.dnd.DND;
53 import org.eclipse.swt.dnd.DragSourceAdapter;
54 import org.eclipse.swt.dnd.DragSourceEvent;
55 import org.eclipse.swt.dnd.Transfer;
56 import org.eclipse.swt.dnd.TransferData;
57 import org.eclipse.swt.events.DisposeEvent;
58 import org.eclipse.swt.events.DisposeListener;
59 import org.eclipse.swt.events.ModifyEvent;
60 import org.eclipse.swt.events.ModifyListener;
61 import org.eclipse.swt.layout.FormAttachment;
62 import org.eclipse.swt.layout.FormData;
63 import org.eclipse.swt.layout.FormLayout;
64 import org.eclipse.swt.widgets.Composite;
65 import org.eclipse.swt.widgets.FileDialog;
66 import org.eclipse.swt.widgets.Item;
67 import org.eclipse.swt.widgets.Menu;
68 import org.eclipse.ui.IActionBars;
69 import org.eclipse.ui.IViewSite;
70 import org.eclipse.ui.IWorkbenchActionConstants;
71 import org.eclipse.ui.IWorkbenchPage;
72 import org.eclipse.ui.IWorkbenchWindow;
73 import org.eclipse.ui.PartInitException;
74 import org.eclipse.ui.PlatformUI;
75 import org.eclipse.ui.contexts.IContextService;
76 import org.eclipse.ui.handlers.IHandlerService;
77 import org.eclipse.ui.part.ViewPart;
78 import org.netxms.client.AgentFile;
79 import org.netxms.client.NXCException;
80 import org.netxms.client.NXCSession;
81 import org.netxms.client.ProgressListener;
82 import org.netxms.client.server.ServerFile;
83 import org.netxms.ui.eclipse.actions.RefreshAction;
84 import org.netxms.ui.eclipse.console.resources.SharedIcons;
85 import org.netxms.ui.eclipse.filemanager.Activator;
86 import org.netxms.ui.eclipse.filemanager.Messages;
87 import org.netxms.ui.eclipse.filemanager.dialogs.CreateFolderDialog;
88 import org.netxms.ui.eclipse.filemanager.dialogs.StartClientToAgentFolderUploadDialog;
89 import org.netxms.ui.eclipse.filemanager.dialogs.StartClientToServerFileUploadDialog;
90 import org.netxms.ui.eclipse.filemanager.views.helpers.AgentFileComparator;
91 import org.netxms.ui.eclipse.filemanager.views.helpers.AgentFileFilter;
92 import org.netxms.ui.eclipse.filemanager.views.helpers.ServerFileLabelProvider;
93 import org.netxms.ui.eclipse.filemanager.views.helpers.ViewAgentFilesProvider;
94 import org.netxms.ui.eclipse.jobs.ConsoleJob;
95 import org.netxms.ui.eclipse.objecttools.views.FileViewer;
96 import org.netxms.ui.eclipse.shared.ConsoleSharedData;
97 import org.netxms.ui.eclipse.tools.MessageDialogHelper;
98 import org.netxms.ui.eclipse.tools.WidgetHelper;
99 import org.netxms.ui.eclipse.widgets.FilterText;
100 import org.netxms.ui.eclipse.widgets.SortableTableViewer;
101 import org.netxms.ui.eclipse.widgets.SortableTreeViewer;
102
103 /**
104 * Editor for server files
105 */
106 public class AgentFileManager extends ViewPart
107 {
108 public static final String ID = "org.netxms.ui.eclipse.filemanager.views.AgentFileManager"; //$NON-NLS-1$
109
110 private static final String TABLE_CONFIG_PREFIX = "AgentFileManager"; //$NON-NLS-1$
111
112 // Columns
113 public static final int COLUMN_NAME = 0;
114 public static final int COLUMN_TYPE = 1;
115 public static final int COLUMN_SIZE = 2;
116 public static final int COLUMN_MODIFYED = 3;
117
118 private boolean filterEnabled = false;
119 private Composite content;
120 private ServerFile[] files;
121 private AgentFileFilter filter;
122 private FilterText filterText;
123 private SortableTreeViewer viewer;
124 private NXCSession session;
125 private Action actionRefreshAll;
126 private Action actionUploadFile;
127 private Action actionUploadFolder;
128 private Action actionDelete;
129 private Action actionRename;
130 private Action actionRefreshDirectory;
131 private Action actionShowFilter;
132 private Action actionDownloadFile;
133 private Action actionTailFile;
134 private Action actionShowFile;
135 private Action actionCreateDirectory;
136 private long objectId = 0;
137
138 /*
139 * (non-Javadoc)
140 *
141 * @see org.eclipse.ui.part.ViewPart#init(org.eclipse.ui.IViewSite)
142 */
143 @Override
144 public void init(IViewSite site) throws PartInitException
145 {
146 super.init(site);
147
148 session = (NXCSession)ConsoleSharedData.getSession();
149 objectId = Long.parseLong(site.getSecondaryId());
150 setPartName(String.format(Messages.get().AgentFileManager_PartTitle, session.getObjectName(objectId)));
151 }
152
153 /*
154 * (non-Javadoc)
155 *
156 * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
157 */
158 @Override
159 public void createPartControl(Composite parent)
160 {
161 content = new Composite(parent, SWT.NONE);
162 content.setLayout(new FormLayout());
163
164 // Create filter area
165 filterText = new FilterText(content, SWT.NONE);
166 filterText.addModifyListener(new ModifyListener() {
167 @Override
168 public void modifyText(ModifyEvent e)
169 {
170 onFilterModify();
171 }
172 });
173 filterText.setCloseAction(new Action() {
174 @Override
175 public void run()
176 {
177 enableFilter(false);
178 }
179 });
180
181 final String[] columnNames = { Messages.get().AgentFileManager_ColName, Messages.get().AgentFileManager_ColType, Messages.get().AgentFileManager_ColSize, Messages.get().AgentFileManager_ColDate };
182 final int[] columnWidths = { 300, 120, 150, 150 };
183 viewer = new SortableTreeViewer(content, columnNames, columnWidths, 0, SWT.UP, SortableTableViewer.DEFAULT_STYLE);
184 WidgetHelper.restoreTreeViewerSettings(viewer, Activator.getDefault().getDialogSettings(), TABLE_CONFIG_PREFIX);
185 viewer.setContentProvider(new ViewAgentFilesProvider());
186 viewer.setLabelProvider(new ServerFileLabelProvider());
187 viewer.setComparator(new AgentFileComparator());
188 filter = new AgentFileFilter();
189 viewer.addFilter(filter);
190 viewer.addSelectionChangedListener(new ISelectionChangedListener() {
191 @Override
192 public void selectionChanged(SelectionChangedEvent event)
193 {
194 IStructuredSelection selection = (IStructuredSelection)event.getSelection();
195 if (selection != null)
196 {
197 actionDelete.setEnabled(selection.size() > 0);
198 }
199 }
200 });
201 viewer.getTree().addDisposeListener(new DisposeListener() {
202 @Override
203 public void widgetDisposed(DisposeEvent e)
204 {
205 WidgetHelper.saveTreeViewerSettings(viewer, Activator.getDefault().getDialogSettings(), TABLE_CONFIG_PREFIX);
206 }
207 });
208 enableDragSupport();
209 enableDropSupport();
210 enableInPlaceRename();
211
212 // Setup layout
213 FormData fd = new FormData();
214 fd.left = new FormAttachment(0, 0);
215 fd.top = new FormAttachment(filterText);
216 fd.right = new FormAttachment(100, 0);
217 fd.bottom = new FormAttachment(100, 0);
218 viewer.getTree().setLayoutData(fd);
219
220 fd = new FormData();
221 fd.left = new FormAttachment(0, 0);
222 fd.top = new FormAttachment(0, 0);
223 fd.right = new FormAttachment(100, 0);
224 filterText.setLayoutData(fd);
225
226 createActions();
227 contributeToActionBars();
228 createPopupMenu();
229 activateContext();
230
231 filterText.setCloseAction(actionShowFilter);
232
233 // Set initial focus to filter input line
234 if (filterEnabled)
235 filterText.setFocus();
236 else
237 enableFilter(false); // Will hide filter area correctly
238
239 refreshFileList();
240 }
241
242 /**
243 * Activate context
244 */
245 private void activateContext()
246 {
247 IContextService contextService = (IContextService)getSite().getService(IContextService.class);
248 if (contextService != null)
249 {
250 contextService.activateContext("org.netxms.ui.eclipse.filemanager.context.AgentFileManager"); //$NON-NLS-1$
251 }
252 }
253
254 /**
255 * Enable drag support in object tree
256 */
257 public void enableDragSupport()
258 {
259 Transfer[] transfers = new Transfer[] { LocalSelectionTransfer.getTransfer() };
260 viewer.addDragSupport(DND.DROP_COPY | DND.DROP_MOVE, transfers, new DragSourceAdapter() {
261 @Override
262 public void dragStart(DragSourceEvent event)
263 {
264 LocalSelectionTransfer.getTransfer().setSelection(viewer.getSelection());
265 event.doit = true;
266 }
267
268 @Override
269 public void dragSetData(DragSourceEvent event)
270 {
271 event.data = LocalSelectionTransfer.getTransfer().getSelection();
272 }
273 });
274 }
275
276 /**
277 * Enable drop support in object tree
278 */
279 public void enableDropSupport()// SubtreeType infrastructure
280 {
281 final Transfer[] transfers = new Transfer[] { LocalSelectionTransfer.getTransfer() };
282 viewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, transfers, new ViewerDropAdapter(viewer) {
283
284 @Override
285 public boolean performDrop(Object data)
286 {
287 IStructuredSelection selection = (IStructuredSelection)data;
288 List<?> movableSelection = selection.toList();
289 for(int i = 0; i < movableSelection.size(); i++)
290 {
291 ServerFile movableObject = (ServerFile)movableSelection.get(i);
292
293 moveFile((ServerFile)getCurrentTarget(), movableObject);
294
295 }
296 return true;
297 }
298
299 @Override
300 public boolean validateDrop(Object target, int operation, TransferData transferType)
301 {
302 if ((target == null) || !LocalSelectionTransfer.getTransfer().isSupportedType(transferType))
303 return false;
304
305 IStructuredSelection selection = (IStructuredSelection)LocalSelectionTransfer.getTransfer().getSelection();
306 if (selection.isEmpty())
307 return false;
308
309 for(final Object object : selection.toList())
310 {
311 if (!(object instanceof ServerFile))
312 return false;
313 }
314 if (!(target instanceof ServerFile))
315 {
316 return false;
317 }
318 else
319 {
320 if (!((ServerFile)target).isDirectory())
321 {
322 return false;
323 }
324 }
325 return true;
326 }
327 });
328 }
329
330 /**
331 * Enable in-place renames
332 */
333 private void enableInPlaceRename()
334 {
335 TreeViewerEditor.create(viewer, new ColumnViewerEditorActivationStrategy(viewer) {
336 @Override
337 protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event)
338 {
339 return event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
340 }
341 }, ColumnViewerEditor.DEFAULT);
342 viewer.setCellEditors(new CellEditor[] { new TextCellEditor(viewer.getTree()) });
343 viewer.setColumnProperties(new String[] { "name" }); //$NON-NLS-1$
344 viewer.setCellModifier(new ICellModifier() {
345 @Override
346 public void modify(Object element, String property, Object value)
347 {
348 if (element instanceof Item)
349 element = ((Item)element).getData();
350
351 if (property.equals("name")) //$NON-NLS-1$
352 {
353 if (element instanceof ServerFile)
354 {
355 doRename((ServerFile)element, value.toString());
356 }
357 }
358 }
359
360 @Override
361 public Object getValue(Object element, String property)
362 {
363 if (property.equals("name")) //$NON-NLS-1$
364 {
365 if (element instanceof ServerFile)
366 {
367 return ((ServerFile)element).getName();
368 }
369 }
370 return null;
371 }
372
373 @Override
374 public boolean canModify(Object element, String property)
375 {
376 return property.equals("name"); //$NON-NLS-1$
377 }
378 });
379 }
380
381 /**
382 * Do actual rename
383 *
384 * @param serverFile
385 * @param newName
386 */
387 private void doRename(final ServerFile serverFile, final String newName)
388 {
389 new ConsoleJob(Messages.get().ViewServerFile_DeletFileFromServerJob, this, Activator.PLUGIN_ID, Activator.PLUGIN_ID) {
390 @Override
391 protected String getErrorMessage()
392 {
393 return Messages.get().AgentFileManager_RenameError;
394 }
395
396 @Override
397 protected void runInternal(IProgressMonitor monitor) throws Exception
398 {
399 session.renameAgentFile(objectId, serverFile.getFullName(), serverFile.getParent().getFullName() + "/" + newName); //$NON-NLS-1$
400
401 runInUIThread(new Runnable() {
402 @Override
403 public void run()
404 {
405 serverFile.setName(newName);
406 viewer.refresh(serverFile, true);
407 }
408 });
409 }
410 }.start();
411 }
412
413 /**
414 * Create actions
415 */
416 private void createActions()
417 {
418 final IHandlerService handlerService = (IHandlerService)getSite().getService(IHandlerService.class);
419
420 actionRefreshDirectory = new Action(Messages.get().AgentFileManager_RefreshFolder, SharedIcons.REFRESH) {
421 @Override
422 public void run()
423 {
424 refreshFileOrDirectory();
425 }
426 };
427 actionRefreshDirectory.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.refreshFolder"); //$NON-NLS-1$
428 handlerService.activateHandler(actionRefreshDirectory.getActionDefinitionId(), new ActionHandler(actionRefreshDirectory));
429
430 actionRefreshAll = new RefreshAction(this) {
431 @Override
432 public void run()
433 {
434 refreshFileList();
435 }
436 };
437
438 actionUploadFile = new Action(Messages.get().AgentFileManager_UploadFile) {
439 @Override
440 public void run()
441 {
442 uploadFile();
443 }
444 };
445 actionUploadFile.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.uploadFile"); //$NON-NLS-1$
446 handlerService.activateHandler(actionUploadFile.getActionDefinitionId(), new ActionHandler(actionUploadFile));
447
448 actionUploadFolder = new Action(Messages.get().AgentFileManager_UploadFolder) {
449 @Override
450 public void run()
451 {
452 uploadFolder();
453 }
454 };
455
456 actionDelete = new Action(Messages.get().AgentFileManager_Delete, SharedIcons.DELETE_OBJECT) {
457 @Override
458 public void run()
459 {
460 deleteFile();
461 }
462 };
463 actionDelete.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.delete"); //$NON-NLS-1$
464 handlerService.activateHandler(actionDelete.getActionDefinitionId(), new ActionHandler(actionDelete));
465
466 actionRename = new Action(Messages.get().AgentFileManager_Rename) {
467 @Override
468 public void run()
469 {
470 renameFile();
471 }
472 };
473 actionRename.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.rename"); //$NON-NLS-1$
474 handlerService.activateHandler(actionRename.getActionDefinitionId(), new ActionHandler(actionRename));
475
476 actionShowFilter = new Action(Messages.get().ViewServerFile_ShowFilterAction, Action.AS_CHECK_BOX) {
477 @Override
478 public void run()
479 {
480 enableFilter(!filterEnabled);
481 actionShowFilter.setChecked(filterEnabled);
482 }
483 };
484 actionShowFilter.setChecked(filterEnabled);
485 actionShowFilter.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.showFilter"); //$NON-NLS-1$
486 handlerService.activateHandler(actionShowFilter.getActionDefinitionId(), new ActionHandler(actionShowFilter));
487
488 actionDownloadFile = new Action(Messages.get().AgentFileManager_Download) {
489 @Override
490 public void run()
491 {
492 startDownload();
493 }
494 };
495 actionDownloadFile.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.download"); //$NON-NLS-1$
496 handlerService.activateHandler(actionDownloadFile.getActionDefinitionId(), new ActionHandler(actionDownloadFile));
497
498 actionTailFile = new Action("Tail") {
499 @Override
500 public void run()
501 {
502 tailFile(true, 500);
503 }
504 };
505
506 actionShowFile = new Action(Messages.get().AgentFileManager_Show) {
507 @Override
508 public void run()
509 {
510 tailFile(false, 0);
511 }
512 };
513
514 actionCreateDirectory = new Action(Messages.get().AgentFileManager_CreateFolder) {
515 @Override
516 public void run()
517 {
518 createFolder();
519 }
520 };
521 actionCreateDirectory.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.newFolder"); //$NON-NLS-1$
522 handlerService.activateHandler(actionCreateDirectory.getActionDefinitionId(), new ActionHandler(actionCreateDirectory));
523 }
524
525 /**
526 * Contribute actions to action bar
527 */
528 private void contributeToActionBars()
529 {
530 IActionBars bars = getViewSite().getActionBars();
531 fillLocalPullDown(bars.getMenuManager());
532 fillLocalToolBar(bars.getToolBarManager());
533 }
534
535 /**
536 * Fill local pull-down menu
537 *
538 * @param manager Menu manager for pull-down menu
539 */
540 private void fillLocalPullDown(IMenuManager manager)
541 {
542 manager.add(actionShowFilter);
543 manager.add(new Separator());
544 manager.add(actionRefreshAll);
545 }
546
547 /**
548 * Fill local tool bar
549 *
550 * @param manager Menu manager for local tool bar
551 */
552 private void fillLocalToolBar(IToolBarManager manager)
553 {
554 manager.add(actionRefreshAll);
555 }
556
557 /**
558 * Create pop-up menu for user list
559 */
560 private void createPopupMenu()
561 {
562 // Create menu manager
563 MenuManager menuMgr = new MenuManager();
564 menuMgr.setRemoveAllWhenShown(true);
565 menuMgr.addMenuListener(new IMenuListener() {
566 public void menuAboutToShow(IMenuManager mgr)
567 {
568 fillContextMenu(mgr);
569 }
570 });
571
572 // Create menu
573 Menu menu = menuMgr.createContextMenu(viewer.getControl());
574 viewer.getControl().setMenu(menu);
575
576 // Register menu for extension.
577 getSite().registerContextMenu(menuMgr, viewer);
578 }
579
580 /**
581 * Fill context menu
582 *
583 * @param mgr Menu manager
584 */
585 protected void fillContextMenu(final IMenuManager mgr)
586 {
587 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
588 if (selection.isEmpty())
589 return;
590
591 if (selection.size() == 1)
592 {
593 if (((ServerFile)selection.getFirstElement()).isDirectory())
594 {
595 mgr.add(actionUploadFile);
596 mgr.add(actionUploadFolder);
597 }
598 else
599 {
600 mgr.add(actionTailFile);
601 mgr.add(actionShowFile);
602 }
603 mgr.add(actionDownloadFile);
604 mgr.add(new Separator());
605 }
606
607 if (selection.size() == 1)
608 {
609 if (((ServerFile)selection.getFirstElement()).isDirectory())
610 {
611 mgr.add(actionCreateDirectory);
612 }
613 mgr.add(actionRename);
614 }
615 mgr.add(actionDelete);
616 mgr.add(new Separator());
617 mgr.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
618 if ((selection.size() == 1) && ((ServerFile)selection.getFirstElement()).isDirectory())
619 {
620 mgr.add(new Separator());
621 mgr.add(actionRefreshDirectory);
622 }
623 }
624
625 /**
626 * Refresh file list
627 */
628 private void refreshFileList()
629 {
630 new ConsoleJob(Messages.get().SelectServerFileDialog_JobTitle, null, Activator.PLUGIN_ID, null) {
631 @Override
632 protected void runInternal(IProgressMonitor monitor) throws Exception
633 {
634 files = session.listAgentFiles(null, "/", objectId); //$NON-NLS-1$
635 runInUIThread(new Runnable() {
636 @Override
637 public void run()
638 {
639 viewer.setInput(files);
640 }
641 });
642 }
643
644 @Override
645 protected String getErrorMessage()
646 {
647 return Messages.get().SelectServerFileDialog_JobError;
648 }
649 }.start();
650 }
651
652 /**
653 * Refresh file list
654 */
655 private void refreshFileOrDirectory()
656 {
657 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
658 if (selection.isEmpty())
659 return;
660
661 final Object[] objects = selection.toArray();
662
663 new ConsoleJob(Messages.get().SelectServerFileDialog_JobTitle, null, Activator.PLUGIN_ID, null) {
664 @Override
665 protected void runInternal(IProgressMonitor monitor) throws Exception
666 {
667 for(int i = 0; i < objects.length; i++)
668 {
669 if (!((ServerFile)objects[i]).isDirectory())
670 objects[i] = ((ServerFile)objects[i]).getParent();
671
672 final ServerFile sf = ((ServerFile)objects[i]);
673 sf.setChildren(session.listAgentFiles(sf, sf.getFullName(), objectId));
674
675 runInUIThread(new Runnable() {
676 @Override
677 public void run()
678 {
679 viewer.refresh(sf);
680 }
681 });
682 }
683 }
684
685 @Override
686 protected String getErrorMessage()
687 {
688 return Messages.get().SelectServerFileDialog_JobError;
689 }
690 }.start();
691 }
692
693 /**
694 * Upload local file to agent
695 */
696 private void uploadFile()
697 {
698 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
699 if (selection.isEmpty())
700 return;
701
702 final Object[] objects = selection.toArray();
703 final ServerFile upladFolder = ((ServerFile)objects[0]).isDirectory() ? ((ServerFile)objects[0]) : ((ServerFile)objects[0])
704 .getParent();
705
706 final StartClientToServerFileUploadDialog dlg = new StartClientToServerFileUploadDialog(getSite().getShell());
707 if (dlg.open() == Window.OK)
708 {
709 final NXCSession session = (NXCSession)ConsoleSharedData.getSession();
710 new ConsoleJob(Messages.get().AgentFileManager_UploadFileJobTitle, null, Activator.PLUGIN_ID, null) {
711 @Override
712 protected void runInternal(final IProgressMonitor monitor) throws Exception
713 {
714 List<File> fileList = dlg.getLocalFiles();
715 for(int i = 0; i < fileList.size(); i++)
716 {
717 final File localFile = fileList.get(i);
718 String remoteFile = fileList.get(i).getName();
719 if(fileList.size() == 1)
720 remoteFile = dlg.getRemoteFileName();
721
722 session.uploadLocalFileToAgent(localFile, upladFolder.getFullName()+"/"+remoteFile, objectId, new ProgressListener() { //$NON-NLS-1$
723 private long prevWorkDone = 0;
724
725 @Override
726 public void setTotalWorkAmount(long workTotal)
727 {
728 monitor.beginTask(Messages.get().UploadFileToServer_TaskNamePrefix + localFile.getAbsolutePath(),
729 (int)workTotal);
730 }
731
732 @Override
733 public void markProgress(long workDone)
734 {
735 monitor.worked((int)(workDone - prevWorkDone));
736 prevWorkDone = workDone;
737 }
738 });
739 monitor.done();
740 }
741
742 upladFolder.setChildren(session.listAgentFiles(upladFolder, upladFolder.getFullName(), objectId));
743 runInUIThread(new Runnable() {
744 @Override
745 public void run()
746 {
747
748 viewer.refresh(upladFolder, true);
749 }
750 });
751 }
752
753 @Override
754 protected String getErrorMessage()
755 {
756 return Messages.get().UploadFileToServer_JobError;
757 }
758 }.start();
759 }
760 }
761
762 /**
763 * Upload local folder to agent
764 */
765 private void uploadFolder()
766 {
767 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
768 if (selection.isEmpty())
769 return;
770
771 final Object[] objects = selection.toArray();
772 final ServerFile upladFolder = ((ServerFile)objects[0]).isDirectory() ? ((ServerFile)objects[0]) : ((ServerFile)objects[0])
773 .getParent();
774
775 final StartClientToAgentFolderUploadDialog dlg = new StartClientToAgentFolderUploadDialog(getSite().getShell());
776 if (dlg.open() == Window.OK)
777 {
778 final NXCSession session = (NXCSession)ConsoleSharedData.getSession();
779 new ConsoleJob(Messages.get().AgentFileManager_UploadFolderJobTitle, null, Activator.PLUGIN_ID, null) {
780 @Override
781 protected void runInternal(final IProgressMonitor monitor) throws Exception
782 {
783 File folder = dlg.getLocalFile();
784 session.createFolderOnAgent(upladFolder.getFullName()+"/"+dlg.getRemoteFileName(), objectId); //$NON-NLS-1$
785 listFilesForFolder(folder, upladFolder.getFullName()+"/"+dlg.getRemoteFileName(), monitor); //$NON-NLS-1$
786
787 upladFolder.setChildren(session.listAgentFiles(upladFolder, upladFolder.getFullName(), objectId));
788 runInUIThread(new Runnable() {
789 @Override
790 public void run()
791 {
792 viewer.refresh(upladFolder, true);
793 }
794 });
795 }
796
797 @Override
798 protected String getErrorMessage()
799 {
800 return Messages.get().UploadFileToServer_JobError;
801 }
802 }.start();
803 }
804 }
805
806 /**
807 * Recursively uploads files to agent and creates correct folders
808 *
809 * @param folder
810 * @param upladFolder
811 * @param monitor
812 * @throws NXCException
813 * @throws IOException
814 */
815 public void listFilesForFolder(final File folder, final String upladFolder, final IProgressMonitor monitor) throws NXCException, IOException
816 {
817 for (final File fileEntry : folder.listFiles())
818 {
819 if (fileEntry.isDirectory())
820 {
821 session.createFolderOnAgent(upladFolder+"/"+fileEntry.getName(), objectId); //$NON-NLS-1$
822 listFilesForFolder(fileEntry, upladFolder+"/"+fileEntry.getName(), monitor); //$NON-NLS-1$
823 }
824 else
825 {
826 session.uploadLocalFileToAgent(fileEntry, upladFolder+"/"+fileEntry.getName(), objectId, new ProgressListener() { //$NON-NLS-1$
827 private long prevWorkDone = 0;
828
829 @Override
830 public void setTotalWorkAmount(long workTotal)
831 {
832 monitor.beginTask(Messages.get().UploadFileToServer_TaskNamePrefix + fileEntry.getAbsolutePath(),
833 (int)workTotal);
834 }
835
836 @Override
837 public void markProgress(long workDone)
838 {
839 monitor.worked((int)(workDone - prevWorkDone));
840 prevWorkDone = workDone;
841 }
842 });
843 monitor.done();
844 }
845 }
846 }
847
848 /**
849 * Delete selected file
850 */
851 private void deleteFile()
852 {
853 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
854 if (selection.isEmpty())
855 return;
856
857 if (!MessageDialogHelper.openConfirm(getSite().getShell(), Messages.get().ViewServerFile_DeleteConfirmation,
858 Messages.get().ViewServerFile_DeletAck))
859 return;
860
861 final Object[] objects = selection.toArray();
862 new ConsoleJob(Messages.get().ViewServerFile_DeletFileFromServerJob, this, Activator.PLUGIN_ID, Activator.PLUGIN_ID) {
863 @Override
864 protected String getErrorMessage()
865 {
866 return Messages.get().ViewServerFile_ErrorDeleteFileJob;
867 }
868
869 @Override
870 protected void runInternal(IProgressMonitor monitor) throws Exception
871 {
872 for(int i = 0; i < objects.length; i++)
873 {
874 final ServerFile sf = (ServerFile)objects[i];
875 session.deleteAgentFile(objectId, sf.getFullName());
876
877 runInUIThread(new Runnable() {
878 @Override
879 public void run()
880 {
881 sf.getParent().removeChield(sf);
882 viewer.refresh(sf.getParent());
883 }
884 });
885 }
886 }
887 }.start();
888 }
889
890 /**
891 * Starts file tail view&messages
892 */
893 private void tailFile(final boolean tail, final int offset)
894 {
895 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
896 if (selection.isEmpty())
897 return;
898
899 final Object[] objects = selection.toArray();
900
901 if (((ServerFile)objects[0]).isDirectory())
902 return;
903
904 final ServerFile sf = ((ServerFile)objects[0]);
905
906 ConsoleJob job = new ConsoleJob(Messages.get().AgentFileManager_DownloadJobTitle, null, Activator.PLUGIN_ID, null) {
907 @Override
908 protected String getErrorMessage()
909 {
910 return String.format(Messages.get().AgentFileManager_DownloadJobError, sf.getFullName(), objectId);
911 }
912
913 @Override
914 protected void runInternal(IProgressMonitor monitor) throws Exception
915 {
916 final AgentFile file = session.downloadFileFromAgent(objectId, sf.getFullName(), offset, tail);
917 runInUIThread(new Runnable() {
918 @Override
919 public void run()
920 {
921 final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
922 try
923 {
924 String secondaryId = Long.toString(objectId) + "&" + URLEncoder.encode(sf.getName(), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
925 FileViewer view = (FileViewer)window.getActivePage().showView(FileViewer.ID, secondaryId,
926 IWorkbenchPage.VIEW_ACTIVATE);
927 view.showFile(file.getFile(), tail, file.getId(), offset);
928 }
929 catch(Exception e)
930 {
931 MessageDialogHelper.openError(window.getShell(), Messages.get().AgentFileManager_Error,
932 String.format(Messages.get().AgentFileManager_OpenViewError, e.getLocalizedMessage()));
933 }
934 }
935 });
936 }
937 };
938 job.start();
939 }
940
941 /**
942 * Download file from agent
943 */
944 private void startDownload()
945 {
946 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
947 if (selection.size() != 1)
948 return;
949
950 final ServerFile sf = (ServerFile)selection.getFirstElement();
951
952 String selected;
953 do
954 {
955 FileDialog fd = new FileDialog(getSite().getShell(), SWT.SAVE);
956 fd.setText(Messages.get().AgentFileManager_StartDownloadDialogTitle);
957 String[] filterExtensions = { "*.*" }; //$NON-NLS-1$
958 fd.setFilterExtensions(filterExtensions);
959 String[] filterNames = { Messages.get().AgentFileManager_AllFiles };
960 fd.setFilterNames(filterNames);
961 fd.setFileName(sf.getName());
962 selected = fd.open();
963
964 if (selected == null)
965 return;
966 } while(selected.isEmpty());
967
968 if (!sf.isDirectory())
969 downloadFile(selected, sf.getFullName());
970
971 final String name = selected;
972 if (sf.isDirectory())
973 {
974 ConsoleJob job = new ConsoleJob(Messages.get().SelectServerFileDialog_JobTitle, null, Activator.PLUGIN_ID, null) {
975 @Override
976 protected void runInternal(IProgressMonitor monitor) throws Exception
977 {
978 downloadDir(sf, name);
979 }
980
981 @Override
982 protected String getErrorMessage()
983 {
984 return Messages.get().AgentFileManager_DirectoryReadError;
985 }
986 };
987 job.setUser(false);
988 job.start();
989 }
990 }
991
992 /**
993 * Recursively download directory from agent to local pc
994 *
995 * @param sf
996 * @param localFileName
997 * @throws IOException
998 * @throws NXCException
999 */
1000 private void downloadDir(final ServerFile sf, String localFileName) throws NXCException, IOException
1001 {
1002 File dir = new File(localFileName);
1003 dir.mkdir();
1004 ServerFile[] files = sf.getChildren();
1005 if(files == null)
1006 {
1007 files = session.listAgentFiles(sf, sf.getFullName(), sf.getNodeId());
1008 }
1009 for(int i = 0; i < files.length; i++)
1010 {
1011 if(files[i].isDirectory())
1012 {
1013 downloadDir(files[i], localFileName + "/" + sf.getName()); //$NON-NLS-1$
1014 }
1015 else
1016 {
1017 downloadFile(localFileName + "/" + files[i].getName(), files[i].getFullName()); //$NON-NLS-1$
1018 }
1019 }
1020 }
1021
1022 /**
1023 * Downloads file
1024 */
1025 private void downloadFile(final String localName, final String remoteName)
1026 {
1027 ConsoleJob job = new ConsoleJob(Messages.get().AgentFileManager_DownloadFileFromAgent, null, Activator.PLUGIN_ID, null) {
1028 @Override
1029 protected void runInternal(IProgressMonitor monitor) throws Exception
1030 {
1031 final AgentFile file = session.downloadFileFromAgent(objectId, remoteName, 0, false);
1032 File outputFile = new File(localName);
1033 outputFile.createNewFile();
1034 InputStream in = new FileInputStream(file.getFile());
1035 OutputStream out = new FileOutputStream(outputFile);
1036 byte[] buf = new byte[1024];
1037 int len;
1038 while((len = in.read(buf)) > 0)
1039 {
1040 out.write(buf, 0, len);
1041 }
1042 in.close();
1043 out.close();
1044 }
1045
1046 @Override
1047 protected String getErrorMessage()
1048 {
1049 return String.format(Messages.get().AgentFileManager_FileDownloadError, remoteName, session.getObjectName(objectId), objectId);
1050 }
1051 };
1052 job.start();
1053 }
1054
1055 /**
1056 * Rename selected file
1057 */
1058 private void renameFile()
1059 {
1060 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1061 if (selection.size() != 1)
1062 return;
1063
1064 viewer.editElement(selection.getFirstElement(), 0);
1065 }
1066
1067 /**
1068 * Move selected file
1069 */
1070 private void moveFile(final ServerFile target, final ServerFile object)
1071 {
1072 new ConsoleJob(Messages.get().AgentFileManager_MoveFile, this, Activator.PLUGIN_ID, Activator.PLUGIN_ID) {
1073 @Override
1074 protected String getErrorMessage()
1075 {
1076 return Messages.get().AgentFileManager_MoveError;
1077 }
1078
1079 @Override
1080 protected void runInternal(IProgressMonitor monitor) throws Exception
1081 {
1082 session.renameAgentFile(objectId, object.getFullName(), target.getFullName() + "/" + object.getName()); //$NON-NLS-1$
1083
1084 runInUIThread(new Runnable() {
1085 @Override
1086 public void run()
1087 {
1088 object.getParent().removeChield(object);
1089 viewer.refresh(object.getParent(), true);
1090 object.setParent(target);
1091 target.addChield(object);
1092 viewer.refresh(object.getParent(), true);
1093 }
1094 });
1095 }
1096 }.start();
1097 }
1098
1099 /**
1100 * Create new folder
1101 */
1102 private void createFolder()
1103 {
1104 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1105 if (selection.isEmpty())
1106 return;
1107
1108 final Object[] objects = selection.toArray();
1109 final ServerFile parentFolder = ((ServerFile)objects[0]).isDirectory() ? ((ServerFile)objects[0]) : ((ServerFile)objects[0])
1110 .getParent();
1111
1112 final CreateFolderDialog dlg = new CreateFolderDialog(getSite().getShell());
1113 if (dlg.open() != Window.OK)
1114 return;
1115
1116 final String newFolder = dlg.getNewName();
1117
1118 new ConsoleJob(Messages.get().AgentFileManager_CreatingFolder, this, Activator.PLUGIN_ID, Activator.PLUGIN_ID) {
1119 @Override
1120 protected String getErrorMessage()
1121 {
1122 return Messages.get().AgentFileManager_FolderCreationError;
1123 }
1124
1125 @Override
1126 protected void runInternal(IProgressMonitor monitor) throws Exception
1127 {
1128 session.createFolderOnAgent(parentFolder.getFullName() + "/" + newFolder, objectId); //$NON-NLS-1$
1129 parentFolder.setChildren(session.listAgentFiles(parentFolder, parentFolder.getFullName(), objectId));
1130
1131 runInUIThread(new Runnable() {
1132 @Override
1133 public void run()
1134 {
1135 viewer.refresh(parentFolder, true);
1136 }
1137 });
1138 }
1139 }.start();
1140 }
1141
1142 /*
1143 * (non-Javadoc)
1144 *
1145 * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
1146 */
1147 @Override
1148 public void setFocus()
1149 {
1150 viewer.getControl().setFocus();
1151 }
1152
1153 /**
1154 * Enable or disable filter
1155 *
1156 * @param enable New filter state
1157 */
1158 private void enableFilter(boolean enable)
1159 {
1160 filterEnabled = enable;
1161 filterText.setVisible(filterEnabled);
1162 FormData fd = (FormData)viewer.getTree().getLayoutData();
1163 fd.top = enable ? new FormAttachment(filterText) : new FormAttachment(0, 0);
1164 content.layout();
1165 if (enable)
1166 {
1167 filterText.setFocus();
1168 }
1169 else
1170 {
1171 filterText.setText(""); //$NON-NLS-1$
1172 onFilterModify();
1173 }
1174 }
1175
1176 /**
1177 * Handler for filter modification
1178 */
1179 private void onFilterModify()
1180 {
1181 final String text = filterText.getText();
1182 filter.setFilterString(text);
1183 viewer.refresh(false);
1184 }
1185 }