ready to beta testing

git-svn-id: https://svn.research-infrastructures.eu/d4science/gcube/trunk/portlets/user/share-updates@90781 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Massimiliano Assante 2014-01-30 15:39:42 +00:00
parent 0a1b754573
commit 3a738ccd8c
12 changed files with 223 additions and 72 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<classpath> <classpath>
<classpathentry kind="src" output="target/share-updates-1.1.1-SNAPSHOT/WEB-INF/classes" path="src/main/java"> <classpathentry kind="src" output="target/share-updates-1.1.2-SNAPSHOT/WEB-INF/classes" path="src/main/java">
<attributes> <attributes>
<attribute name="optional" value="true"/> <attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
@ -31,5 +31,5 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="output" path="target/share-updates-1.1.1-SNAPSHOT/WEB-INF/classes"/> <classpathentry kind="output" path="target/share-updates-1.1.2-SNAPSHOT/WEB-INF/classes"/>
</classpath> </classpath>

View File

@ -1,5 +1,5 @@
eclipse.preferences.version=1 eclipse.preferences.version=1
jarsExcludedFromWebInfLib= jarsExcludedFromWebInfLib=
lastWarOutDir=/Users/massi/Documents/workspace/share-updates/target/share-updates-1.1.1-SNAPSHOT lastWarOutDir=/Users/massi/Documents/workspace/share-updates/target/share-updates-1.1.2-SNAPSHOT
warSrcDir=src/main/webapp warSrcDir=src/main/webapp
warSrcDirIsOutput=false warSrcDirIsOutput=false

View File

@ -4,9 +4,6 @@
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/> <wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/> <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/target/generated-sources/gwt"/> <wb-resource deploy-path="/WEB-INF/classes" source-path="/target/generated-sources/gwt"/>
<dependent-module archiveName="fileupload-progress-bar-1.0.0-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/fileupload-progress-bar/fileupload-progress-bar">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="java-output-path" value="/${module}/target/www/WEB-INF/classes"/> <property name="java-output-path" value="/${module}/target/www/WEB-INF/classes"/>
<property name="context-root" value="share-updates"/> <property name="context-root" value="share-updates"/>
</wb-module> </wb-module>

13
pom.xml
View File

@ -118,11 +118,9 @@
<version>1.4</version> <version>1.4</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.imgscalr</groupId> <groupId>net.coobird</groupId>
<artifactId>imgscalr-lib</artifactId> <artifactId>thumbnailator</artifactId>
<version>4.2</version> <version>[0.4, 0.5)</version>
<type>jar</type>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-fileupload</groupId> <groupId>commons-fileupload</groupId>
@ -140,6 +138,11 @@
<groupId>org.gcube.common</groupId> <groupId>org.gcube.common</groupId>
<artifactId>home-library</artifactId> <artifactId>home-library</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library-jcr</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.gcube.portal</groupId> <groupId>org.gcube.portal</groupId>

View File

