Checkpoint for OAuth functionality in Gridworks

(doesn't work but since it's a substantial chunk of stuff, I want to get it in sooner rather than later)


git-svn-id: http://google-refine.googlecode.com/svn/trunk@516 7d457c2a-affb-35e4-300a-418c747d4874
This commit is contained in:
Stefano Mazzocchi 2010-04-21 21:08:34 +00:00
parent 20a42646ba
commit 439474caeb
33 changed files with 1300 additions and 75 deletions

View File

@ -18,6 +18,10 @@
<classpathentry kind="lib" path="lib/secondstring-20100303.jar" sourcepath="lib-src/secondstring-20100303-sources.jar"/> <classpathentry kind="lib" path="lib/secondstring-20100303.jar" sourcepath="lib-src/secondstring-20100303-sources.jar"/>
<classpathentry kind="lib" path="lib/ant-tools-1.8.0.jar" sourcepath="lib-src/ant-tools-1.8.0-sources.jar"/> <classpathentry kind="lib" path="lib/ant-tools-1.8.0.jar" sourcepath="lib-src/ant-tools-1.8.0-sources.jar"/>
<classpathentry kind="lib" path="lib/vicino-1.1.jar" sourcepath="lib-src/vicino-1.1-sources.jar"/> <classpathentry kind="lib" path="lib/vicino-1.1.jar" sourcepath="lib-src/vicino-1.1-sources.jar"/>
<classpathentry kind="lib" path="lib/httpcore-4.0.1.jar" sourcepath="lib-src/httpcore-4.0.1-sources.jar"/>
<classpathentry kind="lib" path="lib/httpclient-4.0.1.jar" sourcepath="lib-src/httpclient-4.0.1-sources.jar"/>
<classpathentry kind="lib" path="lib/signpost-core-1.2.1.1.jar" sourcepath="lib-src/signpost-core-1.2.1.1-sources.jar"/>
<classpathentry kind="lib" path="lib/signpost-commonshttp4-1.2.1.1.jar" sourcepath="lib-src/signpost-commonshttp4-1.2.1.1-sources.jar"/>
<classpathentry kind="lib" path="lib/poi-3.6.jar"/> <classpathentry kind="lib" path="lib/poi-3.6.jar"/>
<classpathentry kind="lib" path="lib/poi-ooxml-3.6.jar"/> <classpathentry kind="lib" path="lib/poi-ooxml-3.6.jar"/>
<classpathentry kind="lib" path="lib/jython-2.5.1.jar"/> <classpathentry kind="lib" path="lib/jython-2.5.1.jar"/>

View File

@ -54,7 +54,15 @@ licenses/apache2.0.LICENSE.txt
poi-ooxml-schemas poi-ooxml-schemas
servlet-api servlet-api
xmlbeans xmlbeans
signpost
LGPL
----
licenses/marj4j.LICENSE.txt
marc4j
BSD BSD
--- ---
@ -87,6 +95,9 @@ licenses/datejs.LICENSE.txt
licenses/imgareaselect.LICENSE.txt licenses/imgareaselect.LICENSE.txt
imgareaselect imgareaselect
licenses/blockui.LICENSE.txt
blockui
licenses/slf4j.LICENSE.txt licenses/slf4j.LICENSE.txt
slf4j-api slf4j-api

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
lib/httpclient-4.0.1.jar Normal file

Binary file not shown.

BIN
lib/httpcore-4.0.1.jar Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,20 @@
Copyright (c) 2007-2008 M. Alsup
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,34 +0,0 @@
<html>
<head>
<title>ICU4J license - ICU4J 1.3.1 and later</title>
</head>
<body BGCOLOR="#ffffff">
<h2>ICU4J license - ICU4J 1.3.1 and later</h2>
<p>COPYRIGHT AND PERMISSION NOTICE</p>
<p>
Copyright (c) 1995-2001 International Business Machines Corporation and others
</p>
<p>
All rights reserved.
</p>
<p>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons
to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
</p>
<p>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
</p>
<p>
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder.
</p>
<hr>
<small>
All trademarks and registered trademarks mentioned herein are the property of their respective owners.
</small>
</body>
</html>

View File

