From 2fe12b9bbe43c20c4f7c4b46d9154f1a754a232b Mon Sep 17 00:00:00 2001 From: Francesco Mangiacrapa Date: Fri, 19 Feb 2016 14:59:23 +0000 Subject: [PATCH] updated tests git-svn-id: http://svn.d4science-ii.research-infrastructures.eu/gcube/trunk/portlets/user/workspace-tree-widget@124381 82a268e6-3cf1-43bd-a215-b396298e98cf --- .../client/AppControllerExplorer.java | 312 +++++++++--------- .../server/GWTWorkspaceServiceImpl.java | 32 -- .../server/shortener/UrlShortener.java | 131 ++++---- .../user/workspace/GoogleUrlShortener.java | 150 +++++---- .../portlets/user/workspace/UrlShortener.java | 230 +++++++++++++ .../user/workspace/UrlShortenerReaderRR.java | 59 ++-- 6 files changed, 564 insertions(+), 350 deletions(-) create mode 100644 src/test/java/org/gcube/portlets/user/workspace/UrlShortener.java diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/AppControllerExplorer.java b/src/main/java/org/gcube/portlets/user/workspace/client/AppControllerExplorer.java index 96f9656..158172d 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/AppControllerExplorer.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/AppControllerExplorer.java @@ -166,16 +166,16 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt public static final GWTWorkspaceServiceAsync rpcWorkspaceService = (GWTWorkspaceServiceAsync) GWT.create(GWTWorkspaceService.class); private ExplorerPanel explorerPanel; - + private final static HandlerManager eventBus = new HandlerManager(null); private HashMap> subscribers = null; - + private boolean selectRootItem; // private FileUploader fileUploader; public static String myLogin; public static String myLoginFirstName; - + private static AppControllerExplorer singleton; /** @@ -183,11 +183,11 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt */ public AppControllerExplorer() { Registry.register(ConstantsExplorer.RPC_WORKSPACE_SERVICE, rpcWorkspaceService); - subscribers = new HashMap>(); + subscribers = new HashMap>(); bind(); singleton = this; } - + /** * Gets the single instance of AppControllerExplorer. @@ -223,7 +223,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt private void bind() { eventBus.addHandler(UpdateWorkspaceSizeEvent.TYPE, new UpdateWorkspaceSizeEventHandler() { - + @Override public void onUpdateWorkspaceSize(UpdateWorkspaceSizeEvent updateWorkspaceSizeEvent) { doUpdateWorkspaceSize(updateWorkspaceSizeEvent); @@ -233,9 +233,9 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt eventBus.addHandler(RenderForm.TYPE, new RenderFormEventHandler() { @Override public void onRenderForm(RenderForm event) { - + } - }); + }); eventBus.addHandler(SendMessageEvent.TYPE, new SendMessageEventHandler() { @@ -245,7 +245,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt notifySubscriber(sendMessageEvent); } }); - + eventBus.addHandler(UnShareFolderEvent.TYPE,new UnShareFolderEventHandler() { @Override @@ -296,7 +296,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt }); } } - }); + }); } } @@ -310,22 +310,22 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt notifySubscriber(trashEvent); } }); - + eventBus.addHandler(AddAdministratorEvent.TYPE, new AddAdministratorEventHandler() { - + @Override public void onAddAdministrator(AddAdministratorEvent addAdministratorEvent) { - + final FileModel file = addAdministratorEvent.getSelectedFolder(); - + if(file==null || file.getIdentifier()==null) return; - + rpcWorkspaceService.getOwnerByItemId(file.getIdentifier(), new AsyncCallback() { @Override public void onFailure(Throwable caught) { - + if(caught instanceof SessionExpiredException){ GWT.log("Session expired"); eventBus.fireEvent(new SessionExpiredEvent()); @@ -344,28 +344,28 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt showAddAdministratorsDialog(file); else new MessageBoxAlert("Permission denied", "You have no permissions to manage administrators. You are not manager of \""+file.getName()+"\"", null); - + } }); } }); - - + + eventBus.addHandler(EditUserPermissionEvent.TYPE, new EditUserPermissionEventHandler() { - + @Override public void onEditUserPermission(EditUserPermissionEvent editUserPermissionEvent) { - + final FileModel file = editUserPermissionEvent.getSourceFolder(); - + if(file==null || file.getIdentifier()==null) return; - + rpcWorkspaceService.getOwnerByItemId(file.getIdentifier(), new AsyncCallback() { @Override public void onFailure(Throwable caught) { - + if(caught instanceof SessionExpiredException){ GWT.log("Session expired"); eventBus.fireEvent(new SessionExpiredEvent()); @@ -385,14 +385,14 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt ediPermissions(file); else new MessageBoxAlert("Permission denied", "You have no authority to manage user permissions. You are not manager of \""+file.getName()+"\"", null); - + } }); - + } }); - + eventBus.addHandler(GetInfoEvent.TYPE, new GetInfoEventHandler() { @Override @@ -415,7 +415,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt //DEBUG System.out.println("create shared folderEvent - sourceFileModel id "+sourceFileModel.getIdentifier()); - final FileModel parentFileModel= createSharedFolderEvent.getParentFileModel(); + final FileModel parentFileModel= createSharedFolderEvent.getParentFileModel(); final boolean isNewFolder = createSharedFolderEvent.isNewFolder(); DialogShareFolder dialogSharedFolder = null; String parentDirectoryName = null; @@ -461,7 +461,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } else{ - fileModel = finalDialog.getParentFolder(); //add user for share + fileModel = finalDialog.getParentFolder(); //add user for share //create a lowest object to send to server fileModel = new FileModel(fileModel.getIdentifier(), fileModel.getName(), fileModel.getParentFileModel(), fileModel.isDirectory(), fileModel.isShared()); @@ -474,15 +474,15 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt System.out.println("FileModel id "+fileModel.getIdentifier() + " name: "+fileModel.getName() + " parent " + fileModel.getParentFileModel()); for(InfoContactModel contact:finalDialog.getSharedListUsers() ){ System.out.println("Share with Contact "+contact) ; - + }*/ System.out.println("ACL is "+finalDialog.getSelectedACL()); - - + + Info.display("Info", "An operation of sharing was submitted"); explorerPanel.mask("Setting permissions", ConstantsExplorer.LOADINGSTYLE); - + rpcWorkspaceService.shareFolder(fileModel, finalDialog.getSharedListUsers(), isNewFolder, finalDialog.getSelectedACL(), new AsyncCallback() { @Override @@ -510,9 +510,9 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt parentToRefresh = parentFileModel; GWT.log("share completed throwing refresh folder : "+parentToRefresh.getName() +" get id: "+parentToRefresh.getIdentifier()); - + // eventBus.fireEvent(new RefreshFolderEvent(parentToRefresh, true, false, false)); - + //TODO UPDATED ID RefreshFolderEvent refEvent = new RefreshFolderEvent(parentToRefresh, true, true, false); refEvent.setForceReloadBreadCrumb(true); @@ -524,7 +524,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } } - }); + }); } else{//ITEM IS NOT SHAREABLE @@ -628,7 +628,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onRefreshItem(RefreshFolderEvent refreshItemEvent) { - + GWT.log("RefreshFolderEvent: "+refreshItemEvent); if(refreshItemEvent.getFolderTarget()!=null){ @@ -691,17 +691,17 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt if(pasteItemEvent.getIds()==null) return; - + Info.display("Info", "Paste working..."); switch(pasteItemEvent.getOperationType()){ - + case CUT: - + //TODO remove this comments // if(pasteItemEvent.getFolderSourceId()==null || pasteItemEvent.getFolderSourceId().isEmpty()) // return; - + rpcWorkspaceService.moveItems(pasteItemEvent.getIds(), pasteItemEvent.getFolderDestinationId(), new AsyncCallback() { public void onFailure(Throwable caught) { @@ -720,27 +720,27 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onSuccess(Boolean result) { - + FileModel fileInTree = explorerPanel.getAsycTreePanel().getFileModelByIdentifier(pasteItemEvent.getFolderDestinationId()); - + if(result){ - eventBus.fireEvent(new RefreshFolderEvent(fileInTree, false, false, false)); + eventBus.fireEvent(new RefreshFolderEvent(fileInTree, false, false, false)); //explorerPanel.getAsycTreePanel().setExpandTreeLevel(event.getTargetParentFileModel(), true); //Expand level drop } - + if(fileInTree!=null) pasteItemEvent.setTreeRefreshable(true); else pasteItemEvent.setTreeRefreshable(false); - + notifySubscriber(pasteItemEvent); } }); - + break; - - case COPY: - + + case COPY: + rpcWorkspaceService.copyItems(pasteItemEvent.getIds(), pasteItemEvent.getFolderDestinationId(), new AsyncCallback() { @Override @@ -753,9 +753,9 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } new MessageBoxAlert("Error", caught.getMessage(), null); - + eventBus.fireEvent(new RefreshFolderEvent(explorerPanel.getAsycTreePanel().getFileModelByIdentifier(pasteItemEvent.getFolderDestinationId()), false, true, false)); - + notifySubscriber(pasteItemEvent); } @@ -770,16 +770,16 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt pasteItemEvent.setTreeRefreshable(true); else pasteItemEvent.setTreeRefreshable(false); - + notifySubscriber(pasteItemEvent); } }); - + break; - + default: - + } } }); @@ -896,7 +896,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt // } // else // com.google.gwt.user.client.Window.open(ConstantsExplorer.DOWNLOAD_WORKSPACE_SERVICE+"?id="+fileDownloadEvent.getItemIdentifier(), "_self", ""); - // + // if(fileDownloadEvent.getDownloadType().equals(DownloadType.SHOW)){ if(fileDownloadEvent.getItemName()!= null){ @@ -953,26 +953,26 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt caption+= "File/s"; upType = UPLOAD_TYPE.File; } - + caption+= " in: "+folder.getName(); - + MultipleDilaogUpload uploadStream = new MultipleDilaogUpload(caption, folder.getIdentifier(), upType); WorskpaceUploadNotificationListener listener = new WorskpaceUploadNotificationListener() { - + @Override public void onUploadCompleted(String parentId, String itemId) { GWT.log("Upload completed: [parentID: "+parentId+", itemId: "+itemId+", uploadType: "+fileUploadEvent.getUploadType()+"]"); eventBus.fireEvent(new CompletedFileUploadEvent(parentId, itemId, fileUploadEvent.getUploadType(), false)); } - + @Override public void onUploadAborted(String parentId, String itemId) { GWT.log("Upload Aborted: [parentID: "+parentId+", itemId: "+itemId+"]"); } - + @Override public void onError(String parentId, String itemId, Throwable throwable) { - GWT.log("Upload Error: [parentID: "+parentId+", itemId: "+itemId+"]"); + GWT.log("Upload Error: [parentID: "+parentId+", itemId: "+itemId+"]"); } @Override @@ -981,7 +981,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt eventBus.fireEvent(new CompletedFileUploadEvent(parentId, itemId, fileUploadEvent.getUploadType(), true)); } }; - + uploadStream.addWorkspaceUploadNotificationListener(listener); uploadStream.center(); } @@ -991,7 +991,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onCompletedFileUploadEvent(CompletedFileUploadEvent completedFileUploadEvent) { - doCompletedFileUploadEvent(completedFileUploadEvent); + doCompletedFileUploadEvent(completedFileUploadEvent); } private void doCompletedFileUploadEvent(CompletedFileUploadEvent completedFileUploadEvent) { @@ -1038,7 +1038,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onSuccess(Boolean result) { if(result) - explorerPanel.getSmartFolderPanel().removeSmartFolder(smartIdentifier); + explorerPanel.getSmartFolderPanel().removeSmartFolder(smartIdentifier); } @Override @@ -1052,7 +1052,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } } - }); + }); } }); @@ -1071,7 +1071,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt final String query = saveSmartFolderEvent.getSearchText(); final String parentId = saveSmartFolderEvent.getParentId(); - + final DialogAddFolderAndSmart dialogAddSmartFolder = new DialogAddFolderAndSmart("", AddType.SMARTFOLDER); dialogAddSmartFolder.getButtonById(Dialog.OK).addListener(Events.Select, new Listener() { @@ -1100,7 +1100,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt }); - } + } }); @@ -1129,7 +1129,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt private void doRenameItem(final RenameItemEvent event) { final FileModel target = event.getFileTarget(); - final DialogText dgt = new DialogText(ConstantsExplorer.MESSAGE_RENAME, ConstantsExplorer.MESSAGE_ITEM_NAME, event.getFileTarget().getName()); + final DialogText dgt = new DialogText(ConstantsExplorer.MESSAGE_RENAME, ConstantsExplorer.MESSAGE_ITEM_NAME, event.getFileTarget().getName()); dgt.getButtonById(Dialog.OK).addListener(Events.Select, new Listener() { @@ -1198,11 +1198,11 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt mbc.getMessageBoxConfirm().addCallback(new Listener() { public void handleEvent(MessageBoxEvent be) { - + //IF NOT CANCELLED String clickedButton = be.getButtonClicked().getItemId(); if(clickedButton.equals(Dialog.YES)){ - + explorerPanel.getAsycTreePanel().mask("Deleting", ConstantsExplorer.LOADINGSTYLE); rpcWorkspaceService.removeItem(event.getFileTarget().getIdentifier(), new AsyncCallback(){ @@ -1240,7 +1240,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } } - }); + }); } }); @@ -1255,7 +1255,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt private void doSelectedItem(SelectedItemEvent event) { - notifySubscriber(event); + notifySubscriber(event); } }); @@ -1280,13 +1280,13 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onAddItem(AddFolderEvent event) { - doAddItem(event); + doAddItem(event); } private void doAddItem(final AddFolderEvent event) { final FileModel sourceFileModel = event.getFileSourceModel(); - final FileModel parentFileModel= event.getParentFileModel(); + final FileModel parentFileModel= event.getParentFileModel(); String directory = null; @@ -1307,7 +1307,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt if(dialogAddFolder.isValidForm()){ if(sourceFileModel.isDirectory()){ - // + // //TODO REMOVE // System.out.println("description folder: "+dialogAddFolder.getDescription()); @@ -1323,7 +1323,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onSuccess(FolderModel child) { - explorerPanel.getAsycTreePanel().addItem(sourceFileModel.getIdentifier(), child, false); + explorerPanel.getAsycTreePanel().addItem(sourceFileModel.getIdentifier(), child, false); event.setNewFolder(child); notifySubscriber(event); } @@ -1344,7 +1344,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onSuccess(FolderModel child) { - explorerPanel.getAsycTreePanel().addItem(parentFileModel.getIdentifier(), child, false); + explorerPanel.getAsycTreePanel().addItem(parentFileModel.getIdentifier(), child, false); event.setNewFolder(child); notifySubscriber(event); } @@ -1355,7 +1355,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } } - }); + }); } }); @@ -1451,7 +1451,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt public void onClickUrl(OpenUrlEvent openUrlEvent) { doClickUrl(openUrlEvent); - } + } }); @@ -1491,7 +1491,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onSuccess(FileModel child) { - explorerPanel.getAsycTreePanel().addItem(parent.getIdentifier(), child, false); + explorerPanel.getAsycTreePanel().addItem(parent.getIdentifier(), child, false); explorerPanel.getAsycTreePanel().unmask(); notifySubscriber(createUrlEvent); } @@ -1501,12 +1501,12 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt }); } }); - + eventBus.addHandler(VRESettingPermissionEvent.TYPE, new VRESettingPermissionEventHandler() { - + @Override public void onPermissionSetting(VRESettingPermissionEvent settingPermissionEvent) { - + if(settingPermissionEvent.getSourceFile()!=null){ DialogPermission dialog = new DialogPermission(settingPermissionEvent.getSourceFile()); dialog.show(); @@ -1514,13 +1514,13 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt Info.display("Attention", "Select a VRE Folder to change permissions!"); } }); - + eventBus.addHandler(UpdatedVREPermissionEvent.TYPE, new UpdatedVREPermissionEventHandler() { - + @Override public void onUpdateVREPermissions(UpdatedVREPermissionEvent updatedVREPermissionEvent) { notifySubscriber(updatedVREPermissionEvent); - + } }); @@ -1540,9 +1540,9 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt public void doClickOpenReport(OpenReportsEvent openReportsEvent) { - + final NewBrowserWindow newBrowserWindow = NewBrowserWindow.open("", "_self", ""); - + rpcWorkspaceService.getURLFromApplicationProfile(openReportsEvent.getSourceFileModel().getIdentifier(), new AsyncCallback() { @Override @@ -1574,7 +1574,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt private void doClickOpenReportTemplate(OpenReportsEvent openReportTemplateEvent) { final NewBrowserWindow newBrowserWindow = NewBrowserWindow.open("", "_self", ""); - + rpcWorkspaceService.getURLFromApplicationProfile(openReportTemplateEvent.getSourceFileModel().getIdentifier(), new AsyncCallback() { @Override @@ -1681,7 +1681,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt sub.addedFolder(addItemEvent.getNewFolder().getIdentifier(), addItemEvent.getFileSourceModel()); else - sub.addedFolder(addItemEvent.getNewFolder().getIdentifier(), addItemEvent.getParentFileModel()); + sub.addedFolder(addItemEvent.getNewFolder().getIdentifier(), addItemEvent.getParentFileModel()); }else if(event instanceof SubTreeLoadedEvent){ @@ -1701,7 +1701,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt }else if(event instanceof FileUploadEvent){ - // FileUploadEvent fileUpEvent = (FileUploadEvent) event; + // FileUploadEvent fileUpEvent = (FileUploadEvent) event; // sub.addedFile(fileUpEvent.getParentFileModel(), ""); } else if(event instanceof CompletedFileUploadEvent){ @@ -1746,7 +1746,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } } - sub.createNewMessage(hashFiles); + sub.createNewMessage(hashFiles); }else if(event instanceof FileDownloadEvent){ FileDownloadEvent messageEvent = (FileDownloadEvent) event; @@ -1759,7 +1759,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt }else if(event instanceof PasteItemEvent){ - PasteItemEvent pasteEvent = (PasteItemEvent) event; + PasteItemEvent pasteEvent = (PasteItemEvent) event; sub.pasteEventIsCompleted(pasteEvent.isTreeRefreshable(), pasteEvent.getFolderDestinationId()); }else if(event instanceof CopytemEvent){ @@ -1769,11 +1769,11 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt }else if(event instanceof TrashEvent){ TrashEvent trashEvent = (TrashEvent) event; sub.trashEvent(trashEvent.getTrashOperation(), trashEvent.getTargetFileModels()); - + }else if(event instanceof UpdatedVREPermissionEvent){ UpdatedVREPermissionEvent vreEvent = (UpdatedVREPermissionEvent) event; sub.updatedVREPermissions(vreEvent.getVreFolderId()); - + }else if(event instanceof UpdateWorkspaceSizeEvent){ sub.updateWorksapaceSize(true); } @@ -1825,7 +1825,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt listParents.add(item.getParentFileModel()); return; } - + listParents.add(item.getParentFileModel()); getParents(listParents, item.getParentFileModel()); } @@ -1890,7 +1890,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt this.explorerPanel.setSize(400, 600); this.explorerPanel.getAsycTreePanel().setSizeTreePanel(350, 550); -// rootPanel.add(new BasicDNDExample()); //it's example of drag&drop +// rootPanel.add(new BasicDNDExample()); //it's example of drag&drop }else this.explorerPanel = new ExplorerPanel(instancingSmartFolder,instancingMessages); @@ -1902,7 +1902,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt * Use method getPanel. * * @return ExplorerPanel - * @deprecated + * @deprecated */ public ExplorerPanel getTreePanel(){ @@ -1922,7 +1922,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt this.explorerPanel = getPanel(); this.explorerPanel.getAsycTreePanel().setSizeTreePanel(width, height); - this.explorerPanel.getAsycTreePanel().setHeaderTreeVisible(false); + this.explorerPanel.getAsycTreePanel().setHeaderTreeVisible(false); return explorerPanel.getAsycTreePanel(); } @@ -1932,7 +1932,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt */ public void hideSharingFacilities() { explorerPanel.getAsycTreePanel().getContextMenuTree().setHideSharing(); - } + } /** * Refresh root. @@ -1946,7 +1946,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt /** - * Instance only Async Tree. Select by default root items of tree. + * Instance only Async Tree. Select by default root items of tree. * @return ExplorerPanel */ public ExplorerPanel getPanel(){ @@ -1971,34 +1971,34 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt loadMyLogin(); return this.explorerPanel; } - + /** * Edi permissions. * * @param file the file */ private void ediPermissions(final FileModel file) { - + GWT.log("Edit Permissions on "+file); MultiDragConstants.HEADING_DIALOG = "Edit User/s permissions to: "+file.getName(); MultiDragConstants.ALL_CONTACTS_LEFT_LIST = "Shared User/s"; MultiDragConstants.SHARE_WITH_RIGHT_LIST = "Set permissions for User/s"; - + final MultiDragContactsEditPermissions multiDragContact = new MultiDragContactsEditPermissions(LOAD_CONTACTS_AS.SHARED_USER, file.getIdentifier(), true); - + final DialogMultiDragContact multidrag = multiDragContact.getDialog(); - + multidrag.setTxtHelp("Sets the permission for the user(s) dragged in the right list"); - + multidrag.getButtonById(Dialog.OK).addListener(Events.Select, new Listener() { - + @Override public void handleEvent(BaseEvent be) { final List targets = multiDragContact.getTargetContacts(); - + if(targets.size()==0){ MessageBoxConfirm info = new MessageBoxConfirm("Any User/s?", "You have not selected any Users, confirm exit?"); - + info.getMessageBoxConfirm().addCallback(new Listener() { public void handleEvent(MessageBoxEvent be) { @@ -2012,11 +2012,11 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } // GWT.log(targets.toString()); - + if(targets.size()>=1 && multiDragContact.getSelectedAcl()!=null){ - + final List logins = new ArrayList(targets.size()); - + for (org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel infoContactModel : targets) { GWT.log(infoContactModel.toString()); logins.add(infoContactModel.getLogin()); @@ -2027,24 +2027,24 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onFailure(Throwable caught) { new MessageBoxAlert("Error", caught.getMessage(), null); - + } @Override public void onSuccess(ReportAssignmentACL result) { - + String msg = ""; - + if(result.getErrors().size()>0){ for (String error : result.getErrors()){ msg+="
  • "+error +";

  • "; - + } - + new MessageBoxAlert("Warning!!", msg, null); return; } - + String names = ""; for (String name : result.getValidLogins()) { // String name = infoContactModel.getName()!=null? infoContactModel.getName():infoContactModel.getLogin(); @@ -2067,21 +2067,21 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt }else if(clickedButton.equals(Dialog.CANCEL)){ multidrag.hide(); } - + } }); - + } }); - + } } }); - + multidrag.show(); } - + /** * Show add administrators dialog. * @@ -2092,19 +2092,19 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt MultiDragConstants.HEADING_DIALOG = "Edit Administrator/s to: "+file.getName(); MultiDragConstants.ALL_CONTACTS_LEFT_LIST = "All Contacts"; MultiDragConstants.SHARE_WITH_RIGHT_LIST = "New Administrator/s"; - + final SimpleMultiDragWorkspaceContact multiDragContact = new SimpleMultiDragWorkspaceContact(LOAD_CONTACTS_AS.ADMINISTRATOR, file.getIdentifier(), true, false, true); final Dialog multidrag = multiDragContact.getDialogMultiDragContact(); - + multidrag.getButtonById(Dialog.OK).addListener(Events.Select, new Listener() { - + @Override public void handleEvent(BaseEvent be) { final List targets = multiDragContact.getTargetContactsWithMyLogin(); - + if(targets.size()==1){ MessageBoxConfirm info = new MessageBoxConfirm("Any Administrator/s?", "You have not selected any Administrator, confirm only you as Administrator and exit?"); - + info.getMessageBoxConfirm().addCallback(new Listener() { public void handleEvent(MessageBoxEvent be) { @@ -2119,21 +2119,21 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } }); } - + if(targets.size()>1){ - + final List logins = new ArrayList(targets.size()); String names = "
      "; for (org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel infoContactModel : targets) { logins.add(infoContactModel.getLogin()); names+="
    • "+infoContactModel.getName() +";
    • "; } - + String tail = "
    as new "; tail += logins.size()>1?"administrators":"administrator"; tail+= ", confirm?"; MessageBoxConfirm confirm = new MessageBoxConfirm("Setting new Administrator/s?", "You have selected:
    "+names +tail); - + confirm.getMessageBoxConfirm().addCallback(new Listener() { public void handleEvent(MessageBoxEvent be) { @@ -2147,7 +2147,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt if(clickedButton.equals(Dialog.CANCEL)){ multidrag.hide(); } - + } }); @@ -2155,11 +2155,11 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } }); - + multidrag.show(); } - - + + /** * Do add administrator to folder id. * @@ -2167,7 +2167,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt * @param logins the logins */ private void doAddAdministratorToFolderId(final FileModel file, final List logins) { - + rpcWorkspaceService.addAdministratorsByFolderId(file.getIdentifier(), logins, new AsyncCallback() { @Override @@ -2179,11 +2179,11 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt public void onSuccess(Boolean arg0) { String msg = "Updating administrator/s completed successfully"; MessageBox.info("Operation completed", msg, null); - + } }); } - + /** * Sets the acl to folder id. * @@ -2192,13 +2192,13 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt * @param aclTypeID the acl type id */ private void setACLToFolderId(final String folderId, final List logins, String aclTypeID) { - + rpcWorkspaceService.setACLs(folderId, logins, aclTypeID, new AsyncCallback() { @Override public void onFailure(Throwable caught) { new MessageBoxAlert("Error", caught.getMessage(), null); - + } @Override @@ -2208,26 +2208,26 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } }); } - - + + /** * Load my login. */ private void loadMyLogin(){ - + rpcWorkspaceService.getMyLogin(new AsyncCallback() { @Override public void onFailure(Throwable caught) { GWT.log("Error on loading my login is empty"); myLogin = ""; - + } @Override public void onSuccess(UserBean user) { GWT.log("My login is: "+user.getUsername()); - myLogin = user.getUsername(); + myLogin = user.getUsername(); myLoginFirstName = user.getFirstName(); } }); @@ -2293,7 +2293,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } ArrayList pathParentsList = (ArrayList) getListParentsByIdentifierFromTree(itemIdentifier); - + selectItemInTree(itemIdentifier); explorerPanel.getAsycTreePanel().setSubTreeLoaded(false); explorerPanel.getAsycTreePanel().unmask(); @@ -2330,7 +2330,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt FileModel item = this.explorerPanel.getAsycTreePanel().getFileModelByIdentifier(itemIdentifier); - if(item==null){ + if(item==null){ return null; } else{ @@ -2377,7 +2377,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt */ @Override public boolean addFile(String itemIdentifier, String name, String parentIdentifier) { - return false; + return false; } /** @@ -2421,7 +2421,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt if(fileModel.isDirectory()) return fileModel; else - return fileModel.getParentFileModel(); + return fileModel.getParentFileModel(); } /* (non-Javadoc) @@ -2489,7 +2489,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt windowOpenParam.getBrowserWindow().setUrl(ConstantsExplorer.DOWNLOAD_WORKSPACE_SERVICE+params); - // com.google.gwt.user.client.Window.open(ConstantsExplorer.DOWNLOAD_WORKSPACE_SERVICE+params, windowOpenParam.getOption(), ""); + // com.google.gwt.user.client.Window.open(ConstantsExplorer.DOWNLOAD_WORKSPACE_SERVICE+params, windowOpenParam.getOption(), ""); } }; @@ -2534,10 +2534,10 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt if(fileModel==null) return; - + GWT.log("do click url"); final NewBrowserWindow newBrowserWindow = NewBrowserWindow.open("", "_blank", ""); - + rpcWorkspaceService.getUrlById(fileModel.getIdentifier(), fileModel.getGXTFolderItemType().equals(GXTFolderItemTypeEnum.URL_DOCUMENT), false, new AsyncCallback() { @Override diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceServiceImpl.java b/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceServiceImpl.java index b37f615..f4cbcd6 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceServiceImpl.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceServiceImpl.java @@ -2339,38 +2339,6 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT if(wsItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - /*FolderItem folderItem = (FolderItem) wsItem; - String storageID = builder.getStorageIDForFolderItem(folderItem); - - if(storageID==null || storageID.isEmpty()) - throw new Exception("Sorry, public link on "+wsItem.getName() +" is not available"); - - UriResolverReaderParameterForResolverIndex uriResolver = getUriResolver(); - String uriRequest = ""; - - if(uriResolver!=null && uriResolver.isAvailable()){ - -// String itemName = StringUtil.removeSpecialCharacters(folderItem.getName()); -// itemName = StringUtil.replaceAllWhiteSpace(itemName, "_"); -// uriRequest = uriResolver.resolveAsUriRequest(storageID, itemName, folderItem.getMimeType(), true); - - uriRequest = uriResolver.resolveAsStorageIdRequest(storageID, true); - - - //VALIDATE CONNECTION -// if(!HttpRequestUtil.urlExists(uriRequest+"&validation=true")) -// throw new Exception("Sorry, The Public Link for selected file is unavailable"); - - String shortURL = null; - - if(shortenUrl) - shortURL = getShortUrl(uriRequest); - - -// } -// else -// throw new Exception("Sorry, The Uri resolver service is temporarily unavailable. Please try again later");*/ - FolderItem folderItem = (FolderItem) wsItem; String uriRequest = folderItem.getPublicLink(false); diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/shortener/UrlShortener.java b/src/main/java/org/gcube/portlets/user/workspace/server/shortener/UrlShortener.java index c42cfe9..e17b9e1 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/shortener/UrlShortener.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/shortener/UrlShortener.java @@ -1,5 +1,5 @@ /** - * + * */ package org.gcube.portlets.user.workspace.server.shortener; @@ -31,111 +31,112 @@ import org.json.JSONObject; import org.json.JSONTokener; - + public final class UrlShortener { - + /** - * + * */ protected static final String NO_HTTP_URL_SHORTENER_AVAILABLE = "No HTTP URL Shortener available"; protected static final String APPLICATION_JSON = "application/json"; protected static final String LONG_URL = "longUrl"; - + // protected static String shortnerServerUrl = "https://www.googleapis.com/urlshortener/v1/url"; // protected static String urlMethod = ""; // protected static String authenticationKeyParam = "key"; // protected static String authenticationKeyValue ="AIzaSyDfMO0VY3o8GjRUqnTfqScjm_EsFEuBa3g"; - + private static String shortnerServerUrl = ""; protected static final String KEY = "key"; private static String paramKeyValue =""; - + protected static Logger logger = Logger.getLogger(UrlShortener.class); private String uriRequest; private boolean isAvailable = false; - + /* - * @throws Exception - * @throws InvalidResultException - * @throws DiscoveryException + * @throws Exception + * @throws InvalidResultException + * @throws DiscoveryException * @throws IllegalStateException * - * + * */ public UrlShortener(String scope) throws Exception { try{ logger.trace("Tentative reading HTTP-URL-Shortener RR"); - + ScopeUtilFilter scopeUtil = new ScopeUtilFilter(scope,true); - + ScopeProvider.instance.set(scopeUtil.getScopeRoot()); - + XQuery query = queryFor(ServiceEndpoint.class); - + query.addCondition("$resource/Profile/Name/text() eq 'HTTP-URL-Shortener'").setResult("$resource/Profile/AccessPoint"); - + DiscoveryClient client = clientFor(AccessPoint.class); - + List endpoints = client.submit(query); - + if (endpoints.size() == 0){ isAvailable = false; logger.trace("HTTP-URL-Shortener not found"); throw new Exception(NO_HTTP_URL_SHORTENER_AVAILABLE); } - + //Base Address // System.out.println(endpoints.get(0).address()); - + shortnerServerUrl = endpoints.get(0)!=null?endpoints.get(0).address():""; - + if(endpoints.get(0)!=null){ - + paramKeyValue = endpoints.get(0).propertyMap()!=null?endpoints.get(0).propertyMap().get(KEY).value():""; } - + String getParam = ""; - + logger.trace("paramKeyValue: "+paramKeyValue); + //ACTIVE THIS AFTER RELEASE if(paramKeyValue!=null && !paramKeyValue.isEmpty()){ - getParam = "?"+KEY +"="+paramKeyValue; + getParam = "?"+KEY +"="+paramKeyValue; } - + uriRequest = shortnerServerUrl+getParam; - + logger.trace("HTTP-URL-Shortener found, uriRequest: "+uriRequest); - + //DEBUG // System.out.println("HTTP-URL-Shortener found, uriRequest: "+uriRequest); - + isAvailable = true; - - }catch (Exception e) { + + }catch (Exception e) { isAvailable = false; logger.error("an error occurred in reading RR: ", e); throw new Exception(NO_HTTP_URL_SHORTENER_AVAILABLE); } } - + public boolean isAvailable() { return isAvailable; } - + /** - * + * * @param longUrl * @return a shorten url */ public String shorten(String longUrl) throws Exception{ - + if (longUrl == null) { return longUrl; } - + try { logger.trace("shorten longUrl: "+longUrl); - + URL url = new URL(uriRequest); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); @@ -145,42 +146,42 @@ public final class UrlShortener { JSONObject jsonObj = new JSONObject(); jsonObj.put(LONG_URL, longUrl); - + // //ACTIVE THIS AFTER RELEASE // if(paramKeyValue!=null && !paramKeyValue.isEmpty()){ // jsonObj.put(KEY, paramKeyValue); // } - + logger.trace("request json : "+jsonObj.toString()); - + OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); - + JSONTokener tokener = new JSONTokener(rd); JSONObject jsonObject = new JSONObject(tokener); // JSONParser parser = new JSONParser(); // JSONObject jsonObject = (JSONObject) parser.parse(rd); logger.trace("response received json : "+jsonObject.toString()); - + wr.close(); rd.close(); return (String) jsonObject.get("id"); //is shorted url } catch (MalformedURLException e) { - + logger.error("MalformedURLException error in UrlShortener", e); return longUrl; - + } catch (IOException e) { e.printStackTrace(); logger.error("IOException error in UrlShortener", e); return longUrl; } } - + public static String getShortnerServerUrl() { return shortnerServerUrl; } @@ -196,24 +197,6 @@ public final class UrlShortener { public String getUriRequest() { return uriRequest; } - - - - public static void main(String[] args) { - String shorten; - - try { - - UrlShortener urlSh = new UrlShortener("/d4science.research-infrastructures.eu"); - System.out.println("UrlShortener: "+urlSh); - - shorten = urlSh.shorten("https://dev.d4science.org/group/data-e-infrastructure-gateway/workspace?itemid=056648-c7ce-4de3-a4c7-e1411816cc12&operation=gotofolder"); - - System.out.println("Shorted: "+shorten); - } catch (Exception e) { - e.printStackTrace(); - } - } @Override public String toString() { @@ -225,5 +208,23 @@ public final class UrlShortener { builder.append("]"); return builder.toString(); } - + + + + public static void main(String[] args) { + String shorten; + + try { + + UrlShortener urlSh = new UrlShortener("/d4science.research-infrastructures.eu"); + System.out.println("UrlShortener: "+urlSh); + + shorten = urlSh.shorten("https://dev.d4science.org/group/data-e-infrastructure-gateway/workspace?itemid=056648-c7ce-4de3-a4c7-e1411816cc12&operation=gotofolder"); + + System.out.println("Shorted: "+shorten); + } catch (Exception e) { + e.printStackTrace(); + } + } + } \ No newline at end of file diff --git a/src/test/java/org/gcube/portlets/user/workspace/GoogleUrlShortener.java b/src/test/java/org/gcube/portlets/user/workspace/GoogleUrlShortener.java index 5caf977..1a50dac 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/GoogleUrlShortener.java +++ b/src/test/java/org/gcube/portlets/user/workspace/GoogleUrlShortener.java @@ -1,5 +1,5 @@ /** - * + * */ package org.gcube.portlets.user.workspace; @@ -16,50 +16,58 @@ import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; +import org.gcube.common.encryption.StringEncrypter; +import org.gcube.common.scope.api.ScopeProvider; import org.json.JSONObject; import org.json.JSONTokener; - + public final class GoogleUrlShortener { - + /** - * + * */ protected static final String APPLICATION_JSON = "application/json"; protected static final String LONG_URL = "longUrl"; - + static String shortnerServerUrl = "https://www.googleapis.com/urlshortener/v1/url"; - + static String urlMethod = ""; - static String authenticationKeyValue ="AIzaSyDfMO0VY3o8GjRUqnTfqScjm_EsFEuBa3g"; +// static String authenticationKeyValue ="AIzaSyDfMO0VY3o8GjRUqnTfqScjm_EsFEuBa3g"; + static String authenticationKeyValue ="AIzaSyCQSY7UU3xiBqqlzU5ovr-efs6EXKz5e7Y"; + + static String authenticationKeyParam = "key"; - + // static String shortUrl = "https://dev.d4science.org/group/data-e-infrastructure-gateway/workspace?itemid=062c558c-c7ce-4de3-a4c7-e1411816cc12&operation=gotofolder"; - - - + + + public static String shorten(String longUrl) throws Exception { - + if (longUrl == null) { return longUrl; } - + try { URL url = new URL(shortnerServerUrl); - + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", APPLICATION_JSON); JSONObject jsonObj = new JSONObject(); - + + String decrypt = StringEncrypter.getEncrypter().decrypt(authenticationKeyValue); + System.out.println(decrypt); + jsonObj.put(LONG_URL, longUrl); jsonObj.put(authenticationKeyParam, authenticationKeyValue); - + System.out.println("sending request json : "+jsonObj.toString()); - + OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); @@ -70,13 +78,13 @@ public final class GoogleUrlShortener { JSONObject jsonObject = new JSONObject(tokener); System.out.println("response received json : "+jsonObject.toString()); - + wr.close(); rd.close(); return (String) jsonObject.get("id"); //is shorted url } catch (MalformedURLException e) { - + e.printStackTrace(); return longUrl; } catch (IOException e) { @@ -84,30 +92,36 @@ public final class GoogleUrlShortener { return longUrl; } } - - + + public static String shorten4(String longUrl) throws Exception { - + if (longUrl == null) { return longUrl; } - + try { - + JSONObject jsonObj = new JSONObject(); - + jsonObj.put(LONG_URL, longUrl); + + ScopeProvider.instance.set("/gcube"); + + String decrypt = StringEncrypter.getEncrypter().decrypt(authenticationKeyValue); + System.out.println(decrypt); + jsonObj.put(authenticationKeyParam, authenticationKeyValue); String body = jsonObj.toString(); - + HttpCallerUtil httpCaller = new HttpCallerUtil(shortnerServerUrl, "", ""); String json = httpCaller.callPost("", body, APPLICATION_JSON); - + System.out.println("json: "+json); - - + + JSONTokener tokener = new JSONTokener(json); JSONObject jsonObject = new JSONObject(tokener); @@ -116,7 +130,7 @@ public final class GoogleUrlShortener { return (String) jsonObject.get("id"); //is shorted url } catch (MalformedURLException e) { - + e.printStackTrace(); return longUrl; } catch (IOException e) { @@ -124,48 +138,48 @@ public final class GoogleUrlShortener { return longUrl; } } - - - - + + + + public static String shorten3(String longUrl) throws Exception { - + if (longUrl == null) { return longUrl; } - + try { - - + + HttpCallerUtil httpCaller = new HttpCallerUtil(shortnerServerUrl, "", ""); - + // Map parameters = new HashMap(); -// +// // parameters.put("shortUrl", longUrl); // parameters.put("key", authenticationKey); - - + + // String json = httpCaller.callGet(ulrMethod, parameters); - + String body = "{\"longUrl\":\"" + longUrl + "\", \"key\":\"" + authenticationKeyValue + "\"}"; - + urlMethod += authenticationKeyParam +"="+authenticationKeyValue; - + String json = httpCaller.callPost("", body, APPLICATION_JSON); - + System.out.println("json: "+json); - - + + // return json.substring(json.indexOf("http"), json.indexOf("\"", json.indexOf("http"))); - + return json; - + // httpCaller.callGet(urlMethod, parameters); // return json.substring(json.indexOf("http"), json.indexOf("\"", json.indexOf("http"))); - - - + + + } catch (MalformedURLException e) { e.printStackTrace(); return longUrl; @@ -174,11 +188,11 @@ public final class GoogleUrlShortener { return longUrl; } } - - + + private static String googUrl = "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyDfMO0VY3o8GjRUqnTfqScjm_EsFEuBa3g"; - + public static String shorten2(String longUrl) { String shortUrl = ""; @@ -193,7 +207,7 @@ public final class GoogleUrlShortener { wr.write("{\"longUrl\":\"" + longUrl + "\"}"); wr.flush(); - + BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; @@ -202,11 +216,11 @@ public final class GoogleUrlShortener { } String json = sb.toString(); System.out.println("json: "+json); - + wr.close(); rd.close(); return json.substring(json.indexOf("http"), json.indexOf("\"", json.indexOf("http"))); - + // Get the response // BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); // String line; @@ -221,7 +235,7 @@ public final class GoogleUrlShortener { // } // } - + } catch (MalformedURLException ex) { @@ -235,21 +249,21 @@ public final class GoogleUrlShortener { return shortUrl; } - + public static void main(String[] args) { String shorten; - + try { shorten = GoogleUrlShortener.shorten4("https://dev.d4science.org/group/data-e-infrastructure-gateway/workspace?itemid=062c558c-c7ce-4de3-a4c7-e1411816cc12&operation=gotofolder"); - + System.out.println("Shorted: "+shorten); } catch (Exception e) { e.printStackTrace(); } - - - - + + + + } - + } \ No newline at end of file diff --git a/src/test/java/org/gcube/portlets/user/workspace/UrlShortener.java b/src/test/java/org/gcube/portlets/user/workspace/UrlShortener.java new file mode 100644 index 0000000..4390659 --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/workspace/UrlShortener.java @@ -0,0 +1,230 @@ +/** + * + */ +package org.gcube.portlets.user.workspace; + +/** + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * @Jun 28, 2013 + * + */ +import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; +import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +import org.apache.log4j.Logger; +import org.gcube.common.resources.gcore.ServiceEndpoint; +import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.portlets.user.workspace.server.util.scope.ScopeUtilFilter; +import org.gcube.resources.discovery.client.api.DiscoveryClient; +import org.gcube.resources.discovery.client.queries.impl.XQuery; +import org.json.JSONObject; +import org.json.JSONTokener; + + + +public final class UrlShortener { + + /** + * + */ + protected static final String NO_HTTP_URL_SHORTENER_AVAILABLE = "No HTTP URL Shortener available"; + protected static final String APPLICATION_JSON = "application/json"; + protected static final String LONG_URL = "longUrl"; + +// protected static String shortnerServerUrl = "https://www.googleapis.com/urlshortener/v1/url"; +// protected static String urlMethod = ""; +// protected static String authenticationKeyParam = "key"; +// protected static String authenticationKeyValue ="AIzaSyDfMO0VY3o8GjRUqnTfqScjm_EsFEuBa3g"; + + private static String shortnerServerUrl = ""; + protected static final String KEY = "key"; + private static String paramKeyValue =""; + + protected static Logger logger = Logger.getLogger(UrlShortener.class); + private String uriRequest; + private boolean isAvailable = false; + + /* + * @throws Exception + * @throws InvalidResultException + * @throws DiscoveryException + * @throws IllegalStateException * + * + */ + public UrlShortener(String scope) throws Exception { + + try{ + logger.trace("Tentative reading HTTP-URL-Shortener RR"); + + ScopeUtilFilter scopeUtil = new ScopeUtilFilter(scope,true); + + ScopeProvider.instance.set(scopeUtil.getScopeRoot()); + + XQuery query = queryFor(ServiceEndpoint.class); + + query.addCondition("$resource/Profile/Name/text() eq 'HTTP-URL-Shortener'").setResult("$resource/Profile/AccessPoint"); + + DiscoveryClient client = clientFor(AccessPoint.class); + + List endpoints = client.submit(query); + + if (endpoints.size() == 0){ + isAvailable = false; + logger.trace("HTTP-URL-Shortener not found"); + throw new Exception(NO_HTTP_URL_SHORTENER_AVAILABLE); + } + + //Base Address + // System.out.println(endpoints.get(0).address()); + + shortnerServerUrl = endpoints.get(0)!=null?endpoints.get(0).address():""; + + if(endpoints.get(0)!=null){ + + paramKeyValue = endpoints.get(0).propertyMap()!=null?endpoints.get(0).propertyMap().get(KEY).value():""; + } + + String getParam = ""; + logger.trace("paramKeyValue: "+paramKeyValue); + + //ACTIVE THIS AFTER RELEASE + if(paramKeyValue!=null && !paramKeyValue.isEmpty()){ + getParam = "?"+KEY +"="+paramKeyValue; + } + + uriRequest = shortnerServerUrl+getParam; + + logger.trace("HTTP-URL-Shortener found, uriRequest: "+uriRequest); + + //DEBUG +// System.out.println("HTTP-URL-Shortener found, uriRequest: "+uriRequest); + + isAvailable = true; + + }catch (Exception e) { + isAvailable = false; + logger.error("an error occurred in reading RR: ", e); + throw new Exception(NO_HTTP_URL_SHORTENER_AVAILABLE); + } + } + + public boolean isAvailable() { + return isAvailable; + } + + /** + * + * @param longUrl + * @return a shorten url + */ + public String shorten(String longUrl) throws Exception{ + + if (longUrl == null) { + return longUrl; + } + + try { + + logger.trace("shorten longUrl: "+longUrl); + + URL url = new URL(uriRequest); + + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setDoOutput(true); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", APPLICATION_JSON); + + JSONObject jsonObj = new JSONObject(); + jsonObj.put(LONG_URL, longUrl); + +// //ACTIVE THIS AFTER RELEASE +// if(paramKeyValue!=null && !paramKeyValue.isEmpty()){ +// jsonObj.put(KEY, paramKeyValue); +// } + + logger.trace("request json : "+jsonObj.toString()); + + OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); + wr.write(jsonObj.toString()); + wr.flush(); + + BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); + + JSONTokener tokener = new JSONTokener(rd); + JSONObject jsonObject = new JSONObject(tokener); +// JSONParser parser = new JSONParser(); +// JSONObject jsonObject = (JSONObject) parser.parse(rd); + logger.trace("response received json : "+jsonObject.toString()); + + wr.close(); + rd.close(); + return (String) jsonObject.get("id"); //is shorted url + + } catch (MalformedURLException e) { + + logger.error("MalformedURLException error in UrlShortener", e); + return longUrl; + + } catch (IOException e) { + e.printStackTrace(); + logger.error("IOException error in UrlShortener", e); + return longUrl; + } + } + + public static String getShortnerServerUrl() { + return shortnerServerUrl; + } + + public static String getKey() { + return KEY; + } + + public static String getParamKeyValue() { + return paramKeyValue; + } + + public String getUriRequest() { + return uriRequest; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("UrlShortener [uriRequest="); + builder.append(uriRequest); + builder.append(", isAvailable="); + builder.append(isAvailable); + builder.append("]"); + return builder.toString(); + } + + + + public static void main(String[] args) { + String shorten; + + try { + + UrlShortener urlSh = new UrlShortener("/d4science.research-infrastructures.eu"); + System.out.println("UrlShortener: "+urlSh); + + shorten = urlSh.shorten("https://dev.d4science.org/group/data-e-infrastructure-gateway/workspace?itemid=056648-c7ce-4de3-a4c7-e1411816cc12&operation=gotofolder"); + + System.out.println("Shorted: "+shorten); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/src/test/java/org/gcube/portlets/user/workspace/UrlShortenerReaderRR.java b/src/test/java/org/gcube/portlets/user/workspace/UrlShortenerReaderRR.java index 20f1e0a..642d6e5 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/UrlShortenerReaderRR.java +++ b/src/test/java/org/gcube/portlets/user/workspace/UrlShortenerReaderRR.java @@ -1,5 +1,5 @@ /** - * + * */ package org.gcube.portlets.user.workspace; @@ -21,62 +21,63 @@ import org.gcube.resources.discovery.client.queries.impl.XQuery; * */ public class UrlShortenerReaderRR { - + /** - * + * */ protected static final String KEY = "key"; //Base Address protected String uri = ""; - + //Query URL parameter protected String keyValue = ""; - + private String uriRequest = ""; - + public static Logger log = Logger.getLogger(UrlShortenerReaderRR.class); - - + + /** - * @throws Exception - * + * @throws Exception + * */ public UrlShortenerReaderRR() throws Exception { - + ScopeProvider.instance.set("/gcube"); - + XQuery query = queryFor(ServiceEndpoint.class); - + query.addCondition("$resource/Profile/Name/text() eq 'HTTP-URL-Shortener'").setResult("$resource/Profile/AccessPoint"); - + DiscoveryClient client = clientFor(AccessPoint.class); - + List endpoints = client.submit(query); - + if (endpoints.size() == 0) throw new Exception("No Shortener available"); - + //Base Address // System.out.println(endpoints.get(0).address()); - + uri = endpoints.get(0)!=null?endpoints.get(0).address():""; - + if(endpoints.get(0)!=null){ - + keyValue = endpoints.get(0).propertyMap()!=null?endpoints.get(0).propertyMap().get(KEY).value():""; } - + uriRequest = uri+"?"+KEY+"="+keyValue; - - + + System.out.println(uriRequest); + //Query URL parameter // System.out.println(endpoints.get(0).propertyMap().get("parameter").value()); - + } - + /** - * + * * @return Base Address of Uri Resolver */ public String getUri() { @@ -85,15 +86,15 @@ public class UrlShortenerReaderRR { /** - * + * * @return Query URL parameter of Uri Resolver */ public String getParameter() { return keyValue; } - - + + public static void main(String[] args) throws Exception { log.trace(new UrlShortenerReaderRR()); }