@ -17,7 +17,8 @@ import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
*/ */
@RemoteServiceRelativePath("shareupdateServlet") @RemoteServiceRelativePath("shareupdateServlet")
public interface ShareUpdateService extends RemoteService { public interface ShareUpdateService extends RemoteService {
ClientFeed share(String feedText, FeedType type, PrivacyLevel pLevel, String vreName, String linkTitle, String linkDesc, String url, String urlThumbnail, String host, ArrayList<String> mentionedUsers); ClientFeed share(String feedText, FeedType type, PrivacyLevel pLevel, String vreName, LinkPreview preview, String urlThumbnail, ArrayList<String> mentionedUsers, String fileName, String FilePathOnServer);
UserSettings getUserSettings(); UserSettings getUserSettings();

View File

@ -16,9 +16,9 @@ import com.google.gwt.user.client.rpc.AsyncCallback;
*/ */
public interface ShareUpdateServiceAsync { public interface ShareUpdateServiceAsync {
void share(String feedText, FeedType type, PrivacyLevel pLevel, void share(String feedText, FeedType type, PrivacyLevel pLevel,
String vreName, String linkTitle, String linkDesc, String url, String vreName, LinkPreview preview, String urlThumbnail,
String urlThumbnail, String host, ArrayList<String> mentionedUsers, ArrayList<String> mentionedUsers, String fileName,
AsyncCallback<ClientFeed> callback); String FilePathOnServer, AsyncCallback<ClientFeed> callback);
void checkLink(String linkToCheck, AsyncCallback<LinkPreview> callback); void checkLink(String linkToCheck, AsyncCallback<LinkPreview> callback);

View File

@ -59,7 +59,7 @@ public class LinkPreviewer extends Composite {
if (isFilePreview) { if (isFilePreview) {
saveCopy = new SaveInWorkspaceBox(); saveCopy = new SaveInWorkspaceBox();
uploadInWS.add(saveCopy); uploadInWS.add(saveCopy);
} }
} }
@ -99,4 +99,10 @@ public class LinkPreviewer extends Composite {
public String getUrlThumbnail() { public String getUrlThumbnail() {
return switcher.getSelectedImageURL(); return switcher.getSelectedImageURL();
} }
protected boolean isSharingFile() {
return (saveCopy != null);
}
protected boolean isSaveCopySelected() {
return isSharingFile() ? saveCopy.getValue() : false;
}
} }

View File

@ -1,16 +1,10 @@
package org.gcube.portlets.user.shareupdates.client.view; package org.gcube.portlets.user.shareupdates.client.view;
import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.client.ui.Widget;
public class SaveInWorkspaceBox extends Composite { public class SaveInWorkspaceBox extends Composite {
@ -33,6 +27,8 @@ public class SaveInWorkspaceBox extends Composite {
initWidget(uiBinder.createAndBindUi(this)); initWidget(uiBinder.createAndBindUi(this));
} }
protected boolean getValue() {
return saveCheckBox.getValue();
}
} }

View File

@ -56,12 +56,19 @@ public class ShareUpdateForm extends Composite {
final PageBusAdapter pageBusAdapter = new PageBusAdapter(); final PageBusAdapter pageBusAdapter = new PageBusAdapter();
protected final static String SHARE_UPDATE_TEXT = "Share an update or paste a link, use “@” to mention someone"; protected final static String SHARE_UPDATE_TEXT = "Share an update or paste a link, use “@” to mention someone";
protected final static String ERROR_UPDATE_TEXT = "Looks like empty to me!"; protected final static String ERROR_UPDATE_TEXT = "Looks like empty to me!";
public final static String NO_TEXT_FILE_SHARE = "_N0_73X7_SH4R3_";
private final static String LISTBOX_LEVEL = " - "; private final static String LISTBOX_LEVEL = " - ";
public static final String loading = GWT.getModuleBaseURL() + "../images/avatarLoader.gif"; public static final String loading = GWT.getModuleBaseURL() + "../images/avatarLoader.gif";
public static final String avatar_default = GWT.getModuleBaseURL() + "../images/Avatar_default.png"; public static final String avatar_default = GWT.getModuleBaseURL() + "../images/Avatar_default.png";
public static final String attach = GWT.getModuleBaseURL() + "../images/attach.png"; public static final String attach = GWT.getModuleBaseURL() + "../images/attach.png";
/**
* needed to know where to find the (possible) uploaded file
*/
private String uploadedFilePathOnServer;
private String uploadedFileNameOnServer;
private HandlerManager eventBus = new HandlerManager(null); private HandlerManager eventBus = new HandlerManager(null);
private static ShareUpdateFormUiBinder uiBinder = GWT private static ShareUpdateFormUiBinder uiBinder = GWT
@ -97,7 +104,8 @@ public class ShareUpdateForm extends Composite {
@UiField ListBox privacyLevel = new ListBox(false); @UiField ListBox privacyLevel = new ListBox(false);
UserInfo myUserInfo; private UserInfo myUserInfo;
private void bind() { private void bind() {
/** /**
@ -208,13 +216,18 @@ public class ShareUpdateForm extends Composite {
} }
myUserInfo = result.getUserInfo(); myUserInfo = result.getUserInfo();
String toShare = shareTextArea.getText().trim(); String toShare = shareTextArea.getText().trim();
//We allow to post a file without writing nothing in the sharing textarea
if (myLinkPreviewer != null && myLinkPreviewer.isSharingFile() && (toShare.equals(SHARE_UPDATE_TEXT) || toShare.equals(ERROR_UPDATE_TEXT) || toShare.equals("")) ) {
toShare = NO_TEXT_FILE_SHARE;
}
if (toShare.equals(SHARE_UPDATE_TEXT) || toShare.equals(ERROR_UPDATE_TEXT) || toShare.equals("")) { if (toShare.equals(SHARE_UPDATE_TEXT) || toShare.equals(ERROR_UPDATE_TEXT) || toShare.equals("")) {
shareTextArea.addStyleName("error"); shareTextArea.addStyleName("error");
shareTextArea.setText(ERROR_UPDATE_TEXT); shareTextArea.setText(ERROR_UPDATE_TEXT);
return; return;
} }
//then you can post, but pass html //then you can post but you have to pass html checks now
String toPost = shareTextArea.getText(); String toPost = toShare;
postTweet(toPost, shareTextArea.getMentionedUsers()); postTweet(toPost, shareTextArea.getMentionedUsers());
} }
}); });
@ -239,21 +252,22 @@ public class ShareUpdateForm extends Composite {
if (getPrivacyLevel() == PrivacyLevel.SINGLE_VRE) { if (getPrivacyLevel() == PrivacyLevel.SINGLE_VRE) {
vreId = privacyLevel.getValue(privacyLevel.getSelectedIndex()); vreId = privacyLevel.getValue(privacyLevel.getSelectedIndex());
} }
//preparing to send stuff
String linkTitle = ""; String linkTitle = "", linkDescription = "" , linkUrl = "", linkUrlThumbnail = "", linkHost = "", fileName = null, filePath = null;
String linkDescription = "";
String linkUrl = "";
String linkUrlThumbnail = "";
String linkHost = "";
if (myLinkPreviewer != null) { if (myLinkPreviewer != null) {
linkTitle = myLinkPreviewer.getLinkTitle(); linkTitle = myLinkPreviewer.getLinkTitle();
linkDescription = myLinkPreviewer.getLinkDescription(); linkDescription = myLinkPreviewer.getLinkDescription();
linkUrl = myLinkPreviewer.getUrl(); linkUrl = myLinkPreviewer.getUrl();
linkUrlThumbnail = myLinkPreviewer.getUrlThumbnail(); linkUrlThumbnail = myLinkPreviewer.getUrlThumbnail();
linkHost = myLinkPreviewer.getHost(); linkHost = myLinkPreviewer.getHost();
if (myLinkPreviewer.isSaveCopySelected()) {
fileName = uploadedFileNameOnServer;
filePath = uploadedFilePathOnServer;
}
} }
shareupdateService.share(toShare, FeedType.TWEET, getPrivacyLevel(), vreId, linkTitle, linkDescription, linkUrl, linkUrlThumbnail, linkHost, mentionedUsers, new AsyncCallback<ClientFeed>() { LinkPreview preview2Share = new LinkPreview(linkTitle, linkDescription, linkUrl, linkHost, null);
shareupdateService.share(toShare, FeedType.TWEET, getPrivacyLevel(), vreId, preview2Share, linkUrlThumbnail, mentionedUsers, fileName, filePath, new AsyncCallback<ClientFeed>() {
public void onFailure(Throwable caught) { public void onFailure(Throwable caught) {
submitButton.setEnabled(true); submitButton.setEnabled(true);
shareTextArea.setEnabled(true); shareTextArea.setEnabled(true);
@ -353,7 +367,7 @@ public class ShareUpdateForm extends Composite {
* @param fileName the name of the file * @param fileName the name of the file
* @param absolutePathOnServer the path of the file ending with its name on the server temp * @param absolutePathOnServer the path of the file ending with its name on the server temp
*/ */
protected void checkFile(String fileName, String absolutePathOnServer) { protected void checkFile(final String fileName, final String absolutePathOnServer) {
preview.add(new LinkLoader()); preview.add(new LinkLoader());
shareupdateService.checkUploadedFile(fileName, absolutePathOnServer, new AsyncCallback<LinkPreview>() { shareupdateService.checkUploadedFile(fileName, absolutePathOnServer, new AsyncCallback<LinkPreview>() {
public void onFailure(Throwable caught) { public void onFailure(Throwable caught) {
@ -362,12 +376,14 @@ public class ShareUpdateForm extends Composite {
attachButton.getElement().getStyle().setVisibility(Visibility.VISIBLE); //beacuse otherwise it looses the other properties setting attachButton.getElement().getStyle().setVisibility(Visibility.VISIBLE); //beacuse otherwise it looses the other properties setting
} }
public void onSuccess(LinkPreview result) { public void onSuccess(LinkPreview result) {
preview.clear(); preview.clear();
uploadProgress.setVisible(false); uploadProgress.setVisible(false);
if (result != null) if (result != null)
addPreview(result, true); addPreview(result, true);
attachButton.getElement().getStyle().setVisibility(Visibility.HIDDEN); //beacuse otherwise it looses the other properties setting attachButton.getElement().getStyle().setVisibility(Visibility.HIDDEN); //beacuse otherwise it looses the other properties setting
uploadedFilePathOnServer = absolutePathOnServer;
uploadedFileNameOnServer = fileName;
} }
}); });
} }

View File

@ -1,5 +1,6 @@
package org.gcube.portlets.user.shareupdates.server; package org.gcube.portlets.user.shareupdates.server;
import java.awt.Dimension;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.Image; import java.awt.Image;
import java.awt.Rectangle; import java.awt.Rectangle;
@ -13,17 +14,20 @@ import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Iterator;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper; import org.apache.pdfbox.util.PDFTextStripper;
import org.gcube.applicationsupportlayer.social.storage.FTPManager; import org.gcube.applicationsupportlayer.social.storage.FTPManager;
import org.gcube.portal.databook.shared.ImageType; import org.gcube.portal.databook.shared.ImageType;
import org.gcube.portlets.user.shareupdates.shared.LinkPreview; import org.gcube.portlets.user.shareupdates.shared.LinkPreview;
import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -129,24 +133,24 @@ public class FilePreviewer {
*/ */
protected static LinkPreview getImagePreview(String fileName, String path2Image, String httpUrl, String mimeType) throws Exception { protected static LinkPreview getImagePreview(String fileName, String path2Image, String httpUrl, String mimeType) throws Exception {
ArrayList<String> imagesUrl = new ArrayList<String>(); ArrayList<String> imagesUrl = new ArrayList<String>();
Dimension dim = extractDimension(path2Image);
//description //description
String desc = ""; String desc = ((int) dim.getWidth()) + "x" + ((int) dim.getHeight()) + " pixels";
BufferedImage img = ImageIO.read(new File(path2Image)); // load image
BufferedImage thumbnail = Scalr.resize(img, Method.QUALITY, 80, Scalr.OP_ANTIALIAS);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean result = ImageIO.write(thumbnail, "JPG", out);
if (result) {
String httpLink = getFTPManager().uploadImageOnFTPServer(new ByteArrayInputStream(out.toByteArray()), ImageType.JPG);
_log.debug("Image thumbnail available at: " + httpLink);
imagesUrl.add(httpLink);
return new LinkPreview(fileName, desc, httpUrl, mimeType, imagesUrl);
}
else
throw new IOException("Could not process pdf file");
Thumbnails.of(path2Image)
.width(80)
.outputFormat("jpg")
.toOutputStream(out);
String httpLink = getFTPManager().uploadImageOnFTPServer(new ByteArrayInputStream(out.toByteArray()), ImageType.JPG);
_log.debug("\nFlushed, Image thumbnail available at: " + httpLink);
imagesUrl.add(httpLink);
return new LinkPreview(fileName, desc, httpUrl, mimeType, imagesUrl);
} }
/** /**
* *
* @param fileName thename of the file * @param fileName thename of the file
@ -196,5 +200,30 @@ public class FilePreviewer {
doc.close(); doc.close();
return toReturn; return toReturn;
} }
/**
* extract the dimension in pixels without reading the whole file
* @param path2Image
* @return
* @throws IOException
*/
private static Dimension extractDimension(String path2Image) throws IOException {
ImageInputStream in = ImageIO.createImageInputStream(new File(path2Image));
try {
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if (readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(in);
return new Dimension(reader.getWidth(0), reader.getHeight(0));
} finally {
reader.dispose();
}
}
} finally {
if (in != null) in.close();
}
return null;
}
} }

View File

@ -1,16 +1,12 @@
package org.gcube.portlets.user.shareupdates.server; package org.gcube.portlets.user.shareupdates.server;
import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
@ -28,9 +24,6 @@ import org.apache.tika.detect.Detector;
import org.apache.tika.io.TikaInputStream; import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType; import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.gcube.application.framework.core.session.ASLSession; import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.application.framework.core.session.SessionManager; import org.gcube.application.framework.core.session.SessionManager;
import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager; import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager;
@ -41,7 +34,6 @@ import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace; import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException;
import org.gcube.common.homelibrary.util.MimeTypeUtil;
import org.gcube.common.portal.PortalContext; import org.gcube.common.portal.PortalContext;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean; import org.gcube.common.scope.impl.ScopeBean;
@ -62,6 +54,7 @@ import org.gcube.portal.databook.shared.PrivacyLevel;
import org.gcube.portal.databook.shared.UserInfo; import org.gcube.portal.databook.shared.UserInfo;
import org.gcube.portal.databook.shared.ex.FeedIDNotFoundException; import org.gcube.portal.databook.shared.ex.FeedIDNotFoundException;
import org.gcube.portlets.user.shareupdates.client.ShareUpdateService; import org.gcube.portlets.user.shareupdates.client.ShareUpdateService;
import org.gcube.portlets.user.shareupdates.client.view.ShareUpdateForm;
import org.gcube.portlets.user.shareupdates.server.metaseeker.MetaSeeker; import org.gcube.portlets.user.shareupdates.server.metaseeker.MetaSeeker;
import org.gcube.portlets.user.shareupdates.server.opengraph.OpenGraph; import org.gcube.portlets.user.shareupdates.server.opengraph.OpenGraph;
import org.gcube.portlets.user.shareupdates.shared.LinkPreview; import org.gcube.portlets.user.shareupdates.shared.LinkPreview;
@ -79,7 +72,6 @@ import org.slf4j.LoggerFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.w3c.tidy.Tidy; import org.w3c.tidy.Tidy;
import org.xml.sax.ContentHandler;
import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.PortalException;
@ -156,7 +148,7 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar
* *
*/ */
public ClientFeed share(String postText, FeedType feedType, PrivacyLevel pLevel, public ClientFeed share(String postText, FeedType feedType, PrivacyLevel pLevel,
String vreId, String linkTitle, String linkDesc, String url, String urlThumbnail, String host, ArrayList<String> mentionedUserFullNames) { String vreId, LinkPreview preview, String urlThumbnail, ArrayList<String> mentionedUserFullNames,String fileName, String filePathOnServer) {
String escapedFeedText = escapeHtml(postText); String escapedFeedText = escapeHtml(postText);
@ -183,11 +175,27 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar
e.printStackTrace(); e.printStackTrace();
} }
} }
String linkTitle = preview.getTitle();
String linkDesc = preview.getDescription();
String host = preview.getHost();
String url = preview.getUrl();
Date feedDate = new Date(); Date feedDate = new Date();
//this means the user has shared a file without text in it.
String textToPost = "";
if (escapedFeedText.compareTo(ShareUpdateForm.NO_TEXT_FILE_SHARE) == 0) {
textToPost = convertFileNameAnchorHTML(url);
} else {
textToPost = transformUrls(escapedFeedText);
}
Feed toShare = new Feed(UUID.randomUUID().toString(), feedType, username, feedDate, Feed toShare = new Feed(UUID.randomUUID().toString(), feedType, username, feedDate,
"", url, urlThumbnail, transformUrls(escapedFeedText), pLevel, fullName, email, thumbnailURL, linkTitle, linkDesc, host); "", url, urlThumbnail, textToPost, pLevel, fullName, email, thumbnailURL, linkTitle, linkDesc, host);
_log.trace("Attempting to save Feed with text: " + escapedFeedText + " Level: " + pLevel); _log.trace("Attempting to save Feed with text: " + escapedFeedText + " Level: " + pLevel);
boolean result = store.saveUserFeed(toShare); boolean result = store.saveUserFeed(toShare);
//need to put the feed into VRES Timeline too //need to put the feed into VRES Timeline too
@ -207,7 +215,7 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar
} //share on a single VRE Timeline } //share on a single VRE Timeline
//receives a VreId(groupId) get the scope from the groupId //receives a VreId(groupId) get the scope from the groupId
else if (pLevel == PrivacyLevel.SINGLE_VRE && vreId != null && vreId.compareTo("") != 0) { else if (pLevel == PrivacyLevel.SINGLE_VRE && vreId != null && vreId.compareTo("") != 0) {
String vreScope = getScopeByOrganizationId(vreId); String vreScope = (withinPortal) ? getScopeByOrganizationId(vreId) : "/gcube/devsec/devVRE";
_log.trace("Attempting to write onto " + vreScope); _log.trace("Attempting to write onto " + vreScope);
try { try {
store.saveFeedToVRETimeline(toShare.getKey(), vreScope); store.saveFeedToVRETimeline(toShare.getKey(), vreScope);
@ -230,6 +238,14 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar
Thread thread = new Thread(new MentionNotificationsThread(toShare.getKey(), escapedFeedText, nm, mentionedUsers)); Thread thread = new Thread(new MentionNotificationsThread(toShare.getKey(), escapedFeedText, nm, mentionedUsers));
thread.start(); thread.start();
} }
//it means I also should upload a copy on the user's Workspace root folder
if (fileName != null && filePathOnServer != null) {
//The workspace uploader Thread starts here asyncronously
Thread thread = new Thread(new UploadToWorkspaceThread(username, fileName, filePathOnServer));
thread.start();
}
return cf; return cf;
@ -269,7 +285,7 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar
* @param feedText * @param feedText
* @return the text with the clickable url in it * @return the text with the clickable url in it
*/ */
public String transformUrls(String feedText) { private String transformUrls(String feedText) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
// separate input by spaces ( URLs have no spaces ) // separate input by spaces ( URLs have no spaces )
String [] parts = feedText.split("\\s"); String [] parts = feedText.split("\\s");
@ -293,9 +309,19 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar
} }
} }
return sb.toString(); return sb.toString();
} }
/**
*
* @param preview
* @return
*/
private String convertFileNameAnchorHTML(String url) {
StringBuilder sb = new StringBuilder();
sb.append("<span style=\"color:gray; font-size:12px;\">shared </span><a class=\"link\" href=\"").append(url).append("\" target=\"_blank\">").append("a file.").append("</a> ").toString();
return sb.toString();
}
@Override
public UserSettings getUserSettings() { public UserSettings getUserSettings() {
if (getUserSettingsFromSession() != null) if (getUserSettingsFromSession() != null)
return getUserSettingsFromSession(); return getUserSettingsFromSession();
@ -373,13 +399,13 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar
break; break;
case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
mimeType = "application/wordprocessor"; mimeType = "application/wordprocessor";
break; return FilePreviewer.getUnhandledTypePreview(fileName, fileabsolutePathOnServer, httpURL, mimeType);
case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
mimeType = "application/spreadsheet"; mimeType = "application/spreadsheet";
break; return FilePreviewer.getUnhandledTypePreview(fileName, fileabsolutePathOnServer, httpURL, mimeType);
case "application/vnd.openxmlformats-officedocument.presentationml.presentation": case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
mimeType = "application/presentation"; mimeType = "application/presentation";
break; return FilePreviewer.getUnhandledTypePreview(fileName, fileabsolutePathOnServer, httpURL, mimeType);
case "image/png": case "image/png":
case "image/gif": case "image/gif":
case "image/tiff": case "image/tiff":
@ -413,7 +439,7 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar
* @throws MagicMatchNotFoundException * @throws MagicMatchNotFoundException
* @throws MagicException * @throws MagicException
*/ */
private String getMimeType(File file, String filenameWithExtension) throws IOException { protected static String getMimeType(File file, String filenameWithExtension) throws IOException {
TikaConfig config = TikaConfig.getDefaultConfig(); TikaConfig config = TikaConfig.getDefaultConfig();
Detector detector = config.getDetector(); Detector detector = config.getDetector();
TikaInputStream stream = TikaInputStream.get(file); TikaInputStream stream = TikaInputStream.get(file);

View File

@ -0,0 +1,77 @@
package org.gcube.portlets.user.shareupdates.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import org.gcube.common.homelibrary.home.HomeLibrary;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Massimiliano Assante ISTI-CNR
*
*/
public class UploadToWorkspaceThread implements Runnable {
private static Logger _log = LoggerFactory.getLogger(UploadToWorkspaceThread.class);
/**
* the identifier of the workspace you are putting
*/
private String username;
/**
* the name of the file you are putting
*/
private String fileName;
/**
* the path (with name) of the file you are putting
*/
private String fileabsolutePathOnServer;
/**
*
* @param sClient the instance of the storage client
* @param fileToUpload the absolute path of the file
*/
public UploadToWorkspaceThread(String username, String fileName, String fileabsolutePathOnServer) {
super();
this.username = username;
this.fileName = fileName;
this.fileabsolutePathOnServer = fileabsolutePathOnServer;
}
@Override
public void run() {
try {
Workspace ws = HomeLibrary
.getHomeManagerFactory()
.getHomeManager()
.getHome(username).getWorkspace();
File file = new File(fileabsolutePathOnServer);
String mimeType = ShareUpdateServiceImpl.getMimeType(file, fileName);
InputStream fileData = new FileInputStream(file);
String theId = "";
try {
theId = ws.createExternalFile(fileName ,"File added automatically by Share Updates" , mimeType ,fileData, ws.getRoot().getId()).getId();
}
catch (ItemAlreadyExistException ex) {
_log.warn("fileName " + fileName + " exists, appending timestamp");
theId = ws.createExternalFile(fileName+" ("+ new Date()+")" ,"File added automatically by Share Updates" , mimeType ,fileData, ws.getRoot().getId()).getId();
} finally {
fileData.close();
}
fileData.close();
_log.debug("Uploaded " + fileName + " - Returned Workspace id=" + theId);
}
catch (Exception e) {
e.printStackTrace();
_log.error("Something wrong while uploading " + fileName + " in Workspace " + e.getMessage());
}
}
}