@ -12,6 +12,9 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import com.metaweb.gridworks.commands.Command; import com.metaweb.gridworks.commands.Command;
import com.metaweb.gridworks.commands.auth.CheckAuthorizationCommand;
import com.metaweb.gridworks.commands.auth.DeAuthorizeCommand;
import com.metaweb.gridworks.commands.auth.AuthorizeCommand;
import com.metaweb.gridworks.commands.edit.AddColumnCommand; import com.metaweb.gridworks.commands.edit.AddColumnCommand;
import com.metaweb.gridworks.commands.edit.AnnotateOneRowCommand; import com.metaweb.gridworks.commands.edit.AnnotateOneRowCommand;
import com.metaweb.gridworks.commands.edit.AnnotateRowsCommand; import com.metaweb.gridworks.commands.edit.AnnotateRowsCommand;
@ -36,10 +39,10 @@ import com.metaweb.gridworks.commands.info.ComputeClustersCommand;
import com.metaweb.gridworks.commands.info.ComputeFacetsCommand; import com.metaweb.gridworks.commands.info.ComputeFacetsCommand;
import com.metaweb.gridworks.commands.info.ExportRowsCommand; import com.metaweb.gridworks.commands.info.ExportRowsCommand;
import com.metaweb.gridworks.commands.info.GetAllProjectMetadataCommand; import com.metaweb.gridworks.commands.info.GetAllProjectMetadataCommand;
import com.metaweb.gridworks.commands.info.GetColumnsInfoCommand;
import com.metaweb.gridworks.commands.info.GetExpressionHistoryCommand; import com.metaweb.gridworks.commands.info.GetExpressionHistoryCommand;
import com.metaweb.gridworks.commands.info.GetHistoryCommand; import com.metaweb.gridworks.commands.info.GetHistoryCommand;
import com.metaweb.gridworks.commands.info.GetModelsCommand; import com.metaweb.gridworks.commands.info.GetModelsCommand;
import com.metaweb.gridworks.commands.info.GetColumnsInfoCommand;
import com.metaweb.gridworks.commands.info.GetOperationsCommand; import com.metaweb.gridworks.commands.info.GetOperationsCommand;
import com.metaweb.gridworks.commands.info.GetProcessesCommand; import com.metaweb.gridworks.commands.info.GetProcessesCommand;
import com.metaweb.gridworks.commands.info.GetProjectMetadataCommand; import com.metaweb.gridworks.commands.info.GetProjectMetadataCommand;
@ -130,6 +133,10 @@ public class GridworksServlet extends HttpServlet {
_commands.put("preview-protograph", new PreviewProtographCommand()); _commands.put("preview-protograph", new PreviewProtographCommand());
_commands.put("guess-types-of-column", new GuessTypesOfColumnCommand()); _commands.put("guess-types-of-column", new GuessTypesOfColumnCommand());
_commands.put("check-authorization", new CheckAuthorizationCommand());
_commands.put("authorize", new AuthorizeCommand());
_commands.put("deauthorize", new DeAuthorizeCommand());
} }
@Override @Override
@ -170,6 +177,8 @@ public class GridworksServlet extends HttpServlet {
Command command = _commands.get(getCommandName(request)); Command command = _commands.get(getCommandName(request));
if (command != null) { if (command != null) {
command.doPost(request, response); command.doPost(request, response);
} else {
response.sendError(404);
} }
} }
@ -177,6 +186,8 @@ public class GridworksServlet extends HttpServlet {
Command command = _commands.get(getCommandName(request)); Command command = _commands.get(getCommandName(request));
if (command != null) { if (command != null) {
command.doGet(request, response); command.doGet(request, response);
} else {
response.sendError(404);
} }
} }

View File

@ -0,0 +1,33 @@
package com.metaweb.gridworks.commands.auth;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONWriter;
import com.metaweb.gridworks.commands.Command;
import com.metaweb.gridworks.oauth.OAuthUtilities;
import com.metaweb.gridworks.oauth.Provider;
public class AuthorizationCommand extends Command {
private static final String PROVIDER_PARAM = "provider";
protected void respond(HttpServletResponse response, String status, String message) throws IOException, JSONException {
JSONWriter writer = new JSONWriter(response.getWriter());
writer.object();
writer.key("status"); writer.value(status);
writer.key("message"); writer.value(message);
writer.endObject();
}
protected Provider getProvider(HttpServletRequest request) {
String provider_str = request.getParameter(PROVIDER_PARAM);
Provider provider = OAuthUtilities.getProvider(request.getParameter(PROVIDER_PARAM));
if (provider == null) throw new RuntimeException("Can't find OAuth provider '" + provider_str + "'");
return provider;
}
}

View File

@ -0,0 +1,120 @@
package com.metaweb.gridworks.commands.auth;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import com.metaweb.gridworks.Gridworks;
import com.metaweb.gridworks.oauth.Credentials;
import com.metaweb.gridworks.oauth.OAuthUtilities;
import com.metaweb.gridworks.oauth.Provider;
public class AuthorizeCommand extends AuthorizationCommand {
private static final String OAUTH_VERIFIER_PARAM = "oauth_verifier";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// get the provider from the request
Provider provider = getProvider(request);
// see if the request comes with access credentials
Credentials access_credentials = Credentials.getCredentials(request, provider, Credentials.Type.ACCESS);
// prepare the continuation URL that the OAuth provider will redirect the user to
// (we need to make sure this URL points back to this code or the dance will never complete)
String callbackURL = Gridworks.getURL() + "/command/authorize";
if (access_credentials == null) {
// access credentials are not available so we need to check
// to see at what stage of the OAuth dance we are
// get the request token credentials
Credentials request_credentials = Credentials.getCredentials(request, provider, Credentials.Type.REQUEST);
OAuthConsumer consumer = OAuthUtilities.getConsumer(provider);
OAuthProvider pp = OAuthUtilities.getOAuthProvider(provider);
if (request_credentials == null) {
// no credentials were found, so let's start the dance
// get the request token
String url = pp.retrieveRequestToken(consumer, callbackURL);
request_credentials = new Credentials(consumer.getToken(), consumer.getTokenSecret(), provider);
// and set them to that we can retrieve them later in the second part of the dance
Credentials.setCredentials(response, request_credentials, Credentials.Type.REQUEST, 3600);
// now redirect the user to the Authorize URL where she can authenticate against the
// service provider and authorize us.
// The provider will bounce the user back here for us to continue the dance.
response.sendRedirect(url);
} else {
// we are at the second stage of the dance, so we need need to obtain the access credentials now
// if we got here, it means that the user performed a valid authentication against the
// service provider and authorized us, so now we can request more permanent credentials
// to the service provider and save those as well for later use.
// this is set only for OAuth 1.0a
String verificationCode = request.getParameter(OAUTH_VERIFIER_PARAM);
pp.retrieveAccessToken(consumer, verificationCode);
access_credentials = new Credentials(consumer.getToken(), consumer.getTokenSecret(), provider);
// no matter the result, we need to remove the request token
Credentials.deleteCredentials(request, response, provider, Credentials.Type.REQUEST);
if (access_credentials == null) {
// in some circumstances, a request token is present in the user cookies
// but it's not valid to obtain an access token (for example, if the user first
// denied access and then changed her mind and wanted to do the oauth dance again).
// So we need to reset the dance by removing the request token from the cookies
// redirect back to here.
response.sendRedirect(callbackURL);
} else {
Credentials.setCredentials(response, access_credentials, Credentials.Type.ACCESS, 30 * 24 * 3600);
}
finish(response);
}
} else {
finish(response);
}
} catch (Exception e) {
respondException(response, e);
}
}
private void finish(HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "text/html");
PrintWriter writer = response.getWriter();
writer.write(
"<html>" +
"<body></body>" +
"<script type='text/javascript'>" +
"if (top.opener && top.opener.onauthorization) {" +
" top.opener.onauthorization(window);" +
"}" +
"self.close();" +
"</script>" +
"</html>"
);
writer.flush();
}
}

