f01152fa26ff488bf1d763a29d29dd987010faf4
[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-2016 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.ArrayList;
29 import java.util.List;
30 import org.eclipse.core.runtime.IProgressMonitor;
31 import org.eclipse.jface.action.Action;
32 import org.eclipse.jface.action.GroupMarker;
33 import org.eclipse.jface.action.IMenuListener;
34 import org.eclipse.jface.action.IMenuManager;
35 import org.eclipse.jface.action.IToolBarManager;
36 import org.eclipse.jface.action.MenuManager;
37 import org.eclipse.jface.action.Separator;
38 import org.eclipse.jface.commands.ActionHandler;
39 import org.eclipse.jface.dialogs.IDialogSettings;
40 import org.eclipse.jface.util.LocalSelectionTransfer;
41 import org.eclipse.jface.viewers.CellEditor;
42 import org.eclipse.jface.viewers.ColumnViewerEditor;
43 import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent;
44 import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy;
45 import org.eclipse.jface.viewers.ICellModifier;
46 import org.eclipse.jface.viewers.ISelectionChangedListener;
47 import org.eclipse.jface.viewers.IStructuredSelection;
48 import org.eclipse.jface.viewers.SelectionChangedEvent;
49 import org.eclipse.jface.viewers.TextCellEditor;
50 import org.eclipse.jface.viewers.TreeViewerEditor;
51 import org.eclipse.jface.viewers.ViewerDropAdapter;
52 import org.eclipse.jface.window.Window;
53 import org.eclipse.swt.SWT;
54 import org.eclipse.swt.dnd.DND;
55 import org.eclipse.swt.dnd.DragSourceAdapter;
56 import org.eclipse.swt.dnd.DragSourceEvent;
57 import org.eclipse.swt.dnd.Transfer;
58 import org.eclipse.swt.dnd.TransferData;
59 import org.eclipse.swt.events.DisposeEvent;
60 import org.eclipse.swt.events.DisposeListener;
61 import org.eclipse.swt.events.ModifyEvent;
62 import org.eclipse.swt.events.ModifyListener;
63 import org.eclipse.swt.layout.FormAttachment;
64 import org.eclipse.swt.layout.FormData;
65 import org.eclipse.swt.layout.FormLayout;
66 import org.eclipse.swt.widgets.Composite;
67 import org.eclipse.swt.widgets.DirectoryDialog;
68 import org.eclipse.swt.widgets.Display;
69 import org.eclipse.swt.widgets.FileDialog;
70 import org.eclipse.swt.widgets.Item;
71 import org.eclipse.swt.widgets.Menu;
72 import org.eclipse.ui.IActionBars;
73 import org.eclipse.ui.IViewSite;
74 import org.eclipse.ui.IWorkbenchActionConstants;
75 import org.eclipse.ui.IWorkbenchPart;
76 import org.eclipse.ui.IWorkbenchWindow;
77 import org.eclipse.ui.PartInitException;
78 import org.eclipse.ui.PlatformUI;
79 import org.eclipse.ui.contexts.IContextService;
80 import org.eclipse.ui.handlers.IHandlerService;
81 import org.eclipse.ui.part.ViewPart;
82 import org.netxms.client.AgentFileData;
83 import org.netxms.client.NXCException;
84 import org.netxms.client.NXCSession;
85 import org.netxms.client.ProgressListener;
86 import org.netxms.client.constants.RCC;
87 import org.netxms.client.objects.Node;
88 import org.netxms.client.server.AgentFile;
89 import org.netxms.ui.eclipse.actions.RefreshAction;
90 import org.netxms.ui.eclipse.console.resources.SharedIcons;
91 import org.netxms.ui.eclipse.filemanager.Activator;
92 import org.netxms.ui.eclipse.filemanager.Messages;
93 import org.netxms.ui.eclipse.filemanager.dialogs.CreateFolderDialog;
94 import org.netxms.ui.eclipse.filemanager.dialogs.StartClientToAgentFolderUploadDialog;
95 import org.netxms.ui.eclipse.filemanager.dialogs.StartClientToServerFileUploadDialog;
96 import org.netxms.ui.eclipse.filemanager.views.helpers.AgentFileComparator;
97 import org.netxms.ui.eclipse.filemanager.views.helpers.AgentFileFilter;
98 import org.netxms.ui.eclipse.filemanager.views.helpers.AgentFileLabelProvider;
99 import org.netxms.ui.eclipse.filemanager.views.helpers.ViewAgentFilesProvider;
100 import org.netxms.ui.eclipse.jobs.ConsoleJob;
101 import org.netxms.ui.eclipse.shared.ConsoleSharedData;
102 import org.netxms.ui.eclipse.tools.DialogData;
103 import org.netxms.ui.eclipse.tools.MessageDialogHelper;
104 import org.netxms.ui.eclipse.tools.WidgetHelper;
105 import org.netxms.ui.eclipse.widgets.FilterText;
106 import org.netxms.ui.eclipse.widgets.SortableTableViewer;
107 import org.netxms.ui.eclipse.widgets.SortableTreeViewer;
108
109 /**
110 * File manager for agent files
111 */
112 public class AgentFileManager extends ViewPart
113 {
114 public static final String ID = "org.netxms.ui.eclipse.filemanager.views.AgentFileManager"; //$NON-NLS-1$
115
116 private static final String TABLE_CONFIG_PREFIX = "AgentFileManager"; //$NON-NLS-1$
117
118 // Columns
119 public static final int COLUMN_NAME = 0;
120 public static final int COLUMN_TYPE = 1;
121 public static final int COLUMN_SIZE = 2;
122 public static final int COLUMN_MODIFYED = 3;
123 public static final int COLUMN_OWNER = 4;
124 public static final int COLUMN_GROUP = 5;
125 public static final int COLUMN_ACCESS_RIGHTS = 6;
126
127 private boolean initShowFilter = true;
128 private Composite content;
129 private AgentFileFilter filter;
130 private FilterText filterText;
131 private SortableTreeViewer viewer;
132 private NXCSession session;
133 private Action actionRefreshAll;
134 private Action actionUploadFile;
135 private Action actionUploadFolder;
136 private Action actionDelete;
137 private Action actionRename;
138 private Action actionRefreshDirectory;
139 private Action actionShowFilter;
140 private Action actionDownloadFile;
141 private Action actionTailFile;
142 private Action actionShowFile;
143 private Action actionCreateDirectory;
144 private Action actionCalculateFolderSize;
145 private Action actionCopyFilePath;
146 private Action actionCopyFileName;
147 private long objectId = 0;
148
149 /*
150 * (non-Javadoc)
151 *
152 * @see org.eclipse.ui.part.ViewPart#init(org.eclipse.ui.IViewSite)
153 */
154 @Override
155 public void init(IViewSite site) throws PartInitException
156 {
157 super.init(site);
158
159 session = (NXCSession)ConsoleSharedData.getSession();
160 IDialogSettings settings = Activator.getDefault().getDialogSettings();
161 initShowFilter = safeCast(settings.get("AgentFileManager.showFilter"), settings.getBoolean("AgentFileManager.showFilter"), initShowFilter);
162 objectId = Long.parseLong(site.getSecondaryId());
163 setPartName(String.format(Messages.get().AgentFileManager_PartTitle, session.getObjectName(objectId)));
164 }
165
166 /**
167 * @param b
168 * @param defval
169 * @return
170 */
171 private static boolean safeCast(String s, boolean b, boolean defval)
172 {
173 return (s != null) ? b : defval;
174 }
175
176 /*
177 * (non-Javadoc)
178 *
179 * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
180 */
181 @Override
182 public void createPartControl(Composite parent)
183 {
184 content = new Composite(parent, SWT.NONE);
185 content.setLayout(new FormLayout());
186
187 // Create filter area
188 filterText = new FilterText(content, SWT.NONE);
189 filterText.addModifyListener(new ModifyListener() {
190 @Override
191 public void modifyText(ModifyEvent e)
192 {
193 onFilterModify();
194 }
195 });
196
197 String os = ((Node)session.findObjectById(objectId)).getSystemDescription(); //$NON-NLS-1$
198
199 if (os.contains("Windows")) //if OS is windows don't show group and access rights columns //$NON-NLS-1$
200 {
201 final String[] columnNames = { Messages.get().AgentFileManager_ColName, Messages.get().AgentFileManager_ColType, Messages.get().AgentFileManager_ColSize, Messages.get().AgentFileManager_ColDate, Messages.get().AgentFileManager_ColOwner };
202 final int[] columnWidths = { 300, 120, 150, 150, 150 };
203 viewer = new SortableTreeViewer(content, columnNames, columnWidths, 0, SWT.UP, SortableTableViewer.DEFAULT_STYLE);
204 }
205 else
206 {
207 final String[] columnNames = { Messages.get().AgentFileManager_ColName, Messages.get().AgentFileManager_ColType, Messages.get().AgentFileManager_ColSize, Messages.get().AgentFileManager_ColDate, Messages.get().AgentFileManager_ColOwner, Messages.get().AgentFileManager_ColGroup, Messages.get().AgentFileManager_ColAccessRights };
208 final int[] columnWidths = { 300, 120, 150, 150, 150, 150, 200 };
209 viewer = new SortableTreeViewer(content, columnNames, columnWidths, 0, SWT.UP, SortableTableViewer.DEFAULT_STYLE);
210 }
211
212 WidgetHelper.restoreTreeViewerSettings(viewer, Activator.getDefault().getDialogSettings(), TABLE_CONFIG_PREFIX);
213 viewer.setContentProvider(new ViewAgentFilesProvider());
214 viewer.setLabelProvider(new AgentFileLabelProvider());
215 viewer.setComparator(new AgentFileComparator());
216 filter = new AgentFileFilter();
217 viewer.addFilter(filter);
218 viewer.addSelectionChangedListener(new ISelectionChangedListener() {
219 @Override
220 public void selectionChanged(SelectionChangedEvent event)
221 {
222 IStructuredSelection selection = (IStructuredSelection)event.getSelection();
223 if (selection != null)
224 {
225 actionDelete.setEnabled(selection.size() > 0);
226 actionCalculateFolderSize.setEnabled(selection.size() > 0);
227 }
228 }
229 });
230 viewer.getTree().addDisposeListener(new DisposeListener() {
231 @Override
232 public void widgetDisposed(DisposeEvent e)
233 {
234 WidgetHelper.saveTreeViewerSettings(viewer, Activator.getDefault().getDialogSettings(), TABLE_CONFIG_PREFIX);
235 }
236 });
237 enableDragSupport();
238 enableDropSupport();
239 enableInPlaceRename();
240
241 // Setup layout
242 FormData fd = new FormData();
243 fd.left = new FormAttachment(0, 0);
244 fd.top = new FormAttachment(filterText);
245 fd.right = new FormAttachment(100, 0);
246 fd.bottom = new FormAttachment(100, 0);
247 viewer.getTree().setLayoutData(fd);
248
249 fd = new FormData();
250 fd.left = new FormAttachment(0, 0);
251 fd.top = new FormAttachment(0, 0);
252 fd.right = new FormAttachment(100, 0);
253 filterText.setLayoutData(fd);
254
255 createActions();
256 contributeToActionBars();
257 createPopupMenu();
258 activateContext();
259
260 filterText.setCloseAction(actionShowFilter);
261
262 // Set initial focus to filter input line
263 if (initShowFilter)
264 filterText.setFocus();
265 else
266 enableFilter(false); // Will hide filter area correctly
267
268 refreshFileList();
269 }
270
271 /* (non-Javadoc)
272 * @see org.eclipse.ui.part.WorkbenchPart#dispose()
273 */
274 @Override
275 public void dispose()
276 {
277 IDialogSettings settings = Activator.getDefault().getDialogSettings();
278 settings.put("AgentFileManager.showFilter", initShowFilter);
279 super.dispose();
280 }
281
282 /**
283 * Activate context
284 */
285 private void activateContext()
286 {
287 IContextService contextService = (IContextService)getSite().getService(IContextService.class);
288 if (contextService != null)
289 {
290 contextService.activateContext("org.netxms.ui.eclipse.filemanager.context.FileManager"); //$NON-NLS-1$
291 }
292 }
293
294 /**
295 * Enable drag support in object tree
296 */
297 public void enableDragSupport()
298 {
299 Transfer[] transfers = new Transfer[] { LocalSelectionTransfer.getTransfer() };
300 viewer.addDragSupport(DND.DROP_COPY | DND.DROP_MOVE, transfers, new DragSourceAdapter() {
301 @Override
302 public void dragStart(DragSourceEvent event)
303 {
304 LocalSelectionTransfer.getTransfer().setSelection(viewer.getSelection());
305 event.doit = true;
306 }
307
308 @Override
309 public void dragSetData(DragSourceEvent event)
310 {
311 event.data = LocalSelectionTransfer.getTransfer().getSelection();
312 }
313 });
314 }
315
316 /**
317 * Enable drop support in object tree
318 */
319 public void enableDropSupport()// SubtreeType infrastructure
320 {
321 final Transfer[] transfers = new Transfer[] { LocalSelectionTransfer.getTransfer() };
322 viewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, transfers, new ViewerDropAdapter(viewer) {
323
324 @Override
325 public boolean performDrop(Object data)
326 {
327 IStructuredSelection selection = (IStructuredSelection)data;
328 List<?> movableSelection = selection.toList();
329 for(int i = 0; i < movableSelection.size(); i++)
330 {
331 AgentFile movableObject = (AgentFile)movableSelection.get(i);
332
333 moveFile((AgentFile)getCurrentTarget(), movableObject);
334
335 }
336 return true;
337 }
338
339 @Override
340 public boolean validateDrop(Object target, int operation, TransferData transferType)
341 {
342 if ((target == null) || !LocalSelectionTransfer.getTransfer().isSupportedType(transferType))
343 return false;
344
345 IStructuredSelection selection = (IStructuredSelection)LocalSelectionTransfer.getTransfer().getSelection();
346 if (selection.isEmpty())
347 return false;
348
349 for(final Object object : selection.toList())
350 {
351 if (!(object instanceof AgentFile))
352 return false;
353 }
354 if (!(target instanceof AgentFile))
355 {
356 return false;
357 }
358 else
359 {
360 if (!((AgentFile)target).isDirectory())
361 {
362 return false;
363 }
364 }
365 return true;
366 }
367 });
368 }
369
370 /**
371 * Enable in-place renames
372 */
373 private void enableInPlaceRename()
374 {
375 TreeViewerEditor.create(viewer, new ColumnViewerEditorActivationStrategy(viewer) {
376 @Override
377 protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event)
378 {
379 return event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
380 }
381 }, ColumnViewerEditor.DEFAULT);
382 viewer.setCellEditors(new CellEditor[] { new TextCellEditor(viewer.getTree()) });
383 viewer.setColumnProperties(new String[] { "name" }); //$NON-NLS-1$
384 viewer.setCellModifier(new ICellModifier() {
385 @Override
386 public void modify(Object element, String property, Object value)
387 {
388 if (element instanceof Item)
389 element = ((Item)element).getData();
390
391 if (property.equals("name")) //$NON-NLS-1$
392 {
393 if (element instanceof AgentFile)
394 {
395 doRename((AgentFile)element, value.toString());
396 }
397 }
398 }
399
400 @Override
401 public Object getValue(Object element, String property)
402 {
403 if (property.equals("name")) //$NON-NLS-1$
404 {
405 if (element instanceof AgentFile)
406 {
407 return ((AgentFile)element).getName();
408 }
409 }
410 return null;
411 }
412
413 @Override
414 public boolean canModify(Object element, String property)
415 {
416 return property.equals("name"); //$NON-NLS-1$
417 }
418 });
419 }
420
421 /**
422 * Do actual rename
423 *
424 * @param AgentFile
425 * @param newName
426 */
427 private void doRename(final AgentFile agentFile, final String newName)
428 {
429 new ConsoleJob("Rename file", this, Activator.PLUGIN_ID, Activator.PLUGIN_ID) {
430 @Override
431 protected String getErrorMessage()
432 {
433 return Messages.get().AgentFileManager_RenameError;
434 }
435
436 @Override
437 protected void runInternal(IProgressMonitor monitor) throws Exception
438 {
439 final NestedVerifyOverwrite verify = new NestedVerifyOverwrite(agentFile.getType(), newName, true, true, false) {
440
441 @Override
442 public void executeAction() throws NXCException, IOException
443 {
444 session.renameAgentFile(objectId, agentFile.getFullName(), agentFile.getParent().getFullName() + "/" + newName, false); //$NON-NLS-1$
445 }
446
447 @Override
448 public void executeSameFunctionWithOverwrite() throws IOException, NXCException
449 {
450 session.renameAgentFile(objectId, agentFile.getFullName(), agentFile.getParent().getFullName() + "/" + newName, true); //$NON-NLS-1$
451 }
452 };
453 verify.run(viewer.getControl().getDisplay());
454
455 if(verify.isOkPressed())
456 {
457 runInUIThread(new Runnable() {
458 @Override
459 public void run()
460 {
461 if(verify.isOkPressed())
462 refreshFileOrDirectory();
463 agentFile.setName(newName);
464 viewer.refresh(agentFile, true);
465 }
466 });
467 }
468 }
469 }.start();
470 }
471
472 /**
473 * Create actions
474 */
475 private void createActions()
476 {
477 final IHandlerService handlerService = (IHandlerService)getSite().getService(IHandlerService.class);
478
479 actionRefreshDirectory = new Action(Messages.get().AgentFileManager_RefreshFolder, SharedIcons.REFRESH) {
480 @Override
481 public void run()
482 {
483 refreshFileOrDirectory();
484 }
485 };
486 actionRefreshDirectory.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.refreshFolder"); //$NON-NLS-1$
487 handlerService.activateHandler(actionRefreshDirectory.getActionDefinitionId(), new ActionHandler(actionRefreshDirectory));
488
489 actionRefreshAll = new RefreshAction(this) {
490 @Override
491 public void run()
492 {
493 refreshFileList();
494 }
495 };
496
497 actionUploadFile = new Action(Messages.get().AgentFileManager_UploadFile) {
498 @Override
499 public void run()
500 {
501 uploadFile(false);
502 }
503 };
504 actionUploadFile.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.uploadFile"); //$NON-NLS-1$
505 handlerService.activateHandler(actionUploadFile.getActionDefinitionId(), new ActionHandler(actionUploadFile));
506
507 actionUploadFolder = new Action(Messages.get().AgentFileManager_UploadFolder) {
508 @Override
509 public void run()
510 {
511 uploadFolder();
512 }
513 };
514
515 actionDelete = new Action(Messages.get().AgentFileManager_Delete, SharedIcons.DELETE_OBJECT) {
516 @Override
517 public void run()
518 {
519 deleteFile();
520 }
521 };
522 actionDelete.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.delete"); //$NON-NLS-1$
523 handlerService.activateHandler(actionDelete.getActionDefinitionId(), new ActionHandler(actionDelete));
524
525 actionRename = new Action(Messages.get().AgentFileManager_Rename) {
526 @Override
527 public void run()
528 {
529 renameFile();
530 }
531 };
532 actionRename.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.rename"); //$NON-NLS-1$
533 handlerService.activateHandler(actionRename.getActionDefinitionId(), new ActionHandler(actionRename));
534
535 actionShowFilter = new Action(Messages.get().ViewServerFile_ShowFilterAction, Action.AS_CHECK_BOX) {
536 @Override
537 public void run()
538 {
539 enableFilter(!initShowFilter);
540 actionShowFilter.setChecked(initShowFilter);
541 }
542 };
543 actionShowFilter.setChecked(initShowFilter);
544 actionShowFilter.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.showFilter"); //$NON-NLS-1$
545 handlerService.activateHandler(actionShowFilter.getActionDefinitionId(), new ActionHandler(actionShowFilter));
546
547 actionDownloadFile = new Action(Messages.get().AgentFileManager_Download) {
548 @Override
549 public void run()
550 {
551 startDownload();
552 }
553 };
554 actionDownloadFile.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.download"); //$NON-NLS-1$
555 handlerService.activateHandler(actionDownloadFile.getActionDefinitionId(), new ActionHandler(actionDownloadFile));
556
557 actionTailFile = new Action(Messages.get().AgentFileManager_FollowChanges) {
558 @Override
559 public void run()
560 {
561 tailFile(true, 1024);
562 }
563 };
564
565 actionShowFile = new Action(Messages.get().AgentFileManager_Show) {
566 @Override
567 public void run()
568 {
569 tailFile(false, 0);
570 }
571 };
572
573 actionCreateDirectory = new Action(Messages.get().AgentFileManager_CreateFolder) {
574 @Override
575 public void run()
576 {
577 createFolder();
578 }
579 };
580 actionCreateDirectory.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.newFolder"); //$NON-NLS-1$
581 handlerService.activateHandler(actionCreateDirectory.getActionDefinitionId(), new ActionHandler(actionCreateDirectory));
582
583 actionCalculateFolderSize = new Action("Calculate folder &size") {
584 @Override
585 public void run()
586 {
587 calculateFolderSize();
588 }
589 };
590 actionCalculateFolderSize.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.calculateFolderSize"); //$NON-NLS-1$
591 handlerService.activateHandler(actionCalculateFolderSize.getActionDefinitionId(), new ActionHandler(actionCalculateFolderSize));
592
593 actionCopyFileName = new Action("Copy file &name") {
594 @Override
595 public void run()
596 {
597 copyFileName();
598 }
599 };
600 actionCopyFileName.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.copyFileName"); //$NON-NLS-1$
601 handlerService.activateHandler(actionCopyFileName.getActionDefinitionId(), new ActionHandler(actionCopyFileName));
602
603 actionCopyFilePath = new Action("Copy file &path") {
604 @Override
605 public void run()
606 {
607 copyFilePath();
608 }
609 };
610 actionCopyFilePath.setActionDefinitionId("org.netxms.ui.eclipse.filemanager.commands.copyFilePath"); //$NON-NLS-1$
611 handlerService.activateHandler(actionCopyFilePath.getActionDefinitionId(), new ActionHandler(actionCopyFilePath));
612 }
613
614 /**
615 * Contribute actions to action bar
616 */
617 private void contributeToActionBars()
618 {
619 IActionBars bars = getViewSite().getActionBars();
620 fillLocalPullDown(bars.getMenuManager());
621 fillLocalToolBar(bars.getToolBarManager());
622 }
623
624 /**
625 * Fill local pull-down menu
626 *
627 * @param manager Menu manager for pull-down menu
628 */
629 private void fillLocalPullDown(IMenuManager manager)
630 {
631 manager.add(actionShowFilter);
632 manager.add(new Separator());
633 manager.add(actionRefreshAll);
634 }
635
636 /**
637 * Fill local tool bar
638 *
639 * @param manager Menu manager for local tool bar
640 */
641 private void fillLocalToolBar(IToolBarManager manager)
642 {
643 manager.add(actionRefreshAll);
644 }
645
646 /**
647 * Create pop-up menu for user list
648 */
649 private void createPopupMenu()
650 {
651 // Create menu manager
652 MenuManager menuMgr = new MenuManager();
653 menuMgr.setRemoveAllWhenShown(true);
654 menuMgr.addMenuListener(new IMenuListener() {
655 public void menuAboutToShow(IMenuManager mgr)
656 {
657 fillContextMenu(mgr);
658 }
659 });
660
661 // Create menu
662 Menu menu = menuMgr.createContextMenu(viewer.getControl());
663 viewer.getControl().setMenu(menu);
664
665 // Register menu for extension.
666 getSite().registerContextMenu(menuMgr, viewer);
667 }
668
669 /**
670 * Fill context menu
671 *
672 * @param mgr Menu manager
673 */
674 protected void fillContextMenu(final IMenuManager mgr)
675 {
676 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
677 if (selection.isEmpty())
678 return;
679
680 if (selection.size() == 1)
681 {
682 if (((AgentFile)selection.getFirstElement()).isDirectory())
683 {
684 mgr.add(actionUploadFile);
685 mgr.add(actionUploadFolder);
686 }
687 else
688 {
689 mgr.add(actionTailFile);
690 mgr.add(actionShowFile);
691 }
692 }
693
694 mgr.add(actionDownloadFile);
695
696 if (isFolderOnlySelection(selection))
697 mgr.add(actionCalculateFolderSize);
698 mgr.add(new Separator());
699
700 if (selection.size() == 1)
701 {
702 if (((AgentFile)selection.getFirstElement()).isDirectory())
703 {
704 mgr.add(actionCreateDirectory);
705 }
706 mgr.add(actionRename);
707 }
708 mgr.add(actionDelete);
709 mgr.add(new Separator());
710 if (selection.size() == 1)
711 {
712 mgr.add(actionCopyFileName);
713 mgr.add(actionCopyFilePath);
714 }
715 mgr.add(new Separator());
716 mgr.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
717 if ((selection.size() == 1) && ((AgentFile)selection.getFirstElement()).isDirectory())
718 {
719 mgr.add(new Separator());
720 mgr.add(actionRefreshDirectory);
721 }
722 }
723
724 /**
725 * Check if given selection contains only folders
726 *
727 * @param selection
728 * @return
729 */
730 private boolean isFolderOnlySelection(IStructuredSelection selection)
731 {
732 for(Object o : selection.toList())
733 if (!((AgentFile)o).isDirectory())
734 return false;
735 return true;
736 }
737
738 /**
739 * Refresh file list
740 */
741 private void refreshFileList()
742 {
743 new ConsoleJob(Messages.get().SelectServerFileDialog_JobTitle, null, Activator.PLUGIN_ID, null) {
744 @Override
745 protected void runInternal(IProgressMonitor monitor) throws Exception
746 {
747 final List<AgentFile> files = session.listAgentFiles(null, "/", objectId); //$NON-NLS-1$
748 runInUIThread(new Runnable() {
749 @Override
750 public void run()
751 {
752 viewer.setInput(files);
753 }
754 });
755 }
756
757 @Override
758 protected String getErrorMessage()
759 {
760 return Messages.get().SelectServerFileDialog_JobError;
761 }
762 }.start();
763 }
764
765 /**
766 * Refresh file list
767 */
768 private void refreshFileOrDirectory()
769 {
770 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
771 if (selection.isEmpty())
772 return;
773
774 final Object[] objects = selection.toArray();
775
776 new ConsoleJob("Reading remote directory", null, Activator.PLUGIN_ID, null) {
777 @Override
778 protected void runInternal(IProgressMonitor monitor) throws Exception
779 {
780 for(int i = 0; i < objects.length; i++)
781 {
782 if (!((AgentFile)objects[i]).isDirectory())
783 objects[i] = ((AgentFile)objects[i]).getParent();
784
785 final AgentFile sf = ((AgentFile)objects[i]);
786 sf.setChildren(session.listAgentFiles(sf, sf.getFullName(), objectId));
787
788 runInUIThread(new Runnable() {
789 @Override
790 public void run()
791 {
792 viewer.refresh(sf);
793 }
794 });
795 }
796 }
797
798 @Override
799 protected String getErrorMessage()
800 {
801 return "Cannot read remote directory";
802 }
803 }.start();
804 }
805
806 /**
807 * Upload local file to agent
808 */
809 private void uploadFile(final boolean overvrite)
810 {
811 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
812 if (selection.isEmpty())
813 return;
814
815 final Object[] objects = selection.toArray();
816 final AgentFile upladFolder = ((AgentFile)objects[0]).isDirectory() ? ((AgentFile)objects[0]) : ((AgentFile)objects[0])
817 .getParent();
818
819 final StartClientToServerFileUploadDialog dlg = new StartClientToServerFileUploadDialog(getSite().getShell());
820 if (dlg.open() == Window.OK)
821 {
822 final NXCSession session = (NXCSession)ConsoleSharedData.getSession();
823 new ConsoleJob(Messages.get().AgentFileManager_UploadFileJobTitle, null, Activator.PLUGIN_ID, null) {
824 @Override
825 protected void runInternal(final IProgressMonitor monitor) throws Exception
826 {
827 List<File> fileList = dlg.getLocalFiles();
828 for(int i = 0; i < fileList.size(); i++)
829 {
830 final File localFile = fileList.get(i);
831 String remoteFile = fileList.get(i).getName();
832 if(fileList.size() == 1)
833 remoteFile = dlg.getRemoteFileName();
834 final String rFileName = remoteFile;
835
836 new NestedVerifyOverwrite(localFile.isDirectory() ? AgentFile.DIRECTORY : AgentFile.FILE, localFile.getName(), true, true, false) {
837
838 @Override
839 public void executeAction() throws NXCException, IOException
840 {
841 session.uploadLocalFileToAgent(objectId, localFile, upladFolder.getFullName()+"/"+rFileName, overvrite, new ProgressListener() { //$NON-NLS-1$
842 private long prevWorkDone = 0;
843
844 @Override
845 public void setTotalWorkAmount(long workTotal)
846 {
847 monitor.beginTask(Messages.get().UploadFileToServer_TaskNamePrefix + localFile.getAbsolutePath(),
848 (int)workTotal);
849 }
850
851 @Override
852 public void markProgress(long workDone)
853 {
854 monitor.worked((int)(workDone - prevWorkDone));
855 prevWorkDone = workDone;
856 }
857 });
858 monitor.done();
859 }
860
861 @Override
862 public void executeSameFunctionWithOverwrite() throws IOException, NXCException
863 {
864 session.uploadLocalFileToAgent(objectId, localFile, upladFolder.getFullName()+"/"+rFileName, true, new ProgressListener() { //$NON-NLS-1$
865 private long prevWorkDone = 0;
866
867 @Override
868 public void setTotalWorkAmount(long workTotal)
869 {
870 monitor.beginTask(Messages.get().UploadFileToServer_TaskNamePrefix + localFile.getAbsolutePath(),
871 (int)workTotal);
872 }
873
874 @Override
875 public void markProgress(long workDone)
876 {
877 monitor.worked((int)(workDone - prevWorkDone));
878 prevWorkDone = workDone;
879 }
880 });
881 monitor.done();
882 }
883 }.run(viewer.getControl().getDisplay());
884 }
885
886 upladFolder.setChildren(session.listAgentFiles(upladFolder, upladFolder.getFullName(), objectId));
887 runInUIThread(new Runnable() {
888 @Override
889 public void run()
890 {
891
892 viewer.refresh(upladFolder, true);
893 }
894 });
895 }
896
897 @Override
898 protected String getErrorMessage()
899 {
900 return "Cannot upload file to remote agent";
901 }
902 }.start();
903 }
904 }
905
906 class UploadConsoleJob extends ConsoleJob
907 {
908 private boolean askFolderOverwrite;
909 private boolean askFileOverwrite;
910 private boolean overwrite;
911 private File folder;
912 private AgentFile uploadFolder;
913 private String remoteFileName;
914
915 public UploadConsoleJob(String name, IWorkbenchPart wbPart, String pluginId, Object jobFamily, File folder, final AgentFile uploadFolder, final String remoteFileName)
916 {
917 super(name, wbPart, pluginId, jobFamily);
918 askFolderOverwrite = true;
919 askFileOverwrite = true;
920 overwrite = false;
921 this.folder = folder;
922 this.uploadFolder = uploadFolder;
923 this.remoteFileName = remoteFileName;
924 }
925
926 @Override
927 protected void runInternal(IProgressMonitor monitor) throws Exception
928 {
929 NestedVerifyOverwrite verify = new NestedVerifyOverwrite(AgentFile.DIRECTORY, folder.getName(), askFolderOverwrite, askFileOverwrite, overwrite) {
930
931 @Override
932 public void executeAction() throws NXCException, IOException
933 {
934 session.createFolderOnAgent(objectId, uploadFolder.getFullName()+"/"+remoteFileName); //$NON-NLS-1$
935 }
936
937 @Override
938 public void executeSameFunctionWithOverwrite() throws NXCException, IOException
939 {
940 //do nothing
941 }
942 };
943 verify.run(viewer.getControl().getDisplay());
944 askFolderOverwrite = verify.askFolderOverwrite();
945
946 uploadFilesInFolder(folder, uploadFolder.getFullName()+"/"+remoteFileName, monitor); //$NON-NLS-1$
947
948 uploadFolder.setChildren(session.listAgentFiles(uploadFolder, uploadFolder.getFullName(), objectId));
949 runInUIThread(new Runnable() {
950 @Override
951 public void run()
952 {
953 viewer.refresh(uploadFolder, true);
954 }
955 });
956 }
957
958 @Override
959 protected String getErrorMessage()
960 {
961 return Messages.get().UploadFileToServer_JobError;
962 }
963
964 /**
965 * Recursively uploads files to agent and creates correct folders
966 *
967 * @param folder
968 * @param upladFolder
969 * @param monitor
970 * @throws NXCException
971 * @throws IOException
972 */
973 public void uploadFilesInFolder(final File folder, final String uploadFolder, final IProgressMonitor monitor) throws NXCException, IOException
974 {
975 for(final File fileEntry : folder.listFiles())
976 {
977 if (fileEntry.isDirectory())
978 {
979 NestedVerifyOverwrite verify = new NestedVerifyOverwrite(AgentFile.DIRECTORY, fileEntry.getName(), askFolderOverwrite, askFileOverwrite, overwrite) {
980
981 @Override
982 public void executeAction() throws NXCException, IOException
983 {
984 session.createFolderOnAgent(objectId, uploadFolder + "/" + fileEntry.getName()); //$NON-NLS-1$
985 }
986
987 @Override
988 public void executeSameFunctionWithOverwrite() throws NXCException, IOException
989 {
990 //do nothing
991 }
992 };
993 verify.run(viewer.getControl().getDisplay());
994 askFolderOverwrite = verify.askFolderOverwrite();
995
996 uploadFilesInFolder(fileEntry, uploadFolder + "/" + fileEntry.getName(), monitor); //$NON-NLS-1$
997 }
998 else
999 {
1000 NestedVerifyOverwrite verify = new NestedVerifyOverwrite(AgentFile.FILE, fileEntry.getName(), askFolderOverwrite, askFileOverwrite, overwrite) {
1001
1002 @Override
1003 public void executeAction() throws NXCException, IOException
1004 {
1005 session.uploadLocalFileToAgent(objectId, fileEntry, uploadFolder + "/" + fileEntry.getName(), overwrite, new ProgressListener() { //$NON-NLS-1$
1006 private long prevWorkDone = 0;
1007
1008 @Override
1009 public void setTotalWorkAmount(long workTotal)
1010 {
1011 monitor.beginTask(Messages.get().UploadFileToServer_TaskNamePrefix + fileEntry.getAbsolutePath(),
1012 (int)workTotal);
1013 }
1014
1015 @Override
1016 public void markProgress(long workDone)
1017 {
1018 monitor.worked((int)(workDone - prevWorkDone));
1019 prevWorkDone = workDone;
1020 }
1021 });
1022 monitor.done();
1023 }
1024
1025 @Override
1026 public void executeSameFunctionWithOverwrite() throws NXCException, IOException
1027 {
1028 session.uploadLocalFileToAgent(objectId, fileEntry, uploadFolder + "/" + fileEntry.getName(), true, new ProgressListener() { //$NON-NLS-1$
1029 private long prevWorkDone = 0;
1030
1031 @Override
1032 public void setTotalWorkAmount(long workTotal)
1033 {
1034 monitor.beginTask(Messages.get().UploadFileToServer_TaskNamePrefix + fileEntry.getAbsolutePath(),
1035 (int)workTotal);
1036 }
1037
1038 @Override
1039 public void markProgress(long workDone)
1040 {
1041 monitor.worked((int)(workDone - prevWorkDone));
1042 prevWorkDone = workDone;
1043 }
1044 });
1045 monitor.done();
1046 }
1047 };
1048 verify.run(viewer.getControl().getDisplay());
1049 askFileOverwrite = verify.askFileOverwrite();
1050 if(!askFileOverwrite)
1051 overwrite = verify.isOkPressed();
1052 }
1053 }
1054 }
1055 }
1056
1057 /**
1058 * Upload local folder to agent
1059 */
1060 private void uploadFolder()
1061 {
1062 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1063 if (selection.isEmpty())
1064 return;
1065
1066 final Object[] objects = selection.toArray();
1067 final AgentFile upladFolder = ((AgentFile)objects[0]).isDirectory() ? ((AgentFile)objects[0]) : ((AgentFile)objects[0])
1068 .getParent();
1069
1070 final StartClientToAgentFolderUploadDialog dlg = new StartClientToAgentFolderUploadDialog(getSite().getShell());
1071 if (dlg.open() == Window.OK)
1072 {
1073 ConsoleJob job = new UploadConsoleJob(Messages.get().AgentFileManager_UploadFolderJobTitle, null, Activator.PLUGIN_ID, null, dlg.getLocalFile(), upladFolder, dlg.getRemoteFileName());
1074 job.start();
1075 }
1076 }
1077
1078 /**
1079 * Delete selected file
1080 */
1081 private void deleteFile()
1082 {
1083 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1084 if (selection.isEmpty())
1085 return;
1086
1087 if (!MessageDialogHelper.openConfirm(getSite().getShell(), Messages.get().ViewServerFile_DeleteConfirmation,
1088 Messages.get().ViewServerFile_DeletAck))
1089 return;
1090
1091 final Object[] objects = selection.toArray();
1092 new ConsoleJob(Messages.get().ViewServerFile_DeletFileFromServerJob, this, Activator.PLUGIN_ID, Activator.PLUGIN_ID) {
1093 @Override
1094 protected String getErrorMessage()
1095 {
1096 return Messages.get().ViewServerFile_ErrorDeleteFileJob;
1097 }
1098
1099 @Override
1100 protected void runInternal(IProgressMonitor monitor) throws Exception
1101 {
1102 for(int i = 0; i < objects.length; i++)
1103 {
1104 final AgentFile sf = (AgentFile)objects[i];
1105 session.deleteAgentFile(objectId, sf.getFullName());
1106
1107 runInUIThread(new Runnable() {
1108 @Override
1109 public void run()
1110 {
1111 sf.getParent().removeChield(sf);
1112 viewer.refresh(sf.getParent());
1113 }
1114 });
1115 }
1116 }
1117 }.start();
1118 }
1119
1120 /**
1121 * Starts file tail
1122 */
1123 private void tailFile(final boolean followChanges, final int offset)
1124 {
1125 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1126 if (selection.isEmpty())
1127 return;
1128
1129 final Object[] objects = selection.toArray();
1130
1131 if (((AgentFile)objects[0]).isDirectory())
1132 return;
1133
1134 final AgentFile sf = ((AgentFile)objects[0]);
1135
1136 ConsoleJob job = new ConsoleJob(Messages.get().AgentFileManager_DownloadJobTitle, null, Activator.PLUGIN_ID, null) {
1137 @Override
1138 protected String getErrorMessage()
1139 {
1140 return String.format(Messages.get().AgentFileManager_DownloadJobError, sf.getFullName(), objectId);
1141 }
1142
1143 @Override
1144 protected void runInternal(final IProgressMonitor monitor) throws Exception
1145 {
1146 final AgentFileData file = session.downloadFileFromAgent(objectId, sf.getFullName(), offset, followChanges, null);
1147 runInUIThread(new Runnable() {
1148 @Override
1149 public void run()
1150 {
1151 try
1152 {
1153 String secondaryId = Long.toString(objectId) + "&" + URLEncoder.encode(sf.getName(), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
1154 AgentFileViewer.createView(secondaryId, objectId, file, followChanges);
1155 }
1156 catch(Exception e)
1157 {
1158 final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
1159 MessageDialogHelper.openError(window.getShell(), Messages.get().AgentFileManager_Error,
1160 String.format(Messages.get().AgentFileManager_OpenViewError, e.getLocalizedMessage()));
1161 Activator.logError("Exception in AgentFileManager.tailFile", e);
1162 }
1163 }
1164 });
1165 }
1166 };
1167 job.start();
1168 }
1169
1170 /**
1171 * Download file from agent
1172 */
1173 private void startDownload()
1174 {
1175 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1176 if (selection.isEmpty())
1177 return;
1178
1179 AgentFile sf = (AgentFile)selection.getFirstElement();
1180
1181 final String target;
1182 if (!sf.isDirectory() && (selection.size() == 1))
1183 {
1184 FileDialog dlg = new FileDialog(getSite().getShell(), SWT.SAVE);
1185 dlg.setText(Messages.get().AgentFileManager_StartDownloadDialogTitle);
1186 String[] filterExtensions = { "*.*" }; //$NON-NLS-1$
1187 dlg.setFilterExtensions(filterExtensions);
1188 String[] filterNames = { Messages.get().AgentFileManager_AllFiles };
1189 dlg.setFilterNames(filterNames);
1190 dlg.setFileName(sf.getName());
1191 dlg.setOverwrite(true);
1192 target = dlg.open();
1193 }
1194 else
1195 {
1196 DirectoryDialog dlg = new DirectoryDialog(getSite().getShell());
1197 target = dlg.open();
1198 }
1199
1200 if (target == null)
1201 return;
1202
1203 final List<AgentFile> files = new ArrayList<AgentFile>(selection.size());
1204 for(Object o : selection.toList())
1205 files.add((AgentFile)o);
1206
1207 ConsoleJob job = new ConsoleJob("Download from agent", null, Activator.PLUGIN_ID, null) {
1208 @Override
1209 protected void runInternal(IProgressMonitor monitor) throws Exception
1210 {
1211 if (files.size() == 1)
1212 {
1213 AgentFile f = files.get(0);
1214 if (f.isDirectory())
1215 {
1216 long dirSize = -1;
1217 try
1218 {
1219 dirSize = session.getAgentFileInfo(f).getSize();
1220 }
1221 catch(Exception e)
1222 {
1223 }
1224 monitor.beginTask(String.format("Downloading directory %s", f.getName()), (dirSize >= 0) ? (int)dirSize : IProgressMonitor.UNKNOWN);
1225 downloadDir(f, target + "/" + f.getName(), monitor);
1226 monitor.done();
1227 }
1228 else
1229 {
1230 downloadFile(f, target, monitor, false);
1231 }
1232 }
1233 else
1234 {
1235 long total = 0;
1236 for(AgentFile f : files)
1237 {
1238 if (f.isDirectory() && (f.getSize() < 0))
1239 {
1240 try
1241 {
1242 total += session.getAgentFileInfo(f).getSize();
1243 }
1244 catch(Exception e)
1245 {
1246 }
1247 }
1248 else
1249 {
1250 total += f.getSize();
1251 }
1252 }
1253
1254 monitor.beginTask("Downloading files", (int)total);
1255 for(AgentFile f : files)
1256 {
1257 if (f.isDirectory())
1258 {
1259 downloadDir(f, target + "/" + f.getName(), monitor);
1260 }
1261 else
1262 {
1263 downloadFile(f, target + "/" + f.getName(), monitor, true);
1264 }
1265 }
1266 monitor.done();
1267 }
1268 }
1269
1270 @Override
1271 protected String getErrorMessage()
1272 {
1273 return Messages.get().AgentFileManager_DirectoryReadError;
1274 }
1275 };
1276 job.start();
1277 }
1278
1279 /**
1280 * Recursively download directory from agent to local pc
1281 *
1282 * @param sf
1283 * @param localFileName
1284 * @throws IOException
1285 * @throws NXCException
1286 */
1287 private void downloadDir(final AgentFile sf, String localFileName, final IProgressMonitor monitor) throws NXCException, IOException
1288 {
1289 File dir = new File(localFileName);
1290 dir.mkdir();
1291 List<AgentFile> files = sf.getChildren();
1292 if (files == null)
1293 {
1294 files = session.listAgentFiles(sf, sf.getFullName(), sf.getNodeId());
1295 sf.setChildren(files);
1296 }
1297 for(AgentFile f : files)
1298 {
1299 if (f.isDirectory())
1300 {
1301 downloadDir(f, localFileName + "/" + f.getName(), monitor); //$NON-NLS-1$
1302 }
1303 else
1304 {
1305 downloadFile(f, localFileName + "/" + f.getName(), monitor, true); //$NON-NLS-1$
1306 }
1307 }
1308 dir.setLastModified(sf.getModifyicationTime().getTime());
1309 }
1310
1311 /**
1312 * Downloads file
1313 * @throws NXCException
1314 * @throws IOException
1315 */
1316 private void downloadFile(final AgentFile sf, final String localName, final IProgressMonitor monitor, final boolean subTask) throws IOException, NXCException
1317 {
1318 if (subTask)
1319 monitor.subTask(String.format("Downloading file %s", sf.getFullName()));
1320 final AgentFileData file = session.downloadFileFromAgent(objectId, sf.getFullName(), 0, false, new ProgressListener() {
1321 @Override
1322 public void setTotalWorkAmount(long workTotal)
1323 {
1324 if (!subTask)
1325 monitor.beginTask(String.format("Downloading file %s", sf.getFullName()), (int)workTotal);
1326 }
1327
1328 @Override
1329 public void markProgress(long workDone)
1330 {
1331 monitor.worked((int)workDone);
1332 }
1333 });
1334 File outputFile = new File(localName);
1335 outputFile.createNewFile();
1336 InputStream in = new FileInputStream(file.getFile());
1337 OutputStream out = new FileOutputStream(outputFile);
1338 byte[] buf = new byte[1024];
1339 int len;
1340 while((len = in.read(buf)) > 0)
1341 {
1342 out.write(buf, 0, len);
1343 }
1344 in.close();
1345 out.close();
1346 outputFile.setLastModified(sf.getModifyicationTime().getTime());
1347 }
1348
1349 /**
1350 * Rename selected file
1351 */
1352 private void renameFile()
1353 {
1354 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1355 if (selection.size() != 1)
1356 return;
1357
1358 viewer.editElement(selection.getFirstElement(), 0);
1359 }
1360
1361 /**
1362 * Move selected file
1363 */
1364 private void moveFile(final AgentFile target, final AgentFile object)
1365 {
1366 new ConsoleJob(Messages.get().AgentFileManager_MoveFile, this, Activator.PLUGIN_ID, Activator.PLUGIN_ID) {
1367 @Override
1368 protected String getErrorMessage()
1369 {
1370 return Messages.get().AgentFileManager_MoveError;
1371 }
1372
1373 @Override
1374 protected void runInternal(IProgressMonitor monitor) throws Exception
1375 {
1376 NestedVerifyOverwrite verify = new NestedVerifyOverwrite(object.getType(), object.getName(), true, true, false) {
1377
1378 @Override
1379 public void executeAction() throws NXCException, IOException
1380 {
1381 session.renameAgentFile(objectId, object.getFullName(), target.getFullName() + "/" + object.getName(), false); //$NON-NLS-1$
1382 }
1383
1384 @Override
1385 public void executeSameFunctionWithOverwrite() throws IOException, NXCException
1386 {
1387 session.renameAgentFile(objectId, object.getFullName(), target.getFullName() + "/" + object.getName(), true); //$NON-NLS-1$
1388 }
1389 };
1390 verify.run(viewer.getControl().getDisplay());
1391
1392 if(verify.isOkPressed())
1393 {
1394 runInUIThread(new Runnable() {
1395 @Override
1396 public void run()
1397 {
1398 object.getParent().removeChield(object);
1399 viewer.refresh(object.getParent(), true);
1400 object.setParent(target);
1401 target.addChield(object);
1402 viewer.refresh(object.getParent(), true);
1403 }
1404 });
1405 }
1406 }
1407 }.start();
1408 }
1409
1410 /**
1411 * Create new folder
1412 */
1413 private void createFolder()
1414 {
1415 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1416 if (selection.isEmpty())
1417 return;
1418
1419 final Object[] objects = selection.toArray();
1420 final AgentFile parentFolder = ((AgentFile)objects[0]).isDirectory() ? ((AgentFile)objects[0]) : ((AgentFile)objects[0])
1421 .getParent();
1422
1423 final CreateFolderDialog dlg = new CreateFolderDialog(getSite().getShell());
1424 if (dlg.open() != Window.OK)
1425 return;
1426
1427 final String newFolder = dlg.getNewName();
1428
1429 new ConsoleJob(Messages.get().AgentFileManager_CreatingFolder, this, Activator.PLUGIN_ID, Activator.PLUGIN_ID) {
1430 @Override
1431 protected String getErrorMessage()
1432 {
1433 return Messages.get().AgentFileManager_FolderCreationError;
1434 }
1435
1436 @Override
1437 protected void runInternal(IProgressMonitor monitor) throws Exception
1438 {
1439 NestedVerifyOverwrite verify = new NestedVerifyOverwrite(AgentFile.DIRECTORY, newFolder, true, true, false) {
1440
1441 @Override
1442 public void executeAction() throws NXCException, IOException
1443 {
1444 session.createFolderOnAgent(objectId, parentFolder.getFullName() + "/" + newFolder); //$NON-NLS-1$
1445 }
1446
1447 @Override
1448 public void executeSameFunctionWithOverwrite() throws IOException, NXCException
1449 {
1450 //do nothing
1451 }
1452 };
1453 verify.run(viewer.getControl().getDisplay());
1454 parentFolder.setChildren(session.listAgentFiles(parentFolder, parentFolder.getFullName(), objectId));
1455
1456 runInUIThread(new Runnable() {
1457 @Override
1458 public void run()
1459 {
1460 viewer.refresh(parentFolder, true);
1461 }
1462 });
1463 }
1464 }.start();
1465 }
1466
1467 /**
1468 * Show file size
1469 */
1470 private void calculateFolderSize()
1471 {
1472 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1473 if (selection.isEmpty())
1474 return;
1475
1476 final List<AgentFile> files = new ArrayList<AgentFile>(selection.size());
1477 for(Object o : selection.toList())
1478 files.add((AgentFile)o);
1479
1480 new ConsoleJob("Calculate folder size", this, Activator.PLUGIN_ID, null) {
1481 @Override
1482 protected void runInternal(IProgressMonitor monitor) throws Exception
1483 {
1484 for(AgentFile f : files)
1485 {
1486 f.setFileInfo(session.getAgentFileInfo(f));
1487 }
1488 runInUIThread(new Runnable() {
1489 @Override
1490 public void run()
1491 {
1492 viewer.update(files.toArray(), null);
1493 }
1494 });
1495 }
1496
1497 @Override
1498 protected String getErrorMessage()
1499 {
1500 return "Cannot calculate folder size";
1501 }
1502 }.start();
1503 }
1504
1505 /**
1506 * Copy name of file to clipboard
1507 */
1508 private void copyFileName()
1509 {
1510 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1511 if (selection.size() != 1)
1512 return;
1513
1514 WidgetHelper.copyToClipboard(((AgentFile)selection.getFirstElement()).getName());
1515 }
1516
1517 /**
1518 * Copy full path to file to clipboard
1519 */
1520 private void copyFilePath()
1521 {
1522 IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
1523 if (selection.size() != 1)
1524 return;
1525
1526 WidgetHelper.copyToClipboard(((AgentFile)selection.getFirstElement()).getFilePath());
1527 }
1528
1529 /*
1530 * (non-Javadoc)
1531 *
1532 * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
1533 */
1534 @Override
1535 public void setFocus()
1536 {
1537 viewer.getControl().setFocus();
1538 }
1539
1540 /**
1541 * Enable or disable filter
1542 *
1543 * @param enable New filter state
1544 */
1545 private void enableFilter(boolean enable)
1546 {
1547 initShowFilter = enable;
1548 filterText.setVisible(initShowFilter);
1549 FormData fd = (FormData)viewer.getTree().getLayoutData();
1550 fd.top = enable ? new FormAttachment(filterText) : new FormAttachment(0, 0);
1551 content.layout();
1552 if (enable)
1553 {
1554 filterText.setFocus();
1555 }
1556 else
1557 {
1558 filterText.setText(""); //$NON-NLS-1$
1559 onFilterModify();
1560 }
1561 }
1562
1563 /**
1564 * Handler for filter modification
1565 */
1566 private void onFilterModify()
1567 {
1568 final String text = filterText.getText();
1569 filter.setFilterString(text);
1570 viewer.refresh(false);
1571 }
1572
1573 /**
1574 * Nested class that check if file already exist and it should be overwritten
1575 *
1576 */
1577 abstract class NestedVerifyOverwrite
1578 {
1579 private boolean okPresseed;
1580 private int type;
1581 private String name;
1582 private boolean askFolderOverwrite;
1583 private boolean askFileOverwrite;
1584 private boolean overwrite;
1585
1586 public NestedVerifyOverwrite(int fileType, String fileName, boolean askFolderOverwrite, boolean askFileOverwrite, boolean overwrite)
1587 {
1588 type = fileType;
1589 name = fileName;
1590 this.askFolderOverwrite = askFolderOverwrite;
1591 this.askFileOverwrite = askFileOverwrite;
1592 this.overwrite = overwrite;
1593 okPresseed = true;
1594 }
1595
1596 public boolean askFolderOverwrite()
1597 {
1598 return askFolderOverwrite;
1599 }
1600
1601 public boolean askFileOverwrite()
1602 {
1603 return askFileOverwrite;
1604 }
1605
1606 public void run(Display disp) throws IOException, NXCException
1607 {
1608 try
1609 {
1610 executeAction();
1611 }
1612 catch(final NXCException e)
1613 {
1614 if(e.getErrorCode() == RCC.FOLDER_ALREADY_EXIST || type == AgentFile.DIRECTORY)
1615 {
1616 if(askFolderOverwrite)
1617 {
1618 disp.syncExec(new Runnable() {
1619 @Override
1620 public void run()
1621 {
1622 DialogData data = MessageDialogHelper.openOneButtonWarningWithCheckbox(getSite().getShell(),
1623 String.format("%s already exist", e.getErrorCode() == RCC.FOLDER_ALREADY_EXIST ? "Folder" : "File"),
1624 "Do not show again for this upload", String.format("%s %s already exist",e.getErrorCode() == RCC.FOLDER_ALREADY_EXIST ? "Folder" : "File", name));
1625 askFolderOverwrite = !data.getSaveSelection();
1626 okPresseed = false;
1627 }
1628 });
1629 }
1630 }
1631 else if(e.getErrorCode() == RCC.FILE_ALREADY_EXISTS || e.getErrorCode() == RCC.FOLDER_ALREADY_EXIST)
1632 {
1633 if(askFileOverwrite)
1634 {
1635 disp.syncExec(new Runnable() {
1636 @Override
1637 public void run()
1638 {
1639
1640 DialogData data = MessageDialogHelper.openWarningWithCheckbox(getSite().getShell(),
1641 String.format("%s overwrite confirmation", type == AgentFile.DIRECTORY ? "Folder" : "File"),
1642 "Save chose for current upload files",
1643 String.format("%s with %s name already exists. Are you sure you want to overwrite it?", e.getErrorCode() == RCC.FOLDER_ALREADY_EXIST ? "Folder" : "File", name));
1644 askFileOverwrite = !data.getSaveSelection();
1645 okPresseed = data.isOkPressed();
1646 }
1647 });
1648 if(okPresseed)
1649 executeSameFunctionWithOverwrite();
1650 }
1651 else
1652 {
1653 if(overwrite)
1654 {
1655 executeSameFunctionWithOverwrite();
1656 }
1657 }
1658 }
1659 else
1660 throw e;
1661 }
1662 }
1663 public boolean isOkPressed()
1664 {
1665 return okPresseed;
1666 }
1667 public abstract void executeAction() throws NXCException, IOException;
1668 public abstract void executeSameFunctionWithOverwrite() throws NXCException, IOException;
1669 }
1670 }