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