View File

@ -0,0 +1,68 @@
package com.metaweb.gridworks.commands.auth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oauth.signpost.OAuthConsumer;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import com.metaweb.gridworks.Gridworks;
import com.metaweb.gridworks.oauth.Credentials;
import com.metaweb.gridworks.oauth.OAuthUtilities;
import com.metaweb.gridworks.oauth.Provider;
import com.metaweb.gridworks.util.IOUtils;
public class CheckAuthorizationCommand extends AuthorizationCommand {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Provider provider = getProvider(request);
// this cookie should not be there, but this is good hygiene practice
Credentials.deleteCredentials(request, response, provider, Credentials.Type.REQUEST);
Credentials access_credentials = Credentials.getCredentials(request, provider, Credentials.Type.ACCESS);
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "application/json");
if (access_credentials != null) {
Gridworks.log(access_credentials.toString());
OAuthConsumer consumer = OAuthUtilities.getConsumer(access_credentials, provider);
HttpGet httpRequest = new HttpGet("http://" + provider.getHost() + "/api/service/user_info");
httpRequest.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Gridworks " + Gridworks.getVersion());
// this is required by the Metaweb API to avoid XSS
httpRequest.setHeader("X-Requested-With", "1");
consumer.sign(request);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);
OutputStream output = response.getOutputStream();
InputStream input = httpResponse.getEntity().getContent();
IOUtils.copy(input, output);
input.close();
output.close();
}
respond(response, "401 Unauthorized", "You don't have the right credentials");
} catch (Exception e) {
respondException(response, e);
}
}
}

View File

@ -0,0 +1,29 @@
package com.metaweb.gridworks.commands.auth;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.metaweb.gridworks.oauth.Credentials;
import com.metaweb.gridworks.oauth.Provider;
public class DeAuthorizeCommand extends AuthorizationCommand {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "application/json");
Provider provider = getProvider(request);
Credentials.deleteCredentials(request, response, provider, Credentials.Type.ACCESS);
respond(response, "200 OK", "");
} catch (Exception e) {
respondException(response, e);
}
}
}

View File

