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