@ -3,7 +3,6 @@ package com.metaweb.gridworks.commands.edit;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterInputStream; import java.io.FilterInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -50,6 +49,7 @@ import com.metaweb.gridworks.importers.MarcImporter;
import com.metaweb.gridworks.importers.TsvCsvImporter; import com.metaweb.gridworks.importers.TsvCsvImporter;
import com.metaweb.gridworks.importers.XmlImporter; import com.metaweb.gridworks.importers.XmlImporter;
import com.metaweb.gridworks.model.Project; import com.metaweb.gridworks.model.Project;
import com.metaweb.gridworks.util.IOUtils;
import com.metaweb.gridworks.util.ParsingUtilities; import com.metaweb.gridworks.util.ParsingUtilities;
public class CreateProjectCommand extends Command { public class CreateProjectCommand extends Command {
@ -298,7 +298,7 @@ public class CreateProjectCommand extends Command {
private File save(InputStream is) throws IOException { private File save(InputStream is) throws IOException {
File temp = Gridworks.getTempFile(Long.toString(System.currentTimeMillis())); File temp = Gridworks.getTempFile(Long.toString(System.currentTimeMillis()));
temp.deleteOnExit(); temp.deleteOnExit();
copy(is,temp); IOUtils.copy(is,temp);
is.close(); is.close();
return temp; return temp;
} }
@ -330,27 +330,6 @@ public class CreateProjectCommand extends Command {
return result; return result;
} }
private static long copy(InputStream input, File file) throws IOException {
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4 * 1024];
long count = 0;
int n = 0;
try {
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
} finally {
try {
output.close();
} catch (IOException e) {}
try {
input.close();
} catch (IOException e) {}
}
return count;
}
protected void internalImportURL( protected void internalImportURL(
HttpServletRequest request, HttpServletRequest request,
Project project, Project project,

View File

@ -0,0 +1,81 @@
package com.metaweb.gridworks.oauth;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oauth.signpost.OAuth;
import oauth.signpost.http.HttpParameters;
import com.metaweb.gridworks.util.CookiesUtilities;
public class Credentials {
private static final String TOKEN = "oauth_token";
private static final String SECRET = "oauth_token_secret";
public enum Type {
REQUEST("request"),
ACCESS("access");
private final String postfix;
Type(String postfix) {
this.postfix = postfix;
}
public String getCookieName(Provider provider) {
return provider.getHost() + "_" + postfix;
}
};
public static Credentials getCredentials(HttpServletRequest request, Provider provider, Type type) {
Cookie cookie = CookiesUtilities.getCookie(request, type.getCookieName(provider));
return (cookie == null) ? null : makeCredentials(cookie.getValue(), provider);
}
public static void setCredentials(HttpServletResponse response, Credentials credentials, Type type, int max_age) {
String name = type.getCookieName(credentials.getProvider());
Cookie c = new Cookie(name, credentials.toString());
c.setPath("/");
c.setMaxAge(max_age);
response.addCookie(c);
}
public static void deleteCredentials(HttpServletRequest request, HttpServletResponse response, Provider provider, Type type) {
CookiesUtilities.deleteCookie(request, response, type.getCookieName(provider));
}
public static Credentials makeCredentials(String str, Provider provider) {
HttpParameters p = OAuth.decodeForm(str);
return new Credentials(p.getFirst(TOKEN), p.getFirst(SECRET), provider);
}
private Provider provider;
private String token;
private String secret;
public Credentials(String token, String secret, Provider provider) {
this.token = token;
if (token == null) throw new RuntimeException("Could not find " + TOKEN + " in auth credentials");
this.secret = secret;
if (secret == null) throw new RuntimeException("Could not find " + SECRET + " in auth credentials");
}
public String getToken() {
return token;
}
public String getSecret() {
return secret;
}
public Provider getProvider() {
return provider;
}
public String toString() {
return TOKEN + "=" + OAuth.percentEncode(token) + "&" + SECRET + "=" + OAuth.percentEncode(secret);
}
}

View File

@ -0,0 +1,21 @@
package com.metaweb.gridworks.oauth;
public class FreebaseProvider extends Provider {
public FreebaseProvider(String host) {
super(host);
}
public String getRequestTokenServiceURL() {
return "https://" + host + "/api/oauth/request_token";
}
public String getAccessTokenServiceURL() {
return "https://" + host + "/api/oauth/access_token";
}
public String getUserAuthorizationURL() {
return "https://" + host + "/signin/app";
}
}

View File

@ -0,0 +1,48 @@
package com.metaweb.gridworks.oauth;
import java.util.HashMap;
import java.util.Map;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
public class OAuthUtilities {
static final private Map<String,Provider> providers = new HashMap<String,Provider>();
static final private Map<String,String[]> infos = new HashMap<String,String[]>();
static private final String[] FREEBASE_OAUTH_INFO = { "#9202a8c04000641f80000000150979b7" , "8ded7babfad2f94f4c77e39bbd6c90f31939999b"};
static private final String[] SANDBOX_OAUTH_INFO = { "#9202a8c04000641f800000001505964a" , "a816b13991bf1d191ad1c371f3c230feca6a11e2"};
static {
providers.put("freebase", new FreebaseProvider("www.freebase.com"));
providers.put("sandbox", new FreebaseProvider("www.sandbox-freebase.com"));
infos.put("www.freebase.com", FREEBASE_OAUTH_INFO);
infos.put("www.sandbox-freebase.com", SANDBOX_OAUTH_INFO);
}
public static Provider getProvider(String name) {
return (name == null) ? null : providers.get(name);
}
public static OAuthConsumer getConsumer(Provider provider) {
if (provider == null) throw new RuntimeException("Provider can't be null");
String[] consumer_info = infos.get(provider.getHost());
if (consumer_info == null) throw new RuntimeException("Can't find secrets for provider '" + provider.getHost() + "'");
return new CommonsHttpOAuthConsumer(consumer_info[0],consumer_info[1]);
}
public static OAuthConsumer getConsumer(Credentials credentials, Provider provider) {
OAuthConsumer consumer = getConsumer(provider);
consumer.setTokenWithSecret(credentials.getToken(), credentials.getSecret());
return consumer;
}
public static OAuthProvider getOAuthProvider(Provider p) {
return new CommonsHttpOAuthProvider(p.getRequestTokenServiceURL(), p.getAccessTokenServiceURL(), p.getUserAuthorizationURL());
}
}

View File

@ -0,0 +1,19 @@
package com.metaweb.gridworks.oauth;
public abstract class Provider {
protected String host;
public Provider(String host) {
this.host = host;
}
public String getHost() {
return host;
}
abstract public String getRequestTokenServiceURL();
abstract public String getAccessTokenServiceURL();
abstract public String getUserAuthorizationURL();
}

View File

@ -0,0 +1,34 @@
package com.metaweb.gridworks.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookiesUtilities {
public static Cookie getCookie(HttpServletRequest request, String name) {
if (name == null) throw new RuntimeException("cookie name cannot be null");
Cookie cookie = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if (name.equals(c.getName())) {
cookie = c;
}
}
}
return cookie;
}
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) {
Cookie cookie = getCookie(request, name);
if (cookie != null) {
Cookie delCookie = new Cookie(cookie.getName(), cookie.getValue());
delCookie.setDomain(cookie.getDomain());
delCookie.setPath(cookie.getPath());
delCookie.setMaxAge(0);
response.addCookie(delCookie);
}
}
}

View File

@ -0,0 +1,45 @@
package com.metaweb.gridworks.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class IOUtils {
private static final int DEFAULT_BUFFER_SIZE = 4 * 1024;
public static long copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
public static long copy(InputStream input, File file) throws IOException {
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
try {
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
} finally {
try {
output.close();
} catch (IOException e) {}
try {
input.close();
} catch (IOException e) {}
}
return count;
}
}

View File

@ -31,19 +31,29 @@ public class ParsingUtilities {
if (query.startsWith("?")) { if (query.startsWith("?")) {
query = query.substring(1); query = query.substring(1);
} }
String[] pairs = query.split("&"); parseParameters(options,query);
for (String pairString : pairs) {
int equal = pairString.indexOf('=');
String name = equal >= 0 ? pairString.substring(0, equal) : "";
String value = equal >= 0 ? ParsingUtilities.decode(pairString.substring(equal + 1)) : "";
options.put(name, value);
}
} }
return options; return options;
} }
static public Properties parseParameters(Properties p, String str) {
if (str != null) {
String[] pairs = str.split("&");
for (String pairString : pairs) {
int equal = pairString.indexOf('=');
String name = (equal >= 0) ? pairString.substring(0, equal) : "";
String value = (equal >= 0) ? ParsingUtilities.decode(pairString.substring(equal + 1)) : "";
p.put(name, value);
}
}
return p;
}
static public Properties parseParameters(String str) {
return (str == null) ? null : parseParameters(new Properties(),str);
}
static public String inputStreamToString(InputStream is) throws IOException { static public String inputStreamToString(InputStream is) throws IOException {
Reader reader = new InputStreamReader(is, "UTF-8"); Reader reader = new InputStreamReader(is, "UTF-8");
try { try {

View File

@ -0,0 +1,478 @@
/*!
* jQuery blockUI plugin
* Version 2.31 (06-JAN-2010)
* @requires jQuery v1.2.3 or later
*
* Examples at: http://malsup.com/jquery/block/
* Copyright (c) 2007-2008 M. Alsup
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Thanks to Amir-Hossein Sobhi for some excellent contributions!
*/
;(function($) {
if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
alert('blockUI requires jQuery v1.2.3 or later! You are using v' + $.fn.jquery);
return;
}
$.fn._fadeIn = $.fn.fadeIn;
var noOp = function() {};
// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
// retarded userAgent strings on Vista)
var mode = document.documentMode || 0;
var setExpr = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8);
var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && !mode;
// global $ methods for blocking/unblocking the entire page
$.blockUI = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };
// convenience method for quick growl-like notifications (http://www.google.com/search?q=growl)
$.growlUI = function(title, message, timeout, onClose) {
var $m = $('<div class="growlUI"></div>');
if (title) $m.append('<h1>'+title+'</h1>');
if (message) $m.append('<h2>'+message+'</h2>');
if (timeout == undefined) timeout = 3000;
$.blockUI({
message: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
timeout: timeout, showOverlay: false,
onUnblock: onClose,
css: $.blockUI.defaults.growlCSS
});
};
// plugin method for blocking element content
$.fn.block = function(opts) {
return this.unblock({ fadeOut: 0 }).each(function() {
if ($.css(this,'position') == 'static')
this.style.position = 'relative';
if ($.browser.msie)
this.style.zoom = 1; // force 'hasLayout'
install(this, opts);
});
};
// plugin method for unblocking element content
$.fn.unblock = function(opts) {
return this.each(function() {
remove(this, opts);
});
};
$.blockUI.version = 2.31; // 2nd generation blocking at no extra cost!
// override these in your code to change the default behavior and style
$.blockUI.defaults = {
// message displayed when blocking (use null for no message)
message: '<h1>Please wait...</h1>',
title: null, // title string; only used when theme == true
draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded)
theme: false, // set to true to use with jQuery UI themes
// styles for the message when blocking; if you wish to disable
// these and use an external stylesheet then do this in your code:
// $.blockUI.defaults.css = {};
css: {
padding: 0,
margin: 0,
width: '30%',
top: '40%',
left: '35%',
textAlign: 'center',
color: '#000',
border: '3px solid #aaa',
backgroundColor:'#fff',
cursor: 'wait'
},
// minimal style set used when themes are used
themedCSS: {
width: '30%',
top: '40%',
left: '35%'
},
// styles for the overlay
overlayCSS: {
backgroundColor: '#000',
opacity: 0.6,
cursor: 'wait'
},
// styles applied when using $.growlUI
growlCSS: {
width: '350px',
top: '10px',
left: '',
right: '10px',
border: 'none',
padding: '5px',
opacity: 0.6,
cursor: 'default',
color: '#fff',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px'
},
// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
// (hat tip to Jorge H. N. de Vasconcelos)
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
// force usage of iframe in non-IE browsers (handy for blocking applets)
forceIframe: false,
// z-index for the blocking overlay
baseZ: 1000,
// set these to true to have the message automatically centered
centerX: true, // <-- only effects element blocking (page block controlled via css above)
centerY: true,
// allow body element to be stetched in ie6; this makes blocking look better
// on "short" pages. disable if you wish to prevent changes to the body height
allowBodyStretch: true,
// enable if you want key and mouse events to be disabled for content that is blocked
bindEvents: true,
// be default blockUI will supress tab navigation from leaving blocking content
// (if bindEvents is true)
constrainTabKey: true,
// fadeIn time in millis; set to 0 to disable fadeIn on block
fadeIn: 200,
// fadeOut time in millis; set to 0 to disable fadeOut on unblock
fadeOut: 400,
// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
timeout: 0,
// disable if you don't want to show the overlay
showOverlay: true,
// if true, focus will be placed in the first available input field when
// page blocking
focusInput: true,
// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
applyPlatformOpacityRules: true,
// callback method invoked when fadeIn has completed and blocking message is visible
onBlock: null,
// callback method invoked when unblocking has completed; the callback is
// passed the element that has been unblocked (which is the window object for page
// blocks) and the options that were passed to the unblock call:
// onUnblock(element, options)
onUnblock: null,
// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
quirksmodeOffsetHack: 4
};
// private data and functions follow...
var pageBlock = null;
var pageBlockEls = [];
function install(el, opts) {
var full = (el == window);
var msg = opts && opts.message !== undefined ? opts.message : undefined;
opts = $.extend({}, $.blockUI.defaults, opts || {});
opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
var themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
msg = msg === undefined ? opts.message : msg;
// remove the current block (if there is one)
if (full && pageBlock)
remove(window, {fadeOut:0});
// if an existing element is being used as the blocking content then we capture
// its current place in the DOM (and current display style) so we can restore
// it when we unblock
if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
var node = msg.jquery ? msg[0] : msg;
var data = {};
$(el).data('blockUI.history', data);
data.el = node;
data.parent = node.parentNode;
data.display = node.style.display;
data.position = node.style.position;
if (data.parent)
data.parent.removeChild(node);
}
var z = opts.baseZ;
// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
// layer1 is the iframe layer which is used to supress bleed through of underlying content
// layer2 is the overlay layer which has opacity and a wait cursor (by default)
// layer3 is the message content that is displayed while blocking
var lyr1 = ($.browser.msie || opts.forceIframe)
? $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>')
: $('<div class="blockUI" style="display:none"></div>');
var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
var lyr3;
if (opts.theme && full) {
var s = '<div class="blockUI blockMsg blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+z+';display:none;position:fixed">' +
'<div class="ui-widget-header ui-dialog-titlebar blockTitle">'+(opts.title || '&nbsp;')+'</div>' +
'<div class="ui-widget-content ui-dialog-content"></div>' +
'</div>';
lyr3 = $(s);
}
else {
lyr3 = full ? $('<div class="blockUI blockMsg blockPage" style="z-index:'+z+';display:none;position:fixed"></div>')
: $('<div class="blockUI blockMsg blockElement" style="z-index:'+z+';display:none;position:absolute"></div>');
}
// if we have a message, style it
if (msg) {
if (opts.theme) {
lyr3.css(themedCSS);
lyr3.addClass('ui-widget-content');
}
else
lyr3.css(css);
}
// style the overlay
if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform)))
lyr2.css(opts.overlayCSS);
lyr2.css('position', full ? 'fixed' : 'absolute');
// make iframe layer transparent in IE
if ($.browser.msie || opts.forceIframe)
lyr1.css('opacity',0.0);
//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
$.each(layers, function() {
this.appendTo($par);
});
if (opts.theme && opts.draggable && $.fn.draggable) {
lyr3.draggable({
handle: '.ui-dialog-titlebar',
cancel: 'li'
});
}
// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
var expr = setExpr && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
if (ie6 || expr) {
// give body 100% height
if (full && opts.allowBodyStretch && $.boxModel)
$('html,body').css('height','100%');
// fix ie6 issue when blocked element has a border width
if ((ie6 || !$.boxModel) && !full) {
var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
var fixT = t ? '(0 - '+t+')' : 0;
var fixL = l ? '(0 - '+l+')' : 0;
}
// simulate fixed position
$.each([lyr1,lyr2,lyr3], function(i,o) {
var s = o[0].style;
s.position = 'absolute';
if (i < 2) {
full ? s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"')
: s.setExpression('height','this.parentNode.offsetHeight + "px"');
full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
: s.setExpression('width','this.parentNode.offsetWidth + "px"');
if (fixL) s.setExpression('left', fixL);
if (fixT) s.setExpression('top', fixT);
}
else if (opts.centerY) {
if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
s.marginTop = 0;
}
else if (!opts.centerY && full) {
var top = (opts.css && opts.css.top) ? parseInt(opts.css.top) : 0;
var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
s.setExpression('top',expression);
}
});
}
// show the message
if (msg) {
if (opts.theme)
lyr3.find('.ui-widget-content').append(msg);
else
lyr3.append(msg);
if (msg.jquery || msg.nodeType)
$(msg).show();
}
if (($.browser.msie || opts.forceIframe) && opts.showOverlay)
lyr1.show(); // opacity is zero
if (opts.fadeIn) {
var cb = opts.onBlock ? opts.onBlock : noOp;
var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
var cb2 = msg ? cb : noOp;
if (opts.showOverlay)
lyr2._fadeIn(opts.fadeIn, cb1);
if (msg)
lyr3._fadeIn(opts.fadeIn, cb2);
}
else {
if (opts.showOverlay)
lyr2.show();
if (msg)
lyr3.show();
if (opts.onBlock)
opts.onBlock();
}
// bind key and mouse events
bind(1, el, opts);
if (full) {
pageBlock = lyr3[0];
pageBlockEls = $(':input:enabled:visible',pageBlock);
if (opts.focusInput)
setTimeout(focus, 20);
}
else
center(lyr3[0], opts.centerX, opts.centerY);
if (opts.timeout) {
// auto-unblock
var to = setTimeout(function() {
full ? $.unblockUI(opts) : $(el).unblock(opts);
}, opts.timeout);
$(el).data('blockUI.timeout', to);
}
};
// remove the block
function remove(el, opts) {
var full = (el == window);
var $el = $(el);
var data = $el.data('blockUI.history');
var to = $el.data('blockUI.timeout');
if (to) {
clearTimeout(to);
$el.removeData('blockUI.timeout');
}
opts = $.extend({}, $.blockUI.defaults, opts || {});
bind(0, el, opts); // unbind events
var els;
if (full) // crazy selector to handle odd field errors in ie6/7
els = $('body').children().filter('.blockUI').add('body > .blockUI');
else
els = $('.blockUI', el);
if (full)
pageBlock = pageBlockEls = null;
if (opts.fadeOut) {
els.fadeOut(opts.fadeOut);
setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
}
else
reset(els, data, opts, el);
};
// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
els.each(function(i,o) {
// remove via DOM calls so we don't lose event handlers
if (this.parentNode)
this.parentNode.removeChild(this);
});
if (data && data.el) {
data.el.style.display = data.display;
data.el.style.position = data.position;
if (data.parent)
data.parent.appendChild(data.el);
$(el).removeData('blockUI.history');
}
if (typeof opts.onUnblock == 'function')
opts.onUnblock(el,opts);
};
// bind/unbind the handler
function bind(b, el, opts) {
var full = el == window, $el = $(el);
// don't bother unbinding if there is nothing to unbind
if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
return;
if (!full)
$el.data('blockUI.isBlocked', b);
// don't bind events when overlay is not in use or if bindEvents is false
if (!opts.bindEvents || (b && !opts.showOverlay))
return;
// bind anchors and inputs for mouse and key events
var events = 'mousedown mouseup keydown keypress';
b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);
// former impl...
// var $e = $('a,:input');
// b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
};
// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
// allow tab navigation (conditionally)
if (e.keyCode && e.keyCode == 9) {
if (pageBlock && e.data.constrainTabKey) {
var els = pageBlockEls;
var fwd = !e.shiftKey && e.target == els[els.length-1];
var back = e.shiftKey && e.target == els[0];
if (fwd || back) {
setTimeout(function(){focus(back)},10);
return false;
}
}
}
// allow events within the message content
if ($(e.target).parents('div.blockMsg').length > 0)
return true;
// allow events for content that is not being blocked
return $(e.target).parents().children().filter('div.blockUI').length == 0;
};
function focus(back) {
if (!pageBlockEls)
return;
var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
if (e)
e.focus();
};
function center(el, x, y) {
var p = el.parentNode, s = el.style;
var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
if (x) s.left = l > 0 ? (l+'px') : '0';
if (y) s.top = t > 0 ? (t+'px') : '0';
};
function sz(el, p) {
return parseInt($.css(el,p))||0;
};
})(jQuery);

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,83 @@
function FreebaseLoadingDialog() {
this._createDialog();
}
FreebaseLoadingDialog.prototype._createDialog = function() {
var self = this;
var frame = DialogSystem.createDialog();
frame.width("900px");
var header = $('<div></div>').addClass("dialog-header").text('Load Data into Freebase').appendTo(frame);
var body = $('<div></div>').addClass("dialog-body").appendTo(frame);
var footer = $(
'<div class="dialog-footer">' +
'<table width="100%"><tr>' +
'<td class="left" style="text-align: left"></td>' +
'<td class="right" style="text-align: right"></td>' +
'</tr></table>' +
'</div>'
).appendTo(frame);
$.post(
"/command/export-rows?" + $.param({
project: theProject.id,
format : "tripleloader"
}),
{},
function(data) {
frame.find(".dialog-body").html('<div class="freebase-loading-tripleloader-data">' + data + '</pre>');
self._level = DialogSystem.showDialog(frame);
}
);
var left_footer = footer.find(".left");
$('<button></button>').text("Cancel").click(function() {
self._dismiss();
}).appendTo(left_footer);
var right_footer = footer.find(".right");
//$('<div class="freebase-loading-authorization signedin" style="display: none">Signed in as: <span class="user"></span></div>').appendTo(right_footer);
var selector = $('<span>').addClass("freebase-loading-graph-selector").html("Load into " +
'<input type="radio" bind="sandbox" id="freebase-loading-graph-selector-sandbox" name="graph-selector" checked="checked" value="sandbox"/><label class="sandbox" for="freebase-loading-graph-selector-sandbox" title="Load into the sandbox">sandbox</label>' +
'<input type="radio" bind="otg" id="freebase-loading-graph-selector-otg" name="graph-selector" value="otg"/><label class="otg" for="freebase-loading-graph-selector-otg" title="Load into Freebase">freebase</label>'
).buttonset().appendTo(right_footer);
$('<button></button>').text("Load").click(function() {
self._check_authorization(self._load);
}).appendTo(right_footer);
this._elmts = DOM.bind(frame);
this._elmts.otg.click(function() {
if (!confirm("are you sure?")) {
self._elmts.sandbox.attr("checked","checked");
self._elmts.otg.removeAttr("checked");
selector.find("input").button('refresh');
}
});
};
FreebaseLoadingDialog.prototype._check_authorization = function(cont) {
var freebase = this._elmts.otg.attr("checked");
var provider = (freebase) ? "freebase" : "sandbox";
$.get("/command/check-authorization",{ "provider" : provider }, function(data) {
if ("status" in data && data.status == "200 OK") {
if (typeof cont == "function") cont();
} else {
alert("Sorry, we're working very hard to make this happen.");
//Sign.signin(cont,provider);
}
},"json");
};
FreebaseLoadingDialog.prototype._load = function() {
// do the real loading here
}
FreebaseLoadingDialog.prototype._dismiss = function() {
DialogSystem.dismissUntil(this._level - 1);
};

View File

@ -59,7 +59,7 @@ MenuBar.prototype._initializeUI = function() {
{}, {},
{ {
label: "Load into Freebase ...", label: "Load into Freebase ...",
click: function() { alert("Not implemented yet."); } click: function() { self._doLoadIntoFreebase(); }
} }
]); ]);
@ -217,3 +217,7 @@ MenuBar.prototype._doAutoSchemaAlignment = function() {
MenuBar.prototype._doEditSchemaAlignment = function(reset) { MenuBar.prototype._doEditSchemaAlignment = function(reset) {
new SchemaAlignmentDialog(reset ? null : theProject.protograph, function(newProtograph) {}); new SchemaAlignmentDialog(reset ? null : theProject.protograph, function(newProtograph) {});
}; };
MenuBar.prototype._doLoadIntoFreebase = function() {
new FreebaseLoadingDialog();
};

View File

@ -0,0 +1,144 @@
if (typeof window.Sign == 'undefined') {
window.Sign = {
window_position: function() {
var position = {};
if (typeof(window.innerWidth) == 'number') {
// Non-IE
position['width'] = window.outerWidth;
position['height'] = window.outerHeight;
position['top'] = window.screenY;
position['left'] = window.screenX;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
// IE 6+ in 'standards compliant mode'
position['width'] = document.body.clientWidth;
position['height'] = document.body.clientHeight;
position['top'] = window.screenTop;
position['left'] = window.screenLeft;
}
return position;
},
popup : function(url, width, height, windowname) {
width = width || 700;
height = height || 500;
var pos = window.Sign.window_position();
var left = Math.floor((pos['width']-width)/2) + pos['left'];
var top = Math.floor((pos['height']-height)/2) + pos['top'];
// Chrome might fix this bug, but until then add some padding
// to the height of the popup for the urlbar
var is_chrome = /chrome/.test(navigator.userAgent.toLowerCase());
if (is_chrome) {
height += 50;
}
var params = {
width: width,
height: height,
top: top,
left: left,
directories: 'no',
location: 'no',
menubar: 'no',
resizable: 'no',
scrollbars: 'yes',
status: 'no',
toolbar: 'no'
};
var params_list = [];
for (var key in params) {
params_list.push(key + "=" + params[key]);
}
return window.open(url, windowname || "", params_list.join(","));
},
block : function() {
if ($.blockUI) {
$.blockUI({ css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
} });
}
},
unblock : function() {
if ($.unblockUI) {
$.unblockUI();
}
},
signintize : function(cont) {
$('.signedin').show();
$('.signedout').hide();
if (window.user) {
$('.user').html('<a href="http://freebase.com/view' + window.user.id + '">' + window.user.username + '</a>');
}
if (typeof cont == 'function') cont();
},
signin : function(success, provider, width, height) {
var newwin = window.Sign.popup("/command/authorize?" + $.param({ "provider" : provider}), width, height);
console.log(newwin);
newwin.opener = window;
window.onauthorization = function() {
window.Sign.block();
if (typeof success == 'undefined') {
window.location.reload();
} else {
$.ajax({
url: "/command/check-authorization",
dataType: "json",
success: function(data) {
window.user = data;
window.Sign.signintize(success);
window.Sign.unblock();
}
});
}
};
if (window.focus) {
newwin.focus();
console.log("focus");
}
return false;
},
signoutize : function(cont) {
$('.signedin').hide();
$('.signedout').show();
if (typeof cont == 'function') cont();
},
signout : function(success,provider) {
window.Sign.block();
$.ajax({
url: "/command/deauthorize",
data: { "provider" : provider },
success: function() {
if (typeof success == 'undefined') {
window.location.reload();
} else {
window.Sign.signoutize(success);
window.Sign.unblock();
}
}
});
}
};
}

View File

@ -0,0 +1,8 @@
.freebase-loading-tripleloader-data {
height: 500px;
overflow: auto;
border: 1px solid #aaa;
white-space: pre;
padding: 0.3em 0.5em 0.5em 0.5em;
font-family: monospace;
}

View File

@ -43,6 +43,8 @@ public class Gridworks {
static private final int MAX_UPLOAD_SIZE = 1024 * 1024 * 1024; static private final int MAX_UPLOAD_SIZE = 1024 * 1024 * 1024;
static private File tempDir; static private File tempDir;
static private int port;
static private String host;
private static Logger root = Logger.getRootLogger(); private static Logger root = Logger.getRootLogger();
private static Logger logger = Logger.getLogger("com.metaweb.gridworks"); private static Logger logger = Logger.getLogger("com.metaweb.gridworks");
@ -82,17 +84,24 @@ public class Gridworks {
public static int getMaxUploadSize() { public static int getMaxUploadSize() {
return Configurations.getInteger("gridworks.max_upload_size",MAX_UPLOAD_SIZE); return Configurations.getInteger("gridworks.max_upload_size",MAX_UPLOAD_SIZE);
} }
public static String getURL() {
return "http://" + Configurations.get("gridworks.host",DEFAULT_HOST) + ":" + Configurations.getInteger("gridworks.port",DEFAULT_PORT);
}
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
// tell jetty to use SLF4J for logging instead of its own stuff // tell jetty to use SLF4J for logging instead of its own stuff
System.setProperty("VERBOSE","false"); System.setProperty("VERBOSE","false");
System.setProperty("org.mortbay.log.class","org.mortbay.log.Slf4jLog"); System.setProperty("org.mortbay.log.class","org.mortbay.log.Slf4jLog");
// tell macosx to keep the menu associated with the screen // tell macosx to keep the menu associated with the screen
System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.eawt.CocoaComponent.CompatibilityMode", "false"); System.setProperty("com.apple.eawt.CocoaComponent.CompatibilityMode", "false");
// tell the signpost library to log
System.setProperty("debug","true");
// initialize the log4j system // initialize the log4j system
Appender console = new ConsoleAppender(new IndentingLayout()); Appender console = new ConsoleAppender(new IndentingLayout());
root.setLevel(Level.ALL); root.setLevel(Level.ALL);
@ -103,7 +112,10 @@ public class Gridworks {
tempDir = new File(Configurations.get("gridworks.temp","temp")); tempDir = new File(Configurations.get("gridworks.temp","temp"));
if (!tempDir.exists()) tempDir.mkdirs(); if (!tempDir.exists()) tempDir.mkdirs();
port = Configurations.getInteger("gridworks.port",DEFAULT_PORT);
host = Configurations.get("gridworks.host",DEFAULT_HOST);
Gridworks gridworks = new Gridworks(); Gridworks gridworks = new Gridworks();
gridworks.init(args); gridworks.init(args);
@ -111,9 +123,6 @@ public class Gridworks {
public void init(String[] args) throws Exception { public void init(String[] args) throws Exception {
int port = Configurations.getInteger("gridworks.port",DEFAULT_PORT);
String host = Configurations.get("gridworks.host",DEFAULT_HOST);
GridworksServer server = new GridworksServer(); GridworksServer server = new GridworksServer();
server.init(host,port); server.init(host,port);